In C/C++ mode in Emacs, change face of code in #if 0…#endif block to comment face

前端 未结 1 1259
北恋
北恋 2020-12-17 17:00

I\'m trying to add functionality found in some other code editors to my Emacs configuration, whereby C/C++ code within #if 0...#endif blocks is automatically set to the comm

相关标签:
1条回答
  • 2020-12-17 17:43

    Even if you got the multiline regexp to work, you'd still have problems with nested #ifdef/#endif's since it would stop font-locking at the first #endif. This code works, although I'm not sure if there will be a noticeable slow down for large files:

    (defun my-c-mode-font-lock-if0 (limit)
      (save-restriction
        (widen)
        (save-excursion
          (goto-char (point-min))
          (let ((depth 0) str start start-depth)
            (while (re-search-forward "^\\s-*#\\s-*\\(if\\|else\\|endif\\)" limit 'move)
              (setq str (match-string 1))
              (if (string= str "if")
                  (progn
                    (setq depth (1+ depth))
                    (when (and (null start) (looking-at "\\s-+0"))
                      (setq start (match-end 0)
                            start-depth depth)))
                (when (and start (= depth start-depth))
                  (c-put-font-lock-face start (match-beginning 0) 'font-lock-comment-face)
                  (setq start nil))
                (when (string= str "endif")
                  (setq depth (1- depth)))))
            (when (and start (> depth 0))
              (c-put-font-lock-face start (point) 'font-lock-comment-face)))))
      nil)
    
    (defun my-c-mode-common-hook ()
      (font-lock-add-keywords
       nil
       '((my-c-mode-font-lock-if0 (0 font-lock-comment-face prepend))) 'add-to-end))
    
    (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
    

    EDIT: Take into account #else

    EDIT #2: Niftier code to handle arbitrary nesting of if/else/endif's

    0 讨论(0)
提交回复
热议问题