6

As an example, if I start a one line comment:

;; Comment⏎

Emacs will fontify the the whole line, from the beginning of line, occupying the entire width of the window, as comment. This can be made easily visible by setting a background color for the comments.

Is there a way to make emacs only fontify the part of the line that's not empty?

Edit: This is the default behavior of emacs, and not a problem with the init file. You can see this by starting emacs with emacs -Q, open a lisp file, and then (set-face-background 'font-lock-comment-face "yellow")

(Thanks @lawlist)

  • I don't have an answer to your question, but recently ran into issues relating to the C function extend_face_to_end_of_line when working on my own feature requests. If fiddling around with Lisp is insufficient to meet your needs and if you are so inclined, you may be interested in playing with the aforementioned internal function – lawlist Dec 29 '18 at 7:29
  • 2
    @Drew -- Start with Emacs -Q. Type M-x find-library RET simple RET. Evaluate (set-face-background 'font-lock-comment-face "yellow"). The yellow background face extends to the end of the line for all comments. – lawlist Dec 29 '18 at 18:14
  • @lawlist Does that mean there is no way to change this behavior without modifying emacs' C source code? – nialv7 Dec 29 '18 at 20:24
  • 1
    Comments are highlighted in the first of two phases, the syntactic phase. You can fix this by overriding the function that does this, which unfortunately is quite tricky. Another approach is to add a font-lock keyword that match newlines and removes the comment face. (Normally, font-lock keywords can only add faces. However, you can add code that removes keywords as a side effect of either MATCHER or FACENAME.) – Lindydancer Dec 29 '18 at 20:25
  • 2
    @nialv7 -- Background: If the newline character has a face property, Emacs use it for the entire line. So you can get the desired behavior, without changing the C source, by stripping away the comment face from the newline character. – Lindydancer Dec 29 '18 at 20:29
3

(Thanks to @Lindydance)

Here is what I am currently doing to get the effect I want:

(define-minor-mode fontify-line-limit-mode
  "Make sure the highlighting doesn't extend beyond the end of line."
  :lighter ""
  :init-value nil
  ;; Too lazy to define a face for this
  (font-lock-add-keywords nil '(("\n" . (0 font-lock-function-name-face t))) t))

(define-globalized-minor-mode global-fontify-line-limit-mode
  fontify-line-limit-mode (lambda () (fontify-line-limit-mode t)))

(global-fontify-line-limit-mode 1)

I would consider this a hack, and wish there is a better solution to this...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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