Micah Smith
Micah Smith

Reputation: 4471

Wrap comma-delimited lists

I often use gq$ to wrap a line in Vim.

For example, if I have set textwidth=80 as my only line in .vimrc, then

option1, option2, option3, option4, option5, option6, option7, option8, option9, option10, option11

wraps to

option1, option2, option3, option4, option5, option6, option7, option8, option9, 
option10, option11

However, if I want to wrap a comma-delimited list (without spaces), this command does not work, because Vim considers this line as a single word:

option1,option2,option3,option4,option5,option6,option7,option8,option9,option10,option11

Whereas desired output is:

option1,option2,option3,option4,option5,option6,option7,option8,option9,
option10,option11

How can I allow Vim to wrap by splitting a line on commas? I didn't see anything immediately in :help fo-table that is relevant to my case.

Upvotes: 1

Views: 225

Answers (1)

Sato Katsura
Sato Katsura

Reputation: 3086

One way to do it is to use Par. It's the best program for reflowing text hands down, but you have to really like abstractions to digest the manual. My cheat sheet for it:

  • set the environment variable PARINIT:

    export PARINIT='grTbEiq B=.,!?_A_a Q=_s>:|'
    
  • in my vimrc:

    set equalprg=par\ s0\ 72
    set formatprg=par\ s0\ 72
    
    function! s:FormatPar()
        let old_format = &formatprg
        let textwidth = &textwidth > 0 ? &textwidth : 72
        let &formatprg = 'par s0 ' . textwidth . (v:count > 0 ? 'h1p' . v:count : '')
        normal }{gq}
        normal }
        let &formatprg = old_format
    endfunc
    
    nnoremap <silent> <F2> :<C-u>silent! call <SID>FormatPar()<CR>
    

With that F2 re-formats the current paragraph, and using it with a count adds a hanging indent (that is 4F2 formats the paragraph with a hanging indent of 4).

It works very well for email messages, comments in code, and the like. It also has no problem with dealing with lists like above.

Upvotes: 2

Related Questions