I've been writing a lot of text recently in Vim: Notes, blog posts, pretty much any prose I need to write, starts in Vim first for me (including this blog post). But when writing 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 offlist
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^
org0
- 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. Check out the Gist with the full script.
When I call <leader>w
or \w
, Vim will turn on wrapping, toggle wrapping at word boundaries, and turn off list
display. It will also remap all my line navigation keys to display lines rather than actual hard lines.
Drew Neil, author of Practical Vim and Modern Vim, has a detailed screencast of this whole setup over on Vimcasts. But I've also made a quick video of word wrapping in action below.
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.
This post originated on the VimTricks blog.
Top comments (0)