Wrap and unwrap a line in Vim

Last updated: 2023/07/06

Vim is a text editor that is renowned for having a steep learning curve. People like to illustrate its difficulty by pointing out that Vim is so unfriendly to new users that they do not even know how to quit the program!

I learned Vim (and Perl) because that was what my supervisor was using when I was a Honours student. Nowadays Vim is typically not recommended for new users; for example the Software Carpentry recommends Nano. However it is still widely used as an Integrated Development Environment.

I included the brief introduction because I have never written a post about Vim despite using it for over a decade. I use Vim to write my documentation in Markdown and I like to wrap my lines. You can wrap a long line by pressing "g + q + q".

However, I often have to edit a sentence or paragraph that I have already wrapped. After editing I need to re-warp the lines because I have added or removed words. I've been doing this manually until I finally said to myself that I should find a better way to do this.

I should have looked this up a long time ago because it is extremely easy to unwrap a line. You just need to press "v + i + p + J" (capitalised j). If you navigate the cursor to the wrapped line and press those keys, the line becomes unwrapped!

If you do not want to press "gqq" each time to wrap a line, you can turn on automatic line wrapping by using the following setting:

:set tw=79

You can use unwrapping with automatic line wrapping but after unwrapping you need to manually wrap the line by pressing "ggq".

In conclusion, if something seems tedious to do, you should definitely look for a better way to do it! As demonstrated in this post, sometimes the solution is very easy.

Map

If you do this a lot you can map the key combinations to a single key. Include these mappings in your .vimrc file:

:nnoremap <F5> gqq
:nnoremap <F6> vipJgqq

Pressing the F5 key will wrap a line and pressing F6 will join the line back up and then perform a wrap, as I explained above.

Soft wrapping

I shared this post on Mastodon and John Marshall pointed out that hard wrapping (actually adding line breaks into your text) is bad for version control. This is because if you added one word, then every line is different after re-wrapping.

John suggested soft wrapping with:

:set linebreak wrap

but it seems that it may be difficult to soft wrap at 80 characters in Vim in window of arbitrary width, which is what I want.

I do use version control with my documentation, so I should take this into consideration. One solution is to edit my sentences with hard wrapping and after editing I can unwrap it.




Creative Commons License
This work is licensed under a Creative Commons
Attribution 4.0 International License
.
2 comments Add yours

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.