How can I highlight 80 columns when a line has a single % at the very start? What I am looking for is that lines with a single % stand out by a colored rectangle 1 character high and 80 columns wide.
1 Answer
If the major mode works with font-lock-mode
you can add a font-lock keyword in the major mode hook.
If you include newlines in the match the line is highlighted over the full width of the window (if that is what you actually want).
The following example does that for lines only consisting of a single percent character in LaTeX-mode
buffers:
(defcustom my-empty-comment-face 'hi-yellow
"Face for highlighting empty comment lines."
:type 'facep
:group 'LaTeX)
(defun my-font-lock-empty-comments ()
"Highlight empty comments in `LaTeX-mode'."
(message "Adding my-empty-comment-face")
(font-lock-add-keywords
nil
'((
"^%\n" ;; matcher
. ;; match-highlight:
(0 ;; subexp
`(face ,my-empty-comment-face) ;;< facename (evaluates to (face FACE PROP1 VAL1 ...)
t ;;< override comment face
))))))
(add-hook 'LaTeX-mode-hook #'my-font-lock-empty-comments)
Even if the text above is what you actually want I will also answer your question more directly.
Instead of highlighting the whole line you asked for highlighting 80 characters of it:
How to highlight 80 columns when it contains a single % at the start
From those 80 characters 79 characters — the space characters behind the percent sign — do not even exist.
Therefore we put a display
property with the highlighted string of the right length on the existing percent sign.
There follows the modified code:
(defcustom my-empty-comment-face 'hi-yellow
"Face for highlighting empty comment lines."
:type 'facep
:group 'LaTeX)
(defun my-font-lock-empty-comments ()
"Highlight empty comments in `LaTeX-mode'."
(message "Adding my-empty-comment-face")
(font-lock-add-keywords
nil
'((
"^%\n" ;; matcher
. ;; match-highlight:
(0 ;; subexp
`(face default display ,(propertize (concat "%" (make-string 79 ?\s)) 'face my-empty-comment-face)) ;;< facename (evaluates to (face FACE PROP1 VAL1 ...)
t ;;< override comment face
))))))
(add-hook 'LaTeX-mode-hook #'my-font-lock-empty-comments)
M-x highlight-regexp
^%
<Ctrl-J>
<RET>
and choose your favorite face.<Ctrl-J>
in my former comment stands for the key combination: pressing J while holding the Control key down. This key combination inserts a newline when you input regexps. If you include that newline into your regexp the whole line is highlighted as you wish.