Word Wrap in Vim (preserving indentation)

sixtyfootersdude picture sixtyfootersdude · May 13, 2010 · Viewed 11.5k times · Source

I was just looking at this post which describes how to wrap entire words in vim. The accepted solution was this:

:set formatoptions=l
:set lbr

Which takes this text (tabs are shown as \t):

 *Inside of window                        *Outside of window
|---------------------------------------|    
|\t\tthis is a like of text that will wr|ap here                            
|\t\tcan you see the wrap               |
|                                       |
|---------------------------------------|

This accomplishes a behavior like this (tabs are shown as \t):

 *Inside of window                        *Outside of window
|---------------------------------------|    
|\t\tthis is a like of text that will   |
|wrap here                              |
|\t\tcan you see the wrap               |
|                                       |
|---------------------------------------|

I would however like to redefine this function. I would like the wrapped line to have the same number of tabs in front of it that the line above has plus one. Ie:

 *Inside of window                        *Outside of window
|---------------------------------------|    
|\t\tthis is a like of text that will   |
|\t\t\twrap here                        |
|\t\tcan you see the wrap               |
|                                       |
|---------------------------------------|

Any ideas?

Answer

JoshuaD picture JoshuaD · Oct 26, 2014

This did not work when the question was originally asked, but as of June 25, 2014, this will work. (Assuming you update your vim to a version newer than that date)

Add to your .vimrc:

" Indents word-wrapped lines as much as the 'parent' line
set breakindent
" Ensures word-wrap does not split words
set formatoptions=l
set lbr

And that's it!

--

Some people (myself included) share a single .vimrc across multiple computers. In that case, it's important to have this line be robust (to avoid annoying error messages). This is a little better:

if has("patch-7.4.354")
    " Indents word-wrapped lines as much as the 'parent' line
    set breakindent
    " Ensures word-wrap does not split words
    set formatoptions=l
    set lbr
endif

This way, if you're on an earlier version of vim, you don't get an error message.