您可以使用CursorMoved 和CursorMovedI 自动命令根据光标当前所在的行设置所需的文本宽度(或任何其他设置):
augroup gitsetup
autocmd!
" Only set these commands up for git commits
autocmd FileType gitcommit
\ autocmd CursorMoved,CursorMovedI *
\ let &l:textwidth = line('.') == 1 ? 50 : 72
augroup end
基本逻辑很简单:let &l:textwidth = line('.') == 1 ? 50 : 72,尽管嵌套的自动命令使它看起来很时髦。如果您愿意,可以将其中的一部分提取到脚本本地函数 (fun! s:setup_git()) 并调用它。
顺便说一下,&:l 的语法与 setlocal 相同(但对于 setlocal,我们不能使用右侧的表达式,只能使用简单的字符串)。
一些相关问题:
请注意,默认的gitcommit.vim 语法文件在 50 个字符后已经停止突出显示第一行。来自/usr/share/vim/vim80/syntax/gitcommit.vim:
syn match gitcommitSummary "^.\{0,50\}" contained containedin=gitcommitFirstLine nextgroup=gitcommitOverflow contains=@Spell
[..]
hi def link gitcommitSummary Keyword
只有前 50 行被突出显示为“关键字”(我的配色方案中为浅棕色),之后不应用突出显示。
如果还有:
syn match gitcommitOverflow ".*" contained contains=@Spell
[..]
"hi def link gitcommitOverflow Error
注意它是如何被注释掉的,可能是因为它有点太自以为是了。不过,您可以轻松地将其添加到您的 vimrc 中:
augroup gitsetup
autocmd!
" Only set these commands up for git commits
autocmd FileType gitcommit
\ hi def link gitcommitOverflow Error
\| autocmd CursorMoved,CursorMovedI *
\ let &l:textwidth = line('.') == 1 ? 50 : 72
augroup end
这将使 50 个字符之后的所有内容都显示为错误(如果需要,您还可以通过选择不同的高亮组来使用不那么突兀的颜色)。