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

By Xah Lee. Date: . Last updated: .

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-q ()
  "Returns non-nil if inside string, else nil.
Result depends syntax table's string quote character."
  (let ((result (nth 3 (syntax-ppss))))
    (message "%s" 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-q ()
  "Returns non-nil if inside comment, else nil.
Result depends on syntax table's comment character."
  (let ((result (nth 4 (syntax-ppss))))
    (message "%s" result)

thanks to Elias Martenson for feedback.

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from my keyboard store.