Usr_25
Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.
VIM USER MANUALby Bram Moolenaar
Editing formatted text
Text hardly ever comes in one sentence per line. This chapter is aboutbreaking sentences to make them fit on a page and other formatting.Vim also has useful features for editing single-line paragraphs and tables.
25.1 Breaking lines
25.2 Aligning text
25.3 Indents and tabs
25.4 Dealing with long lines
25.5 Editing tables
Breaking lines
Vim has a number of functions that make dealing with text easier. By default,the editor does not perform automatic line breaks. In other words, you haveto press
<Enter> yourself. This is useful when you are writing programs whereyou want to decide where the line ends. It is not so good when you arecreating documentation and want the text to be at most 70 character wide. If you set the
'textwidth' option, Vim automatically inserts line breaks.Suppose, for example, that you want a very narrow column of only 30characters. You need to execute the following command:
:set textwidth=30
Now you start typing (ruler added):
1 2 312345678901234567890123456789012345
I taught programming for a whi
If you type "l" next, this makes the line longer than the 30-character limit.When Vim sees this, it inserts a line break and you get the following:
1 2 312345678901234567890123456789012345
I taught programming for a
whil
Continuing on, you can type in the rest of the paragraph:
1 2 312345678901234567890123456789012345
I taught programming for a
while. One time, I was stopped
by the Fort Worth police,
because my homework was too
hard. True story.
You do not have to type newlines; Vim puts them in automatically.
Note:The
'wrap' option makes Vim display lines with a line break, but thisdoesn't insert a line break in the file.
REFORMATTING
The Vim editor is not a word processor. In a word processor, if you deletesomething at the beginning of the paragraph, the line breaks are reworked. InVim they are not; so if you delete the word "programming" from the first line,all you get is a short line:
1 2 312345678901234567890123456789012345
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 firstline, type:
v4jgq
"v" to start Visual mode, "4j" to move to the end of the paragraph and thenthe "gq" operator. The result is:
1 2 312345678901234567890123456789012345
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 textlayouts, see
auto-format.
Since "gq" is an operator, you can use one of the three ways to select thetext 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, butyou have to know the line count. A more useful motion command is "}". Thismoves to the end of a paragraph. Thus "gq}" formats from the cursor to theend 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 thewhole 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 joinedtogether. A common mistake is to have a line with a space or tab. That's ablank line, but not an empty line.
Vim is able to format more than just plain text. See
fo-table for how tochange this. See the
'joinspaces' option to change the number of spaces usedafter a full stop. It is possible to use an external program for formatting. This is usefulif your text can't be properly formatted with Vim's builtin command. See the
'formatprg' option.
To center a range of lines, use the following command:
:{range}center [width]{range} is the usual command-line range. [width] is an optional line width touse for centering. If [width] is not specified, it defaults to the value of
'textwidth'. (If
'textwidth' is 0, the default is 80.) For example:
:1,5center 40
results in the following:
I taught for a while. One
time, I was stopped by the
Fort Worth police, because my
homework was too hard. True
story.
RIGHT ALIGNMENT
Similarly, the ":right" command right-justifies the text:
:1,5right 37
gives this result:
I taught for a while. One
time, I was stopped by the
Fort Worth police, because my
homework was too hard. True
story.
LEFT ALIGNMENT
Finally there is this command:
:{range}left [margin]Unlike ":center" and ":right", however, the argument to ":left" is not thelength of the line. Instead it is the left margin. If it is omitted, thetext will be put against the left side of the screen (using a zero marginwould do the same). If it is 5, the text will be indented 5 spaces. Forexample, use these commands:
:1left 5:2,5left
This results in the following:
I taught for a while. One
time, I was stopped by the
Fort Worth police, because my
homework was too hard. True
story.
Vim has no built-in way of justifying text. However, there is a neat macropackage that does the job. To use this package, execute the followingcommand:
:packadd justify
Or put this line in your
vimrc:
:packadd! justify
This Vim script file defines a new visual command "_j". To justify a block oftext, highlight the text in Visual mode and then execute "_j". Look in the file for more explanations. To go there, do "gf" on this name:$VIMRUNTIME/pack/dist/opt/justify/plugin/justify.vim.
An alternative is to filter the text through an external program. Example:
:%!fmt
25.3 Indents and tabs
Indents can be used to make text stand out from the rest. The example textsin this manual, for example, are indented by eight columns. You wouldnormally enter this by typing
<Tab> at the start of each line. Take thistext:
the first linethe second line
This is entered by typing
<Tab>, some text,
<Enter>,
<Tab> and more text. The
'autoindent' option inserts indents automatically:
:set autoindent
When a new line is started it gets the same indent as the previous line. Inthe above example, pressing the
<Tab> key after
<Enter> is not needed anymore.
INCREASING INDENT
To increase the amount of indent in a line, use the ">" operator, in Normalmode. Often this is used as ">>", which adds indent to the current line.In Insert mode, use
<C-t>. The amount of indent added is specified with the
'shiftwidth' option. Thedefault value is 8. To make ">>" insert four columns worth of indent, forexample, type this:
:set shiftwidth=4
When used on the second line of the example text, this is what you get:
the first line
the second line
"4>>" will increase the indent of four lines.
SOFT TAB STOPS
If you want to make indents a multiple of 4, you set
'shiftwidth' to 4. Butwhen pressing a
<Tab> you still get 8 columns worth of indent. To changethis, set the
'softtabstop' option:
:set softtabstop=4
Vim now creates invisible tab stops for your cursor every 4 columns; hitting
<Tab> jumps to the next stop and inserts the exact mix of spaces or tabsneeded.
Note:You could set the
'tabstop' option to 4. However, if you edit thefile another time, with
'tabstop' set to the default value of 8, itwill look wrong. In other programs and when printing the indent willalso be wrong. Therefore it is recommended to keep
'tabstop' at eightall the time. That's the standard value everywhere on UNIX-likesystems.
25.4 Dealing with long lines
Sometimes you will be editing a file that is wider than the number of columnsin the window. When that occurs, Vim wraps the lines so that everything fitson the screen. If you switch the
'wrap' option off, each line in the file shows up as oneline on the screen. Then the ends of the long lines disappear off the screento the right. When you move the cursor to a character that can't be seen, Vim will scrollthe text to show it. This is like moving a viewport over the text in thehorizontal direction. By default, Vim does not display a horizontal scrollbar in the GUI. If youwant to enable one, use the following command:
:set guioptions+=b
One horizontal scrollbar will appear at the bottom of the Vim window.
If you don't have a scrollbar or don't want to use it, use these commands toscroll the text. The cursor will stay in the same place, but it's moved backinto the visible text if necessary.
zhscroll right4zhscroll four characters rightzHscroll half a window width rightzescroll right to put the cursor at the endzlscroll left4zlscroll four characters leftzLscroll half a window width leftzsscroll left to put the cursor at the start
Let's attempt to show this with one line of text. The cursor is on the "w" of"which". The "current window" above the line indicates the text that iscurrently visible. The "window"s below the text indicate the text that isvisible after the command left of it.
|<-- current window -->|some long text, part of which is visible in the window
ze
|<-- window -->| zH
|<-- window -->| 4zh
|<-- window -->| zh
|<-- window -->| zl
|<--window -->| 4zl
|<-- window -->| zL
|<-- window -->| zs
|<--window -->|MOVING WITH WRAP OFF
When
'wrap' is off and the text has scrolled horizontally, you can use thefollowing commands to move the cursor to a character you can see. Thus textleft and right of the window is ignored. These never cause the text toscroll:
g0to first visible character in this lineg^to first non-blank visible character in this linegmto middle of screen linegMto middle of the text in this lineg$to last visible character in this line
|<-- window -->|some long text, part of which is visible in one line
g0 g^ gm gM g$
When preparing text for use by another program, you might have to makeparagraphs without a line break. A disadvantage of using
'nowrap' is that youcan't see the whole sentence you are working on. When
'wrap' is on, words arebroken halfway, which makes them hard to read. A good solution for editing this kind of paragraph is setting the
'linebreak' option. Vim then breaks lines at an appropriate place whendisplaying the line. The text in the file remains unchanged. Without
'linebreak' text might look like this:
+---------------------------------+|letter generation program for a b||ank. They wanted to send out a s||pecial, personalized letter to th||eir richest 1000 customers. Unfo||rtunately for the programmer, he |+---------------------------------+
After:
:set linebreak
it looks like this:
+---------------------------------+|letter generation program for a ||bank. They wanted to send out a ||special, personalized letter to ||their richest 1000 customers. ||Unfortunately for the programmer,|+---------------------------------+
Related options:
'breakat' specifies the characters where a break can be inserted.
'showbreak' specifies a string to show at the start of broken line.Set
'textwidth' to zero to avoid a paragraph to be split.
MOVING BY VISIBLE LINES
The "j" and "k" commands move to the next and previous lines. When used ona long line, this means moving a lot of screen lines at once. To move only one screen line, use the "gj" and "gk" commands. When a linedoesn't wrap they do the same as "j" and "k". When the line does wrap, theymove to a character displayed one line below or above. You might like to use these mappings, which bind these movement commands tothe cursor keys:
:map <Up> gk:map <Down> gj
TURNING A PARAGRAPH INTO ONE LINE
edit-paragraph-joinIf you want to import text into a program like MS-Word, each paragraph shouldbe a single line. If your paragraphs are currently separated with emptylines, this is how you turn each paragraph into a single line:
:g/./,/^$/join
That looks complicated. Let's break it up in pieces:
:g/./A ":global" command that finds all lines that containat least one character. ,/^$/A range, starting from the current line (the non-emptyline) until an empty line. joinThe ":join" command joins the range of lines togetherinto one line.
Starting with this text, containing eight lines broken at column 30:
+----------------------------------+|A letter generation program ||for a bank. They wanted to ||send out a special, ||personalized letter. || ||To their richest 1000 ||customers. Unfortunately for ||the programmer, |+----------------------------------+
You end up with two lines:
+----------------------------------+|A letter generation program for a ||bank.They wanted to send out a s||pecial, personalized letter. ||To their richest 1000 customers. ||Unfortunately for the programmer, |+----------------------------------+
Note that this doesn't work when the separating line is blank but not empty;when it contains spaces and/or tabs. This command does work with blank lines:
:g/\S/,/^\s*$/join
This still requires a blank or empty line at the end of the file for the lastparagraph to be joined.
Suppose you are editing a table with four columns:
nice table test 1test 2 test 3
input A 0.534
input B 0.913
You need to enter numbers in the third column. You could move to the secondline, use "A", enter a lot of spaces and type the text. For this kind of editing there is a special option:
set virtualedit=all
Now you can move the cursor to positions where there isn't any text. This iscalled "virtual space". Editing a table is a lot easier this way. Move the cursor by searching for the header of the last column:
/test 3
Now press "j" and you are right where you can enter the value for "input A".Typing "0.693" results in:
nice table test 1 test 2 test 3
input A 0.534 0.693
input B 0.913
Vim has automatically filled the gap in front of the new text for you. Now,to enter the next field in this column use "Bj". "B" moves back to the startof a white space separated word. Then "j" moves to the place where the nextfield can be entered.
Note:You can move the cursor anywhere in the display, also beyond the endof a line. But Vim will not insert spaces there, until you insert acharacter in that position.
COPYING A COLUMN
You want to add a column, which should be a copy of the third column andplaced before the "test 1" column. Do this in seven steps:1. Move the cursor to the left upper corner of this column, e.g., with "/test 3".2. PressCTRL-V to start blockwise Visual mode.3. Move the cursor down two lines with "2j". You are now in "virtual space": the "input B" line of the "test 3" column.4. Move the cursor right, to include the whole column in the selection, plus the space that you want between the columns. "9l" should do it.5. Yank the selected rectangle with "y".6. Move the cursor to "test 1", where the new column must be placed.7. Press "P".
The result should be:
nice table test 3 test 1 test 2 test 3
input A 0.693 0.534 0.693
input B 0.913
Notice that the whole "test 1" column was shifted right, also the line wherethe "test 3" column didn't have text.
Go back to non-virtual cursor movements with:
:set virtualedit=
VIRTUAL REPLACE MODE
The disadvantage of using
'virtualedit' is that it "feels" different. Youcan't recognize tabs or spaces beyond the end of line when moving the cursoraround. Another method can be used: Virtual Replace mode. Suppose you have a line in a table that contains both tabs and othercharacters. Use "rx" on the first tab:
| rx | V
The layout is messed up. To avoid that, use the "gr" command:
| grx | V
What happens is that the "gr" command makes sure the new character takes theright amount of screen space. Extra spaces or tabs are inserted to fill thegap. Thus what actually happens is that a tab is replaced by "x" and thenblanks added to make the text after it keep its place. In this case atab is inserted. When you need to replace more than one character, you use the "R" commandto go to Replace mode (see
04.9). This messes up the layout and replacesthe wrong characters:
| R0.786 |V
The "gR" command uses Virtual Replace mode. This preserves the layout:
|gR0.786 |V
REFORMATTING TABS IN TABLES
You edit a file that contains tabular data and the original author of the filedecided to align the tabular data using tab characters (instead of spaces).Alas, they were using tab stops separated by 4 columns and Vim's defaultis 8 columns; the table looks wrong! What can be done? To fix the appearance without modifying the file, adjust the settingtemporarily:
:set tabstop=4
This updates the visual layout, but the file itself remains unchanged. Another possibility is to permanently reformat the file. For this Vimprovides the
:retab command. First, set
'tabstop' to match original layout(as above), then run:
:retab 8
The ":retab" command will change
'tabstop' to 8, while changing the text suchthat it looks the same. It changes spans of white space into tabs and spacesfor this. You can now write the file.
Warning: When using ":retab" on a program, it may change white space insidea string constant. Therefore it's a good habit to use "\t" instead of areal tab.