6

When, while executing an emacs-lisp function, point is at the beginning of a line, how can I check whether that line is part of a block comment, inside it, or starting it?

The stupid approach, that I am doing now, is to go to the first non-whitespace character and see if its face is font-lock-comment-face or some such:

(save-excursion
  (skip-syntax-forward "\\s-")
  (let ((face (get-char-property (point) 'face)))
    (or (eq face 'font-lock-comment-face)
        (eq face 'font-lock-comment-delimiter-face)
        (eq face 'font-lock-doc-face))))

But this fails sometimes, because the function that invokes this might be run before fontification is performed.

Is there some standard way of doing this? (Please include, if you can, a link to the emacs lisp manual section that I've missed.)

Kirill
  • 1,019
  • 7
  • 19
  • The first half of this question is the same as http://stackoverflow.com/questions/12815781/emacs-lisp-and-c-mode-when-am-i-in-a-comment-region/12820339#12820339. – Stefan Dec 10 '14 at 15:24

1 Answers1

8

As far as I know the standard way of checking if a point is within a comment is by calling syntax-ppss. See Parser state for the meaning of its return value.

In particular,

(nth 4 (syntax-ppss))

is not nil when the point is in a comment.

To determine if this is a block comment, try checking if the text at the beginning of the comment (position (nth 8 (syntax-ppss))) matches a regular expression (for example by using looking-at).

Constantine
  • 9,072
  • 1
  • 34
  • 49
  • 1
    Actually, `(nth 4 (syntax-ppss))` can evaluate to other values than `t` when inside a comment (e.g. an integer). But it will always be a non-nil value. – Stefan Dec 10 '14 at 13:57
  • Thanks for the correction, @Stefan! I updated the answer. – Constantine Dec 10 '14 at 15:26
  • Awesome! This inspired to fix a function I use to pull up the next line to the current line: http://emacs.stackexchange.com/q/7519/115 – Kaushal Modi Jan 18 '15 at 18:59