6

I've tried whitespace-mode, but I can't configure it the way I want. There are others, but some of them are obsolete and I don't want to try them all.

I always indent via tabs and can't stand trailing whitespace. I never combine tabs and spaces (which means that with tabwidth=4 I can indent only multiples of 4, that's fine). I don't want non-indenting spaces to be highlighted as it's highly disturbing. I don't want any non-indenting tabs as there are always an error.

The following pattern express it maybe more clearly

  • ^\t* + - indenting space
  • [ \t]+$ - trailing space or tab
  • [^\t\n]+\t - non-indenting tab

It should work for all buffers and ideally use some nasty color.

I'm looking for either a package allowing exactly this or a hint what could I modify to get it in the easiest way. I used to hack emacs a lot some 15 years ago, but that's too long ago.


  • @Drew My regex was "^\t* " without the quotes, but the trailing space was invisible despite using backtics. I've just fixed it by adding + (your regex would be even better, but I wanted to keep it simple). My third regex was wrong as well (I meant a tab after anything but tab or newline). – maaartinus Aug 20 '16 at 18:03
5

This should do what you want. Define regexps that match what you want, and faces.

Then match the subgroups in the function you add to font-lock-keywords. The subgroups are used to say that you want only the spaces after indenting tabs, and only non-indenting tabs.

(defface my-tab '((t (:background "LemonChiffon"))) "..." :group 'faces)

(defface my-space '((t (:background "HotPink"))) "..." :group 'faces)

(defface my-trailing-whitespace '((t (:background "Gold"))) "..." :group 'faces)

(defvar indenting-space-re "^[\t]*\\([ ]+\\)"
   "Regexp to match space chars after tab chars, at the start of a line.")

(defvar trailing-white-re "[\u00a0\040\t]+$"
   "Regexp to match trailing whitespace")

(defvar non-indenting-tabs-re "[^\n\t]+\\(\t+\\)"
   "Regexp to match bol, non-newline, non-tab chars, then tab chars.")

(defun foo ()
  "..."
  (font-lock-add-keywords
   nil
   `((,indenting-space-re (1 'my-space t))               ; indenting spaces
     (,non-indenting-tabs-re (1 'my-tab t))              ; non-indenting tabs
     (,trailing-white-re (0 'my-trailing-whitespace t))) ; trailing whitespace
   'APPEND))

(add-hook 'font-lock-mode-hook 'foo)
  • Perfect. I thought that it was harder, but it's very simple and clear, once you've showed me what to use (your example works as is, but I may add more stuff someday). – maaartinus Aug 20 '16 at 20:12

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.