6

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?

nispio
  • 8,225
  • 2
  • 36
  • 74

1 Answers1

5

Works for me:

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

Edit

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)))
)
Adobe
  • 1,869
  • 14
  • 27