我试图让我的 Vim 设置在打开 Scala 文件时自动折叠导入语句。这与 Intellij 打开文件时的操作类似。目前,我的 .vimrc
文件中有以下几行来自 wiki .
set foldmethod=syntax
set foldenable
syn region foldImports start=/(^\s*^import\) .\+/ end=/^\s*$/ transparent fold keepend
但是,当我打开 .scala
文件时,它不会折叠导入,而是折叠对象的主体。我也在使用vim-scala plugin 。感谢您的帮助!
最佳答案
您已经非常接近让它发挥作用了。我们应该考虑一些奇怪的因素。
- 将
foldmethod
设置为syntax
(顺便说一句,这在学习 Vimscript the Hardway 中没有记录。所以:help Foldmethod
是解决这个问题的关键出)
SYNTAX fold-syntax
A fold is defined by syntax items that have the "fold" argument. |:syn-fold|
The fold level is defined by nesting folds. The nesting of folds is limited with 'foldnestmax'.
Be careful to specify proper syntax syncing. If this is not done right, folds may differ from the displayed highlighting. This is especially relevant when using patterns that match more than one line. In case of doubt, try using brute-force syncing:
:syn sync fromstart
要注意的主要事情是 sync fromstart
如果您有可以在整个文件中匹配的正则表达式并且只想捕获 header ,那么这是一个有用的帮助器。在你的情况下,你应该能够忽略这一点,但只是需要注意一些。
- 自上而下的正则表达式扫描
由于导入 block 是相当可预测的,我们可以简化 start
和 end
看起来像这样:
syn region foldImports start="import" end=/import.*\n^$/ fold keepend
由于region
只是寻找一些字符串来开始匹配,我们可以使用“import”
(或/import/
)然后对于最终值,我们想要使用更精心设计的语句。关键是我们希望结尾是导入的最后一行,后面有一个空行 (/import.*\n^$/
)
希望这对你有用(我不使用 scala,所以你可能需要根据需要稍微调整正则表达式)
关于scala - 在 Vim 中折叠 Scala 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34563239/