Given that the point is right in front of a comment, how do I move it to the end of the comment, but before the comment end markers?

For example:

  • for a C++ // xxx comment, I would like to move the point to the end of the line
  • for C-style /* xxx */ comments I would like to move the point to right before the second *.

To complicate matters, I would like this to be mode independent. Also, I would like the solution to be based on the syntax table, as there are major modes that don't set up the comment-related regex variables properly.

Starting points:

  • The function forward-comment can move the point the after the comment end marker, but I want it to stop before the comment end marker
  • The syntax table can define three kinds of comments at the same time (where the b and c flags indicate that character is part of alternative comment kinds). When the point is inside a comment, the function syntax-ppss can tell which kind of comment it is.

1 Answer 1


This can be done, although Emacs doesn't seem to provide useful info about multi-line comment ends, so it needs a hard coded check for */.

(defun my-end-of-comment ()
  (let ((state (syntax-ppss))
        (point-init (point)))

    ;; We may be at the comment start, which isn't considered a comment.
    (unless (nth 4 state)
        (skip-syntax-forward "^-")
        (let ((state-test (syntax-ppss)))
          (when (and (nth 4 state-test) (<= point-init (nth 8 state-test)))
            (setq state state-test)))))

    (when (nth 4 state)
      (let ((start (nth 8 state)))
        (goto-char start)
        (forward-comment 1)
        (skip-syntax-backward ">")
        ;; Hard code '*/' for C.
        (when (looking-back "\\*\\/")
          (forward-char -2))))))
  • Close, but I would like to avoid hard-code things for a specific language. It fails for // foo */. This is a C++-style comment, but it place the point before */. It also fails for /*foobar*/ since the (skip-syntax-forward "^-") pass the entire comment. (The (forward-char -3) should be (forward-char -2), since we can't assume that the */ sequence is preceded by a space, right?) Commented Jun 20, 2020 at 19:51
  • I don't think you can get this info - from the syntax tree at least. I thought the comment-end or block-comment-end variables might be of use, but it seems neither are used by default.
    – ideasman42
    Commented Jun 21, 2020 at 0:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.