Vim line wrapping and word boundary

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:

  1. :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:

  1. :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):

  1. function SetWrap()
  2. 	setlocal wrap linebreak nolist
  3. 	set virtualedit=
  4. 	setlocal display+=lastline
  5. 	noremap  <buffer> <silent> <Up>   gk
  6. 	noremap  <buffer> <silent> <Down> gj
  7. 	noremap  <buffer> <silent> <Home> g<Home>
  8. 	noremap  <buffer> <silent> <End>  g<End>
  9. 	inoremap <buffer> <silent> <Up>   <C-o>gk
  10. 	inoremap <buffer> <silent> <Down> <C-o>gj
  11. 	inoremap <buffer> <silent> <Home> <C-o>g<Home>
  12. 	inoremap <buffer> <silent> <End>  <C-o>g<End>
  13. endfunction

Now you can execute this command in your buffer:

  1. :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:

  1. au BufRead *.markdown call SetWrap()

Add new comment