【问题标题】:How to write a foldexpr for Vim that would use the comments structure?如何为 Vim 编写一个使用注释结构的 foldexpr?
【发布时间】:2014-06-21 16:38:53
【问题描述】:

是否可以构造一个foldexpr 来检测以下匹配\n\n"\s[A-Z][A-Z].*\n 作为第一级折叠的开始,并且这些匹配\n"\s[A-Z][a-z].*\n 作为第二级折叠的开始?自然,最接近的\n\n\n 将标记第一级折叠的结束,然后\n\n 将关闭第二级折叠。

还是我错过了什么?

(我当然知道 {{{ 标记,只是我在文件中添加其他标记似乎不正确......)

【问题讨论】:

  • 简短回答:是的。你试过什么?什么给你带来困难?
  • 嗯......只是所有那些set foldexpr=getline(v:lnum)=~'^"\s[A-Z][A-Z].*#' 和类似的尝试似乎都不起作用。因此我有点迷路了:)。

标签: vim folding


【解决方案1】:

您将无法在单行中做到这一点(至少,不容易或清楚地)。你会想写一个函数。

您的函数将无法使用单个 getline() 加正则表达式比较,因为 getline() 仅返回单行并且您希望在开始/结束字符串中包含多行。但是,您可以使用多个 getline() 调用并分别比较每一行。

要启用在当前现有折叠的同一级别开始新折叠,您需要返回字符串“>1”或“>2”。对于结束折叠,设置一个显式级别可能是最简单的(使用字符串“:help fold-expr。了解函数中最后一行的折叠级别可能很有用。为此,请使用函数foldlevel()

这是一个我认为可以满足您要求的示例,但如果它实际上不是您想要的,您可能需要清理它。加载脚本,获取它,它可以将自己用作测试数据:

fun! FoldSomething(lnum)
  let line1=getline(a:lnum)
  let line2=getline(a:lnum+1)
  if line1=~'^$'
    if line2=~#'^"\s[A-Z][A-Z]'
      return ">1"
    elseif line2=~'^$'
      return 0
    elseif foldlevel(a:lnum-1)==2
      return 1
    endif
  elseif line1=~#'^"\s[A-Z][a-z]'
    return ">2"
  endif
  return "="
endfun
set foldexpr=FoldSomething(v:lnum)
set foldmethod=expr
set foldcolumn=3
finish


" AA level 1 fold
" This is a level 2 fold
Here is some stuff under the fold.
It should be part of the level 2.

This isn't in the level 2.
I guess that makes it just part of the level 1.

" This is another
" level 2 fold.
" Watch out!
" This is 2 level 2 folds.


" BB another level 1 fold
" starts here.
"



This line shouldn't be folded at all.

That's because there were so many empty lines before.

【讨论】:

  • 还有一个问题:有什么地方可以放在 $VIMHOME 中吗?可能是 ~/.vim/after/ftplugin 之类的东西?你有什么建议?
  • 这取决于您何时要触发此折叠。 ~/.vim/after/ftplugin 如果您希望它适用于给定类型的所有文件(我假设这是 Vim 代码,所以它会放在一个名为 vim.vim 的文件中)。如果您只希望它用于某些文件,您可以将此文件作为脚本在某些文件的 autocmd 中获取,或者在 .vimrc 中定义函数并在 autocmds 中为某些文件设置 foldexpr 和方法。
猜你喜欢
  • 2010-10-05
  • 2011-08-24
  • 2023-03-28
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
相关资源
最近更新 更多