Search code examples
emacselispwhitespacefont-lock

How to highlight tab characters for files from specific project in Emacs


I have this code to highlight tab characters and want to disable them using project-specifics macro:

(require 'highlight-chars)
(make-variable-buffer-local 'prevent-highlight-tabs)
(setq highlight-chars-disable '(term-mode erc-mode fundamental-mode))
(setq-default prevent-highlight-tabs nil)
(add-hook 'font-lock-mode-hook
          (lambda()
            (message "lock")
            (when (and (null (memql major-mode highlight-chars-disable))
                       (not prevent-highlight-tabs))
              (message "%s" prevent-highlight-tabs)
              (hc-highlight-tabs))))
(custom-set-faces '(hc-tab ((t (:background "red")))))

and project-specifics is a macro that define add find-file-hook and dired-after-readin-hook from this question

(project-specifics "projects/test"
  (message "specific")
  (setq prevent-highlight-tabs t)
  (setq indent-tabs-mode t))

What I wanted to do is disable red tabs (I want them because in most projects I want only spaces, and want to see tabs) for files in project/test, but I have a problem because the code from font-lock-mode-hook is executing before project-specifics (find-file-hook), and prevent-highlight-tabs is always nil in font-lock-mode-hook. Why is that, and how to fix it?


Solution

  • What you are doing seems convoluted.

    And it is partly undefined (here) - e.g., what is the major mode highlight-chars-disable? That is not defined in library highlight-chars.el, and it doesn't sound like something that would be a good candidate for a major mode.

    See the Commentary of library highlight-chars.el for suggestions.

    Something like this, perhaps (and you would put property prevent-highlight-tabs on any major-mode symbols you like:

    (add-hook 'font-lock-mode-hook
              (lambda () (unless (get major-mode 'prevent-highlight-tabs)
                           (hc-highlight-tabs))))
    

    Or something like this (from the Commentary):

    (add-hook 'change-major-mode-hook
              (lambda ()
                (add-hook 'font-lock-mode-hook 'hc-highlight-tabs)))
    
    (add-hook 'after-change-major-mode-hook
              (lambda ()
                (when (eq major-mode 'THE-MODE)
                  (remove-hook 'font-lock-mode-hook 'hc-highlight-tabs)
                  (hc-dont-highlight-tabs)))
              'APPEND)