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.

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


ELisp Write Major Mode

Basics

Package Name/Load

Syntax Table