7

Is there a way to highlight (set the background color for example) the space before a line, when it's indentation isn't aligned to the current indentation-width?

4 spaces indentation for eg:

fn my_func() {
    if foo() {
        ##bar();
        blob();
    ###fez();
        baz();
    }
}

where the # characters represent the background showing a different color, back until the indentation is aligned to 4.

Of course this is only useful when code follows strict indentation conventions.


Note that I'm aware of emacs advanced auto-indentation features and indent-highlighting plugins, but would prefer something less intrusive that only shows up when there is an issue. A little like highlighting trailing spaces.

ideasman42
  • 8,375
  • 1
  • 28
  • 105
  • This doesn't answer your question, but functions like `c-indent-defun` will correct indentation for you, which might achieve the desired outcome. – Tyler Feb 14 '17 at 18:18
  • @Tyler, the issue is *you're* not always the only person writing the code. Checking out files written by others is quite a common use case - and you don't always want to re-indent their work either (bug-fixing or changes for code-review), so just seeing odd-indentation is useful. – ideasman42 Feb 14 '17 at 23:37
  • That makes sense. Just checking - sometimes people ask how to get half-way to something, not realizing that Emacs will take you all the way to the goal. But your use-case is reasonable. – Tyler Feb 14 '17 at 23:41

2 Answers2

3

Using font-lock...

(font-lock-add-keywords nil
  '(("^ \\{4\\}*\\( \\{1,3\\}\\)[^ ]" 1 'match)))
politza
  • 3,316
  • 14
  • 16
3

This can be done using font-lock-add-keywords.

The example below shows you can can selectively enable this feature in your configuration - for different formats.

  • Note the indentation is read from tab-width.
  • This example uses whitespace-trailing, you may want to use match or any other color.

eg:

;; highlight non-aligning indent offset
(defun highlight-indent-offset ()
 (font-lock-add-keywords
  nil
  `((,(lambda (limit)
        (re-search-forward
         (format "^ \\{%d\\}*\\( \\{1,%d\\}\\)[^ ]" tab-width (- tab-width 1))
         limit t))
     1 'whitespace-trailing))))

Then this function can be called for spesific modes: eg,

(add-hook
 'rust-mode-hook
 (lambda ()
   (setq tab-width 4)
   (highlight-indent-offset)
   (setq indent-tabs-mode nil)))

This is a minor changes to @politza's answer.

politza
  • 3,316
  • 14
  • 16
ideasman42
  • 8,375
  • 1
  • 28
  • 105