Word wrapping

4.3
(87)

I’ve been writing a lot of text recently in Vim: Notes, blog posts, pretty much any prose I need to write — they all start in Vim first for me (including this blog post). But when writing and editing prose, adding hard line breaks is often unnatural. Instead, I’d prefer if Vim would soft wrap my text at the width of my window.

Vim can do that, and there’s a few options you can set together in order to create a better soft-wrapped text experience:

  • :set wrap – Wraps text instead of forcing a horizontal scroll. This is the Vim default, but just noting here that you do need to have this set, naturally.
  • :set linebreak – Wraps text at the end of a word. This is what prevents a word from being split in two.
  • :set nolist – You must turn off list which displays whitespace characters as text.

It’s important to note that the mappings you use such as j and k to go up and down and ^ (or 0) and $ to go the beginning and end of a line, all apply to actual lines, not soft-wrapped “display” lines. Vim does have a way to navigate across wrapped lines, however! Prepend g to any of those key presses:

  • gj – Go down one wrapped line
  • gk – Go up one wrapped line
  • g^ or g0 – Go to the beginning of the wrapped line
  • g$ – Go to the end of the wrapped line

But that’s sort of annoying. Rather than needing to prepend all of those key presses with g while in word-wrap mode, we could simply remap all of those. For example j could be mapped to gj while in this special prose-writing word-wrap mode. Let’s put this all together into a function inside our .vimrc that allows us to toggle this mode on and off:

let s:wrapenabled = 0
function! ToggleWrap()
  set wrap nolist
  if s:wrapenabled
    set nolinebreak
    unmap j
    unmap k
    unmap 0
    unmap ^
    unmap $
    let s:wrapenabled = 0
  else
    set linebreak
    nnoremap j gj
    nnoremap k gk
    nnoremap 0 g0
    nnoremap ^ g^
    nnoremap $ g$
    vnoremap j gj
    vnoremap k gk
    vnoremap 0 g0
    vnoremap ^ g^
    vnoremap $ g$
    let s:wrapenabled = 1
  endif
endfunction
map <leader>w :call ToggleWrap()<CR>

When I call <leader>w or \w, Vim will turn on wrapping, toggle wrapping at word boundaries, and turn off listchar display. It will also remap all my line navigation keys to display lines rather than actual hard lines.

If you’re interested in more tips like this that are useful for note-taking in Vim, you might want to pre-order our course Master Vim Note-Taking. We are hard at work on this course, it’s shaping up to be even better than our first course, Git Better with Vim.

How useful was this tip?

Average rating 4.3 / 5. Vote count: 87

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts