Emacs Lisp: How to Determine If Cursor is Inside String or Comment

Master emacs+lisp, benefit for life. Testimonials. Thank you for support.
, , …,

Emacs has basic functions to parse syntax. It can determine whether cursor is inside string or comment.

(nth 3 (syntax-ppss)) returns true if cursor is inside a string.

(defun inside-string? ()
  "Returns non-nil if inside string, else nil.
This depends on major mode having setup syntax table properly."
  (interactive)
  (let ((result (nth 3 (syntax-ppss))))
    (message "%s" result)
    result))

Evaluate the above, and move cursor about and try it.

(nth 4 (syntax-ppss)) returns true if cursor is inside a comment.

(defun inside-comment? ()
  "Returns non-nil if inside comment, else nil.
This depends on major mode having setup syntax table properly."
  (interactive)
  (let ((result (nth 4 (syntax-ppss))))
    (message "%s" result)
    result))

thanks to Elias Martenson for feedback.

Like what you read?
Buy Xah Emacs Tutorial
or share some
blog comments powered by Disqus