在vim中为链接自定义语法高亮显示

时间:2009-08-26 08:07:02

标签: vim graph syntax-highlighting vim-syntax-highlighting

我有一个图表的自定义文件格式,如下所示:

node1.link1 : node2
node1.attribute1 : an_attribute_for_node1
node2.my_attribute1 : an_attribute_for_node2

(属性名称没有什么特别之处,如果可以在点的左边找到它的值,则属性是链接。所以node2是一个链接,因为文件中的某处有一行以node2.<something>)开头。

我想突出显示属性值,如果它们是链接(所以我想突出显示node2,但不是attribute_for_node1)。

显然,这种语法高亮不能仅基于行宽regexp,因为需要读取整个文件才能进行正确的高亮显示。

我已经为这种文件提供了一个python解析器(它给出了dict string -> (string -> string)的dict),但我不知道python是否可以与vim 7中的语法高亮相互作用。

修改 作为澄清,为此示例生成的字典是:

d = {
  'node1': {'link1' : 'node2', 'attribute1' : 'an_attribute_for_node1'},
  'node2': {'attribute2': 'an_attribute_for_node2'}
}

根据定义,l是节点n的链接,当且仅当:

d[n][l] in d

名称没有意义,格式仅取决于结构,并且没有语言关键字。 我想在第一行中突出显示node2,因为它是节点的名称。

我希望现在更清楚了。

有人有想法吗?

1 个答案:

答案 0 :(得分:2)

这应该是非常简单的,但是确切地解决你的dict看起来有点困难(什么是'字符串'?node1?attribute1?还有什么?)。我有一个我写的插件叫做ctags highlighter,它做了一个非常类似的事情:它使用ctags生成一个关键字列表,然后使用python将其变成一个简单的vim脚本,可以恰当地突出显示这些关键字。

基本上,您需要做的是使您的解析器(或使用您的解析器的另一个python模块)生成关键字列表(node1,node2等)并以此形式输出它们(使用与您一样多的行)喜欢,但不要使行<:>>

syn keyword GraphNode node1 node2
syn keyword GraphNode node3

将其写入文件并创建一个类似于:

的自动命令
autocmd BufRead,BufNewFile *.myextension if filereadable('nodelist.vim') | source nodelist.vim | endif

然后做:

hi GraphNode guifg=blue

或其他什么。如果您需要更多详细信息,请发布有关解析器的更多信息,或查看my plugin中的代码。

有关详细信息,请参阅

:help :autocmd
:help syn-keyword
:help BufEnter
:help BufNewFile
:help filereadable()
:help :source
:help :highlight

修改

我仍然不完全确定我知道你想要什么,但如果我理解正确,这样的事情应该有效:

假设您的python解析器名为mypyparser.py,它接受​​一个参数(当前文件名),它创建的字典称为MyPyDict。您显然必须修改脚本以匹配解析器的实际使用。在运行时路径中的某处添加此脚本(例如,在.vimrc或〜/ .vim / ftplugin / myfiletype.vim中),然后打开文件并键入:HighlightNodes

" Create a command for ease of use
command! HighlightNodes call HighlightNodes()
function! HighlightNodes()
    " Run the parser to create MyPyDict
    exe 'pyfile mypyparser.py ' . expand('%:p')
    " Next block is python code (indent gone to keep python happy)
    py <<EOF
# Import the Vim interface
import vim
# Iterate through the keys in the dictionary and highlight them in Vim
for key in MyPyDict.keys():
    vim.command('syn keyword GraphNode ' + key)
endfor
EOF
    " Make sure that the GraphNode is highlighted in some colour or other
    hi link GraphNode Keyword
endfunction