Vim line wrapping and word boundary
By andre
Vim (vi) is a very powerful and customizable text editor. There are many parameters you can fine-tune to adjust the way your data is displayed. For example, vim can visually wrap lines, which are too long to fit the width of the screen. This is “virtual” wrapping - no new line characters are actually added to the text. By default, vim wraps the text at the last character, which fits in the visible area. However, especially when editing long runs of text, it is much more convenient to see lines wrap at word boundaries. To achieve this simply use the following command:
:set linebreak
That’s it - your text will be wrapped on word boundaries in all active buffers. To affect the current buffer only, use this alternative:
:setlocal linebreak
When you set the option above, vim might give you one annoyance. Trying to move the cursor up or down, you will notice, that it moves not by display line, but by logical lines, which is quite inconvenient. To cure this you can create the following function (put it in your
.vimrc
file):
function SetWrap()
setlocal wrap linebreak nolist
set virtualedit=
setlocal display+=lastline
noremap <buffer> <silent> <Up> gk
noremap <buffer> <silent> <Down> gj
noremap <buffer> <silent> <Home> g<Home>
noremap <buffer> <silent> <End> g<End>
inoremap <buffer> <silent> <Up> <C-o>gk
inoremap <buffer> <silent> <Down> <C-o>gj
inoremap <buffer> <silent> <Home> <C-o>g<Home>
inoremap <buffer> <silent> <End> <C-o>g<End>
endfunction
Now you can execute this command in your buffer:
:call SetWrap()
and your cursor will behave as expected. You can combine it with the powerful
au
to automatically set this for some files, for instance:
au BufRead *.markdown call SetWrap()