在 Vim 中折叠 Scala 导入

Folding of Scala imports in Vim

我试图让我的 Vim 安装程序在我打开 Scala 文件时自动折叠导入语句。这类似于打开文件时 Intellij 所做的事情。我目前在 wiki.

.vimrc 文件中有以下几行
set foldmethod=syntax
set foldenable
syn region foldImports start=/(^\s*^import\) .\+/ end=/^\s*$/ transparent fold keepend

但是,当我打开 .scala 文件时,它不会折叠导入内容,而是折叠对象的主体。我也在用vim-scala plugin。感谢您的帮助!

你已经非常接近让它工作了。我们应该考虑一些有趣的因素。

  • foldmethod 设置为 syntax(顺便说一下,这在学习 Vimscript 硬道上没有记录。所以 :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,这是一个有用的帮助程序。在你的情况下,你应该能够忽略这一点,但只是需要注意的事情。

  • 自上而下的正则表达式扫描

由于导入块是相当可预测的,我们可以将 startend 简化为如下所示:

syn region foldImports start="import" end=/import.*\n^$/ fold keepend

因为 region 只是在寻找一些字符串来开始匹配,我们可以只使用 "import"(或 /import/)然后作为我们想要使用的结束值更精心制作的声明。关键是我们希望结尾是导入的 last 行,后面有一个空行 (/import.*\n^$/)

希望这对你有用(我不使用 scala,所以你可能需要根据需要稍微调整正则表达式)