Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to wrap text for printing in Vim

📅 2015-Nov-09 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ print, vim, wrap ⬩ 📚 Archive

Problem

Vim can be used to print a text file using your printer. The font and font size used for printing can be configured in Vim. Depending on the font and font size used you may find that the width of the paper is not enough to accommodate the width of the text. Parts of the lines longer than the paper width are simply not printed!

Solution

Vim can be requested to wrap the text using :set wrap command. However, this is only for display and the text width used for wrapping is the width of the terminal or window that Vim is using. This has no effect on printing.

What we need to do is to set a text width and reformat the text by enforcing this text width. Note that you will need to check how many columns of text width will fit into the printed page for your font, font size and paper size.

:set textwidth=80
gg
gq
G

The breakdown of this command is: gg moves cursor to first line of file. gq is the command to reformat all text from current position to the position specified after this. G is the command to move to last line of file. When applied after gq, this reformats the entire file from first line to last line, enforcing the text width we specified earlier.

The formatted file can now be printed. After printing, you can undo this reformatting if it is not needed.

For more details about these commands:

:help textwidth
:help gq
:help wrap

Tried with: Vim 7.4 and Ubuntu 14.04


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧