5

I have some lisp code that contains a comment:

(while list
  ;; take the head of LIST
  (setq len 1))

I want to extract the positions of the sexps. I'm using scan-sexps. If I call M-: (scan-sexps 12 1) with the above code in a buffer, it returns 54, as expected.

However, if I try to do this programmatically:

(setq src "(while list
  ;; take the head of LIST
  (setq len 1))")

(with-temp-buffer
  (insert src)
  (scan-sexps 12 1))

I get 22! This seems to be parsing the words in my comment. Why don't I get 54, and how do I fix this?

Reading the docstring for scan-sexps, it mentions parse-sexp-ignore-comments. However, this doesn't seem to affect the outcome:

(with-temp-buffer
  (insert src)
  (setq parse-sexp-ignore-comments t)
  (scan-sexps 12 1)) ; still 22

How can I make scan-sexps return the end position of the next sexp, ignoring comments?

5

The problem is that with-temp-buffer puts the buffer in a fundamental mode, and you are counting on it being in a Lisp mode, such as emacs-lisp-mode. So comments and sexps are not what you are expecting.

(with-temp-buffer
  (emacs-lisp-mode)
  (insert src)
  (scan-sexps 12 1))

;; => 54
| improve this answer | |
  • 1
    Aha, makes sense! Digging into this some more, it's the syntax-table (rather than e.g. block-comment-start) that scan-sexps needs. – Wilfred Hughes Sep 12 '16 at 23:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.