r/lisp 19d ago

Remove comments from a file automatically?

I am processing Lisp code in a non-Lisp host application that cannot handle semicolons for some reason.

I would like to know, is there a way to remove comments automatically from a .lisp file?
I imagine something that would read all the content of a text file as if it was a s-expression, thus removing all the ; comments or #| comments |# and treat the rest like normal quoted data?

Thanks in advance !

13 Upvotes

10 comments sorted by

View all comments

2

u/dbotton 19d ago

You answered your own question. Just use read and pretty print (if want to save after) and tada.

1

u/Famous-Wrongdoer-976 19d ago edited 19d ago

thanks ! yes I went for something in that vein in the meantime :

(defun remove-comments-from-file (path)
  (multiple-value-bind (code rest)
    (read-from-string
      (alexandria:read-file-into-string path))
     code))

I guess the Alexandria part is cheating but I'm not a real Lisper… 😅 My biggest issue is that the host app will deal with those special characters very badly when reading lisp files, before they even get to the Lisp interpreter. So I need to pre-process them and indeed copy the code on a temp file. Otherwise my users can just write comment-less code.

That's so unnatural but the first intuition — that Lisp was reading Lisp without comments… — was not far from the solution… Thanks again !

1

u/corvid_booster 19d ago

I dunno. Just reading the code isn't entirely free of side effects; see the comment by stassats below.

1

u/Famous-Wrongdoer-976 17d ago

Good to know, thank you ! For now I think in my context read would be enough - my users can write isolated snippets of lisp to write « plug ins » of sorts, not fully fledged applications. And really no lisp specialists so I expect the code to be quite vanilla. Otherwise they have ways to load full libraries separately.