From time to time I open a script or config file for which there is no major mode defined. When I invoke comment-region within that buffer, Emacs will prompt me for the comment syntax, and save it as the buffer-local variable comment-start.

Can I enable syntax highlighting of comment lines in that buffer?

Once the variable comment-start has been set, what other steps do I need to take in order for font-lock-mode to start highlighting my comment lines?

1 Answer 1


Works for me:

(setq comment-start "#")
(font-lock-add-keywords nil '(("#.+" . font-lock-comment-face)))


Here's a more general solution:

(defun set-comment-char (char)
  "Sets comment char for current buffer."
  (interactive "sComment char: ")
  (setq comment-start char)
  (font-lock-add-keywords nil `((,(concat comment-start ".+") . font-lock-comment-face)))

Edit 2:

Here's a more general solution:

(define-derived-mode text-mode-with-hash-comments text-mode
  "text-mode with # comments"

  (setq comment-start "#")
  (font-lock-add-keywords nil '(("#.+" . font-lock-comment-face)))
  • I agree that it works, but it is also not very generalized.
    – nispio
    Commented Sep 24, 2015 at 22:16

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.