Limit git subject line to post commit to 50 characters

I often use vim to format git commit messages. The trend that I see with increasing popularity is that the first line of a commit message should be limited to 50 characters, and subsequent lines should be limited to 72 characters.

I already know how to do a commit transfer of 72 characters based on my vimrc file :

 syntax on au FileType gitcommit set tw=72 

Is there a way to make vim autowrap the first line with 50 characters and then 72 characters after that?

No less good answer can highlight everything after the 50th column only in the first row to indicate that my heading is too long ...

+5
source share
1 answer

You can use the CursorMoved and CursorMovedI to set the desired text width (or any other setting) based on the line the cursor is in:

 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 

The basic logic is simple: let &l:textwidth = line('.') == 1 ? 50 : 72 let &l:textwidth = line('.') == 1 ? 50 : 72 , although the nested auto-commands make it pretty funny. You can extract part from it into a script-local function ( fun! s:setup_git() ) and call it if you want.

The &:l syntax is similar to setlocal , by the way (but with setlocal we cannot use an expression, for example, on the right side, only a simple string).

Some related questions:


Note that the default syntax file gitcommit.vim 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 

Only the first 50 lines are highlighted as “Keyword” (light brown in my color scheme), after which no highlight is highlighted.

If also has:

 syn match gitcommitOverflow ".*" contained contains=@Spell [..] "hi def link gitcommitOverflow Error 

Notice how this was commented, perhaps because it is too stubborn. You can easily add this to your 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 

That will do everything after the appearance of 50 characters as an error (you could, if you want, also use less intrusive colors by choosing a different selection group).

+4
source

All Articles