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?

Wilfred Hughes
  • 6,890
  • 2
  • 29
  • 59

1 Answers1

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
YoungFrog
  • 3,496
  • 15
  • 27
Drew
  • 75,699
  • 9
  • 109
  • 225
  • 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