将git commit消息的主题行限制为50个字符

时间:2017-05-12 05:34:09

标签: git vim

我经常使用vim来格式化我的git提交消息。我在increasing popularity看到的趋势是提交消息的第一行应限制为50个字符,然后后续行应限制为72个字符。

I already know how to make my commit wrap at 72 characters based on my vimrc file

syntax on
au FileType gitcommit set tw=72

有没有办法让vim自动包装第一行50个字符,然后再用72个字符?

一个同样好的答案可以突出显示第50行第一行后的所有内容,以表示我的标题太长了...

1 个答案:

答案 0 :(得分:4)

您可以使用CursorMovedCursorMovedI自动命令根据光标当前所在的行设置所需的textwidth(或任何其他设置):

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个字符后的所有内容显示为错误(如果您愿意,也可以通过选择不同的突出显示组来使用不那么突兀的颜色)。