Thursday, July 24, 2008

vi vim reformat

(from the Vim documentation article "Editing formatted text" at vim.org)
REFORMATTING
The Vim editor is not a word processor. In a word processor, if you delete something at the beginning of the paragraph, the line breaks are reworked. In Vim they are not; so if you delete the word "programming" from the first line, all you get is a short line:

1 2 3
12345678901234567890123456789012345
I taught for a
while. One time, I was stopped
by the Fort Worth police,
because my homework was too
hard. True story.

This does not look good. To get the paragraph into shape you use the "gq" operator.
Let's first use this with a Visual selection. Starting from the first line, type:
v4jgq
"v" to start Visual mode, "4j' to move to the end of the paragraph and then the "gq" operator. The result is:

1 2 3
12345678901234567890123456789012345
I taught for a while. One
time, I was stopped by the
Fort Worth police, because my
homework was too hard. True
story.

Note: there is a way to do automatic formatting for specific types of text layouts, see |auto-format|.
Since "gq" is an operator, you can use one of the three ways to select the text it works on: With Visual mode, with a movement and with a text object.
The example above could also be done with "gq4j". That's less typing, but you have to know the line count. A more useful motion command is "}". This moves to the end of a paragraph. Thus "gq}" formats from the cursor to the end of the current paragraph.
A very useful text object to use with "gq" is the paragraph. Try this:
gqap
"ap" stands for "a-paragraph". This formats the text of one paragraph (separated by empty lines). Also the part before the cursor.
If you have your paragraphs separated by empty lines, you can format the whole file by typing this:
gggqG
"gg" to move to the first line, "gqG" to format until the last line.
Warning: If your paragraphs are not properly separated, they will be joined together. A common mistake is to have a line with a space or Tab. That's a blank line, but not an empty line.
Vim is able format more than just plain text. See |fo-table| for how to change this. See the 'joinspaces' option to change the number of spaces used after a full stop.
It is possible to use an external program for formatting. This is useful if your text can't be properly formatted with Vim's builtin command. See the 'formatprg' option.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home