Elisp: Determine Cursor is Inside String/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 on 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 [https://plus.google.com/+EliasMartenson/posts] for feedback.

Elisp Syntax Table

  1. Character Type
  2. Syntax Table Tutorial
  3. Find Syntax of a Character
  4. Modify Syntax Table Temporarily
  5. is Cursor Inside String/Comment
  6. Regex Patterns and Syntax Table
  7. Find Matching Bracket Char

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs

Emacs

Emacs Lisp

Misc