0

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

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

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

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

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

我已经有一个用于此类文件的 python 解析器(它给出 dict 的 dict string -> (string -> string)),但我不知道 python 是否可以与 vim 7 中的语法突出显示交互。

编辑 作为澄清,为这个例子制作的字典是:

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

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

d[n][l] 在 d

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

我希望现在更清楚了。

有人有想法吗?

4

1 回答 1

2

这应该非常简单,但是要准确地计算出您的 dict 的外观有点困难(什么是'string'?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

管他呢。如果您想了解更多详细信息,请发布有关您的解析器的更多信息或查看我的插件中的代码。

有关详细信息,请参阅

: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
于 2009-08-26T11:30:10.947 回答