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

thanks to Elias Martenson for feedback.

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs