Search code examples
emacsremoving-whitespaceblank-line

Emacs: highlight 2 or more empty lines


I have entered the following code in my .emacs file to highlight unwanted white spaces.

(require 'whitespace)
(setq whitespace-style '(face empty tabs lines-tail trailing))
(global-whitespace-mode t)

This shows (1) empty lines at the beginning & end of buffer (2) tabs (3) lines which go over the 80 character limit (4) trailing white spaces

I would like emacs to automatically highlight '2 or more empty lines'. Any ideas on how to implement this? I did find a blog post explaining a way to do this with the help of regexp, but I am not sure how to implement this in .emacs file.

Edit 1: Found a way to delete extra blank lines but this still doesn't help me with highlighting multiple blank lines automatically. delete extra blank lines in emacs

Edit 2: Adding the following to .emacs seems to work, but only after I save and reopen file in a buffer.

(add-hook 'change-major-mode-hook '(lambda () (highlight-regexp "\\(^\\s-*$\\)\n" 'hi-yellow)))

Edit 3: After adding (global-hi-lock-mode 1) to .emacs file just before the line in Edit 2, it seems to highlight 1 or more empty lines within the buffer. I am not sure how to modify the regexp so that it will only accept 2 or more empty lines.


Solution

  • Just use library Highlight (highlight.el). That's what it's for.

    Use command hlt-highlight-regexp-region (C-x X h x) or hlt-highlight-regexp-to-end (C-x X h e). (To unhighlight a regexp, use C-x X u x or C-x X u e.)

    Interactively, you input the regexp to use as usual in Emacs (with C-q C-j to match a newline character, and no need for double backslashes), so you type \(^\s-*$\) C-q C-j.