在emacs中的C/C ++模式中,更改#if 0…#Endif Block中的代码的面孔要注释脸
-
13-10-2019 - |
题
我正在尝试将其他一些代码编辑器中的功能添加到我的EMACS配置中,在#if 0 ...#Endif Blocks中的C/C ++代码将自动设置为注释面/字体。根据我的测试 CPP-Highlight模式 做类似我想要的事情,但需要用户操作。似乎与字体锁功能联系在一起是使行为自动的正确选择。
我已经成功地遵循了GNU文档中的示例,以改变单线正则表达式的面孔。例如:
(add-hook 'c-mode-common-hook
(lambda ()
(font-lock-add-keywords nil
'(("\\<\\(FIXME\\|TODO\\|HACK\\|fixme\\|todo\\|hack\\)" 1
font-lock-warning-face t)))))
可以很好地突出显示文件中任何地方的调试相关关键字。但是,我在匹配#if 0 ...#Endif作为多行正则表达式上遇到问题。我在这篇文章中找到了一些有用的信息(如何组合区域u003C?php foo; bar; ?>“),这表明必须专门告知EMAC,以允许多行比赛。但是此代码:
(add-hook 'c-mode-common-hook
(lambda ()
'(progn
(setq font-lock-multiline t)
(font-lock-add-keywords nil
'(("#if 0\\(.\\|\n\\)*?#endif" 1
font-lock-comment-face t))))))
仍然对我不起作用。也许我的正则表达式是错误的(尽管它似乎使用 MX重建器),我弄乱了我的语法,或者我完全遵循错误的方法。我正在使用OS X 10.6.5上的Aquamacs 2.1(基于GNU Emacs 23.2.50.1),如果有所不同。
任何援助将不胜感激!
解决方案
即使您让多行式正直工作起作用,您仍然会遇到嵌套的问题 #ifdef/#endif
因为它会停止锁定字体锁定 #endif
. 。该代码有效,尽管我不确定大型文件是否会引起明显的速度:
(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)
编辑:考虑到 #else
编辑#2:niftier代码处理if/else/endif的任意嵌套的代码
不隶属于 StackOverflow