我该如何在vim中自动高亮一个单词?

10

我想突出显示某个单词,不考虑文件类型。在我的 .vimrc 文件中添加了以下内容:

highlight link notes todo
syntax match notes contained "TODO"
syntax match notes contained "NOTE"
syntax match notes contained "!!!"
syntax match notes contained "???"
注意:我也尝试过syntax match notes "TODO"(不包含引号)。
不幸的是,我无法使这些关键字得到任何突出显示。
编辑:
为了应用语法,我将代码移动到.vim/after/syntax/html.vim中。 它目前看起来像:
syntax match todo contained "\<\(TODO\|NOTE\|!!!\|???\)"
现在,当我键入 :syntax 时,我得到了 Todo xxx match /\<\(TODO\|NOTE\|!!!\|???\)/ contained
但是,当我尝试键入带有 TODO 的 HTML 注释(即<!-- TODO something -->)时,没有应用突出显示。
此外,我是否需要为每个文件类型创建一个.vim/after/syntax/file_type.vim,或者我可以以某种通用的方式应用它?
3个回答

4
一个可能的解决全局高亮的方法是将关键词附加到现有的语法组。在您的.vimrc文件中:
function! HighlightAnnotations()
  syn keyword vimTodo contained HACK OPTIMIZE REVIEW
  syn keyword rubyTodo contained HACK REVIEW
  syn keyword coffeeTodo contained HACK OPTIMIZE REVIEW
  syn keyword javaScriptCommentTodo contained HACK OPTIMIZE REVIEW
endfunction
autocmd Syntax * call HighlightAnnotations()

我正在为我常用的语言添加到现有的Todo类型中。我很懒,所以我将它添加到所有文件类型中,但如果您想要更具体的话,可以更有针对性一些。

要查找现有组,请打开带有您感兴趣的扩展名的文件,然后运行:syn list。Vim将提供当前加载的所有语法组的列表。

希望这能成为一个可行的解决方案,直到您能想出一种在所有文件类型上实现此操作的方法。


2
这个教程包含一个脚本以及执行你想要做的操作的说明。请查看此链接

2

I'm late to the table with this, but I got it to work by adding these three lines to my html.vim syntax file which I have in $HOME/vimfiles/after/syntax:

syntax keyword htmlTodo contained todo<br>
syntax match htmlComment /<!--.*/ contains=htmlTodo<br>
hi def link htmlTodo Todo

I'm only using "todo", but the list could be expanded by adding more keywords, i.e. syntax keyword htmlTodo contained todo hack test review...

An alternative:
Remove the syntax match ... line and add the following:

syntax clear htmlComment
syntax clear htmlCommentPart
syntax region htmlComment                start=+<!+      end=+>+  contains=htmlCommentPart,htmlCommentError,@Spell,htmlTodo 
syntax region htmlCommentPart  contained start=+--+      end=+--\s*+  contains=@htmlPreProc,@Spell,htmlTodo
syntax region htmlComment                  start=+<!DOCTYPE+ keepend end=+>+


我发现只有在"todo"和"<!-"在同一行时才有效,所以对于块状注释则无效。另一种解决方法是用以下代码替换语法匹配的行,这将清空并重建htmlComment和htmlCommentPart语法元素。我会将其作为另一个答案发布。 - Steve Doyle
1
":syntax clear" 就是我想要的。谢谢。 - CJBS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接