Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show trailing whitespace on emacs only on non-empty lines

Right now I'm using:

(setq show-trailing-whitespace t)

In my .emacs to show trailing whitespace for my CC mode. I can't seem to figure out how to have it not show the whitespace font for whitespace only lines.

Empty lines separating indenting code are sometimes indented at the code level and sometimes not indented at all, and I don't want to draw my attention to a line I don't care to change.

I'd like to stick to built-in emacs modules, but I'm willing to use whitespace.el but it's not clear how to configure it to do this.

like image 540
gabeiscoding Avatar asked Sep 11 '09 19:09

gabeiscoding


People also ask

How do I get rid of trailing whitespace in Emacs?

Type M-x delete-trailing-whitespace to delete all trailing whitespace. This command deletes all extra spaces at the end of each line in the buffer, and all empty lines at the end of the buffer; to ignore the latter, change the variable delete-trailing-lines to nil .

How do you fix a trailing whitespace error?

Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file. In emacs: C-M-% <space> + $ then press return twice.

How will you remove all leading and trailing whitespace in string?

We can eliminate the leading and trailing spaces of a string in Java with the help of trim(). trim() method is defined under the String class of java.


2 Answers

Since you want to use built-in modules, I'd advise using the whitespace.el link you specified - as it is shipped with Emacs 23. This answer works when using that whitespace.

As long as you have 'trailing in your 'whitespace-style variable (which it is by default), the following change to the regular expression for what indicates "trailing" whitespace should give you what you want:

(setq whitespace-trailing-regexp
  "\\b\\(\\(\t\\| \\|\xA0\\|\x8A0\\|\x920\\|\xE20\\|\xF20\\)+\\)$")

Note: It is just the default value, with the \b prepended, indicating that the whitespace should follow a word.

like image 92
Trey Jackson Avatar answered Nov 09 '22 22:11

Trey Jackson


With

"\\b.*\\(\\(\t\\| \\|\xA0\\|\x8A0\\|\x920\\|\xE20\\|\xF20\\)+\\)$"

the word does not need to be directly in front of the trailing whitespaces but there can be e.g. punctuation characters between them (i.e. this also highlights trailing whitespaces behind non-word characters).

Edit:
Using

"\\b.*?\\(\\(\t\\| \\|\xA0\\|\x8A0\\|\x920\\|\xE20\\|\xF20\\)+\\)$")

highlights all the trailing whitespaces and thus eliminates the drawback mentioned in comment #1.

like image 43
Marvin Avatar answered Nov 10 '22 00:11

Marvin