python 在vim中突出显示不匹配的括号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/542929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:20:52  来源:igfitidea点击:

Highlighting unmatched brackets in vim

pythonvimsyntax-highlighting

提问by Michael Kristofik

I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the c.vimsyntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?

在 vim 中编写 python 代码时,我被不匹配的括号反复烧毁。我喜欢它们对 C 代码的处理方式——vim 用红色突出显示了所有跟在不匹配括号后面的花括号。我c.vim简要地查看了语法文件以试图理解它,但是处理括号错误的部分非常复杂。谁能解释该代码的工作原理并建议我如何为 python 代码编写类似的东西?

Example C code with unmatched parens:

带有不匹配括号的示例 C 代码:

int main(void
{  /* brace highlighted in red */
}  /* brace highlighted in red */

Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).

由于 python 代码没有花括号来突出显示,我们将不得不选择其他东西(可能是其他括号)。

BTW, I tried out this vim pluginbut I wasn't happy with the behavior.

顺便说一句,我尝试了这个 vim 插件,但我对它的行为不满意。

Edit:

编辑:

I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a file.write()method call. It would be nice if I could get vim to make that mistake more visually obvious.

我正在使用 python 生成 C++ 代码(一种喜欢括号和分号的语言)。我有一个讨厌的习惯,就是不使用file.write()方法调用的尾随括号。如果我能让 vim 使这个错误在视觉上更明显,那就太好了。

Update:

更新:

Ok, here's what I've tried so far.

好的,这是我迄今为止尝试过的。

:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error

Unfortunately, all this does is highlight as an error the right paren of all balancedparentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it.

不幸的是,所有这些都将所有平衡括号的右括号突出显示为错误,这与我想要做的相反。我真的不明白我在这里做什么(只是从现有的 C 语法文件中复制出来的)。如果有人能解释我做了什么(错误),我将不胜感激。

采纳答案by DrAl

If I understand correctly and you are trying to look at non-matching parenthesis in C code (that was generated in python), I would recommend you install rainbow.vim from Dr Chip's Site. This will highlight braces in different colours depending on the levels of indentation and will highlight unmatching braces in red as you have requested. A screenshot http://img294.imageshack.us/img294/8586/rainbow.jpg http://img294.imageshack.us/img294/8586/rainbow.jpg

如果我理解正确并且您正在尝试查看 C 代码(在 python 中生成)中的不匹配括号,我建议您从Dr Chip's Site安装 Rainbow.vim 。这将根据缩进级别以不同颜色突出显示大括号,并根据您的要求以红色突出显示不匹配的大括号。截图http://img294.imageshack.us/img294/8586/rainbow.jpg http://img294.imageshack.us/img294/8586/rainbow.jpg

To install, download rainbow.vimand place in vimfiles/after/syntax/c/(create this directory if it is not present).

安装、下载rainbow.vim并放入vimfiles/after/syntax/c/(如果该目录不存在,则创建该目录)。

On Linux, this will be ~/.vim/after/syntax/c/rainbow.vim

在 Linux 上,这将是 ~/.vim/after/syntax/c/rainbow.vim

On Windows, it may be c:\vim\vimfiles\after\syntax\c\rainbow.vimor possibly somewhere else, see :help runtimepath.

在 Windows 上,它可能在c:\vim\vimfiles\after\syntax\c\rainbow.vim或可能在其他地方,请参阅:help runtimepath

Note that there are some plugins that conflict with rainbow.vim, but it's not too hard to make them co-operate.

请注意,有一些插件会与 发生冲突rainbow.vim,但让它们协同工作并不难。

If you are trying to highlight non-matching parenthesis in the python code, you could modify rainbow.vim to use the python syntax clusters instead of the C ones, but this is a little more involved, but you could use something along the lines of (modified version of Dr Chip's rainbow code):

如果你想在 python 代码中突出显示不匹配的括号,你可以修改 Rainbow.vim 来使用 python 语法集群而不是 C 的,但这有点复杂,但你可以使用类似的东西(奇普博士彩虹代码的修改版):

syn cluster pyParenGroup contains=pythonString,pythonRawString,pythonEscape,pythonNumber,pythonBuiltin,pythonException
syn match pyParenError display ')'
syn region  pyParen     transparent matchgroup=hlLevel0 start='(' end=')' contains=@pyParenGroup,pyParen1
syn region  pyParen1        transparent matchgroup=hlLevel1 start='(' end=')' contains=@pyParenGroup,pyParen2
syn region  pyParen2        transparent matchgroup=hlLevel2 start='(' end=')' contains=@pyParenGroup,pyParen3
syn region  pyParen3        transparent matchgroup=hlLevel3 start='(' end=')' contains=@pyParenGroup,pyParen4
syn region  pyParen4        transparent matchgroup=hlLevel4 start='(' end=')' contains=@pyParenGroup,pyParen5
syn region  pyParen5        transparent matchgroup=hlLevel5 start='(' end=')' contains=@pyParenGroup,pyParen6
syn region  pyParen6        transparent matchgroup=hlLevel6 start='(' end=')' contains=@pyParenGroup,pyParen7
syn region  pyParen7        transparent matchgroup=hlLevel7 start='(' end=')' contains=@pyParenGroup,pyParen8
syn region  pyParen8        transparent matchgroup=hlLevel8 start='(' end=')' contains=@pyParenGroup,pyParen9
syn region  pyParen9        transparent matchgroup=hlLevel9 start='(' end=')' contains=@pyParenGroup,pyParen
hi link pyParenError Error

if &bg == "dark"
    hi default   hlLevel0 ctermfg=red         guifg=red1
    hi default   hlLevel1 ctermfg=yellow      guifg=orange1      
    hi default   hlLevel2 ctermfg=green       guifg=yellow1      
    hi default   hlLevel3 ctermfg=cyan        guifg=greenyellow  
    hi default   hlLevel4 ctermfg=magenta     guifg=green1       
    hi default   hlLevel5 ctermfg=red         guifg=springgreen1 
    hi default   hlLevel6 ctermfg=yellow      guifg=cyan1        
    hi default   hlLevel7 ctermfg=green       guifg=slateblue1   
    hi default   hlLevel8 ctermfg=cyan        guifg=magenta1     
    hi default   hlLevel9 ctermfg=magenta     guifg=purple1
else
    hi default   hlLevel0 ctermfg=red         guifg=red3
    hi default   hlLevel1 ctermfg=darkyellow  guifg=orangered3
    hi default   hlLevel2 ctermfg=darkgreen   guifg=orange2
    hi default   hlLevel3 ctermfg=blue        guifg=yellow3
    hi default   hlLevel4 ctermfg=darkmagenta guifg=olivedrab4
    hi default   hlLevel5 ctermfg=red         guifg=green4
    hi default   hlLevel6 ctermfg=darkyellow  guifg=paleturquoise3
    hi default   hlLevel7 ctermfg=darkgreen   guifg=deepskyblue4
    hi default   hlLevel8 ctermfg=blue        guifg=darkslateblue
    hi default   hlLevel9 ctermfg=darkmagenta guifg=darkviolet
endif

EDIT:

编辑:

As a test, I downloaded gvim70.zipand vim70rt.zipfrom ftp://ftp.vim.org/pub/vim/pc/(these are the Windows versions of Vim 7.0). I unzipped the two files into a new directory and ran gvim.exefrom vim/vim70/gvim.exe. I do nothave any vim configuration stored in "C:\Documents and Settings", so running this vim is the same as running a 'vanilla' configuration. I then downloaded pyprint.pyfrom amk.ca/python/simple/pyprint.htmlas a piece of sample code and copied the above code into a file called code.vim. In gVim, I entered :e pyprint.py. It opened in the white-background window, with no syntax highlighting. I then entered :syntax on, which switched the default syntax highlighting on. I added a second )character on line 8. Finally, I entered :source code.vim, which made the second )character be highlighted in red.

作为测试,我从ftp://ftp.vim.org/pub/vim/pc/下载了gvim70.zipvim70rt.zip(这些是 Vim 7.0 的 Windows 版本)。我将这两个文件解压缩到一个新目录中并从. 我没有在“C:\Documents and Settings”中存储任何 vim 配置,所以运行这个 vim 与运行“vanilla”配置相同。然后我从amk.ca/python/simple/pyprint.html下载了一段示例代码,并将上面的代码复制到一个名为 code.vim 的文件中。在 gVim 中,我输入了. 它在白色背景窗口中打开,没有语法高亮显示。然后我进入gvim.exevim/vim70/gvim.exepyprint.py:e pyprint.py:syntax on,它打开了默认语法突出显示。我)在第 8 行添加了第二个字符。最后,我输入了:source code.vim,这使第二个)字符以红色突出显示。

I've also carried out this test on Linux (with Vim 7.2), by entering the following command sequence:

我还在 Linux(使用 Vim 7.2)上进行了这个测试,输入以下命令序列:

cd ~
mv .vimrc old_dot_vimrc
mv .gvimrc old_dot_gvimrc
mv .vim old_dot_vim
vim pyprint.py
:e pyprint.py
" Add extra bracket here!
:syntax on
:source code.vim

Again, the second bracket is highlighted and everything else seems normal.

同样,第二个括号突出显示,其他一切似乎正常。

回答by Andrew Barnett

You can get vim to do the opposite: do a

你可以让 vim 做相反的事情:做一个

:set showmatch

:set showmatch

and it will highlight matching parens. You'll know when you're unbalanced when it doesn't highlight something.

它将突出显示匹配的括号。当它没有突出某些东西时,您就会知道何时不平衡。

I'm also assuming you're familiar with the '%' command, which bounces you to the matching element.

我还假设您熟悉 '%' 命令,它会将您跳转到匹配的元素。

回答by Whaledawg

Stop gap solution:

止损解决方案:

:imap ( ()<C-[>i

This will make it so every time you type a left paren it will automatically put in the right and put you in the position of typing in between.

这将使每次您键入左括号时,它都会自动放在右侧,并将您置于中间键入的位置。

回答by Brian Carper

Not sure if it'll be more or less confusing for you, but you could look at the lisp.vimsyntax file (especially the part where g:lisp_rainbowis handled) to see how you can highlight matching parens.

不确定它是否会或多或少让您感到困惑,但您可以查看lisp.vim语法文件(尤其g:lisp_rainbow是处理的部分)以了解如何突出显示匹配的括号。

If you manage to highlight all the matching parens, you could have the leftover parens (i.e. unmatched parens) have default Error highlighting. This is what the lisp file seems to be doing.

如果您设法突出显示所有匹配的括号,您可以让剩余的括号(即不匹配的括号)具有默认的错误突出显示。这就是 lisp 文件似乎正在做的事情。

EDIT: How about this:

编辑:这个怎么样:

syn match parenError ")"
syn region matchingParens transparent start="(" end=")" contains=matchingParens
hi parenError guifg=red

If you :syn clearand run those, it seems to work. Note that the order the syncommands are executed matters. Per :h :syn-priority, the rule matched lastis the one that takes effect, which may be why your rules highlighted all the end-parens in the file.

如果你:syn clear并运行它们,它似乎工作。请注意,syn执行命令的顺序很重要。Per :h :syn-priority最后匹配的规则是生效的规则,这可能是您的规则突出显示文件中所有结尾括号的原因。

EDIT #2:

编辑#2:

What c.vim is actually doing is highlighting any{}inside of (), whether everything is properly closed or not. Try typing ({})in C mode, it still highlights the {}as an error.

c.vim 实际上在做的是突出显示 的任何{}内部(),无论一切是否正确关闭。尝试({})在 C 模式下输入,它仍然突出显示{}为错误。

I don't think this approach can be used to test directly for a (with an unmatched ), because :syn regiondoesn't care whether the end-pattern is there or not.

我不认为这种方法可用于直接测试 a(与 unmatched ),因为:syn region不关心是否存在结束模式。

So you have to find something Python-specific that should never belong inside (). Then match against "(\_[^)]*the_forbidden_something". I don't know Python enough to know what that might be.

所以你必须找到一些不应该属于 Python 特定的东西()。然后对战"(\_[^)]*the_forbidden_something"。我对 Python 不够了解,无法知道那可能是什么。

If nothing else, you can do:

如果没有别的,你可以这样做:

syn match openParen "(\_[^)]*\%$"

which matches an open paren with no closing parens before the end-of-file. This fails if it finds any closing paren at all, which means it won't even catch (()<EOF>.

它匹配在文件结束之前没有关闭括号的开放括号。如果它找到任何关闭括号,这将失败,这意味着它甚至不会 catch (()<EOF>

回答by Nathan Fellman

Have you tried using matchit.vim? It supports all sorts of matches, and it shouldwork in Python.

你试过使用matchit.vim吗?它支持各种匹配,并且应该可以在 Python 中工作。

回答by Bryce Guinta

The plugin vim-matchopendoes what you are looking for

插件vim-matchopen 可以满足您的需求


The highlight color changes based on your colorscheme


高光颜色根据您的配色方案而变化

回答by Michael Kristofik

As a workaround, I found this indent scripton the vim website that supposedly does a better job of indenting Python code. When you end a line with unbalanced parens, it indents the next line to line up with the open paren.

作为一种解决方法,我在 vim 网站上发现了这个缩进脚本,据说它在缩进 Python 代码方面做得更好。当您以不平衡的括号结束一行时,它会缩进下一行以与开放的括号对齐。