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

mgi*_*son 6 git vim

我经常vim用来格式化我的git提交消息.我越来越 受欢迎的趋势是提交消息的第一行应限制为50个字符,然后后续行应限制为72个字符.

我已经知道如何根据我的vimrc文件将我的提交换行设置为72个字符:

syntax on
au FileType gitcommit set tw=72
Run Code Online (Sandbox Code Playgroud)

有没有办法让vim第一行自动换行50个字符,然后是72个字符?

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

Mar*_*oij 5

You can use the CursorMoved and CursorMovedI autocommands to set the desired textwidth (or any other setting) based on the line the cursor is currently on:

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
Run Code Online (Sandbox Code Playgroud)

The basic logic is simple: let &l:textwidth = line('.') == 1 ? 50 : 72, although the nested autocommands make it look rather funky. You could extract some of it out to a script-local function (fun! s:setup_git()) and call that, if you prefer.

The &:l syntax is the same as setlocal, by the way (but with setlocal we can't use an expression such as on the right-hand-side, only a simple string).

Some related questions:


Note that the default gitcommit.vim syntax file already stops highlighting the first line after 50 characters. From /usr/share/vim/vim80/syntax/gitcommit.vim:

syn match   gitcommitSummary    "^.\{0,50\}" contained containedin=gitcommitFirstLine nextgroup=gitcommitOverflow contains=@Spell
[..]
hi def link gitcommitSummary        Keyword
Run Code Online (Sandbox Code Playgroud)

Only the first 50 lines get highlighted as a "Keyword" (light brown in my colour scheme), after that no highlighting is applied.

If also has:

syn match   gitcommitOverflow   ".*" contained contains=@Spell
[..]
"hi def link gitcommitOverflow      Error
Run Code Online (Sandbox Code Playgroud)

Notice how it's commented out, probably because it's a bit too opinionated. You can easily add this to your vimrc though:

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
Run Code Online (Sandbox Code Playgroud)

Which will make everything after 50 characters show up as an error (you could, if you want, also use less obtrusive colours by choosing a different highlight group).