正则表达式 – 在Emacs的C/C++模式下,将#if 0 …#endif块中的代
发布时间:2020-12-14 06:27:50 所属栏目:百科 来源:网络整理
导读:我正在尝试将其他代码编辑器中的功能添加到我的Emacs配置中,由此#if 0 …#endif块中的C/C++代码自动设置为注释面/字体.根据我的测试,cpp-highlight-mode做的是像我想要的,但需要用户操作.看起来像绑定字体锁功能是使自动执行行为的正确选项. 我已经成功地在G
我正在尝试将其他代码编辑器中的功能添加到我的Emacs配置中,由此#if 0 …#endif块中的C/C++代码自动设置为注释面/字体.根据我的测试,cpp-highlight-mode做的是像我想要的,但需要用户操作.看起来像绑定字体锁功能是使自动执行行为的正确选项.
我已经成功地在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作为多行正则表达式遇到问题.我在这篇文章(How to compose region like “”)中发现了一些有用的信息,这表明Emacs必须被告知具体允许多行匹配.但这段代码: (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)))))) 仍然不适合我也许我的正则表达式是错误的(虽然它似乎使用M-x重建器),我搞砸了我的语法,或者我完全遵循错误的方法.我在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) 编辑: 编辑#2:Niftier代码来处理if / else / endif的任意嵌套 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |