The user manual (an older version) is available as a single, ready to print HTML and PDF file here: http://vimdoc.sf.net
Getting Started
Read this from start to end to learn the essential commands.
usr_01 About the manuals
:help usr_01
This chapter introduces the manials available with Vim. Read this to know the conditions under which the commands are explained.
01.1 Two manuals
The Vim docymentation consists of two parts:
- The User manual
- Task oriented explanations, from simple to complex. Reads from start to end like a book.
- The Reference manual
- Precise description of how everything in Vim works.
The notation used in these manuals is explained here: notation
JUMPING AROUND
The text contains hyperlinks between the two parts, allowing you to quickly jump between the descripting of an editing task and a precise explanation of the commands and options used for it. Use these two commands:
- Press
CTRL-]to jump to a subject under the cursor. - Press
CTRL-oto jump back (repeat to go further back).
Many links are in vertical bars,like this: bars. The bar themselves may be hidden or invisible; see below. An option name, like ‘number’, a command in double quotes like :write and any other word can also be used as a link. Try it out: Move the cursor to CTRL-] and press CTRL-o on it.
Other subjects can be found with the :help command; see help.txt
The bars and stars are usually hidden with the conceal feature. They also use hl-Ignore, using the same color for the text as the background. You can make them visible with:
:set conceallevel=0
:hi link HelpBar Normal
:hi link HelpStar Normal
01.2 Vim installed
Most of the manuals assume that Vim has bean properly installed. If you didn’t do that yet, or if Vim doesn’t run properly (e.g., files can’t be found or in the GUI the menus do not show up) first read the chapter on installation: usr_90.txt
not-compatible
The manuals often assume you are using Vim with Vi-compatibility switched off. For most commands this doesn’t matter, but sometimes it is important, e.g., for multi-level undo. An easy way to make sure you are using a nice setup is to copy the example vimrc file. By doing this inside Vim you don’t have to check out where it is located. How to do this depends on the system you are using:
Unix:
:!cp -i $VIMRUNTIME/vimrc_example.vim ~/.vimrc
MS-Windows:
:!copy $VIMRUNTIME/vimrc_example.vim $VIM/_vimrc
Amiga:
:!copy $VIMRUNTIME/vimrc_example.vim $VIM/.vimrc
If the file already exists you probably want to keep it.
If you start Vim now, The compatible option should be off. You can check it with this command:
:set compatible?
If it responds with “nocompatible” you are doing well. If the response is “compatible” you are in trouble. You will have to find out why the option is still set. Perhaps the file you wrote above is not found. Use this command to find out:
:scriptnames
If your file is not in the list, check its location and name. If it is in the list, there must be some other place where the ‘compatible’ option is switched back on.
For more info see vimrc and compatible-default.
Note
This manual is about using Vim in the normal way. There is an alternaive called “evim” (easy Vim). This is still Vim, but used in a way that resembles a click-and-type editor like Notepad. It always stays in Insert mode, thus it feels very different. It is not explained in the user manual, since it should be mostly self-explanatory. See evim-keys for details.
01.3 Using the Vim tutor
tutor vimtutor
Instead of reading the text (boring!) you can use the vimtutor to learn your first Vim commands. This is a 30-minute tytorial that teaches the most basic Vim functionality hands-on.
On Unix, if Vim has bean properly installed, you can start it from the shell:
vimtutor
On MS-Windows you can find it in the Program/Vim menu. Or execute vimtutor.bat in the $VIMRUNTIME directory.
This will make a copyof the tutor file, so that you can edit it without the risk of damaging the original.
There are a few translated versions of the tutor. To find out if yours is avaiable, use the two-letter language code. For French:
vimtutor fr
On Unix, if you prefer using the GUI version of Vim, use gvimtutor or vimtutor -g instead of vimtutor.
For OpenVMS, if Vim has bean properly installed, you can start vimtutor from a VMS prompt with:
@VIM:vimtutor
Optionally add the two-letter language code as above.
On other systems, you have to do a little work:
- Copy the tutor file. You can do this with Vim (it knows where to find it):
vim --clean -c 'e $VIMRUNTIME/tutor/tutor' -c 'w! TUTORCOPY' -c 'q'. This will write the file TUTORCOPY in the current directory.- For French:
vim --clean -c 'e $VIMRUNTIME/tutor/tutor.fr' -c 'w! TUTORCOPY' -c 'q'. To use a translated version of the tutor, append the two-letter language code to the filename.
- Edit the copied file with Vim:
vim --clean TUTORCOPY. The –clean argument makes sure Vim is started with noce defaults. - Delete the copied file when you are finished with it:
del TUTORCOPY.
01.4 Copyright
manual-copyright
The Vim user manual and reference manual are Copyright (c) 1988-2003 by Bram Moolenaar. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later. The latest version is presently available at:http://www.opencontent.org/openpub/.
People who contribute to the manuals must agree with the above copyright notice.
frombook
Parts of the user manual come from the book 《Vi IMproved - Vim》 by Steve Oualline (published by New Riders Publishing, ISBN: 0735710015). The Open Publication License applies to this book. Only selected parts are included and these have been modified (e.g., by removing the pictures, updating the text for Vim 6.0 and later, fixing mistakes). The omission of the frombook tag does not mean that the text does not come from the book.
Many thanks to Steve Oualline and New Riders for creating this book and publishing it under the OPL! It has been a great help while writing the user manual. Not only by providing literal text, but also by setting the tone and style.
If you make money through selling the manuals, you are strongly encouraged to donate part of the profit to help AIDS victims in Uganda. See iccf.
usr_02 The first steps in Vim
:help usr_02
This chapter provides just enough information to edit a file with Vim. Not well or fast, but you can edit. Take some time to practice with these commands, they form the base for what follows.
- 02.1 Running Vim for the First Time
- 02.2 Inserting text
- 02.3 Moving around
- 02.4 Deleting characters
- 02.5 Undo and Redo
- 02.6 Other editing commands
- 02.7 Getting out
- 02.8 Finding help
02.1 Running Vim for the First Time
To start Vim, enter this command: gvim file.txt. In UNIX you can type this at any command prompt. If you are running Mocrosoft Windows, open a Command Prompt and enter the command. In either case, Vim starts editing a file called file.txt. Because this is a new file, you get a blank window. This is what your screen will look like:
+---------------------------------------+
|# |
|~ |
|~ |
|~ |
|~ |
|"file.txt" [New file] |
+---------------------------------------+
('#' is the cursor position.)
The tilde(~) lines indicate lines not in the file. In other words, when Vim runs out of file to display, it displays tilde lines. At the bottom of the screen, a message line indicates the file is named file.txt and shows that you are creating a new file. The message information is temporary and other information overwrites it.
THE VIM COMMAND
The gvim command causes the editor to create a new window for editing. If you use this command:
vim file.txt
the editing occurs inside your command window. In other words, if you are running inside an xterm, the editor uses your xterm window. If you are using as MS-Windows command prompt window, the editing occurs inside this window. The text in the window will look the same for both versions, but with gvim you have extra features, like a menu bar. More about that later.
02.2 Inserting text
The Vim editor is a modal editor. That means that the editor behaves differently, depending on which mode you are in. The two basic modes are called Normal mode and Insert mode. In Normal mode the characters you type are commands. In Insert mode the characters are inserted as text.
Since you have just started Vim it will be in Normal mode. To start Insert mode you type the i command(i for Insert). Then you can enter the text. It will be inserted into the file. Do not worry if you make mistakes; you can correct then later. To enter the following programmer’s limerick, this is what you type:
iA very intelligent turtle
Found programming UNIX a hurdle
After typing turtle you press the <Enter>key to start a new line. Finally you press the <Esc> key to stop Insert mode and go back to Normal mode. You now have two lines of text in your Vim window:
+---------------------------------------+
|A very intelligent turtle |
|Found programming UNIX a hurdle |
|~ |
|~ |
| |
+---------------------------------------+
WHAT IS THE MODE?
To be able to see what mode you are in, type this command:
:set showmode
You will notice that when typing the colon Vim moves the cursor to the last line of the window. That’s where you type colon commands (commands that start with a colon). Finish this command by pressing the <Enter> key (all commands that start with a colon are finished this way).
Now, if you type the i command Vim will display –INSERT– at the bottom of the window. This indicates you are in Insert mode.
+---------------------------------------+
|A very intelligent turtle |
|Found programming UNIX a hurdle |
|~ |
|~ |
|-- INSERT -- |
+---------------------------------------+
If you press <Esc> to go back to Normal mode the last line will be made blank.
GETTING OUT OF TROUBLE
One of the problems for Vim novices is mode confusion, which is caused by forgetting which mode you are in or by accidentally typing a command that switches modes. To get back to Normal mode, no matter what mode you are in, press the <Esc> key. Sometimes you have to press it twice. If Vim beeps back at you, you already are in Normal mode.
02.3 Moving around
After you return to Normal mode, you can move around by using these keys:
| h | left | 左 |
| j | down | 下 |
| k | up | 上 |
| l | right | 右 |
At first, it may appear that these commands were chosen at random. After all, who ever heard of using l for right? But actually, these is a very good reason for these choices: Moving the cursor is the most common thing you do in an editor, and these keys are on the home row of your right hand. In other words, these commands are placed where you can type them the fastest (especially when you type with ten fingers).
Note
You can alse move the cursor by using the arrow keys. If you do, however, you greatly slow down your editing because to press the arrow keys, you must move your hand from the text keys to the arrow keys. Considering that you might be doing it hundreds of times an hour, this can take a significant amount of time.
Also, there are keyboards which do not have arrow keys, or which locate them in unusual places; therefore, knowning the use of the hjkl keys helps in those situations.
One way to remember these commands is that h is on the left, l is on the right and j points down. In a picture:
k
h l
j
The best way to learn these commands is by using them. Use the i command to insert some more lines of text. Then use the hjkl keys to move around and insert a word somewhere. Don’t forget to press <Esc> to go back to Normal mode. The vimtutor is also a nice way to learn by doing.
For Japanese users, Hiroshi Iwatani suggested using this:
Komsomolsk
^
|
Huan Ho <--- ---> Los Angeles
(Yellow river) |
v
Java (the island, not the programming language)
02.4 Deleting characters
To delete a character, move the cursor over it and type x. (This is a throwback to the old days of the typewriter, when you deleted things by typing xxxx over them.) Move the cursor to the beginning of the first line, for example, and type xxxxxxx (seven x’s) to delete “A very “. The result should look like this:
+---------------------------------------+
|intelligent turtle |
|Found programming UNIX a hurdle |
|~ |
|~ |
| |
+---------------------------------------+
Now you can insert new text, for example by typing:
iA young <Esc>
This begins an insert (the i), inserts the words A young, and then exits insert mode (the final <Esc>). The result:
+---------------------------------------+
|A young intelligent turtle |
|Found programming UNIX a hurdle |
|~ |
|~ |
| |
+---------------------------------------+
DELETING A LINE
To detete a whole line use the dd command. The following line will then move up to fill the gap:
+---------------------------------------+
|Found programming UNIX a hurdle |
|~ |
|~ |
|~ |
| |
+---------------------------------------+
DELETING A LINE BREAK
In Vim you can join two lines together, which means that the line break between them is deleted. The J command does this.
Take these two lines:
A young intelligent
turtle
Move the cursor to the first line and press J:
A young intelligent turtle
02.5 Undo and Redo
Suppose you delete too much. Well, you can type it in again, but an easier way exists. The u command undoes the last edit. Take a look at this in action: After using dd to delete the first line, u brings it back.
Another one: Move the cursor to the A in the first line:
A young intelligent turtle
Now type xxxxxxx to delete A young. The result is as follows:
intelligent turtle
Type u to undo the last delete. That delete removed the g, so the undo restores the character.
g intelligent turtle
The next u command restores the next-to-last character deleted:
ng intelligent turtle
The next u command gives you the u, and so on:
ung intelligent turtle
oung intelligent turtle
young intelligent turtle
young intelligent turtle
A young intelligent turtle
Note
If you type u twice, and the result is that you get the same text back, you have Vim configured to work Vi compatible. Look here to fix this: not-compatible.
This text assumes you work The Vim Way. You might prefer to use the good old Vi way, but you will have to watch out for small differences in the text then.
REDO
If you undo too many times, you can press CTRL-R (redo) to reverse the preceding command. In other words, it undoes the undo. To see this in action, press CTRL-R twice. The character A and the space after it disappear:
young intelligent turtle
There’s a special version of the undo command, the U (undo line) command.The undo line command undoes all the changes made on the last line that was edited. Typing this command twice cancels the preceding U.
A very intelligent turtle
xxxx Delete very
A intelligent turtle
xxxxxx Delete turtle
A intelligent
Restore line with "U"
A very intelligent turtle
Undo "U" with "u"
A intelligent
The U command is a change by itself, which the u command undoes and CTRL-R redoes. This might be a bit confusing. Don’t worry, with u and CTRL-R you can go to any of the situations you had. More about that in section 32.2
02.6 Other editing commands
Vim has a large number of commands to change the text. See Q_in and below.
Here are a few often used ones.
APPENDING
The i command inserts a character before the character under the cursor.
That works fine; but what happens if you want to add stuff to the end of the line? For that you need to insert text after the cursor. This is done with the a (append) command.
For example, to change the line
and that's not saying much for the turtle.
to
and that's not saying much for the turtle!!!
move the cursor over to the dot at the end of the line. Then type x to delete the period. The cursor is now positioned at the end of the line on the e in turtle. Now type
a!!!<Esc>
to append three exclamation points after the e in turtle:
and that's not saying much for the turtle!!!
OPENING UP A NEW LINE
The o command creates a new, empty line below the cursor and puts Vim in Insert mode. Then you can type the text for the new line.
Suppose the cursor is somewhere in the first of these two lines:
A very intelligent turtle
Found programming UNIX a hurdle
If you now use the o command and type new text:
oThat liked using Vim<Esc>
The result is:
A very intelligent turtle
That liked using Vim
Found programming UNIX a hurdle
The O command (uppercase) opens a line above the cursor.
USING A COUNT
Suppose you want to move up nine lines. You can type kkkkkkkkk or you can enter command 9k. In fact, you can precede many commands with a number. Earlier in this chapter, for instance, you added three exclamation points to the end of a line by typing a!!!<Esc>. Another wat to do this is to use the command 3a!<Esc>. Thr count of 3 tells the command that follows to triple its effect. Similarly, to delete three characters, use the command 3x. The count always comes before the command it applies to.
02.7 Getting out
To exit, use the ZZ command. This command writes the file and exits.
Note:
Unlike many other editors, Vim does not automatically make a backup file. If you type ZZ, your changes are committed and there’s no turning back. You can configure the Vim editor to produce backup files;see 07.4.
DISCARDING CHANGES
Sometimes you will make a sequence of changes and suddenly realize you were better off before you started. Not to worry; Vim has a quit-and-throw-things-away command. It is:
:q!
Don’t forget to press <Enter> to finish the command.
For those of you interested in the details, the three parts of this command are the colon (:), which enters Command-line mode; the q command, which tells the editor to quit; and the override command modifier (!).
The override command modifier is needed because Vim is reluctant to throw away changes. If you were to just type :q, Vim would display an error message and refuse to exit:
E37: No write since last change (use ! to override)
By specifying the override, you are in effect telling Vim, “I know that what I’m doing looks stupid, but I really want to do this.”
If you want to continue editing with Vim: The :e! command reloads the original version of the file.
02.8 Finding help
Everything you always wanted to know can be found in the Vim help files. Don’t be afraid to ask!
If you know what you are looking for, it is usually easier to search for it using the help system, instead of using Google. Because the subjects follow a certain style guide.
Also the help has the advantage of belonging to your particular Vim version.
You won’t see help for commands added later. These would not work for you.
To get generic help use this command
:help
You could alse use the first function key <F1>. If you keybord has a <Help> key it might work as well.
If you don’t supply a subject, :help displays the general help window. The creators of Vim did something very clever (or very lazy) with the help system: They made the help window a normal editing window. You can use all the normal Vim commands to move through the help information. Therefore h, j, k, and l move left, down, up and right.
To get out of the help window, use the same command you use to get out of the editor: ZZ. This will only close the help window, not exit Vim.
As you read the help text, you will notice some text enclosed in vertical bars (for example, help). This indicates a hyperlink. If you position the cursor anywhere between the bars and press CTRL-] (jump to tag), the help system takes you to the indicated subject. (For reasons not discussed here, the Vim terminology for a hyperlink is tag. So CTRL-] jumps to the location of the tag given by the word under the cursor.)
After a few jumps, you might want to go back. CTRL-T (pop tag) takes you back to the preceding position. CTRL-O (jump to older position) also works nicely here.
At the top of the help screen, there is the notation *help.txt*. This name between * characters is used by the help system to define a tag (hyperlink destination).
See 29.1 for details about using tags.
To get help on a given subject, use the following command:
:help {subject}
To get help on the x command, for example, enter the following:
:help x
To find out how to delete text, use this command:
:help deleting
To get a complete index of all Vim commands, use the following command:
:help index
When you need to get help for a control character command (for example, CTRL-A), you need to spell it with the prefix CTRL-.
:help CTRL-A
The Vim editor has many different modes. By default, the help system displays the normal-mode commands. For example, the following command displays help for the normal-mode CTRL-H command:
:help CTRL-H
To identify other modes, use a mode prefix. If you want the help for the insert-mode version of a command, use i_. For CTRL-H this gives you the following command:
:help i_CTRL-H
When you start the Vim editor, you can use several command-line arguments. These all begin with a dash (-). To find what the -t argument does, for example, use the command:
:help -t
The Vim editor has a number of options that enable you to configure and customize the editor. If you want help for an option, you need to enclose it in single quotation marks To find out what the number option does, for example, use the following command:
:help 'number'
The table with all mode prefixes can be found below: help-summary
Special keys are enclosed in angle brackets. To find help on the up-arrow key in Insert mode, for instance, use this command:
:help i_<Up>
If you see an error message that you don’t understand, for example:
E37: No write since last change (use ! to override)
You can use the error ID at the start to find help about it:
:help E37
help-summary
- Use
Ctrl-Dafter typing a topic and let Vim show all avaiable topics. Or press Tab to complete:
:help some<Tab>
More information on how to use the help:
:help helphelp
- Follow the links in bars to related help. You can go from the detailed help to the user documentation, which describes certain commands more from a user perspective and less detailed. E.g. after:
:help pattern.txt
You can see the user guide topics 03.9 and usr_27 in the introduction.
- Options are enclosed in single apostrophes. To go to the help topic for the list option:
:help 'list'
If you only know you are looking for a certain option, you can also do:
:help options.txt
to open the help page which describes all option handling and then search using regular expressions, e.g. textwidth.
Certain options have their own namespace, e.g.:
:help cpo-<letter>
for the corresponding flag of the cpoptions settings, substitute <letter> by a specific flag, e.g.:
:help cpo-<letter>
And for the guioptions flags:
:help go-<letter>
- Normal mode commands do not have a prefix. To go to the help page for the gt command:
:help gt
- Insert mode commands start with i_. help for deleting a word:
:help i_CTRL-W
- Visual mode commands start with v_. Help for jumping to the other side of the Visual area:
:help v_o
- Command line editing and arguments start with c_. Help for using the command argument %:
:help c_%
- Ex-commands always start with :, so to go to the
:scommand help:
:help :s
- COmmands specifically for debugging start with >. To go to the help for the cont debug command:
:help >cont
- Key combinations. They usually start with a single letter indicating the mode for which they can be used. E.g.:
:help i_CTRL-X
takes you to the family of CTRL-X commands for insert mode which can be used to auto-complete different things. Note, that certain keys will always be written the same, e.g. Control will always be CTRL.
For normal mode commands there is no prefix and the topic is available at :h CTRL-<Letter>. E.g.
:help CTRL-W
In contrast
:help c_CTRL-R
will describe what the CTRL-R does when entering commands in the Command line and
:help v_CTRL-A
talks about incrementing numbers in visual mode and
:help g_CTRL-A
talks about the g<C-A> command (e.g. you have to press g then <CTRL-A>). Here the g stands for the normal command g which always expects a second key before doing something similar to the commands starting with z.
- Regexp items always start with
/.So to get help for the\+quantifier in Vim regexes:
:help /\+
If you need to know everything about regular expressions, start reading at:
- Registers always start with quote. To find out about the special : register:
- Vim script is available at
:help eval.txt
Certain aspects of the language are available at :h expr-X where X is a single letter. E.g.
:help expr-!
will take you to the topic describing the ! (Not) operator for Vim script.
Also important is
:help function-list
to find a short description of all functions available. Help topics for Vim script functions always include the (), so:
:help append()
talks about the append Vim script function rather than how to append text in the current buffer.
- Mapping are talked about in the help page
:h map.txt. Use
:help mapmode-i
to find out about the :imp command. Also use :map-topic
to find out about certain subtopics particular for mapping. e.g:
:help :map-local
for buffer-local mapping or
:help map-bar
for how the | is handled in mappings.
- Command definitions are talked about
:h command-topic, so use
:help command-bar
to find out about the ! argument for custom commands.
- Window management commands always start with
CTRL-W, so you find the corresponding help at:h CTRL-W_letter. E.g.
:help CTRL-W_p
for moving the previous accessed window. You can also access
:help windows.txt
and read your way through if you are looking for window handling commands.
- Use
:helpgrepto search in all help pages (and also of any installed plugins). See:helpgrepfor how to use it.
To search for a topic:
:helpgrep topic
This takes you to the first match. To go to the next one:
:cnext
All matches are available in the quickfix window which can be opened with:
:copen
Move around to the match you like and press Enter to jump to that help.
- The user manual. This describes help topics for beginners in a rather friendly way. Start at usr_toc.txt to find the table of content (as you might have guessed):
:help usr_toc.txt
Skim over the contents to find interesting topics. The Digraphs and “Entering special characters” items are in chapter 24, so to go to that particular help page:
:help usr_24.txt
Also if you want to access a certain chapter in the help, the chapter number can be accessed directly like this:
:help 10.1
which goes to chapter 10.1 in usr_10.txt and talks about recording macros.
- Highlighting groups. Always start with hl-groupname. E.g.
:help hl-WarningMsg
talks about the WarningMsg highlighting group.
- Syntax highlighting is namespaced to
:syn-topic. E.g.
:help :syn-conceal
talks about the conceal argument for the :syn command.
- Quickfix commands usually start with
:cwhile location list commands usually start with:l - Autocommand events can be found by their name:
:help BufWinLeave
To see all possible events:
:help autocommand-events
- Command-line switches always start with
-. SO for the help of the-fcommand switch of Vim use:
:help -f
- Optional features always start with
+. To find out about the conceal feature use:
:help +conceal
- Documentation for included filetype specific functionality is usually available in the form
ft-<filetype>-<functionality>. So
:help ft-c-syntax
talks about the C syntax file and the option it provides. Sometimes, additional sections for omni completion
:help ft-php-omni
or filetype plugins
:help ft-tex-plugin
are available.
- Error and Warning codes can be looked up directly in the help. So
:help E297
takes you exactly to the description of the swap error message and
:help W10
talks about the warning Changing a readonly file.
SomeTimes, however, those error codes are not described, but rather are listed at the Vim command that usually causes this. So:
:help E128
takes you to the :function command
usr_03 Moving around
:help usr_03
Before you can insert or delete text the cursor has to be moved to the right place. Vim has a large number of commands to position the cursor. This chapter shows you how to use the most important ones. You can find a list of these commands below Q_lr.
- 03.1 Word movement
- 03.2 Moving to the start or end of a line
- 03.3 Moving to a character
- 03.4 Matching a paren
- 03.5 Moving to a specific line
- 03.6 Telling where you are
- 03.7 Scrolling around
- 03.8 Simple searches
- 03.9 Simple search patterns
- 03.10 Using marks
03.1 Word movement
To move the cursor forward one word, use the w command. Like most Vim commands, you can use a numeric prefix to move past multiple words. For example, 3w moves three words. This figure shows how it works (starting at the position marked with x):
This is a line with example text
x-->-->->----------------->
w w w 3w
Notice that w woves to the start of the next word if it already is at the start of a word.
The b command moves backword to the start of the previous word:
This is a line with example text
<----<--<-<---------<--x
b b b 2b b
There is also the e command that moves to the next end of a word and ge, which moves to the previous end of a word:
This is a line with example text
<----<----x---->------------>
2ge ge e 2e
If you are at the last word of a line, the w command will take you to the first word in the next line. Thus you can use this to move through a paragraph, much faster than using l. b does the same in the other direction.
A word ends at a non-word character, such as a ., - or ). To change what Vim considers to be a word, see the iskeyword option. If you try this out in the help directory, iskeyword needs to be reset for the examples to work:
:set iskeyword&
It is also possible to move by white-space separated WORDs. This is not a word in the normal sense, that’s why the uppercase is used. The commands for moving by WORDs are also uppercase, as this figure shows:
ge b w e
<- <- ---> --->
This is-a line, with special/separated/words (and some more).
<----- <----- --------------------> ----->
gE B W E
With this mix of lowercase and uppercase commands, you can quickly move forward and backward through a paragraph.
03.2 Moving to the start or end of a line
The $ command moves the cursor to the end of a line. If your keyboard has an <End> key it will do the same thing.
The ^ command moves to the first non-blank character of the line. The 0 command (zero) moves to the very first character of the line, and the <Home> key does the same thing. In a picture (. indicates a space):
^
<-----------x
.....This is a line with example text
<----------------x x-------------->
0 $
(the ….. indicates blanks here)
The $ command takes a count, like most movement commands. But moving to the end of the line several times doesn’t make sense. Therefore it causes the editor to move to the end of another line. For example, 1$ moves you to the end of the first line (the one you’re on), 2$ to the end of the next line, and so on.
The 0 command doesn’t take a count argument, because the 0 would be part of the count. Unexpectedly, using a count with ^ doesn’t have any effect.
03.3 Moving to a character
One of the most useful movement commands is the single-character search command. The command fx searches forward in the line for the single character x. Hint: f stands for Find.
For example, you are at the beginning of the following line. Suppose you want to go to the h of human. Just execute the command fh and the cursor will be positioned over the h:
To err is human. To really foul up you need a computer.
---------->--------------->
fh fy
This also shows that the command fy moves to the end of the word really.
You can specify a count; therefore, you can go to the l of foul with 3fl:
To err is human. To really foul up you need a computer.
--------------------->
3fl
The F command searches to the left:
To err is human. To really foul up you need a computer.
<---------------------
Fh
The tx command works like the fx command, except it stops one character before the searched character. Hint: t stands for To. The backward version of this command is Tx.
To err is human. To really foul up you need a computer.
<------------ ------------->
Th tn
These four commands can be repeated with ;. , repeats in the other direction. The cursor is never moved to another line. Not even when the sentence continues.
Sometimes you will start a search, only to realize that you have typed the wrong command. You type f to search backward, for example, only to realize that you really meant F. To about a search, press <Esc>. So f<Esc> is an aborted forward search and doesn’t do anything. Note: <Esc> cancels most operations, not just searches.
03.4 Matching a parenthesis
When writing a program you often end up with nested () constructs. Then the % command is very handy: It moves to the matching paren. If the cursor is on a ( it will move to the matching ). If it’s on a ) it will move to the matching (.
%
<----->
if (a == (b * c) / d)
<---------------->
%
This also works for [] and {} pairs. (This can be defined with the matchpairs option.)
When the cursor is not on a useful character, % will search forward to find one. Thus if the cursor is at the start of the line of the previous example, % will search forward and find the first (. Then it moves to its match:
if (a == (b * c) / d)
---+---------------->
%
03.5 Moving to a specific line
If you are a C or C++ programmer, you are familiar with error messages such as the following:
prog.c:33: j undeclared (first use in this function)
This tells you that you might want to fix something on line 33. So how do you find line 33? One way is to do 9999k to go to the top of the file and 32j to go down thirty-two lines. It is not a good way, but it works, A much better way of doing things is to use the G command. With a count, this command positions you at the given line number. For example, 33G puts you on line 33. (For a better way of going through a compiler’s error list, see usr_30.txt, for information on the :make command.)
With no argument, G positions you at the end of the file. A quick way to go to the start of a file use gg. 1G will do the same, but is a tiny bit more typing.
| first line of a file ^
| text text text text |
| text text text text | gg
7G | text text text text |
| text text text text
| text text text text
V text text text text |
text text text text | G
text text text text |
last line of a file V
Another way to move to a line is using the % command with a count. For example 50% moves you to halfway the file. 90% goes to near the end.
The previous assumes that you want to move to a line in the file, no matter if it’s currently visible or not. What if you want to move to one of the lines you can see? This figure shows the three commands you can use:
+---------------------------+
H --> | text sample text |
| sample text |
| text sample text |
| sample text |
M --> | text sample text |
| sample text |
| text sample text |
| sample text |
L --> | text sample text |
+---------------------------+
HintsL H stands for Home, M for Middle and L for Last. Alternatively, H for high, M for Middle and L for low.
03.6 Telling where you are
To see where you are in a file, there are three ways:
- Use the
CTRL-Gcommand. You get a message like this (assuming theruleroption is off):
"usr_03.txt" line 233 of 650 --35%-- col 45-52
This shows the same of the file you are editing, the line number where the cursor is, the total number of lines, the percentage of the way through the file and the column of the cursor.
Sometimes you will see a split column number. For example, col 2-9. This indicates that the cursor is positioned on the second character, but because character one is a tab, occupying eight spaces worth of columns, the screen column is 9.
- Set the
numberoption. This will display a line number in front of every line:
:set number
:set nu
To switch this off again:
:set nonumber
:set nonu
Since number is a boolean option, prepending no to its names has the effect of switching it off. A boolean option has only these two values, it is either on or off.
Vim has many options. Besides the boolean ones there are options with a numerical value and string options. You will see examples of this where they are used.
- Set the
ruleroption. This will display the cursor position in the lower right corner of the Vim window:
:set ruler
Using the ruler option has the advantage that it doesn’t take much room, thus there is more space for your text.
03.7 Scrolling around
The CTRL-U command scrolls down half a screen of text. Think of looking through a viewing window at the text and moving this window up by half the height of the window. Thus the window moves up over the text, which is backward in the file. Don’t worry if you have a little trouble remembering which end is up. Most users have the same problem.
The CTRL_D command moves the viewing window down half a screen in the file, thus scrolls the text up half a screen.
+----------------+
| some text |
| some text |
| some text |
+---------------+ | some text |
| some text | CTRL-U --> | |
| | | 123456 |
| 123456 | +----------------+
| 7890 |
| | +----------------+
| example | CTRL-D --> | 7890 |
+---------------+ | |
| example |
| example |
| example |
| example |
+----------------+
To scroll one line at a time use CTRL-E (scroll up) and CTRL-Y (scroll down).
Think of CTRL-E to give you one line Extra. (If you use MS-Windows compatible key mappings CTRL-Y will redo a change instead of scroll.)
To scroll forward by a whole screen (except for two lines) use CTRL-F. To scroll backwards, use CTRL-B. These should be easy to remember: F for forwards and B for Backwards.
A common issue is that after moving down many lines with j your cursor is at the bottom of the screen. You would like to see the context of the line with the cursor. That’s done with the zz command.
+------------------+ +------------------+
| earlier text | | earlier text |
| earlier text | | earlier text |
| earlier text | | earlier text |
| earlier text | zz --> | line with cursor |
| earlier text | | later text |
| earlier text | | later text |
| line with cursor | | later text |
+------------------+ +------------------+
The ztcommand put the cursor line at the top, zb at the bottom. There are a few more scrolling commands, see Q_sc. To always keep a few lines of context around the cursor, use the scrolloff option.
03.8 Simple searches
To search for a string, use the /string command. To find the word include, for example, use the command:
/include
You will notice that when you type the / the cursor jumps to the last line of the Vim window, like with colon commands. That is where you type the word. You can press the backspace key (backarrow or <BS>) to make corrections. Use the <Left> and <Right> cursor keys when necessary.
Pressing <Enter> executes the command.
Note:
The characters .*[]^%/\?~$ have special meanings. If you want to use them in a search you must put a \ in front of them. See below.
To find the next occurrence of the same string use the n command. Use this to find the first #include after the cursor:
/#include
And then type n several times. You will move to each #include in the text.
You can also use a count if you know which match you want. Thus 3n finds the third match. You can also use a count with /: 4/the goes to the fourth match of the.
The ? command works like / but searches backwards:
?word
The N command repeats the last search the opposite direction. Thus using N after a / command searches backwards, using N after ? searches forwards.
IGNORING CASE
Normally you have to type exactly what you want to find. If you don’t care about upper or lowercase in a word, set the ignorecase option:
:set ignorecase
If you now search for word, it will also match Word and WORD. To match case again:
:set noignorecase
HISTORY
Suppose you do three searches:
/one
/two
/three
Now let’s start searching by typing a simple / without pressing <Enter>. If you press <Up> (the cursor key), Vim puts /three on the command line. Pressing <Enter> at this point searches for three. If you do not press <Enter>, but press <Up> instead, Vim changes the prompt to /two. Another press of <Up> moves you to /one.
You can also use the <Down> cursor key to move through the history of search commands in the other direction.
If you know what a previously used pattern starts with, and you want to use it again, type that character before pressing <Up>. With the previous example, you can type /o<Up> and Vim will put /one on the command line.
The commands starting with : also have a history. That allows you to recall a previous command and execute it again. These two histories are separate.
SEARCHING FOR A WORD IN THE TEXT
Suppose you see the word TheLongFunctionName in the text and you want to find the next occurrence of it. You could type /TheLongFunctionName, but that’s a lot of typing. And when you make a mistake Vim won’t find it.
There is an easier way: Position the cursor on the word and use the * command. Vim will grab the word under the cursor and use it as the search string.
The # command does the same in the other direction. You can prepend a count: 3* searches for the third occurrence of the word under the cursor.
SEARCHING FOR WHOLE WORDS
If you type /the it will also match there. To only find words that end in the use:
/the\>
The \> item is a special marker that only matches at the end of a word.
Similarly \< only matches at the begining of a word. Thus to search for the word the only:
/\<the\>
This does not match there or soothe. Notice that the * and # commands use these start-of-word and end-of-word markers to only find whole words (you can use g* and g# to match partial words).
HIGHLIGHTING MATCHES
While editing a program you see a variable called nr. You want to check where it’s used. You could move the cursor to nr and use the * command and press n to go along all the matches.
There is another way. Type this command:
:set hlsearch
If you now search for nr, Vim will highlight all matches. That is a very good way to see where the variable is used, without the need to type commands.
To switch this off:
:set nohlsearch
Then you need to switch it on again if you want to use it for the next search command. If you only want to remove the highlighting, use this command:
:nohlsearch
This doesn’t reset the option. Instead, it disables the highlighting. As soon as you execute a search command, the highlighting will be used again. Also for the n and N commands.
TUNING SEARCHES
There are a few options that change how searching works. These are the essential ones:
:set incsearch
This makes Vim display the match for the string while you are still typing it. Use this to check if the right match will be found. Then press <Enter> to really jump to that location. Or type more to change the search string.
:set nowrapscan
This stops the search at the end of the file. Or, when you are searching backwards, it stops the search at the start of the file. The wrapscan option is on by default, thus searching wraps around the end of the file.
INTERMZZO
If you like one of the options mentioned before, and set it each time you use Vim, you can put the command in your Vim startup file.
Edit the file, as mentioned at not-compatible. Or use this command to find out where it is:
:scriptnames
Edit the file, for example with:
:edit ~/.vimrc
Then add a line with the command to set the option, just like you typed it in Vim. Example:
Go:set hlsearch<Esc>
G Moves to the end of the file. o starts a new line, where you type the :set command. You end insert mode with <Esc>. Then write and close the file:
ZZ
If you now start Vim again, the hlsearch option will already be set.
03.9 Simple search patterns
The Vim editor uses regular expressions to specify what to search for.
Regular expressions are an extremely powerful and compact way to specify a search pattern. Unfortunately, this power comes at a price, because regular expressions are a bit tricky to specify.
In this section we mention only a few essential ones. More about search patterns and commands can be found in chapter 27 usr_27.txt. You can find the full explanation here: pattern
BEGINING AND END OF A LINE
The ^ character matches the begining of a line. On an English-US keyboard you find it above the 6. The pattern include matches the word include anywhere on the line. But the pattern ^include matches the word include only if it is at the begining of a line.
The $ character matches the end of a line. Therefore, was$ matches the word was only if it is at the end of a line.
Let’s mark the places where /the matches in this example line with xs:
the solder holding one of the chips melted and the
xxx xxx xxx
Using /the$ we find this match:
the solder holding one of the chips melted and the
xxx
And with /^the we find this one:
the solder holding one of the chips melted and the
xxx
You can try searching with /^the$; it will only match a single line consisting entirely of the. White space does matter here, thus if a line contains a space after the word, like the , the pattern will not match.
MATCHING ANY SINGLE CHARACTER
The . (dot) character matches any existing character. For example, the pattern c.m matches a string whose first character is a c, whose second character is anything, and whose third character is m. Example:
We use a computer that became the cummin winter.
xxx xxx xxx
MATCHING SPECIAL CHARACTERS
If you really want to match a dot, you must avoid its special meaning by putting a backslash before it.
If you search for ter., you will find these matches:
We use a computer that became the cummin winter.
xxxx xxxx
Searching for ter\. only finds the second match.
03.10 Using marks
When you make a jump to a position with the G command, Vim remembers the position from before this jump. This position is called a mark. To go back where you came from, use this command:
``
This ` is a backtick or open single-quote character.
If you use the same command a second time you will jump back again. That’s because the ` command is a jump itself, and the position from before this jump is remembered.
Generally, every time you do a command that can move the cursor further than within the same line, this is called a jump. This includes the search commands / and n (it doesn’t matter how far away the match is). But not the character searches with fx and tx or the word movements w and e.
Also, j and k are not considered to be a jump, even when you use a count to make them move the cursor quite a long way away.
The `` command jumps back and forth, between two points. The CTRL-O command jumps to older positions (Hint: O for older). CTRL-I then jumps back to newer positions (Hint: for many common keyboard layouts, I is just next to O).Consider this sequence of commands:
33G
/^The
CTRL-O
You first jump to line 33, then search for a line that starts with The.Then with CTRL-O you jump back to line 33. Another CTRL-O takes you back to where you started. If you now use CTRL-I you jump to line 33 again. And to the match for The with another CTRL-I.
| example text ^ |
33G | example text | CTRL-O | CTRL-I
| example text | |
V line 33 text ^ V
| example text | |
/^The | example text | CTRL-O | CTRL-I
V There you are | V
example text
Note:
CTRL-I is the same as <Tab>.
The :jumps command givesa list of positions you jumped to. The entry which you used last is marked with a >.
NAMED MARKS
Vim enables you to place your own marks in the text. The command ma marks the place under the cursor as mark a. You can place 26 marks (a through z) in your text. You can’t see them, it’s just a position that Vim remembers.
To go to a mark, use the command `{mark}, where {mark} is the mark letter. Thus to move to the a mark:
`a
The command ’mark (single quotation mark, or apostrophe) moves you to the begining of the line containing the mark. This differs from the `mark command, which also moves you to the marked column.
The marks can be very useful when working on two related parts in a file. Suppose you have some text near the start of the file you need to look at, while working on some text near the end of the file.
Move to the text at the start and place the s (start) mark there:
ms
Then move to the text you want to work on and put the e (end) mark there:
me
Now you can move around, and when you want to look at the start of the file, you use this to jump there:
's
Then you can use ‘’ to jump back to where you were, or ’e to jump to the text you were working on at the end.
There is nothing special about using s for start and e for end, they are just easy to remember.
You can use this command to get a list of marks:
:marks
You will notice a few special marks. These include:
' The cursor position before doing a jump
" The cursor position when last editing the file
[ Start of the last change
] End of the last change
usr_04 Making small changes
:help usr_04
This chapter shows you several ways of making corrections and moving text around. It teaches you the three basic ways to change text: operator-motion,Visual mode and text objects.
- 04.1 Operators and motions
- 04.2 Changing text
- 04.3 Repeating a change
- 04.4 Visual mode
- 04.5 Moving text
- 04.6 Copying text
- 04.7 Using the clipboard
- 04.8 Text objects
- 04.9 Replace mode
- 04.10 Conclusion
04.1 Operators and motions
In chapter 2 you learned the x command to delete a single character. And using a count: 4x deletes four characters.
The dw command deletes a word. You may recongnize the w command as the move word command. In fact, the d command may be followed by any motion command, and it deletes from the current location to the place where the cursor winds up.
The 4w command, for example, moves the cursor over four words. The d4w command deletes four words.
To err is human. To really foul up you need a computer.
------------------>
d4w
To err is human. you need a computer.
Vim only deletes up to the position where the motion takes the cursor. That’s because Vim knows that you probably don’t want to delete the first character of a word. if you use the e command to move to the end of a word, Vim guesses that you do want to include that last character:
To err is human. you need a computer.
-------->
d2e
To err is human. a computer.
Whether the character under the cursor is include depends on the command you used to move to that character. The reference manual calls this exclusive when the character isn’t included and inclusive when it is.
The $ command moves to the end of a line. The d$ command deletes from the cursor to the end of the line. This is an inclusive motion, thus the last character of the line is included in the delete operation:
To err is human. a computer.
------------>
d$
To err is human
There is a pattern here: operator-motion. You first type an operator command. For example, d is the delete operator. Then you type a motion command like 4l or w. This way you can operate on any text you can move over.
04.2 Changing text
Another operator is c, change. It acts just like the d operator, except it leaves you in Insert mode. For example, cw changes a word. Or more specifically , it deletes a word and then puts you in Insert mode.
To err is human
------->
c2wbe<Esc>
To be human
This c2wbe<Esc> contains these bits:
c the change operator
2w move two words (they are deleted and Insert mode started)
be insert this text
<Esc> back to Normal mode
You will have noticed something strange: The space before human isn’t deleted. There is a saying that for every problem there is an answer that is simple, clear, and wrong. that is the case with the example used here for the cw command. The c operator works just like the d operator, with one exception: cw. It actually works like ce, change to end of word. Thus the space after the word isn’t included. This is an exception that dates back to the old Vi. Since many people are used to it now, the inconsisrency has remained in Vim.
MORE CHANGES
Like dd deletes a whole line, cc changes a whole line. It keeps the existing indent (leading white space) though.
Just like d$ deletes until the end of the line, c$ changes until the end of the line. It’s like doing d$ to delete the text and then a to start Insert mode and append new text.
SHORTCUTS
Some operator-motion commands are used so often that they have been given a single-letter command:
x stands for dl (delete character under the cursor)
X stands for dh (delete character left of the cursor)
D stands for d$ (delete to end of the line)
C stands for c$ (change to end of the line)
s stands for cl (change one character)
S stands for cc (change a whole line)
WHERE TO PUT THE COUNT
The commands 3dw and d3w delete three words. If you want to get really pickly about things, the first command, 3dw, deletes one word three times; the command d3w deletes three words once. This is a difference without a distinction. You can actually put in two counts, however. For example, 3d2w deletes two words, repeated three times, for a total of six words.
REPLACING WITH ONE CHARACTER
The r command is not an operator. It waits for you to type a character, and will replace the character under the cursor with it. You could do the same with cl or with the s command, but with r you don’t have to press <Esc> to get back out of insert mode.
there is somerhing grong here
rT rt rw
There is something wrong here
Using a count with r causes that many characters to be replaced with the same character. Example:
There is something wrong here
5rx
There is something xxxxx here
To replace a character with a line break use r<Enter>. This deletes one character and inserts a line break. Using a count here only applies to the number of characters deleted: 4r<Enter> replaces four characters with one line break.
04.3 Repeating a change
The . command is one of the simplest yet powerful commands in Vim. It repeats the last change. For instance, suppose you are editing an HTML file and want to delete all the <B> tags. You position the cursor on the first < and delete the <B> with the command df>. You then go to the < of the next </B> and delete it using the . command. The . command executes the last change command (in this case, df>). To delete another tag, position the cursor on the < and use the . command.
To <B>generate</B> a table of <B>contents
f< find first < --->
df> delete to > -->
f< find next < --------->
. repeat df> --->
f< find next < ------------->
. repeat df> -->
The . command works for all changes you make, except for u (undo), CTRL-R (redo) and commands that start with a colon (:).
Another example: You want to change the word four to five. It appears several times in your text. You can do this quickly with this sequence of commands:
/four<Enter> find the first string "four"
cwfive<Esc> change the word to "five"
n find the next "four"
. repeat the change to "five"
n find the next "four"
. repeat the change
etc.
04.4 Visual mode
To delete simple items the operator-motion changes work quite well. But often it’s not so easy to decide which command will move over the text you want to change. Then you can use Visual mode.
You start Visual mode by pressing v. You move the cursor over the text you want to work on. While you do this, the text is highlighted. Finally type the operator command.
For example, to delete from the middle of one word to the middle of another word:
This is an examination sample of visual mode
---------->
velllld
This is an example of visual mode
When doing this you don’t really have to count how many times you have to press l to end up in the right position. You can immediately see what text will be deleted when you press d.
If at any time you decide you don’t want to do anything with the highlighted text, just press <Esc> and Visual mode will stop without doing anything.
SELECTING LINES
If you want to work on whole lines, use V to start Visual mode. You will see right away that the whole line is highlighted, without moving around.When you move left or right nothing changes. When you move up or down the selection is extended whole lines at a time.
For example, select three lines with Vjj:
+------------------------+
| text more text |
>> | more text more text | |
selected lines >> | text text text | | Vjj
>> | text more | V
| more text more |
+------------------------+
SELECTING BLOCKS
If you want to work on a rectangular block of characters, use CTRL-V (:visual block or :vb)to start Visual mode. This is very useful when working on tables.
name Q1 Q2 Q3
pierre 123 455 234
john 0 90 39
steve 392 63 334
To delete the middle Q2 column, move the cursor to the Q of Q2. Press CTRL-V to start blockwise Visual mode. Now move the cursor three lines down with 3j and to the next word with w. You can see the first character of the last column is included. To exclude it, use h. Now press d and the middle column is gone.
GOING TO THE OTHER SIDE
If you have selected some text in Visual mode, and discover that you need to change the other end of the selection, use the o command (Hint: o for other end). The cursor will go to the other end, and you can move the cursor to change where the selection starts. Pressing o again brings you back to the other end.
When using blockwise selection, you have four corners. o only takes you to one of the other corners, diagonally. Use O to move to the other corner in the same line.
Note that o and O in Visual mode work very differently from Normal mode, where they open a new line below or above the cursor.
04.5 Moving text
When you delete something with d, x, or another command, the text is saved. You can paste it back by using the p command. (The Vim name for this is put).
Take a look at how this works. First you will delete an entire line, by putting the cursor on the line you want to delete and typing dd. Now you move the cursor to where you want to put the line and use the p (put) command. The line is inserted on the line below the cursor.
a line a line a line
line 2 dd line 3 p line 3
line 3 line 2
Because you deleted an entire line, the p command placed the text line below the cursor. If you delete part of a line (a word,for instance), the p command puts it just after the cursor.
Some more boring try text to out commands.
---->
dw
Some more boring text to out commands.
------->
welp
Some more boring text to try out commands.
MORE ON PUTTING
The P command puts text line p, but before the cursor. When you deleted a whole line with dd, P will put it back above the cursor. When you deleted a word with dw, P will put it back just before the cursor.
You can repeat putting as many times as you like. The same text will be used.
You can use a count with p and P. The text will be repeated as many times as specified with the count. Thus dd and then 3p puts three copies of the same deleted line.
SWAPPING TWO CHARACTERS
Frequently when you are typing, you fingers get ahead of your brain (or the other way around?). The result is a type such as teh for the. Vim makes it easy to correct such problems. Just put the cursor on the e of teh and execute the command xp. This works as follows: x deletes the character e and places it in a register. p puts the text after the cursor, which is after the h.
teh th the
x p
04.6 Copying text
To copy text from one place to another, you could delete it, use u to undo the deletion and then p to put it somewhere else. There is an easier way: yanking. The y operator copies text into a register. Then a p command can be used to put it.
Yanking is just a Vim name for copying. The c letter was already used for the change operator, and y was still available. Calling this operator yank made it easier to temember to use the y key.
Since y is an operator, you use yw to yank a word. A count is possible as usual. To yank two words use y2w. Example:
let sqr = LongVariable *
-------------->
y2w
let sqr = LongVariable *
p
let sqr = LongVariable * LongVariable
Notice that yw includes the white space after a word. If you don’t want this, use ye.
The yy command yanks a whole line, just like dd deletes a whole line. Unexpectedly, while D deletes from the cursor to the end of the line, Y works like yy, it yanks the whole line. Watch out for this inconsistency! Use y$ to yank to the end of the line.
a text line yy a text line a text line
line 2 line 2 p line 2
last line last line a text line
last line
04.7 Using the clipboard
If you are using the GUI version of Vim (gvim), you can find the Copy item in the Edit menu. First select some text with Visual mode, then use the Edit/Copy menu item. The selected text is now copied to the clipboard. You can paste the text in other programs. In Vim itself too.
If you have copied text to the clipboard in another application, you can paste it in Vim with the Edit/Paste menu item. This works in Normal mode and Insert mode. In Visual mode the selected text is replaced with the pasted text.
The Cut menu item deletes the text before it’s put on thr clipboard. The Copy, Cut and Paste items are also avaiable in the popup menu (only where there is a popup menu, of course). If your Vim has a toobar, you can also find these items there.
If you are not using the GUI, or if you don’t like using a menu, you have to use another way. You use the normal y (yank) and p (put) commands, but prepend "* (double-quote star) before it. To copy a line to the clipboard:
"*yy
To put text from the clipboard back into the text:
"*p
This only morks on versions of Vim that include clipboard support. More about the clipboard can be found in section 09.3 and here: clipboard
04.8 Text objects
If the cursor is in the middle of a word and you want to delete that word, you need to move back to its start before you can do dw. There is a simpler way to do this: daw.
this is some example text.
daw
this is some text.
The d of daw is the delete operator. aw is a text object. Hint: aw stands for A Word. Thus daw is Delete A Word. To be precise, the white space after the word is also deleted (or the white space before the word if at the end of the line).
Using text objects is the third way to make changes in Vim. We already had operator-motion and Visual mode. Now we add operator-text object.
It is very similar to operator-motion, but instead of operating on the text between the cursor position before and after a movement command, the text object is used as a whole. It doesn’t matter where in the object the cursor was.
To change a whole sentence use cis. Take this text:
Hello there. This
is an example. Just
some text.
Move to the start of the second line, on is an. Now use cis:
Hello there. Just
some text.
The cursor is in between the blanks in the first line. Now you type the new sentence Another line.:
Hello there. Another line. Just
some text.
cis consists of the c (change) operator and the is text object. This stands for Inner Sentence. There is also the as (A Sentence) object. The difference is that as includes the white space after the sentence and is doesn’t. If you would delete a sentence, you want to delete the white space at the same time, thus use das. If you want to type new text the white space can remain, thus you use cis.
You can also use text objects in Visual mode. It will include the text object in the Visual selection. Visual mode continues, thus you can do this several times. For example, start Visual mode with v and select a sentence with as. Now you can repeat as to include more sentences. Finally you use an operator to do something with the selected sentences.
You can find a long list of text objects here: text-objects
04.9 Replace mode
The R command causes Vim to enter replace mode. In this mode, each character you type replaces the one under the cursor. This continues until you type <Esc>.
In this example you start Replace mode on the first t of text:
This is text.
Rinteresting.<Esc>
This is interesting.
You may have noticed that this command replaced 5 characters in the line with twelve others. The R command automatically extends the line if it runs out of characters to replace. It will not continue on the next line.
You can switch between Insert mode and Replace mode with the <Insert> key.
When you use <BS> (backspace) to make a correction, you will notice that the old text is put back. Thus it works like an undo command for the previously typed character.
04.10 Conclusion
The operators, movement commands and text objects give you the possibility to make lots of combinations. Now that you know how they mork, you can use N operators with M movement commands to make N * M commands!
You can find a list of operators here: operator.
For example, there are many other ways to delete pieces of text. Here are a few common ones:
x delete character under the cursor (short for "dl")
X delete character before the cursor (short for "dh")
D delete from cursor to end of line (short for "d$")
dw delete from cursor to next start of word
db delete from cursor to previous start of word
diw delete word under the cursor (excluding white space)
daw delete word under the cursor (including white space)
dG delete until the end of the file
dgg delete until the start of the file
If you use c instead of d they become change commands. And with y you yank the text. And so forth.
There are a few common commands to make changes that didn’t fit somewhere else:
~ Change case of the character under the cursor, and move the
cursor to the next character. This is not an operator (unless 'tildeop' is set),
thus you can't use it with a motion command.
It does work in Visual mode, where it changes case for all the selected text.
I Start Insert mode after moving the cursor to the first
non-blank in the line.
A Start Insert mode after moving the cursor to the end of the
line.
usr_05 Set your settings
:help usr_05
Vim can be tuned to work like you want it to. This chapter shows you how to make Vim start with options set to different values. Add pligins to extend Vim’s capabilities. Or define your own macros.
- 05.1 The vimrc file
- 05.2 The example vimrc file explained
- 05.3 The defaults.vim file explained
- 05.4 Simple mappings
- 05.5 Adding a package
- 05.6 Adding a plugin
- 05.7 Adding a help file
- 05.8 The option window
- 05.9 Often used options
05.1 The vimrc file
vimrc intro
You probably got tired of typing commands that you use very often. To start Vim with all your favorite option settings and mappings, you write them in what is called the vimrc file. Vim executes the commands in this file when it starts up.
If you already have a vimrc file (e.g., when your sysadmin has one setup for you), you can edit it this way:
:edit $MYVIMRC
If you don’t have a vimrc file yet, see vimrc to find out where you can create a vimrc file. Also, the :version command mentions the name of the *user vimrc file Vim looks for.
For Unix and Macintosh this file is always used and is recommended:
~/.vimrc
For MS-Windows you can use one of these:
$HOME/_vimrc
$VIM/_vimrc
If you are creating the vimrc file for the first time, it is recommended to put this line at the top:
source $VIMRUNTIME/defaults.vim
This initializes Vim for new users (as opposed to traditional Vi users). See defaults.vim for the details.
The vimrc file can contain all the commands that you type after a colon. The simplest ones are for setting options. For example, if you want Vim to always start with the incsearch option on, add this line your vimrc file:
set incsearch
For this new line to take effect you need to exit Vim and start it again. Later you will learn how to do this without exiting Vim.
This chapter only explains the most basic items. For more information on how to write a Vim script file: usr_41.txt.
05.2 The example vimrc file explained
vimrc_example.vim
In the first chapter was explained how the example vimrc (include in the Vim distribution) file can be used to make Vim startup in not-compatible mode (see not-compatible). The file can be found here:
$VIMRUNTIME/vimrc_example.vim
In this section we will explain the various commands used in this file. This will give you hints about how to set up your own preferences. Not everything will be explained though. Use the :help command to find out more.
" Get the defaults that most users want.
source $VIMRUNTIME/defaults.vim
This loads the defaults.vim file in the $VIMRUNTIME directory. This sets up Vim for how most users like it. If you are one of the few that don’t, then comment out this line. The commands are explained below:
defaults.vim-explained
if has("vms")
set nobackup
else
set backup
if has('persistent_undo')
set undofile
endif
endif
This tells Vim to keep a backup copy of a file when overwriting it. But not on the VMS system, since it keeps old versions of files already. The backup file will have the same name as the original file with ~ added. See 07.4
This also sets the undofile option, if available. This will store the multi-level undo information in a file. The result is that when you change a file, exit Vim, and then edit the file again, you can undo the changes made previously. It’s a very powerful and useful feature, at the cost of storing a file. For more information see undo-persistence.
The if command is very useful to set options<bt>
only when some condition is met. More about that in use_41.txt.
if &t_Co > 2 || has("gui_running")
set hlsearch
endif
This switches on the hlsearch option, telling Vim to highlight matches with the last used search pattern.
augroup vimrcEx
au!
autocmd FileType text setlocal textwidth=78
augroup END
This makes Vim break text to avoid lines getting longer than 78 characters. But only for files that have been detected to be plain text. There are actually two parts here. autocmd FileType text is an autocommand. This defines that when the file type is set to text the following command is automatically executed. setlocal textwidth=78 sets the textwidth option to 78, but only locally in one file.
The wrapper with augroup vimrcEx and augroup END makes it possible to delete the autocommand with the au! command. See :augroup
if has('syntax') && has('eval')
packadd! matchit
endif
This loads the matchit plugin if the required features are available. It makes the % command more powerful. This is explained at matchit-install
05.3 The default.vim file explained
defaults.vim-explained
The defaults.vim file is loaded when the user has no vimrc file. When you create a new vimrc file, add this line near the top to keep using it:
source $VIMRUNTIME/defaults.vim
Or use the vimrc_example.vim file, as explained above.
The following explains what defaults.vim is doing.
if exists('skip_defaults_vim')
finish
endif
Loading defaults.vim can be disabled with this command:
let skip_defaults_vim = 1
This has to be done in the system vimrc file. See system-vimrc. If you have a user vimrc this is not needed, since defaults.vim will not be loaded automatically.
set nocompatible
As mentioned in the first chapter, these manuals explain Vim working in an improved way, thus not completely Vi compatible. Setting the compatible option off, thus nocompatible takes care of this.
set backspace=indent,eol,start
This specifies where in Insert mode the <BS> is allowed to delete the character in front of the cursor. The three items, separated bt commas, tell Vim to delete the white space at the start of the line, a line break and the character before where Insert mode started. See backspace.
set history=200
Keep 200 commands and 200 search patterns in the history. Use another number if you want to remember fewer or more lines. See history.
set ruler
Always display the current cursor position in the lower right corner of the Vim window. See ruler.
set showcmd
Display an incomplete command in the lower right corner of the Vim window, left of the ruler. For example, when you type 2f, Vim is waiting for you to type the character to find and 2f is displayed. When you press w next, the 2fw command is executed and the displayed 2f is removed.
+-------------------------------------------------+
|text in the Vim window |
|~ |
|~ |
|-- VISUAL -- 2f 43,8 17% |
+-------------------------------------------------+
^^^^^^^^^^^ ^^^^^^^^ ^^^^^^^^^^
'showmode' 'showcmd' 'ruler'
set wildmenu
Display completion matches in a status line. That is when you type <Tab> and there is more than one match. See wildmenu.
set ttimeout
set ttimeoutlen=100
This makes typing Esc take effect more quickly. Normally Vim waits a second to see if the Esc is the start of an escape sequence. If you have a very slow remote connection, increase the number. See ttimeout.
set display=truncate
Show @@@ in the last line if it is truncted, instead of hiding the whole line. See dispaly.
set incsearch
Display the match for a search pattern when halfway typing it. See incsearch
set nrformats-=octal
Do not recognize numbers starting with a zero as octal. See nrformats.
map Q gq
This defines a key mapping. More about that in the next section. This defines the Q command to do formatting with the gq operator. This is how it worked before Vim 5.0. Otherwise the Q command starts Ex mode, but you will not need it.
inoremap <C-U> <C-G>u<C-U>
CTRL-U in insert mode deletes all entered text in the current line. Use CTRL-G u to first break undo, so that you can undo CTRL-U after inserting a line break. Revert with :iunmap <C-U>.
if has('mouse')
set mouse=a
endif
Enable using the mouse if avaiable. See mouse.
vnoremap _g y:exe "grep /" .. escape(@", '\\/') .. "/ *.c *.h"<CR>
This mapping yanks the visually selected text and searches for it in C files. You can see that a mapping can be used to do quite complicated things. Still, it is just a sequence of commands that are executed like you typed them.
syntax on
Enable highlighting files in color. See syntax.
vimrc-filetype
filetype plugin indent on
This switches on three very clever mechanisms:
- Filetype detecition.
Whenever you start editing a file, Vim will try to figure out what kind of file this is. When you edit main.c, Vim will see the.cextension and recognize this as a c filetype. When you edit a file that starts with#!/bin/sh, Vim will recognize it as a sh filetype.
The filetype detection is used for syntax highlighting and the other two items below.
See filetype. - Using filetype plugin files
Many different filetypes are edited with different options. For example, when you edit a c file, it’s very useful to set the cindent option to automatically indent the lines. These commonly useful option settings are included with Vim in filetype plugins. You can also add your own, see write-filetype-plugin. - Using indent files
When editing programs, the indent of a line can often be computed automatically. Vim comes with these indent rules for a number of filetypes. See :filetype-indent-on and indentexpr.
restore-cursor last-position-jump
autocmd BufReadPost *
\ if line("'\"") >= 1 && line("'\"") <= line("$") && &ft !~# 'commit'
\ | exe "normal! g`\""
\ | endif
Another autocommand. This time it is used after reading any file. The complicated stuff after it checks if the '" mark is defined, and jumps to it if so. The backslash at the start of a line is used to continue the command from the previous line. That avoids a line getting very long.
See line-continuation. This only works in a Vim script file, not when typing commands at the command-line.
command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis
\ | wincmd p | diffthis
This adds the :DiffOrig command. Use this in a modified buffer to see the differences with the file it was loaded from. See diff and :DiffOrig.
set nolangremap
Prevent that the langmap option applies to characters that result from a mapping. If set (default), this may break plugins (but it’s backward compatible). See langremap.
05.4 Simple mappings
A mapping enables you to bind a set of Vim commands to a single key. Suppose, for example, that you need to surround certain words with curly braces. In other words, you need to change a word such as amount into {amount}. With the :map command, you can tell Vim that the F5 key does this job. The command is as follows:
:map <F5> i{<Esc>ea}<Esc>
Note:
When entering this command, you must enter <F5> by typing four characters. Similarly, <Esc> is not entered by pressing the <Esc> key, but by typing five characters. Watch out for this difference when reading the manual!
Let’s break this down:
<F5> The F5 function key. This is the trigger key that causes the
command to be executed as the key is pressed.
i{<Esc> Insert the { character. The <Esc> key ends Insert mode.
e Move to the end of the word.
a}<Esc> Append the } to the word.
After you execute the :map command, all you have to do to put {} around a word is to put the cursor on the first character and press F5.
In this example, the tirgger is a single key; it can be any string. But when you use an existing Vim command, that command will no longer be available.You better avoid that.
One key that can be used with mappings is the backslash. Since you probably want to define more than one mapping, add another character. You could map \p to add parentheses around a word, and \c to add curly braces, for example:
:map \p i(<Esc>ea)<Esc>
:map \c i{<Esc>ea}<Esc>
You need to type \ and the p quickly after another, so that Vim knows they belong together.
The :map command (with no arguments) lists your current mappings. At least the ones for Normal mode. More about mappings in section 40.1.
05.5 Adding a package
add-package matchit-install
A package is a set of files that you can add to Vim. There are two kinds of packages: optional and automatically loaded on startup.
The Vim distribution comes with a few packages that you can optionally use. For example, the matchit plugin. This plugin makes the % command jump to matching HTML tags, if/else/endif in Vim scripts, etc. Very useful, although it’s not backwards compatible (that’s why it is not enabled by default).
To start using the matchit plugin, add one line to your vimrc file:
packadd! matchit
That’s all! After restarting Vim you can find help about this plugin:
:help matchit
This works, because when :packadd loaded the plugin it also added the package directory in runtimepath, so that the help file can be found.
You can find packages on the Internet in various places. It usually comes as an archive or as a repository. For an archive you can follow these steps:
1. create the package directory:
mkdir -p ~/.vim/pack/fancy
"fancy" can be any name of your liking. Use one that describes the package.
2. unpack the archive in that directory. This assumes the top directory in the archive is "start":
cd ~/.vim/pack/fancy
unzip /tmp/fancy.zip
If the archive layout is different make sure that you end up with a path like this:
~/.vim/pack/fancy/start/fancytext/plugin/fancy.vim
Here "fancytext" is the name of the package, it can be anything else.
Note:
MS-Windows path like this ~\vimfiles\pack\fancy\start\fancytext\plugin\fancy.vim
More information about packages can be found here: packages
05.6 Adding a plugin
add-plugin plugin
Vim’s functionally can be extended by adding plugins. A plugin is nothing more than a Vim script file that is loaded automatically when Vim starts. You can add a plugin very easily by dropping it in your plugin directory. {not available when Vim was compiled without the +eval feature}
There are two types of plugins:
- global plugin: Used for all kinds of files
- filetype plugin: Only used for a specific type of file
The global plugins will be discussed first, then the filetype ones add-filetype-plugin
GLOBAL PLUGINS
######## standard-plugin
When you start Vim, it will automatically load a number of global plugins. You don’t have to do anything for this. They add functionality that most people will want to use, but which was implemented as a Vim script instead of being compiled into Vim. You can find them listed in the help index standard-plugins-list. Also see load-plugins.
######## add-global-plugin
You can add a global plugin to add functionality that will always be present when you use Vim. There are only two steps for adding a global plugin:
- Get a copy of the plugin.
- Drop it in the right directory.
GETTING A GLOBAL PLUGIN
Where can you find plugins?
- Some are always loaded, you can see them in the directory $VIMRUNTIME/plugin.
- Some come with Vim. You can find them in the directory $VIMRUNTIME/macros and its sub-directories and under $VIM/vimfiles/pack/dist/opt/.
- Download from the net. There is a large collection on http://www.vim.org.
- They are sometimes posted in a Vim maillist.
- You could write one yourself, see write-plugin.
Some plugins come as a vimball archive, see vimball.
Some plugins can be updated automatically, see getscript.
USING A GLOBAL PLUGIN
First read the text in the plugin itself to check for any special conditions. Then copy the file to your plugin directory:
| system | plugin directory |
|---|---|
| Unix | ~/.vim/plugin |
| PC | $HOME/vimfiles/plugin or $VIM/vimfiles/plugin |
| Amiga | s:vimfiles/plugin |
| Macintosh | $VIM:vimfiles:plugin |
| Mac OS X | ~/.vim/plugin/ |
Example for Unix (assuming you didn’t have a plugin directory yet):
mkdir ~/.vim
mkdir ~/.vim/plugin
cp /tmp/yourplugin.vim ~/.vim/plugin
That’s all! Now you can use the commands defined in this plugin.
Instead of putting plugins directly into the plugin/ directory, you may better organize them by putting them into subdirectories under plugin/. As an example, consider using ~/.vim/plugin/perl/*.vim for all your Perl plugins.
FILETYPE PLUGINS
######## add-filetype-plugin ftplugins
The Vim distribution comes with a set of plugins for different filetypes that you can start using with this command:
:filetype plugin on
That’s all! See vimrc-filetype.
If you are missing a plugin for a filetype you are using, or you found a better one, you can add it. There are two steps for adding a filetype plugin:
- Get a copy of the plugin.
- Drop it in the right directory.
GETTING A FILETYPE PLUGIN
You can find them in the same places as the global plugins. Watch out if the type of file is mentioned, then you know if the plugin is a global or a filetype one. The scripts in $VIMRUNTIME/macros are global ones, the filetype plugins are in $VIMRUNTIME/ftplugin.
USING A FILETYPE PLUGIN
######## ftplugin-name
You can add a filetype plugin by dropping it in the right directory. The name of this directory is in the same directory mentioned above for global plugins, but the last part is ftplugin. Suppose you have found a plugin for the stuff filetype, and you are on Unix. Then you can move this file to the ftplugin directory:
mv thefile ~/.vim/ftplugin/stuff.vim
If that file already exists you already have a plugin for stuff. You might want to check if the existing plugin doesn’t conflict with the one you are adding. If it’s OK, you can give the new one another name:
mv thefile ~/.vim/ftplugin/stuff_too.vim
The underscore is used to separate the name of the filetype from the rest, which can be anything. If you use otherstuff.vim it wouldn’t work, it would be loaded for the otherstuff filetype.
On MS-DOS like filesystems you cannot use long filenames. You would run into trouble if you add a second plugin and the filetype has more than six characters. You can use an extra directory to get around this:
mkdir $VIM/vimfiles/ftplugin/fortran
copy thefile $VIM/vimfiles/ftplugin/fortran/too.vim
The generic names for the filetype plugins are:
ftplugin/<filetype>.vim
ftplugin/<filetype>_<name>.vim
ftplugin/<filetype>/<name>.vim
Here <name> can be any name that you prefer.
Examples for the stuff filetype on Unix:
~/.vim/ftplugin/stuff.vim
~/.vim/ftplugin/stuff_def.vim
~/.vim/ftplugin/stuff/header.vim
The <filetype> part is the name of the filetype the plugin is to be used for. Only files of this filetype will use the settings from the plugin. The <name> part of the plugin file doesn’t matter, you can use it to have several plugins for the same filetype. Note that it must end in .vim.
Further reading:
- filetype-plugins Documentation for the filetype plugins and information about how to avoid that mappings cause problems.
- load-plugins When the global plugins are loaded during startup.
- ftplugin-overrule Overruling the settings from a global plugin.
- write-plugin How to write a plugin script.
- plugin-details For more information about using plugins or when your plugin doesn’t work.
- new-filetype How to detect a new file type.
05.7 Adding a help file
add-local-help
If you are lucky, the plugin you installed also comes with a help file. We will explain how to install the help file, so that you can easily find help for your new plugin.
Let us use the doit.vim plugin as an example. This plugin comes with documentation: doit.txt. Let’s first copy the plugin to the right directory. This time we will do it from inside Vim. (You may skip some of the mkdir commands if you already have the directory.)
:!mkdir ~/.vim
:!mkdir ~/.vim/plugin
:!cp /tmp/doit.vim ~/.vim/plugin
The cp command is for Unix, on MS-Windows you can use copy.
Now create a doc directory in one of the directories in runtimepath.
:!mkdir ~/.vim/doc
Copy the help file to the doc directory.
:!cp /tmp/doit.txt ~/.vim/doc
Now comes the trick, which allows you to jump to the subjects in the new help file: Generate the local tags file with the :helptags command.
:helptags ~/.vim/doc
Now you can use the
:help doit
command to find help for doit in the help file you just added. You can see an entry for the local help file when you do:
:help local-additions
The title lines from the local help files are automagically added to this section. There you can see which local help files have bean added and jump to them through the tag.
For writing a local help file, see write-local-help.
05.8 The option window
If you are looking for an option that does what you want, you can search in the help files here: options. Another way is by using this command:
:options
This opens a new window, with a list of options with a one-line explanation. The options are grouped by subject. Move the cursor to a subject and press <Enter> to jump there. Press <Enter> again to jump back. Or use CTRL-O.
You can change the value of an option. For example, move to the displaying text subject. Then move the cursor down to this line:
set wrap nowrap
When you hit <Enter>, the line will change to:
set nowrap wrap
The option has now been switched off.
Just above this line is a short description of the wrap option. Move the cursor one line up to place it in this line. Now hit <Enter> and you jump to the full help on the wrap option.
For options that take a number or string argument you can edit the value. Then press <Enter> to apply the new value. For example, move the cursor a few lines up to this line:
set so=0
Position the cursor on the zero with $. Change it into a five with r5. Then press <Enter> to apply the new value. When you now move the cursor around you will notice that the text starts scrolling before you reach the border. This is what the scrolloff option does, it specifies an offset from the window border where scrolling starts.
05.9 Often used options
There are an awful lot of options. Most of them you will hardly ever use. Some of the more useful ones will be mentioned here. Don’t forget you can find more help on these options with the :help command, with single quotes before and after the option name. For example:
:help 'wrap'
In case you have messed up an option value, you can set it back to the default by putting an ampersand (&) after the option name. Example:
:set iskeyword&
NOT WRAPPING LINES
Vim normally wraps long lines, so that you can see all of the text. Sometimes it’s better to let the text continue right of the window. Then you need to scroll the text left-right to see all of a long line. Switch wrapping off with this command:
:set nowrap
Vim will automatically scroll the text when you move to text that is not displayed. To see a context of ten characters, do this:
:set sidescroll=10
This doesn’t change the text in the file, only the way it is displayed.
WRAPPING MOVEMENT COMMANDS
Most commands for moving around will stop moving at the start and end of a line. You can change that whit the whichwrap option. This sets it to the default value:
:set whichwrap=b,s
This allows the <BS> key, when used in the first position of a line, to move the cursor to the end of the previous line. And the <Space> key moves from the end of a line to the start of the next one.
To allow the cursor keys <Left> and <Right> to also wrap, use this command:
:set whichwrap=b,s,<,>
This is still only for Normal mode. To let <Left> and <Right> do this in Insert mode as well:
:set whichwrap=b,s,<,>,[,]
There are a few other flags that can be added, see whichwrap
VIEWING TABS
When there are tabs in a file, you cannot see where they are. To make them visible:
:set list
Now every tab is displayed as ^I. And a $ is displayed at the end of each line, so that you can spot trailing spaces that would otherwise go unnoticed.
A disadvantage is that this looks ugly when there are mant Tabs in a file. If you have a color terminal, or are using the GUI, Vim can show the spaces and tabs as highlighted characters. Use the listchars option:
:set listchars=tab:>-,trail:-
Now every tab will be displayed as >--- (with more or less -) and trailing white space as -. Looks a lot better, doesn’t it?
KEYWORDS
The iskeyword option specifies which characters can appear in a word:
:set iskeyword
iskeyword=@,48-57,_,192-255
The @ stands for all alphabetic letters. 48-57 stands for ASCII characters 48 to 57, which are the numbers 0 to 9. 192-255 are the printable latin characters.
Sometimes you will want to include a dash in keywords, so that commands like w consider upper-case to be one word. You can do it like this:
:set iskeyword+=-
:set iskeyword
iskeyword=@,48-57,_,192-255,-
If you look at the new value, you will see that Vim has added a comma for you.
To remove a character use -=. For example, to remove the underscore:
:set iskeyword-=_
:set iskeyword
iskeyword=@,48-57,192-255,-
This time a comma is automatically deleted.
ROOM FOR MESSAGES
When Vim starts there is one line at the bottom that is used for messages. When a message is long, it is either truncated, thus you can only see part of it, or the text scrolls and you have to press <Enter> to continue.
You can set the cmdheight option to the number of lines used for messages. Example:
:set cmdheight=3
This does mean there is less room to edit text, thus it’s a compromise.
usr_06 Using syntax highlighting
:help usr_06
Black and white text is boring. With colors your file comes to life. This not only looks nice, it also speeds up your work. Change the colors used for the different sorts of text. Print your text, with the colors you see on the screen.
- 06.1 Switching it on
- 06.2 No or wrong colors?
- 06.3 Different colors
- 06.4 With colors or without colors
- 06.5 Printing with colors
- 06.6 Further reading
06.1 switching it on
It all starts with one simple command:
:syntax enable
That should work in most situations to get color in your files. Vim will automagically detect the type of file and load the right syntax highlighting. Suddenly comments are blue, keywords brown and string red. This makes it easy to overview the file. After a while you will find that black&white text slows you down!
If you always want to use syntax highlighting, put the :syntax enable command in your vimrc file.
If you always want syntax highlighting only when the terminal supports colors, you can put this in your vimrc file:
if &t_Co > 1
syntax enable
endif
If you want syntax highlighting only in the GUI version, put the :syntax enable command in your gvimrc file.
06.2 No or wrong colors?
There can be a numberof reasons why you don’t see colors:
- You terminal does not support colors.
Vim will use bold, italic and underlined text, but this doesn’t look very nice. You probably will want to try to get a terminal with colors. For Unix, I recommend the xterm from the XFree86 project: xfree-xterm. - Your terminal does support colors, but Vim doesn’t know this.
Make sure your $TERM setting is correct. For example, when using an xterm that supports colors:setenv TERM xterm-coloror (depending on your shell):TERM=xterm-color; export TERM
The terminal name must match the terminal you are using. If it still doesn’t work, have a look at xterm-color, which shows a few ways to make Vim display colors (not only for an xterm). - The file type is not recognized.
Vim doesn’t know all file types, and sometimes it’s near to impossible to tell what language a file uses. Try this command::set filetype
If the result isfiletype=then the problem is indeed that Vim doesn’t know what type of file this is. You can set the type manually::set filetype=fortran
To see which types are available, look in the directory $VIMRUNTIME/syntax. For the GUI you can use the Syntax menu. Setting the filetype can also be done with a modeline, so that the file will be highlighted each time you edit it. For example, this line can be used in a Makefile (put it near the start or end of the file):# vim: syntax=make
You might know how to detect the file type yourself. Often the file name extension (after the dot) can be used.
See new-filetype for how to tell Vim to detect that file type. - There is no highlighting for your file type.
You could try using a similar file type by manually setting it as mentioned above. If that isn’t good enough, you can write your own syntax file, see mysyntaxfile.
Or the colors could be wrong:
- The colored text is very hard to read.
Vim guesses the background color that you are using. If it is black (or another dark color) it will use light colors for text. If it is white (or another light color) it will use dark colors for text. If Vim guessed wrong the text will be hard to read. To solve this, set the background option. For a dark background::set background=darkAnd for a light background::set background=light
Make sure you put this before the:syntax enablecommand, otherwise the colors will already have been set. You could do:syntax resetafter settingbackgroundto make Vim set the default colors again. - The colors are wrong when scrolling bottom to top.
Vim doesn’t read the whole file to parse the text. It starts parsing wherever you are viewing the file. That saves a lot of time, but sometimes the colors are wrong. A simple fix is hittingCTRL-L. Or scroll back a bit and then forward again.
For a real fix, see :syn-sync. Some syntax files have a way to make it look further back, see the help for the specific syntax file. For example, tex.vim for the Tex syntax.
06.3 Different colors
:syn-default-override
If you don’t like the default colors, you can select another color scheme. In the GUI use the Edit/Color Scheme menu. You can also type the command:
:colorscheme evening
evening is the name of the color scheme. There are several others you might want to try out. Look in the directory $VIMRUNTIME/colors.
When you found the color scheme that you like, add the :colorscheme command to your vimrc file.
You could also write your own color scheme. This is how you do it:
- Select a color scheme that comes close. Copy this file to your own Vim directory. For Unix, this should work:
!mkdir ~/.vim/colors
!cp $VIMRUNTIME/colors/morning.vim ~/.vim/colors/mine.vim
This is done from Vim, because it knows the value of $VIMRUNTIME.
- Edit the color scheme file.
| Edit the color scheme file. These entries are useful | |
|---|---|
| term | attributes in a B&W terminal |
| cterm | attributes in a color terminal |
| ctermfg | foreground color in a color terminal |
| ctermbg | background color in a color terminal |
| gui | attributes in the GUI |
| guifg | foreground color in the GUI |
| guibg | background color in the GUI |
For example, to make comments green:
:highlight Comment ctermfg=green guifg=green
Attributes you can use for cterm and gui are bold and underline. If you want both, use bold,underline. For details see the :highlight command.
- Tell Vim to always use your color scheme. Put this line in your vimrc:
colorscheme mine
If you want to see what the most often used color combinations look like, use this command:
:runtime syntax/colortest,vim
You will see text in various color combinations. You can check which ones are readable and look nice. These aren’t the only colors available to you though. You can specify #rrggbb hex colors and you can define new names for hex colors in v:colornames like so:
let v:colornames['mine_red'] = '#aa0000'
If you are authoring a color scheme for others to use, it is important to define these colors only when they do not exist:
call extend(v:colornames, {'mine_red': '#aa0000'}, 'keep')
This allows users of the color scheme to override the precise definition of that color prior to loading your color scheme. For example, in a .vimrc file:
runtime colors/lists/css_colors.vim
let v:colornames['your_red'] = v:colornames['css_red']
colorscheme yourscheme
As a color scheme author, you should be able to reply on some color names for GUI colors. These are defined in colors/lists/default.vim. All such files found on the runtimepath are loaded each time the colorscheme command is run. A canonical list is provided by the vim distribution, which should include all X11 colors (previously defined in rgb.txt).
06.4 With colors or without colors
Displaying text in color takes a lot of effort. If you find the displaying too slow, you might want to disable syntax highlighting for a moment:
:syntax clear
When editing another file (or the same one) the colors will come back.
If you want to stop highlighting completely use:
:syntax off
This will completely disable syntax highlighting and remove it immediately for all buffers. See :syntax-off for more details.
:syn-manual
If you want syntax highlighting only for specific files, use this:
:syntax manual
This will enable the syntax highlighting, but not switch it on automatically when starting to edit a buffer. To switch highlighting on for the current buffer, set the syntax option:
:set syntax=ON
06.5 Printing with colors
syntax-printing
In the MS-Windows version you can print the current file with this command:
:hardcopy
You will get the usual printer dialog, where you can select the printer and a few settings. If you have a color printer, the paper output should look the same as what you see inside Vim. But when you use a dark background the colors will be adjusted to look good on white paper.
There are several options that change the way Vim prints:
To print only a range of lines, use Visual mode to select the lines and then type the command:
v100j:hardcopy
v starts Visual mode. 100j modes a hundred lines down, they will be highlighted. Then :hardcopy will print those lines. You can use other commands to move in Visual mode, of course.
This also works on Unix, if you have a PostScript printer. Otherwise, you will have to do a bit more work. You need to convert the text to HTML first, and then print it from a web browser.
Convert the current file to HTML with this command:
:TOhtml
In case that doesn’t work:
:source $VIMRUNTIME/syntax/2html.vim
You will see it crunching away, this can take quite a while for a large file. Some time later another window shows the HTML code. Now write this somewhere (doesn’t matter where, you throw it away later):
write main.c.html
Open this file in your favorite brower and print it from there. If all goes well, the output should look exactly as it does in Vim. See 2html.vim for details. Don’t forget to delete the HTML file when you are done with it.
Instead of printing, you could also put the HTML file on a web server, and let others look at the colored text.
06.6 Further reading
usr_44.txt Your own syntax highlighted.
syntax All the details.
usr_07 Editing more than one file
help :usr_07
No matter how many files you have, you can edit them without leaving Vim. Define a list of files to work on and jump from one to the other. Copy text from one file and put it in another one.
- 07.1 Edit another file
- 07.2 A list of files
- 07.3 Jumping from file to file
- 07.4 Backup files
- 07.5 Copy text between files
- 07.6 Viewing a file
- 07.7 Changing the file name
07.1 Edit another file
So far you had to start Vim for every file you wanted to edit. There is a simple way. To start editing another file, use this command:
:edit foo.txt
You can use any file name instead of foo.txt. Vim will close the current file and open the new one. If the current file has unsaved changes, however, Vim displays an error message and does not open the new file:
E37: No write since last change (use ! to override)
Note:
Vim puts an error ID at the start of each error message. If you do not understand the message or what caused it, look in the help system for this ID. In this case:
:help E37
At this point, you have a number of alternatives. You can write the file using this command:
:write
Or you can force Vim to discard your changes and edit the new file, using the force (!) character:
:edit! foo.txt
If you want to edit another file, but not write the changes in the current file yet, you can make it hidden:
:hide edit foo.txt
The text with changes is still there, but you can’t see it. This is further explained in section 22.4: The buffer list.
07.2 A list of files
You can start Vim to edit a sequence of files. For example:
vim one.c two.c three.c
This command starts Vim and tells it that you will be editing three files. Vim displays just the first file. After you have done your thing in this file, to edit the next file you use this command:
:next
If you have unsaved changes in the current file, you will get an error message and the :next will not work. This is the same problem as with :edit mentioned in the previous section. To abandon the changes:
:next!
But mostly you want to save the changes and move on to the next file. There is a special command for this:
:wnext
This does the same as using two separate commands:
:write
:next
WHERE AM I?
To see which file in the argument list you are editing, look in the window title. It should show something like (2 of 3). This means you are editing the second file out of three files.
If you want to see the list of files, use this command:
:args
This is short for arguments. The output might look like this:
one.c [two.c] three.c
These are the files you started Vim with. The one you are currently editing, two.c, is in square brackets.
MOVING TO OTHER ARGUMENTS
To go back one file:
:previous
This is just like the :next command, except that it moves in the other direction. Again, there is a shortcut command for when you want to write the file first:
:wprevious
To move to the very last file in the list:
:last
And to move back to the first one again:
:first
There is no :wlast or wfirst command though!
You can use a count for :next and :previous. To skip two files forward:
:2next
AUTOMATIC WRITING
When moving around the files and making changes, you have to remember to use :write. Otherwise you will get an error message. If you are sure you always want to write modified files, you can tell Vim to automatically write them:
:set autowrite
When you are editing a file which you may not want to write, switch it off again:
:set noautowrite
EDITING ANOTHER LIST OF FILES
You can redefine the list of files without the need to exit Vim and start it again. Use this command to edit three other files:
:args five.c six.c seven.h
Or use a wildcard, like it’s used in the shell:
:args *.txt
Vim will take you to the first file in the list. Again, if the current file has changes, you can either write the file first, or use :args! (wirh ! added) to abandon the changes.
arglist-quit
DID YOU EDIT THE LAST FILE?
When you use a list of files, Vim assumes you want to edit them all. To protect you from exiting too early, you will get this error when you didn’t edit the last file in the list yet:
E173: 46 more files to edit
If you really want to exit, just do it again. Then it will work (but not when you did other commands in between).
07.3 Jumping from file to file
To quickly jump between two files, press CTRL-^ (on English-US keyboards the ^ is above the 6 key). Example:
:args one.c two.c three.c
You are now in one.c.
:next
Now you are in two.c. Now use CTRL-^ to go back to one.c. Another CTRL-^ and you are back in two.c. Another CTRL-^ and you are in one.c again. If you now do:
:next
You are in three.c. Notice that the CTRL-^ command does not change the idea of where you are in the list of files. Only commands like :next and :previous do that.
The file you were previously editing is called the alternate file. When you just started Vim CTRL-^ will not work, since there isn’t a previous file.
PREDEFINED MARKS
After jumping to another file, you can use two predefined marks which are very useful:
`"
This takes you to the position where the cursor was when you left the file. Another mark that is remembered is the position where you made the last change:
`.
Suppose you are editing the file one.txt. Somewhere halfway through the file you use x to delete a character. Then you go to the last line with G and write the file with :w. You edit several other files, and then use :edit one.txt to come back to one.txt. If you now use `“ Vim jumps to the last line of the file. Using `. takes you to the position where you deleted the character. Even when you move around in the file `” and `. will take you to the remembered position. At least until you make another change or leave the file.
FILE MARKS
In section 03.10 was explained how you can place a mark in a file with mx and jump to that position with `x. That works within one file. If you edit another file and place marks there, these are specific for that file. Thus each file has its own set of marks, they are local to the file.
So far we were using marks with a lowercase letter. There are also marks with an uppercase letter. These are global, they can be used from any file. For example suppose that we are editing the file foo.txt. Go to halfway down the file (“50%”) and place the F mark there (F for foo):
50%mF
Now edit the file bar.txt and place the B mark (B for bar) at its last line:
GmB
Now you can use the ’F command to jump back to halfway foo.txt. Or edit yet another file, type ’B and you are at the end of bar.txt again.
The file marks are remembered until they are placed somewhere else. Thus you can place the mark, do hours of editing and still be able to jump back to that mark.
It’s often useful to think of a simple connection between the mark letter and where it is placed. For example, use the H mark in a header file, M in a Makefile and C in a C code file.
To see where a specific mark is, give an argument to the :marks command:
:marks M
You can also give several arguments:
:marks MCP
Don’t forget that you can use CTRL-O and CTRL-I to jump to older and newer positions without placing marks there.
07.4 Backup files
Usually Vim does not produce a backup file. If you want to have one, all you need to do is execute the following command:
:set backup
The name of the backup file is the original file with a ~ added to the end. If your file is named data.txt, for example, the backup file name is data.txt~.
If you do not like the fact that the backup files end with ~, you can change the extension:
:set backupext=.bak
This will use data.txt.bak instead of data.txt~.
Another option that matters here is backupdir. It specifies where the backup file is written. The default, to write the backup in the same directory as the original file, will mostly be the right thing.
Note:
When the backup option isn’t set but the writebackup is, Vim will still create a backup file. However, it is deleted as soon as writing the file was completed successfully. This functions as a safety against losing your original file when writing fails in some way (disk full is the most common cause; being hit by lightning might be another, although less common).
KEEPING THE ORIGINAL FILE
If you are editing source files, you might want to keep the file before you make any changes. But the backup file will be overwritten each time you write the file. Thus it only contains the previous version, not the first one.
To make Vim keep the original file, set the patchmode option. This specifies the extension used for the first backup of a changed file. Usually you would do this:
:set patchmode=.orig
When you now edit the file data.txt for the first time, make changes and write the file, Vim will keep a copy of the unchanged file under the name data.txt.orig.
If you make further changes to the file, Vim will notice that data.txt.orig already exists and leave it alone. Further backup files will then be called data.txt~ (or whatever you specified with backupext).
If you leave patchmode empty (that is the default), the original file will not be kept.
07.5 Copy text between files
This explains how to copy text from one file to another. Let’s start with a simple example. Edit the file that contains the text you want to copy. Move the cursor to the start of the text and press v. This starts Visual mode. Now move the cursor to the end of the text and press y. This yanks (copies) the selected text.
To copy the above paragraph, you would do:
:edit thisfile
/This
vjjjj$y
Now edit the file you want to put the text in. Move the cursor to the character where you want the text to appear after. Use p to put the text there.
:edit otherfile
/There
p
Of course you can use many other commands to yank the text. For example, to select whole lines start Visual mode with V. Or use CTRL-V to select a rectangular block. Or use Y to yank a single line, yaw to yank-a-word, etc.
The p command puts the text after the cursor. Use P to put the text before the cursor. Notice that Vim remembers if you yanked a whole line or a block, and puts it back that way.
USING REGISTERS
When you want to copy several pieces of text from one file to another, having to switch between the files and writing the target file takes a lot of time. To avoid this, copy each piece of text to its own register.
A register is a place where Vim stores text. Here we will use the registers named a to z (later you will find out there are others). Let’s copy a sentence to the f register (f for First):
"fyas
The yas command yanks a sentence like before. It’s the "f that tells Vim the text should be placed in the f register. This must come just before the yank command.
Now yank three whole lines to the l register (l for line):
"l3y
The count could be before the "l just as well. To yank a block of text to the b (for block) register:
CTRL-Vjjww"by
Notice that the register specification "b is just before the y command. This is required. If you would have put it before the w command, it would not have worked.
Now you have three pieces of text in the f, l and b registers. Edit another file, move around and place the text where you want it:
"fp
Again, the register specification "f comes before the p command.
You can put the registers in any order. And the text stays in the register until you yank something else into it. Thus you can put it as many times as you like.
When you delete text, you can also specify a register. Use this to move several pieces of text around. For example, to delete-a-word and write it in the w register:
"wdaw
Again, the register specification comes before the delete command d.
APPENDING TO A FILE
When collecting lines of text into one file, you can use this command:
:write >> logfile
This will write the text of the current file to the end of logfile. Thus it is appended. This avoids that you have to copy the lines, edit the log file and put them there. Thus you save two steps. But you can only append to the end of a file.
To append only a few lines, select them in Visual mode before typing :write. In chapter 10 you will learn other ways to select a range of lines.
07.6 Viewing a file
Sometimes you only want to see what a file contains, without the intention to ever write it back. There is the risk that you type :w without thinking and overwrite the original file anyway. To avoid this, edit the file read-only.
To start Vim in readonly mode, use this command:
vim -R file
On Unix this command should do the same thing:
view file
You are now editing file in read-only mode. When you try using :w you will get an error message and the file won’t be written.
When you try to make a change to the file Vim will give you a warning:
W10: Warning: Changing a readonly file
The change will be done though. This allows for formatting the file, for example, to be able to read it easily.
If you make changes to a file and forgot that it was read-only, you can still write it. Add the ! to the write command to force writing.
If you really want to forbid making changes in a file, do this:
vim -M file
Now every attempt to change the text will fail. The help files are like this, for example. If you try to make a change you get this error message:
E21: Cannot make changes, 'modifiable' is off
You could use the -M argument to setup Vim to work in a viewer mode. This is only voluntary though, since these commands will remove the protection:
:set modifiable
:set write
07.7 Changing the file name
A clever way to start editing a new file is by using an existing file that contains most of what you need. For example, you start writing a new program to move a file. You know that you already have a program that copies a file, thus you start with:
:edit copy.c
You can delete the stuff you don’t need. Now you need to save the file under a new name. The :saveas command can be used for this:
:saveas move.c
Vim will write the file under the given name, and edit that file. Thus the next time you do :write, it will write move.c. copy.c remains unmodified.
When you want to change the name of the file you are editing, but don’t want to write the file, you can use this command:
:file move.c
Vim will mark the file as not edited. This means that Vim knows this is not the file you started editing. When you try to write the file, you might get this message:
E13: File exists (use ! to override)
This protects you from accidentally overwriting another file.
usr_08 Splitting windows
:help usr_08
Display two different files above each other. Or view two locations in the file at the same time. See the difference between two files by putting them side by side. All this is possible with split windows.
- 08.1 Split a window
- 08.2 Split a window on another file
- 08.3 Window size
- 08.4 Vertical splits
- 08.5 Moving windows
- 08.6 Commands for all windows
- 08.7 Viewing differences with vimdiff
- 08.8 Various
- 08.9 Tab pages
08.1 Split a window
The easiest way to open a new window is to use the following command:
:split
This command splits the screen into two windows and leaves the cursor in the top one:
+----------------------------------+
|/* file one.c */ |
|~ |
|~ |
|one.c=============================|
|/* file one.c */ |
|~ |
|one.c=============================|
| |
+----------------------------------+
What you see here is two windows on the same file. The line with ==== is the status line. It displays information about the window above it. (In practice the status line will be in reverse video.)
The two windows allow you to view two parts of the same file. For example, you could make the top window show the variable declarations of a program, and the bottom one the code that uses these variables.
The CTRL-W w command can be used to jump between the windows. If you are in the top window, CTRL-W w jumps to the window below it. If you are in the bottom window it will jump to the first window. (CRTL-W CTRL-W does the same thing, in case you let go of the CTRL key a bit later.)
CLOSE THE WINDOW
To close a window, use the command:
:close
Actually, any command that quits editing a file works, like :quit and ZZ. But :close prevents you from accidentally exiting Vim when you close the last window.
CLOSING ALL OTHER WINDOWS
If you have opened a whole bunch of windows, but now want to concentrate on one of them, this command will be useful:
:only
This closes all windows, except for the current one. If any of the other windows has changes, you will get an error message and that window won’t be closed.
08.2 Split a window on another file
The following command opens a second window and starts editing the given file:
:split two.c
If you were editing one.c, then the result looks like this:
+----------------------------------+
|/* file two.c */ |
|~ |
|~ |
|two.c=============================|
|/* file one.c */ |
|~ |
|one.c=============================|
| |
+----------------------------------+
To open a window on a new, empty file, use this:
:new
You can repeat the :split and :new commands to create as many windows as you like.
08.3 Window size
The :split command can take a number argument. If specified, this will be the height of the new window. For example, the following opens a new window three lines high and starts editing the file alpha.c:
:3split alpha.c
For existing windows you can change the size in several ways. When you have a working mouse, it is easy: Move the mouse pointer to the status line that separates two windows, and drag it up or down.
To increase the size of a window:
CTRL-W +
To decrease it:
CTRL-W -
Both of these commands take a count and increase or decrease the window size by that many lines. Thus 4 CTRL-W + make the window four lines higher.
To set the window height to a specified number of lines:
{height}CTRL-W _
That’s: a number {height}, CTRL-W and then an under score (the - key with Shift on English-US keyboards).
To make a window as high as it can be, use the CTRL-W _ command without a count.
USING THE MOUSE
In Vim you can do many things very quickly from the keyboard. Unfortunately, the window resizing commands requite quite a bit of typing. In this case, using the mouse is faster. Position the mouse pointer on a status line. Now press the left mouse button and drag. The status line will move, thus making the window on one side higher and the other smaller.
OPTIONS
The winheight option can be set a minimal desired height of a window and winminheight to a hard minimum height.
Likewise, there is winwidth for the minimal desired width and winminwidth for the hard minimum width.
The equalalways option, when set, makes Vim equalize the windows sizes when a window is closed or opened.
08.4 Vertical splits
The :split command creates the new window above the current one. To make the window appear at the left side, use:
:vsplit
or:
:vsplit two.c
The result looks something line this:
+--------------------------------------+
|/* file two.c */ |/* file one.c */ |
|~ |~ |
|~ |~ |
|~ |~ |
|two.c===============one.c=============|
| |
+--------------------------------------+
Actually, the | lines in the middle will be in reverse video. This is called the vertical separator. It separates the two windows left and right of it.
There is also the :vnew command, to open a vertically split window on a new, empty file. Another way to do this:
:vertical new
The :vertical command can be inserted before another command that splits a window. This will cause that command to split the window vertically instead of horizontally. (If the command doesn’t split a window, it works unmodified.)
MOVING BETWEEN WINDOWS
Since you can split windows horizontally as much as you like, you can create almost any layout of windows. Then you can use these commands to move between them:
CTRL-W h move to the window on the left
CTRL-W j move to the window below
CTRL-W k move to the window above
CTRL-W l move to the window on the right
CTRL-W t move to the TOP window
CTRL-W b move to the BOTTOM window
You will notice the same letters as used for moving the cursor. And the cursor keys can also be used, if you like.
More commands to move to other windows: Q_wi.
08.5 Moving windows
You have split a few windows, but now they are in the wrong place. Then you need a command to move the window somewhere else. For example, you have three windows like this:
+----------------------------------+
|/* file two.c */ |
|~ |
|~ |
|two.c=============================|
|/* file three.c */ |
|~ |
|~ |
|three.c===========================|
|/* file one.c */ |
|~ |
|one.c=============================|
| |
+----------------------------------+
Clearly the last one should be at the top. Go to that window (using CTRL-W w) and then type this command:
CTRL-W K
This uses the uppercase letter K. What happens is that the window is moved to the very top. You will notices that K is again used for moving upwards.
When you have vertical splits, CTRL-W K will move the current window to the top and make it occupy the full width of the Vim window. If this is your layout:
+-------------------------------------------+
|/* two.c */ |/* three.c */ |/* one.c */ |
|~ |~ |~ |
|~ |~ |~ |
|~ |~ |~ |
|~ |~ |~ |
|~ |~ |~ |
|two.c=========three.c=========one.c========|
| |
+-------------------------------------------+
The using CTRL-W K in the middle window (three.c) will result in:
+-------------------------------------------+
|/* three.c */ |
|~ |
|~ |
|three.c====================================|
|/* two.c */ |/* one.c */ |
|~ |~ |
|two.c==================one.c===============|
| |
+-------------------------------------------+
The other three similar commands (you can probably guess these now):
CTRL-W H move window to the far left
CTRL-W J move window to the bottom
CTRL-W L move window to the far right
08.6 Commands for all windows
When you have several windows open and you want to quit Vim, you can close each window separately. A quicker way is using this command:
:qall
This stands for quit all. If any of the windows contain changes, Vim will not exit. The cursor will automatically be positioned in a window with changes. You can then either use :write to save the changes, or :quit! to throw them away.
If you know there are windows with changes, and you want to save all these changes, use this command:
:wall
This stands for write all. But actually, it only writes files with changes. Vim knows it doesn’t make sense to write files that were not changed.
And then there is the combination of :qall and :wall: the write and quit all command:
:wqall
This writes all modified files and quits Vim.
Finally, there is a command that quits Vim and throws away all changes:
:qall!
Be careful, there is no way to undo this command!
OPENING A WINDOW FOR ALL ARGUMENTS
To make Vim open a window for each file, start it with the -o argument:
vim -o one.txt two.txt three.txt
This results in:
+-------------------------------+
|file one.txt |
|~ |
|one.txt========================|
|file two.txt |
|~ |
|two.txt========================|
|file three.txt |
|~ |
|three.txt======================|
| |
+-------------------------------+
The -O argument is used to get vertically split windows.
When Vim is already running, the :all command opens a window for each file in the argument list. :vertical all does it with vertical splits.
08.7 Viewing differences with vimdiff
There is a special way to start Vim, which shows the differences between two files. Let’s take a file main.c and insert a few characters in one line. Write this file with the [backup] option set, so that the backup file main.c~ will contain the previous version of the file.
Type this command in a shell (not in Vim):
vimdiff main.c~ main.c
Vim will start, with two windows side by side. You will only see the line in which you added characters, and a few lines above and blow it.
VV VV
+-----------------------------------------+
|+ +--123 lines: /* a|+ +--123 lines: /* a| <- fold
| text | text |
| text | text |
| text | text |
| text | changed text | <- changed line
| text | text |
| text | ------------------| <- deleted line
| text | text |
| text | text |
| text | text |
|+ +--432 lines: text|+ +--432 lines: text| <- fold
| ~ | ~ |
| ~ | ~ |
|main.c~==============main.c==============|
| |
+-----------------------------------------+
(This picture doesn’t show the highlighting, use the vimdiff command for a better look.)
The lines that were not modified have been collapsed into one line. This is called a closed fold. They are indicated in the picture with <- fold. Thust he single fold line at the top stands for 123 text lines. These lines are equal in both files.
The line marked with <- changed line is highlighted, and the inserted text is displayed with another color. This clearly shows what the difference is between the two files.
The line that was deleted is displayed with --- in the main.c window. See the <- deleted line marker in the picture. These characters are not really there. They just fill up main.c, so that it displays the same number of lines as the other window.
THE FOLD COLUMN
Each window has a column on the left with a slightly different background. In the picture above these are indicated with VV. You notice there is a plus character there, in front of each closed fold. Move the mouse pointer to that plus and click the left button. The fold will open, and you can see the text that it contains.
The fold column contains a minus sign for an open fold. If you click on this -, the fold will close.
Obviously, this only works when you have a working mouse. You can also use zo to open a fold and zc to close it.
DIFFING IN VIM
Another way to start in diff mode can be done from inside Vim. Edit the main.c file, then make a split and show the differences:
:edit main.c
:vertical diffsplit main.c~
The :vertical command is used to make the window split vertically. If you omit this, you will get a horizontal split.
If you have a patch or diff file, you can use the third way to start diff mode. First edit the file to which the patch applies. Then tell Vim the name of the patch file:
:edit main.c
:vertical diffpatch main.c.diff
WARNING: The patch file must contain only one patch, for the file you are editing. Otherwise you will get a lot of error messages, and some files might be patched unexpectedly.
The patching will only be done to the copy of the file in Vim. The file on your harddisk will remain unmodified (until you decide to write the file).
SCROLL BINDING
When the files have more changes, you can scroll in the usual way. Vim will try to keep both the windows start at the same position, so you can easily see the differences side by side.
When you don’t want this for a moment, use this command:
:set noscrollbind
JUMPING TO CHANGES
When you have disabled folding in some way, it may be difficult to find the changes. Use this command to jump forward to the next change:
]c
To go the other way use:
[c
Prepended a count to jump further away.
REMOVING CHANGES
You can move text from one window to the other. This either removes differences or adds new ones. Vim doesn’t keep the highlighting updated in all situations. To update it use this command:
:diffupdate
To remove a difference, you can move the text in a highlighted block from one window to another. Take the main.c and main.c~ example above. Move the cursor to the left window, on the line that was deleted in the other window. Now type this command:
dp
The change will be removed by putting the text of the current window in the other window. dp stands for diff put.
You can also do it the other way around. Move the cursor to the right window, to the line where changed was inserted. Now type this command:
do
The change will now be removed by getting the text from the other window. Since there are no changes left now, Vim puts all text in a closed fold. do stands for diff obtain. dg would have been better, but that already has a different meaning (dgg deletes from the cursor until the first line).
For details about diff mode, see vimdiff
08.8 Various
The laststatus option can be used to specify when the last window has a statusline:
0 never
1 only when there are split windows (the default)
2 always
Many commands that edit another file have a variant that splits the window. For Command-line commands this is done by prepending an s. For example: :tag jumps to a tag, :stag splits the window and jumps to a tag.
For Normal mode commands a CTRL-W is prepended. CTRL-^ jumps to the alternate file, CTRL-W CTRL-^ splits the window and edits the alternate file.
The splitbelow option can be set to make a new window appear below the current window. The splitright option can be set to make a vertically split window appear right of the current window.
When splitting a window you can prepend a modifier command to tell where the window is to appear:
:leftabove {cmd} left or above the current window
:aboveleft {cmd} idem
:rightbelow {cmd} right or below the current window
:belowright {cmd} idem
:topleft {cmd} at the top or left of the Vim window
:botright {cmd} at the bottom or right of the Vim window
08.9 Tab pages
You will have noticed that windows never overlap. That means you quickly run out of screen space. The solution for this is called Tab pages.
Assume you are editing thisfile. To create a new tab page use this command:
:tabedit thatfile
This will edit the file thatfile in a window that occupies the whole Vim window. And you will notice a bar at the top with the two file names:
+----------------------------------+
| thisfile | /thatfile/ __________X| (thatfile is bold)
|/* thatfile */ |
|that |
|that |
|~ |
|~ |
|~ |
| |
+----------------------------------+
You now have two tab pages. The first one has a window for thisfile and the second one a window for thatfile. It’s like two pages that are on top of each other, with a tab sticking out of each page showing the file name.
Now use the mouse to click on thisfile in the top line. The result is
+----------------------------------+
| /thisfile/ | thatfile __________X| (thisfile is bold)
|/* thisfile */ |
|this |
|this |
|~ |
|~ |
|~ |
| |
+----------------------------------+
Thus you can switch between tab pages by clicking on the label in the top line. If you don’t have a mouse or don’t want use it, you can use the gt command. Mnemonic: Goto Tab.
Now let’s create another tab page with the command:
:tab split
This makes a new tab page with one window thatis editing the same buffer as the window we were in:
+-------------------------------------+
| thisfile | /thisfile/ | thatfile __X| (thisfile is bold)
|/* thisfile */ |
|this |
|this |
|~ |
|~ |
|~ |
| |
+-------------------------------------+
You can put :tab before any Ex command that opens a window. The window will be opened in a new tab page. Another example:
:tab help gt
Will show the help text for gt in a new tab page.
A few more things you can do with tab pages:
- click with the mouse in the space after the last label
The next tab page will be selected, like withgt - click with the mouse on the X in the top right corner
The current tab page will be closed. Unless there are unsaved changes in the current tab page. - double click with the mouse in the top line
A new tab page will be created. - the
tabonlycommand
Closes all tab pages except the current one. Unless there are unsaved changes in other tab pages.
For more information about tab pages see tab-page.
usr_09 Using the GUI
:help usr_09
usr_10 Making big changes
:help usr_10
10.1 Record and playback commands
usr_11 Recovering from a crash
:help usr_11
Did your computer crash? And you just spent hours editing? Don’t panic! Vim stores enough information to be able to restore most of your work. This chapter shows you how to get your work back and explains how the swap file is used.
11.1 Basic recovery
In most cases recovering a file is quite simple, assuming you know which file you were editing (and the harddisk is still working). Start Vim on the file, with the -r argument added:
vim -r help.txt
Vim will read the swap file (used to store text you were editing) and may read bits and pieces of the original file. If Vim recovered your changes you will see these messages (with different file names, of course):
Using swap file ".help.txt.swp"
Original file "~/vim/runtime/doc/help.txt"
Recovery completed. You should check if everything is OK.
(You might want to write out this file under another name
and run diff with the original file to check for changes)
You may want to delete the .swp file now.
To be on the safe side, write this file under another name:
:write help.txt.recovered
Compare the file with the original file to check if you ended up with what you expected. Vimdiff is very useful for this 08.7. For example:
:write help.txt.recovered
:edit #
:diffsp help.txt
Watch out for the original file to contain a more recent version (you saved the file just before the computer crashed). And check that no lines are missing (something went wrong that Vim could not recover).
If Vim produces warning messages when recovering, read them carefully. This is rare though.
If the recovery resulted in text that is exactly the same as the file contents, you will get this message:
Using swap file ".help.txt.swp"
Original file "~/vim/runtime/doc/help.txt"
Recovery completed. Buffer contents equals file contents.
You may want to delete the .swp file now.
This usually happens if you already recovered your changes, or you wrote the file after making changes. It is safe to delete the swap file now.
It is normal that the last few changes can not be recovered. Vim flushes the changes to disk when you don’t type for about four seconds, or after typing about two hundred characters. This is set with the undatetime and updatecount options. Thus when Vim didn’t get a chance to save itself when the system went down, the changes after the last flush will be lost.
If you were editing without a file name, give an empty string as argument:
vim -r ""
You must be in the right directory, otherwise Vim can’t find the swap file.
11.2 Where is the swap file?
Vim can store the swap file in several places. Normally it is in the same directory as the original file. To find it, change to the directory of the file, and use:
vim -r
Vim will list the swap files that it can find. It will also look in other directories where the swap file for files in the current directory may be located. It will not find swap files in any other directories though, it doesn’t search the directory tree.
The output could look like this:
Swap files found:
In current directory:
1. .main.c.swp
owned by: mool dated: Tue May 29 21:00:25 2001
file name: ~mool/vim/vim6/src/main.c
modified: YES
user name: mool host name: masaka.moolenaar.net
process ID: 12525
In directory ~/tmp:
-- none --
In directory /var/tmp:
-- none --
In directory /tmp:
-- none --
If there are several swap files that look like they may be the one you want to use, a list is given of these swap files and you are requested to enter the number of the one you want to use. Carefully look at the dates to decide which one you want to use.
In case you don’t know which one to use, just try them one by one and check the resulting files if they are what you expected.
USING A SPECIFIC SWAP FILE
If you know which swap file needs to be used, you can recovering by giving the swap file name. Vim will then find out the name of the original file from the swap file.
Example:
vim -r .help.txt.swo
This is also handy when the swap file is in another directoey than expected. Vim recognizes files with the pattern *.s[uvw][a-z] as swap files.
If this still does not work, see what file names Vim reports and rename the files accordingly. Check the directory option to see where Vim may have put the swap file.
Note:
Vim tries to find the swap file by searching the directories in the dir option, looking for files that match filename.sw?. If wildcard expansion doesn’t work (e.g., when the shell option is invalid), Vim does a desperate try to find the file filename.swp. If that fails too, you will have to give the name of the swapfile itself to be able to recover the file.
11.3 Crashed or not?
ATTENTION E325
Vim tries to protect you from doing stupid things. Suppose you innocently start editing a file, expecting the contents of the file to show up. Instead, Vim produces a very long message:
E325: ATTENTION
Found a swap file by the name ".main.c.swp"
owned by: mool dated: Tue May 29 21:09:28 2001
file name: ~mool/vim/vim6/src/main.c
modified: no
user name: mool host name: masaka.moolenaar.net
process ID: 12559 (still running)
While opening file "main.c"
dated: Tue May 29 19:46:12 2001
(1) Another program may be editing the same file.
If this is the case, be careful not to end up with two
different instances of the same file when making changes.
Quit, or continue with caution.
(2) An edit session for this file crashed.
If this is the case, use ":recover" or "vim -r main.c"
to recover the changes (see ":help recovery").
If you did this already, delete the swap file ".main.c.swp"
to avoid this message.
You get this message, because, when starting to edit a file, Vim checks if a swap file already exists for that file. If there is one, there must be something wrong. It may be one of these two situations.
- Another edit session is active on this file. Look in the message for the line with
process ID. It might look like this:
process ID: 12559 (still running)
The text (still running) indicates that the process editing this file runs on the same computer. When working on a non-Unix system you will not get this extra hint. When editing a file over a network, you may not see the hint, because the process might be running on another computer. In those two cases you must find out what the situation is yourself.
If there is another Vim editing the same file, continuing to edit will result in two versions of the same file. The one that is written last will overwrite the other one, resulting in loss of changes. You better quit this Vim.
- The swap file might be the result from a previous crash of Vim or the computer. Check the dates mentioned in the message. If the date of the swap file is newer than the file you were editing, and this line appers:
modified: YES
Then you very likely have a crashed edit session that is worth recovering.
If the date of the file is newer than the date of the swap file, then either it was changed after the crash (perhaps you recovered it earlier, but didn’t delete the swap file?), or else the file was saved before the crash but after the last write of the swap file (then you’re lucky: you don’t even need that old swap file). Vim will warn you for this with this extra line:
NEWER than swap file!
Note that in the following situation Vim knows the swap file is not useful and will automatically delete it:
- The file is a valid swap file (Magic number is correct).
- The flag that the file was modified is not set.
- The process is not running.
You can programmatically deal with this situation with the FileChangedShell autocommand event.
UNREADABLE SWAP FILE
Sometimes the line
[cannot be read]
will appear under the name of the swap file. This can be good or bad, depending on circumstances.
It is good if a previous editing session crashed without having made any changes to the file. Then a directory listing of the swap file will show that it has zero bytes. You may delete it and proceed.
It is slightly bad if you don’t have read permission for the swap file. You may want to view the file read-only, or quit. On multi-user systems, if you yourself did the last changes under a different login name, a logout followed by a login under that other name might cure the read error. Or else you might want to find out who last edited (or is editing) the file and have a talk with them.
It is very bad if it means there is a physical read error on the disk containing the swap file. Fortunately, this almost never happens. You may want to view the file read-only at first (if you can), to see the extent of the changes that were forgotten. If you are the one in charge of that file, be prepared to redo your last changes.
swap-exists-choices
WHAT TO DO?
If dialogs are supported you will be asked to select one of six choices:
Swap file ".main.c.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort, (D)elete it:
- O Open the file readonly. Use this when you just want to view the file and don’t need to recover it. You might want to use this when you know someone else is editing the file, but you just want to look in it and not make changes.
- E Edit the file anyway. Use this with caution! If the file is being edited in another Vim, you might end up with two versions of the file. Vim will try to warn you when this happens, but better be safe than sorry.
- R Recover the file from the swap file. Use this if you know that the swap file contains changes that you want to recover.
- Q Quit. This avoids starting to edit the file. Use this if there is another Vim editing the same file.
When you just started Vim, this will exit Vim. When starting Vim with files in several windows, Vim quits only if there is a swap file for the first one. When using an edit command, the file will not be loaded and you are taken back to the previously edited file. - A Abort. Like Quit, but also abort further commands. This is useful when loading a script that edits several files, such as a session with multiple windows.
- D Delete the swap file. Use this when you are sure you no longer need it. For example, when it doesn’t contain changes, or when the file itself is newer than the swap file.
On Unix this choice is noly offered when the process that created the swap file does not appear to be running.
If you do not get the dialog (you are running a version of Vim that does not support it), you will have to do it manually. To recover the file, use this command:
:recover
Vim cannot always detect that a swap file already exists for a file. This is the case when the other edit session puts the swap files in another directory or when the path name for the file is different when editing it on different machines. Therefore, don’t rely on Vim always warning you.
If you really don’t want to see this message, you can add the A flag to the shortmess option. But it’s very unusual that you need this.
For remarks about encryption and the swap file, see :recover-crypt.
For programmatic access to the swap file, see swapinfo().
11.4 Further reading
- swap-file An explanation about where the swap file will be created and what its name is.
- :preserve Manually flushing the swap file to disk.
- :swapname See the name of the swap file for the current file.
- updatecount Number of key strokes after which the swap file is flushed to disk.
- updatetime Timeout after which the swap file is flushed to disk.
- swapsync Whether the disk is synced when the swap file is flushed.
- directory List of directory names where to store the swap file.
- maxmem Limit for memory usage before writing text to the swap file.
- maxmemtot Same, but for all files in total.
usr_12 Clever tricks
:help usr_12
Editing Effectively
Subjects that can be read independently.
usr_20 Typing command-line commands quickly
:help usr_20
usr_21 Go away and come back
:help usr_21
usr_21 Go away and come back :help usr_21
usr_22 Finding the file to edit
:help usr_22
usr_23 Editing other files
:help usr_23
usr_24 Inserting quickly
:help usr_24
usr_25 Editing formatted text
:help usr_25
usr_26 Repeating
:help usr_26
usr_27 Search commands and patterns
:help usr_27
usr_28 Folding
:help usr_28
usr_29 Moving through programs
:help usr_29
usr_30 Editing programs
:help usr_30
usr_31 Exploiting the GUI
:help usr_31
usr_32 The undo tree
:help usr_32
Vim provides multi-level undo. If you undo a few changes and then make a new change you create a branch in the undo tree. This text is about moving through the branches.
- 32.1 Undo up to a file write
- 32.2 Numbering changes
- 32.3 Jumping around the tree
- 32.4 Time travelling
32.2 Numbering changes
In section 02.5 we only discussed one line of undo/redo. But it is also possible to branch off. This happens when you undo a few changes and then make a new change. The new changes become a branch in the undo tree.
Let’s start with the text one. The first change to make is to append ** too**. And then move to the first o and change it into w. We then have two changes, numbered 1 and 2, and three states of the text:
one
|
change 1
|
one too
|
change 2
|
one two
If we now undo one change, back to one too, and change one to me we create a branch in the undo tree:
one
|
change 1
|
one too
/ \
change 2 change 3
| |
one two me too
You can noe use the ucommand to undo. If you do this twice you get to one. Use CTRL-R to redo, and you will go to one too. One more CTRL-R takes you to me too. Thus undo and redo go up and down in the tree, using the branch that was last used.
What matters here is the order in which the changes are made. Undo and redo are not considered changes in this context. After each change you have a new state of the text.
Note
that only the changes are numbered, the text shown in the tree above has no identifier. They are mostly referred to by the number of the change above it. But sometimes by the number of one of the changes below it, especially when moving up in the tree, so that you know which change was just undone.
Next chapter: usr_40 Make new commands
Tuning Vim
Make Vim work as you like it.
usr_40 Make new commands
:help usr_40
Vim is an extensible editor. You can take a sequence of commands you use often and turn it into a new command. Or redefine an existing command. Autocmooands make it possible to execute commands automatically.
40.1 Key mapping
A simple mapping was explained in section 05.4. The principle is that one sequence of key strokes is translated into another sequence of key strokes. This is a simple, yet powerful mechanism.
The simplest form is that one key is mapped to a sequence of keys. Since the function keys, except <F1>, have no predefined meaning in Vim, these are good choices to map. Example:
:map <F2> GoDate: <Esc>:read !date<CR>kJ
This shows how three modes are used. After going to the last line with G, the o command opens a new line and starts Insert mode. The text Date: is inserted and <Esc> takes you out of insert mode.
Notice the use of special keys inside <>. This is called angle bracket notation. You type these as separate characters, not by pressing the key itself. This makes the mappings better readable and you can copy and paste the text without problems.
The : character takes Vim to the command line. The :read !date command reads the output from the date command and appends it below the current line. The <CR> is required to execute the :read command.
At this point of execution the text looks like this:
Date:
Fri Jun 15 12:54:34 CEST 2001
Now kj moves the cursor up and joins the lines together.
To decide which key or keys you use for mapping, see map-which-keys.
MAPPING AND MODES
The :map command defines remapping for keys in Normal mode. You can also define mappings for other modes. For example, :imap applies to Insert mode. You can use it to insert a date below the cursor:
:imap <F2> <CR>DATE: <Esc>:read !date<CR>kj
It looks a lot like the mapping for <F2> in Normal mode, only the start is different. The <F2> mapping for Normal mode is still there. Thus you can map the same key differently for each mode.
Notice that, although this mapping starts in Insert mode, it ends in Normal mode. If you want it to continue in Insert mode, append an a to the mapping.
| Here is an overview of map commands and in which mode they work | |
|---|---|
| :map | Normal, Visual and Operator-pending |
| :vmap | Visual |
| :nmap | Normal |
| :omap | Operator-pending |
| :map! | Insert and Command-line |
| :imap | Insert |
| :cmap | Command-line |
Operator-pending mode is when you typed an operator character, such as d or y, and you are expected to type the motion command or a text object. Thus when you type dw, the w is entered in operator-pending mode.
Suppose that you want to define <F7> so that the command d<F7> deletes a C program block (text enclosed in curly braces, {}). Similarly y<F7> would yank the program block into the unnamed register. Therefore, what you need to do is to define <F7> to select the current program block. You can do this with the following command:
:omap <F7> a{
This causes <F7> to perform a select block a{ in operator-pending mode, just like you typed it. This mapping is useful if typing a { on your keyboard is a bit difficult.
LISTING MAPPING
To see the currently defined mappings, use :map without arguments. Or one of the variants that include the mode in which they work. The output could look like this:
_g :call MyGrep(1)<CR>
v <F2> :s/^/> /<CR>:noh<CR>``
n <F2> :.,$s/^/> /<CR>:noh<CR>``
<xHome> <Home>
<xEnd> <End>
The first column of the list shows in which mode the mapping is effective. This is n for Normal mode, i for Insert mode, etc. Ablank is used for a mapping defined with :map, thus effective in both Normal and Visual mode.
One useful purpose of listing the mapping is to check if special keys in <> form have bean recognized (this only works when color is supported). For example, when <Esc> is displayed in clolor, it stands for the escape character. When it has the same color as the other text, it is five characters.
REMAPPING
The result of a mapping is inspected for other mappings in it. For example, the mappings for <F2> above could be shortened to:
:map <F2> G<F3>
:imap <F2> <Esc><F3>
:map <F3> oDate: <Esc>:read !date<CR>kJ
For Normal mode <F2> is mapped to go to the last line, and then behave like <F3> was pressed. In Insert mode <F2> stops Insert mode with <Esc> and then also uses <F3>. Then <F3> is mapped to do the actual work.
Suppose you hardly ever use Ex mode, and want to use the Q command to format text (this was so in old versions of Vim). This mapping will do it:
:map Q gq
But, in rare cases you need to use Ex mode anyway. Let’s map gQ to Q,so that you can still go to Ex mode:
:map gQ Q
What happens now is that when you type gQ it is mapped to Q. So far so good. But then Q is mapped to gq, thus typing gQ results in gq, and you don’t get to Ex mode at all.
To avoid keys to be mapped again. use the :noremap command:
:noremap gQ Q
Now Vim knows that the Q is not to be inspected for mappings that apply to it. There is a similar command for every mode: | |
|---|---|
| :noremap | Normal,Visual and Operator-pending |
| :vnoremap | Visual |
| :nnoremap | Normal |
| :onoremap | Operator-pending |
| :noremap! | Insert and Command-line |
| :inoremap | Insert |
| :cnoremap | Command-line |
RECURSIVE MAPPING
When a mapping triggers itself, it will run forever. This can be used to repeat an action an unlimited number of times.
For example, you have a list of files that contain a version number in the first line. You edit these files with Vim *.txt. You are now editing the first file. Define this mapping:
:map ,, :s/5.1/5.2/<CR>:wnext<CR>,,
Now you type ,,. This triggers the mapping. It replaces 5.1 with 5.2 in the first line. Then it does a :wnext to write the file and edit the next one. The mapping ends in ,,. This triggers the same mapping again, thus doing the substitution, etc.
This continues until there is an error. In this case it could be a file where the substitute command doesn’t find a match for 5.1. You can then make a change to insert 5.1 and continue by typing ,, again. Or the :wnext fails, because you are in the last file in the list.
When a mapping runs into an error halfway, the rest of the mapping is discarded. CTRL-C interrupts the mapping (CTRL-Break on MS-Windows).
DELETE A MAPPING
To remove a mapping use the :unmap command.
| Again, the mode the unmapping applies to depends on the command used: | |
|---|---|
| :unmap | Normal, Visual and Operator-pending |
| :vunmap | Visual |
| :nunmap | Normal |
| :ounmap | Operator-pending |
| :unmap! | Insert and Command-line |
| :iunmap | Insert |
| :cunmap | Command-line |
There is a trick to define a mapping that works in Normal and Operator-pending mode, but not in Visual mode. First define it for all three modes, then delete it for Visual mode:
:map <C-A> /---><CR>
:vunmap <C-A>
Notice that the five characters <C-A> stand for the single key CTRL-A.
To remove all mappings use the :mapclear command. You can guess the variations for different modes by now. Be careful with this command, it can’t be undone.
SPECIAL CHARACTERS
The :map command can be followed by another command. A | character separates the two commands. This also means that a | character can’t be used inside a map command. To include one, use <Bar> (five characters). Example:
:map <F8> :write <Bar> !checkin %:S<CR>
The same problem applies to the :unmap command, with the addition that you have to watch out for trailing white space. These two commands are different:
:unmap a | unmap b
:unmap a| unmap b
The first command tries to unmap a , with a trailing space.
When using a space inside a mapping, use <Space> (seven characters):
:map <Space> W
This makes the spacebar move a blank-separated word forward.
It is not possible to put a comment directly after a mapping, because the character is considered to be part of the mapping. You can use |, this starts a new, empty command with a comment. Example:
:map <Space> W| " Use spacebar to move forward a word
MAPPING AND ABBREVIATIONS
Abbreviations are a lot like Insert mode mappings. The arguments are handled in the same way. The main difference is the way they are triggered. An abbreviation is triggered by typing a non-word character after the word. A mapping is triggered when typing the last character.
Another difference is that the characters you type for an abbreviation are inserted in the text while you type them. When the abbreviation is triggered these characters are deleted and replaced by what the abbreviation produces. When typing the characters for a mapping, nothing is inserted until you type the last character that triggers it. If the showcmd option is set, the typed characters are displayed in the last line of the Vim window.
An exception is when a mapping is ambiguous. Suppose you have done two mappings:
:imap aa foo
:imap aaa bar
Now, when you type aa, Vim doesn’t know if it should apply the first or the second mapping. It waits for another character to be typed. If it is an a, the second mapping is applied add results in bar. If it is a space, for example, the first mapping is applied, resulting in foo, and then the space is inserted.
ADDITIONALLY…
The <script> keyword can be used to make a mapping local to a script. See :map-<script>.
The <buffer> keyword can be used to make a mapping local to a specific buffer. See :map-<buffer>.
The <unique> keyword can be used to make defining a new mapping fail when it already exists. Otherwise a new mapping simple overwrites the old one. See :map-<unique>.
To make a key do nothing, map it to <Nop> (five characters). This will make the <F7> key do nothing at all:
:map <F7> <Nop>| map! <F7> <Nop>
There must be no space after <Nop>.
40.2 Defining command-line commands
The Vim editor enables you to define your own commands. You execute these commands just like any other Command-line mode command.
To define a command, use the :command command, as follows:
:command DeleteFirst 1delete
Now when you execute the command :DeleteFitst Vim executes :1delete, which deletes the first line.
Note:
User-defined commands must start with a capital letter. You cannot use :X, :Next and :Print. The underscore cannot be used! You can use digits, but this is discouraged.
To list the user-defined commands, execute the following command:
:command
Just like with the builtin commands, the user defined commands can be abbreviated. You need to type just enough to distinguish the command from another. Command line completion can be used to get the full name.
NUMBER OF ARGUMENTS
User-defined commands can take a series of arguments. The number of arguments must be specified by the -nargs option. For instance, the example :DeleteFirst command takes no arguments, so you could have defined it as follows:
:command -nargs=0 DeleteFirst 1delete
However, beacuse zero arguments is the default, you do not need to add -nargs=0. The other values of -narg are as follows:
| -nargs | |
|---|---|
| -nargs=0 | No arguments |
| -nargs=1 | One argument |
| -nargs=* | Any number of arguments |
| -nargs=? | Zero or one argument |
| -nargs=+ | One or more arguments |
USING THE ARGUMENTS
Inside the command definition, the arguments are represented by the <args> keyword. For example:
:command -nargs=+ Say :echo "<args>"
Now when you type
:Say Hello World
Vim echoes Hello World. However, if you add a double quote, it won’t work. For example:
:Say he said "hello"
To get special characters turned into a string, properly escaped to use as an expression, use <q-args>:
:command -nargs=+ Say :echo <q-args>
Now the above :Say command will result in this to be executed:
:echo "he said" \"hello\""
The <f-args> keyword contains the same information as the <args> keyword, except in a format suitable for use as function call arguments. For example:
:command -nargs=* DoIt :call AFunction(<f-args>)
:DoIt a b c
Executes the following command:
:call AFunction("a","b","c")
LINE RANGE
Some commands take a range as their argument. To tell Vim that you are defining such a command, you need to specify a -range option. The values for this option are as follows:
-range Range is allowed; default is the current line.
-range=% Range is allowed; default is the whole file.
-range={count} Range is allowed; the last number in it is used as a
single number whose default is {count}.
When a range is specified, the keywords <line1> and <line2> get the values of the first and last line in the range. For example, the following command defines the SaveIt command, which writes out the specified range to the file save_file:
:command -range=% SaveIt :<line1>,<line2>write! save_file
OTHER OPTIONS
Some of the other options and keywords are as follows:
-count={number} The command can take a count whose default is
{number}. The resulting count can be used
through the <count> keyword.
-bang You can use a !. If present, using <bang> will result in a !.
-register You can specify a register. (The default is
the unnamed register.)
The register specification is available as
<reg> (a.k.a. <register>).
-complete={type} Type of command-line completion used. See
:command-completion for the list of possible
values.
-bar The command can be followed by | and another
command, or " and a comment.
-buffer The command is only available for the current
buffer.
Finally, you have the <lt> keyword. It stands for the character <. Use this to escape the special meaning of the <> items mentioned.
REDEFINING AND DELETING
To redefine the same command use the ! argument:
:command -nargs=+ Say :echo "<args>"
:command! -nargs=+ Say :echo <q-args>
To delete a user command use :delcommand. It tales a single argument, which is the name of the command. Example:
:delcommand SaveIt
To delete all the user commands:
:comclear
Careful, this can’t be undone!
More details about all this in the reference manual: user-commands.
40.3 Autocommands
An autocommand is a command that is executed automatically in response to some event, such as a file being read or written or a buffer change, Through the use of autocommands you can train Vim to edit compressed files, for example. That is used in the gzip plugin.
Autocommands are very powerfull. Use them with care and they will help you avoid typing many commands. Use them carelessly and they will cause a lot of trouble.
Suppose you want to replace a datestamp on the end of a file every time it is written. First you define a function:
:function DateInsert()
: $delete
: read !date
:endfunction
You want this function to be called each time, just before a buffer is written to a file. This will make that happen:
:autocmd BufWritePre * call DateInsert()
BufWritePre is the event for which this autocommand is triggered: Just before (pre) writing a buffer to a file. The * is a pattern to match with the file name. In this case it matches all files.
With this command enabled, when you do a :write, Vim checks for any matching BufWritePre autocommands and executes them, and then it performs the :write.
The general form of the :autocmd command is as follows:
:autocmd [group] {events} {file-pattern} [++nested] {command}
The [group] name is optional. It is used in managing and calling the commands (more on this later).
The {event} parameter is a list of events (comma separated) that trigger the command.
{file-pattern} is a filename, usually with wildcards. For example, using *.txt makes the autocommand be used for all files whose name end in .txt.
The optional [++nested] flag allows for nesting of autocommands (see below),
and finally, {command} is the command to be executed.
When adding an autocommand the already existing ones remain. To avoid adding the autocommand several times you should use this form:
:augroup updateDate
: autocmd!
: autocmd BufWritePre * call DateInsert()
:augroup END
This will delete any previously defined autocommand with :autocmd! before defining the new one. Groups are explained later.
EVENTS
One of the most useful events is BufReadPost. It is triggered after a new file is being edited. It is commonly used to set option values. For example, you know that *.gsm files are GUN assembly language. To get the syntax file right, define this autocommand:
:autocmd BufReadPost *.gsm set filetype=asm
If Vim is also to detect the type of file, it will set the filetype option for you. This triggers the Filetype event. Use this to do something when a certain type of file is edited. For example, to load a list of abbreviations for text files:
:autocmd Filetype text source ~/.vim/abbrevs.vim
When starting to edit a new file, you could make Vim insert a skeleton骨架;框架:
:autocmd BufNewFile *.[ch] 0read ~/skeletons/skel.c
See autocmd-events for a complete list of events.
PATTERNS
The {file-pattern} argument can actually be a comma-separated list of file patterns. For example: *.c,*.h matches files ending in .c and .h.
The usual file wildcards can be used. Here is a summary of the most often used ones:
* Match any character any number of times
? Match any character once
[abc] Match the character a, b or c
. Matches a dot
a{b,c} Matches "ab" and "ac"
When the pattern includes a slash (/) Vim will compare directory names. Without the slash only the last part of a file name is used. For example,*.txt matches /home/biep/readme.txt. The pattern /home/biep/* would also match it. But /home/foo/*.txt wouldn’t.
When including a slash, Vim matches the pattern against both the full path of the file (/home/biep/readme.txt) and the relative path (e.g., biep/readme.txt).
Note:
When working on a system that uses a backslash as file separator, such as MS-Windows, you still use forward slashes in autocommands. This makes it easier to write the pattern, since a backslash has a special meaning. It also makes the autocommands portable.
DELETING
To delete an autocommand, use the same command as what it was defined with, but leave out the {command} at the end and use a !. Example:
:autocmd! FileWritePre *
This will delete all autocommands for the FileWritePre event that use the * pattern.
LISTING
To list all the currently defined autocommands, use this:
:autocmd
The list can be very long, especially when filetype detection is used. To list only part of the commands, specify the group, event and/or pattern. For example, to list all BufNewFile autocommands:
:autocmd BufNewFile
To list all autocommands for the pattern *.c:
:autocmd * *.c
Using * for the event will list all the events. To list all autocommands for the cprograms group:
:autocmd cprograms
GROUPS
The {group} item, used when defining an autocommand, groups related autocommands together. This can be used to delete all the autocommands in a certain group, for example.
When defining several autocommands for a certain group, use the :augroup command. For example, let’s define autocommands for C programs:
:augroup cprograms
: autocmd BufReadPost *.c,*.h :set sw=4 sts=4
: autocmd BufReadPost *.cpp :set sw=3 sts=3
:augroup END
This will do the same as:
:autocmd cprograms BufReadPost *.c,*.h :set sw=4 sts=4
:autocmd cprograms BufReadPost *.cpp :set sw=3 sts=3
To delete all autocommands in the cprograms group:
:autocmd! cprograms
NESTING
Generally, commands executed as the result of an autocommand event will not trigger any new events. If you read a file in response to a FileChangedShell event, it will not trigger the autocommands that would set the syntax, for example. To make the events triggered, add the nested argument:
:autocmd FileChangedShell * ++nested edit
EXECUTING AUTOCOMMANDS
It is possible to trigger an autocommand by pretending an event has occurred. This is useful to have one autocommand trigger another one. Example:
:autocmd BufReadPost *.new execute "doautocmd BufReadPost " . expand("<afile>:r")
This defines an autocommand that is triggered when a new file has been edited. The file name must end in .new. The :execute command uses expression evaluation to form a new command and execute it. When editing the file tryout.c.new the executed command will be:
:doautocmd BufReadPost tryout.c
The expand() function takes the <afile> argument, which stands for the file name the autocommand was executed for, and takes the root of the file name with :r.
:doautocmd executes on the current buffer. The :doautoall command works like doautocmd except it executes on all the buffers.
USING NORMAL MODE COMMANDS
The commands executed by an autocommand are Command-line commands. If you want to use a Normal mode command, the :normal command can be used. Example:
:autocmd BufReadPost *.log normal G
This will make the cursor jump to the last line of *.log files when you start to edit it.
Using the :normal command is a bit tricky. First of all, make sure its argument is a complete command, including all the arguments. When you use i to go to Insert mode, there must also be a <Esc> to leave Insert mode again. If you use a / to start a search pattern, there must be a <CR> to exeucte it.
The :normal command uses all the text after it as commands. Thus there can be no | and another command following. To work around this, put the :normal command inside an :execute command. This also makes it possible to pass unprintable characters in a convenient way. Example:
:autocmd BufReadPost *.chg execute "normal ONew entry:\<Esc>" |
\ 1read !date
This also shows the use of a backslash to break a long command into more lines. This can be used in Vim scripts (not at the command line).
When you want the autocommand do something complicated, which involves jumping around in the file and then returning to the original position, you may want to restore the view on the file. See restore-position for an example.
IGNORING EVENTS
At times, you will not want to trigger an autocommand. The eventignore option contains a list of events that will be totally ignored. For example, the following causes events for entering and leaving a window to be ignored:
:set eventignore=WinEnter,WinLeave
To ignore all events, use the following command:
:set eventignore=all
To set it back to the normal behavior, make eventignore empty:
:set eventignore=
usr_41 Write a Vim script
:help usr_41
usr_42 Add new menus
:help usr_42
usr_43 Using filetypes
:help usr_43
usr_44 Your own syntax highlighted
:help usr_44
usr_45 Select your language (locale)
:help usr_45
Writing Vim script
usr_50 Advanced Vim script writing
:help usr_50
usr_51 Write plugins
:help usr_52
usr_52 Installing Vim
:help usr_52
Making Vim Run/read
usr_90 Installing Vim
:help usr_90
Before you can use Vim you have to install it. Depending on your system it’s simple or easy. This Chapter gives a few hints and also explains how upgrading to a new version is done.
90.1 Unix
First you have to decide if you are going to install Vim system-wide or for a single user. The installation is almost the same, but the directory where Vim is installed in differs.
For a system-wide installation the base directory /usr/local is often used. But this may be different for your system. Try finding out where other packages are installed.
When installing for a single user, you can use your home directory as the base. The files will be placed in subdirectories like bin and shared/vim.
FROM A PACKAGE
You can get precompiled binaries for many different UNIX systems. There is a long list with links on this page: http://www.vim.org/binaries.html
Volunteers maintain the binaries, so they are often out of date. It is a good idea to compile your own UNIX version from the source. Also, creating the editor from the source allows you to control which features are compiled.
This does require a compiler though.
If you have a Linux distribution, the vi program is probably a minimal version of Vim. It doesn’t do syntax highlighting, for example. Try finding another Vim package in your distribution, or search on the web site.
FROM SOURCES
To compile and install Vim, you will need the following:
- A C compiler (GCC preferred)
- The GZIP program (you can get it from http://www.gnu.org)
- The Vim source and runtime archives
To get the Vim archives, look in this file for a mirror near you, this should provide the fastest download: ftp://ftp.vim.org/pub/vim/MIRRORS
Or use the home site ftp.vim.org, if you think it’s fast enough. Go to the unix directory and you’ll find a list of files there. The version number is embedded in the file name. You will want to get the most recent version.
You can get the files for Unix in one big archive that contains everything: vim-8.2.tar.bz2
You need the bizp2 program to uncompress it.
COMPILING
First create a top directory to work in, for example:
mkdir ~/vim
cd ~/vim
Then unpack the archives there. You can unpack it like this:
tar xf path/vim-8.2.tar.bz2
If your tar command doesn’t support bz2 directly:
bzip2 -d -c path/vim-8.2.tar.bz2|tar xf -
Change path to where you have downloaded the file.
If you are satisfied with getting the default features, and your environment is setup properly, you should be able to compile Vim with just this:
cd vim82/src
make
The make program will run configure and compule everything. Further on we will explain how to compile with different features.
If there are errors while compiling, carefully look at the error messages.
There should be a hint about what went wrong. Hopefully you will be able to correct it. You might have to disable some features to make Vim compile.
Look in the Makefile for specific hints for your system.
TESTING
Now you can check if compiling worked OK:
make test
This will run a sequence of test scripts to verify that Vim works as expected.
Vim will be started many times and all kinds of text and messages flash by.
If it is alright you will finally see:
test results:
ALL DONE
If you get TEST FAILURE some test failed. If there are one or two messages about failed tests, Vim might still work, but not perfectly. If you see a lot of error messages or Vim doesn’t finish until the end, there must be something wrong. Either try to find out yourself, or find someone who can solve it.
You could look in the maillist-archive for a solution. If everything else fails, you could ask in the vim maillist if someone can help you.
INSTALLING
if you want to install in your home directory, edit the Makefile and search for a line:
#prefix = $(HOME)
Remove the # at the start of the line.
When installing for the whole system, Vim has most likely already selected a good installation directory for you. You can also sprcify one, see below.
You need to become root for the following.
To install Vim do:
make install
That should move all the relevant files to the right place. Now you can try running vim to verify that it works. Use two simple tests to check if Vim can find its runtime files:
:help
:syntax enable
If this doesn’t work, use this command to check where Vim is looking for the runtime files:
:echo $VIMRUNTIME
You can also start Vim with the -V argument to see what happens during startup:
vim -V
Don’t forget that the user manual assumes you Vim in a certain way. After installing Vim, follow the instructions at not-compatible to make Vim work as assumed in this manual.
SELECTING FEATURES
Vim has many ways to select features. One of the simple ways is to edit the Makefile. There are many directions and examples. Often you can enable or disable a feature by uncommenting a line.
An alternative is to run configure separately. This allows you to specify configuration options manually. The disadvantage is that you have to figure out what exactly to type.
Some of the most interesting configure arguments follow. These can also be enabled from the Makefile.
--prefix={directory} Top directory where to install Vim.
--with-features=tiny Compile with many features disabled.
--with-features=small Compile with some features disabled.
--with-features=big Compile with more features enabled.
--with-features=huge Compile with most features enabled.
See +feature-list for which featur e
is enabled in which case.
--enable-perlinterp Enable the Perl interface. There are
similar arguments for ruby, python and
tcl.
--disable-gui Do not compile the GUI interface.
--without-x Do not compile X-windows features.
When both of these are used, Vim will
not connect to the X server, which
makes startup faster.
To see the whole list use:
./configure --help
You can find a bit of explanation for each feature, and links for more information here: feature-list.
For the adventurous, edit the file feature.h. You can also change the source code yourself!
90.2 MS-Windows
There are two ways to install the Vim program for Microsoft Windows. You can uncompress several archives, or use a self-installing big archive. Most users with fairly recent computers will prefer the second method. For the first one, you will need:
- An archive with binaries for Vim.
- The Vim runtime archive.
- A program to unpack the zip files.
To get the Vim archives, look in this file for a mirror near you, this should provide the fastest download: ftp://ftp.vim.org/pub/vim/MIRRORS
Or use the home site ftp.vim.org, if you think it’s fast enough. Go to the pc directory and you’ll find a list of files there. The version number is embedded in the file name. You will want to get the most recent version.
We will use *82 here, which is version 8.2.
gvim82.exe The self-installing archive.
This is all you need for the second method. Just launch the executable, and follow the prompts.
For the first method you must choose one of the binary archive. These are available:
gvim82.zip The normal MS-Windows GUI version.
gvim82ole.zip The MS-Windows GUI version with OLE support.
Uses more memory, supports interfacing with
other OLE applications.
vim82w32.zip 32 bit MS-Windows console version.
You only need one of them. Although you could install both a GUI and a console version. You always need to get the archive with runtime files.
vim82rt.zip The runtime files.
Use your un-zip program to unpack the files. For example, using the unzip program:
cd c:\
unzip path\gvim82.zip
unzip path\vim82rt.zip
This will unpack the files in the directory c:\vim\vim82. If you already have a vim directory somewhere, you will want to move to the directory just above it. Now change to the vim\vim82 directory and run the install program:
install
Carefully look through the messages and select the options you want to use. If you finally select do it the install program will carry out the actions you selected.
The install program doesn’t move the runtime files. They remain where you unpacked them.
In case you are not satisfied with the features included in the supplied binaries, you could try compiling Vim yourself. Get the source archive from the same location as where the binaries are. You need a compiler for which a makefile exists. Microsoft Visual C, MinGW and Cygwin compilers can be used.
CHeck the file src/INSTALLpc.txt for hints.
90.3 upgrading
If you are running one version of Vim and want to install another, here is what to do.
UNIX
When you type make install the runtime files will be copied to a directory which is specific for this version. Thus they will not overwrite a previous version. This makes it possible to use two or more versions next to each other.
The executable vim will overwrite an older version. If you don’t care about keeping the old version, running make install will work fine. You can delete the old runtime files manually. Just delete the directory with the version number in it and all files below it. Example:
rm -rf /usr/local/share/vim/vim74
There are normally no changed files below this directory. If you did change the filetype.vim file, for example, you better merge the changes into the new version before deleting it.
If you are careful and want to try out the new version for a while before switching to it, install the new version under another name. You need to specify a configure argument. For example:
./configure --with-vim-name=vim8
Before running make install, you could use make -n install to check that no valuable existing files are overwritten.
When you finally decide to switch to the new version, all you need to do is to rename the binary to vim. For example:
mv /usr/local/bin/vim8 /usr/local/bin/vim
MS-WINDOWS
Upgrading is mostly equal to installing a new version. Just unpack the files in the same place as the previous version. A new directory will be created. e.g., vim82, for the files of the new version. Your runtime files, vimrc file, viminfo, etc. will be left alone.
If you want to run the new version next to the old one, you will have to do some handwork. Don’t run the install program, it will overwrite a few files of the old version. Execute the new binaries by specifying the full path. The program should be able to automatically find the runtime files for the right version. However, this won’t work if you set the $VIMRUNTIME variable somewhere.
If you are satisfied with the upgrade, you can delete the files of the previous version. See 90.5.
90.4 Common installation issues
This section describes some of the common problems that occur when installing Vim and suggests some solutions. It also contains answers to many installation questions.
Q: I Do Not Have Root Privileges. How Do I Install Vim?(Unix)
Use the following configuration command to install Vim in a directory called $HOME/vim:
./configure --prefix=$HOME
This gives you a personal copy of Vim. You need to put $HOME/bin in your path to execute the editor. Also see install-home.
Q: The Colors Are Not Right on My Screen.(Unix)
Check your terminal settings by using the following command in a shell:
echo $TERM
If the terminal type listed is not correct, fix it. For more hints, see 06.2. Another solution is to always use the GUI version of Vim, called gvim. This avoids the need for a correct terminal setup.
Q: My Backspace And Delete Keys Don’t Work Right
The definition of what key sends what code is very unclear for backspace <BS> and Delete <Del> keys. First of all, check your $TERM setting. If there is nothing wrong with it, try this:
:set t_kb=^V<BS>
:set t_kD=^V<Del>
In the first line you need to press CTRL-V and then hit the backspace key.
In the second line you need to press CTRL-V and then hit the Delete key.
You can put these lines in your vimrc file, see 05.1. A disadvantage is that it won’t work when you use another terminal some day. Look here for alternate solutions: :fixdel.
Q: I Am Using RedHat Linux. Can I Use the Vim That Comes with the System?
By default RedHat installs a minimal version of Vim. Check your RPM packages for something named Vim-enhanced-version.rpm and install that.
Q: How Do I Turn Syntax Coloring On? How Do I Make Plugins Work?
Use the example vimrc script. You can find an explanation on how to use it here: not-compatible.
See chapter 6 for information about syntax highlighting: usr_06.txt.
Q: What Is a Good vimrc File to Use?
See the http://www.vim.org Web site for several good examples.
Q: Where Do I Find a Good Vim Plugin?
See the Vim-online site: http://vim.sf.net. Many users have uploaded useful Vim scripts and plugins there.
Q: Where Do I Find More Tips?
See the Vim-online site: http://vim.sf.net. There is an archive with hints from Vim users. You might also want to search in the maillist-archive.
90.5 Uninstalling Vim
In the unlikely event you want to uninstall Vim completely, this is how you do it.
UNIX
When you installed Vim as a package, check your package manager to find out how to remove the package again.
If you installed Vim from sources you can use this command:
make uninstall
However, if you have deleted the original files or you used an archive that someone supplied, you can’t do this. Do delete the files manually, here is an example for when /usr/local was used as the root:
rm -rf /usr/local/share/vim/vim82
rm /usr/local/bin/eview
rm /usr/local/bin/evim
rm /usr/local/bin/ex
rm /usr/local/bin/gview
rm /usr/local/bin/gvim
rm /usr/local/bin/gvim
rm /usr/local/bin/gvimdiff
rm /usr/local/bin/rgview
rm /usr/local/bin/rgvim
rm /usr/local/bin/rview
rm /usr/local/bin/rvim
rm /usr/local/bin/rvim
rm /usr/local/bin/view
rm /usr/local/bin/vim
rm /usr/local/bin/vimdiff
rm /usr/local/bin/vimtutor
rm /usr/local/bin/xxd
rm /usr/local/man/man1/eview.1
rm /usr/local/man/man1/evim.1
rm /usr/local/man/man1/ex.1
rm /usr/local/man/man1/gview.1
rm /usr/local/man/man1/gvim.1
rm /usr/local/man/man1/gvimdiff.1
rm /usr/local/man/man1/rgview.1
rm /usr/local/man/man1/rgvim.1
rm /usr/local/man/man1/rview.1
rm /usr/local/man/man1/rvim.1
rm /usr/local/man/man1/view.1
rm /usr/local/man/man1/vim.1
rm /usr/local/man/man1/vimdiff.1
rm /usr/local/man/man1/vimtutor.1
rm /usr/local/man/man1/xxd.1
MS-WINDOWS
If you installed Vim with the self-installing archive you can run the uninstall-gui program located in the same directory as the other Vim programs, e.g. c:\vim\vim82. You can also launch it from the Start menu if installed the Vim entries there. This will remove most of the files, menu entries and desktop shortcuts. Some files may remain however, as they need a Windows restart before being deleted.
You will be given the option to remove the whole *vim directory. It probably contains your vimrc file and other runtime files that you created, so be careful.
Else, if you installed Vim with the zip archives, the preferred way is to use the uninstall program. You can find it in the same directory as the install program , e.g., c:\vim\vim82. This should also work from the usual install/remove software page.
However, this only removes the registry entries for Vim. You have to delete the files yourself. Simple select the directory vim\vim82 and delete it recursively. There should be no files there that you changed, but you might want to check that first.
The vim directory probably contains your vimrc file and other runtime files that you created. You might want to keep that.