4

With reference to the link, In C/C++ mode in Emacs, change face of code in #if 0...#endif block to comment face.

I tried the code but it doesnot seem to be working. My emacs version is GNU Emacs 21.3.1 on Linux.

Please can you let me know where I am going wrong.

TIA

imz -- Ivan Zakharyaschev
  • 4,921
  • 6
  • 53
  • 104
asd
  • 41
  • 2

1 Answers1

3

cpp-highlight-mode can be made to work without user interaction. This is how I have mine set up:

(defun cpp-highlight-if-0/1 ()
  "Modify the face of text in between #if 0 ... #endif."
  (interactive)
  (setq cpp-known-face '(background-color . "dim gray"))
  (setq cpp-unknown-face 'default)
  (setq cpp-face-type 'dark)
  (setq cpp-known-writable 't)
  (setq cpp-unknown-writable 't)
  (setq cpp-edit-list
        '((#("1" 0 1
             (fontified nil))
           nil
           (background-color . "dim gray")
           both nil)
          (#("0" 0 1
             (fontified nil))
           (background-color . "dim gray")
           nil
           both nil)))
  (cpp-highlight-buffer t))

(defun jpk/c-mode-hook ()
  (cpp-highlight-if-0/1)
  (add-hook 'after-save-hook 'cpp-highlight-if-0/1 'append 'local)
  )

(add-hook 'c-mode-common-hook 'jpk/c-mode-hook)

The key is figuring out that cpp-highlight-mode looks at cpp-edit-list. I set things up the way I wanted the interactive way and then looked at the cpp-edit-list that resulted with C-h v.

cnd
  • 32,616
  • 62
  • 183
  • 313
jpkotta
  • 9,237
  • 3
  • 29
  • 34
  • Nice! What is the first element in each sublist of `cpp-edit-list` for? The doc only describes that as a string, but you seem to use it for more (e.g., `#("1" 0 1 (fontified nil))`). – Michaël Jan 13 '21 at 03:54
  • I think what I have in the answer is copy-pasta. And I don't have that function in my init.el anymore for some reason. But the doc says it's a 4 element list: https://github.com/emacs-mirror/emacs/blob/master/lisp/progmodes/cpp.el#L92 – jpkotta Jan 14 '21 at 16:57
  • Thanks! Yes, it's a four element list, but the first element should just be a string, not `#("1" 0 1 (fontified nil))`. Now granted, it does work, but I'm perplexed by this! – Michaël Jan 14 '21 at 18:54
  • 1
    That first element might be a fancy fontified string. Which apparently can be used as a regular string in this context. E.g. try using `buffer-substring` on a buffer with colored text. Like I said, this was copy pasta, it might be better if it was just a plain string. – jpkotta Jan 15 '21 at 17:40