问题
I have a bash script file which starts with a function definition, like this:
#!/bin/bash
# .....
# .....
function test {
...
...
}
...
...
I use vim 7.2, and I have set g:sh_fold_enabled=1
such that folding is enabled with bash. The problem is that the folding of the function test is not ended correctly, i.e. it lasts until the end of file. It looks something like this:
#!/bin/bash
# .....
# .....
+-- 550 lines: function test {----------------------------------------
~
~
The function itself is just about 40 lines, and I want something that lookes like this ("images" say more than a thousend words, they say...):
#!/bin/bash
# .....
# .....
+-- 40 lines: function test {----------------------------------------
...
...
...
~
~
Does anyone know a good solution to this problem?
回答1:
I have done some research, and found a way to fix the problem: To stop vim from folding functions until the end of file, I had to add a skip-statement to the syntax region for shExpr
(in the file sh.vim
, usually placed somewhere like /usr/share/vim/vim70/syntax/
):
syn region shExpr ... start="{" skip="^function.*\_s\={" end="}" ...
This change stops the syntax file from thinking that the {
and }
belongs to the shExpr group, when they actually belong to the function group. Or that is how I have understood it, anyway.
Note: This fix only works for the following syntax:
function test
{
....
}
and not for this:
function test {
....
}
A quick and dirty fix for the last bug is to remove shExpr from the @shFunctionList cluster.
回答2:
It should just work, but there seems to be a bug in the syntax file. The fold region actually starts at the word 'function' and tries to continue to the closing '}', but the highlighting for the '{...}' region takes over the closing '}' and the fold continues on searching for another one. If you add another '}' you can see this in action:
function test {
...
}
}
回答3:
There seems to be a simpler solution on Reddit.
To quote the author in the post:
The options I use are:
syntax=enable filetype=sh foldmethod=syntax let g:sh_fold_enabled=3 g:is_sh=1
EDIT: Workaround
vim -u NONE -c 'let g:sh_fold_enabled=7' -c ':set fdm=syntax' -c 'sy on' file.sh
g:sh_fold_enabled=4 seemed to be the agreed upon fold-level in the discussion. This solution is working perfectly for me. I did not have to edit the syntax file.
Edit: g:sh_fold_enabled=5 is actually the right one. Not 4. Also, as the poster showed on Reddit, those commands must go before any other setting in vimrc, except the plugins.
来源:https://stackoverflow.com/questions/413015/a-problem-with-folding-bash-functions-in-vim