Michael Anhari

Formatting text to a desired width in vim

Laptop with terminal application on screen

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
      79).
      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:

Formatting text in vim using the gq command.

Ah, so many yays right now.

Newsletter

I'm working on sending out a weekly newsletter. I'll make it as easy as possible to unsubscribe at any time.