How to detect if the point is within a comment area?
Check the fourth* value in the list returned by
(nth 4 (syntax-ppss))
nil if point is outside any comment,
t if inside a non-nestable comment, or an integer (the nesting depth) if inside a nestable comment. See the docstring for
parse-partial-sexp for more details.
Note that this doesn't work with Org-mode, you should use this:
(defun in-comment-p () "Testy if cursor/point in a commented line?" (save-excursion (if (derived-mode-p 'org-mode) (save-match-data (beginning-of-line) (looking-at "^[ \t]*#")) (nth 4 (syntax-ppss)))))
use the font-face, this is the trick I learned from flyspell.
syntax-ppss two years ago, it does not work for two reason:
not work on edge of comment (comment limit), for example, for comment like
// this is commentin c++-mode, if you place the cursor over the
/character, the result of
(nth 4 (syntax-ppss))is nil.
not work at all in major-mode like web-mode
Here is code I copied from flyspell:
(defun evilnc--in-comment-p (&optional pos) "Test if character at POS is comment. If POS is nil, character at `(point)' is tested" (interactive) (unless pos (setq pos (point))) (let* ((fontfaces (get-text-property pos 'face))) (when (not (listp fontfaces)) (setf fontfaces (list fontfaces))) (delq nil (mapcar #'(lambda (f) ;; learn this trick from flyspell (or (eq f 'font-lock-comment-face) (eq f 'font-lock-comment-delimiter-face))) fontfaces))))
Please note the code could be extended to support new major modes by fuzz matching font face.
I've used this trick for about three years without failure. Besides, considering flyspell is widely used for so long, I could claim this method is reliable.
See Which keyboard shortcut to use for navigating out of a string for similar question.