Formatting Text In Vim

April 08, 2017

After developing in vim for awhile, I’ve developed a need for text to wrap at 80 characters. Yesterday, I stumbled across the built-in gq command in vim.

Let’s take a look at what the help documentation has to say about it (:help gq):

gq{motion}		Format the lines that {motion} moves over.
      Formatting is done with one of three methods:
      1. If 'formatexpr' is not empty the expression is
        evaluated.  This can differ for each buffer.
      2. If 'formatprg' is not empty an external program
        is used.
      3. Otherwise formatting is done internally.

      In the third case the 'textwidth' option controls the
      length of each formatted line (see below).
      If the 'textwidth' option is 0, the formatted line
      length is the screen width (with a maximum width of
      The 'formatoptions' option controls the type of
      formatting |fo-table|.
      The cursor is left on the first non-blank of the last
      formatted line.

I have textwidth set to 80 (you can determine what you have it set to via :set textwidth?), so lets see what this looks like in action. The other day I was pasting in some text into vim from MIT’s Open CourseWare and needed to format it after pasting. Here’s how it works, using the gq command for the entire line with gqq:

gqq command in vim

Ah, so many yays right now.