Comprehensive Vim Tutorial Guide
Comprehensive Vim Tutorial Guide
The Vim
Tutorial and
Reference
By Steve Oualline
Table of Contents
Introduction.............................................................................................. 26
Chapter 1:Basic Editing............................................................................28
Chapter 2:Editing a Little Faster..............................................................42
Chapter 3:Searching.................................................................................59
Chapter 4:Text Blocks and Multiple Files.................................................69
Chapter 5:Windows and Tabs....................................................................83
Chapter 6:Basic Visual Mode....................................................................99
Chapter 7:Commands for Programmers.................................................111
Chapter 8:Basic Abbreviations, Keyboard Mapping, and Initialization
Files......................................................................................................... 148
Chapter 9:Basic Command-Mode Commands.........................................159
Chapter 10:Basic GUI Usage...................................................................168
Chapter 11:Dealing with Text Files.........................................................175
Chapter 12:Automatic Completion.........................................................192
Chapter 13:Autocommands.....................................................................202
Chapter 14:File Recovery and Command-Line Arguments.....................211
Chapter 15:Miscellaneous Commands....................................................226
Chapter 16:Cookbook..............................................................................232
Chapter 17:Topics Not Covered..............................................................247
Chapter 18:Complete Basic Editing........................................................260
Chapter 19:Advanced Searching Using Regular Expressions.................290
Chapter 20:Advanced Text Blocks and Multiple Files.............................309
Chapter 21:All About Windows, Tabs, and Sessions...............................335
Chapter 22:Advanced Visual Mode.........................................................351
Chapter 23:Advanced Commands for Programmers...............................363
Chapter 24:All About Abbreviations and Keyboard Mapping.................418
Chapter 25:Complete Command-Mode (:) Commands...........................427
Chapter 26:Advanced GUI Commands....................................................453
Chapter 27:Expressions and Functions...................................................487
Chapter 28:Customizing the Editor........................................................533
Chapter 29:Language-Dependent Syntax Options..................................563
Chapter 30:How to Write a Syntax File...................................................586
Appendix A: Installing Vim.....................................................................598
Appendix B: The <> Key Names.............................................................605
Appendix C: Normal-Mode Commands...................................................608
Appendix D: Command-Mode Commands...............................................633
Appendix E: Visual-Mode Commands.....................................................734
Appendix F: Insert Mode Commands......................................................738
Appendix G: Option List..........................................................................742
Introduction.......................................................................................................26
Copyright and License Information...............................................................26
Part I Tutorial........................................................................................... 27
Chapter 3:Searching..........................................................................................59
Simple Searches............................................................................................59
Search History...............................................................................................60
History Window..........................................................................................61
Searching Options..........................................................................................61
Highlighting...............................................................................................61
Incremental Searches................................................................................62
Searching Backward..................................................................................64
Reverse Search History..............................................................................64
Changing Direction........................................................................................65
Basic Regular Expressions.............................................................................66
The Beginning (^) and End ($) of a Line...................................................66
Match Any Single Character (.)..................................................................67
Matching Special Characters.....................................................................68
Regular Expression Summary....................................................................68
Script Files...................................................................................................157
Chapter 13:Autocommands.............................................................................202
Basic Autocommands...................................................................................202
Groups..........................................................................................................203
Events..........................................................................................................204
File Patterns.................................................................................................207
Nesting.........................................................................................................208
Listing Autocommands................................................................................208
Removing Commands..................................................................................209
Ignoring Events............................................................................................209
Chapter 16:Cookbook......................................................................................232
Character Twiddling....................................................................................232
Replacing One Word with Another Using One Command...........................232
Interactively Replacing One Word with Another.........................................233
Alternate Method.....................................................................................234
Moving Text.................................................................................................234
Copying a Block of Text from One File to Another......................................235
Method 1: Two Windows with Traditional Vi-Style Commands...............235
Method 2: Two Windows Using Visual Mode...........................................236
Method 3: Two Different Vim Programs..................................................236
Sorting a Section.........................................................................................237
Sorting the old Vi way:.............................................................................239
Finding a Procedure in a C Program...........................................................239
Drawing Comment Boxes.............................................................................240
Reading a UNIX man Page...........................................................................241
Trimming the Blanks off an End-of-Line......................................................242
Oops, I Left the File Write-Protected...........................................................243
Changing Last, First to First Last................................................................243
How to Edit All the Files that Contain a Given Word..................................245
Finding All Occurrences of a Word Using the Built-in Search Commands. 246
Part II Reference.....................................................................................259
Scrolling Up Summary.............................................................................270
Scrolling Down.............................................................................................271
Define How Much to Scroll..........................................................................272
Adjusting the View.......................................................................................272
Delete to the End of the Line.......................................................................275
The C Command...........................................................................................275
The s Command...........................................................................................275
The S Command...........................................................................................276
Deleting Text................................................................................................276
Insert Text at the Beginning or End of the Line..........................................277
Arithmetic....................................................................................................277
Joining Lines with Spaces............................................................................278
Replace Mode..............................................................................................279
Virtual Editing..............................................................................................280
Replace Mode...........................................................................................281
Digraphs.......................................................................................................282
Changing Case.............................................................................................282
Other Case-Changing Commands................................................................283
Advanced Undo............................................................................................284
Undo Time Machine.................................................................................284
Undo Level...............................................................................................284
Change Sets and Branching.....................................................................285
Getting Out..................................................................................................288
Smart Tabs...............................................................................................368
Using a Different Tab Stop.......................................................................370
No Tabs....................................................................................................370
The 'copyindent' and 'preserveindent' Options........................................371
The :retab Command................................................................................371
Modelines.................................................................................................372
Shift Details.................................................................................................372
Specifying a Formatting Program................................................................373
Formatting Comments.................................................................................373
Defining a Comment....................................................................................374
Customizing the C Indentation....................................................................376
The 'cinoptions' Options...........................................................................377
The 'cinwords' Option..............................................................................383
Advanced Diff Mode.....................................................................................383
Moving from difference to difference......................................................384
Moving Differences Around.....................................................................384
Customizing Diff.......................................................................................385
Comparing Two Files The Old Fashioned Way.............................................385
Advanced Folding.........................................................................................387
Additional fold commands........................................................................389
Toggling folds...........................................................................................390
Enabling and disabling folding................................................................390
Moving around folds................................................................................390
Executing a command for all folds...........................................................390
Customizing folds.....................................................................................390
Controlling what opens and closes folds..................................................391
Fold Methods............................................................................................391
The Preview Window...................................................................................392
Match Options..............................................................................................394
Showing Matches.........................................................................................394
Finding Unmatched Characters...................................................................395
Method Location..........................................................................................396
Movement....................................................................................................396
Comment Moves.......................................................................................396
Dealing with Multiple Directories................................................................397
The include Path.......................................................................................399
Checking the Path....................................................................................400
Defining a Definition................................................................................402
Locating include Files..............................................................................402
Multiple Error Lists.....................................................................................403
Manipulating the quick fix list.....................................................................403
Local error lists........................................................................................404
Customizing the :make Command...............................................................406
The Error Format.....................................................................................407
Entering Commands....................................................................................492
How to Experiment..................................................................................493
The :echo Statement....................................................................................493
Echoing in Color.......................................................................................494
Printing error messages using :echoerr......................................................494
Echoing message.........................................................................................495
Control Statements......................................................................................495
The :if Statement......................................................................................495
Looping.....................................................................................................496
The :for Loop............................................................................................496
The :execute Command............................................................................497
Exceptions....................................................................................................497
Defining Your Own Function........................................................................499
Using a Function......................................................................................500
Function Options......................................................................................500
Listing Functions......................................................................................501
Deleting a Function..................................................................................502
Running Functions in a Sandbox.................................................................502
Debugging a Function..................................................................................502
Other debugging commands....................................................................505
Redrawing the screen..............................................................................506
Profiling a function......................................................................................506
Other Profile Commands..........................................................................508
Deleting Profile Items..............................................................................508
User-Defined Commands.............................................................................508
The Operator Function................................................................................510
Built-In Functions........................................................................................511
Obsolete Functions......................................................................................531
Plugins and other scripts.............................................................................531
Customizing Messages.................................................................................541
Showing the Mode.......................................................................................542
Showing Partial Commands.........................................................................542
Short Messages............................................................................................543
The 'terse' Option.........................................................................................544
The "File Modified" Warning........................................................................544
Error Bells....................................................................................................544
Status Line Format......................................................................................545
Rulers...........................................................................................................548
Reporting Changes......................................................................................548
Help Window Height....................................................................................549
Preview Window Height...............................................................................549
Defining How 'list' Mode Works...................................................................549
Changing the line number size....................................................................550
Changing the Highlighting..........................................................................550
The 'more' Option........................................................................................552
Number Format...........................................................................................552
Restoring the Screen...................................................................................552
Pasting Text..................................................................................................552
Wildcards.....................................................................................................553
Customizing Behavior of the Screen Movement Commands.......................557
File Writing Options.....................................................................................557
Memory Options...........................................................................................557
Function Execution Options.........................................................................557
Terminal Options..........................................................................................558
Terminal Name.........................................................................................558
Lazy Redraw.............................................................................................558
Internal Termcap......................................................................................558
Fast Terminals..........................................................................................558
Mouse Usage Inside a Terminal...............................................................558
How Much to Scroll..................................................................................559
Some More Obscure Options.......................................................................559
Compatibility............................................................................................559
Weirdinvert...............................................................................................560
Debugging................................................................................................560
Production....................................................................................................561
Keyboard Mapping.......................................................................................561
Encoding......................................................................................................562
Macintosh Silliness......................................................................................562
Obsolete Options..........................................................................................562
Legacy Options............................................................................................562
Ada...............................................................................................................563
Ant................................................................................................................564
Apache.........................................................................................................565
Assembly Language.....................................................................................565
ASP...............................................................................................................566
BaaN............................................................................................................566
Basic.............................................................................................................566
C and C++...................................................................................................566
Doxygen....................................................................................................569
CH................................................................................................................569
Chill..............................................................................................................569
Changelog....................................................................................................570
COBOL.........................................................................................................570
Cold Fusion..................................................................................................570
CSH / TCSH.................................................................................................570
CYNLIB........................................................................................................570
CWEB...........................................................................................................570
Desktop........................................................................................................570
Dircolors......................................................................................................571
DocBook.......................................................................................................571
DosBatch......................................................................................................571
Doxygen.......................................................................................................571
DTD..............................................................................................................571
Eiffel.............................................................................................................572
ERLANG.......................................................................................................572
FlexWiki.......................................................................................................573
Form.............................................................................................................573
Fortran.........................................................................................................573
FVWM..........................................................................................................573
Haskell.........................................................................................................574
HTML...........................................................................................................574
Inform..........................................................................................................574
IDL (Interface Definition Language)............................................................575
Java..............................................................................................................575
Lace..............................................................................................................576
Lex...............................................................................................................576
Lisp..............................................................................................................576
Lite...............................................................................................................576
LPC...............................................................................................................577
LUA..............................................................................................................577
Mail..............................................................................................................577
Make............................................................................................................577
Maple...........................................................................................................577
Mathematica................................................................................................578
Moo..............................................................................................................578
MSQL...........................................................................................................578
NCF..............................................................................................................578
Nroff.............................................................................................................579
OCAML.........................................................................................................579
Papp.............................................................................................................579
Pascal...........................................................................................................579
Perl...............................................................................................................580
Php3/ Php4...................................................................................................580
PlainTex........................................................................................................581
PPWizard......................................................................................................581
Phtml............................................................................................................581
PostScript.....................................................................................................581
Printcap and Termcap..................................................................................582
Progress.......................................................................................................582
Python..........................................................................................................582
Quake...........................................................................................................582
ReadLine......................................................................................................582
Rexx.............................................................................................................583
Ruby.............................................................................................................583
Scheme.........................................................................................................583
SDL..............................................................................................................583
Sed...............................................................................................................583
SGML...........................................................................................................584
Shell.............................................................................................................584
Speedup.......................................................................................................584
TCsh.............................................................................................................584
TeX...............................................................................................................584
TinyFugue....................................................................................................585
Vim...............................................................................................................585
XF86Config..................................................................................................585
Xml...............................................................................................................585
Introduction
I'm not sure this book is a labor of love or a love of labor. It certainly is the
longest book I've written. When I first started using Vim I noticed that there
were a “few” commands that Vim had that it's the old Vi editor didn't have. So I
decided to write a book which would serve as documentation to this wonderful
editor.
The goal of this book is to provide a tutorial to show the reader how to use
the power of Vim to solve common problems. Also the book attempts to show
you visually the operation of very major command and option, and to fully
document the rest.
Unfortunately, I've had to impose some limits on the book. This book does
not cover editing in any language but English mostly due to the fact that English
is the only language I know. Also it does not cover the interfaces to external
tools which I do not posses.
This book is copyrighted by Steve Oualline and published under the same
license. Basically what license states is that you can use the material in this book
for your own use as long as you give credit to the sources (this book and the
orginal Vim (Vi Improved) Book.)
A downloadable version of this book is available from the author's web site
([Link]
1 Part I
2 Tutorial
After you get these commands down pat, you can learn the more advanced
editing commands.
If you have not installed Vim, you need to read Appendix A: Installing Vim
and install the editor. (If Vim came with your Linux system, read Appendix A:
Installing Vim because you may not get the full editor by default.)
You also can enable the advanced features from within Vim at any time
with this command:
:set nocompatible
You can also use the command:
:set nocp
Note: Both these commands have an implied <enter> at the end. Also the
'compatible' option like most Vim options has a long form
('compatible') and a short form ('cp'). For clarity the long form is used in
the examples in this book.
~
~
~
~
~
"[Link]" [New File]
Figure 1-1: Initial Vim window.
The gvim command causes the editor to create a new window for editing.
If you use the command vim, 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 an MS-DOS command prompt window under Microsoft
Windows, the editing occurs inside the window. Figure 1-2 shows a typical
MS-DOS command prompt window.
Modes
The Vim editor is a modal editor. That means that the editor behaves
differently, depending on which mode you are in. If the bottom of the screen
displays the filename or is blank, you are in normal mode. If you are in insert
mode, the indicator displays --INSERT--; and if you are in visual mode, the
indicator shows --VISUAL--.
Inserting Text
To enter text, you need to be in insert mode. Type i, and notice that the
lower left of the screen changes to --INSERT-- (meaning that you are in insert
mode).
Now type some text. It will be inserted into the file. Do not worry if you
make mistakes; you can correct them later. Enter the following programmer's
limerick:
A very intelligent turtle
Found programming UNIX a hurdle
The system, you see,
Ran as slow as did he,
And that's not saying much for the turtle.
After you have finished inserting, press the <Esc> key. The --INSERT--
indicator goes away and you return to normal mode. (The indicator for this
mode is a blank indicator.) Your screen should now look something like Figure
1-3.
A very intelligent turtle
Found programming UNIX a hurdle
The system, you see,
Ran as slow as did he,
And that's not saying much for the turtle.
~
~
~
~
Figure 1-3: Screen after the text has been inserted.
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.
Moving Around
After you return to normal mode, you can move around by using these
keys: h (left), j (down), k (up), and 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, there 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.
Note You can also 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. If you want to edit efficiently, use h, j, k,
and l.
Also, there are keyboards which do not have arrow keys, or which locate
them in unusual places; therefore, knowing the use of these keys helps in
those situations.
h l
j
commands is to copy this information on a Post-It Note and put it on the edge of
your monitor until you get used to these commands. (A quick reference for
novices can be found in Appendix I: Basic Vim Quick Reference.)
Aliases
The alias for the h command include <Left>, <BS>, CTRL-H and CTRL-K.
The aliases for j are <Down>, <NL>, CTRL-J, and CTRL-N. For k we have <Up>
and CTRL-P. Finally for l we can also use <Right> and <Space>.
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 the first seven characters on the line.
Figure 1-4 shows the result. To enter a correction, type iA young <Esc>. This
begins an insert (the i), inserts the words A young, and then exits insert mode
(the final <Esc>). Figure 1-5 shows the results.
intelligent turtle
Found programming UNIX a hurdle
The system, you see,
Ran as slow as did he,
And that's not saying much for the turtle.
~
~
~
~
Figure 1-4: Screen after delete (xxxxxxx).
A young intelligent turtle
Found programming UNIX a hurdle
The system, you see,
Ran as slow as did he,
And that's not saying much for the turtle.
~
~
~
~
Figure 1-5: Note Result of the insert.
Note: Vim is a text editor. By default, it does not wrap text. If you type
past the edge of the screen, the line will appear to wrap, but what you
really have is a long line wrapped so that Vim can display it. If you want
multiple lines you must end each line by pressing the <Enter> key. If you
don't and just keep typing when you reach the right margin, all you will do
is insert a very long line into the editor. You will not automatically go to
the next line. To do so, you need to press the <Enter> key. (This is the
default mode of operation. You can configure the Vim editor to word wrap,
however, as discussed in Chapter 11: Dealing with Text Files)
Note: If you are an old Vi user, note that the multilevel undo of Vim differs
significantly from the single level available to a Vi user.
Note: Throughout this book we assume that you have turned off Vi
compatibility. See the first section of this chapter for more information. If
compatibility is turned on the u command provides one level of undo.
Lets see how the U command works. We'll start with the line:
A very intelligent turtle
Type xxxxx to delete “very<space>”.
A intelligent turtle
Move over to the “t” in “turtle and delete “turtle” with the command xxxxx.
A intelligent
Restore line with the U command.
A very intelligent turtle
Second U undoes the preceding U.
A intelligent
Getting Out
To exit, use the ZZ command. This command writes the file (if modified)
and exits. 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, as discussed in
Chapter 14: File Recovery and Command-Line Arguments)
Discarding Changes
Sometimes you will make a set of changes and suddenly realize you were better
off before you started. Don't worry; Vim has a "quit-and-throw-things-away"
command. It is :q!. For those of you interested in the details, the three parts of
this command are the colon (:), which enters command 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. Because this is a command mode command, you need to type <Enter>
to finish it. (All command mode commands have <Enter> at the end. This is not
shown in the text.) If you were to just type :q, Vim would display an error
message and refuse to exit:
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'm a big boy and really want to do this."
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.
Deleting a Line
To delete a line, use the dd command, which deletes the line on which the
cursor is positioned. To delete the middle line of this example, for instance,
position the cursor anywhere on the line The system, you see, as shown in
Figure 1-6. Now type dd. Figure 1-7 shows the results.
A very intelligent turtle
Found programming UNIX a hurdle
The system, you see,
Ran as slow as did he,
And that's not saying much for the turtle!!!
~
~
~
Figure 1-6: Screen before dd command.
To add a new line, use the o (lower case)command to open up a new line
below the cursor. The editor is then placed in insert mode.
Suppose, for example, that you want to add a line to the sample text just
below the third line. Start by leaving the cursor on the Ran as slow. . . line,
as seen in Figure 1-7. Now type o to open up a new line. Enter the text for the
line and then press <Esc> to end insert mode. Figure 1-8 shows the results. If
you want to open a line above the cursor, use the O (uppercase) command.
A very intelligent turtle
Found programming UNIX a hurdle
Ran as slow as did he,
Help
Finally, there's one more important command, the :help (:h, <F1>, <Help>)
command. To get help, enter the following:
:help
(Remember the implied <Enter> for command-mode commands.) This
displays a general help window, as seen in Figure 1-9.
Jump to a subject: Position the cursor on a tag between |bars| and hit CTRL-].
With the mouse: ":set mouse=a" to enable the mouse (in xterm or GUI).
Double-click the left mouse button on a tag between |bars|.
Jump back: Type CTRL-T or CTRL-O (repeat to go further back).
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, k, j, and l
move left, up, down, right, and so on.
To get out of the help system, use the same command you use to get out of
the editor: ZZ.
As you read the help text, you will notice some text enclosed in vertical
bars (for example, |:help|). If you are using the GUI this text is colored cyan.1
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.)
1 It's still enclosed in vertical bars but they are colored white, the same color as the background
which makes them very hard to see.
After a few jumps, you might want to go back. CTRL-T (pop tag) takes you
back to the preceding screen. Or in Vim terms, it "pops a tag off the tag stack."
At the top of this screen, there is the notation *[Link]*. This is used by the
help system to define a tag (hyperlink destination). Chapter 7: Commands for
Programmers explains tags in detail. 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 what is available, 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 this command, prefix the key with i_.This gives you the
following command:
:help i_CTRL-H
The table below lists several other mode prefixes.
When you start the Vim editor, you can use several command-line options.
These all begin with a dash (-).To find what the -t command-line option 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'
Special keys are enclosed in angle brackets. To find help on the up-arrow
key, for instance, use this command:
:help <Up>
Appendix B: The <> Key Names provides a complete list of the key names.
Help Language
By default Vim will set the language for the help file to the current
language of your system. (From the locale settings.) If you wish to use another
language, use the 'helplang' ('hlg') option. This option contains a series of
languages to search for help text.
So to search for help in German, Italian, and then English use the
command:
:set helplang=de,it
You can get to the help screen by pressing the <F1> key. This displays the
general help screen, and you can navigate from there. If your keyboard has a
<Help> key, you can use it as well.
Summary
You now know enough to edit with Vim. Not well or fast, but you can edit.
Take some time to practice with these commands before moving on to the next
chapter. After you absorb these commands, you can move on to the more
advanced commands that enable you to edit faster and easier.
● Digraphs
One of the things I noticed as I wrote this chapter is the amazing number
of different ways you can move through a file. Although I have been using Vi and
now Vim as my main editor for the past 15 years, I have never bothered to learn
all of them. I get by with the 10% I like.
There are lots of different ways of doing things in Vim. This chapter
discusses one useful selection of all the possible commands.
Word Movement
Let's start with movement. To move the cursor forward one word, use the w
command. The b command moves backward one word. Like most Vim
commands, you can use a numeric prefix to move past multiple words. For
example, 4b moves back four words. Figure 2-1 shows how these commands
work.
w w w 2w 3w
4b b
Figure 2-1: Word movement.
The ^ command moves to the first nonblank character of the line. The
<Home> or <kHome> key moves to the first character of the line, as seen in Figure
2-3. (The 0 [zero] command does the same thing.) Like every other command
previously discussed, these commands (except 0 [zero]) can take a numeric
argument. They do not do anything with it, but you can specify it if you want to.
<Home>
<kHome>
Figure 2-3: The ^ and <Home> commands.
fi fl 2fo 3fe
2Fa Fy
Figure 2-4: Operation of the f and F commands
The tx (search `til) command works like the fx command, except it stops
one character before the indicated character. The backward version of this
command is Tx. Figure 2-5 shows how these commands work.
ti tl 2to 3te
2Ta Ty
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 abort a search, press <Esc> as the search key. So
f<Esc> is an aborted forward search. (Note: <Esc> cancels most operations, not
just searches.)
Another way to move through the file is with the % command. The 50%
command moves you through the file, 25% a quarter, 90% ninety percent, etc. (%
by itself finds the matching {} which is a different command.)
Note: These line numbers are for your information only; they are not
written into the file when you exit.
The Vim editor is highly configurable and has a huge number of options.
You can use the :set command in many different ways, which are described in
Chapter 28: Customizing the Editor. The 'number' option is a boolean option,
meaning that it can be on or off. To turn it on, use this command:
:set number
To turn it off, use this command:
:set nonumber
The numbers disappear from your screen. Figure 2-7 shows what happens
we you do a :set nonumber.
Ode to a maintenance programmer
===============================
****
Figure 2-7 Results of :set nonumber.
Where Am I?
The CTRL-G command displays a status line that indicates where you are in
the file. For example:
"[Link]" [Modified] line 81 of 153 --52%-- col 1
This indicates that you are editing a file called [Link], and that it has been
modified since the editing started. The cursor is positioned on line 81 out of a
total of 153, or about 52% of the way through the file. The cursor is currently
sitting in column 1.
Sometimes you will see a split column number (for example, col 2-9).This
indicates that the cursor is positioned on character 2. But because character
one is a tab, the screen column is 9. Figure 2-8 shows the results of a typical
CTRL-G command.
CTRL-U
A dozen, a gross, and a score, 101 blocks of crud on the disk! ...
Plus three times the square root of four,
Divided by seven, -----
Plus five time eleven,
Equals nine squared plus zero, no more. A dozen, a gross, and a score,
Plus three times the square root of four,
---- Divided by seven,
Plus five time eleven,
I really hate this damned machine Equals nine squared plus zero, no more.
A dozen, a gross, and a score, Equals nine squared plus zero, no more.
Plus three times the square root of four,
Divided by seven, ----
3 Plus five time eleven,
Equals nine squared plus zero, no more. I really hate this damned machine
I wish that they would sell it.
---- It never does quite what I want
But only what I tell it.
I really hate this damned machine
CTRL-D
Deleting Text
As you learned in Chapter 1: Basic Editing, the dd command deletes a line.
But suppose you want to delete part of a line, say a word. The way to do that is
to start visual mode with the v command. You can now highlight the text you
want to delete with the cursor movement commands. We want to delete a word,
so we pass over it with the w command. Unfortunately this leaves us with the
cursor positioned on the first character of the next word. We don't want to
delete that so we backup with the left (h) command.
Finally we need to tell Vim what to do with the text, so we enter the d
command to delete it. Figure 2-10 shows the steps we used:
This is a test Type v to start visual.
Press d to delete
This a test.
Figure 2-10: Visual mode and delete
Note: To get help about what the delete (d) command does in visual mode
use the command:
:help v_d
As we will see in future sections the visual mode gives you a very powerful
way of dealing with large blocks of text.
It is possible to delete sections of text without using the visual mode. The
advantage of doing things non-visually is that you save a single keystroke. The
disadvantage is that you really have to know what you are doing as there is no
visual feedback to show you what's going on.
To delete a word in normal mode you use the command dw. You may
recognize 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. (Therefore, we say the syntax
of the d command is dmotion.)
The 3w command, for example, moves the cursor over three words. The
d3w command deletes three words, as seen in Figure 2-11. (You can write it as
d3w or 3dw; both versions work the same.)
The $ command moves to the end of a line. The d$ command deletes from
the cursor to the end of the line, as seen in Figure 2-12. A shortcut for this is the
D command.
The commands 3dw and d3w delete three words. If you want to get really
picky 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).
This command deletes two words, repeated three times, for a total of six words.
The visual method of deleting things lets you see exactly what you are
going to delete before you delete it. You can also make adjustments before you
delete the text. This makes things much easier for large complex deletes.
On the other hand, the normal mode delete provides no feedback. You type
d and a motion command and hope you did the right thing. (If you didn't there's
always the undo command.) The advantage of the normal mode method of doing
things is that it's quicker for small amounts of text, especially when you know
where the motion command is going to send the cursor. In other words if you
have to delete three words, d3w is probably what you want to use. But if you
have to delete 57 words (maybe 57 you're not sure) the v<move>d is better.
Changing Text
The c command changes text. It acts just like the d command, except it
leaves you in insert mode. For example, if you go into visual mode (v) highlight a
word (w) and then press c, the word will disappear and you'll be left in insert
mode.
The normal mode version of the c command acts like the d command
except that 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. Figure
2-14 illustrates how this command works.
There is a saying that for every problem there is an answer that's simple,
clear, and wrong. That is the case with the example used here for the cw
command. The cmotion command works just like the dmotion command, with
one exception: the cw and dw commands. Whereas cw deletes the text up to the
space following the word (and then enters insert mode), the dw command deletes
the word and the space following it.
a word (w)
cwscrew <Esc>
c – Change
w – Word (the motion)
screw<blank> (text)
<Esc> - End insert
Figure 2-14: How cw works.
The cc command works on the entire line. That is, it deletes the line and
then goes into insert mode. In other words, cc works on the current line just like
dd. Likewise, c$ or C change from the cursor to the end of the line.
The . Command
The . command is one of the most simple yet powerful commands in Vim. It
repeats the last delete or change command. 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 kill 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 press the . command. Figure 2-15 illustrates how this can
work.
1. Start here
2. f< --find "<" of <B>
3. df>-- delete to ">" 5. f< --find "<" of "</B>"
6. . --repeat last change (df>)
<P>
To <B>generate</B> a table of contents
all the C <B>program</B> files in your
current working directory, use the
<B>command</B>:
<PRE>
$<B> ctags *.c</B>
</PRE>
7. j -- Next line
8. ^ -- Start of line
9. f< --find "<" of "<B>"
10. . --repeat last change (df>)
11. f< --find "<" of </B>
912 . --repeat last change (df>)
Joining Lines
To join a set of lines in visual mode, start visual mode (v) highlight the lines
you wish to join, and press J. All the highlighted lines will be put together in
one big line. A space is placed between the pieces that are joined as seen in
Figure 2-16. (If there is no space it is added. If there is one space, it is
preserved. If there are multiple spaces, they are turned into on.)
In normal mode, the J command joins the current line with the next one. ,
as illustrated by Figure 2-17. If a count is specified, then count lines are joined
(minimum of two).
This is a test
This is
a test J
Replacing Characters
The r{char} command replaces the character under the cursor with
{char}. Figure 2-18 shows how you can use the r command to replace a z with
an s. The r command can be preceded with a count, indicating the number of
characters to be replaced. In Figure 2-19, we go to the beginning of line (the ^
command) and execute 5ra to replace the first five characters with a.
This iz a test.
rs
This is a test.
Figure 2-18: The replace (r) command.
This is a test.
5ra
aaaaais a test.
Figure 2-19: Replace (r) command with count.
Note: The r command treats <Enter> in a special way. No matter how big
the count is, only one <Enter> is inserted. Therefore, 5ra inserts five a
characters, whereas 5r<Enter> replaces five characters with one <Enter>.
Be careful where you place the count. The 5rx command replaces five
characters with the character x, whereas r5x replaces the character under the
cursor with 5 (r5) and then deletes a character (x).
Changing Case
The ~ command changes a character's case. It changes uppercase to
lowercase and vice versa. If a count is specified, the count characters are
changed. Figure 2-20 contains examples.
now is the time. . . . now is the time . .
.
~ 6~
Keyboard Macros
The . command repeats the preceding change. But what if you want to do
something more complex than a single change? That's where the keyboard
macros come in. The q{character} command records keystrokes into the
register named character. (The character must be between a and z.) To finish
recording, just type a q command. You can now execute the macro by typing the
@{character} command. (This can be preceded by a count, which will cause the
macro to be executed that number of times.)
Take a look at how to use these commands in practice. You have a list of
filenames that look like this:
stdio.h
fcntl.h
unistd.h
stdlib.h
And what you want is the following:
#include "stdio.h"
#include "fcntl.h "
#include "unistd.h"
#include "stdlib.h"
You start by moving to the first character of the first line. Next you execute
the following commands:
Command Description
qa Start recording a macro in register a
^ Go to beginning of the line
i#include “<Esc> Insert the text #include “
$ Go to the end of line
a”<Esc> Append the character “ after the cursor.
j Go to the next line
q Quit recording
Now that you have done the work once, you can repeat the change by
typing the command @a. Alternatively, because you have three lines to go, you
can change them using the command 3@a. Figure 2-21 shows how to define and
then execute a macro.
stdio.h Start
fcntl.h
unistd.h
stdlib.h
Digraphs
Some characters are not on the keyboard--for example, the copyright
character (©). To type these letters in Vim, you use digraphs, where two
characters represent one. To enter a ©, for example, you type CTRL-KcO (Capital
letter “O”). To find out what digraphs are available, use the following command:
:digraphs
Note: :dig is the same as :digraphs
The Vim editor will display the digraph-mapping table, as seen in Figure
2-22. This shows, for example, that the digraph you get by typing CTRL-KCt is
the character (¢).This is character number 162.
Warning: The digraphs are set up assuming that you have a standard
ISO-646 character set. Although this is an international standard, your
particular display or printing system might not use it.
:digraphs
NU ^@ 10 SH ^A 1 SX ^B 2 EX ^C 3 ET ^D 4 EQ ^E 5 AK ^F 6
BL ^G 7 BS ^H 8 HT ^I 9 LF ^@ 10 VT ^K 11 FF ^L 12 CR ^M 13
SO ^N 14 SI ^O 15 DL ^P 16 D1 ^Q 17 D2 ^R 18 D3 ^S 19 D4 ^T 20
NK ^U 21 SY ^V 22 EB ^W 23 CN ^X 24 EM ^Y 25 SB ^Z 26 EC ^[ 27
FS ^\ 28 GS ^] 29 RS ^^ 30 US ^_ 31 SP 32 Nb # 35 DO $ 36
At @ 64 <( [ 91 // \ 92 )> ] 93 '> ^ 94 '! ` 96 (! { 123
!! | 124 !) } 125 '? ~ 126 DT ^? 127 PA ~@ 128 HO ~A 129 BH ~B 130
NH ~C 131 IN ~D 132 NL ~E 133 SA ~F 134 ES ~G 135 HS ~H 136 HJ ~I 137
VS ~J 138 PD ~K 139 PU ~L 140 RI ~M 141 S2 ~N 142 S3 ~O 143 DC ~P 144
P1 ~Q 145 P2 ~R 146 TS ~S 147 CC ~T 148 MW ~U 149 SG ~V 150 EG ~W 151
SS ~X 152 GC ~Y 153 SC ~Z 154 CI ~[ 155 ST ~\ 156 OC ~] 157 PM ~^ 158
AC ~_ 159 NS | 160 !I ¡ 161 Ct ¢ 162 Pd £ 163 Cu ¤ 164 Ye ¥ 165
BB ¦ 166 SE § 167 ': ¨ 168 Co © 169 -a ª 170 << « 171 NO ¬ 172
-- - 173 Rg ® 174 'm ¯ 175 DG ° 176 +- ± 177 2S ² 178 3S ³ 179
'' ´ 180 My µ 181 PI ¶ 182 .M · 183 ', ¸ 184 1S ¹ 185 -o º 186
>> » 187 14 ¼ 188 12 ½ 189 34 ¾ 190 ?I ¿ 191 A! À 192 A' Á 193
A> Â 194 A? Ã 195 A: Ä 196 AA Å 197 AE Æ 198 C, Ç 199 E! È 200
E' É 201 E> Ê 202 E: Ë 203 I! Ì 204 I' Í 205 I> Î 206 I: Ï 207
D- Ð 208 N? Ñ 209 O! Ò 210 O' Ó 211 O> Ô 212 O? Õ 213 O: Ö 214
*X × 215 O/ Ø 216 U! Ù 217 U' Ú 218 U> Û 219 U: Ü 220 Y' Ý 221
TH Þ 222 ss ß 223 a! à 224 a' á 225 a> â 226 a? ã 227 a: ä 228
aa å 229 ae æ 230 c, ç 231 e! è 232 e' é 233 e> ê 234 e: ë 235
-- More --
Chapter 3: Searching
This chapter introduces you to the various Vim search commands. The
basic search commands in Vim are rather simple, which means that you can get
started with searching fairly easily. In this chapter, you learn about the
following:
● Search options
● Incremental searches
● Changing directions
Simple Searches
To search for a string, use the /string command. To find the word
include, for example, use the command /include. An <Enter> is implied at the
end of this command. (Any time the cursor jumps to the bottom of the screen
and you type something, you must end it with <Enter>.)
/********************************************************
* cd-speed *
* Report the speed of a cd-rom *
* (Also works on hard drives and other *
* devices) *
* *
* Usage: *
* cd-speed <device> *
* *
********************************************************/
#include <iostream.h>
#include <iomanip.h>
/include
To find the next include, use the command /<Enter>.The cursor now
moves to the next occurrence of the string, as shown by Figure 3-2.
/********************************************************
* cd-speed *
* Report the speed of a cd-rom *
* (Also works on hard drives and other *
* devices) *
* *
* Usage: *
* cd-speed <device> *
* *
********************************************************/
#include <iostream.h>
#include <iomanip.h>
/include
Another way to find the next match is with the n command. This command
does the same thing as /<Enter>, but does it with one less keystroke.
Both the /<Enter> and n commands can have a count specified. If there is
a count, the command searches for the count number of matches from the
current location.
Search History
The search command has a history feature. Suppose, for example, that you
do three searches:
/one
/two
/three
If you do not press <Enter>, but press <Up> instead, Vim changes the
prompt to /two. Another <Up> command moves you to /one. In other words,
after you do a number of searches, you can use the <Up> and <Down> keys to
select one of your recent searches.
History Window
If you execute the command q/, Vim will open up a search history window.
See Figure 3-3.
~
~
~
[No Name] [+] 1,2 All
/one
/two
/three
command-line 51,0-1 Bot
/
Figure 3-3: Search History Window
Most of the normal editing commands work within this window. When you
find the search you want (or create it in the editor), press <Enter> to execute the
search. If you wish to abort the search and return to command mode, use the ZZ
or :q commands.
If you wish to abort everything :qall will close both the search history
window and everything else.
Searching Options
Many different options control the way you perform a search. This section
discusses a few of them.
Highlighting
If you turn on this option and then search for include, for example, all the
include strings are highlighted, as seen in Figure 3-4. To turn off search
highlighting, use this command:
:set nohlsearch
To clear the current highlighting, use the following command:
:nohlsearch
Search highlighting is now turned off; matched text will not be highlighted.
However, the highlighting will return when you use a search command.
* devices) *
* *
* Usage: *
* cd-speed <device> *
* *
********************************************************/
#include <iostream.h>
#include <iomanip.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
Figure 3-4 The 'hlsearch' option.
Incremental Searches
By default, Vim uses the traditional search method: You specify the string,
and then Vim performs the search. When you use the following command, the
editor performs incremental searches:
:set incsearch
The editor starts searching as soon as you type the first character of the
string. Each additional character further refines the search.
Suppose, for example, that you want to search for ioctl.h, but this time
you want to use an incremental search. First, you turn on incremental
searching. Next, you start the search by typing the /i command. Figure 3-5
shows how the editor searches for the first i and positions the cursor on it.
* devices) *
* *
* Usage: *
* cd-speed <device> *
* *
********************************************************/
#include <iostream.h>
#include <iomanip.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
Figure 3-5: Results after /i.
You continue the search by typing an o. Your search now is /io, so the
editor finds the first io, as seen in Figure 3-6. This is still not the place you
want, so you add a c to the search, resulting in the /ioc command. The Vim
editor advances, as illustrated in Figure 3-7, to the first match of ioc. This is
what you want to find, so you press <Enter>, and you're there.
* devices) *
* *
* Usage: *
* cd-speed <device> *
* *
********************************************************/
#include <iostream.h>
#include <iomanip.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
Figure 3-6: Incremental search after /io.
* devices) *
* *
* Usage: *
* cd-speed <device> *
* *
********************************************************/
#include <iostream.h>
#include <iomanip.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
Figure 3-7: Incremental search after /ioc.
Searching Backward
Like forward search (?) you can use the <Up> and <Down> keys to go
through the search history. You can also open a search history for reverse
searches with the command q?.
Changing Direction
Suppose you start a forward search for unsigned using the /unsigned
command. You can turn around and search in the reverse direction by using the
? Command. The n command repeats the search in the same direction. The N
command reverses the direction on the search and repeats it. To make things a
little clearer, line numbering has been turned on using the following command:
:set number
In this example, we use the following search commands:
Command Meaning Result
/unsigned Meaning Forward search for unsigned. Line 24
n Repeat search in the same (forward) direction. Line 26
n Search again. Line 29
? Reverse search Line 26
N Change search direction (reverse -> forward) and Line 29
repeat search.
Figure 3-9 shows the /unsigned command used to perform a search. The n
command was used twice to go the next occurrences of the string. Then we
reversed course with a ? command (which always goes backward.) Finally, we
reverse course again with the N command. Figure 3-9 shows this tortured path.
19 #include <sys/fcntl.h>
/unsigned 20 #include <sys/time.h>
21 #include <errno.h>
n 22
n 23 // Read at most 10MB
? 24 const unsigned int MAX_READ = 10
N 25 // Size of a buffer
26 const unsigned int BUF_SIZE = 62
27
28 // Buffer to be written
29 static unsigned char buffer[BUF_SIZE];
:set number
Figure 3-9: Different kinds of search commands.
The $ character matches the end of a line. Therefore, was$ finds the word
was only if it is at the end of a line. Figure 3-10, for example, shows a search for
the pattern the with highlighting enabled.
<Hl> Dumb user tricks
At one university the computer center was experience
trouble with a new type of computer terminal. Seems
that the professors loved to put papers on top of
the equipment, covering the ventilation holes. Many
terminals broke down because they became so hot that
the solder holding one of the chips melted and the
chip fell out.
The student technicians were used to this problem. One
day a technician took the back off a terminal
/the
Figure 3-10: Searching for the.
Next you see what happens when searching for the regular expression
^the. The results, as seen in Figure 3-11, show that only two occurrences, both
of which begin lines, are highlighted. Finally a search for the$. As you can see
from Figure 3-12, only one the ends a line. If you want to search for a line
consisting of just the word the, use the regular expression ^the$. To search for
empty lines, use the regular expression ^$.
The character . matches any single character. For example, the expression
c.m matches a string whose first character is a c, whose second character is
anything, and whose third character is m. Figure 3-13 shows that the pattern
matched the com of computer and the cam of became.
Note: The following list assumes that the 'magic' option is on (the
default). (See The 'magic' Option on page 304 for information on this
option.)
Character Meaning
x The literal character x
^ Start of line
$ End of line
, A single character
\x Turns off the special meaning of many characters, gives special
meaning to a few others
With most editors, you can just cut and paste. However, the Vim editor has
the concept of a register. This enables you to hold data for multiple cut, copy, or
paste operations. Most other editors are limited to a single cut/paste clipboard.
With the Vim registers you get more than 26 clipboards.
Up until now, you have worked with single files in this book. You will now
start using multiple files. This will enable you to perform the same edits on a
series of files, and to cut and paste between files.
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 pressing dd. Now you move
the cursor to where you want to place the line and use the p (put) command. The
line is inserted on the line following the cursor. Figure 4-1 shows the operation
of these commands.
Because you deleted an entire line, the p command placed the text on the
line after the cursor. If you delete part of a line (a word with the dw command,
for instance), the p command puts it just after the character under the cursor
(see Figure 4-2).
We will delete the word in the middle.
Character Twiddling
Frequently when you are typing, your fingers get ahead of your brain. The
result is a typo such as teh for the. The Vim editor makes it easy to correct such
problems. Just put the cursor on the e of teh and execute the command xp.
Figure 4-3 illustrates this command. This works as follows:
x Deletes the character e and places it in a register.
p Puts the text after the cursor, which is on the h.
teh
x – delete character
th
the
Figure 4-3: Character twiddling with xp.
More on "Putting"
You can execute the p command multiple times. Each time, it inserts
another copy of the text into the file. The p command places the text after the
cursor. The P command places the text before the cursor. A {count} can be
used with both commands and, if specified, the text will be inserted {count}
times.
3. Move the line just before where you want to insert the block.
4. Execute p to “put” the block on the line after the one the cursor is on.
This works great if you know the exact number of lines you wish to move.
However for me, any text block larger than three lines confuses me. This
method of moving text is impractical for such large text blocks.
Fortunately we have visual mode. We can start line visual mode with the V
(upper case) command. This is like the simple visual mode (v) we've used before,
only it works only on entire lines.
5. Move the line just before where you want to insert the block.
6. Execute p to “put” the block on the line after the one the cursor is on.
Figure 4-4 shows how this works. The major advantage of moving text
using this method is that you don't have to count and you can tell exactly what
text is going to be moved before you move it.
4
Line 1 Line 1 j Line 1 d Line 1 j Line 1 p
Line 2V Line 2 Down Line 4 Delete Line 4 Down Line 4 Put
Line 3 Visual Line 3 One Line 5 Line 5 Line Line 5
Line 4 Line Line 4 Line 2
Line 5 Line 5 Line 3
Figure 4-4: Moving a block of text visually.
Marks
The Vim editor enables you to place marks in your 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 use a number of other special marks as well.)
The `{mark} command can be very useful when deleting a long series of
lines. To delete a long series of lines, follow these steps:
1. Move the cursor to the beginning of the text you want to delete.
2. Mark it using the command ma. (This marks it with mark a.)
Note:There is nothing special about using the a mark. Any mark from a to
z may be used.
There is nothing special about doing the beginning first followed by the
end. You could just as easily have marked the end, moved the cursor to the
beginning, and deleted to the mark.
One nice thing about marks is that they stay with the text even if the text
moves (because you inserted or deleted text above the mark. Of course, if you
delete the text containing the mark, the mark disappears.
The display shows the location of the marks a through d as well as the
special marks: `, ", [, and ]. Marks a through d are located at lines 1, 8, 14, and
25 in the file.
Yanking
For years, I used a simple method for copying a block of text from one
place to another. I deleted it using the d command, restored the deleted text
with the p command, and then went to where I wanted the copy and used the p
to put it into the text.
There is a better way. The y command "yanks" text into a register (without
removing it from the file). (Every other editor calls this a “copy”.)
To yank visually you start visual mode with v, highlight the text you wish to yank
and yank it with y. Figure 4-6 shows how this works.
To error is human. Default register:
To really foul up you
need a computer. To really foul up you
To keep things fouled up y moves text into need a computer.
you need government. the default register To keep things fouled up
Figure 4-6: Yanking text.
Take a look at how you can use the yank (y) command along with the mark
command (m) to duplicate a block of text. First go to the top of the text to be
copied and mark it with ma. Then go to the bottom and do a y'a (yank to mark
a). Now go to where the copied text is to be inserted and put it there using the p
command. Figure 4-7 shows these commands in action.
Line 1 Line 1
Line 2 (ma line) Line 2 (ma line)
Line 3 Line 3
Line 4 (y'a done here) Line 4 (y'a done here)
Line 5 Line 5
Line 6 Line 6
Line 7 2) Go to line 4 Line 7
~ ~
~ ~
~ ~
~ ~
~ ~
3 lines yanked
Line 1 Line 1
Line 2 (ma line) Line 2 (ma line)
Line 3 Line 3
Line 4 (y'a done here) Line 4 (y'a done here)
Line 5 Line 5
Line 6 Line 6
Line 7 Line 2 (ma line)
~ Line 3
~ Line 4 (y'a done here)
~ Line 7
~ ~
~ ~
3 more lines
Yanking Lines
Filtering
The visual ! command takes a block of text and filters it through another
program. In other words, it runs the system command represented by command,
giving it the block of text represented by motion as input. The output of this
command then replaces the selected block.
Because this summarizes badly if you are unfamiliar with UNIX filters, take
a look at an example. The sort command sorts a file. If you execute the
following command, the unsorted file [Link] will be sorted and written to
[Link]. (This works on both UNIX and Microsoft Windows.)
$ sort <[Link] >[Link]
Now do the same thing in Vim. You want to sort lines 1 through 10 of a file.
First start visual mode (v) and highlight the first 10 lines. Then press !.
In anticipation of the filtering, the cursor drops to the bottom of the screen
and a ! prompt displays. You can now type in the name of the filter program, in
this case sort. Therefore, your full command is as follows:
!sort<Enter>
The result is that the sort program is run on the first 10 lines. The output
of the program replaces these lines.
Like normal mode delete (d) and normal mode yank (y), the filter command
has a normal mode version as well. The command !{motion} processes the
block of text starting at the current line and going to whatever line {motion}
takes you through a filter.
The !! command runs the current line through a filter. (I have found this a
good way to get the output of system commands into a file.) I'm editing a
[Link] file, for example, and want to include in it a list of the files in the
current directory. I position the cursor on a blank line and type the following:
!!ls
This puts the output of the ls command into my file. (Microsoft Windows
users would use dir.) Another trick is to time stamp a change. To get the
current date time (on UNIX), I use the following command:
!!date
This proves extremely useful for change histories and such.
Note: Using !! like this is technically not filtering because commands like
ls and date don't read standard input.
This command automatically closes the current file and opens the new one.
If the current file has unsaved changes, however, Vim displays a warning
message and aborts the command:
No write since last change (use ! to override)
At this point, you have a number of options. You can write the file using
this command:
:write
Note: :w may be used instead of :write.
Or you can force Vim to discard your changes and edit the new file using
the force (!) option, as follows:
:e! file
To edit a new,unnamed buffer use the :enew (:ene) command. It works just
like :edit only the new buffer is unnamed.
If you attempt to change a read-only file, you receive a warning. You can
still make the changes; you just can't save them. When you attempt to save a
changed read-only file, Vim issues an error message and refuses to save the file.
(You can force the write with the :write! command, as described later in this
chapter.)
To edit the next file, you need to change files using the :next command
(:n). Figure 4-10 shows the results.
/* File two.c */
~
~
~
~
"two.c" 1L, 17C
Figure 4-9: :next.
Note that if you have unsaved changes in the current file and you try to do
a :next, you will get a warning message and the :next will not work. You can
solve this problem in many different ways. The first is to save the file using the
following command:
:write
In other words, you can perform a :write followed by a :next. The Vim
editor has a shorthand command for this. The following command performs both
operations:
:wnext
Note: :wn is the same as :wnext.
Or, you can force Vim to go the next file using the force (!) option. If you
use the following command and your current file has changes, you will lose those
changes:
:next!
Finally, there is the 'autowrite' ('aw') option. If this option is set, Vim
will not issue any No write... Instead, it just writes the file for you and goes
on. To turn this option on, use the following command:
:set autowrite
To turn it off, use this command:
:set noautowrite
5 You can continue to go through the file list using the following command until
6 you reach the last file:
:next
Also, the :next command can take a repeat count. For example, if you
execute the command
:2 next
(or :2next), Vim acts like you issued a :next twice.
Note: Some commands like :quit will fail if any open file has been
modified. The 'autowrite' option only works for the current file. If you want
something that works on all files you need the 'autowriteall' ('awa') option.
/* File two.c */
~
~
~
~
one.c [two.c] three.c
Figure 4-10: Output of :args
This figure shows three files being edited: one.c, two.c, and three.c. The
file currently being editing is two.c.
To go back a file, you can execute any of the following commands (all are
equivalent):
:previous
:prev
:Next
:N
These commands act just like the :next command, except that they go
backward rather than forward. If you want to write the current file and go to the
previous one, use any of the following commands:
:wprevious
:wp
:wNext
:wN
To start editing from the first file, no matter which file you are on, execute
the following command:
:first
(You can also use the commands :rewind, :rew, and :fir to do the same
thing.)
Suppose that you edit two files by starting Vim with the following:
$ gvim one.c two.c
You edit a little on the first file, and then go to the next file with the
following:
:wnext
At this point, the previous file, one.c, is considered the alternate file. This
has special significance in Vim. For example, a special text register (#) contains
the name of this file.
By pressing CTRL-^, you can switch editing from the current file to the
alternate file. Therefore, if you are editing two.c and press CTRL-^, you will
switch to one.c (two.c becoming the alternate file). Pressing CTRL-^ one more
time switches you back.
Matching
Though not exactly a search command, the :match (:maxx) command can
be very useful in finding test. It causes all text that matches a given pattern to
be highlighted on the screen. For example, to highlight all the word “TODO”
with the Error syntax highlighting, use the command:
:match Error /TOOD/
To find out what highlighting names are available use the :highlight (:hi)
command:
:highlight
To clear the match from the screen, use the command:
:match none
There are can be three matches active at one time. These are set by the
:match, :2match, and :3match commands. If some text is matched by more than
one command, the lowest one wins.
● Window selection
● Basic Tabs
This command splits the screen into two windows (and leaves the cursor in
the top one), as seen in Figure 5-1.
/* File one.c */
~
~
one.c
/* File one.c */
~
one.c
Figure 5-1: Splitting a window.
Both are editing the same file, so you can view two different parts of a file
simultaneously.
If you are at the bottom window, the CTRL-Ww command moves the cursor
to the top window (alternate command: CTRL-W CTRL-W). If you are at the top
window, the editor jumps to the bottom one on the screen.
Usually you would expect CTRL-W CTRL-C also to close a window. It would
if all the CTRL-W commands were consistent. Because CTRL-C cancels any
pending operation, however, CTRL-W CTRL-C does nothing.
Vertical Windows
The :split (:sp) commands divides the screen horizontally. To divide the
screen vertically use the :vsplit (:vs) command. Figure 5-3 shows the result of
this operation:
It should be noted anything that the :split command can do, the
:vsplit command can do vertically.
To move from the left window to the right use the CTRL-Wl
(CTRL-W CTRL-L, CTRL-W<Right>) command. To go from the right to left use the
CTRL-Wh (CTRL-W CTRL-H, CTRL-W<Left>) command. The CTRL-Ww
(CTRL-W CTRL-W) command moves you to to the next window to the right,
wrapping to the leftmost window if there is no window to the right. Figure 5-4
shows how these commands work:
7
8 CTRL-W h
9 CTRL-W l
10
11
/* one.c */ |/* one.c */
|
~ |~
~ |~
~ |~
~ |~
~ |~
~ |~
one.c one.c
CTRL-W w
CTRL-W w
The following command opens a second window and starts editing the
given file:
:split file
Figure 5-5 shows what happens when you start editing one.c and then
execute the following command
:split two.c
/* File two.c */
~
~
two.c
/* File one.c */
~
one.c
Figure 5-5: Results of :split two.c.
The :split (:sp) command can also execute an initial command using the
+command convention. Figure 5-6 shows what happens when you are editing
one.c and execute the following command:
:split +/printf three.c
{
printf("%2d squared is %3d\n", i, i*i);
}
three.c
/* File one.c */
~
one.c
Figure 5-6: Result of :split with a + command
Quick Split
The command CTRL-Wn (CTRL-W CTRL-N, :new) splits a window and starts
editing a new file.
Split Summary
count The size of the new window in lines. (Default is to split the
current window into two equal sizes.)
+command An initial command.
file The name of the file to edit. (Default is the current file.)
The following command splits the current window and starts a new file in
the other window:
:new
The :vnew (:vne) does the same thing vertically.
Drag it to here
Grab the bar with the mouse
The command count CTRL-W+ increases the window size by count (default
= 1). Similarly count CTRL-W- decreases the window's size by count (default =
1). The command CTRL-W= makes all the windows the same size (or as close as
possible).
The command count CTRL-W_ (CTRL-W CTRL-_) makes the current window
count lines high. If no count is specified, the window is increased to its maximum
size.
The :resize (:res) command can be used to change the height of the
window from the command line. The argument to this command can be an
simple number (i.e. 24) in which case the window is set to that size. If the
argument begins with a plus or minus, (i.e. +5, -7), then the window in increased
or decreased in size.
Buffers
The Vim editor uses the term buffer to describe a file being edited.
Actually, a buffer is a copy of the file that you edit. When you finish changing the
buffer and exit, the contents of the buffer are written to the file. Buffers not only
contain file contents, but also all the marks, settings, and other stuff that go with
it.
Normally it is pretty easy to tell what buffers you have: If it has a window
on the screen, it is a buffer; if it is not on the screen, it is not a buffer.
Now for a new concept thrown into the mix, that of the hidden buffer.
Suppose you are editing a file named one.c and you need to do some work on
two.c. You split the screen and create two windows, one for each file. But you do
not like split-screen mode; you want to see one file at a time.
One solution is to make the window for two.c as big as possible. This
works, but there still is an annoying little bit of one.c showing. Another solution
is to close the one.c window, but then you lose all the changes for that file.
The Vim editor has another solution for you: the :hide (:hid) command.
This causes the current buffer to become "hidden."This causes it to disappear
from the screen. But Vim still knows that you are editing this buffer, so it keeps
all the settings, marks, and other stuff around. Actually, a buffer can have three
states:
Inactive The file is not being edited, but keep the information about it
anyway.
The inactive state takes a little explaining. When you edit another file, the
content of the current file is no longer needed, so Vim discards it. But
information about marks in the file and some other things are still useful and are
remembered along with the name of the file. Also, a file that was included in the
command with which you started Vim, but was not edited, will also be an inactive
buffer.
Figure 5-9 shows the results of this command. The first column is the
buffer number. The second is a series of flags indicating the state of the buffer.
The third is the name of the file associated with the buffer. The state flags are:
- Inactive buffer.
h Buffer is hidden.
% Current buffer.
# Alternate buffer.
1. The next to last file you were working on, also known as the alternate
file (# flag).This buffer has been hidden (h flag).You were editing file one.c
and left the cursor on line 1.
3. An inactive buffer. You want to edit three.c, but you have made no
changes to it.
4. Another file on the argument list that has not been edited.
5. When you executed a :help command, the Vim editor opened two
files. The first one of these is called [Link].
Selecting a Buffer
You can select which buffer to use by executing the following command:
:buffer number
(:b is the abbreviation for :buffer.)
The number parameter is the buffer number. If you do not know the
number of the buffer, but you do know the filename, you can use this command:
:buffer file
Figure 5-10 shows the results of a typical :buffer command.
/* File three.c */
#include <stdio.h>
int i;
int main()
{
for (i = 1; i <= 10; ++i)
{
printf("%2d squared is %3d\n", i,
i*i);
}
return (0);
}
~
~
three.c
Figure 5-10: :3buffer or :buffer three.c.
The following command splits the window and starts editing the buffer:
:sbuffer number
(:sb is the abbreviation for :sbuffer.)
If a number is specified, the new window will contain that buffer number. If
no number is present, the current buffer is used.
This also takes a filename as an argument. If you are editing the file
three.c and execute the following command
:sbuffer one.c
You get the results seen in Figure 5-11.
/* File one.c */
~
~
~
~
~
one.c
/* File three.c */
#include <stdio.h>
int i;
int main()
{
for (i = 1; i <= 10; ++i)
"three.c" line 1 of 1 100% col 1 ((2) of 3)
Figure 5-11: Result of :sbuffer.
:bm.)
:sbmodified count Shorthand for :split and :bmodified. (Same as
:sbm.)
Buffer Types
There are many different special buffers you'll encounter in the Vim editor.
To keep track of them Vim uses the 'buftype' ('bt') option. It can contain the
following values:
<emtpy> Normal buffer
acwrite A buffer which will always be written with an :autocmd.
help Help window
nofile A buffer that is not associated with a file and will not be written.
nowrite This buffer will not be written.
quickfix A quickfix list.
Buffer Options
Usually when the last window of a file is closed, the buffer associated with
the file becomes inactive. If the option 'hidden' ('hid') is set, files that leave
the screen do not become inactive; instead they automatically become hidden.
Therefore if you want to keep the contents of all your old buffers around while
editing, use the following command
:set hidden
Note: The :hide command always hides the current file no matter what
the 'hidden' option is set to.
The 'bufhidden' ('bh') can be used to fine tune when a buffer appears
and hides. (Do not use this option unless you know what you are doing.) The
values for this option are:
<empty> The value of the 'hidden' option is used to decide whether or not to
hide the buffer.
delete Delete the buffer as if a :bdelete were performed on it. (Use caution
Normally, the split/buffer related commands split the current window. If the
'switchbuf' ('swb') option is set to useopen and there is a window displaying
the buffer you want to display already on the screen, the Vim will just make that
window the current one instead of performing the split (see Figure 5-12).
$ gvim t.c Makefile
:snext
:set switchfbuf=useopen
:sbrewind
#include <stdio.h>
int main()
{
i = 5;
printf("Hello World/n");
t.c
t: t.c
gcc t.c
~
~
~
Makefile
You can click on each tab to make that tab the current tab. If you wish to
edit a specific file use the command:
:tabedit {file-name}
In general the :tab command will cause any command that would open a
new window to open a new tab instead. For example:
:tab :split [Link]
Tabs may be closed by the :quit (:q) command. Or you can write the file
and close the tab with ZZ. The :tabclose (:tabc) command acts just like :quit.
However, if you give :tabclose a numeric argument, that tab is close. For
example to close the second tab, use the command:
:tabclose 2
The :tabonly (:tabo) command closes all the other tabs. This will fail if
closing a tab would result in data loss, unless the override (!) is specified.
Selecting a tab
To make a particular tab the current one, click on it. Or you can use the
Vim command :tabnext (:tabn) to go to the next tab. This command wraps so if
you're on the last tab, you'll wind up on the first one.
Finally :tabfirst (:tabf, :tabrewind, :tabr) goes the first tab and
:tablast (:tabl) goes to the last one.
:tabfirst :tablast
:tabnext
:tabprevious
The CTRL-Wgf command opens a new tab and starts to edit the file who's
name is under the cursor. Vim will search for the file using the same algorithm
as it uses for the :find command. The CTRL-WgF command does the same thing,
only it goes a step farther. It not only starts editing the file in a new tab, but
jumps to the line number following the file name.
The -p command does the same thing except that it opens each file in it's
own tab. Like -o you can give it a numeric argument. Unlike -o there is an
option ('tabpagemax' aka 'tpm') which limits the number of tabs opened this
way.
● Visual yanking
#include <stdio.h>
d – delete int i;
highlighted int main()
text {
for (i = 1; i <= 10; ++i)
return (0);
~
~
~
three.c
3 fewer lines
Figure 6-2: Visual delete.
Note: To get help on the commands that operate in visual mode, use the
prefix v_. Therefore
:help v_d
describes what the d command does in visual mode.
Remember, you can always type <Esc> to get back to normal mode so you
know where you are. Some people find <Esc> a little annoying because it beeps if
you type it twice. The first <Esc> goes from visual mode to normal mode. The
second <Esc> in normal mode is an error and generates the beep. (The
command CTRL-C will do the same thing as well.)
If you want to make sure that you are in normal mode and do not want to
generate a beep, use the CTRL-\CTRL-N command. This acts just like <Esc> but
without the noise.
The d command deletes the highlighted text, as shown in Figure 6-6. The D
command deletes the highlighted lines, even if only part of a line is highlighted
(see Figure 6-7). (X does the same thing.)
Line 1 Line 1
Line 2 2
Line 3 Line 3
Line 4 d - deletes the Line 4
Line 5. highlighted text Line 5.
~ ~
~ ~
~ ~
~ ~
[Link] [Link] [+]
-- VSUAL --
Figure 6-6: Deleting text in visual mode.
Line 1 Line 1
Line 2 Line 3
Line 3 Line 4
Line 4 D - deletes the Line 5.
Line 5. highlighted lines ~
~ ~
~ ~
~ ~
~ ~
[Link] [Link] [+]
-- VSUAL --
Figure 6-7: The visual D command.
Yanking Text
The y command places the highlighted text into a register. The linewise
version of this command, Y, places each line of the highlighted text into a
register.
Switching Modes
Suppose you are in character mode (started by v) and you realize you want
to be in block mode. You can switch to block mode by just pressing CTRL-V.
In fact, you can switch visual modes at any time by just selecting the new
mode. To cancel visual mode, press the <Esc> key; or you can switch to the
mode you are already in. (In other words, if you use v to start visual mode, you
can use another v to exit it.)
Changing Text
The c command deletes the highlighted text and starts insert mode. The C
does the same thing, but it works only on whole lines.
Note: r and s do the same thing as c in visual mode. The same thing goes
for R and S and the C command.
Joining Lines
The J command joins all the highlighted lines into one long line. Spaces
are used to separate the lines. If you want to join the lines without adding
spaces, use the gJ command. Figure 6-8 shows how the J and the gJ commands
work.
Line 1 J Line 1
Line 2 Line 2 Line 3
Line 3 Line 4
Line 4 ~
~ ~
~ ~
~ ~
~ ~
~ ~
[Link] [Link] [+]
-- VISUAL --
gJ
Line 1
Line 2Line 3
Line 4
~
~
~
~
~
~
[Link] [+]
The < does the process in reverse. (Note that these commands have a
different meaning when using visual block mode.) The = command indents the
text the proper amount according to what Vim thinks is the proper information
for your program. The CTRL-] command will jump to definition of the function
highlighted.
Keyword Lookup
The K command is designed to look up the selected text using the man
command. (Linux and UNIX only.) It works just like the normal-mode K
command except that it uses the highlighted text as the keyword.
Inserting Text
The command Istring<Esc> inserts the text on each line starting at the
left side of the visual block, as seen in Figure 6-9.
You start by pressing CTRL-V to enter visual block mode. Now you define
your block. Next you type I to enter insert mode followed by the text to insert.
As you type, the text appears on the first line. After you press <Esc> to end the
insert, the text will magically be inserted in the rest of the lines contained in the
visual selection. Figure 6-9 shows how this process works.
Do alpha.c Do file alpha.c
Do one.c Do one.c
Do four.c Do four.c
Do three.c Do three.c
Do two.c Do two.c
~ ~
~ ~
~ ~
[Link] [+] [Link] [+]
-- VISUAL BLOCK -- -- INSERT --
Do file alpha.c
Do file one.c
Do file four.c
Do file three.c
Do file two.c
~
~
~
[Link] [+]
-- VISUAL BLOCK --
If the block spans short lines that do not extend into the block, the text is
not inserted in that line. Figure 6-10 illustrates what happens to short lines. If
the string contains a newline, the I acts just like a normal-mode insert (i)
command and affects only the first line of the block.
This is a long line This is a very long line
short short
This is a long line This is a very long line
~ ~
~ ~
~ ~
[Link] [+] [Link] [+]
-- VISUAL BLOCK --
Changing Text
The visual block c command deletes the block and then throws you into
insert mode to enable you to type in a string. The string will be inserted on each
line in the block (see Figure 6-11). The c command works only if you enter less
than one line of new text. If you enter something that contains a newline, only
the first line is changed. (In other words, visual block c acts just normal-mode c
if the text contains more than one line.)
Note: The string will not be inserted on lines that do not extend into the
block. Therefore if the block includes some short lines, the string will not
be inserted in the short lines.
The C command deletes text from the left edge of the block to the end of
line. It then puts you in insert mode so that you can type in a string, which is
added to the end of each line (see Figure 6-12). Again, short lines that do not
reach into the block are excluded. (R and S act just like the C command except
they replace the text with what's insert instead of replacing multiple lines.)
This is a long line This is changed
short short
This is a long line This is changed
~ ~
~ ~
~ ~
[Link] [+] [Link] [+]
-- VISUAL BLOCK --
The visual block A throws Vim into insert mode to enable you to input a
string. The string is appended to the block (see Figure 6-13). If there are short
lines in the block, spaces are added to pad the line and then string is appended.
You can define a right edge of a visual block in two ways. If you use just
motion keys, the right edge is the edge of the highlighted area. If you use the $
key to extend the visual block to the end of line, the inserted text will add the
text to the end of each line (see Figure 6-14).
This is a long line This is a very long lineXXX
short shortXXX
This is a long line This is a very long lineXXX
~ ~
~ ~
~ ~
[Link] [+] [Link] [+]
-- VISUAL BLOCK --
Define the visual block by Add "XXX" to the end of each line
using the command with the AXXX<Esc> command.
CTRL-V$jj.
The $ moves the cursor to
the end of the line
Figure 6-14: Block visual $ and A commands.
Replacing
The rchar command applies all the selected characters with a single
character (see Figure 6-15). Short lines that do not extend into the block are not
affected.
Shifting
The command > shifts the text to the right one shift width, opening
whitespace. The starting point for this shift is the left side of the visual block
(see Figure 6-16). The < command removes one shift width of whitespace at the
left side of the block (see Figure 6-17). This command is limited by the amount
of text that is there; so if there is less than a shift width of whitespace available,
it removes what it can.
Oh woe to Mertle the turtle
who found web surfing quite a hurtle.
The system you see
was slower than he.
And that's not saying much for the turtle.
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
-- VISUAL BLOCK --
12
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
aaa BBBBBBBBBBB
Getting help for the commands that use visual block mode differs a little
from other commands. You need to prefix the command with v_b_.To get help on
the visual block r command, for example, type the following:
:help v_b_r
● Syntax coloring
● Automatic indentation
● Indentation commands
Syntax Coloring
The following command turns on syntax coloring.
:syntax on
(:syntax on can be abbreviated :sy on.)
That means that things such as keywords, strings, comments, and other
syntax elements will have different colors. (If you have a black-and-white
terminal, they will have different attributes such as bold, underline, blink, and so
on.) You can customize the colors used for syntax highlighting as well as the
highlighting method itself.
To turn off syntax highlighting use the :syntax off (:sy off) command.
Most of the time syntax coloring works just fine. But sometimes it can be a
little tricky to set up. The following sections take a look at some common
problems and solutions.
Ever try and read light yellow text on a white background? It is very hard
to do. If you see this on your screen, you have a problem. The Vim editor has
two sets of syntax colors. One is used when the background is light, and the
other when the background is dark. When Vim starts, it tries to guess whether
your terminal has a light or dark background and sets the option 'background'
to light or dark. It then decides which set of colors to use based on this option.
Be aware, however, that the editor can guess wrong.
To find out the value of the 'background' option, use the following
command:
:set background?
If Vim's guess is not correct, you can change it using a command such as
this:
:set background=light
You must use this command before executing the command:
:syntax on
I Turned on Syntax Colors, but All I Get Is Black and White (UNIX)
To fix this problem you need to know what shell (command process) you
are using. If you use csh, put the following in your $HOME/.cshrc file:
if ($term == xterm) set term = xterm-color
For bash put the following in your $HOME/.bashrc file:
if [ $TERM = xterm]; then export TERM=xterm-color; fi
Other systems and other shells require different changes.
I'm Editing a C File with a Non-Standard Extension. How Do I Tell Vim About It?
The Vim editor uses a file's extension to determine the file type. For
example, files that end in .c or .h are considered C files. But what if you are
editing a C header file named [Link]?
If you are still having trouble with colors, run the Vim color test. This is a
short Vim program that displays all the colors on the screen so that you can
verify the correctness of the Vim colors. The color test can be started with these
two commands:
:edit $VIMRUNTIME/syntax/[Link]
:source %
Matching Pairs
The % command is designed to match pairs of (), {}, or []. Place the cursor
on one, type % and you will jump to the other. Figure 7-1 shows how the %
command works.
The2% command will also match the ends of C comments (see Figure 7-2).
(For you non-C programmers, these begin with /* and end with */.)
/* A comment */
% /*
* A multi-line comment.
*/
Also the % command will match #ifdef with the corresponding #endif.
(Same goes for #ifndef and #if.) For #if, #else, and #endif sets, the %
command will jump from the #if to the #else, and then to the #endif and back
to the #if. Figure 7-3 shows how % works with preprocesser directives.
#ifndef SIZE
% #define SIZE 100
#endif /* SIZE */
#ifdef UNIX
% #define EOL "\n";
#else /* UNIX */
% #define EOL "\r\n";
%
#endif /* UNIX */
Figure 7-3:% and the #if/#else/#endif.
Note: The Vim editor is smart about matching pairs of operators. It knows
about strings, and {} or [] will be ignored inside a string.
Shift Commands
The Vim editor has lots of commands that help the programmer indent his
program correctly. The first ones discussed here merely shift the text to the left
(115115<<) or the right (>>).
The left shift command (<<) shifts the current line one shift width to the
left. The right shift command (>>) does the same in the other direction.
The << command shifts a single line. As usual you can prefix this command
with a count; for example, 5<< shifts 5 lines. The command <motion shifts each
line from the current cursor location to where motion carries you.
You can also highlight a set of lines in visual mode (v command) and then
shift them with < or >.
Automatic Indentation
The Vim editor has a variety of automatic indentation options. The major
indentation modes are the following:
cindent This works for C-style programs (C, C++, Java, and so
on).When this style of indentation is enabled, the Vim editor
automatically indents your program according to a
"standard" C style.
smartindent In this mode, Vim indents each line the same amount as the
preceding one, adding an extra level of indentation if the line
contains a left curly brace ({) and removing a indentation
level if the line contains a right curly brace (}). An extra
indent is also added for any of the keywords specified by the
'cinwords' option.
autoindent New lines are indented the same as the previous line.
The next few sections explore these indentation modes in detail.
C Indentation
The Vim editor knows something about how C, C++, Java, and other
structured language programs should be indented and can do a pretty good job
of indenting things properly for you. To enable C-style indentation, just execute
the following command:
:set cindent
With this option enabled, when you type something such as if (x), the
next line will automatically be indented an additional level. Figure 7-5 illustrates
how 'cindent' works.
When you type something in curly braces ({}), the text will be indented at
the start and unindented at the end.
Note: One side effect of automatic indentation is that it helps you catch
errors in your code early. I have frequently entered a } to finish a
procedure, only to find that the automatic indentation put it in column 4.
You don't want to switch on the 'cindent' option manually every time you
edit a C file. This is how you make it work automatically: Put the following lines
in your .vimrc (UNIX) or _vimrc (Windows) file:
:filetype on
:autocmd FileType c,cpp :set cindent
(:filetype can be abbreviated :filet. :autocmd may be abbreviated
:au.)
The first command (:filetype on) turns on Vim's file type detection logic.
The second, performs the command :set cindent if the file type detected is c
or cpp. (This includes C, C++, and header files.)
Smartindent
The 'cindent' mode is not the only indent mode available to Vim users.
There is also the 'smartindent' mode. In this mode, an extra level of
indentation is added for each { and removed for each }. An extra level of
indentation will also be added for any of the words in the 'cinwords' option.
Lines that begin with # are treated specially. If a line starts with #, all
indentation is removed. This is done so that preprocesser directives will all start
in column [Link] indentation is restored for the next line.
Autoindent
If you have set the 'autoindent' option using the :set autoindent
command, the Vim editor automatically indents the second printf by four spaces
(to line up with the preceding line). Figure 7-6 illustrates the operation of the
'autoindent' option. Type four spaces for indent; with 'autoindent' set, the
following lines are automatically indented.
if (true) {
autoindent ¬¬¬¬printf("It is true\n");
printf("It is really true\n");
}
Figure 7-6: 'autioindent'
That is nice, but when you get ready to enter the } line, the Vim editor also
indents four spaces. That is not good because you want the } to line up with the
if statement. While in insert mode, the CTRL-D command will cause Vim to back
up one shift width (see Figure 7-7). CTRL-D moves the } back one shift width.
13
if (true) {
¬¬¬¬printf("It is true\n");
printf("It is really true\n");
}
CTRL-D
Figure 7-7: CTRL-D
The = Command
The =motion command indents the selected text using Vim's internal
formatting program. If you want to indent a block of text, for example, you can
use the = command to do it. The motion in this case is the % (go to matching {})
command. Figure 7-8 shows the results.
{
if (strcmp (arg, option1) == 0)
return (1) ;
if (strcmp (arg, option2) == 0)
return (1) ;
return (0) ;
}
1) Position cursor on the first "{"
{
if (strcmp (arg, option1) == 0)
return (1) ;
if (strcmp (arg, option2) ==0)
return (1) ;
return (0) ;
}
Figure 7-8: The = command.
Another way of doing this is to use the visual mode = command. For
example, to indent all the code inside a set of {} (including the {}), execute the
following commands:
Diff Mode
Vim has a diff mode which displays the differences between two or more
files side by side. For example, let's take a look at the difference between two
different version of a program. To do this we execute the command:
$ gvimdiff [Link] [Link]
The first 29 lines are the same in both files so Vim has put in a fold hiding
them from you. The line:
static int raw;
is different between the two files. Not only is the line highlighted, but the
actual different (and extra “i”) is highlighted in a different color. You can also
easily see where a line was added in the first file as well.
The nice thing about doing this in Vim is that you can edit both files. To
move from one window to another use the window left (CTRL-W h) or window
right (CTRL-W l) commands.
You can also easily move differences from one file to another. To move a
change from the current file to the other one, use the dp (diff put) command. To
move a change from the other file to the one you are editing now, use the do (diff
obtain) command.2
Folding
Suppose you are looking at some badly written code such as that in Figure
7-11.
if (condition) {
// ... 1200 lines of code
} else {
return (ERROR);
}
Figure 7-11: Bad code
If you look at the code normally, this is all you're going to see:
if (condition) {
// Junky code line 1
// Junky code line 2
// Junky code line 3
// Junky code line 4
Now if you scroll down, and down, and down, and down, you'll finally get
the to the else clause. As you see figuring out the structure of such code is
difficult.
The Vim fold feature helps you see the structure of this style of code. Let's
see how to use this feature. To do this we execute the following steps:
#if (x) {
+--1200 lines: Junk code line 1-----------------
} else {
return (ERROR);
}
Figure 7-12: Screen after folding
This makes it easy to see the structure of the program. If you want to see
what's in the fold that you just created, position the cursor on the fold and
execute the command zo (Fold Open).
Note: Power users can do the same thing by positioning the cursor on the
"{" and entering zfi{. (This is the zf{motion} command with the inner { select
command: i{.)
So far we've been creating folds manually. This assumes that the
'foldmethod' ('fdm') is set to manual, the default.
We can also define folds based on indentation. Figure 7-13 shows some
unfolded code.
if (a) {
if (b) {
if (d) {
if (e) {
if (f) {
do_something();
}
}
}
}
}
Figure 7-13: Unfolded text
Now let's put the cursor on the fold and do a zo. One level of indention is
displayed. (See Figure 7-15.)
if (a) {
if (b) {
+--- 7 lines: if (d) {-------------------------
}
}
Figure 7-15: One level of indent unfolded
The zo and zc commands open and close folds manually. In other words
this commands override what Vim would normally do. To reset the folding to the
defaults (no overrides) with the command zX.
So far we've been opening and closing folds manually. The 'foldlevel'
('fdl') option controls how many level of indents cause Vim to fold. For
example, if you set the 'foldlevel' to 3 anything indented three or more
'shiftwidth' ('sw') indentations is folded.
You can use the :set command to adjust the 'foldlevel' but this is
cumbersome. Instead you can use the zm (fold more) command to reduce the
'foldlevel' increasing the amount of text folded. The zr (fold reduce)
increases the 'foldlevel', reducing the amount of text folded. Figure 7-16
shows how this works.
Somewhere
zR off to the right
there's no
folding
zr zr
zM
Finally to totally get rid of folding use the zR command. To fold things to
the max use the zM command.
C and C++ are problem languages in that they have these nasty
pre-processor directives that don't following the normal indenting rules. To
handle these types of lines the 'foldignore' ('fdi') is used. It tells Vim that
any lines that begin with a certain character are not to be considered for
computing the indentation of a line. Instead these lines inherit their indentation
level from the lines above or below.
Initially when you start editing the 'foldlevel' is set to 1. If you want to
have it start at a different value, set the 'foldlevelstart' ('fdls') to whatever
you want the initial value to be.
CTRL-I, ]CTRL-I Search for a word under the cursor in the current file
and any brought in by #include directives.
gd, gD Search for the definition of a variable.
]CTRL-D, [CTRL-D Jump to a macro definition.
]d, [d, ]D, [D Display macro definitions.
The [CTRL-I command jumps to the word under the cursor. The search
starts at the beginning of the file and also searches files brought in by #include
directives. The ]CTRL-I does the same thing, starting at the cursor location.
The gd command searches for the local declaration of the variable under
the cursor (see Figure 7-17).This search is not perfect because Vim has a limited
understanding of C and C++ syntax. In particular, it goes to the wrong place
when you ask for the local declaration of a global variable. Most of the time,
however, it does a pretty good job.
int global_var; gd
int main() Moves cursor to here.
{
int local_var; 'hlsearch' is on
global_var = local_var = 5;
printf("%d %d", global_var, local_var);
return (0);
}
Figure 7-17: The gd command.
The gD command searches for the global definition of the variable under
the cursor(see Figure 7-18). Again, this search is not perfect, but most of the
time it does the right thing.
int global_var; gD
int main() Moves cursor to here.
{
int local_var; 'hlsearch' is on
global_var = local_var = 5;
printf("%d %d", global_var, local_var);
return (0);
}
Figure 7-18: The gD command.
The [CTRL-D command searches for the first definition of the macro whose
name is under the cursor. The ]CTRL-D command searches for the next
definition of the macro. These commands search not only the file you are
editing, but also all files that are #included from this file. Figure 7-19 shows the
[CTRL-D and ]CTRL-D commands.
#include <stdio.h>
#define SIZE 10 [CTRL-D
int i = EOF ;
int main ( )
{
for (i = 1; i <= SIZE; ++i)
{
printf( "%2d squared is %3d\d", i,
i*i)
;
}
return (0) ; ]CTRL-D
}
#undef SIZE
#define SIZE 20
Figure 7-19: [CTRL-D and ]CTRL-D.
The [d command displays the first definition of the macro whose name is
under the cursor. The ]d command does the same thing only it starts looking
from the current cursor position and finds the next definition. Figure 7-20 shows
the result of [d.
#include <stdio.h>
#define SIZE 10
int i = EOF; [d
int main()
{
for (i = 1; i <= SIZE; ++i)
{
printf("%2d squared is %3d\n", i,
i*i);
}
return (0);
}
#undef SIZE
#define SIZE 20
Figure 7-20: [d command.
The ]D and [D commands list all the definitions of a macro. The difference
between the two is that [D starts the list with the first definition, whereas ]D
starts the list with the first definition after the cursor. Figure 7-21 shows the
results of a [D command.
int main()
{
for (i = 1; i <= SIZE; ++i)
{
printf("%2d squared is %3d\n", i, i*i);
}
return (0);
}
#undef SIZE
#define SIZE 20
~
~
~
test.c
1: 2 #define SIZE 10
2: 13 #define SIZE 20
Press RETURN or enter command to continue
Figure 7-21: [D command.
Unfortunately this shifts the {} in addition to the text. Suppose you just
want to shift what is in the {}. Then you need to do the following:
This shift right command (>) shifts the selected text to the right one shift width.
In this case, the selection command that follows is i{, which is the "inner {}
block" command. Figure 7-23 shows the execution of these commands.
You can also use the visual K command to do the same thing. The format of
the man command is as follows:
$ man [section] subject
The K command gets the subject from the word under the cursor. But what
if you need to select the section number? It is simple; the K command takes a
count argument. If specified, this is used as the section number. Therefore, if
you position the K over the word mkdir and execute the 2K, you will get the
mkdir(2) page.
You can customize the Error: Reference source not foundK command. It
runs the program specified by the 'keywordprg' ('kp') option. By default, on
UNIX this is man. Solaris has a non-standard man command. Sections must be
specified with the -s switch. So the 'keywordprg' option defaults to man -s on
Solaris. The Vim editor is smart enough to know that if no section is specified,
that it must drop the -s.
Tags
The Vim editor can locate function definitions in C and C++ programs.
This proves extremely useful when you are trying to understand a program. The
location of function definitions (called tags in Vim terminology) is stored in a
table of contents file generated by the program ctags.3 To generate the table of
contents file, which is named tags, use the following command:
$ ctags *.c
Now when you are in Vim and you want to go to a function definition, you
can jump to it by using the following command:
:tag function
This command will find the function even if it is another file. The CTRL-]
command jumps to the tag of the word that is under the cursor. (g<LeftMouse>
and <C-LeftMouse> are equivalent to CTRL-].) This makes it easy to explore a
tangle of C code.
3 You may need to install Exuberant ctags from [Link] if you system does
not have it already.
Suppose, for example, that you are in the function write_block. You can
see that it calls write_line. But what does write_line do? By putting the
cursor on the call to write_line and typing CTRL-], you jump to the definition
of this function (see Figure 7-24). The write_line function calls write_char.
You need to figure out what it does. So you position the cursor over the call to
write_char and press CTRL-]. Now you are at the definition of write_char (see
Figure 7-25).
void write_block(char line_set[])
{
int i;
for (i = 0; i < N_LINES; ++i)
write_line(line_set[i]);
}
The :tags command shows the list of the tags that you have traversed
through (see Figure 7-26).
~
:tags
# TO tag FROM line in file/text
1 1 write_block 1 write_block.c
2 1 write_line 5 write_block.c
3 1 write_char 5 write_line.c
>
Press RETURN or enter command to continue
Figure 7-26: The :tags command.
Now to go back. The CTRL-T command goes the preceding tag. (The
commands g<RightMouse> and <C-RightMouse> do the same thing.) This
command takes a count argument that indicates how many tags to jump back.
So, you have gone forward, and now back. Let's go forward again. The
following command goes to the next tag on the list:
:tag
You can prefix it with a count and jump forward that many tags. For
example:
:3tag
Figure 7-27 illustrates the various types of tag navigation.
:tag write_block
The :tag command replaces the current window with the one containing
the new function. But suppose you want to see not only the old function but also
the new one? You can split the window using the :split command followed by
the :tag command. But Vim has a shorthand command that is shorthand for both
commands:
:stag name
Figure 7-28 shows how this command works.
void write_block( void write_char(char ch)
char line_set[] {
) write_raw(ch);
{ write_char.c
int i; for (i = 0; i < N_LINES; ++i)
for (i = 0; i < N_LINES; write_line(line_set[i]);
write_line(line_set[i]); write_block.c
} "write_char.c" 4L,
:stag write_char
The CTRL-W] command splits the current window and jumps to the tag
under the cursor in the upper window (see Figure 7-29). (CTRL-W CTRL-] works
as well.) If a count is specified, the new window will be count lines high.
void write_block( void write_line(char line[])
char line_set[] {
) int i;
{ write_line.c
int i; for (i = 0; i < N_LINES; ++i)
for (i = 0; i < N_LINES; write_line(line_set[i]);
write_line(line_set[i]); write_block.c
} "write_char.c" 4L,
Suppose you "sort of " know the name of the procedure you want to find?
This is a common problem for Microsoft Windows programmers because of the
extremely inconsistent naming convention of the procedures in the Windows API.
UNIX programmers fare no better. The convention is consistent; the only
problem is that UNIX likes to leave letters out of system call names (for example,
creat).
You can use the :tag command to find a procedure by name, or it can
search for a regular expression. If a procedure name begins with /, the :tag
command assumes that the name is a regular expression. If you want to find a
procedure named "something write something," for example, you can use the
following command:
:tag /write
This finds all the procedures with the word write in their names and
positions the cursor on the first one. If you want to find all procedures that
begin with read, you need to use the following command:
:tag /^read
If you are not sure whether the procedure is DoFile, do_file, or Do_File,
you can use this command:
:tag /DoFile\|do_file\|Do_File
or
:tag /[Dd]o_\=[Ff]ile
These commands can return multiple matches. You can get a list of the
tags with the following command:
:tselect name
(:tselect may be abbreviated as :ts.) Figure 7-30 shows the results of a
typical :tselect command.
~
# pri kind tag file
> 1 F C f write_char write_char.c
void write_char(char ch)
2 F f write_block write_block.c
void write_block(char line_set[])
3 F f write_line write_line.c
void write_line(char line[])
4 F f write_raw write_raw.c
void write_raw(char ch)
Enter nr of choice (<CR> to abort):
Figure 7-30: :tselect command.
The first column is the number of the tag. The second column is the
Priority column. This contains a combination of three letters.
The last line of the :tselect command gives you a prompt that enables
you to enter the number of the tag you want. Or you can just press Enter (<CR>
in Vim terminology) to leave things alone.
The g] command does a :tselect on the identifier under the cursor. The
:tjump command (a.k.a. :tj) works just like the :tselect command, except if
the selection results in only one item, it is automatically selected. The gCTRL-]
command does a :tjump on the word under the cursor. A number of other
related commands relate to this tag selection set, including the following:
:tag /write
:tnext
:tnext
:tnext
:trewind
:tlast
Shorthand Commands
The command :stselect (:sts) does the same thing as :tselect, except
that it splits the window first. The :stjump does the same thing as a :split and
a :tjump.
beta.o: beta.c
gcc -c beta.c
You may have a little difficulty seeing the problem from this listing. The
problem is that the indent for the first command is a tab, whereas the indent on
the second one uses eight spaces. This difference is impossible to see on screen;
so how do you tell the difference between the two versions? The following
command puts Vim in list mode:
:set list
In this mode, tabs show up as ^I. Also the editor displays $ at the end of
each line (so you can check for trailing spaces). Therefore, if you use the
following command
:set list
your example looks like this:
alpha.o: alpha.c$
^Igcc -c alpha.c$
$
beta.o: beta.c$
gcc -c beta.c$
From this it is easy to see which line contains the spaces and which has a
tab. (You can customize list mode by using the 'listchars' ('lcs') option.)
If the 'expandtab' option is set, when you type a tab, Vim inserts spaces.
This is not good if you are editing a Makefile. To insert a real tab, no matter
what the options are, type in CTRL-V<Tab> in insert mode. The CTRL-V tells Vim
not to mess with the following character.
Note: If you have syntax coloring turned on, the Vim editor will highlight
lines that begin with spaces in red, whereas lines that start with <Tab>
display normally.
4. Run the block through the external program sort using the command
!'a sort.
SOURCES = \
[Link] \
[Link] \
[Link] \
[Link] \
[Link] \
[Link] \
[Link] \
[Link] \
[Link] \
rio_glob.cpp
rio_io.cpp \
[Link] \
set_ix.cpp \
[Link] \
All the lines, except the last one, must end with a backslash (\). Sorting
can disrupt this pattern. Make sure that the backslashes are in order after a
sort. Figure 7-32 shows how you might need to fix the source list.
SOURCES = \ SOURCES = \
[Link] \ [Link] \
[Link] \ [Link] \
[Link] \ [Link] \
[Link] \ [Link] \
[Link] \ [Link] \
[Link] \ [Link] \
[Link] \ [Link] \
[Link] \ [Link] \
[Link] \ [Link] \
[Link] \ [Link] \
Fix
rio_glob.cpp rio_glob.cpp \
rio_io.cpp \ rio_io.cpp \
set_ix.cpp \ set_ix.cpp \
[Link] \ [Link] Fix
To sort a list using visual mode, you need to execute the following
commands:
4. Execute the command !sort. The ! tells Vim to pipe the selected text
through a command. The command in this case is sort. (This command
has an implied <Enter> at the end.)
The :make (:mak) command runs the program make (supplying it with any
argument you give) and captures the results:
:make [arguments]
If errors were generated, they are captured and the editor positions you
where the first error occurred.
Take a look at a typical :make session. (Typical :make sessions generate far
more errors and fewer stupid ones.) Figure 7-33 shows the results. From this
you can see that you have errors in two files, main.c and sub.c.
:!make | & tee /tmp/[Link]
gcc g Wall o prog main.c sub.c
main.c: In function `main':
main.c:6: too many arguments to function `do_sub'
main.c: At top level:
main.c:10: parse error before `}'
sub.c: In function `sub':
sub.c:3: `j' undeclared (first use in this function)
sub.c:3: (Each undeclared identifier is reported only once
sub.c:3: for each function it appears in.)
sub.c:4: parse error before `}'
sub.c:4: warning: control reaches end of non-void function
make: *** [prog] Error 1
2 returned
"main.c" 11L, 111C
(3 of 12): too many arguments to function `do_sub'
Press RETURN or enter command to continue
When you press Enter (what Vim calls Return), you see the results shown
in Figure 7-34.
int main()
{
int i=3;
do_sub("foo");
++i;
return (0);
}
}
~
(3 of 12): too many arguments to function do_sub
Figure 7-34: The first error.
The editor has moved you to the first error. This is line 6 of main.c. You
did not need to specify the file or the line number, Vim knew where to go
automatically. The following command goes to where the next error occurs (see
Figure 7-35):
:cnext
int main()
{
int 1=3;
do_sub("foo");
++i;
return (0);
}
}
~
(5 of 12): parse error before `}´
Figure 7-35: :cnext.
int sub(int i)
{
return (i * j)
}
~
~
~
~
~
~
(7 of 12): `j' undeclared (first use in this function)
Figure 7-36: :cnfile command
If you forget what the current error is, you can display it using the
following command:
:cc
To see a list of errors, use the commands:
:copen
This command opens a new window showing all the errors as shown in
Figure 7-37.
int sub(int i)
{
return (i * j)
}
~
~
~
~
~
~
(7 of 12): `j' undeclared (first use in this function)
Figure 7-37: :copen command
~
~
:clist
3 main.c:6: too many arguments to function `do_sub'
5 main.c:10: parse error before `}'
7 sub.c:3: `j' undeclared (first use in this function)
8 sub.c:3: (Each undeclared identifier is reported only once
9 sub.c:3: for each function it appears in.)
10 sub.c:4: parse error before `}'
11 sub.c:4: warning: control reaches end of non-void function
Press RETURN or enter command to continue
If you want to list only a subset of the errors, you can give :clist a range
of errors to list. For example:
If you have already run make and generated your own error file, you can
tell Vim about it by using the :cfile error-file command. Where error-file
is the name of the output of the make command or compiler. If the error-file is
not specified, the file specified by the 'errorfile' option is used.
Finally the following command exits Vim like :quit but exits with an error
status (exit code=1):
:cquit
This is useful if you are using Vim in an integrated development
environment and a normal exit would cause a recompilation.
The 'errorfile' option (also 'ef') defines the default filename used for
the :clist command (:cl) as well as the -q command-line option. (This file is
not used for the :make command's output.) If you want to define your default
error file, use the following command:
:set errorfile=[Link]
if (rate_limit++ < 3)
log(L_IOCTL, "Please report in case toggling the power "
"LED doesn't work for your card!\n");
if (enable)
write_reg16(adev, IO_ACX_GPIO_OUT,
read_reg16(adev, IO_ACX_GPIO_OUT) & ~gpio_pled);
(1 of 481): /* A hack. Not moving message rate limiting t 2677,7-14 63%
You can use the :cnext (:cn), :cprevious (:cp, :cNext, :cN) , and :cc
commands to page through the list of matches. Also :crewind (:crew,
:cfirst, :cf) goes to the first match and :clast (:cl) to the last. Finally, the
following command goes to the first match in the next file:
:cnfile
The :copen (:cope) command opens a new window containing all the items
found as seen in Figure 7-40.
if (rate_limit++ < 3)
3rdparty/acx/pci.c [RO] 2677,7-14 63%
3rdparty/acx/pci.c|2677 col 7| /* A hack. Not moving message rate limiting to
adev->xxx
3rdparty/at76c503a/at76_usb.c|5410 col 27| /* jal: this is a dirty hack needed by
Tim in ad-hoc mode */
3rdparty/at76c503a/at76_usb.c|5560 col 12| /* Magic hack for Novell IPX-in-802.3
packets */
3rdparty/ipw3945/ipw3945.c|11004 col 4| /* hack this function to show different
aspects of received frames,
3rdparty/ipw3945/ipw3945.c|11149 col 21| * but you can hack it to show more, if
you'd liketo. */
3rdparty/ndiswrapper/ntoskernel.c|1778 col 57| * related to ACPI: "_SM_" and
"_DMI_". This may be the hack they do
[Quickfix List] 1,1 Top
:cc
You can move up and down this list using the normal movement commands.
When you a item you are interested in, you can press <Enter> and Vim will jump
to that location.
Let's suppose you've written a Java program with Vim and wish to see if it
compiles. You write it out using the :w command and load it in Eclipse. Being a
typical programmer, the file needs some fixing, so you let Eclipse fix it. After
saving the file, the one in the Vim editor is out of date.
Vim will detect this and ask if you wish to load the file. If you answer yes,
it will read in the new file and let you continue editing. Eclipse will do the same
thing, so the two editors (Vim and Eclipse's internal editor) work well together as
long as you remember to save the changes after each edit.
Vim also has a option: 'autoread' ('ar') which will cause the editor to
automatically read a file when a change is detected.
Abbreviations
An abbreviation is a short word that takes the place of a long one. For
example, ad stands for advertisement. The Vim editor enables you to type in an
abbreviation and then will automatically expand it for you. To tell Vim to expand
the abbreviation ad into advertisement every time you type it, use the following
command:
:abbreviate ad advertisement
(:abbreviate can be abbreviated as :ab.)
Now, when you type ad, the whole word advertisement will be inserted into
the text.
What is Typed Result
I saw the a I saw the a
I saw the ad I saw the ad
I saw the ad<space> I saw the advertisement<space>
It is possible to define an abbreviation that results in multiple words. For
example, to define JB as Jack Benny, use the following command:
:abbreviate JB Jack Benny
As a programmer, I use two rather unusual abbreviations:
:abbreviate #b /****************************************
:abbreviate #e <space>****************************************/
These are used for creating boxed comments. The comment starts with #b,
which draws the top line. I then put in the text and use #e to draw the bottom
line. The number of stars (*) in the abbreviations is designed so that the right
side is aligned to a tab stop. One other thing to notice is that the #e abbreviation
begins with a space. In other words, the first two characters are space-star.
Usually Vim ignores spaces between the abbreviation and the expansion. To
avoid that problem, I spell space as seven characters: "<", "s", "p", "a", "c", "e",
">".
Note: The abbreviation is not expanded until after you finish the word by
typing a space, tab, or other whitespace. That is so that a word such as
addition won't get expanded to advertisementdition.
Mapping
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 configure Vim so that the F5 key
does this job. The command is as follows:
:map <F5> i{<Esc>ea}<Esc>
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. (In this
example, the trigger is a single key; it can be any string.)
i{<ESC> Insert the { character. Note that we end with the <Esc> key.
Note: When entering this command, you can enter <F5> by pressing the F5
key or by entering the characters <, F, 5, and >.
Either way works. However, you must enter <Esc> as characters. That is
because the <Esc> key tells Vim to abort the command. Another way of
entering an <Esc> key is to type CTRL-V followed by the <Esc> key. (The
CTRL-V tells Vim to treat the <Esc> as a literal character instead of acting
on it.)
Warning: The :map command can remap the Vim commands. If the trigger
string is the same as a normal Vim command, the :map will supersede the
command in Vim.
It does this by modifying the internal Vim definitions for backspace (t_kb)
and delete (t_kD). This command affects only the Vim keyboard mappings.
Your operating system may have its own keyboard mapping tables. For
example, Linux users can change their keyboard mapping by using the loadkeys
command. For further information, Linux users should check out the online
documentation for loadkeys.
The X Window system also has a keyboard mapping table. If you want to
change this table, you need to check out the xmodmap command. Check the X
Window system documentation for details on how to use this command.
Earlier versions of Vim (5.4 and prior) use the following option values.
These still work but are deprecated.
1 "indent,eol"
2 "indent,eol,start"
During startup, the Vim editor looks for an initialization file. If it is found, it
is automatically executed. (Only the first file found is read.) The initialization
files are as follows:
UNIX
$HOME/.vimrc
$HOME/_vimrc
$HOME/.exrc
$HOME/_exrc
MS-DOS
$HOME/_vimrc
$HOME/.vimrc
$VIM/_vimrc
$VIM/.vimrc
$HOME/_exrc
$HOME/.exrc
$VIM/_exrc
$VIM/.exrc
When you are running the GUI version, some other files are also read. The
gvimrc file is found in the same location as the vimrc files mentioned in the list.
The $VIMRUNTIME/[Link] is read too. One way you can find out which
initialization files are read is to use the :version (:ve) command:
:version
In the middle of all the junk it lists out is a list of the initialization files (see
Figure 8-3).
:version
:version
VIM - Vi IMproved 7.1 (2007 May 12, compiled Sep 7 2007 17:07:14)
Included patches: 1-87
Compiled by Anssi Hannula <anssi@[Link]>
Huge version with GTK2-GNOME GUI. Features included (+) or not (-):
+arabic +autocmd +balloon_eval +browse ++builtin_terms +byte_offset +cindent
+clientserver +clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
+cryptv +cscope
+cursorshape +dialog_con_gui +diff +digraphs +dnd -ebcdic +emacs_tags +eval
+ex_extra +extra_search +farsi +file_in_path +find_in_path +folding -footer
+fork() +gettext
-hangul_input +iconv +insert_expand +jumplist +keymap +langmap +libcall +linebreak
+lispindent +listcmds +localmap +menu +mksession +modify_fname +mouse +mouseshape
+mouse_dec
-mouse_gpm -mouse_jsbterm +mouse_netterm +mouse_xterm +multi_byte +multi_lang
-mzscheme +netbeans_intg -osfiletype +path_extra +perl +postscript +printer
+profile +python
+quickfix +reltime +rightleft -ruby +scrollbind +signs +smartindent -sniff
+statusline -sun_workshop +syntax +tag_binary +tag_old_static -tag_any_white +tcl
+terminfo
+termresponse +textobjects +title +toolbar +user_commands +vertsplit +virtualedit
+visual +visualextra +viminfo +vreplace +wildignore +wildmenu +windows
+writebackup +X11
-xfontset +xim +xsmp_interact +xterm_clipboard -xterm_save
system vimrc file: "/etc/vim/vimrc"
user vimrc file: "$HOME/.vimrc"
user exrc file: "$HOME/.exrc"
system gvimrc file: "/etc/vim/gvimrc"
user gvimrc file: "$HOME/.gvimrc"
system menu file: "$VIMRUNTIME/[Link]"
fall-back for $VIM: "/usr/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK
-I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/include/atk-1.0
-I/usr/include/cairo -I/usr/include/pan
go-1.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include
-I/usr/include/freetype2 -I/usr/include/libpng12 -DORBIT2=1 -pthread
-I/usr/include/libgnomeui-2.0 -I/usr/include/l
ibart-2.0 -I/usr/include/gconf/2 -I/usr/include/gnome-keyring-1
-I/usr/include/libgnome-2.0 -I/usr/include/libbonoboui-2.0
-I/usr/include/libgnomecanvas-2.0 -I/usr/include/gtk-
2.0 -I/usr/include/gnome-vfs-2.0 -I/usr/lib/gnome-vfs-2.0/include
-I/usr/include/orbit-2.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include
-I/usr/include/libbonobo-2.0 -I/u
sr/include/bonobo-activation-2.0 -I/usr/include/libxml2 -I/usr/include/pango-1.0
-I/usr/include/freetype2 -I/usr/include/gail-1.0 -I/usr/lib/gtk-2.0/include
-I/usr/include/atk-
1.0 -I/usr/include/cairo -I/usr/include/libpng12 -O2 -g -pipe
-Wp,-D_FORTIFY_SOURCE=2 -fstack-protector --param=ssp-buffer-size=4 -fexceptions
-fomit-frame-pointer -march=i
586 -mtune=generic -fasynchronous-unwind-tables -I/usr/local/include
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm
-I/usr/lib/perl5/5.8.8/i386-linux/CORE
One other initialization file has not yet been discussed: .exrc. The old Vi
editor used this file for initialization. This is only read if Vim cannot find any
other initialization file. Because the old Vi program does not understand many of
the Vim commands, you will probably want to put everything in the .vimrc file.
The :mkexrc (:mk) command writes the mappings to the .exrc file. If you want to
use all the power of Vim, however, you must use the :mkvimrc command instead.
My .vimrc File
My .vimrc file contains the following:
:syntax on
:autocmd FileType * set formatoptions=tcql
\ nocindent comments&
:autocmd FileType c,cpp set formatoptions=croql
\ cindent comments=sr:/*,mb:*,ex:*/,://
:set autoindent
:set autowrite
:ab #d #define
:ab #i #include
:ab #b /****************************************
:ab #e <Space>****************************************/
:ab #l /*-------------------------------------------- */
:ab #j Jack Benny Show
:set shiftwidth=4
:set hlsearch
:set incsearch
:set textwidth=70
The file starts with a command to turn syntax coloring on:
:syntax on
The next thing is an autocommand executed every time a file type is
determined (on file load). In this case, set the formatting options to tcql, which
means autowrap text (t), autowrap comments (c), allow gq to format things (q),
and do not break long lines in insert mode (l). I also turn off C-style indenting
(nocindent) and set the 'comments' option to the default (comments&):
:autocmd FileType * set formatoptions=tcql
\ nocindent comments&
If a C or C++ file is loaded, the following autocommand is executed. It
defines some additional format options, namely adding the comment header for
new lines (r) and new lines opened with an O command (o). It also turns on C
indentation and defines the 'comments' option for C- and C++-style comments.
Because this autocommand comes after the one for all files, it is executed second
(but only for C and C++ files). Because it is executed second, its settings
override any set by a previous autocommand:
:autocmd FileType c,cpp set formatoptions=croql
\ cindent comments=sr:/*,mb:*,ex:*/,://
The next options turn on automatic indentation (indent each line the same
as the preceding one) and autowriting (write files when needed). Note that
because the autocommands execute when the file type is determined, any
settings they have override these:
:set autoindent
:set autowrite
What follows is a set of abbreviations useful to programmers and a
collector of old Jack Benny radio shows:
:ab #d #define
:ab #i #include
:ab #b /****************************************
:ab #e <Space>****************************************/
:ab #l /*----------------------------------------------*/
:ab #j Jack Benny Show
The indentation size is set to 4, a value that studies have shown is best for
programming:
:set shiftwidth=4
The next two options turn on fancy searching:
:set hlsearch
:set incsearch
When working with text, I like a 70-column page:
:set textwidth=70
Script Files
To read a file containing Vim commands (and to execute the commands),
use the :source (:so) command:
:source [Link]
A special version of this command is the :runtime (:ru) command. This
searches the 'runtimepath' ('rtp') for the file. If the file is not present it
reports an error. (This is so you can find and load scripts that are part of the Vim
runtime.)
To see what files have already been loaded, use the :scriptnames (:scr)
command. Figure 8-4 shows the results.
1: /home/sdo/.vimrc
2: /usr/local/share/vim/vim71/syntax/[Link]
3: /usr/local/share/vim/vim71/syntax/[Link]
4: /usr/local/share/vim/vim71/syntax/[Link]
5: /usr/local/share/vim/vim71/[Link]
6: /home/sdo/.vim/plugin/[Link]
7: /usr/local/share/vim/vim71/plugin/[Link]
8: /usr/local/share/vim/vim71/plugin/[Link]
9: /usr/local/share/vim/vim71/plugin/[Link]
10: /usr/local/share/vim/vim71/plugin/[Link]
11: /usr/local/share/vim/vim71/plugin/[Link]
12: /usr/local/share/vim/vim71/plugin/[Link]
13: /usr/local/share/vim/vim71/plugin/[Link]
14: /usr/local/share/vim/vim71/plugin/[Link]
15: /usr/local/share/vim/vim71/plugin/[Link]
16: /usr/local/share/vim/vim71/plugin/[Link]
Press ENTER or type command to continue
Figure 8-4: Output of :scriptnames
Scripts which deal with non-English languages are a little tricky to read.
To help with the internationalization of Vim, the :scriptencoding (:scripte)
command lets you tell Vim what encoding to use for a script.
For example, Vim comes with a script that provides Chinese menu
translations, $VIMRUNTIME/langmenu_chinese_gb.[Link]. The beginning of
this script includes the line:
:scriptencoding cp936
To return the encoding to the default use the :scriptencoding command
with no parameters:
:scriptencoding
Even though it was line oriented, the ex editor was an extremely versatile
and efficient editor. It is still very useful today. Even with Vim's tremendous
command set, a few things are still better done with ex-style commands. So the
people who created Vim give you access to all the ex commands through the use
of command-line mode. Any command that begins with a colon(:) is considered
an ex-style command. This chapter shows how ex-mode commands are
structured and also discusses the most useful ones, including the following:
● Substitution
You will get a colon (:) prompt at the beginning of each line when you are
in Ex mode. This can be turned off by turning off the 'prompt' option. Also the
Q command4 will also enter Ex mode, but will not give you command line editing
capability.
4 Some distributions of Linux come with a system vimrc file which maps Q to gq (format text).
Ranges
:1% print
1 At one university the computer center was
...
36 Notice:
37
38 If your computer catches fire, please turn it
39 off and notify computing services.
The line number dot (.) is the current line. For example:
:. print
39 off and notify computing services.
You can also specify lines by their content. The line number /pattern/
specifies the next line containing the pattern.
Let's move up to the top with :1 print, and then print the lines from the
current line (.) to the first line containing the word trouble:
:1 print
1 At one university the computer center
was :.,/trouble/print
1 At one university the computer center was
2 experiencing trouble with a new type of
Similarly, ?pattern? specifies the first previous line with pattern in it. In
the following example, we first move to the end of the file with :39 print and
then print the last line with the word Notice in it to the end of the file:
:39 print
39 off and notify computing services. :?
Notice:?,39 print
36 Notice:
37
38 If your computer catches fire, please turn it
39 off and notify computing services.
Marks
Marks can be placed with the normal-mode m command. For example, the
ma command marks the current location with mark a.
You can use marks to specify a line for command-mode commands. The
line number 'a specifies the line with mark a is to be used. Start in normal mode,
for example, and move to the first line of the file. This is marked with a using the
command ma. You then move to line 3 and use the command mz to mark line as z.
The command
:'a, `z print
is the same as the following command:
:1,3 print
Next, enter the :print command to print these lines. The minute you
press :, Vim goes to the bottom of the screen and displays the following:
:'<,'>
The special mark < is the top line of the visual selection and the mark > is
the bottom. Thus, Vim is telling you that it will run the command on the visual
selection. Because < is on line 1, and > is on line 3, a :print at this point prints
lines 1 to [Link] full command, as it appears onscreen, looks like this:
:`<,`>print
Substitute Command
The :substitute command enables you to perform string replacements on
a whole range of lines. The general form of this command is as follows:
:range substitute /from/to/ flags
(Spaces were added for readability.)
This command changes the from string to the to string. For example, you
can change all occurrences of Professor to Teacher with the following
command:
:% substitute /Professor/Teacher/
Note: The :substitute command is almost never spelled out completely.
Most of the time, people use the abbreviated version :s. (The long version
is used here for clarity.)
Suppose you have a file containing a list of names in the form last, first,
and you want to change it to first, last. How do you do it?
Note: This command uses regular expressions which are covered in detail
in Chapter 19: Advanced Searching Using Regular Expressions.
Substitute from
Substitute to
The :write command usually does not overwrite an existing file. The
force (!) option causes it to ignore this protection and to destroy any existing
file. The :write command proves extremely useful when it comes to exporting
portions of a large file to a smaller one--for example, if you have a collection of
jokes and want to write one out to a file to send to a friend. To export a single
joke, first highlight it in visual mode. Then use the following command to write it
out to the file [Link]:
:'<,'> write [Link]
in Inches
mm Millimeters
Mouse Usage
Standards are wonderful. In Microsoft Windows, you can use the mouse to
select text in a standard manner. The X Window system also has a standard
system for using the mouse. Unfortunately, these two standards are not the
same. Fortunately, you can customize Vim. You can make the behavior of the
mouse look like an X Window system mouse or a Microsoft Windows mouse. The
following command makes the mouse behave like an X Window mouse:
:behave xterm
(:behave can be abbreviated as :be.)
The following command makes the mouse look like a Microsoft Windows
mouse:
:behave mswin
The default behavior of the mouse on UNIX systems is xterm. The default
behavior on a Microsoft Windows system is selected during the installation
process. In addition to controlling the behavior of the mouse, the :behave
command affects the following options:
X Mouse Behavior
You can issue a number of other special commands for the mouse,
including the following
<S-LeftMouse> Search forward for the next occurrence
of the word under the cursor.
<S-RightMouse> Search backward for the preceding
occurrence of the word under the
cursor.
Tear-Off Menus
The menus in Vim (all GUI versions except Athena) have an interesting
feature: "tearoff " menus. If you select the first menu item (the dotted lines), you
can drag the menu to another location on the screen. Figure 10-3 shows how to
tear off a menu.
Drag to
tear off
When torn off, the menu remains as its own window until you close it using
the normal window close command.
Toolbar
A toolbar appears in the GTK and MS-Windows versions of the GUI. It looks
something like Figure 10-4. The icons perform the following functions:
The 'cursorline' ('cul') option highlights the line the cursor is on.
(Warning: This command uses a different highlighting than 'cursorcolumn' and
by default, does not highlight the background.)
● Troff-related commands
1 2 3
12345678901234567890123456789012345
I taught programming for a
while
Continuing on, you can type in the rest of the paragraph:
1 2 3
12345678901234567890123456789012345
I taught programming for a
while. One time, I was stopped
by the Fort Worth police
because my homework was too
hard. True story.
You do not have to type newlines; Vim puts them in automatically. You can
specify when to break the line in two different ways. The following option tells
Vim to break the line 30 characters from the left side of the screen:
:set textwidth=30
If you use the following option, you tell Vim to break the lines so that you
have margin characters from the right side of the screen.:
:set wrapmargin=margin
('wm' is short for 'wrapmargin'.)
The Vim editor is not a word processor. In a word processor, if you delete
something at the beginning of the paragraph, the line breaks are reworked. In
Vim they are not; so if you delete some words from the first line, all you get is a
short line:
1 2 3
12345678901234567890123456789012345
I taught for a
while. One time, I was stopped
by the Fort Worth police
because my homework was too
hard. True story.
This does not look good; so how do you get the paragraph into shape?
There are several ways. The first is to select the paragraph as part of a visual
selection:
I taught for a
while. One time, I was stopped
by the Fort Worth police
because my homework was too
hard. True story.
Then you execute the gq command to format the paragraph.
I taught for a while. One
time, I was stopped by the
Fort Worth police because my
homework was too hard. True
story.
Another way to format a paragraph is to use the gqmotion command.
Therefore to format 5 lines, you use the command gq4j. (The 4j tells gq to
format this line and the next 4 -- 5 lines total.)
The move forward paragraph command (})also proves useful in such cases.
To format a paragraph, for example, position the cursor on the first line of the
paragraph and use the command gq}. It is much easier to use this command than
to count the lines.
The command gqip formats the current paragraph. (The gq formats the
selected text and the ip selects the "inner paragraph.") This is easier than gq}
because you don't have to put the cursor on the beginning of a paragraph.
Finally, to format a line, use the gqgq command. You can shorten this to
gqq.
Justifying Text
The Vim editor has no built-in way of justifying text. However, there is a
neat macro package that does the job. To use this package, execute the
following command:
:source $VIMRUNTIME/macros/[Link]
This macro file defines a new visual command _j.To justify a block of text,
highlight the text in visual mode and then execute _j.
The J command joins two lines putting in one space to separate them. If
the 'joinspaces' option is set, when the first line ends with a punctuation mark
(period, question mark, or exclamation point), two spaces are added. Input the
following (= represents a space):
This=is=a=test.
Second=line.
When the 'joinspaces' option is turned off with the following command
:set nojoinspaces
the result of a J on the first line is as follows:
This=is=a=test.=Second=line .
If the option is set using this command
:set joinspaces
the result is as follows:
This=is=a=test.==Second=line .
This tells Vim to not only wrap comments, but also to reformat comments
as part of a gq command.
The 2 option tells Vim to format based on the second line of the text rather
than the first. For example, the original example text is displayed in Figure 11-1.
If you do not have the 2 flag in the 'formatoptions' and you reformat the
paragraph with gq}, you get the results shown in Figure 11-2.
The first Centronics Printer manual had a whole
chapter devoted to how to open up the packing
crate and find the manual. (What did they think we
were reading anyway?)
~
~
~
~
~
Figure 11-1: The original text.
If you go back to the original paragraph, however, set the 2 flag with the
following
:set formatoptions += 2
and reformat using gq}, you will get the results shown in Figure 11-3.
The first Centronics Printer manual
had a whole chapter devoted to how to
open up the packing crate and find the
manual. (What did they think we were
reading anyway?)
~
~
~
~
Figure 11-3: Formatted text (2 set).
The v flag character controls where a line will be split. Suppose that you
have the following line:
This is a test of the very long line wrapping
Now add the word logic to the end of the sentence. Without the v flag,
the result is as follows:
This is a test of the very
long line wrapping logic.
With v in 'formatoptions', you get the following:
Vim will attempt to recognize numbered lists and properly format them. In
order to tell what a number list looks like, it is matched against the string in the
'formatlistpat' ('flp') option. By default this is: ^\s*\d\+[\]:.)}\t ]\s*
which translates to beginning of line (^), any number of spaces (\s*), one or
more digits (\d\+), any one of the characters: ]:.)}, <tab> or <space>, followed
by a bunch of spaces (\s*).
You can also use the 'formatexpr' ('fex') option to define an expression
which will tell Vim how to format a paragraph. If both 'formatexpr' and
'formatprg' are set, 'formatexpr' will be used.
Even without this option, however, you can always use the filter (!)
command to format text. To run a paragraph through the program fmt, for
example, use the command !}fmt. The ! starts a filter command, the } tells Vim
to filter a paragraph, and the rest (fmt) is the name of the command to use.
Basic Spelling
Vim can spell check your text on the fly. Words that are not spelled
correctly will be highlighted. By default this feature is turned off, to turn it on,
set the 'spell' option:
:set spell
Figure 11-4 shows an editing session with lots of misspelled words and
spell checking enabled. (In this example we use underline to indicate a
misspelled word. The Vim GUI actually uses a read squiggly line which is
impossible to reproduce in a black and white book.)
A church hhad just bought ttheir first
computer and were learning how to uuse it.
The church secretary ddecided to set uppp
a form letter to be used in a ffuneral
service. Where tthe person's name was to
be she put in tthe word "<name>". When a
funeral occurred she would change this
word to tthe actual name of tthe departed.
Figure 11-4: Editing with spelling errors highlighted
Now that you can see which words are bad, it would be nice to get them
corrected. To get a list of suggested fixes for the bad word, position the cursor
on a misspelled word and enter the command z=. Figure 11-5 shows the result.
Change "hhad" to:
1 "had"
2 "head"
3 "shad"
4 "Had"
5 "hand"
6 "hard"
7 "Head"
8 "Chad"
Type number (<Enter> cancels):
Figure 11-5: Result of the z= command
To change the word, just enter the number of the replacement (in this
example 1). If you don't want to change anything, just press <Enter>.
Note: The change you make is stored in the . (dot) command so you can
repeat it as needed.
If you are like me and you make the same spelling mistakes over and over
again the same way, you'll want to fix all the spelling errors like one. (I must
remember that “beleive” is spelled “believe”.)
To find the next misspelled word use the ]s command. The ]S does the
same thing, only it does not stop on rare words or words that come from another
region.
Both the ]s and ]S commands start from the current cursor location for
their searches. If you want to start from the beginning of the file use the [s and
[S commands.
Spelling Language
Unfortunately everyone in the world does not speak the same language. If
you need to change the language Vim uses for spell checking, set the
'spelllang' ('spl') option. This option takes a comma separated list of
dictionaries to use for spell checking. If a spellfile for that language is not
available, Vim will ask if you want to download it. For example:
:set spelllang=de
not found in 'runtimepath': "spell/[Link]"
not found in 'runtimepath': "spell/[Link]"
Cannot find spell file for "de" in
Do you want me to try downloading it?
(Y)es, [N]o:
Note: Automatic downloading is not enabled if you don't have the ability to
write into the directory containing the spelling files ($RUNTIME/spell).
CAT
Word Lists
Vim lets you create your own word list to augment the built-in dictionary.
To really use this feature you need to first set the 'spellfile' ('spf') option.
The name of this file must end in .add. For example:
:set spellfile=my_words.add
Now suppose you find that you have a perfectly good word in your
document but it's not in the dictionary. To add it to your local word list, put the
cursor on the word and enter the command zg. The word will be added to your
local word list.
You may notice that two files are created: my_words.add and
my_words.[Link]. The second file is a compiled version of the first. In fact Vim
compiles all it's dictionaries for speed. In this case my_words.[Link] is compiled
automatically.
Vim not only keeps track of good words, but bad words as well. For
example, if your file contains the words "ain't" and you consider that an
abomination, then you can put in the bad word list by positioning the cursor on
the word and entering the command zw.
As with zg, the word marked by zw goes into the spell file. However it is
flagged as a badly spelled word.
If you accidentally put a bad word on the good list, the zug command
removes the from the list. The zuw command does the same thing only it
removes a word that flagged as wrong.
Vim also maintains a internal word list. This list is stored in memory and
goes away after each editing session. To add a word to the internal good list,
enter the command zG. For bad words, use the command zW.
And of course the zuG and zuW remove words from the internal list.
The spelling commands (zg, zG, zw, zW, zug, zuG, zuw, zuW) have their own
command mode versions.
Vim allows you to use multiple word lists for spelling. The 'spellfile'
option actually takes a comma separated list of word files.
:set spellfile=[Link],[Link]
Each of the word commands (zg, zw, zug, zuG, :spellgood, :spellwrong,
:spellundo) takes a numeric argument. For example, the zg command adds the
word under the cursor to the first word file. The command 2zg will add it to the
second file ([Link]). The commend :2spellgood {word} will do the same
thing.
The :spellinfo (:spelli) command lists the dictionary files being used.
:spellinfo
file: /usr/local/share/vim/vim71/spell/[Link]
File Formats
Back in the early days, the old Teletype machines took two character times
to do a newline. If you sent a character to the machine while it was moving the
carriage back to the first position, it tried to print it on-the-fly, leaving a smudge
in the middle of the page. The solution was to make the newline two characters:
<Return> to move the carriage to column 1, and <Line Feed> to move the paper
up.
When computers came out, storage was expensive. Some people decided
that they did not need two characters for end-of-line. The UNIX people decided
they could use <Line Feed> only for end-of-line. The Apple people standardized
on <Return>. The MS-DOS (and Microsoft Windows) folks decided to keep the
old <Return><Line Feed>.
This means that if you try to move a file from one system to another, you
have line problems. The Vim editor automatically recognizes the different file
formats and handles things properly behind your back.
Note: If you are an old Vi user and tried to edit an MS-DOS format file, you
would have found that each line ended with a ^M character. (^M is
<Return>.) Fortunately, Vim handles UNIX, MS-DOS and Apple file
formats automatically.
The option 'fileformats' ('ffs') contains the various formats that will
be tried when a new file is edited. The following option, for example, tells Vim to
try UNIX format first and MS-DOS format second:
:set fileformats=unix,dos
The detected file format is stored in the 'fileformat' ('ff') option. To
see which format you have, execute the following command:
:set fileformat?
You can use the 'fileformat' option to convert from one file format to
another. Suppose, for example, that you have an MS-DOS file named [Link]
that you want to convert to UNIX format. Start by editing the MS-DOS format
file:
$ vim [Link]
Now change the file format to UNIX:
:set fileformat=unix
When the file is written, it will be in UNIX format.
:set endofline
(Last line ends in <EOL>.) or
:set noendofline
(Last line does not have an <EOL>.) This option only works when the
'binary' option is set.
Troff-Related Movement
A number of commands enable you to move through text. The ) command
moves forward one sentence. The ( command does the same thing backward.
At one time the troff program was the standard UNIX word processor. It
takes as input a text file with processing directives in it and formats the text.
Although troff is rarely used these days, the Vim editor still contains an option
for dealing with this formatter.
The troff program uses macros to tell it what to do. Some of these macros
start paragraphs. In the following example, for instance, the macro .LP starts
each paragraph:
Because troff uses lots of different macro packages, Vim needs to know
which macros start a paragraph. The 'paragraphs' ('para') option does this.
The format of this option is as follows:
:set paragraphs="macromacromacro..."
Each macro is the two-character name of a troff macro. For example:
:set paragraphs="P<Space>LP"
tells Vim that the macros .P and .LP start a paragraph. (Note that you use
P<Space> to indicate the .P macro.)
.P .LI
Section Moving
The [[ and [] commands move a section backward. A section is defined
by any text separated by a page break character (CTRL-L). The reason there are
two movement commands is that these commands also move to the beginning
and end of procedures. (Chapter 7: Commands for Programmers contains
information on programming commands.)
This is page 1
]] ^L
This is page 2
Another paragraph
]] ^L
This is page 3
with a two line paragarph
And another one
~
~
~
~
~
~
Figure 11-7: The ]] command.
Defining Sections
You can also define a section using troff macros. The 'sections'
('sect')option acts much like the 'paragraph' option, except that it defines the
macros that separate sections rather than paragraphs. The default is:
:set sections=SHNHH HUnhsh
● Automatic completion
Automatic Completion
When you are entering text, Vim can assist you to complete words.
Suppose, for example, that you are creating a C program and want to type in the
following:
total = ch_array[0] + ch_array[1] + ch_array[2];
You start by entering the following:
total = ch_array[0] + ch_
At this point, you tell Vim to complete the word using the command
CTRL-P. This command tells Vim to search for a word to complete. In this case,
it is the word ch_array. So typing CTRL-P gives you the following:
total = ch_array[0] + ch_array
After a little more typing, you get this:
total = ch_array[0] + ch_array[1] +
If you now type CTRL-P again, Vim will search again for a word that
completes the word before the cursor. (In this case, it is "".) The first word that
matches is ch_array.
Typing CTRL-P again gives you the next word that matches (in this case,
total).
A third CTRL-P causes the editor to run out of words, so it returns to the
original entry: "".
A fourth CTRL-P causes the editor to start over again with ch_array.
1. Current file
You can customize the search order. (This is described in the section
Automatic Completion Details below.)
Searching Forward
When you type CTRL-P, Vim searches backward for a word to complete.
The CTRL-N command searches forward. Other than the direction, it acts just
like the CTRL-P command.
When you match words in this way, the completed word takes on the case
of the matched word. Therefore, the completion list for ins is as follows: instep
Inside, INSERT.
What if you want to match INSERT, but put the word insert (lowercase) in
your text. You must tell Vim to infer the case of the new word from what is
typed, not what is matched. You can set the option 'infercase' ('inf'),
:set infercase
Vim uses the 'path' ('pa') option to tell it where to look for files that were
included in the current file. (Note that the 'path' option also is used for other
commands such as :find.)
Specifying a Dictionary
File include.h
#define MAX(x, y) ((x) < (y) ? (y) : (x))
#define MIN(x, y) ((x) < (y) ? (x) : (y))
int sum(int i1, int i2) {
return(i1+i2);
}
File main.c
#include "include.h"
#define MORE "/usr/ucb/more"
You can start by editing main.c. If you type CTRL-X, you enter CTRL-X
mode. The editor now displays a mini-prompt at the bottom of the screen (see
Figure 12-1).
#include "include.h"
#define MORE "/usr/ucb/more"
~
~
~
-- ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)
Figure 12-1: CTRL-X mode.
Suppose that you want to look for a macro definition. You would now type
CTRL-D. The screen displays the fact that there are three matches, and then
displays a new menu (see Figure 12-2).
#include "include.h"
#define MORE "/usr/ucb/more"
MAX
MAX include.h
MIN include.h
MORE
~
~
~
-- Definition completion (^D/^N/^P) --
Figure 12-2: CTRL-X CTRL-D.
At this point, CTRL-N searches for the next match (and CTRL-P searches for
the previous one). The CTRL-D key acts just like CTRL-P. Using these keys, you
can cycle through the list of definitions until you find the one that you want.
Tag Search
The CTRL-X CTRL-] command searches for the next tag. A tag is a C/C++
function definition. The program ctags generates a list of C/C++ function
definitions (tags) and stores them in the tags file. We have generated our tags
file using the following command:
$ ctags *.c *.h
Now when we enter CTRL-X CTRL-] in insert mode, we get what is shown
in Figure 12-3
#include "include.h"
#define MORE "/usr/ucb/more"
MORE
MORE
!_TAG_FILE_FORMAT
!_TAG_FILE_SORTED
!_TAG_PROGRAM_AUTHOR
!_TAG_PROGRAM_NAME
!_TAG_PROGRAM_URL
!_TAG_PROGRAM_VERSION
MAX
MIN
sum
~
~
~
-- Tag completion (^]/^N/^P) --
Figure 12-3: CTRL-X CTRL-].
By default, the Vim editor just displays the name alone. If you execute the
following command, the entire tag (the function prototype) displays:
:set showfulltag
('sft' is the short form of 'showfulltag')
If you repeat your matching commands with this option enabled, you get
the results shown in Figure 12-5.
#include "include.h"
#define MORE "/usr/ucb/more"
int sum(int i1, int i2)
MORE
MORE
!_TAG_FILE_FORMAT
xtended format; --format=1 will not append ;" to lines/
!_TAG_FILE_SORTED
=unsorted, 1=sorted, 2=foldcase/
!_TAG_PROGRAM_AUTHOR
hiebert@[Link]/
!_TAG_PROGRAM_NAME
!_TAG_PROGRAM_URL
fficial site/
!_TAG_PROGRAM_VERSION
MAX
MIN
sum
int sum(int i1, int i2) {
~
~
~
-- Tag completion (^]/^N/^P)--
Figure 12-5: The results.
Finding Filenames
If you use the CTRL-X CTRL-F command, the Vim editor will match a
filename. It scans the current directory for files and displays each one that
matches the word in front of the cursor. Suppose, for example, that you have the
following files in the current directory:
The result:
The exit code is in the file sub_exit.c
Line Mode
All the commands discussed so far work on words only. The CTRL-X
CTRL-L command works on lines. If you enter CTRL-X CTRL-L in the example,
for instance, you get the results shown in Figure 12-6. You can now use CTRL-N
and CTRL-P to go up and down lines.
#include "include.h"
#define MORE "/usr/ucb/more"
#define MORE "/usr/ucb/more"
#include "include.h"
#define MORE "/usr/ucb/more" ~
~
~
-- Whole line completion (^L/^N/^P)--
Figure 12-6: CTRL-X CTRL-L.
The command CTRL-X CTRL-K searches the dictionary files for the given
word.
The CTRL-X CTRL-T command does the same thing except that the word
files specified by 'thesaurus' ('tsr') option are used.
Guessing
The CTRL-X CTRL-V command guesses what type of word is before the
cursor and performs the approbate completion.
● Basic autocommands
● Autocommand groups
Basic Autocommands
Suppose you want to put a date stamp on the end of a file every time it is
written. One way you could do this is to define a function:
:function DateInsert()
: $read !date " Insert the date at the
: " end ($) of the file.
:endfunction
Now when you want to write the file all you have to do is to call this
function:
:call DateInsert()
Then you write the file.
If you forget, however, and use the normal Vim file writing commands, you
screw things up. It would be nice if you could do things automatically. That is
where autocommands come in.
The command
:autocmd FileWritePre * :call DateInsert()
causes the command :call DateInsert() to be executed for all files (*)
just before writing the file (FileWritePre).
Groups
The :augroup (:aug) command starts the definition of a group of
autocommands. The group name is just a convenient way to refer to the set of
autocommands. For example:
:augroup cprograms
: autocmd FileReadPost *.c :set cindent
: autocmd FileReadPost *.cpp :set cindent
:augroup END
Because the :autocmd definitions are inside the scope :augroup, they are
put in the cprograms group. The commands in this group are executed after
reading a file that ends in .c or .cpp. If you want to add another command to this
group for headers, you can use the :augroup command or just include a group
name in your specification:
:autocmd cprograms FileReadPost *.h :set cindent
Now suppose you are editing a file called [Link] that you would like
treated as a C program. You can tell Vim to go through all the cprograms
autogroup commands and execute the ones that match *.c for the FileReadPost
event. The command to do this is:
Note: Do not use this to trigger autocommands that switch buffers, create
buffers, or delete them. In other words, when using this command, leave
the buffers alone.
Events
You can use the following events to trigger an autocommand:
BufNewFile Triggered when editing a
file that does not exist.
BufReadPre BufReadPost Triggered before
(BifReadPre) / after
(BufReadPost) reading a
buffer.
BufRead Alias for BufReadPost.
BufFilePre BufFilePost Before / after changing
the name of a buffer with
the :file (:f) command.
When writing a file, Vim triggers only one pair of the following events:
BufWritePre BufWritePost
FilterWritePre FilterWritePost
FileAppendPre FileAppendPost
FileWritePre FileWritePost
When reading a file, one of the following set of events will be triggered:
BufNewFile
BufReadPre BufReadPost
FilterReadPre FilterReadPost
FileReadPre FileReadPost
File Patterns
The filename pattern matching uses the UNIX standard system. The
following list identifies the special characters in the file matching patterns.
* Match any characters, any length
? Match any single character
, Separates alternate patterns such as: one,two,three which
matches the string one, two, or three.
Nesting
Generally, commands executed as the result of an autocommand event will
not trigger any new events. For example, suppose you define a :autocmd which
responds to the Syntax event by reading a file. You also have a :autocmd
defined for the event FileReadPre. So a Syntax event is triggered, this causes a
file read which would normally trigger a FileReadPre event. Except because
you are already in a :autocmd and events do not next, the second event is
ignored. However, if you include the keyword nested, then events within events
will trigger a :autocmd. For example:
:autocmd FileChangedShell *.c nested e!
Listing Autocommands
The following command lists all the autocommands:
:autocmd
For example:
:autocmd
--- Auto-Commands --
filetype BufEnter
*.xpm if getline(1) =~ "XPM2"|set ft=xpm2|endif
*.xpm2 set ft=xpm2
...
FileType
* set formatoptions=tcql nocindent comments&
c set formatoptions=croql cindent
...
filetype StdinReadPost
* if !did_filetype()|so [Link]|endif
Syntax
OFF syn clear
abc so $VIMRUNTIME/syntax/[Link]
(Listing truncated.)
From this, you can see a number of commands under the group filetype.
These command are triggered by the BufEnter and StdinReadPost events.
There are also a couple of commands with no group name triggered by the
FileType event. If you want a subset of all the commands, try the following:
:autocmd group event pattern
If group is specified, only the commands for that group are listed. Event
can be one of the previously defined events or * for all events. The pattern
specifies an optional file matching pattern. Only the commands that match are
listed.
For example:
:autocmd filetype BufEnter *.xpm
--- Auto-Commands --
filetype BufEnter
*.xpm if getline(1) =~ "XPM2"|set ft=xpm2|endif
Removing Commands
The command :autocmd! removes autocommands. The matching rules
are the same for listing commands, so the following removes all the
autocommands:
:autocmd!
To remove the commands for a specific group, execute this command:
:autocmd! group
You can also specify events and patterns for the group, as follows:
:autocmd! group event pattern
Again, event can be * to match all events. You can use the :autocmd!
command to remove existing commands and define a new one in one command.
The syntax for this is as follows:
:autocmd! group event pattern nested command
This is the equivalent of the following:
:autocmd! group event pattern
:autocmd group event pattern nested command
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 all Window Enter and Leave events to ignored:
:set eventignore=WinEnter,WinLeave
('eventignore' can be abbreviated as 'ie')
:set eventignore=all
● Encryption
Command-Line Arguments
There are several useful command-line arguments. The most useful is
--help, which displays a short help screen listing all the command-line argu-
ments:
$ vim --help
VIM - Vi IMproved 7.0 (2006 May 7, compiled Jun 27 2006 19:50:12)
Arguments:
-- Only file names after this
-g Run using GUI (like "gvim")
-f or --nofork Foreground: Don't fork when starting GUI
-- lots more help --
To find out which version of Vim you have as well as to list the compilation
options, use the following command:
$ vim –version
VIM - Vi IMproved 7.0 (2006 May 7, compiled Jun 27 2006 19:50:12)
Compiled by oualline@[Link]
Normal version with GTK2 GUI. Features included (+) or not (-):
-arabic +autocmd +balloon_eval +browse +builtin_terms +byte_offset +cindent
+clientserver +clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
-- more compile options --
+wildignore +wildmenu +windows +writebackup +X11 -xfontset +xim +xsmp_interact
+xterm_clipboard -xterm_save
system vimrc file: "$VIM/vimrc"
user vimrc file: "$HOME/.vimrc"
user exrc file: "$HOME/.exrc"
system gvimrc file: "$VIM/gvimrc"
user gvimrc file: "$HOME/.gvimrc"
system menu file: "$VIMRUNTIME/[Link]"
fall-back for $VIM: "/usr/local/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK -DXTHREADS
-- long command --
To view a file, you can "edit" it in read-only mode by using the -R command:
$ vim -R [Link]
On most systems, the following command does the same thing:
$ view [Link]
This actually starts “editing” the file with the 'modifiable' ('ma') option
turned off. You can turn on this option if you want to change the file.
Encryption
The -x argument tells Vim to encrypt the file. For example, create a file
that contains something you want to keep secret:
$ vim -x [Link]
The editor now prompts you for a key used for encrypting and decrypting
the file:
Enter encryption key:
You can now edit this file normally and put in all your secrets. When you
finish editing the file and tell Vim to exit, the file is encrypted and written.
If you try to print this file using the cat or type commands, all you get is
garbage.
The option 'key' contains your encryption key. If you set this option to
the empty string (""), you turn off encryption:
:set key=
If you set this to a password, you turn on encryption. For example:
:set key=secret (Not a good idea!)
Setting the encryption key this way is not a good idea because the
password appears in the clear. Anyone shoulder surfing can read your password.
To avoid this problem, the :X command was created. It asks you for an
encryption key and sets the key option to whatever you type in. (Note that the
password will not be echoed. Instead * is printed for each character entered.)
:X
Enter encryption key:
Limits on Encryption
One way to avoid letting people read your swap file is to avoid using one. If
the -n argument is supplied on the command line, no swap file is used (instead,
Vim puts everything in memory). For example, to edit the encrypted file [Link]
and to avoid swap file problems use the following command:
$ vim -x -n [Link]
Note: If you use the -n argument, file recovery is impossible.
Also while the file is in memory, it is in plain text. Anyone with privileges
can look in the editor's memory and discover the contents of the file. If you use a
.viminfo file, be aware that the contents of text registers are written out in the
clear as well. If you really want to secure the contents of a file, edit it only on a
portable computer not connected to a network, use good encryption tools, and
keep the computer locked up in a big safe when not in use.
The Vim editor does a superb job as a screen-oriented editor when started
in normal mode. For batch processing, however, it does not lend itself to
creating clear, commented command files; so here you will use ex mode instead.
This mode gives you a nice command-line interface that makes it easy to put into
a batch file.
Foreign Languages
The Vim editor can handle a variety of languages. Unfortunately, to edit
these languages, you do not only need a Vim editor with the language features
compiled in, but you also need special fonts and other operating system support.
This means that unfortunately foreign language support is beyond the scope of
this book.
But the command-line arguments for the foreign languages are as follows:
-F Farsi
-H Hebrew
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
('bk' is the short name for 'backup'.)
The name of the backup file is the original file with a "~" added to the end.
If your file is named [Link], for example, the backup file name is [Link]~. If
you do not like the fact that the backup files end with ~, you can change the
extensions by using the following:
:set backupext=string
('bex' is the short name for 'backupext'.)
The Vim editor goes you one better when it comes to the backup file. If you
set the 'patchmode' ('pm') option, Vim backs up the file being edited to a file
with the same name, but with the 'patchmode' string appended to it. This will
be done only if the file does not exist. For example, suppose you execute this
command:
:set patchmode=.org
Now you edit the existing file [Link] for the first time. When you exit Vim
checks to see whether the file [Link] exists. It does not, so the old file is
saved under that name. The next time you edit, the file does exist; so the backup
is written to [Link]~.The file [Link] is not used from now on. Instead, all
backups will go to [Link]~ .
Usually Vim puts the backup file in the same directory as the file itself. You
can change this with the 'backupdir' ('bdir') option. For example, the
following causes all backup files to be put in the ~/tmp directory:
:set backupdir=~/tmp/
This can create problems if you edit files of the same name in different
directories. That is because their backup files will all go to the ~/tmp directory
and the name collision will cause the old backup files to disappear.
For some directories it is not useful to write a backup file. For example
you don't really need to backup temporary files in /tmp. The list of such files is
defined by the 'backupskip' ('bks') option. It is a list of strings. Any file
matching any one of these strings will not be backed up.
1. Vim checks to see whether the file has been changed outside of Vim.
For example, someone could have overwritten the file with a new one. If
this happens, a warning is issued and the editor asks if you want to
continue.
4. If the 'patchmode' option is set and no patch file exists, the backup
file is renamed to become the patch file.
The reason that Vim overwrites the existing file is to preserve any hard
links that you might have on a UNIX system. On non-UNIX systems the backup
is created by renaming the original file instead of making a copy.
Note: If you set the 'nobackup' and 'nowritebackup' options, Vim just
overwrites the existing file. This can cause loss of data if the disk fills up
during the file update.
By default, the 'writebackup' option is set. This means that the system
Vim uses to write a file makes it very difficult to lose data. By using this
method, there is no chance you will lose your file if the disk fills up. You may not
be able to write out the new version of the file, but at least you do not lose the
old one.
There are two ways to create a backup file. The one discussed above is
triggered when 'backupcopy' ('bkc') is set to no. The backup method is:
There are a number of subtitle problems with this system. First any hard
links that pointed to the original file, now point to the backup. Second if the
original file was owned by someone else, it is now owned by you.
To avoid these problems (and create others) you can set 'backupcopy' to
yes. If this happens the Vim creates the backup file using the following steps:
2. Truncate current
Because the file is not deleted or renamed, all the links and permissions
remain. However, it does take time to copy the original file to the backup.
The 'backupcopy' option has a third value: auto. When set to auto Vim
will figure out the most efficient way of creating the backup and then use it.
If the editor is aborted during mid-edit, however, it does not get a chance
to delete the swap file. This means that if you are in the middle of Vim sessions
and your system locks, forcing a reboot, the swap file will not be deleted.
When Vim first starts editing a file, it checks for a swap file. If it finds one,
that means that either another editing session is in progress or another editing
session was started and the editor got aborted. Therefore, Vim issues a warning
(see Figure 14-1), and gives you a chance to decide what to do.
~
~
~
~
~
ATTENTION
Found a swap file by the name ".[Link]"
dated: Thu Feb 17 22:44:00 2000
owned by: sdo
file name: /tmp/[Link]
modified: no
host name: [Link]
user name: sdo
process ID: 8449 (still running)
While opening file "[Link]"
dates: Thu Feb 17 22:45:33 2000
(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 [Link]"
to recover the changes (see ":help recovery)".
If you did this already, delete the swap file ".[Link]"
to avoid this message.
Several options and other commands affect file recovery. See the snext
section for more information.
The Vim editor goes to a great deal of trouble not to overwrite any old
swap files. The first time a file is edited, the swap file name is .[Link]. If
the editor is aborted and you start editing again, the next swap file is called
.[Link], and then .[Link], and so on. You can tell Vim to recover using a
specific swap file by specifying the name of the swap file with the command:
$ vim -r [Link]
To find out the name of the swap file you are currently using, execute the
following command:
:swapname
(;swapname can be abbreviated as :sw.)
Usually the swap file is written every 4 seconds or when you type 200
characters. These values are determined by the 'updatecount' ('uc') and
'updatetime' ('ut') options. To change the amount of time Vim waits before
writing the swap file to 23 seconds, for example, use the following command:
:set updatetime=23000
Note: The 'updatetime' is specified in milliseconds.
To change the number of characters you have to type before Vim writes
stuff to the swap file to 400, for instance, use this command:
:set updatecount=400
If you change the 'updatecount' to 0, the swap file will not be written.
However, the decision whether to write a swap file is better controlled by the
'swapfile' option. If you have this option set, a swap file will be created (the
default):
:set swapfile
If you do not want a swap file, use the following command:
:set noswapfile
('swf' is the short name for 'swapfile'.)
This option can be set/reset for each edited file. If you edit a huge file and
don't care about recovery, set 'noswapfile'. If you edit a file in another
window, it will still use a swap file.
On most operating systems, when you "write" a file, the data usually goes
into a memory buffer and is actually written to the disk when the operating
system "thinks" it is appropriate. This usually takes only a few seconds. If you
want to make sure that the data gets to disk, however, you want to use the
following command:
:set swapsync
('sws' is the short name for 'swapsync')
This command tells Vim to perform a sync operation after each writing of
the swap file to force the data onto the disk. The 'swapsync' option can be
empty, fsync, or sync, depending on what system call you want to do the writing.
Generally, Vim writes the swap file in the same directory as the file itself.
You can change this by using the 'directory' ('dir') option. For example, the
following tells Vim to put all swap files in /tmp:
:set directory=/tmp (Not a good idea)
This is not a good idea because if you try to edit the file [Link] in two
different directories at the same time, you encounter a swap file collision.
However, this command overwrites your existing file with all your changes.
The following is a related command:
:preserve
(:preserve can be written as :pre.)
This command writes all the edits to the swap file. The original file
remains unchanged and will not be changed until you do a :write or exit with
ZZ. If the system crashes, you can use the swap file to recover all your edits.
Note that after a :preserve, you can recover even if the original file is lost.
Without this command, you need both the original file and the swap file to
recover.
If you want to discard any changes you have made to the file and attempt
to recover, use the following command:
:recover! [Link]
MS-DOS Filenames
If you are on an MS-DOS or Windows 3.1 machine, you are stuck with very
limited filenames. The Vim editor detects this and limits the swap filename to
something that can be used on this type of machine. Whereas the normal swap
file for [Link] is .[Link], for example, if you are in short name mode, it is
foo_txt.swp.
You can set the 'shortname' option to force Vim to use this convention.
This is useful if have a Linux or other system and are editing files on an MS-DOS
partition. In this case, the operating system (Linux) supports long filenames,
but the actual disk you are working on (MS-DOS format) does not. Therefore,
you need to tell Vim to use the short swap names by giving it the following
command:
:set shortname
This option is not available for the MS-DOS version of Vim because it
would be always on. Instead, it is used when you are cross-platform editing.
The 'readonly' ('ro') flag is also set automatically if the file is read-only.
In only one circumstance should you reset this: when you are using a source
control system that normally leaves files in read-only mode. You want to edit the
file, so you start Vim.
The editor warns you that the file is read-only and sets the 'readonly'
option. At this point, you realize that you forgot to tell the source control system
that you want to edit the file. So you use :shell (:sh) to go to the command
prompt and execute the commands needed to tell the system that you want to
edit the file. The RCS system uses the co -l command to do this, for example; the
SCCS system uses sccs edit.
After getting permission to edit the file, you use the exit command to
return to
Vim, where you execute the following command to mark the file as
editable:
:set noreadonly
● Sleeping
● Terminal control
The command :goto offset (:go) also positions the cursor to a given byte
location within the file.
The gg command acts much like the G command. It goes to the line
specified by its count. For example, 5gg goes to line [Link] difference between gg
and G is that if no count is specified, gg goes to the first line and G goes to the
last.
Screen Redraw
The CTRL-L command redraws the screen. This proves useful when you
are on a terminal and some system message or other text screws up your screen.
With the advent of the dedicated GUI, the need for this command is greatly
diminished.
Sleep
The :sleep time (:sl) command does nothing for the specified number of
seconds. If time ends in m, it is specified in milliseconds. This command proves
useful when you want to pause during the execution of a macro.
Terminal Control
On most terminals, the CTRL-S command stops output. To restart it again,
you type CTRL-Q. These commands are not part of Vim; to avoid keyboard
conflicts, however, they are not used by any Vim commands.
You should not try to use these commands in a :map command because
your terminal might interpret them and they might never get to Vim.
Note: CTRL-Z in insert mode inserts the character CTRL-Z; it does not
suspend the editor.
General Help
The :help, :h, <F1> and <Help> commands all display the general help
screen.
The :helpgrep (:helpg) command does a :vimgrep on the help files and
lets you go through the results with :cc, :cn, :cp, and the other :vimgrep
related commands. The :lhelpgrep (:lh) command does the same thing only
using the local version of the :vimgrep command,
The :helptags (:helpt) command generates a help tags files for all the
files in a given directory. This is useful only if you are writing help files.
For Nvi compatibility some additional commands have been added. The
:exusage (:exu) command displays help on the command mode commands (aka
the Ex commands.) The :viuslage (:viu) command displays help on the normal
mode commands. Both these commands do not work as well as :help but were
included for compability.
Window Size
The z height <CR> command resizes the current window to height. If
there is only one window open, Vim will display only height lines. (The rest will
be blank.) This is useful for slow terminals.
Signs
A sign is small marker on the left side of the screen. The sign feature is
designed to help Vim work with visual debuggers or IDEs. It gives the IDE the
ability to show things like breakpoints and other annotations.
Before you can use a sign, it must be defined. In this example we are
defining a sign named Here that uses the text “=>” to point to a location.
linehl Highlight to use for the line on which the sign has
been placed.
Now that we've defined a sign, we can put it somewhere. In this case we
are going to put it on line 3 of the file [Link].
:sign place 1 line=3 name=Here file=[Link]
The 1 is the sign id number. The line is the line on which to place the
sign. The last parameters is the name of the file.
Line 1
..Line 2
=>Line 3
Line 4
Line 5
Figure 15-1: Sign placement
Open Mode
The Vim editor has all the capabilities of the Vi editor except one: open
mode. This mode is Vi's way of coping with terminals it does not understand. It
is difficult to get into this mode, difficult to use it, and the fact that Vim does not
have it is no great loss.
Vim does have a command to enter open mode, but when you issue the
command
:open
all you get is an error message.
● Character twiddling
● Moving text
● Sorting a section
Character Twiddling
If you type fast, your fingers can easily get ahead of your mind. Frequently
people transpose characters. For example, the word the comes out teh. To
swap two characters (for example, e with h), put the cursor on the e and type xp.
The x command deletes a character (the e), and the p pastes it after the cursor
(which is now placed over the h).
:1,$s/idiots/managers/g
The colon (:) indicates that you are going to execute an ex type command.
All ex commands begin with range of line numbers on which the command
operates. In this case, the whole document is chosen, from line 1 to the last line
($).The shorthand for 1,$ is simply % as shown previously.
4. Use the n command to repeat the last search (find the next idiot).
5. Execute the . (dot) command to repeat the last edit (change one word
to manager). If you do not want to change the word, skip this step.
Alternate Method
Moving Text
Suppose you want to move a bunch of paragraphs from the top of the
document to the bottom.
1. Move the cursor to the top of the paragraph you want to move.
5. Move the cursor to the line where the text is to go. The paragraph
will be placed after this one.
3. Move to the line above where you want to put the text, and type the
command:
:'a,'b move .
(:m is short for :move.)
7. Execute y'a to yank (copy in Microsoft parlance) the text from the
current cursor location to mark a ('a) into the default register.
9. Go to the line where the insert is to occur. The text will be placed
before this line.
10. Issue the P command to put (paste in Microsoft terminology) the text
in the default register above the current line.
9. Go to the line where the insert is to occur. The text will be placed
before this line.
10. Issue the P command to put (paste in Microsoft terminology) the text
in the default register above the current line.
In this method, you start up two Vim programs and copy text from one to
another. You do this by using the system Clipboard register ("*).
2. Start another Vim program to edit the second file. (If you are using
Linux or UNIX, the second editor can be started on another machine.
However, both programs must use the same X Windows display.)
7. Use the "*y command to yank (copy in Microsoft parlance) the text
into the system Clipboard register ("*).
8. Change to the other editing command. (Make that editor your active
window.)
9. Go to the line where the insert is to occur. The text will be placed
before this line.
10. Issue the command "*P to put (paste in Microsoft terminology) the
text in the system Clipboard register ("*) above the current line.
Note: This method enables you to not only move text between two Vim
applications, but also to "yank" and "put" between Vim and other
applications as well. For example, you can select text in an xterm window
using the mouse and paste it into a Vim editing using "*P. Or you can copy
text into the system register in a Vim session and paste it into a Microsoft
Word document using the Edit, Paste commands.
Or if you're editing a book about Vim using OpenOffice, you can yank the
text using “*P and paste it into a figure inside your book using the middle
mouse button.
Sorting a Section
Frequently you will be editing a file with a list of names in it (for example,
a list of object files that make up a program). For example:
version.o
pch.o
getopt.o
util.o
getopt1.o
inp.o
patch.o
backupfile.o
This list would be nice in alphabetic order (or at least ASCII order). To do
this using Vim commands execute the following:
Warning: In actual practice, what you see in most Makefiles (files used by
UNIX to control compilation) looks more like this:
OBJS = \
version.o \
pch.o \
getopt.o \
util.o \
getopt1.o \
inp.o \
patch.o \
backupfile.o
Notice that the backslash (\) is used to indicate a continuation line. After
sorting this looks like the following:
OBJS = \
backupfile.o
getopt.o \
getopt1.o \
inp.o \
patch.o \
pch.o \
util.o \
version.o \
The names are in order, but the backslashes are wrong. Do not forget to
fix them using normal editing before continuing:
OBJS = \
backupfile.o \ (added)
getopt.o \
getopt1.o \
inp.o \
patch.o \
pch.o \
util.o (removed)
In this method we avoid using Vim's internal :sort command and instead
use an external command. This system also avoids visual mode.
4. Execute the !'asort command. The ! command tells Vim to run the
text through a command. The 'a tells the editor that the text to be worked
on starts at the current line and ends at mark a. The command that the text
is to go through is sort.
First, however, you must generate a table of contents file called a tags file.
(This file has been given the obvious name tags.) The ctags command generates
this table of contents file.
After this file has been generated, you tell Vim that you want to edit a
procedure and it will find the file containing that procedure and position you
there. If you want to edit the procedure write_file, for example, use the
following command:
$ gvim -t write_file
Now suppose as you are looking at the write_file procedure that it calls
setup_data and you need to look at that procedure.
To jump to that function, position the cursor at the beginning of the word
setup_data and press CTRL-]. This tells Vim to jump to the definition of this
procedure. This repositioning occurs even if Vim has to change files to do so.
Note: If you have edited the current file and not saved it, Vim will issue a
warning and ignore the CTRL-]command.
/*******************************************************
* Program -- Solve it -- Solves the worlds problems. *
* All of them. At once. This will be a great *
* program when I finish it. *
*******************************************************/
Drawing these boxes like this is tedious at best. But Vim has a useful
feature called abbreviations that makes things easier . First, you need to create a
Vim initialization file called ~/.vimrc. The ~/.vimrc file must contain the
following lines:
:ab #b /***************************************
:ab #e <Space>****************************************/
These commands define a set of Vim abbreviations. Abbreviations were
discussed in Chapter 8: Basic Abbreviations, Keyboard Mapping, and
Initialization Files. To create a comment box, enter #b<Enter>. The screen looks
like this:
/************************************************
Enter the comments, including the beginning and ending * characters.
Finally, end the comment by typing #e<Enter>.This causes the ending comment
to be entered.
Another (better) option is to use an external program like boxes (see http://
[Link]), which generates all kinds of ASCII art boxes and can be
customized. Here, one might visually select the text and then issue the
command :'<,'> !boxes -r ,which would remove an existing box and put a new
box around the text.
Note: This page was written in Vim. So how did we enter the #b and #e?
Easy, we typed in #bb and then deleted a character. (We could not enter #b
or it would have been expanded.) The actual command was i#bb<Esc>x.
Another good tool for this sort of thing is tal, which lines up the final
character (the *, here) so it looks nice.
N^HNA^HAM^HME^HE
The first set of slashes encloses the "from text." The text is "any
whitespace" (\s), repeated zero or more times (*), followed by "end-of-line"
($).The result is that this pattern matches all trailing whitespace.
The matching text is to be replaced by the text in the next set of slashes.
This text is nothing, so the spaces and tabs are effectively removed.
So what can you do? You do not want to throw away all those changes, but
you need to get out of Vim so that you can turn on write permission. Use the
command :w! to force the writing of the file.
The line range for this command is the whole file, as indicated by the range
1,$.
In this case, the first regular expression is any bunch of characters that
does not include a comma. The [^,] means anything but a comma, and the *
means a bunch (zero or more characters). Note:This means that all leading
spaces will also be matched, which may not be what is desired.
The result of this substitution is that the first word on the line is assigned
to \1 and the second to \[Link] values are used in the end of the command to
reverse the words.
Match anything but comma Any Character Repeated 0 or more times The
end of the line
Figure 16-2 breaks out the various parts of the regular expressions used in
this illustration:
:l,$s/\([^,]*\), \(.*$\)/\2 \1/
For example, suppose you want to edit all the C program files that contain
the word frame_counter. To do this you use the command:
$ vim `grep -l 'frame_counter' *.c`
Let's look at this command in detail. The grep command searches through
a set of files for a given word. Because the -l option is specified, the command
will only list the files containing the word and not print the line itself. The word
it is searching for is frame_counter. Actually, this can be any regular
expression. (Note:What grep uses for regular expressions is not as complete or
complex as what Vim uses.)
The entire command is enclosed in backticks (`).This tells the UNIX shell
to run this command and pretend that the results were typed on the command
line.
So what happens is that the grep command is run and produces a list of
files, these files are put on the Vim command line. This results in Vim editing the
file list that is the output of grep.
You can then use the commands :n and :rewind to browse through the
files.
Why show this here? This is a feature of the UNIX shell (such as 'bash'),
and isn't part of Vim's repertoire. The way to accomplish something similar
within Vim, and which works on Win32 as well is:
:args `grep -l 'frame_counter' *.c`
which will set the argument list, in other words, the files "on the command
line."
The editor will now open the first file where a match is found and position
the file on the first matching line.
To go to the next matching line (no matter what file), use the :cnext
command. To go to the previous match, use the :cprev command.
This chapter briefly describes the commands omitted from the rest of the
book.
Cscope
MzScheme
The MzScheme interface enables you use PLT Scheme scripts from within
Vim. For information use the command:
:help mzscheme
Netbeans
Netbeans use the -nb command line parameter to start Vim and provide
Vim with information concerning the connection between the two programs.
One of the communications systems involves Vim sending hot keys back to
Netbeans through the :nbkey (:nbk) command.
Since all this communication is handled internally normal user will not
have to worry about the -nb command line parameter or the :nbkey command.
OLE
Perl
The Perl interface enables you to execute perl command from Vim and also
gives the Perl programs an interface that they can use to access some of Vim's
functions. For a complete description of what is available, execute the following
command:
:help perl
Python
Ruby
Ruby is yet another scripting language you can use with Vim. For a
complete description of what is available, execute the following command:
:help ruby
Sniff+
:help sniff
Tcl
Tcl is another scripting language. As usual, Vim provides you with a way to
execute Tcl scripts as well as an interface for accessing parts of Vim from within
Tcl. For full information, use the following command:
:help tcl
:tcl command
:{range}tcld command Execute a Tcl command once for each line in the
:{range}tcldo command range. The variable line is set to the contents of
the line.
:tclf file Execute the Tcl script in the given file.
:tclfile file
Foreign Languages
The Vim editor can handle many different types of foreign languages.
Unfortunately, the author cannot. Here is a very short listing of the commands
available to you for editing in other languages. For complete information, you
need to consult the Vim documentation and as well as the documentation that
came with your computer system. Although Vim contains many
language-specific options, a few are fairly generic.
<F8> Toggle between left-to-right and
right-to-left modes.
:set rl When set, indicates that the file is
:set rightleft displayed right to left rather than
:set norl left to right (default=norightleft).
:set norightleft
:set rlc=search Allow right to left input for the
:set rightleftcmd=search given mode. The only legal mode is
search which is also the default.
:set ari When set, let CTRL-_ toggle the
:set allowrevins revins option. This enables you to
:set noari input languages that run from right
:set noallowrevins to left rather than left to right.
:set ri When set, insert mode works right
:set revins to left rather than left to right. The
:set nori CTRL-_ command toggles this option
:set norevins if the option allowrevins is set.
:set gfs=f1,f2 Define a font f1 for English and
:set guifontset=f1,f2 another f2 for a foreign language.
This works only if Vim was compiled
with the 'fontset' enabled and
only applies on UNIX systems.
:set gfw=f1,f2 Specifies a list of fonts to use for
If this option is set, then delete (x) will delete each part of the combination
on it's own. If the option is off ('nodelcobine') then delete removes the entire
character.
Input Method
The following options control the current input method works with Vim.
keymap The name of the current keyboard mapping.
kmp
imactivekey Tells Vim what the input mode activation key is. The option
imak is of the form {modifier}-{key} where the modifier is zero
or more of:
S Shift key
L Lock key
C Control key
1 Mod1 key
2 Mod2 key
3 Mod3 key
4 Mod4 key
5 Mod5 key
imcmdline When this option is set, Vim will always use the input
imc method to enter or edit a command mode command.
imdisable If set, the input method is never used.
imd
iminsert Tell Vim when to turn the language dependent input
imi mapping (See :lmap page 425). The possible values are
Arabic
Chinese
Note: The Vim documentation does not contain help on the subject of
Chinese input. That is operating system dependent.
Farsi
The Farsi language is supported, although you must explicitly enable Farsi
when you compile the editor. It is not enabled by default. To edit in a Farsi file,
start Vim in Farsi mode by using the -F option.
For example:
$ vim -F [Link]
You can get complete information on Farsi editing by executing the
following command:
:help farsi
:set fk If set, this option tells Vim that you are using a
:set fkmap Farsi keyboard (default=nofkmap).
:set nofk
:set nofkmap
:set akm When 'altkeymap' is set, the alternate keyboard
:set altkeymap mapping is Farsi. If noaltkeymap is set, the default
:set noakm alternate keyboard mapping is Hebrew
:set noaltkeymap (default=noaltkeymap).
CTRL-_ Toggle between Farsi and normal mode
(insert-mode command).
<F9> Toggles the encoding between ISIR-3342 standard
and Vim extended ISIR-3342 (supported only in
right-to-left mode).
Hebrew
Japanese
Korean
To edit in Korean, you need to tell Vim about your keyboard and where
your fonts reside. You can obtain information on how to do this by executing the
following command:
:help hangul
Binary Files
Editing binary files using a text editor is tricky at best and suicidal at
worst. If you have the right combination of expertise and desperation, you can
use Vim to edit binary files.
:set bin If set, then set things up for editing a binary
:set binary file.
:set nobin
:set nobinary
Note: I realize that some people out there need to edit a binary file and
that you know what you are doing. For those of you in that situation, Vim is
an excellent editor. Fortunately for those who need to, Vim comes with a
great utility, xxd which allows one to edit binary files almost painlessly. See
the online docs for more information:
:help xxd
16 Part II
17 Reference
Generally you will not use all the commands in this chapter. Instead you
will pick out a nice subset you like and use them. Chapter 2 presented one
subset. If you prefer to pick your own, however, read this chapter and have fun.
Word Movement
The Vim editor has many different commands to enable you move to the
beginning or end of words. But you can also customize the definition of a word
through the use of some of the Vim options. The following sections explore in
depth the word movement commands.
The w command moves forward one word. You actually wind up on the
beginning of the next word. The e command moves forward one word, but leaves
you on the end of the word.
w w w e e
ge ge b b
1. The Vim editor does a good job of defining a sane answer to this
question. (Skip to the next section.)
2. If you want to know the details, read the rest of this section.
But LISP programmers can use the dash (-) in a variable name. They
consider the word total-size a single word. C programmers consider it two
words. So how do you resolve this conflict?
The Vim solution is to create an option that defines what is in a word and
what is not. The following command defines the characters that belong in a
word:
:set iskeyword=specification
To see what the current value of this option is, use this command:
:set iskeyword?
The following represents a typical value:
iskeyword=@,48-57,_,192-255
This is all the letters (@), the digits (ASCII characters numbered 48-57 or
0-9), the underscore (_) and the international letters (192-255, à through Y).
The 'iskeyword' option controls what is and is not a keyword. Other types
of characters are controlled by similar options, including the following:
The 'isident' option is used for commands such as [d, which searches for
the definition of a macro whose identifier is under the cursor. (See Chapter 7:
Commands for Programmers, for information on this command.)
So now you know what words are, right? Well, the Vim editor also has
commands that affect WORDS. These two terms, WORDS and words, represent
two different things. (Only a programmer could think up terms that differ only by
case.)
[count]<C-Right>
[count] W Move count WORDS forward.
Note: <C-Left> is the same as CTRL<LEFT>. See Appendix B: The <> Key
Names for a list of <> key names.
Beginning of a Line
The ^ command moves you to the first non-blank character on the line. If
you want to go to the beginning of the line, use the 0 command. Figure 18-2
shows these commands.
completed = true
0 ^
The ; command continues the search in the same direction as the last f or
F command. If you want to reverse the direction of the search, use the ,
command. Figure 18-3 shows several typical searches.
fe ; ;
, ,
Figure 18-3: Repeat single-character search.
ATTENTION
This room is fullfilled mit special electronische
3- equippment. Fingergrabbing and pressing the
- (minus)
cnoeppkes from the computers is allowed for die
experts only! So all the "lefhanders" stay away
and do not disturben the brainstorming von here
+
working intelligencies. Otherwise you will be out
thrown and kicked anderswhere! Also: please keep
still and only watchen astaunished the
blinkenlights.
2+
Cursor-Movement Commands
Several commands enable you to move to different parts of the screen.
The H command moves to the top of the screen. If a count is specified, the cursor
will be positioned to the count line from the top. Therefore, 1H moves to the top
line, 2H the second line, and so on.
The L command is just like H except that the end of the screen is used
rather than the start.
Jumping Around
The Vim editor keeps track of where you have been and enables you to go
back to previous locations. Suppose, for example, that you are editing a file and
execute the following commands:
1G Go to line 1
10G Go to line 10
20G Go to line 20
Line 20 is not recorded in the jump list yet, because you are on it. The
jump list records only things after you jump off of them. The > points to the
current item in the list; in this case, it points to the blank line at the end
indicating an unrecorded location.
Now that you know what the jump list is, you can use it. The CTRL-O
command jumps back one line. Executing this command takes you back to line
10. The jump list now looks like this:
jump line col file/text
2 1 0 Dumb User Stories
> 0 10 0 ventilation holes. Many terminals
0 20 0
The > has moved up one line. If you use the CTRL-O command again, you
move to line 1. The CTRL-I or <TAB> command moves you to the next jump in
the list. Thus you have the following:
1G Go to line 1.
10G Go to line 10.
20G Go to line 20.
CTRL-O Jump to previous location (line 10).
CTRL-O Jump to previous location (line 1).
<TAB> Jump to next location (line 10).
Using these commands, you can quickly navigate through a series of
jumping off points throughout your file.
Error: Reference source not foundThe jump list keeps track of where the
cursor has been. The change list does something similar but only records the
location of the cursor when a change is made. The does the same thing, only it's
limited to cursor locations where something changed.
To go to the previous change, use the command g;. This can be proceeded
with a count to go back multiple changes. To go to the next change, use the
command [count]g, (g<comma>).
Where Am I, in Detail
The CTRL-G command displays summary information at the bottom of the
screen telling you where you are in the file (see Chapter 2: Editing a Little
Faster). However, you can get more detailed information if you ask. The basic
CTRL-G output looks like this:
To get more information, give CTRL-G a count. The bigger the count, the
more detailed information you get. The 1CTRL-G command gives you the full
path of the file, for example:
"/usr/[Link]" [Modified] line 81 of 153 --52%-- col 1
The 2CTRL-G command lists a buffer number as well. (You can read more
on buffers in Chapter 5: Windows and Tabs)
buf 1: "/usr/[Link]" [Modified] line 81 of 153 --52%-- col 1
If you are interested in having the current cursor location displayed all the
time, check out the 'ruler' ('ru') option in Chapter 28: Customizing the Editor.
Scrolling Up
As discussed in Chapter 2: Editing a Little Faster, the CTRL-U command
scrolls up half a screen.
To scroll the window up one line at a time, use the CTRL-Y command. This
command can be multiplied by an argument. For example, 5CTRL-Y scrolls up 5
lines (see Figure 18-8).
line 20 line 19 5CTRL-Y line 14
line 21 line 20 line 15
line 22 CTRL-Y line 21 line 16
line 23 line 22 line 17
line 24 line 23 line 18
line 25 line 24 line 19
line 26 line 25 line 20
line 27 line 26 line 21
line 28 line 27 line 22
line 29 line 28 line 23
Figure 18-8: The CTRL-Y command.
You can specify this command as <PageUp> or <S-Up>. (<S-Up> is the Vim
notation for the Shift+up-arrow key.)
Scrolling Up Summary
Commands will scroll the screen making the indicated line the top line.
line 40
CTRL-Y line 41
2CTRL-Y line 42
line 43
line 44
CTRL-U line 45
line 46
CTRL-B line 47
line 48
line 49
Scrolling Down
There are similar commands for moving down as well, including the
following:
Both CTRL-B and CTRL-F scroll a full screen by default. You can adjust the
amount of scrolling by setting the 'window' ('wi') option to the number of lines
you want to scroll.
If you supply an argument to this command, it will use that line rather than
the current one. z<Enter> positions the current line at the top of the screen, for
instance, whereas 88z<Enter> positions line 88 at the top.
The z<Enter> command not only positions the line at the top of the screen,
it also moves the cursor to the first non-blank character on the line. If you want
to leave the cursor where it is on the line, use the command zt. (If you change
the current line by giving the command an argument, Vim will try to keep the
cursor in the same column.) Figure 18-13 shows the zt command.
Enjoys work, but she likes A very intelligent turtle
the beach more. Found programming UNIX a
She found a good way hurdle
To combine work and The system, you see,
play: Ran as slow as did he,
She sells C shells And that's not saying
by the seashore. much for the turtle.
zt
***** *****
If you want to position a line to the end of the screen, use the zb or z-
command. The z- positions the cursor on the first non-blank column, whereas zb
leaves it alone. Figure 18-14 shows the effects of these commands.
the beach more. Equals nine squared
Finally, the zz and z. commands position the line at the center of the
window. The zz command leaves the cursor in its current column, and z. moves
it to the first nonblank column. Figure 18-15 shows what these commands do.
Equals nine squared She found a good way
plus zero, no more. To combine work and play:
She sells C shells
***** by the seashore.
***** *****
3D D
Attention
The C Command
The C command deletes text from the cursor to the end of the line and then
puts the editor in insert mode. If a count is specified, it deletes an additional
count-1 lines. In other words, the command works like the D command, except
that it puts you in insert mode.
The s Command
The s (substitute) command deletes a single character and puts the editor
in insert mode. If preceded by a count, then count characters are deleted.
Figure 18-17 illustrates this command.
sone<esc>
4sunderstand<esc>
The S Command
The S command deletes the current line and puts the editor in insert mode.
If a count is specified, it deletes count lines. This differs from the C command in
that the C command deletes from the current location to the end of the line,
whereas the S command always works on the entire line. Figure 18-18 illustrates
the use of the S command.
Text affected by C
Over the years system installers have
developed many different ways to string
cables above false ceilings. One of the
2C
more innovative is the "small dog"
method. One person takes a small dog, S (Even if the
ties a string to its collar and puts the cursor is in the
dog in the ceiling. The owner then goes middle of the line)
to the spot where they want the cable to
come out and calls the dog. Dog runs to
owner. The attach a cable to the string, 2S
pull it through, and the cable is
installed.
Deleting Text
The [count] x command deletes characters starting with the one under
the cursor moving right. The X command deletes characters to the left of the
cursor. Figure 18-19 shows how these two commands work.
3x
3X
Arithmetic
The Vim editor can perform simple arithmetic on the text. The CTRL-A
command increments the number under the cursor. If an argument is specified,
that number is added to the number under the cursor. Figure 18-20 shows how
various types of numbers are incremented.
123 0177 0x1E 123
The CTRL-X command works just like the CTRL-A command, except the
number is decremented; or if an argument is present, the number is subtracted
from the number. Figure 18-21 shows how to decrement numbers.
124 0177 0x1E 123
Note: If the first line ends with some trailing spaces, the gJ command will
not remove them.
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>. Figure 18-23 contains a short example.
This is a test.
Rmess<Esc>
This is a mess.
Figure 18-23: The R command.
3Rmess<Esc>
This is a messmessmess.
Figure 18-24: R command with a count.
You may have noticed that this command replaced 12 characters on a line
with only 5 left on it. The R command automatically extends the line if it runs out
of characters to replace.
Virtual Editing
Normally Vim treats tab as a single character. This means when you move
the cursor across a line containing the cursor will “jump” from one position to
the other as it moves across the tab. Figure 18-25 shows how this works.
X<Tab> This is a test
l Cursor jumps
You can enable virtual mode by setting the 'virtualedit' ('ve') option to
all. Now when you move you left you move one character left on the screen. In
other words, the cursor does not jump. See Figure 18-26.)
X<Tab> This is a test
Virtual editing also lets you move the cursor past the end of line. This
makes thing because the $ command moves to the end of line, and in some cases
the $ command could move the cursor to the left!.
rx
xThis is a test
Figure 18-27: Simple non-virtual replace.
With virtual editing Vim is smart enough to figure out how to replace a
single character in screen space, preserving the spacing.
18
<Tab> This is a test
The block keyword tells Vim to allow virtual movement in block visual
mode. All other modes will act normally. If you wish to do virtual editing in
insert mode, you need the insert keyword. These options can be combined if
you want both modes:
:set virtualedit=block,insert
Finally there is the onemore keyword. If this is not set, you move the
cursor to the right as far as you want to. There is no limit. However, if the
onemore keyword is present, right movement is limited to character past the end
of line.
Replace Mode
If you use the virtual replace command, gr{character}, you replace the
"virtual character" under the cursor (see Figure 18-28) regardless of the state of
the 'virtualedit' option. If the real character under the cursor is part of a tab,
only the space representing the tab jumped over is replaced. The gR command
enters virtual replace mode. Each character you type will replace one character
in screen space until you finish things off with <Esc>.
Digraphs
As learned in Chapter 2: Editing a Little Faster, executing CTRL-K
character1 character2 inserts a digraph. You can define your own digraphs by
using the following command:
:digraphs character1 character2 number
(:dig for short.)
This tells Vim that when you type CTRL-K character1 character2 that
you should insert the character whose character number is number. If you are
entering a lot of digraphs, you can turn on the 'digraph' option by using this
command:
:set digraph
(The option can be abbreviated as 'dig')
This means that you can now enter digraphs by using the convention
character1<BS>character2. (<BS> is the backspace character.)
This mode has its drawbacks, however. The digraph C<BS>o is the
copyright character (©). If you type x but want to type y, you can correct your
mistake by typing x (oops), <BS>, and y. If you do that with C and o, however, it
does not erase the C and put in the o; instead, it inserts ©.
Therefore, you need to type C (oops), <BS>, o (darn, © appeared), <BS>, and
o.
Changing Case
The ~ command changes a character's case. The behavior of the ~
command depends on the value of the 'tildeop' ('top') option. With the option
unset, the command behaves normally:
:set notildeop
If you set the following option, however, the syntax of the command
changes to ~motion:
:set tildeop
For example the command ~fq changes the case of all the characters up to
and including the first q on the line. Figure 18-29 shows some examples.
now is the time. . . . now is the time. . . .
3~l ~fm
3g~l ~gfm
A special version of this command, g~~ or g~g~, changes the case of the
entire line (see Figure 18-31).
now is the time. . . .
g~~
The gumotion, guu, and gugu act just like their gU counterparts, except that
they make the text lowercase. Figure 18-320 illustrates these commands.
Advanced Undo
Vim has an advanced undo system that lets you forget about your mistakes
in a lot of different ways.
Let's say that you are working on a program starting at 9:00 in the
morning. You try something new and make lots of changes to your program
implementing the brand new methodology that your friend just told you about.
About 10:00 you figure out that what you just did was total garbage and
won't work. But you've made all those changes. How many times do you have to
press u (undo) to get back to the 9:00 state?
The answer is none. All you have to do is to tell the Vim you want the file
you had an hour ago. This is done with the :earlier (:ea) command.
:earlier 1h
Time for the :earlier command can be specified as a number of seconds (s),
minutes (m), or hours (h). If no unit is specified it is the number of change sets
(see below for the definition of this term.)
Of course if you realize that you went back to far, you can always go
forward with the :later (:lat) command.
Undo Level
You can execute only so many undo commands. This limit is set by the
'undolevels' ('ul') option. To set this limit to 5,000 changes, use the following
command:
:set undolevels=5000
1. Create the file, save it, and exit Vim and start a new editing session.
The change tree for this editing session appears in Figure 18-35.
Change A
Change set 4
Change B Change set 6
Change C Change E
Change D Change F
We can now list the change sets with the :undolist (:undol) command.
:undolist
number changes time
4 4 12 seconds ago
6 4 6 seconds ago
Press ENTER or type command to continue
This listing shows our two change sets. Right now we are at the bottom of
change set number 4. Pressing undo (u) four times causes each of the changes (F,
E, B, A) to be undone. Pressing redo (CTRL-R) four times redoes the changes.
Now let's switch to change set number 4 with the :undo (:u) command:
:undo 4
All of a sudden the file changes to the state it was in after we completed
the last step of change set 4 (Change D). Figure 18-36 shows the result:
A
B
C
D
Change E
Change F
Figure 18-36: Result of :undo 4
Now the undo (u) command goes up and down the changes in change set
number 4. (Changes D, C, B, A.)
Lets switch to the second change set (:undo 6). The screen should look
like Figure 18-37.
A
B
Change C
Change D
E
F
~
0 changes; before #6 17:16:44
Figure 18-37: Screen after :undo 6
Now lets undo a change using the g- command. The first g- undoes change
F. See Figure 18-38.
A
B
Change C
Change D
E
Change F
Figure 18-38: Screen after first g-
The next g- undoes change E, but moves over to a new part of the change
tree and redoes changes C and D. See Figure 18-39.
A
B
C
D
Change E
Change F
Figure 18-39: File after second g-.
Change A
Change B
Change C Change E
Change D Change F
The :undojoin (:undoj) command tells Vim to make all further changes
part of the same undo block. This undo block ends when the user executes the
next command. This command is useful for scripts and functions that want all
their commands to be part of the same undo block.
Getting Out
The ZQ command is an alias for the :q! or :quit! Command. The
command exits and discards all changes.
The :write command writes out the file. The :quit command exits. You
can use a shorthand for these commands:
:wq
This command can take a filename as an argument. In this case, the edit
buffer will be written to the file and then Vim will exit. To save your work under a
new filename and exit, for instance, use the following command:
:wq [Link]
This command will fail with an error message if the file [Link] exists
and is read-only. If you want Vim to overwrite the file, use the override option (!):
:wq! [Link]
Finally, you can give the :wq command a line-range argument. (See
Chapter 25: Complete Command-Mode (:) Commands for more on ranges.) If a
line range is present, only those lines are written to the file. To write out only
the first 10 lines of a file and exit, for example, execute the following command:
:1,10wq [Link]
The :xit (:x) command acts much like the :wq command except that it only
writes the file if the buffer has been modified.
● Search options
Searching Options
This section describes some of the more sophisticated options that you can
use to fine-tune your search. The 'hlsearch' ('hls') option has been turned on
to show you how these options affect the searching.
Case Sensitivity
# */
#ifdef HAVE_CONFIG_H
# include "auto/config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#INCLUDE <FCNTL.H>
#INCLUDE <SYS/TYPES.H>
#INCLUDE <NETDB.H>
#include <netinet/in.h>
#include <errno.h>
#include <sys/socket.h>
#ifdef HAVE_LIBGEN_H
# include <libgen.h>
#endif
/include
Figure 19-1: Case-sensitive search.
# */
#ifdef HAVE_CONFIG_H
# include "auto/config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#INCLUDE <FCNTL.H>
#INCLUDE <SYS/TYPES.H>
#INCLUDE <NETDB.H>
#include <netinet/in.h>
#include <errno.h>
#include <sys/socket.h>
#ifdef HAVE_LIBGEN_H
# include <libgen.h>
#endif
/include
Figure 19-2: Non-case-sensitive search.
If you have 'ignorecase' set, word matches word, WORD, and Word. It also
means that WORD will match the same thing. If you set the following two options,
any search string typed in lowercase is searched, ignoring the case of the search
string:
:set ignorecase
:set smartcase
('scs' is the abbreviation for 'smartcase'.)
If you have a string with at least one uppercase character, however, the
search becomes case sensitive. Thus you have the following matches:
String Matches
Word Word
WORD WORD
WorD WorD
Wrapping
By default, a forward search starts searching for the given string starting
at the current cursor location. It then proceeds to the end of the file. If it does
not find the string by that time, it starts from the beginning and searches from
the start of the file to the cursor location. Figure 19-3 shows how this works.
1
2 // Read at most 10MB
1) Start 3 const. unsigned int MAX_READ=(10*1024*1024)
4
2) /unisgned 5 // Size of a buffer
6 const unsigned int BUF_SIZE = (62 * 1024);
3) n 7
8 // Buffer to be written
9 static unsigned char buffer[BUF_SIZE];
4) n
10
Figure 19-3: Wrapping.
This example starts by searching for unsigned. The first search goes to
line 6. The next search moves to line 9. When trying to search again, you reach
the end of the file without finding the word. At this point, the search wraps back
to line 1 and the search continues. The result is that you are now on line 3.
Now when the search hits the end of the file, an error message displays
(see Figure 19-4).
1
2 // Read at most 10MB
3 const. unsigned int MAX_READ = (10 * 1024 *1024
4
5 // Size of a buffer
6 const unsigned int BUF_SIZE = (62 * 1024);
7
8 // Buffer to be written
9 static unsigned char buffer[BUF_SIZE];
10
Interrupting Searches
If you are in the middle of a long search and want to stop it, you can type
CTRL-C on a UNIX system or CTRL-BREAK on Microsoft Windows. On most
systems, unless you are editing a very large file, searches are almost
instantaneous.
19 #include <sys/fcntl.h>
20 #include <sys/time.h>
21 #include <errno.h>
22
23 // Read at most 10MB
24 const unsigned int MAX_READ =(10*1024*1024);
25 // Size of a buffer
* 26 const unsigned int BUF_SIZE = (62 *1024);
27
28 // Buffer to be written
29 static unsigned char buffer[BUF_SIZE];
Figure 19-5: * command.
These commands work on whole words only. In other words, if you are on
const and conduct a * search, you will not match constant.
The g* command performs an instant word search, but does not restrict
the results to whole words. So whereas * will not match constant, the g*
command will match it. The g# (g£) command does the same thing in the reverse
direction.
Search Offsets
By default, the search command leaves the cursor positioned on the
beginning of the pattern. You can tell Vim to leave it some other place by
specifying an offset. For the forward search command (/), the offset is specified
by appending a slash (/) and the offset, as follows:
/const/2
This command searches for the pattern const and then moves to the
beginning of the second line past the pattern. Figure 19-6 shows how this works.
19 #include <sys/fcntl.h>
/const/4 20 #include <sys/time.h>
21 #include <errno.h>
Find const 22
23 // Read at most 10MB
Go down 4 24 const unsigned int MAX_READ =(10*1024*1024);
lines 25 // Size of a buffer
26 const unsigned int BUF_SIZE = (62 *1024);
27
28 // Buffer to be written
29 static unsigned char buffer[BUF_SIZE];
Figure 19-6: Search offsets.
If the offset is a simple number, the cursor will be placed at the beginning
of the offset line from the match. The offset number can be positive or negative.
If it is positive, the cursor moves down that many lines; if negative, it moves up.
If the offset begins with b and a number, the cursor moves to the beginning
of the pattern, and then travels the "number" of characters. If the number is
positive, the cursor moves forward, if negative, backward. The command
/const/b2 moves the cursor to the beginning of the match, for instance, and
then two characters to the right (see Figure 19-7).
const unsigned int BUF_SIZE = (62 * 1024);
Note: The b offset is a synonym for s. Therefore, you can use b (begin),
and s (start) for the first character of the match.
The e offset indicates an offset from the end of the match. Without a
number it moves the cursor onto the last character of the match. The command
/const/e puts the cursor on the t of const. Again, a positive number moves the
cursor to the right, a negative number moves it to the left (see Figure 19-8).
const unsigned int BUF_SIZE = (62 * 1024);
Finally, there is the null offset. This is the empty string. This cancels the
preceding offset.
Specifying Offsets
The atom \< matches the beginning of a word. The atom \> matches the
end of a word. For example, a search for the expression for finds all
occurrences of for, even those in other words, such as Californian and
Unfortunately. Figure 19-9 shows the results of this search. If you use the
regular expression \<for\>, however, you match only the actual word for. Figure
19-10 contains the results of this refined search.
The expression te* also matches the string t. Why? Because e* can match
a zero length string of e's. And t is the letter t followed by zero e's.
This is a test.
te tee teee teee
Figure 19-12: Search for te\+.
Special Atoms
Now try a search for any four digits. Figure 19-14 displays the results.
19 #include <sys/fcntl.h>
20 #include <sys/time.h>
21 #include <errno.h>
22
23 // Read at most 10MB
24 const unsigned int MAX_READ=(10*1024*1024);
25 // Size of a buffer
26 const unsigned int BUF_SIZE = (62 * 1024);
27
28 // Buffer to be written
29 static unsigned char buffer[BUF_SIZE];
Figure 19-14: Search for \d\d\d\d.
Now try a search for any three letters followed by an underscore. Figure
19-15 displays the results.
19 #include <sys/fcntl.h>
20 #include <sys/time.h>
21 #include <errno.h>
22
23 // Read at most 10MB
24 const unsigned int MAX_READ=(10*1024*1024);
25 // Size of a buffer
26 const unsigned int BUF_SIZE = (62 * 1024);
27
28 // Buffer to be written
29 static unsigned char buffer[BUF_SIZE];
Figure 19-15: Search for \a\a\a_.
Character Ranges
The \a atom matches all the letters (uppercase and lowercase). But
suppose you want to match only the vowels. The range operator enables you to
match one of a series of characters. For example, the range [aeiou] matches a
single lowercase vowel. The string t[aeiou]n matches tan, ten, tin, ton and
tun.
You can specify a range of characters inside the brackets ([]) by using a
dash. For example, the pattern [0-9], matches the characters 0 through 9. (That
is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.)
You can combine ranges with other characters. For example, [0-9aeiou]
matches any digit or lowercase vowel.
However, in certain circumstances, Vim can figure out that you don't want
a special character to be special. For example, ^ at the beginning of an
expression matches the beginning of line. A ^ in the middle of the
expression matches ^. So 2\^4 and 2^4 match the same thing. But rather
try remember them all, all you need to remember is that if you escape
always you will rarely go wrong.
Character Classes
Suppose you want to specify all the uppercase letters. One way to do this
is to use the expression [A-Z]. Another way is to use one of the predefined
character classes. The class [:upper:] matches the uppercase characters.
Therefore, you can write [A-Z] as [[:upper:]].
You can write the entire alphabet, upper- and lowercase, [[:upper:]
[:lower:]]. There are a large number of different character classes.
Note: You cannot use the special atoms like \a and \d in a range. For
example, [\a\d] matches the characters \, a, \, and d. It does not match
the letters (\a) and digits (\d).
Repeat Modifiers
You can specify how many times an atom is to be repeated. The general
form of a repeat is as follows:
\{minimum, maximum}
For example, the regular expression a\{3,5} will match 3 to 5 a's. (that is,
aaa, aaaa, or aaaaa.) By default, the Vim editor tries to match as much as
possible. So a\{3,5} will match as many a's as it can (up to 5).
If only one number is specified, the atom must match exactly that number
of times. Therefore, a\{5} matches 5 a's, exactly.
If you put a minus sign (-) before any of the numbers, the Vim editor tries
to match as little as possible.
Grouping ( \(\) )
You can specify a group by enclosing it in a \( and \). For example, the
expression a*b matches b, ab, aab, aaab, and so on. The expression a\(XY\)*b
matches ab, aXYb, aXYXYb, aXYXYXYb, and so on.
When you define a group using \(\), the first enclosed string is assigned
to the atom \1. To match the string the the, for instance, use the regular
expression \(the\) \1. To find repeated words, you can get a bit more general
and use the expression \(\<\a\+\>\) \1. Figure 19-16 breaks this into its
components.
Put matching text in \1
\(\<\a\+\>\) \1
Match beginning of a word
Match a single letter
Repeat 1 or more times
Ending of a word
Match space
Match what was in the first \ (... \ )
The first group is assigned to \1, the second to \2, and so on.
The \| operator enables you to specify two or more possible matches. The
regular expression foo\|bar matches foo or bar. For example, the search
/procedure\|function
Start by specifying the digit as [0-9], now add the uppercase letter: [0-9]
[A-Z]. There are three of them, so you get [0-9][A-Z]\{3}. Finally, you add
the three digits on the end, resulting in [0-9][A-Z]\{3}[0-9]\{3}.
The experts tell us that this form is faster than using the [] form. If you
are editing a file where this speed up makes a difference, however, your file
might be too big.
All four of these expressions work. Which version should you use?
Whichever one you can remember. You should remember this old adage: The
simple way you can remember is much faster than the fancy way you can't.
The expressions discussed so far assume that the 'magic' option is on.
When this option is turned off, many of the symbols used in regular expressions
lose their magic powers. They only get them back when escaped. Specifically, if
you execute the command
:set nomagic
the *, ., [, and ] characters are not treated as special characters. If you
want to use the * for "0 or more repeats," you need to escape it: \*. You should
keep the 'magic' option on (the default) for portability and macro files.
Using \m in a regular expression tells Vim to treat all the following text as
if 'magic' were set. The special sequence \M tells Vim to treat the string as if
'nomagic' were set.
The string \v turns “very magic” mode which makes almost every
character magic. To turn this off use \V. The following table summarizes these
items.
'magic' 'nomagic'
\v \m \M \V
$ $ $ \$ matches end-of-line
. . \. \. matches any character
* * \* \* any number of the previous atom
() \(\) \(\) \(\) grouping into an atom
| \| \| \| separating alternatives
\a \a \a \a alphabetic character
\\ \\ \\ \\ literal backslash
\. \. . . literal dot
\{ { { { literal '{'
Simple Atoms
x The literal character x.
^ Start of line.
$ End of line.
. A single character.
\< Start of a word.
\> End of word.
Range Atoms
[abc] Match either a, b, or c.
[^abc] Match anything except a, b, or c.
[a-z] Match all characters from a through z.
[a-zA-Z] Match all characters from a through z and A through
Z.
Character Classes
[:alnum:] Match all letters and digits.
[:alpha:] Match letters.
[:ascii:] Match all ASCII characters.
[:backspace:] Match the backspace character (<BS>).
[:blank:] Match the space and tab characters.
[:cntrl:] Match all control characters.
[:digit:] Match digits.
[:escape : ] Matches the escape character (<Esc>).
[:graph:] Match the printable characters, excluding space.
[:lower:] Match lowercase letters.
[:print:] Match printable characters, including space.
[:punct:] Match the punctuation characters.
[:return:] Matches the end-of-line (carriage return, <Enter>,
<CR>, <NL>).
[:space:] Match all whitespace characters.
[:tab:] Match the tab character (<Tab>).
[:upper:] Match the uppercase letters.
[:xdigit:] Match hexadecimal digits.
\b <BS>.
\d Digit
\D Non-digit.
\e <Esc>.
\f Any filename character as defined by the 'isfname'
option.
\F Any filename character, but does not include the
digits.
\h Head of word character (A-Za-z_).
\H Non-head of word character (any character except
A-Za-z_).
\i Any identifier character as defined by the 'isident'
option.
\I Any identifier character, but does not include the
digits.
\k Any keyword character as defined by the 'iskeyword'
option.
\K Any keyword character, but does not include the
digits.
\l Lowercase character (a-z).
\L Non-lowercase character (any character except a-z).
\o Octal digit (0-7).
\O Non-octal digit.
\p Any printable character as defined by the 'isprint'
option.
\P Any printable character, but does not include the
digits.
\r <CR>.
\s Whitespace (<Space> and <Tab>).
\S Non-whitespace character. (Any character except
<Space> and <Tab>).
\t <Tab>.
\u Uppercase character (A-Z).
\U Non-uppercase character (any character except A-Z).
\w Word character (0-9A-Za-z_).
\W Non-word character (any character except
0-9A-Za-z_).
\x Hexadecimal digit (0-9 a-f A-F).
\X Non-hexadecimal digit.
\~ Matches the last given substitute string.
Modifiers
This chapter shows you all the other ways of doing things. If you find that
you do not like the limitations of the commands in Chapter 4, read this one; you
should find a way to get around your annoyances.
For example, you learned how to yank and put (cut and paste) using a
single register to hold the text. That is fine if you are dealing with a single block
of text. If you want to deal with more, however, check out how to use multiple
registers later in this chapter.
● Global marks
● Dealing with files that contain lines longer than the screen width
Line 1
Line 2 (yank line)
Line 3
LLine 4 (put line)
Line 5
gp gP
Line 1 Line 1
Line 2 (yank line) Line 2 (yank line)
Line 3 Line 3
Line 4 (put line) Line 2 (yank line)
Line 2 (yank line) Line 4 (put line)
L
Line 5 Line
L 5
Special Marks
Vim has a number of special built-in marks. The first one is the single
quotation (') mark. It marks the location of the cursor before the latest jump. In
other words, it is your previous location (excluding minor moves such as up/down
and so on). Other special marks include the following:
" The last place the cursor was resting when you left the file
Manipulating Marks
The :delmarks (:delm) command deletes all the marks. If you wish to
delete a specific set of marks, specify them as an argument to :delmarks.
The :lockmarks (:loc) command locks the location of the marks while a
command is being executed. For example:
:lockmarks :%! sort
The :lockmarks command assumes that the command does not change
the numbers of lines in the file.
The :keepmarks (:ke) does the same thing except that if the file gets
shorter any marks that are located past the end of the file are deleted. This only
works for filter (:!) commands.
Multiple Registers
So far, you have performed all your yanks and deletes without specifying
which register to use. If no register is specified, the unnamed register is used.
The characters that denote this register are two double quotation marks ("").
The first double quote denotes a register; the second double quote is the name of
the register. (Therefore, for example, "a means use register a.)
You can specify which register the deleted or yanked text is to go into by
using a register specification before the command. The format of a register
specification is "register, where register is one of the lowercase letters. (This
gives you 26 registers to play around with.)
Therefore, whereas yy puts the current line into the unnamed register, the
command "ayy places the line in the a register, as seen in Figure 20-2. (The text
also goes into the unnamed register at the same time.)
Line 1 unamed register "= "Line 3 (yy here)”
Line 2
Line 3 (yy here)
Line 4 ("ayy here) register a = "Line 4 ("ayy here)”
Figure 20-2: Using the a register for yank and put.
Unnamed Register
This illustration shows that the unnamed register (") contains Line 3 (yy
here).
The alphabetic registers are the normal ones used for yanking and pasting
text. Other, special registers are described in the following sections.
Appending Text
When you use a command such as "ayy, you replace the text in the register
with the current line. When you use the uppercase version of a register, say
"Ayy, you append the text to what is already in the register (see Figure 20-4).
Note that the result is two lines, "Line 3" and "Line 2". (The ^J in the register
indicates end of line.)
Line 1
Line 2 ("Ayy here)
Line 3 ("ayy here)
Line 4
~
~ 1) “ayy
~
Yank line into
~
register a 2) “Ayy
~
~ Append the line on to
~ register a
Special Registers
Vim has a number of special registers. The first is the unnamed register,
whose name is double quote (").
Others include the registers 1 through 9. Register 1 contains the last text
you deleted; register 2 the next to last, and so on.
(Back in the bad old days of Vi, these registers were a lifesaver. You see, Vi
had only one level of undo. So if you deleted three lines by executing dd three
times, you were out of luck if you wanted to undo the delete using the u
command. Fortunately, the three lines were stored in registers 1, 2, and 3, so
you could put them back with "1P"2P"3P. You can also use the command "1P..
("1P and two dots).
Placing text into the black hole register causes it to disappear. You can
also "put" the black hole register, but this is pretty much useless because the
black hole register always contains nothing. The black hole register is useful
when you want to delete text without having it go into the 1 through 9 registers.
For example, dd deletes a line and stores it in 1. The command "_dd deletes a
line and leaves 1 alone.
The expression register (=) is designed so that you can enter expressions
into text. When you enter a command beginning with an expression register
specification, the Vim editor displays the prompt = at the end of the screen. This
gives you an opportunity to type in an expression such as 38*56, and you can
then put the result into the text with the p command. For example
"=38*56<Enter>p gives you 2128. Figure 20-5 shows this register in action.
The width is 38. Enter the text, press <Esc> to
The height is 56. enter normal mode.
So the area is
~ Execute "= to start expression mode.
~ The cursor jumps to here.
~
=38*56
An expression can contain all the usual arithmetic operators (*, +, -, /, and
so on) as well as a ton of specialized Vim functions and operators. If you are
doing more than simple arithmetic, you will want to check the full expression
documentation.
You can specify the value of an environment variable, for example, by using
the expression $NAME (for instance, $HOME). You can determine the value of a Vim
variable by just specifying the variable (LineSize, for instance).
The clipboard register (*) enables you to read and write data to the system
clipboard. This can be the X selection (UNIX) or the Microsoft Windows
Clipboard. This enables you to cut and paste text between the Vim editor and
other applications.
Suppose, for example, that you want to edit all the C program files that
contain the word frame_counter. To do this, you use the following command:
$ vim `grep -l 'frame_counter' *.c`
Consider this command in detail. The grep command searches through a
set of files for a given word. Because the -l option is specified, the command
will list only the files containing the word and not print the line itself. The word
it is searching for is frame_counter. Actually, this can be any regular
expression. (Note that what grep uses for regular expressions is not as complete
or complex as what Vim uses.)
The entire command is enclosed in backticks (`). This tells the UNIX shell
to run this command and pretend that the results were typed on the command
line. So what happens is that the grep command is run and produces a list of
files; these files are put on the Vim command line. This results in Vim editing the
file list that is the output of grep.
You might be asking, "Why show this here?" This is a feature of the UNIX
shell (for example, bash), and is not part of Vim's repertoire. The way to
accomplish something similar within Vim, and which works on Win32 as well, is
as follows:
:args `grep l 'frame_counter' *.c`
(:ar is the short form of this command and you can use :next `cmd` and
:n `cmd` as well.)
This command sets the argument list (for example, the files "on the
command line," as it were).
This command enables you to specify a file by its position in the argument
list. Suppose, for instance, that you start Vim with this command:
$ gvim one.c two.c three.c four.c five.c six.c seven.c
The following command causes you to be thrown into the file four.c.
:argument 4
The {++opt} argument lets you specify some options to be used for each
file. These include:
Option Meaning
++bad={value} If {value} is a single character, replace all bad
characters with that character. The keyword drop
causes the bad characters to be dropped. A value of
keeps retains the bad characters.
++bin Turns on the 'binary' option.
++binary
++edit This only works for :read commands. It specifies that
the options for the file be the same as the file being
currently edited.
++enc={encoding} Specify the file encoding.
++encoding={encoding}
+ff={format} Specify the file format.
++fileformat={format}
++nobin Turn off the 'binary' option.
++nobinary
If you wish to just add files to the argument list (and keep the existing files,
use the :argadd (:arga) command. The general form of this command is:
:[count] argadd {file}
If a [count] is given the file is added after the [count] argument. If no
count is present, it is added to the end.
Suppose you want to edit the file you've just added. The :argedit (:arge)
command is a combination of :argadd and :edit.
To delete arguments from the argument list use the :argdelete (:argd)
command. It take an file name pattern as an argument, which means you can
use wildcards. For example, if you wish to remove all the C header files from an
argument list use the command:
:argdelete *.h
You can also delete arguments by position. Simply supply the :argdelete
command with a range. For example, to delete the second and third arguments,
use the command:
:2,3argdelete
So far we've been using one argument list. Vim actually supports two
different types of argument lists. The global argument list is the default for all
windows. However a window can switch over and use a local argument list if it
wants to.
The :drop (:dr) also sets the argument list. The form of this command is:
:drop {file} [file] [file] ...
Not only does it set the argument list, but it starts editing the first file. If a
the file is already being displayed in a window it will go to it. Otherwise it switch
the current window to the file. But if the file in the window hash changes in it
and can not be abandoned then it will split the window and to go the first file.
Global Marks
The marks a-z are local to the file. In other words, you can place a mark a
in file one.c and another mark a in file two.c. These marks are separate and
have nothing to do with each other. If you execute a go-to-mark command, such
as 'a, you will jump within that file to the given mark.
The uppercase marks (A-Z) differ. They are global. They mark not only the
location within the file, but also the file itself.
Take a look at an example. You are editing the file one.c and place the
mark A in it. You then go on to edit file two.c. When you execute the
jump-to-mark-A command ('A), the Vim editor will switch you from file two.c to
file one.c and position the cursor on the mark.
For example, you are editing a bunch of C files named alpha.c, beta.c, and
gamma.c. You execute the following commands:
Currently you are in file gamma.c. When you execute the command to go
to mark F ('F), you switch files to beta.c. Now you use the following command to
go to alpha.c.
:rewind
Place the F mark there using the mF command. Because this is a global
mark (you can put it in only one place), the mark named F in the file beta.c
disappears.
Movement
Even though you are in insert mode, you can still move the cursor. You
cannot do this with the traditional Vim keys h, j, k, and l, because these would
just be inserted. But you can use the arrow keys <Left>, <Right>, <Up>, and
<Down>. If you hold down the Control key, you can move forward and backward
words. In other words, execute <C-Left> to go backward one word, and
<C-Right> forward.
The <Home> command moves the cursor to the beginning of a line, and
<End> moves to the end. The key <C-Home> moves to the beginning of the file,
and <C-End> moves to the end.
Inserting Text
If you type CTRL-A, the editor inserts the text you typed the last time you
were in insert mode. Assume, for example, that you have a file that begins with
the following:
"file.h"
/* Main program begins */
You edit this file by inserting #include at the beginning of the first line:
#include "file.h"
The CTRL-V command is used to quote the next character. In other words,
any special meaning the character has, it will be ignored. For example,
CTRL-V<Esc> inserts an escape. You can also use the command CTRL-Vdigits to
insert the character number digits. For example, the character number 64 is @.
So CTRL-V64 inserts @. The CTRL-Vdigits uses "decimal" digits by default, but
you can also insert the hex digits.
For example,
CTRL-V123
and
CTRL-Vx7b
both insert the { character.
The CTRL-Y command inserts the character above the cursor. This is useful
when you are duplicating a previous line.
One of my favorite tricks is to use ASCII art to explain complex things such
as regular expressions. For example:
[0-9]*[a -z]*
||||||||||||+---- Repeat 0 or more times
|||||||+++++----- Any lower case letter
|||||+---------- Repeat 0 or more times ++++
+----------- Any digit
Take a look at how you can use CTRL-Y to create this file. You start by
entering the first two lines:
[0-9]*[a-z]*
|||||||||||+---- Repeat 0 or more times
Now you type CTRL-Y six times. This copies the | from the previous line
down six times:
[0-9]*[a-z]*
|||||||||||+---- Repeat 0 or more times
||||||
Now all you have to do is enter the rest of the comments.
The CTRL-E command acts like CTRL-Y except it inserts the character
below the cursor.
Inserting a Register
Now you dump this into register a with the command "ayy.
Next you enter insert mode and use CTRL-Ra to put the text into the file.
The result is as follows:
All men^H^H^Hpeople are created equal (original line)
All people are created equal (CTRL-Ra line)
Notice that Vim put the contents in as if you had typed them. In other
words, the <BS> character (^H) deletes the previous character.
Now if you want to put the contents of the register in the file without
interpretation, you could use CTRL-R CTRL-R a. This results in the following:
All men^H^H^Hpeople are created equal (original line)
All people are created equal (CTRL-Ra line)
The command CTRL-\ CTRL-N ends insert mode and goes to normal mode.
In other words, it acts like <Esc>. The only advantage this has over <Esc> is that
it works in all modes.
● Command-line history
● Search-string history
● Input-line history
● Registers
● Marks
● Buffer list
● Global variables
The trick is that you have to enable it. This is done through the following
command:
:set viminfo={string}
The {string} specifies what to save. (The 'viminfo' option can be
abbreviated as 'vi'.)
Let's take a look at how you can build up your own 'viminfo' string.
First, the ' (single quote) option is used to specify how many files for
which you save local marks (a-z). Pick a nice round number for this option
(1000, for instance). Your 'viminfo' option now looks like this:
:set viminfo='1000
The f option controls whether global marks (A-Z 0-9) are stored. If this
option is 0, none are stored. If it is 1 or you do not specify an f option, the
marks are stored. You want this feature, so now you have this:
:set viminfo='1000,f1
The r option tells Vim about removable media. Marks for files on
removable media are not stored. The idea here is that jump to mark is a difficult
command to execute if the file is on a floppy disk that you have left in your top
desk drawer at home. You can specify the r option multiple times; therefore, if
you are on a Microsoft Windows system, you can tell Vim that floppy disks A and
B are removable with the r option:
:set viminfo='1000,f1,rA:,rB:
UNIX has no standard naming convention for floppy disks. On my system,
however, the floppy disk is named /mnt/floppy; therefore, to exclude it, I use this
option:
:set viminfo='1000,f1,r/mnt/floppy
Note: There is a 50-character limit on the names of the removable media.
The " option (which must be escaped (\") to let Vim know it's not a
comment) controls how many lines are saved for each of the registers. By
default, all the lines are saved. If 0, nothing is saved. You like the default, so you
will not be adding a \" specification to the 'viminfo' line.
Generally, when Vim starts, if you have the 'hlsearch' ('hi') option set,
the editor highlights the previous search string (left over from the previous
editing sessions). To turn off this feature, put the h flag in your 'viminfo'
option list. (Or you can just start Vim, see the highlighting, and decide you do not
like it and execute a :nohlsearch (:noh).)
The '@' option controls the number of items to save in the input-line
history. (The input history records anything you type as result of an input
function call.) For this example, let this default to the size of the input-line
history.
If the '%' option is present, save and restore the buffer list. The buffer list
is restored only if you do not specify a file to edit on the command line:
:set viminfo='1000,f1,r/mnt/floppy,:100,/100,%
The ! option saves and restores global variables. (These are variables
whose names are all uppercase.)
:set viminfo='1000,f1,r/mnt/floppy,:100,/100,%,!
Finally, the n option specifies the name of the 'viminfo' file. By default,
this is $HOME/.viminfo on UNIX. On Microsoft Windows, the file is as follows:
C:\_viminfo
The 'n' option must be the last option parameter. Because we like the
default filename, we leave this option off. Therefore, the full 'viminfo' line is
this:
:set viminfo='1000,f1,r/mnt/floppy,:100,/100,%,!
You can put this command and other initializations into a .vimrc
initialization file. The .viminfo file is automatically written when the editor exits,
and read upon initialization. But you may want to write and read it explicitly.
The following command writes the .viminfo file:
:wviminfo[!] [file]
(:wv is the short version of this command.)
If a file is specified, the information is written to that file. Similarly, you can
read the .viminfo file using this command:
:rviminfo [file]
This reads all the settings from file. If any settings conflict with currently
existing settings, however, the file settings will not be used. If you want the
information in the .viminfo file to override the current settings, use the following
command:
:rviminfo! [file]
If you set the 'nowrap' option, each line in the file shows up as one line on
the screen. Then the ends of the long lines disappear off the screen to the right
(see Figure 20-7).
A programmer once worked on a form letter genera
for a bank. They wanted to send out a special, p
letter to their richest 1000 customers. Unfortun
programmer, he didn't adequately debug his code.
Even worse,
the bank didn't check the first batch of form le
Figure 20-7: :set nowrap.
By default, Vim does not display a horizontal scrollbar on the GUI. If you
want to enable one, as shown in Figure 20-8, use the following command:
:set guioptions+=b
('guioptions' can be abbreviated as 'go'.)
This window can be scrolled horizontally. All you have to do is position the
cursor on a long line and move to the right using the l or $ command. Figure
20-9 shows what happens when you do a little horizontal scrolling.
The ^ command moves to the first non-blank character of the line. The g^
command moves to the first non-blank character on the screen. If there is text
to the left of the window, it is ignored.
g^ g$ $
^ gm
The [count]zh command scrolls the screen count characters left while the
zl command does the same thing to the right.
The zL command scrolls half a screen to the left and the zR command
scrolls half screen to the right.
In this case, line 3 has wrapped. Now you start with the cursor on line 2.
Executing a j command moves you to the beginning of line 3. Another j and you
are down to the beginning of line 4. Note that although you have moved down a
line in text space, you have moved down two lines in screen space.
Wrapping
By default, the Vim editor wraps long lines. It does this by putting as
much of the line as possible on the first screen line, and then to breaking it, and
putting the rest on the next line. You can to turn this off by setting the following
option:
:set nowrap
With this option set, long lines just disappear off the right side of the
screen. When you move the cursor along them, the screen scrolls horizontally
and you can see what you are doing. You can customize wrapping by setting
some Vim options. First of all, you can tell Vim to break lines at nice places by
setting the option:
:set linebreak or
:set lbr
Figure 20-13 shows how this option affects the screen.
A programmer once worked on a form A programmer once worked on a
letter generation program form letter generation program
for a bank. They wanted to send ou for a bank. They wanted to send
t a special, personalized out a special, personalized
letter to their richest 1000 custo letter to their richest 1000
mers. Unfortunately for the customers. Unfortunately for the
programmer, he didn't adequately d programmer, he didn't adequately
ebug his code. Even worse, debug his code. Even worse,
the bank didn't check the first ba the bank didn't check the first
tch of form letters. batch of form letters.
But what defines a "nice" place on the line. The answer is the characters
in the 'breakat' ('brk') option. By default, these are ^ I ! @ * - +
_ ; : , . / ?. Now suppose you do not want to break words with _ in them.
You need to remove _ from the list of 'breakat' characters, so you execute the
following command:
:set breakat -=_
Usually when lines are broken, nothing is put at the beginning of the
continuation lines. You can change this, however, by defining the 'showbreak'
('sbr') option. For example:
:set showbreak="---->"
Finally, there is the question of what to do if you need to break a line at the
end of the screen. You have two choices: First, you can refuse to display half of a
line. The Vim editor will display an @ at the bottom of the screen to indicate
"there is a long line here that we cannot fit it on the screen. Second, you can
display half the line. The Vim default is method one. If you want to use method
two, execute this command:
:set display=lastline
('dy' is short for 'display'.)
Spelling Dictionaries
Vim lets you create word lists in a variety of formats. The simplest is a
straight word list. To turn a word list into a dictionary it needs to be compiled.
This is done using the :mkspell (:mksp) command.
The :mkspell command takes an option (-ascii) which tells it to skip all
non-ASCII characters.
Vim accepts word lists in a variety of formats. One of the more common
dictionary layouts is the MySpell format. One source for dictionary files is
[Link]
Vim supports both simple word lists, and a very complex word lists. The
latter specify things language and region, as well as indicating word parts
(prefixes, suffixes), rare words, and misspelled words. Since this feature is of
interest only to the handful users who will actually make word lists, a full
description has been omitted.
The :mkspell command can take multiple input files and produce a single
word list. The naming of the input files must follow the convention
{name}_{encoding}. The following command creates a English language
dictionary for three regions.
:mkspell en en_US en_CA en_AU
Finally if no output name is specified, the :mkspell command will produce
one based on the input name.
Dumping dictionaries
If you need to see a list of the words in the current dictionary use the
:spelldump (:spelld) command. This opens a new window with the list of
words in it.
If you use the override (!) option on this command, the words along with a
word count is dumped.
expr:{expression}
Finally, this chapter discusses session files. These files enable you to save
and restore all your editing and window settings so that you can return to editing
where you left off.
● Split searches
● Shorthand operators
● Session files
/* File one.c */
CTRL-Ww ~
1CTRL-WW ~
CTRL-Wt ~
one.c
2CTRL-Ww /* File two.c */
2CTRL-WW ~
~
~
3CTRL-Ww two.c
3CTRL-WW /* File three.c */
CTRL-Wb #include <stdio.h>
int i;
three.c
Figure 21-1: Window selection commands.
[count]CTRL-Ww Go down a window. If at the bottom, wrap. If
[count]CTRL-W CTRL-W count is specified, go to the window number
count.
countCTRL-WW Go up a window. If at the top, wrap. If count is
specified, go to the window number count.
/* File one.c */
~
~
~
one.c
CTRL-Ww /* File two.c */
CTRL-WW
~
~ CTRL-WW
~
two.c
/* File three.c */
#include <stdio.h>
int i;
CTRL-Ww CTRL-WW
three.c
Figure 21-2: More window selection commands.
The CTRL-WR command rotates the windows upward (see Figure 21-4).
/* File one.c */ /* File two.c */
~ ~
~ ~
one.c two.c
/* File two.c */ /* File three.c */
~ CTRL-WR #include <stdio.h>
~ int i;
two.c three.c
/* File three.c */ /* This file four.c *
#include <stdio.h> /
int i; ~
three.c four.c
/* This file four.c * /* File one.c */
/ ~
~ ~
four.c one.c
Figure 21-4: Rotating a window up.
The quit command :quit (:q, CTRL-Wq, CTRL-W CTRL-Q) closes the
current window. (If this is the last window for a file, the file is closed.) If you
have multiple windows up, you can quit them all using this command:
:qall
(:qa is the short form of :qall.)
If some of the files have been modified, and the changes have not been
saved, the :qall command fails. If you want to abandon the changes you have
made, use the force option (!), which gives you this command:
:qall!
(Use this with caution because you can easily discard work you wanted to
keep.) If you want to perform a combination of :wall and :qall, use this
command:
:wqall
(The aliases for :wqall are :wqa, :xa, :xall.)
If you have specified multiple files on the command line or through the
file-list command, the :all (:al, :sall, :sal) command opens up a window for
each file (see Figure 21-7).
A variation of the :all command opens a new window for each hidden
buffer:
:unhide
(Alternate formats :unh, :sunhide, :su.)
This command can take an argument that limits the number of windows
that can be opened at one time. To unhide all the buffers but put no more than
five windows on screen, for example, use the following command:
:unhide 5
/* File two.c */
~
~
CTRL-W "two.c" 1L, 17C
CTRL-_ /* File three.c */
#include <stdio.h>
int i;
"three.c" 11L, 160C
Figure 21-8: CTRL-W CTRL-^.
Split Search
The CTRL-W CTRL-I command splits the window, and then searches for the
first occurrence of the word under the cursor. This search goes through not only
the current file, but also any #include files.
If you position the cursor on the printf on “Hello World” and press
CTRL-W CTRL-I, you get a screen that looks like Figure 21-9.
extern int fprintf(...);
Shorthand Commands
The Vim editor contains some shorthand commands that do the work of
multiple commands, including the following:
:{count}snext :split followed by :countnext
:{count}sn
:{count}sprevious :split followed by :countprevious
:{count}spr
:{count}sNext :split followed by :countNext
:{count}sN
:srewind :split followed by :rewind
:sre
:sfirst
:sf
:slast :split followed by :last
:sl
:sargument :split followed by :argument
:sa
CTRL-W CTRL-D :split followed by ]CTRL-D
CTRL-Wd
CTRL-W CTRL-F :split followed by a :find
CTRL-Wf
CTRL-Wg] :split followed a CTRL-]
One nice thing about these commands is that they do not open a new
window if they fail.
The :windo (:wind) command will execute a command for each open
window. For example, to change “vim” to “Vim” in all the windows use the
command:
:windo :%s/vim/Vim/g
Advanced Buffers
The following sections discuss adding, deleting, and unloading buffers.
Adding a Buffer
The Vim editor maintains a list of buffers. Usually you put a file on the list
by editing it. But you can explicitly add it with the following command:
:badd file
(This is a bad command. Let me rephrase that. The abbreviated version of
this command is :bad.)
The named file is merely added to the list of buffers. The editing process
will not start until you switch to the buffer. This command accepts an argument:
:badd +lnum file
When you open a window for the buffer, the cursor will be positioned on
line lnum.
Deleting a Buffer
The
:bdelete
command deletes a buffer. (:bd is the short form.)
Unloading a Buffer
The :bwipeout (:bw) command unloads the file and causes Vim to forget
everything it knew about it. This command takes the same syntax as :bdelete
and should not be used unless you know what you are doing.
The :ball (:ba, :sball, :sba) command opens a window for each buffer.
Windowing Options
The 'laststatus' ('ls') option controls whether the last window has a
status line. (See Figure 21-10.) The three values of this option are as follows:
0 The last window never has a status line.
1 If there is only one window on the screen, do not display the status line. If
there are two or more, however, display a status line for the last window.
(default).
2 Always display a status line even if there is only one window on screen.
The 'winheight' ('wh') option sets the minimum number of lines for a
window. This is not a hard limit; if things get too crowded, Vim will make smaller
windows. The 'winwidth' ('wiw') option does the same thing, only for width.
When the 'equalalways' ('ea') option is enabled (the default), Vim will
always split the screen into equal-size windows. When off, splits can result in
windows of different sizes. Figure 21-11 shows the effect of this option.
gvim one.c
:split
:split
/* File one.c */ /* File one.c */
~ ~
~ ~
~ ~
~ one.c
one.c /* File one.c */
/* File one.c */ ~
~ ~o
~ one.c
~ /* File one.c */
~ ~
one.c ~
/* File one.c */ ~
~ ~
~ ~
~ ~
~ ~
one.c one.c
:split :split
If you split horizontally, and the 'equalalways' option is set, any window
with the 'winfixheight' ('wfh') option set will not change size. For vertical
splits the 'winfexwidth' ('wfw') option keeps the size constant.
Controling a split
A :vsplit command opens a window to the left of the current one. The
'splightright' ('spr') option causes new to open to the right.
The :topleft (:to) command will open a window at the top of the screen
for horizontal splitting commands. The window will go across the entire screen.
For vertical splitting commands, the window will occupy the entire left of the
screen.
The :botright (:bo) command acts in a similar manner except the winow
will occupy the entire bottom or right of the screen.
Tabs
In this section we'll take a look at how to execute one command for
multiple tabs as well as how to customize the tab system.
The :tabdo (:tabd) command executes a given command for every tab.
For example, to change the word "idiot" to "politician" for every tab, use the
command:
:tabdo :s/idiot/politician/
The :tabs command lists the tabs and the files being edited in them.
For example:
:tabs
Tab page 1
> + [Link]
Tab page 2
[Link]
[Link]
Press ENTER or type command to continue
The :tabmove (:tabm) command moves the current tab to just after the
given tab.
For example Figure 21-12 shows what happens when we have the tab
[Link] open and execute the command:
:tabmove 1
Customzing tabs
Tabs are still available if you are using console (non-GUI) mode. They don't
look as nice and you can't click to move from tab to tab, but you do have tabs.
(However, you may wish to consider using windows instead.)
The 'showtabline' ('stal') tells Vim when to show the tab line. This
option has the following values
Sessions
Suppose you are editing along, and it is the end of the day. You want to
quit work and pick up where you left off the next day. You can do this by saving
your editing session and restoring it the next day.
A Vim session contains all the information about what you are editing. This
includes things such as the file list, windows, and other information. (Exactly
what is controlled by the 'sessionoptions' ('ssop') option is described later in
the section "Specifying What Is Saved in a Session.")
For example:
:mksession [Link]
Later if you want to restore this session, you can use this command:
:source [Link]
If you want to start Vim and restore a specific session, you can use the
following command:
$ vim -c ":source [Link]"
(This tells Vim to execute a specific command on startup (-c). The
command is :source [Link], which loads the session [Link].)
Views
Let's say you've got a lot of windows and tabs open. You've gone to a lot of
trouble to make things look just right. Each window is just in the right place,
and the options have been finely tuned to make things just perfect.
Things are great as long as you stay within Vim. But once Vim exists, all
these settings are lost.
That's where the :mkview (:mkvie) command comes in. It creates a script
that restores all your windows and settings to their current values. (It's not
perfect, but it does a pretty good job.)
The script is called [Link]. You can load it with the command:
:source [Link]
You can also :mkview without a file name. In this case the file is stored in
the directory specified by the 'viewdir' ('vdir') option. If a number is used as
an argument, then a numbered view is stored in this directory.
In any case, these views can be loaded by using the :loadview (:lo)
command.
● Reselecting text
● Select mode
To yank the text into a register, use the y command. The D and the Y
commands act like their lowercase counterparts, except they work on entire
lines, whereas d and y work on just the highlighted section.
The $ Command
In block visual mode, the $ command causes the selection to be extended
to the end of all the lines in the selection. Moving the cursor up or down
extends the select text to the end of the line. This extension occurs even if the
new lines are longer than the current ones. Figure 22-1 shows what happens
when you don't use the $ command, and Figure 22-2 shows what happens when
this command is used.
Cursor movement
A very intelligent turtle 1) l to move right
Found programming UNIX a hurdle 2) j to move down
The system, you see,
Start
Ran as slow as did he,
And that's not saying much for the turtle.
***
-- VISUAL BLOCK --
Figure 22-1: Block visual mode without $ command.
***
-- VISUAL BLOCK --
Figure 22-2: Block visual mode with the $ command.
gv goes to
reselect previous visual
gv goes to
new visual if done twicel
Selecting Objects
A number of commands in visual mode are designed to help you highlight
the text you want.
That is because when you perform a selection, the text selected is from the
old cursor location to the new one inclusive. Now if you use the w command to
move, the result is that the cursor is placed on the first character of the next
word. Therefore if you delete the text, you not only get the words you selected,
but the first character of the next word.
The aw command leaves the cursor positioned just before the first
character of the next word. In other words, it selects the word and the spaces
beyond it, but not the next word.
Another reason to use aw rather than w is that aw selects the whole word,
no matter which part of the word the cursor is on, whereas w just selects from
the current location to the end of the word.
If you want to just select the word, and nothing but the word, use the iw
(inner word) command. Figure 22-4 shows how iw and aw work.
This is a test
w
This is a test
aw
This is a test
iw
a( i(
The O command moves the cursor to the other corner of the selection in
block visual mode (see Figure 22-7). In other words, the O command moves to
the other end of the selection on the same line.
The last sign in pseudo-German has made its
way around the world. It even made its way to
Germany where they translated it into
pseudo-English.
ATTENTION
Case Changes
The ~ command inverts the case of the selection. The U command makes
the text uppercase and the u command turns the text into lowercase. Figure
22-8 illustrates how the various case-changing commands work. The figures
show initial selection, ~, U, and u, respectively.
Line 1 Line 1 Line 1 Line 1
Line 2 lINE 2 LINE 2 line 2
Line 3 lIne 3 LINE 3 line 3
Line 4 Line 4 Line 4 Line 4
Line 5. Line 5. Line 5. Line 5.
~ ~ ~ ~
~ ~ ~ ~
~ ~ ~ ~
~ ~ ~ ~
[Link] [Link] [Link] [Link]
--VISUAL-- --VISUAL--
~ U u
Initial
Selection
Joining Lines
The J command joins all the highlighted lines into one long line. Spaces
are used to separate the lines. If you want to join the lines without adding
spaces, use the gJ command. Figure 22-9 shows how the J and gJ commands
work.
Line 1 J Line 1
Line 2 Line 2 Line 3
Line 3 Line 4
Line 4 ~
~ ~
~ ~
~ ~
~ ~
~ ~
[Link] [Link] [+]
-- VISUAL --
gJ
Line 1
[Link] (28. Sep. 2007) The Vim Book Page 357
The Vim Tutorial and Reference
Formatting a Block
The gq command formats the text (see Figure 22-10).
Select lines Oh woe to Mertle the turtle
who found web surfing quite a hurtle.
The system you see
was slower than he.
And that's not saying much for the turtle.
~
[Link]
-- VISUAL --
With rot13, if you encode something twice, you decode it. Therefore if the
text is encoded, g? decodes it. If it is in plain text, g? encodes it. Figure 22-11
shows how this encryption works.
Note: The ! command always works on lines even if you are in character
visual mode or visual block mode.
Select Mode
Select mode is yet another visual mode that allows for quick deletion or
replacement of the selected text. The way you use select mode is simple. You
highlight the text and then type <BS> to delete it. Or you can highlight the text,
and then replace it by just typing the replacement.
How does select mode compare with visual mode? With visual mode, you
highlight the text and then perform an operation. In other words, you need to
end the visual mode operation with a command. With select mode, the
commands are limited to <BS> (for delete) and printable characters (for
replacement). This makes things faster because you do not need to enter a
command, but it is much more limited than visual mode.
You can choose from three select-mode flavors. The commands to start the
various flavors of the select mode are as follows:
gh Start characterwise selection.
gH Start linewise selection.
gCTRL-H Start block selection.
Moving the cursor in select mode is a little more difficult than moving it in
normal visual mode because if you type any printable character, you delete the
selected text and start inserting. Therefore, to select text, you must use the
arrow, CTRL, and function keys.
You can also use the mouse to select text if you set the 'selectmode'
('slm') option to mouse, as follows:
:set selectmode=mouse
(Without this option, the mouse performs a visual selection rather than a
select-mode selection.)
You can also use the 'selectmode' option to let the shifted cursor keys
enter select mode.
The backspace command (<BS> or CTRL-H) deletes the selected text (see
Figure 22-13).
Replacing Text
Typing any printable character causes the selected text to be deleted and
throws Vim into insert mode (see Figure 22-14).
Switching Modes
The CTRL-O command switches from selection mode to visual mode for one
command. The CTRL-G command switches to visual mode without returning. To
switch from visual mode to select mode, use the CTRL-G command.
Because of that, Vim includes a lot of commands you can use to customize
and enhance it to make editing programs easier.
Consider, for example, the problem of the <Tab> character. You can deal
with this character in many different ways. You can set the tab stops to the
indentation size, leave them at the default eight characters, or eliminate them
altogether (force everyone to use spaces). The Vim editor supports all these
types of editing. This chapter shows you how to use each of them.
Previously, you saw how to turn on C indent mode. This chapter describes,
in detail, how to customize this mode.
You have learned how to turn syntax highlighting on as well. This chapter
takes you a step further, showing you how to customize it. This chapter discusses
the following:
● Removing autoindents
● Tabbing options
● Customizing C indentation
● Matching options
Or you can use 0CTRL-D. The 0CTRL-D command in insert mode removes all
the automatic indentation and puts the cursor in column 1. (Note that when you
type the 0, it appears on the screen--at this point, Vim thinks you are trying to
insert a 0 into the text. When you type in the CTRL-D, it realizes you are
executing a 0CTRL-D command and the 0 disappears.)
When you use 0CTRL-D, the cursor returns to column 1 (see Figure 23-1).
The next line also starts in column 1 (normal 'autoindent' behavior).
0CTRL-D if (flag) {
un-indents go to skip_it;
this line {
do something();
This line is not /* This is the start of comment block */
automatically /* This is the second line of the block */
indented Figure 23-1: The 0CTRL-D command.
Suppose, however, that you are typing in a label or an #ifdef directive and
want to go to column 1 for one line only. In this case, you want the ^CTRL-D
command. This places you in column 1 for the current line only. When you enter
the next line, the indent is automatically restored (see Figure 23-2).
^CTRL-D if (flag) {
un-indents go to skip_it;
this line }
#ifdef FLAG
Automatically if (flag2) {
indented
Inserting Indent
The CTRL-T command is like a <Tab>, except that it inserts an indent the
size of the 'shiftwidth' option. If you use a 'shiftwidth' ('sw') of 4, for
instance, pressing <Tab> moves you to the next 8-column boundary (a 'tabstop'
('ts'), assuming that you have the default setting of 'tabstop=8'). But pressing
CTRL-T moves us you to the next 4-column boundary.
The CTRL-T and CTRL-D commands work at any point on the line (not just
the beginning). Therefore, you can type some text and then use CTRL-T and
CTRL-D to adjust the indentation.
Inserting Registers
Generally when you use CTRL-R to insert the contents of a register, the
contents are autoindented. If you do not want this to happen, use the command
CTRL-R CTRL-O register. On the other hand, if you want to insert a register and
have Vim "do the right thing," use the CTRL-R CTRL-P register command.
Take a look at how this works. Assume that you are editing a file that
contains the following:
1 int main()
2 {
3 if (x)
4 {
5 y();
6 }
The following settings have been made:
:set number
:set cindent
:set shiftwidth=4
You start on line 3 and do a V to enter line visual mode. Going down to line
6, you highlight the entire if block. You dump this in register a with the
command "ay. Next you add two lines at the end to start another if. Your text
now looks like this:
1 int main()
2 {
3 if (x)
4 {
5 y();
6 }
7 if (z)
8 {
Register a contains the following:
if (x)
{
y();
}
Next you go into insert mode and insert the contents of register a using the
command CTRL-R a. The result is ugly:
if (x)
{
y();
}
So what happened? Register a contains indented lines. But Vim has
indenting turned on. Because you inserted the register indent and all, you
wound up with double indentation. That was not what you wanted. Go back to
where you were (CTRL-Ou, undo) and execute a CTRL-R CTRL-O a. The result is
as follows:
1 int main()
2 {
3 if (x)
4 {
5 y();
6 }
7 if (z)
8 {
9 if (x)
10 {
11 y();
12 }
This is better. You do not have the double indents. Trouble is, you still do
not have the right indent. The problem is that Vim kept the old indent from the
original text. Because this line is under the if (z) statement, however, it should
be indented an extra level. So you go back and try CTRL-R CTRL-P a.
2. Tell the machine that tab stops are only 4 spaces and use tabs
everywhere. (This is one solution I personally frown upon, because I do not
use the special setting and the text appears to be over-indented.)
3. Throw up your hands and say that tabs are the work of the devil and
always use spaces.
If you are using a combination of tabs and spaces, you just edit normally.
The Vim defaults do a fine job of handling things. But you can make life a little
easier by setting the 'softtabstop' ('sts') option. This option tells Vim to
make the Tab key look and feel as if tabs were set at the value of 'softtabstop',
but use a combination of tabs and spaces to fake things (see Figure 23-3). After
you execute the following command, every time you press the Tab key the cursor
moves to the next 4-column boundary:
:set softtabstop=4
The first time you press it, however, you get 4 spaces inserted in your text.
The second time, Vim takes out the 4 spaces and puts in a tab (thus taking you to
column 8).
Smart Tabs
Another related option is the 'smarttab' ('sta') option. With this option
on (:set smarttab), tabs inserted at the beginning of a line are treated like soft
tabs. The tab size used in this case is defined by the 'shiftwidth' option.
But tabs inserted elsewhere in the text act just like normal tabs. Note that
you must have soft tabs off (:set softtabstop=0) for this option to work. Figure
23-4 shows sample results.
Smart indenting is a combination of soft tabs and normal tabs. When you
execute the following command, Vim treats tabs at the beginning of a line
differently:
:set smarttab
Suppose, for example, that you have the following settings:
:set shiftwidth=4
:set tabstop=8
:set smarttab
Tab stops are every eight spaces and the indentation size is four spaces.
When you type <Tab> at the beginning of a line, the cursor will move over the
indentation size (four spaces). Doing a double <Tab> moves over two indention
sizes (eight spaces [4*2]).
The following table shows you what happens if you type certain things at
the beginning of the line.
What's types What's Inserted
<Tab> Four spaces
<Tab><Tab> One tab
<Tab><Tab><Tab> One tab, four spaces
<Tab><Tab><Tab><Tab> Two tabs
When you type <Tab> anywhere else in the line, however, it acts like a
normal tab.
You can actually change it to be any value you want. Figure 23-5 shows
what happens when 'tabstop' is set to 4.
Note: Just because you change it in Vim does not mean that it will change
in your terminal window, that your printing program will not still use
eight-character tab stops, or that other editors will use the new setting.
Therefore, your type and print commands might require special options to
handle things.
No Tabs
If you want absolutely no tabs in your file, you can set the 'expandtab'
('et') option. When this option is set, the <Tab> key inserts a series of spaces.
(Note that setting 'expandtab' does not affect any existing tabs. In other words,
any tabs in the document remain tabs. If you want to convert tabs to spaces, use
the :retab (:ret) command, which is explained later.)
Note: If you really want to insert a tab when this option is on, type
CTRL-V<Tab>. The CTRL-V command tells Vim that you really want to insert
this <Tab> as a tab and not a bunch of spaces.
If the 'preserveindent' ('pi') is set then then Vim will attempt keep
whatever indent structure you already have. (As much as possible.) For
example, if you 16 wide indent consists of 8 spaces and one <tab>, Vim will keep
what you've got. Without this option it will use two tabs.
If the 'copyindent' ('ci') option is set, when a new line is opened, Vim
will attempt to copy the indentation from the previous line.
The :retab command transforms text with tab stops at one setting to tab
stops with another. You can use it to turn tabs into a series of spaces as well, or
a series of spaces into tabs.
For example, suppose that you have a file that was created with tab stops
of 4 (:set tabstop=4). This is a non-standard setting, and you want to change
things so that the tab stops are 8 spaces. (You want the text to look the same,
just with different tab stops.) To change the tap stop in the file from 4 to 8, first
execute the command
:set tabstop=4
The text should appear on the screen correctly. Now execute the command
:%retab 8
This changes the tab stops to 8. The text will appear unmodified, because
Vim has changed the white space to match the new value of 'tabstop'.
For another example, suppose that you are required to produce files with
no tabs in them. First, you set the 'expandtab' option. This causes the <Tab>
key to insert spaces on any new text you type. But the old text still has tabs in it.
To replace these tabs with spaces, execute the command
:%retab
Because you didn't specify a new tabstop, the current value of 'tabstop' is
used. But because the option 'expandtab' is set, all tabs will be replaced with
spaces.
Modelines
One of the problems with all these tabbing options is that people use them.
Therefore, if you work with files created by three different people, you can easily
have to work with many different tab settings. One solution to this problem is to
put a comment at the beginning or end of the file telling the reader what tab
stops to use.
For example:
/* vim:tabstop=8:expandtab:shiftwidth=8 */
When you see this line, you can establish the appropriate Vim settings, if
you want to. But Vim is a smart editor. It knows about comments like this and
will configure the settings for you. A few restrictions apply. The comment must
be formatted in this manner and it must appear in the first or last five lines of the
program (unless you change the setting of 'modelines' ).
Shift Details
Suppose that you are typing with a shift width of 4 and you enter a line
with 3 spaces in front of it. What should the >> command do? Should it add 4
spaces in front of the line or move it to the nearest shift width. The answer
depends on the value of the 'shiftround' ('sr') option.
Usually this option is not set, so >> puts in 4 spaces. If you execute the
following command, >> moves the indent to the next shift-width boundary:
:set shiftround
Figure 23-6 shows how this works.
123456789012345678
With "noshiftround">>moves size = 20
the text over 4 spaces
size = 20
8 spaces
3 spaces
Column 8
Figure 23-6: The 'shiftround' option.
Formatting Comments
One of the great things about Vim is that it understands comments. You
can ask Vim to format a comment and it will do the right thing.
4. Format the visual block with the command gq. The result is:
/*
* This is a test. Of the text formatting.
*/
Note that Vim properly handled the beginning of each line.
(For deciding what is and is not a comment, Vim uses the 'comments'
('com') option, described in the following section.)
Defining a Comment
The 'comments' option defines what is a comment. This option is a series
of flag:string pairs.
A C comment starts with /*, has a middle of *, and ends with */, as
follows:
/*
* This is a comment
*/
This results in the 'comments' option specification of
set comments=s1:/*,mb:*,ex:*/
The s1 indicates that this is the start of a three-part comment (s) and the
other lines in the command need to be indented an extra space (1). The
comment starts with the string /*.
The middle of the comment is defined by the mb:* part. The m indicates a
middle piece, and the b says that a blank must follow anything that is inserted.
The text that begins the comment is *.
The ending is specified by ex:*/. The e indicates the end, and the x
indicates that you have only to type the last character of the ending to finish the
comment. The end delimiter is */.
Take a look at how this definition works. First, you need to set the
following option :
:set formatoptions=qro
375('fo' is the short version of 'formatoptions'.)
The following options prove useful for formatting text (see Chapter 11:
Dealing with Text Files for complete details):
q Allow formatting of comments using gq.
r Automatically insert the middle of a comment after pressing
<Enter>.
o Automatically insert the middle of a comment when a line inside a
comment is opened with an O or o command.
Now start typing in comments. You start with a line containing the
comment header, /*, as follows:
/*
When you type <Enter>, because r is in the format options, you get the
following:
/*
*
The Vim editor automatically inserted the * surrounded by a space on each
side to make the comment look good. Now enter a comment and a new line:
/*
* This is an example
*
Now you need to end the comment. But Vim has already typed a space
after the asterisk. How can you enter */? The answer is that Vim is smart and
will end the comment properly if you just type /. The cursor moves back, the
slash is inserted, and you get the following:
/*
* This is an example
*/
You can use a number of different formatting commands to format text or
comments. For more information on these, see Chapter 11: Dealing with Text
Files and Chapter 20: Advanced Text Blocks and Multiple Files.
<name> The named key. See Appendix B: The <> Key Names
for a list of names.
^X Control character (that is, CTRL-X).
o Tells Vim to indent the line when you use an o
command to open a new line.
O Line o, but for the O command.
e Re-indent the line when you type the final e in else.
: Re-indent the line when you type a colon after a label
or case statement.
<^>, <<>, <>>, The literal character inside the angle brackets.
<o>, <e>, <O>
The default value for this the 'cinkeys' option is as follows:
:set cinkeys=0{,0},:,0#,!^F,o,O,e
Figure 23-7 shows how the 'cinkeys' option works.
0{ - { is the first
character typed on the e - Second "e" of
line if (x) "else"
{
0} - } is the first do_it();
character typed on the }
line else : - Colon anywhere
{ on the line
0# - # is the first goto_here:
character entered do_other();
on the line }
#define DONE 1
Figure 23-7: The 'cinkeys' option.
The 'cinoptions' option controls how much Vim indents each line. This
option consists of a series of key indent pairs. The key is a single letter that
controls what part of the program is affected (see the following table and Error:
Reference source not found and Error: Reference source not found). The indent
tells the program how much indentation to use. This can be a number of spaces
(for example, 8), or a negative number of spaces (-8). It can also be a multiple of
the 'shiftwidth' option that is specified as s. For example, 1s is a shift width,
0.5s is half a shift width, and -1s un-indents a shift width.
The following examples show what happens with various indent options.
These examples assume a 'shiftwidth' of 4. (Note dot represents space.)
cindentopt=”” cindentopt=”>2” cindentopt=”>s2”
if (flag) if (flag) if (flag)
{ { {
....do_it(); ..do_it(); ........do_it();
} } }
cindentopt=”” cindentopt=”l1”
switch (x) { switch (x) {
....case a: ....case a:
........foo(); ........foo();
........break; ........break;
case b: { ....case b: {
foo(); ........foo();
break; ........break;
} ....}
} }
cindentopt=”” cindentopt=”b1”
switch (x) { switch (x) {
....case a: ....case a:
........foo(); ........foo();
........break; ....break;
} }
a = (b + a = (b + a = (b +
........c) ..c) ........c)
c = ((c + d c = ((c + d c = ((c + d
.....) * ( .....) * ( .....) * (
.........e + f) ...e + f) .........e + f)
....) ..) ....)
cindentopt=”” cindentopt=”m1”
a = (b + a = (b +
....) * (d + ) * (d +
........) * e + ) * e +
....( f + ( g * ( f + ( g *
............h) + i) ........h) + i)
cindentopt=”” cindentopt=”M1”
if ( a || ( if ( a || (
............b && c ............b && c
..........) || ............) ||
........d ........d
...) ........)
cindentopt=””
addListener(new EventListener() {
........public void eventHandler(Event e) {
........process(e);
........}
........});
cindentopt=”j1”
addListener(new EventListener() {
....public void eventHandler(Event e) {
........process(e);
....}
});
The 'cinwords' option defines what words cause the next C statement to
be indented one level in the Smartindent and cindent mode. The default value of
this option is as follows:
:set cinwords=if,else,while,do,for,switch
The first is :diffsplit {filename} (:diffs). This splits the window and
does a diff between the current file and new file you just specified. By default
this splits the window horizontally so you may want to execute the following
command to split things vertically:
:vertical diffsplit {file-name}
The other way is to execute the command :diffthis (:difft). This makes
the current file part of the set of files who's differences are being displayed.
Naturally you have to execute this command for more than one file for the diffs
to appear.
Vim knows how to run the standard GNU patch program, but if you have a
different one you can set the 'patchexpr' ('pex') to be anything you want.
When that :diffpatch command is run, Vim will evaluate this option to perform
the patch.
Vim attempts to be very good about making sure that the difference display
is keep up to date even when you change a file. However, it's not perfect. If
things get a little confused, you can always tell Vim to redo the difference
highlighting with the :diffupdate (:dif) command.
Finally to take a window out of the difference set, use the :diffoff
command. The command :diffoff! performs this operation for all windows in
the current tab page.
First of all they take a range argument. All differences within that range
will be moved. For example, to take all the differences in the first 100 lines from
the current file and put them in the other file use the command:
5 The patch program is a standard Linux and UNIX tool. A version for Microsoft Windows is
found in the Cygwin package.
:1,100 diffput
The other advantage of :diffget and :diffput is that they take an
argument which specifies which buffer is to be considered the “other” file. This
can be a buffer number, or enough of a file name so that Vim can identify the
buffer.
For example, suppose we are doing a multi-way diff between the file
main.c, main.c.v1, main.c.v2, main.c.v3. We are currently ediing main.c and
want to grab the diff from main.c.v2. For that we use the command:
:diffget v2
Customizing Diff
The 'diff' option tells Vim whether or not this file is part of the diff set. If
this option is set, the the file is part of the set, if not set (nodiff) then it is not.
The 'diffopt' ('dip') option let's customize difference mode. The values
for this option include:
Option Meaning
filler Display filler lines when lines are added or deleted to keep
things aligned.
context:{number} Display {number} lines of context around a difference.
icase Ignore case differences
iwhite Ignore whitespace differences
horizontal By default split the windows horizontally in diff mode.
vertical By default split the windows vertically in diff mode.
foldcolumn:{column} Set the number of columns to use for the folding indicator.
Now when one window scrolls, so does the other. Figure 23-8
demonstrates how this command works. (Go down to line 14 in the first window;
the second window scrolls.) As you scroll through both windows, you might
encounter a place where you must move one window without moving the other.
To do so, all you have to do is execute the following command in the window you
want to move:
:set noscrollbind
After moving the text, then synchronize scrolling, by executing:
:set scrollbind
jump When switching between windows, make sure the offsets are
0.
Finally, the following command synchronizes the two windows:
:syncbind
(:sync for short.)
Suppose, for example, that you have been looking at two versions of a file,
moving both around. To look at some things, you turned off 'scrollbind'. Now
the files point at two different places. You want to go back to synchronized
scrolling.
You could synchronize the windows by going to each and moving it to the
right location; you let Vim do the work. In this case, you set 'scrollbind' in
both windows and then execute the following:
:syncbind
Vim then synchronizes the two files.
Advanced Folding
There are actually a number of different ways that you can cause folding to
happen in your text. We've already discussed the manual mode where you
manually decide to open and close folds. In Chapter 7: Commands for
Programmers we also discussed the indent method where the indent level
controls what's folded.
You can also put special markers in your text that tell Vim where to start
and stop a fold. To make this work you need to set 'foldmethod' ('fdm') to
marker.
The 'foldmarker' ('fmr') option consists of two strings, the first starts a
fold, the second ends it. By default the value of this option is {{{,}}}. Let's
take a look at a typical text
{{{
This will be folded
}}}
This is normal
{{{
Another fold (to be hidden
}}}
Vim will display this text as
When in marker mode, the visual command zf command not only creates
the fold, it adds the marker to the end of line. In Figure 23-9 we first highlight
three lines in visual mode then fold them with zf. (Power users can use
zf{motion} to do the same thing.)
A normal line
Fold me
Fold me
Fold me
Normal again
zf
A normal line
+-- 3 lines: Fold me---------------------------
A normal line
zo to open the fold
A normal line
Fold me{{{
Fold me
Fold me}}}
Normal again
Figure 23-9: Creating a fold with zf
The commentstring' ('cms') option can be used to tell Vim to put the
markers inside a comment. This option is a string with a %s in side which tells
Vim where the comment should go. For example:
:set commentstring=\ Comment:%s
We can see the results of a zf with the 'commenstring' set in Figure
23-10.
A normal line
Fold me Comment:{{{
Fold me
Fold me Comment:}}}
Normal again
Figure 23-10: zf with 'commentstring' set.
The :fold (:fo) command will fold a range of lines. For example to fold
the first 10 lines of a file use the command:
:1,10 fold
The zd command deletes a fold, but will not delete nested folds. The zD
command deletes all folds recursively for the fold under the cursor.
If you want to see all the text that in the window, the zE command will open
all the folds visible on the screen when you execute this command.
The zo command opens a single fold. The zO command opens all the folds
under the cursor.
A fold can also be opened with the :foldopen (:foldo) command. All folds
within the line range specified are opened one level. If the override (!) option is
used, all levels are opened.
The zc command closes one level of fold around where the cursor is
located. The zC command closes them all.
A fold can also be closed with the :foldclose (:foldc) command. All
folds within the line range specified are closed one level. If the override (!)
option is used, all levels are closed.
Toggling folds
So zo opens a fold and zc closes. The za command will open a fold if it's
closed and close it if it's open. This works on one level of folding. To toggle all
the levels at once, use the zA command.
You can use the normal movement commands to go up and down the
screen. If you want to jump from fold to fold, use the [z command to move to
the start of the current fold (obviously the fold must be open). The ]z command
moves to the end of the fold. The zj command moves down to the start of the
next fold and zk moves up to the end of the previous one.
Customizing folds
The 'foldtext' ('fdt') option controls how the text for a fold is displayed.
The following variables are set during the execution of this function:
The 'foldcolumn' ('fdc') option tells Vim what column to display the fold
information in. It's value must be between 0 and 12.
Fold Methods
There are many different ways folds can be created. This is controlled by
the 'foldmethod' ('fdm') options.
When the 'foldmethod' is set to syntax, then any syntax elements which
have the fold option on them are folded. For example in the C language to fold
all the stuff between #if 0 and #endif, Vim uses the following syntax rule:
:syn region cCppOut
\ start="^\s*\(%:\|#\)\s*if\s\+0\+\>"
\ end=".\@=\|$" contains=cCppOut2 fold
When 'foldmethod' is set to expr then the expression in the 'foldexpr'
('fde') is evaluated to get the fold level. Creating such a function is a
challenging bit of Vim programming and is beyond the scope of this book.
(If you already have a preview window up, it is switched to the definition of
the function.) Figure 23-11 shows a typical example. Assume that you have just
executed the following command:
:ptag copy_p_data
After you have finished with the preview window, execute the following
command:
:pclose
(:pc, CTRL-W CTRL-Z, CTRL-Wz accomplish the same thing.)
assert((*the_data->n_data_ptr) <1000);
return (result);
}
/* Create data from a db data record */
void copy_p_data(
struct p_data *the_data,
const datum db_data
){
the_data->n_data_ptr = (int*)&the_data->raw_data[0];
set_datum(the_data, db_data);
}
/mnt/sabina/sdo/tools/local/proto/p_data.c [Preview]
copy_p_data(&cur_entry, cur_value);
pq.c
Figure 23-11: :ptag example.
Match Options
The 'matchpairs' ('mps') option controls what characters are matched by
the % command. The default value of this option is as follows:
:set matchpairs = (:),{:},[:]
This tells Vim to match pairs of (), [], and {}. To match <> (useful if you
are editing HTML documents), for example, use the following command:
:set matchpairs=<:>
This matches just <> pairs. If you want to match <> in addition to the other
characters, you need this command:
:set matchpairs=(:),{:},[:],<:>
This is a little long and awkward to type. The += flavor of the :set
command adds characters to an option. Therefore, to add <> to the match list,
use the following command:
:set matchpairs+=<:>
Showing Matches
If you execute the following command, when you enter any type of bracket
( (, ), [, ], {, }), Vim will cause the cursor to jump to the matching bracket
briefly when entering:
:set showmatch
('showmatch' can be abbreviated as 'sm')
Generally this jump lasts only for a half second, but you can change it with
the 'matchtime' ('mat') option. If you want to make it 1.5 seconds, for
instance, use the following command:
:set matchtime=15
The value of this option is 1/10 second.
The ]) command finds the next unmatched ). The [( finds the previous
unmatched (. The command [# finds the previous unmatched #if or #else (see
Figure 23-13). The command ]# finds the next unmatched conditional.
#ifdef FOO
# define SIZE 1
#else /* FOO */
# ifdef BAR
# define SIZE 20
# else /* BAR */
# define SIZE 30
[# # define WIDTH 10
#endif
Figure 23-13: The [# command.
Method Location
The following commands move to the beginning or end of a Java method:
[m Search backward for the start of a method.
[M Search backward for the end of a method.
]m Search forward for the start of a method.
]M Search forward for the end of a method.
Movement
Several movement commands are designed to help programmers navigate
through their text. The first set finds the characters { and } in column 1. (This
usually indicates the start of a procedure, structure, or class definition.) The
four curly brace-related movement commands are as follows:
count [[ Move backward to the preceding { in column 1.
count [] Move backward to the preceding } in column 1.
count ]] Move forward to the next { in column 1.
count ][ Move forward to the next } in column 1.
Figure 23-14 shows how these commands work.
int sub1 (void)
[] {
return (1);
[[ }
int sub2 (void)
Cursor starts here {
return (2);
][ }
int sub3 (void)
]] {
return (3);
}
Figure 23-14: Curly brace movement commands.
Comment Moves
The commands [/ and [* move you backward to the start of the first C
comment it can find. The commands ]/ and ]* move you forward to the end of
the next C comment it can find. Figure 23-15 illustrates some simple comment
motions.
[/ /*
* Comment.
*/
Cursor starts here int a;
int b;
/*
]/ * Comment.
*/
Figure 23-15: Comment motions.
prog
main.c lib.c
main.h lib.h
You start editing in the directory main. The first thing you need to do is
tell Vim about your new directory. You use the :set ^= (:se ^=) command to
put the directory at the top of the search path with the following command:
:set path ^= ../lib
('path' can be abbreviated 'pa'.)
Suppose you are editing the file main.c. The file looks like this:
#include "main.h"
#include "lib.h"
Suppose, however, that you want to edit the file lib.c. This name does not
appear in the text, so you cannot use the gf command. Instead, you execute the
following command:
:find lib.c
(:fi is the diminutive form of :find.6)
This acts just like the :vi command, except the editor searches for the file
along the path. The following command does the same thing, but it splits the
window and then does a :find :
:sfind lib.c
(:sf is the abbreviation for :sfind.)
6 I'm sorry but with all these abbreviations, I'm running out of ways to describe them.
The gf command acts like a :find command but use the word under the
cursor as the name of the file to edit. If there is more than one file along the
'path' that matches the given file name, then you can select which one Vim
edits by giving the gf command a count.
In other words if you position the cursor on the name param.h and execute
the command 2gf, Vim will edit the second param.h file it finds looking through
the directories specified by the 'path' option.
The Java language is a little funny. The syntax of the import directive is
designed to decouple the name of the imported class from the file system. So the
directive:
import [Link];
actually refers to the file com/steve/[Link]. To handle this Vim uses
two options. The first 'includeexpr' ('inex') defines an expression that Vim
uses to translate names in the text to file names. The second 'suffixesadd'
('sua') defines the suffixes to add to a name in the text to convert it to a file
name for the gf command.
2The 'path' ('pa') option is used by Vim to tell it where to look for files that
were included in the current file. The format of this option is as follows:
:set path=directory,directory,...
The parameter directory is a directory to search. For example:
:set path=/usr/include,/usr/X11R6/include
You can use wildcards (*) in any directory of the path specification:
:set path=/usr/include,/usr/include/*
There are a number of special directories:
. (dot)
For example, the following command tells Vim to search /usr/include and
all it is subdirectories, the directory in which the file resides (.), and the current
directory (,,).
:set path=/usr/include/**,.,,
To make sure that you can find all the #include files, you can execute the
following command:
:checkpath
(:che for short.)
This command works not only on the #include directives in the file you are
editing, but also on any files that they #include and so on. The result is that all
#include files are checked.
In this case, a number of files include the files stddef.h and stdarg.h. But
Vim cannot find these files. If you want to tell Vim to search the Linux-specific
include directory, you can execute the following command:
:set path+=/usr/include/linux
get_rel_name(&cur_entry, i),
get_full_name(&cur_entry, i));
}
if (gdbm_errno != 0) {
-- Included files not found in path --
/usr/include/stdio.h -
<stddef.h>
<stdarg.h>
/usr/include/bits/types.h --
<stddef.h>
/usr/include/libio.h --
/usr/include/_G_config.h --
<stddef.h>
<stdarg.h>
/usr/include/bits/stdio-lock.h --
/usr/include/pthread.h --
/usr/include/sched.h --
/usr/include/time.h --
<stddef.h>
/usr/include/stdlib.h --
<stddef.h>
/usr/include/sys/types.h --
<stddef.h>
/usr/include/alloca.h --
<stddef.h>
/usr/include/string.h --
<stddef.h>
Press RETURN or enter command to continue
Figure 23-17: The :checkpath command.
Now do another:
:checkpath
Figure 23-18 shows the results.
for (i = 0; i < *cur_entry.n_data_ptr; i++) {
printf("\t%d %s (%s)\n",
(int)get_flags(&cur_entry, i),
get_rel_name(&cur_entry, i),
get_full_name(&cur_entry, i));
}
if (gdbm_errno != 0) {
All included files were found
Figure 23-18: :checkpath with all files found.
This command lists only the files that cannot be found. If you want to list
all #include files, use this command:
:checkpath!
Figure 23-19shows the results.
Included files in path
<stdio.h>
/usr/include/stdio.h >
<features.h>
/usr/include/features.h >
<sys/cdefs.h>
/usr/include/sys/cdefs.h >
<features.h> (Already listed)
<gnu/stubs.h>
<stddef.h>
<stdarg.h>
<bits/types.h>
/usr/include/bits/types.h >
<features.h> (Already listed)
<stddef.h> (Already listed)
<bits/pthreadtypes.h>
/usr/include/bits/pthreadtypes.h >
<bits/sched.h>
<libio.h>
/usr/include/libio.h >
More
Figure 23-19: The :checkpath! command.
Defining a Definition
The Vim editor knows about C and C++ macro definitions. But what about
other languages? The option 'define' ('def') contains the regular expression
that Vim uses when it looks for a definition. To have Vim look for macros that
start with the string function, for instance, use the following command:
:set define=function
The 'include' ('inc') option defines what an include directive looks like.
This option is used for the ]CTRL-I, [CTRL-I, ]d, and [d searches that look
through #include'd files.
In Java you specify packages. The package names happen to look a lot like
file names except that the slashes (/) have been changed to dots (.). In order to
make transformation from Java package to actual file path, Vim uses the value of
the 'includeexpr' ('inex') to change the name in the program to a name that
the file system understands.
This option is used for the :checkpath command as well. Like the
'define' option, the value of this option is a regular expression.
The [i command searches for the first occurrence of the word under the
cursor. Text inside comments is ignored.
The ]i command searches for the next occurrence of the word under the
cursor. Again, text inside comments is ignored.
The [I command lists all the lines which contain the keyword under the
cursor. (Comments ignored.) The ]I command does the same thing starting at
the current cursor location.
There are a whole lot of other commands that change the contents of the
quick fix list. These are:
Command Add or Jump or Description
Replace No Jump
:cfile {file} Replace Jump Replace error list with file.
:cf {file}
:cgetfile {file} Replace No Jump Replace error list with file.
:cg {file}
:caddfile {file} Adds No Jump Add file to error list.
:caddf {file}
:cbuffer {buffer} Replace Jump Replace error list with buffer.
:cb {buffer}
:cgetbuffer {buffer} Replace No Jump Replace error list with buffer.
:cgetb {buffer}
:caddbuffer {file} Adds No Jump Add buffer to error list.
:cad {biffer}
:cexpr {expr} Replace Jump Replace error list with the
:cex {expr} expression.
:cgetexpr {expr} Replace No Jump Replace error list with
:cgetx {expr} expression.
:cadexpr {expr} Adds No Jump Add the expression to error
:cadde {expr} list.
Vim actually maintains two different types of lists. So far we've been using
the error list which is the same no matter what the current buffer is. There is
also a local list which is local to a buffer. The two are very similar and all of the
error list commands have local list equivalents. The following tables lists the
various commands.
Error Location
List List Description
Command Command
:cc :ll Display current error.
:cn :lne
Display next error.
:cnext :lnext
:cN :lN
:cNext :lNext
Display previous error.
:cp :lp
:cprevious :lprevious
:cnf :lnf
Display first error in the next file.
:cnfile :lnfile
:cNf :lNf
:cNfile :lNfile
Display last error in the previous file.
:cpf :lpf
:cpfile :lpfile
:cr :lr
:crewind :lrewind
Display the first error.
:cfir :lfir
:cfirst :lfirst
:cla :lla
Display the last error.
:clast :llast
:cf :lf
Read errors from a file. Jump to first.
:cfile :lfile
:cg :lg
Read errors from a file. No jump.
:cgetfile :lgetfile
:caddf :laddf
Add lines from a file to the error list
:caddfile :laddfile
:cb :lb
Read errors from a buffer. Jump to first
:cbuffer :lbuffer
:cgetb :lgetb
Read errors from a buffer. No jump.
:cgetbuffer :lgetbuffer
:cad :laddb
Add lines from a buffer to the error list.
:caddbuffer :laddbuffer
:cex :lex
Create error list from expression. Jump to first
:cexpr :lexpr
:cgete :lgete
Create error list from expression. No jump.
:cgetexpr :lgetexpr
:cadde :lad
Add expression to the error list.
:caddexpr :laddexpr
:cl :lli
List errors
:clist :llist
:cope :lop
Open a window containing the error list
:copen :lopen
:ccl :lcl
Close the error list window
:cclose :lclose
:cw :lw
Open the quick fix window if needed.
:cwindow :lwindow
:col :lol
Go to older error list
:colder :lolder
:cnew :lnew
Go to newer error list
:cnewer :lnewer
:mak :lmak
Run the make program and capture the results.
:make :lmake
:vim :lv
Generate results using the internal grep
:vimgrep :lvimgrep
:vimgrepa : :
vimgrepadd lvimgrepa Add grep results to the list
:lvimgrepadd
:gr :lgr Run the external grep comamnd and capture the
:grep :lgrep results
:grepa :lgrepa Run the external grep command and add the result
:grepadd :lgrepadd to the quick fix list
:tag :ltag
Jump to a given tag.
:ta :lt
Amiga t:vim##.Err
UNIX, Linux, FreeBSD /tmp/vim##.err
Microsoft Windows and others vim##.err
You can include special Vim keywords in the command specification. The %
character expands to the name of the current file. So if you execute the
command
:set makeprg=make\ %
and you do a
:make
it executes the following command:
$ make file.c
The parameter file.c is the name of the file you are editing. This is not too
useful, so you will refine
The option 'errorformat' ('efm') controls how Vim parses the error file
so that it knows the filename and line number where the error occurred. The
format of this option is as follows:
:set errorformat=string,string,string
The string is a typical error message with the special character % used to
indicate special operations (much like the standard C function scanf). The
special characters are as follows:
%f Filename
%l Line number
%c Column
%t Error type (a single character)
%n Error number
%m Error message
%r Matches the remainder of the line
%*char Matches (and skips) any scanf conversion specified by char.
%% The character %
To get the filename right Vim needs to be aware of this change. The
following error format specifications are used to tell Vim about directory
changes:
%D Specifies a message printed on entering a directory. The %f in this
string indicates the directory entered.
%X Specifies the leave directory message. The %f in this string specifies
the directory that make is done with.
Some compilers, such as the GNU GCC compiler, output very verbose error
messages. The GCC error message for an undeclared variable is as follows:
tmp.c: In function 'main':
tmp.c:3: 'i' undeclared (first use in this function)
tmp.c:3: (Each undeclared identifier is reported only once
tmp.c:3: for each function it appears in.)
If you use the default Vim 'errorformat' settings, this results in three
error messages. This is really annoying. Fortunately, the Vim editor recognizes
multiline error messages. The format codes for multiline error messages are as
follows:
%A Start of a multiline message (unspecified type)
%E Start of a multiline error message
%W Start of a multiline warning message
%C Continuation of a multiline message
%Z End of a multiline message
%G Global; useful only in conjunction with + or -
%O Single-line file message: overread the matched part
%P Single-line file message: push file %f onto the stack
Now you have a problem. If you use this definition, the %m will match just
'i'. You want a longer error message. So you use + to make Vim put the entire
line in the message:
%+E%f:%l:\ %m\ undeclared\ (first\ use\ in\ this\ function)
The middle matches this:
tmp.c:3: (Each undeclared identifier is reported only once
This translates into the error string:
%-C%f:%l:\ (Each\ undeclared\ identifier\ is\ reported\ only\ once
Note the use of the - modifier to keep this message out of the list of
messages.
There is only one problem with this technique: It doesn't work. The
problem is that Vim goes through the list of strings in 'errorformat' in order,
stopping on the first one that matches. We are appending our messages to the
existing list of messages, and the error string for the GNU compiler (%f:%l:%m)
is defined before us.
It is matched first, and therefore you never get to your two new error
messages. You need to put the more specific matches (your two new messages)
at the beginning. This is accomplished with the following command:
" This will work
:set errorformat ^=
\%-G%f:%l:\ (Each\ undeclared\ identifier\ is\ reported\ only\ once,
\%-G%f:%l:\ for\ each\ function\ it\ appears\ in.)
Remember, the :set ^= command adds the string to the beginning of the
list.
Normally when you do a :make and errors occur,Vim will display the
offending file in the current window. If you set the 'switchbuf' ('swb') option
to split, then the editor will split the current window displaying the bad file in
the new window. Note the 'switchbuf' option can have the values: ''(nothing),
'split,useopen' and 'split,useopen'." For a description of the useopen
argument see Chapter 5: Windows and Tabs.
Makefile
Figure 23-20: The 'switchbuf' option.
Customizing :grep
The :grep (:gr) command runs the program specified by the 'grepprg'
('gp') option. This option contains the command line to use. The # and %
characters will be expanded to be the names of the current and alternate file.
The :grep command uses the 'grepformat' option to tell Vim how to parse
the output of grep. (It uses the same format as the 'errorformat' option.)
Some systems limit the number of characters you can have in a function
name. If you want this limit to be reflected in Vim, you can set the 'taglength'
('tl') option to the maximum length of your function names.
You specify the name of the tags file with the 'tags' ('tag') option. This
can be made to point to a file in another directory. For example:
:set tags+=/home/oualline/tools/vim/tags
But this causes a little confusion. Did you start in the current directory
and tell ctags to put the tag file in the directory /home/oualline/tools/vim or did
you execute the ctags command in this directory?
The Vim editor solves this problem with yet another option. If you set the
following, all tags are relative to the directory that contains the tag file:
:set tagrelative
otherwise, they are relative to the current directory. ('tr' is short for
'tagrelative'.)
With the 'tagstack' option set, the :tag and :tjump commands build a
tag stack. Otherwise, no stack is kept.
Black-and-White Terminals
bold italic
Color Terminals
The color entries are defined by the cterm settings. You can set them
using cterm=attribute just like a normal term entry.
But there are additional options for a color terminal. The setting
ctermfg=colornumber defines the foreground color number. The
ctermbg=colornumber defines the background .
Color names are recognized as well as color numbers. The following tells
Vim to display comments in red on blue, underlined:
:highlight Comment cterm=underline ctermfg=red ctermbg=blue
(Incidentally, this looks really ugly.)
GUI Definition
The GUI terminal uses the option gui=attribute to display the attributes
of a syntax element in the GUI window. The options guifg and guibg define the
colors. These colors can be named. If the name contains a space, the color
name should be enclosed in single quotation marks. To keep things portable, the
Vim people suggest you limit your color names to the following.
Black Blue Brown Cyan
DarkBlue DarkCyan DarkGray DarkGreen
DarkMagenta DarkRed Gray Green
LightBlue LightCyan LightGray LightGreen
LightMagenta LightRed LightYellow Magenta
Orange Purple Red SeaGreen
SlateBlue Violet White Yellow
You can define the color as well by using the standard X11 color numbers.
(This works on all systems, regardless of whether you are using X11.) These are
of the form #rrggbb, where rr is the amount of red, gg is the amount of green,
and bb is the amount of blue. (These three numbers are in hexadecimal.) Under
Microsoft Windows, the following colors are available:
Black Blue Brown
Cyan DarkBlue DarkCyan
DarkGray DarkGreen DarkMagenta
DarkRed Green LightBlue
LightCyan LightGray LightGreen
LightMagenta LightRed Magenta
Red Sys_3DDKShadow Sys_3DFace
Sys_3DHighlight Sys_3DHilight Sys_3DLight
Sys_3DShadow Sys_ActiveBorder Sys_ActiveCaption
Sys_AppWorkspace Sys_Background Sys_BTNFace
Sys_BTNHighlight Sys_BTNHilight Sys_BTNShadow
Sys_BTNText Sys_CaptionText Sys_Desktop
Sys_GrayText Sys_Highlight Sys_HighlightText
Sys_InactiveBorder Sys_InactiveCaption Sys_InactiveCaptionText
Sys_InfoBK Sys_InfoText Sys_Menu
Sys_MenuText Sys_ScrollBar Sys_Window
Sys_WindowFrame Sys_WindowText White
Yellow
You can use the font=x-font as well to define which font to use. This is
not for the faint of heart, because X11 font names are complex. For example:
:highlight Comment font=
\font=-misc-fixed-bold-r-normal--14-130-75-75-c-70-iso8859-1
Microsoft Windows fonts can be used as well:
:highlight Comment font=courier_helv:h12
Combining Definitions
You can define colors for multiple terminals in a single highlight command.
For example:
:highlight Error term=reverse cterm=bold ctermfg=7 ctermbg=1
Syntax Elements
Color Chart
If you want to see what the various colors look like on your terminal, you
can use Vim's color chart. To access this chart, either pull down the
Syntax|Color test menu (gvim) or follow these steps:
grey_on_black black_on_grey
" lightred lightred_on_white white_on_lightred
" lightred_on_black black_on_lightred
" lightgreen lightgreen_on_white white_on_lightgreen
" lightgreen_on_black black_on_lightgreen
" lightyellow lightyellow_on_white white_on_lightyellow
" lightyellow_on_black black_on_lightyellow
" lightblue lightblue_on_white white_on_lightblue
" lightblue_on_black black_on_lightblue
" lightmagenta lightmagenta_on_white white_on_lightmagenta
" lightmagenta_on_black black_on_lightmagenta
" lightcyan lightcyan_on_white white_on_lightcyan
" lightcyan_on_black black_on_lightcyan
● Listing abbreviations
● Mode-specific mappings
Removing an Abbreviation
To remove an abbreviation, use the command :unabbreviate (:una).
Suppose you have the following abbreviation, for example:
:abbreviate @a fresh
(The abbreviation of :abbreviate is :ab.)
The :abbreviate command defines abbreviations that work for both insert
mode and command-line mode. If you type the abbreviation @a in the text, for
example, it will expand to fresh. Likewise, if you put it in a command-mode (:)
command, it will also expand .
If you want to define an abbreviation that works only in insert mode, you
need the :iabbrev (:ia) command:
:iabberv @a fresh
This means that in command mode, @a is just @a. The :noremap (:no)
version of this command is :inoreabbrev (:inorea). To unabbreviate an
insert-mode abbreviation, use the command :iunabbreviate (:inua). To clear
out all the insert abbreviations, use the following command:
:iabclear
(Or you can shorten this to :iabc.)
If you want an abbreviation defined just for command mode, use the
:cabbreviate (:ca) command. The :noremap version of this command is
:cnoreabbrev (:cnorea). To remove a definition, use the :cunabbreviate
(:cuna) command; and to clear out the entire abbreviation list, use the command
:cabclear (:cabc).
Listing Abbreviations
You can list all abbreviations by using the :abbreviate (:ab) command
with no arguments (see Figure 24-1).
~
~
~
c r :rewind
i ab abbreviate
! h Help
Press RETURN or enter command to continue
Figure 24-1: :abbreviate output.
The first column contains a flag indicating the abbreviation type. The flags
are:
c Command mode
i Insert mode
! Both
The command CTRL-C causes Vim to exit insert mode. The difference
between CTRL-C and <Esc> is that CTRL-C does not check for an abbreviation
before entering normal mode.
The "v" flavor of the :map command tells Vim that this mapping is valid
only for visual mode. Table 24-1 lists seven different flavors of the :map
command.
Now suppose that you want to define <F7> so that the command d<F7>
deletes the 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.
With this mapping in place, when you press the d of d<F7>, you enter
operator-pending mode. Pressing <F7> executes the command a{ in
operator-pending mode, selecting the block. Because you are performing a d
command, the block is deleted.
Undoing a Mapping
The :map command with no arguments lists out the mappings (see Figure
24-2).
~
~
~
<xHome> <Home>
<xEnd> <End>
<SxF4> <SF4>
<SxF3> <SF3>
<SxF2> <SF2>
<SxF1> <SF1>
<xF4> <F4>
<xF3> <F3>
<xF2> <F2>
<xF1> <F1>
Press RETURN or enter command to continue
Figure 24-2: Output of :map command.
The first column lists flags indicating the modes for which the mapping is
valid.
Character Mode
n Normal
v Visual
o Operator-pending
i Insert
c Command line
The second column indicates the various lhs of any mappings. The third
column is the value of the rhs of the mapping. If the rhs begins with an asterisk
(*),the rhs cannot be remapped.
The :map command lists all the mappings for normal, visual, and
operator-pending modes. The :map! command lists all the mappings for insert
and command-line mode. The :imap, :vmap, :omap, :nmap, and :cmap commands
list only the mappings for the given modes.
Recursive Mapping
Remapping Abbreviations
Abbreviations can cause problems with mappings. Consider the following
settings, for example:
:abbreviate @a ad
:imap ad adder
Now when you type @a, the string ad is inserted. Because ad is mapped in
insert mode to the string adder, the word adder is inserted in the text.
If you use the command :noreabbrev (:norea), however, you tell Vim to
avoid this problem. Abbreviations created with this command are not candidates
for mapping.
The following chart shows the commands and the various modes they are
associated with:
Mode Commands
Normal, Visual :map : : :
Operator Pending noremap : unmap : mapclear :
no unm mapc
Normal :nmap : :nunmap :nmapclear
:nm nnremap : :nun :nmapc
nn
Visual :vmap :vnoremap :vunmap :vmapclear
Select :vm :vn :vu :vmapc
Visual :xmap :xnoremap :xunmap :xmapclear
:xm :xn :xu :xmapc
Operator :omap :onoremap :ounmap :omapclear
Pending :om :ono :ou :omapc
Insert :map! :noremap! :unmap! :mapclear!
Command Line :no! :unm! :mapc!
Insert :imap :inoremap :iunmap :imapclear
:im :ino :iu :imapc
Command :cmap :cnoremap :cunmap :cmapclear
Line :cm :cno :cu :cmapc
Language :lmap :lnoremap :lunmap :lmapclear
Depedent :lm :ln :lu :lmapc
Mode Commands
Select :smap :snoremap :sunmap :smapclear
:sno :sun :smapc
Being expert in the command-mode means that you are a Vim power user
with the ability to execute a number of amazing high-speed editing commands.
You can also open the command mode history window with the q: or
CTRL-F command. This window lets you use the up (j) and down (k) commands
to select a command. You can edit this command using the normal Vim
commands, then execute it by pressing <Enter>.
Actually, the key (CTRL-F) which opens the command history window is
configurable by setting the option 'cedit'. The default just happens to be
CTRL-F.
The number of lines that appear for the command window is controlled by
the value of the 'cmdwinheight' ('cwh') option.
Editing Commands
The :delete (:d) command deletes a range of lines. To delete lines 1
through 5 (inclusive), for example, use the following command:
:1,5 delete
The general form of the :delete command is as follows:
:[range] delete [register] [count]
The register parameter specifies the text register in which to place the
deleted text. This is one of the named registers (a-z). If you use the uppercase
version of the name (A-Z), the text is appended to what is already in the register.
If this parameter is not specified, the unnamed register is used.
The count parameter specifies the number of lines to delete (more on this
later in this section).
The range parameter specifies the lines to use. Consider the following
example (spaces added for readability):
:1, 3 delete
Figure 25-1 shows the results of this command.
1 A UNIX sales lady, Lenore,
2 Enjoys work, but she likes the beach more.
3 She found a good way
4 To combine work and play:
5 She sells C shells by the seashore.
:1,3 delete
1 To combine work and play:
2 She sells C shells by the seashor
~
~
~
~
3 fewer lines
Figure 25-1: :1,3 delete.
You have learned how to use search patterns for line specification. For
example, the following command deletes starting from the first line with hello to
the first line that contains goodbye.
:/hello/,/goodbye/ delete
Note: If goodbye comes before hello, the line range will be backwards, and
the command will not work.
You can refine the search string specification by adding an offset. For
example, /hello/+1 specifies the line one line after the line with the word hello
in it. Therefore, the following command results in the screen shown in Figure
25-2.
You can also use special shorthand operators for patterns, as follows:
\/ Search forward for the last pattern used.
\? Search backward for the last pattern used.
\& Search forward for the pattern last used as substitute pattern.
You can also chain patterns. The following command, for example, finds
the string first and then searches for the string second.
/first//second/
Figure 25-3 shows the result of the command:
:/found//work/ delete
You can also specify a line number on which to start. To start the search at
line 7, for instance, use the following command-line specification:
7/first/
If you execute a : command with no count (as most users generally do), the
Vim editor puts you into command mode and enables you to specify the range. If
you give the command a count(5:, for example), the range is count lines
(including the current one). The actual specification of this arrangement is that
if you include a count, your line range is as follows:
:.,count - 1
In the example original file, for instance, if you move to the top line and
then execute the following command, you get the results shown in Figure 25-4:
:3delete
Note: You can specify a line range for this type of command, but the first
line is ignored and the second one is used.
The :move command is much like the :copy command, except the lines are
moved rather than copied. The following command results in what is shown in
Figure 25-7:
:1,3 move 4
Inserting Text
Suppose that you want to insert a bunch of lines and for some reason you
want to use command mode. You need to go to the line above where you want
the new text to appear. In other words, you want the text to be inserted after the
current line. Now start the insert by executing the :append (:a) command. Type
the lines that you want to add and finish by typing a line that consists of just a
period (.). The following example illustrates the :append command.
:% print
A UNIX sales lady, Lenore,
Enjoys work, but she likes the beach more.
She found a good way
To combine work and play:
She sells C shells by the seashore.
:1 append
This line is appended.
.
:% print
A UNIX sales lady, Lenore,
This line is appended.
Enjoys work, but she likes the beach more.
She found a good way
To combine work and play:
She sells C shells by the seashore.
The general form of the :append command is as follows:
:[line] append
The line is the line after which to insert the new text.
The :stopinsert (:stopi) command stops insert mode as if you had typed
<ESC>. But this command is a little hard to enter manually, since you must stop
insert mode before you can type it in. It is useful however in :autocmd
declarations. For example, if you want to exit insert mode when you enter a
buffer, use the command:
:autocmd BufEnter * :stopinsert
Substitute
The format of the basic substitute command is as follows:
:[range] s /from/to/[flags] [count]
(You can use :substitute for :s, but in practice this is almost never done.)
Note: This example uses a slash (/) to separate the patterns. Actually you
can use almost any character that does not appear in the patterns. The
following, for example, is perfectly valid:
:s +from+to+
This can prove extremely useful when you are dealing with patterns that
contain slashes, such as filenames:
:1,$ s +/home/user+/apps/product+
The Vim editor uses a special set of magic characters to represent special
things. For example, star (*) stands for "repeat 0 or more times." If you set the
'nomagic' option, however, the magic meanings of some of these characters are
turned off. (For a complete list of the magic characters and how the 'nomagic'
option affects them, see Chapter 19: Advanced Searching Using Regular
Expressions.)
The :smagic (:sm) command performs a substitute but assumes that the
'magic' option is set during the command. For example, start in command mode
with a one-line file. You start by printing the entire file:
:%print
Test aaa* aa* a*
Now set the 'magic' option and perform a substitution. The p flag tells the
editor to print the line it changed:
:set magic
:1 s /a*/b/p
bTest aaa* aa* a*
This command made only one change at the beginning of the line. So why
did it change Test to bTest when there is no a around? The answer is that the
magic character star (*) matches zero or more times. Test begins with zero a's.
But why did it make only one change? Because the :substitute command
changes only the first occurrence unless the g flag is present. Now undo the
change and try again:
:undo
:1 s /a*/b/pg
bTbebsbtb b*b b*b b*b
This time you got what you wanted. Now try it again with the 'nomagic'
option set:
:undo
:set nomagic
:1 s /a*/b/pg
Test aab ab b
Without 'magic', a star (*) is just a star. It is substituted directly. The
:smagic command forces magic on the star (*) and other characters while the
substitution is being made, resulting in the following:
:undo
:1 smagic /a*/b/pg
bTbebsbtb b*b b*b b*b
The :snomagic (:sno) forces 'magic' off.
:undo
:set magic
:1 snomagic /a*/b/pg
Test aab ab b
The & command repeats the substitution. This enables you to keep your
old from and to strings, but also to supply a different range or flags. The general
form of this command is:
:[range]& [flags] [count]
For example:
:1 s /a\+/b/p
Test b* aa* a*
The command changes the first occurrence of from on the line. You want
the entire line, so you repeat the substitution with the g option:
:&g
Of course, this does not print (because the new flags--in this case
g--replaces the flags and you did not specify p or, more specifically, pg). Take a
look at the result:
:1 print
Test b* b* b*
This is what you wanted.
The :~ command acts just like the &r command, except that it uses as from
the last search pattern (used for a / or ? search) rather than the last
:substitute from string.
Substitute flags
& Use the previous flags again. This must be the first
flag in the list.
i Ignore case.
Global Changes
The command-mode commands covered so far have one limitation: They
work only on a contiguous set of lines. Suppose, however, that you want to
change just the lines that contain a certain pattern. In such a case, you need the
:global (:g) command.
To print all the lines within a file that contain the word Professor, for
instance, use the following command:
:% global /Professor/ print
Professor: Yes.
Professor: You mean it's not supposed to do
Professor: Well there was no Computer Center
Professors of mathematics will prove the
The :global! (:g!) command applies the command to all the lines that do
not match the given pattern, as will the :vglobal command.
The :ijump (:ij) command searches for the given pattern and jumps to the
first occurrence of the word in the given range. It searches not only the current
file, but all files brought in by #include directives. The general form of this
command is as follows:
:[range] ijump [count] [/]pattern[/]
If a count is given, jump to the count occurrence of the pattern. If the
pattern is enclosed in slashes it must be whole word. With slashes it is a regular
expression. Consider the file hello.c, for example:
#include <stdio.h>
int main() {
printf("Hello World\n");
return (0);
}
The following command goes to the first line that contains define EOF:
:ijump /define\s*EOF/
In this case, it is in the include file stdio.h. The :ilist (:il) command
acts like :ijump, except it lists the lines instead of jumping to them:
:ilist EOF
/usr/include/libio.h
1: 84 #ifndef EOF
2: 85 # define EOF (-1)
3: 327 && __underflow (_fp) == EOF ? EOF \
/usr/include/stdio.h
4: 83 #ifndef EOF
5: 84 # define EOF (-1)
6: 408 null term.), or -1 on error or EOF. */
/usr/include/bits/stdio.h
7: 138 if (__c == EOF) \
8: 157 if ((*__ptr++, __stream) == EOF) \
The :isearch (:is) command is like :ilist, except that the first
occurrence is listed:
:isearch EOF
#ifndef EOF
Finally, the command :isplit (:isp) works like a :split and a :ijump.
You learned how to use the command [CTRL-D to jump to the definition of
the macro under the cursor. The :djump (:dj) command accomplishes the same
thing for the macro named name:
:djump name
To jump to the macro MAX, for example, use this command:
:djump MAX
You do not have to know the full name of the macro to find its definition. If
you know only part of a name, you can perform a search for a partial string by
enclosing the name in slashes, as follows:
:djump /MAX/
This command finds the first definition of the macro with the word MAX in
it. You can give the :djump command a range argument that restricts the search
to the given range:
:50,100 djump /MAX/
This command finds the first definition of any macro containing the word
MAX in lines 50 through 100.
If you do not want the first definition, but the second, you can add a count
to the command. To find the second definition of MAX, for instance, use this
command:
:djump 2 MAX
The :dlist (:dl) command works just like :djump, except that instead of
moving to the macro definition, the command just lists all the definitions that
match:
:dlist EOF
/usr/include/libio.h
1: 85 # define EOF (-1)
/usr/include/stdio.h
2: 84 # define EOF (-1)
The :dsearch (:ds) command works just like :dlist, except that it
displays only the first definition:
:dsearch EOF
# define EOF (-1)
Directory Manipulation
To change the current working directory, use the following command:
:cd dir
(Also known as :chdir, :chd.)
This command acts just like the system cd command. On UNIX, it changes
the current working directory to the given directory. If no directory is specified,
it goes to the user's home directory.
To find out which directory Vim is currently using, use the :pwd (:pw)
command:
:pwd
Start deep in the directory tree, for instance:
:pwd
/mnt/sabina/sdo/writing/book/vim/book/11
You are working on a UNIX system, so go to your $HOME directory:
:cd
:pwd
/home/sdo
Jump into another directory:
:cd tmp
:pwd
/home/sdo/tmp
Return to the previous directory:
:cd -
:pwd
/home/sdo
Return to the previous directory before this one:
:cd -
:pwd
/home/sdo/tmp
The :cd command is global. In other words, the current directory is
changed for everyone. If you want to change it for just a single window use the
:lcd (:lc, :lchdir, :lch) command.
The 'cdpath' ('cd') option can be used to give Vim a set of directories to
search when doing a :cd. For example, if you enter the command:
:set cdpath=/usr/src,/new/src,,
:cd tools
Then Vim will attempt to go to the first directory it finds in the list:
/usr/src/tools
/usr/new/tools
./tools
Note: The current directory is just the empty string: ,,
(<comma><comma>).
Also if enable the 'auctochdir' ('acd') option then the directory will
automatically change when you change files to the directory of the file you are
currently editing.
Current File
The :file (:f) command prints out the current file and line information:
:file
If you want to change the name of what Vim thinks is the filename, use this
command:
:file name
Suppose, for example, that you start editing a file called [Link]. You
get this file just right, so you write it out using the :write (:w) command.
Now you want to shorten the file and write it out as [Link]. So now
you execute this command:
:file [Link]
Now when you continue to edit, any changes are saved to [Link].
Take a look at how this works. You start by editing the file [Link].
:file
"[Link]" line 1 of 1 --100%-- col 1
The :write command with no arguments writes the file to the current
filename (in this case, [Link]).
:write
"[Link]" 1 line, 18 characters written
Now you want to change the filename to [Link]. The editor tells you that
this is a new filename.
:file [Link]
"[Link]" [Not edited] line 1 of 1 -100%- col 1
The :write command is used to write the file. In this case, the current
filename differs; it is [Link].
:write
"new/txt" [New File] 1 line, 18 chars written
The following command prints the current line number:
:=
For example:
:=
line 1
Warning: The following two commands are different; the difference being
only the spacing:
:write! lpr
:write !lpr
The first writes to the file named lpr with the force option in place. The
second sends the output to the command lpr.
Updating Files
The :update (:up) command acts just like the :write command, with one
exception: If the buffer is not modified, the command does nothing.
Reading Files
The :read (:r) command reads in a file. The general form of this command
is as follows:
:[line] read file
The preceding command reads the file in and inserts it just after line. If no
file is specified, the current file is used. If no line is supplied, the current line is
used.
Like :write, the :read command can use a command rather than a file. To
read the output of a command and insert it after the current line, use the
following command:
:[line] read !command
Register Execution
Chapter 2: Editing a Little Faster showed you how to record macros in
registers. If you want to use these macros in command mode, you can execute
the contents of a register with the command :@ (:*).
:[line]@register
This command moves the cursor to the specified line, and then executes
the register. This means that the following command executes the previous
command line:
:@:
To execute the previous :@register command, use this command:
:[line]@@
Simple Edits
The following sections describe simple edits.
Shifting
The :> command shifts lines to the right. The :< command shifts lines to
the left. The following command, for example, shifts lines 5 through 10 to the
right:
:5, 10 >
Changing Text
The :change (:c) command acts just like the :delete command, except
that it performs an :insert as well.
Joining Lines
The :join (:j) command joins a bunch of lines (specified by the range
parameter) together into one line. Spaces are added to separate the lines. If you
do not want the added spaces, use the :join! command.
Yanking Text
The :yank (:y) command yanks the specified lines into the register:
:[range] yank [register]
If no register is specified, the unnamed register is used.
Putting Text
The :put command puts the contents of a register after the indicated line.
To dump the contents of register a after line 5, for example, use the following
command:
:5put a
If you want to put the text before the line, use this command:
:5put! a
Undo/Redo
The :undo (:u) command undoes a change just like the u command does.
The :redo command redoes a change like CTRL-R does.
Marks
To mark the beginning of the line, use the :mark (:ma) command.
:mark register
command. If a line is specified, that line will be marked. The :k command
does the same thing, with the exception that you don't have to put a space in
front of the register name.
Miscellaneous Commands
The following sections describe some miscellaneous commands you can
use.
The :preserve (:pre) command writes out the entire file to the "swap" file.
This makes it possible to recover a crashed editing session without the original
file. (If you do not use this command, you need both the swap file and the
original to perform recovery.) See Chapter 14: File Recovery and Command-Line
Arguments, for information on recovering crashed sessions.
To execute a single shell command, use the following Vim command (where
cmd is the system command to execute):
:!cmd
To find the current date, for instance, use this command:
:!date
The following command repeats the last shell command you executed:
:!!
Finally, the following command suspends Vim and goes to the command
prompt:
:shell
You can now enter as many system commands as you want. After you have
finished, you can return to Vim with the exit command.
Shell Configuration
Command History
:history
# cmd history
2 1 print
3 5
4 7 print
5 . print
> 6 history
The Vim editor maintains a set of histories for various commands. A code
identifies each of these:
Code History Type
c cmd : Command-line history (command-mode commands)
s search / Search strings (See Chapter 3: Searching)
e expr = Expression register history
i input @ Input line history (data typed in response to an
:input operator)
a all All histories
Therefore, to get a list of all the various history buffers, use the :history
all command:
:history all
# cmd history
2 1 print
35
4 7 print
5 . print
6 history
> 7 history all
# search history
1 human
2 uni
3 comp
4 Seem
> 5 \<At\>
# expr history
1 55
2 2*88
> 3 5+99
# input history
Press Return or enter command to continue
The general form of the :history command is as follows:
:history code first , last
If no first and last are specified, the whole history is listed. The first
parameter defaults to the first entry in the history, and the last defaults to the
last. Negative numbers indicate an offset from the end of the history. For
example, -2 indicates the next-to-last history entry. The following command, for
example, list history entries 1 through 5 for command-mode commands:
:history c 1,5
And, this next command lists the last 5 search strings:
:history s -5,
The 'history' ('hi') option controls how may commands to remember for
command mode (: mode) commands. To increase the number of commands to
remember (to 50, for instance), use this command:
:set history=50
The Vim editor keeps track of the last few error and information messages
displayed on the last line of the screen. To view the message history, use the
:messages (:mes) command:
:messages
"../[Link]" 6092 lines, 174700 characters
Entering Ex mode. Type "visual" to go to Normal
mode.
search hit BOTTOM, continuing at TOP
Not an editor command: xxxxx
search hit BOTTOM, continuing at TOP
search hit BOTTOM, continuing at TOP
Pattern not found: badbad
Not an editor command: :^H
Invalid address
You can also use the :redir command to append to a file by using this
command:
:redir >> file
Getting Out
The :exit (:exi, :xit, :x) command writes the current file and closes the
window:
:exit
When the last window is closed, the editor stops. If the override flag (!) is
given, an attempt will be made to write the file even if it is marked read-only. You
can also specify a filename on the command line. The data will be written to this
file before exiting. The following command, for example, saves the current file in
[Link] and exits.
:exit [Link]
If you want to save only a portion of the file, you can specify a range of
lines to write. To save only the first 100 lines of a file and exit, for example, use
this command:
:1,100 exit [Link]
Advanced Hardcopy
The :hardcopy (:ha) command will print the file to the line printer. You
can also send the printed output to a file with the command:
:[range]hardcopy[!] > file
Warning: The command always overwrites the file without warning. The
override option (!) is used only to automatically select the default printer when
using Microsoft Windows.
Normally the file is printed to the default printer. To change the name of
the printer, set the 'printerdev' ('pdev') option. For example, to go to the
printer named “Fred”, execute the command:
:set printerdev=Fred
The 'printfont' ('pfn') tells the printer what font to use. The actual font
name is the same as for the 'guifont' option. (See page 482.)
The 'encoding' ('enc') option Vim what encoding to use for the text in
the file. If you wish to use a different encoding for printing set the
'printencoding' ('penc') option.
Finally the 'printexpr' ('pexpr') option sets the expression to use for
printing. The expression is passed in the variables v:fname_in as the file to be
printed. This file must be deleted by the expression.
The remainder of this chapter introduces you to the commands that enable
you to customize all these features.
On UNIX you can tell gvim to start at a given location and size by using the
-geometry flag. The general format of this option is as follows:
-geometry {width}x{height}-{x_offset}+{y_offset}
The width and height options specify the width and height of the window
(in characters). The x-offset and y-offset tell the X Windows System where to put
the window.
The x-offset specifies the number of pixels between the left side of the
screen and the right side of the window. If the x-offset specification is negative,
it specifies the distance between the left edge of the editor and the right side of
the screen.
Similarly, the y-offset specifies the top margin, or if negative, the bottom
margin.
Thus, the -geometry +0+0 option puts the window in the upper-left corner,
whereas -geometry -0-0 specifies the lower-right corner. The width and height
parameters specify how big the editing window is to be in lines and columns. To
have a 24-by-80 editing window, for example, use the option -geometry 80x24.
y o'set
x o'set
Height
width
The :winpos (:winp) command displays the current location (in pixels) of
the upper-left corner of the window:
:winpos
If you want to move the window, you can use this command:
:winpos X Y
To position the screen 30 pixels down and 20 pixels over from the left, for
instance, use the following command:
:winpos 20 30
Window Size
The following command displays the number of lines in the editing window:
:set lines?
To change this number, use this command:
:set lines=lines
Lines is the number of lines you want in the new editing window.
To change the number of columns on the screen, use the 'columns' ('co')
option:
:set columns=columns
The 'guioptions'
You can control a number of GUI-based features with the 'guioptions'
('go') option. The general form this command is as follows:
:set guioptions=options
Options is a set of letters, one per option.
a Autoselect When set, if you select text in the visual mode, Vim
tries to put the selected text on the system's global
clipboard. This means that you can select text in
one Vim session and paste it in another using the
"*p command. Without this option you must use
the "*y command to copy data to the clipboard.
Note: You must set this in the initialization file (because by the time you
can set it from the edit window, it is too late).
m Option
no m Option
Note: This option must be set in the .vimrc file. (By the time .gvimrc is
read, it is too late.)
Grey
Removed
b option r option
l option
:set toolbar=icons,tooltips
:set toolbar=icons,text,tooltips
:set toolbar=text,tooltips
Note: To turn off the toolbar, you cannot set this option to the empty
string. Instead use the following command:
:set guioptions -= T
You can also customize the size of the icons using the 'toolbariconsize'
('tbis') option. (This only works if you are using the GTK+2 gui.) The value of
this option are tiny, small, medium, and large.
If you do not like what Vim selects for your title, you can change it by
setting the following:
:set titlestring=Hello\ World!
When you exit Vim, it tries to restore the old title. If it cannot restore it
(because it is impossible to remember it), the editor sets the title to the string
specified by the 'titleold' option. For example:
:set titleold=vim\ was\ here!
When the window is iconified, the icon option tells Vim whether to attempt
to put the name of the file in the icon title. If this option is set, Vim attempts to
change the icon text.
If you do not like the Vim default, you can set the 'iconstring' option and
that text will be used for the icon string.
The 'icon' option, if set causes the string under the icon to contain the
name of the file being edited (or the value of 'iconstring' if set). If the option is
turned off, the icons just have the generic title Vim.
This only works with certain types of window managers which do not
include the major Linux desktops KDE and Gnome.
Mouse Customization
The Vim editor is one of the few UNIX text editors that is mouse-aware.
That means you can use the mouse for a variety of editing operations. You can
customize the utility of the mouse by using the options discussed in the following
sections.
Mouse Focus
Generally when you want to move from one Vim editing window to another,
you must use one of the window change commands such as CTRL-Wj or CTRL-Wk
or click the mouse inside that window. If you set the 'mousefocuse' ('mousef')
option, the current Vim editing window is the one where the mouse pointer is
located:
:set mousefocus
Note: This option affects only the windows within a Vim session. If you are
using the X Windows System, the selection of the current window (X Client
window) is handled by the window manager. On Microsoft Windows, the
current window selection is handled by Microsoft Windows, which always
forces you to use "click to type."
The 'mousemodel' ('mousem') option defines what the mouse does. There
are three possible modes: extend, popup, and popup_setpos. To set the mouse
model, use the following command:
:set mousemodel=mode
In all modes, the left mouse button moves the cursor, and dragging the
cursor using the left button selects the text.
In extend mode, the right mouse button extends the text and the middle
button pastes it in. This behavior is similar to the way an xterm uses the mouse.
In popup mode, the right mouse button causes a small pop-up menu to
appear. This behavior is similar to what you find in most Microsoft Windows
applications.
The popup_setpos mode is exactly like popup mode, except when you press
the right mouse button, the text cursor is moved to the location of the mouse
pointer, and then the pop-up menu appears.
Mouse Configuration
The 'mouse' option enables the mouse for certain modes. The possible
modes are as follows:
n Normal
v Visual
i Insert
c Command-line
Mouse Mapping
The left mouse button (<LeftMouse>) moves the text cursor to where the
mouse pointer is located. The <RightMouse> command causes Vim to enter
visual mode. The area between the text cursor and the mouse pointer is
selected. The <MiddleMouse> acts like the P command and performs a put to
insert in the unnamed register in the file. If you precede the mouse click with a
register specification (such as "a, for instance), the contents of that register are
inserted.
If you have a wheel on your mouse, the up-wheel (<MouseUp>) moves three
lines up. Similarly, a down-wheel movement (<MouseDown>) moves three lines
down. If you press Shift, the screen moves a page. In other words, <S-MouseUp>
goes up a page and <S-MouseDown> goes down a page.
Double-Click Time
When you are editing with the GUI, you have a text cursor and a mouse
pointer to deal with. If that is too confusing, you can tell Vim to turn off the
mouse pointer when not in use. To enable this feature, set the 'mousehide'
('mh') option:
:set mousehide
When you start typing, the mouse pointer disappears. It reappears when
you move the mouse.
Select Mode
The 'selectmode' ('slm') option defines when the editor starts select
mode instead of visual mode. The following three events can trigger select
mode:
The 'keymodel' ('km') option allows the keys <Left>, <Right>, <Up>,
<Down>, <End>, <Home>, <PageUp>, and <PageDown> to do special things. If you set
this option as follows, Shift+key starts a selection: The
:set keymodel=startsel
If the option is set as follows, an unshifted key results in the section being
stopped:
:set keymodel=stopsel
You can combine these options as well, as follows:
:set keymodel=startsel,stopsel
Custom Menus
The menus that Vim uses are defined in the file $VIMRUNTIME/[Link].
If you want to write your own menus, you might first want to look through
that file. To define a menu item, use the :menu (:me) command. The basic form
of this command is as follows:
:menu menu-item command-string
(This command is very similar to the :map command.) The menu-item
describes where on the menu to put the item. A typical menu-item is [Link],
which represents the item Save under the menu File. The ampersand character
(&) is used to indicate an accelerator. In the gvim editor, for instance, you can use
Alt-F to select File and S to select save. Therefore, the menu-item looks like
&File.&Save. The actual definition of the [Link] menu item is as follows:
:menu 10.340 &File.&Save<Tab>:w :confirm w<CR>
The number 10.340 is called the priority number. It is used by the editor to
decide where it places the menu item. The first number (10) indicates the
position on the menu bar. Lower numbered menus are positioned to the left,
higher numbers to the right.
The second number (340) determines the location of the item within the
pulldown menu. Lower numbers go on top, higher number on the bottom.
Figure 26-10 diagrams the priorities of the current menu items. The
menu-item in this example is &File.&Save<Tab>:w. This brings up an important
point: menu-item must be one string. If you want to put spaces or tabs in the
name, you either use the <> notation (<space>, <tab>, for instance) or use the
backslash (\) escape.
10 20 40 50 60 70 9999
Character Mode
i Insert
c Command line
Some menus like the Buffers menu contain a dynamically generated list.
In the case of the Buffers menu it's a list of buffers. The 'menuitems' ('mis')
option controls how many items can be generated.
Toolbar Icons
The toolbar uses icons rather than text to represent the command. The
name of the icon is taken from the name of the menu item. For example, the
menu-item named ToolBar. New causes the New icon to appear on the toolbar.
The Vim editor has 28 built-in icons. The following table lists these.
Each icon has two names. The New icon, for instance, can be specified as
[Link] or ToolBar.builtin00.
The editor looks for a file in the $VIMRUNTIME/pximaps directory for the
icon, then will search its internal list of icons. The name of the icon file is
[Link] on Microsoft Windows and tb_{name}.xpm on UNIX. On Microsoft
Windows, the icon may be any size. On UNIX, it must be 20×20 pixels.
Open builtin01
Save builtin02
Undo builtin03
Cut builtin05
Copy builtin06
Paste builtin07
Print builtin08
Help builtin09
Find builtin10
SaveAll builtin11
SaveSesn builtin12
NewSesn builtin13
LoadSesn builtin14
RunScript builtin15
Replace builtin16
WinClose builtin17
WinMax builtin18
WinMin builtin1
WinSplit builtin20
Shell builtin21
FindPrev builtin22
FindNext builtin23
FindHelp builtin24
TagJump builtin26
RunCtags builtin27
Toolbar Tips
The toolbar can display a "tip" when the cursor is placed over an icon. To
define the tip, issue the :tmenu (:tm) command:
:tmenu menu-item tip
For example, the following command causes the tip Open file to display
when the cursor rests over the Open icon (see Figure 26-11):
:tmenu [Link] Open file
:menu
---- Menus ---
1 ToolBar
10 Open
n* :browse confirm e<CR>
v* <C-C>:browse confirm e<CR><C-\><C-G>
s* <C-C>:browse confirm e<CR><C-\><C-G>
o* <C-C>:browse confirm e<CR><C-\><C-G>
20 Save
n*s :if expand("%") == ""|browse confirm w|else|confirm w|endif<CR>
v*s <C-C>:if expand("%") == ""|browse confirm w|else|confirm w|endif<CR><
C-\><C-G>
s*s <C-C>:if expand("%") == ""|browse confirm w|else|confirm w|endif<CR><
C-\><C-G>
o*s <C-C>:if expand("%") == ""|browse confirm w|else|confirm w|endif<CR><
The problem with the :menu command is that you get 51 screens of data.
That is a lot. To get just the menu items for a specific top-level menu, use the
following command:
:menu menu
For example, the following command lists only the menu items for the File
menu:
:menu File
The next command lists the items for just the [Link] menu:
:menu [Link]
:menu [Link]
--- Menus ---
340 &Save^I:w
n*s :if expand("%") == ""|browse confirm w|else|confirm w|endif<CR>
v*s <C-C>:if expand("%") == ""|browse confirm w|else|confirm w|endif<CR><C-
\><C-G>
s*s <C-C>:if expand("%") == ""|browse confirm w|else|confirm w|endif<CR><C-
\><C-G>
o*s <C-C>:if expand("%") == ""|browse confirm w|else|confirm w|endif<CR><C-
\><C-G>
The letters at the beginning of each line denote the mode in which the
command applies. They correspond to the letters used for the mode parameter
described earlier.
The :emenu (:en) command executes the menu-item as if the user had
selected the command from the menu:
:emenu menu-item
No Remapping Menus
The :menu command defines a menu item. If you want to define an item
and make sure that no mapping is done on the right side, use the :noremenu
(:noreme) command.
Like other mapping commands this has several forms depending on mode:
:tunmenu menu-item
You can tear off a menu by using the dotted tear-off line on the GUI.
Another way to do this is to execute the :tearoff (:te) command:
:tearoff menu-name
Translating A Menu
The base language of all built-in menus is English. If you want to add a
translation to your own language, use the :menutranslate (:menut) command.
For example:
:menutranslate Open Abierto
Now when you have “Open” as an item in a menu, “Abierto” will be
displayed instead.
If you want to have your own translations properly loaded into Vim you
need to execute the following commands in order:
:source $VIMRUNTIME/[Link]
:source $VIMRUNTIME/[Link]
The actual translation that's used for the menu is controlled by the
'languagemenu' ('lm') option. Set this to your local language if you need to
understand the menus.
The :browse (:bro) command opens up a file browser and then executes a
command on the file selected. For example, the following command opens a file
browser and enables the user to select a file (see Figure 26-12):
:browse edit
The editor then performs an :edit file command.
If the [directory] parameter is not present, the directory for the browser
is selected according to the 'browsedir' ('bsdir') option. This option can have
one of three values:
Therefore, if you always want to start in the current directory, put the
following command in your initialization file:
:set browsedir=current
Finding a String
The :promtfind (:pro) command displays a search dialog box (see Figure
26-13):
:promptfind [string]
If a string is specified, the string is used as the initial value of the Find
What field. When the user presses the Find Next button, the Vim editor
searches for the given string.
There is a similar dialog box for the replace command. The :promptrepl
(:promptr) command displays a Replace dialog box (see Figure 26-14):
:promptrepl [string]
Finding Help
The :helpfind (:helpf) command brings up a dialog box that enables you
to type in a subject that will be used to search the help system:
:helpfind
Confirmation
Note: This command works for the terminal version of Vim as well, but the
Confirmation dialog box does not look as nice. This is illustrated in Figure
26-16.
This is a test
:confirm :q
Save changes to "Untitled"?
[Y]es, (N)o, (C)ancel:
Figure 26-16: Confirmation without a GUI.
The :browse set (:bro set, :opt, :options) command opens a window
that enables you to browse through the options:
:browse set
Figure 26-17 shows the screen.
" Each "set" line shows the current value of an option (on the left).
" Hit <CR> on a "set" line to execute it.
" A boolean option will be toggled.
" For other options you can edit the value.
" Hit <CR> on a help line to open a help window on this option.
" Hit <CR> on an index line to jump there.
" Hit <Space> on a "set" line to refresh it.
1 important
2 moving around, searching and patterns
3 tags
option-window
~
[No Name]
"option-window" [New File]
This window gives you access to all the options. The beginning is a short
table of contents, starting with the following:
1 important
2 moving around, searching and patterns
You can use the cursor commands to position the cursor on one of the
items and press <CR> to get a list of the options for this section. If you were to
move the cursor down to the first entry (important) and press <CR>, for instance,
you would get Figure 26-18.
1 important
~
~
[No Name]
/ 1 important
[No Name]
If you close the help screen and move down to the set nocp line and press
<CR>, the option is toggled. (This works for all Boolean options.) The next option
('cpoptions') is a string. To change its value, just edit it using the normal Vim
editing commands, and then press <CR> to set the option to this value.
The 'autoselect' option works for both the GUI and console versions of
Vim.
Coloring
opt-guioptionsd(27-3)When Vim starts the GUI, it tries to figure out
whether you have a light or dark background and performs the 'background'
('bg') option to set the proper value:
:set background=value
The syntax files use the value of this option to determine which colors to
use.
Warning: When the GUI is started, the value of this option is light.
The .gvimrc file is then read and processed. After this, the window is
created. Only after the window is created can Vim tell the color of the
background, so it is only after this that the background option is set. This
means that anything in the .gvimrc that depends on the background being
correct will fail.
You can also turn on and off anti-aliasing with the 'antialias' ('anti')
option. Currently this only works on the Mac.
old Does not allow selection for one character past the end of
a line. The last character of the selection is included in
the operation.
inclusive The character past the end of the line is included, and the
last character of the selection is included in the
operation.
exclusive The character past the end of the line is included, and the
last character of the selection is not included in the
operation.
If you have a wheel on your mouse, the mouse-wheel commands act just
like they do in normal mode.
The :simalt (:si) key simulates the pressing of Alt+key. You can use this
in the following command, for example:
:map <M-f> :simalt f<CR>
This command tells Vim that when Meta-F (Alt+f in Microsoft Windows
terminology) is pressed, the editor is to simulate the pressing of the Alt+f key.
This brings down the File menu.
The 'mouseshape' ('mouses') option defines which cursor to use for the
various modes in the GUI version of Vim. The format of this command is as
follows:
:set mouseshape=mode:cursor,mode:cursor,...
The modes are:
a Everywhere.
c Appending to the command-line.
Line spacing
The 'linespacing' ('lsp') option tell Vim how many extra pixels of space
to put between lines.
MS-DOS-Specific Commands
The :mode (:mod) command changes the screen mode of an MS-DOS
window:
:mode mode
This command is effective only if you are editing inside MS-DOS; it does
not work inside a Microsoft Windows GUI.
Mode is an MS-DOS screen mode such as B80, B40, c80, c40, or one of the
screenmode numbers.
● User-defined functions
The Vim editor uses special prefixes to denote different types of variables.
The prefixes are as follows:
Name Use
All uppercase, digits, and Variables which can be stored in the
underscore .viminfo file if the 'viminfo' ('vi') option
contains the ! flag.
Initial uppercase letter, Variable saved by the make session
lowercase letter somewhere (:mksession, :mks) command.
inside
:let Save_this_option = 1 " Options saved in session
:let forget_this = "yes" " Discarded between sessions
All lowercase, digits, and A variable not stored in any save file.
underscore
$environment Environment variable.
@register Text register.
&option The name of an option.
b:name The variable is local to the buffer. Each
buffer can have a different value of this
variable.
w:name A variable local to a window.
g:name A global variable. (Used inside functions to
denote global variables.)
a:name An argument to a function.
v:name A Vim internal variable
Some examples:
Constants
The Vim editor uses a variety of constants. There are the normal integers:
0xAC Hexadecimal
Expressions
There are three forms of each operator. The bare form (i.e. ==) honors the
'ignorecase' option. The ? form (i.e.==?) always ignores case differences while
the # form (i.e.==#) never ignores different case characters.
Deleting a Variable
A variable can be locked so that its value can not be changed using the
:lockvar (:lockv) command:
:lockvar line_size
If you lock with a depth of two then the array is locked and any items in the
array are locked. But any items referenced by items in the array (which require
two levels of indexing to access) are not locked.
A level of 3 locks the array, the items, items referenced by the items, but
items referenced by items inside items (requiring three levels of indexing to get
to.)
The :lockvar! command with the override(!) sets the locking level to 100
and pretty much locks everything.
Entering Commands
When you are entering arguments to a command, you can use a number of
special words and characters. The words work when you need to enter an
argument such a file name, directory, or other word argument such as the
argument to :tag and the :vimgrep pattern. The special words are::
% Current filename
# Alternate filename
<cword> The word under the cursor.
<cWORD> The WORD under the cursor.
<cfile> The filename under the cursor.
<afile> The name of a file being read or written during the execution
of a related autocommand. (See Chapter 13: Autocommands
for more information.
<abuf> The current buffer number in an autocommand.
<amatch> Like <abuf>, but when used with a FileType or Syntax event
it is not the file name, but the file type or syntax name.
<sfile> The name of the file currently being :sourced.
You can modify each of these words by one or more of the modifiers listed
here (for example, the :p modifier, which turns a filename into a full pathname).
If the name of the file under the cursor is test.c, for instance, <cfile> would be
test.c. On the other hand, <cfile>:p would be /home/oualline/examples/test.c.
How to Experiment
You can determine how Vim will apply modifiers to a filename. First create
a text file whose content is the filename on which you want to run experiments.
Put the cursor on this filename and then use the following command to test out a
modifier:
:echo expand("<cword>:p")
(Change :p to whatever modifier you want to check.)
The following sections discuss the :echo statement and expand function in
more detail.
Echoing in Color
You can use the :echohl (:echoh) command to change the color of the
output :echo to a given highlight group. For example:
:echohl ErrorMsg
:echo "A mistake has been made"
:echohl None
Note: Good programming practice dictates that you always reset the
highlighting to None after your message. That way you do not affect other
:echo commands.
If you want to see what highlight groups are defined, use the command
:highlight (:hi) :
:highlight
Echoing message
The :echomsg (:echom) command acts just like :echo only the string is
saved in the message buffer and will appear if you issue a :messages command.
Control Statements
The Vim editor has a variety of control statements that enable you to
change the flow of a macro or function. With these, you can make full use of
Vim's sophisticated script language.
The statements inside the :if statement are executed if the condition is
non-zero. The four-space indent inside the :if is optional, but encouraged
because it makes the program much more readable. The :if statement can have
an :else clause:
:if {condition}
: " Statement
: " Statement
:else
: " Statement
: " Statement
:endif
(:el can be used for :else if you wish to make your code hard to read.)
Looping
The :while (:wh) command starts a loop. The loop ends with the
:endwhile (:endw) command:
:while counter < 30
: let counter = counter + 1
: " Do something
:endwhile
The :continue (:con) command goes to the top of the loop and continues
execution. The :break (:brea) command exits the loop:
:while counter < 30
: if skip_flag
: continue
: endif
: if exit_flag
: break
: endif
: "Do something
:endwhile
The :for statement loops through all the elements of a list. For example:
:set list=['a', 'b', 'c']
:for item in list
: echo item
:endfor
(For the lazy, :endfo can be used to end the loop. Please don't use it
however as it makes the code less readable.)
If the items in the list are arrays, you can specify a set variables in the
:for. The variables will be assigned each corresponding element in the array.
For example, the following two code fragments are equivalent:
:let m=[[11,12],[21,22],[31,32]]
:for [x,y] in m
: echo x " -> " y
:endfor
:for q in m
: echo q[0] " -> " q[1]
:endfor
Exceptions
When an error occurs Vim throws an exception. If this exception is not
caught, Vim will print an error message and abort processing. For example:
:badcommand
E492: Not an editor command: badcommand
If you want to intercept exception you need to create a try/catch block.
You start by putting everything in a a :try block.:
:try
: “ Do something that might cause an exception
The :try is followed by all the commands you hope to execute.
Next comes the exception handling code. Each exception gets its own
:catch (:cat) statement which tells Vim, when an error occurs (exception is
throw), come here to handle it.
:catch /^E492/
: echo 'Someone typed a bad command'
The argument to :catch is a regular expression. Vim is highly text
oriented and the exception handling is no exception.7 Our regular expression
(/^E492/) matches any string beginning with “E492”. Since all Vim errors are
numbered this will match the “Not an editor command” error no matter what
language is selected for the error message.
7 No pun intended.
All Vim errors (like “E492: Not an editor command”) act like they were
produced with :echoerr.
The :finish (:fini) command will cause all subsequent statements inside
a :try to be skipped. The next statement to be executed will be the first
statement in the :finally block if there is any. If not, the it will be the first
statement after the :endtry. If this statement is executed outside a :try, all the
remaining statement inside the file will be skipped. (The command can not be
executed outside of a file or :try.)
You now use the :return (:retu) statement to return the smallest number
to the user. Finally, you end the function:
: return smaller
:endfunction
The complete function definition is as follows:
:function Min(num1, num2)
: if a:num1 < a:num2
Using a Function
You can now use your function in any Vim expression. For example:
:let tiny = Min(10, 20)
You can also call a function explicitly using the function name with the
:call (:cal) command:
:[range] call function([parameters])
If a range is specified, the function is called for each line, unless the
function is a special "range"-type function (as discussed later).
Function Options
If you attempt to define a function that already exists, you will get an error.
You can use the force option (!) to cause the function to silently replace any
previous definition of the function:
:function Max(num1, num2)
: " Code
:endfunction
If the word abort follows the function definition, the function aborts on the
first error. For example:
:function Do_It() abort
Finally, Vim enables you to define functions that have a variable number of
arguments. The following command, for instance, defines a function that must
have 1 argument (start) and can have up to 19 additional arguments:
:function Show(start, ...)
The variable a:1 contains the first optional argument, a:2 the second, and
so on. The variable a:0 contains the number of extra arguments. For example:
:function Show(start, ...)
: let index = 1 " Loop index
: echo "Show is" a:start
: while (index <= a:0)
: echo "Arg" index "is " a:000[index]
: let index = index + 1
: endwhile
:endfunction
Listing Functions
:function Show
let index = 1 " Loop index
echo "Show is" a:start
while (index <= a:0)
echo "Arg" index "is " a:index
let index = index + 1
endwhile
Deleting a Function
Debugging a Function
Vim has a built-in debugger that lets you debug functions. Let's take a look
at a typical function. This one goes through and changes lines such as:
stdio.h
to lines which look like:
#include <stdio.h>
The function is fairly smart. It can tell the difference between system
includes and user includes and insert the correct C statement for each type of
include.
Let's start by listing out the contents of the function so we know what we
are dealing with:
:function Include
function Include()
1 : " Get the current line
2 : let l:line = getline(".")
3 :
4 : let l:dir_list = split(&path, ",")
5 : " Loop through the local dirs looking for the file
6 : for l:cur_dir in l:dir_list
7 : if (filereadable(l:cur_dir."/".l:line))
8 :
9 : " System directory?
10 : if (match(l:cur_dir, "/usr/include") == 0)
11 :
12 : " Put the #include in the right place
13 : let l:line = "#include <".l:line.">"
14 : else
15 : " Put the #include in the right place
16 : let l:line = "#include \"".l:line."\""
17 : endif
18 :
19 : call setline(".", l:line)
20 : return
21 : endif
22 : endfor
23 :
24 : "At this point we did not find anything
25 : "We could put in a default
endfunction
In order to understand what this function does we would like to single step
through it. So the first thing we do is use the :breakadd (:breaka) command to
add a breakpoint at the beginning of the function.
:breakadd func Include
In this example the func parameter tells Vim to stop at the first line of the
function.
Next we need to start the debugger. The :debug (:deb) command tells Vim
to run the following command, but do so inside the debugger. Without
the :debug, we'd just execute the function normally.
:debug call Include()
Entering Debug mode. Type "cont" to continue.
The debug command step single steps through the code, stepping into any
functions called along the way. If we wanted to step over the function calls, we
need the debugging command next.
Now let's examine one of the function's variables. This is done with the
:echo command:
>:echo l:line
stdio.h
Let's now take a look at the l:dir_list variable. Since this is an array,
the result looks a little different.
>echo l:dir_list
['.', '/usr/include', '']
Next we take a look at what breakpoints we have with the :breaklist
(:breakl) command.
>:breaklist
1 func Include line 1
The next interesting point for us in this function is line 10 where we do the
match() call. Let's put a breakpoint there. The following command tells Vim to
put a breakpoint in a function (func) named Include at line 10:
>:breakadd func 10 Include
The :breakadd command has both a function and a file. The file forms
looks like:
:breakadd file file-name
:breakadd file line file-name
The first form sets a breakpoint that is triggered when a file is loaded. The
second when a specific line of a file is executed. These commands are useful for
debugging Vim command files and the code that exists outside functions.
Normally Vim does not redraw the screen until the current function or
script finishes. To force a redraw, use the :redraw (:redr) command. If you
have an extreme problem with the screen :redraw! clears and redraws the
screen.
Profiling a function
Vim has a built-in profiling feature. To start you must turn on profiling
with the command:
:profile start file-name
(:profile can be abbreviated :prof.)
This tells Vim to start profiling and to write the results out to the given file
upon exit. Now at this point we told Vim to do profiling but haven't given it
anything to profile. Let's tell it to profile our Include() function:
:profile func Include
Now when we execute this function Vim records the profile information.
Let's execute the function once:
:call Include()
Next we exit with the ZZ command. The profile results are now available
in the file we specified at the beginning of this process:
FUNCTION Include()
Called 1 time
Total time: 0.000244
Self time: 0.000244
If you wish to turn off profiling you can do so with any of the following
commands:
:profdel *
:profdel number
:profdel func line function-name
:profdel file line file-name
:profdel here
(:profdel can be abbreviated :profd.)
User-Defined Commands
The Vim editor enables you to define your own commands. You execute
these commands just like any other command-mode command. To define a
command, use the :command (:com) command. For example:
:command DeleteFirst :1delete
Now when you execute the command
:DeleteFirst
the Vim editor performs a
:1delete
which deletes the first line.
-nargs=0 No arguments
The function takes one argument which tells it if the motion was line or
char (character) oriented. (It is also possible for it to be called with the block
argument, but this is almost never done because g@ is not useful is block visual
mode.)
When the function is called the starting mark ('[) will be placed where the
motion starts and the ending mark (']) will be located where it ends.
This is a highly specialized Vim feature and you may need to refer to the
on-line help for details.
Built-In Functions
The Vim editor has a number of built-in functions. This section lists all the
built-in functions.
append(line_number, string)
What it does: Appends the string as a new line after line_number.
Parameters:
Returns: Integer.
Parameter:
Returns: String.
Parameters:
Returns: String.
Parameter:
Parameter:
Parameter:
Returns: String.
Parameter:
buffer_expression
Returns: Integer.
Parameter:
buffer_expression
Parameter:
Returns: Integer.
Parameter:
Returns: Integer.
Parameter:
Returns: Integer.
Parameters:
Returns: Integer.
GUI Confirmation
~
~
:confirm :q
Save changes to "Untitled"?
[Y]es, (N)o, (C)ancel:
Confirmation without a GUI
Note: This function works on both the GUI and console version of the
editor. The console versions of the dialog boxes do not look as nice:
:echo confirm("Hello", "&One\n&Two", 1, "Error")
Hello
[O]ne, (T)wo: O
delete(file_name)
What it does: Deletes the file.
Parameter:
Returns: Integer.
Returns: Integer.
Parameters:
Returns: String.
For example:
:echo escape("This is a 'test'.", " '")
This\ is\ a\ \'test\'."
exists(string)
What it does: Checks to see whether the item specified by
{string} exits.
Parameters:
Returns: Integer.
Parameters:
Parameter:
Returns: Integer.
Parameters:
Returns: String.
getcwd()
What it does: Obtains the current working directory.
Returns: String.
Parameter:
Returns: Integer.
Parameter:
line_number The line number of the line to get or "." for the line
the cursor is on.
Returns: String.
Returns: Integer.
Parameter:
Parameter:
Parameters:
Parameters:
Parameters:
Returns: String.
Parameter:
Returns: Integer.
Parameter:
Parameter:
Returns: Integer.
The ID number.
hostname()
What it does: Gets the name of the computer.
Returns: String.
Parameter:
Parameter:
Parameters:
Note: The function must return a string or NULL. A function that returns
a random pointer might crash Vim.
Returns: String.
Parameter:
Returns: Integer.
Parameter:
Returns: Integer.
Returns: Integer.
Parameters:
Returns: String.
Parameters:
Returns: String.
For example:
:map ax Test
:echo maparg("ax")
Test
:echo maparg("axx")
:echo mapcheck("ax")
Test
:echo mapcheck("axx")
Test
match(string, pattern)
What it does: Checks to see whether string matches pattern.
Setting the 'ignorecase' ('ic') option causes the
editor to ignore upper/lowercase difference.
Parameters:
Integer.
Parameters:
nr2char(number)
What it does: Turns a number into a character.
Parameter:
Parameters:
Parameters:
Parameters:
Returns: String.
Parameter:
Returns: Integer.
For example:
:echo strpart("This is a test", 0, 4)
This
:echo strpart("This is a test", 5, 2)
is
If the start or length parameters specify
non-existent characters, they are ignored. For
example, the following strpart command starts to
the left of the first character:
:echo strpart("This is a test", -2, 4)
Th
Parameters:
Parameter:
Returns: String.
Returns: String.
Parameters:
Returns: Integer.
Parameters:
Returns: String.
Parameter:
Returns: Integer.
system(command)
What it does: Executes the external command specified by
command and captures the output. The options
'shell' ('sh') and 'shellredir' ('ssr') apply to
this function.
Parameter:
Returns: String.
Returns: String.
Parameter:
Returns: Integer.
Parameter:
Returns: Integer.
Parameter:
Returns: Integer.
Returns: Integer.
Obsolete Functions
A few functions are currently obsolete and have been replaced with newer
versions; however, you might still find some scripts that use them.
Obsolete Name Replacement
buffer_exists() bufexists()
buffer_name() bufname()
buffer_number() bufnr()
last_buffer_nr() bufnr("$")
file_readable() filereadable()
highlight_exists() hlexists()
highlightID() hlID()
:source [Link]
There are a number of files that Vim reads in automatically. Any file that is
in the $HOME/.vim/plugin directory is considered a plugin and read in
automatically.
Vim has a couple of funny syntax elements that to help avoid name
collisions with plugins or any other script. The <SID> string will be translated
into a magic character (named <SNR>) a unique serial number and an
underscore. So putting <SID> in front of all your variables and functions in a
script assures that they will all have a unique name.
This chapter discusses how to use the ones that enable you to customize
the appearance and the behavior of your Vim editor.
Setting
The Vim editor has a variety of ways of setting options. Generally, to set an
option, you use the :set (:st) command:
:set option=value
This works for most options. Boolean options are set with this command:
:set option
They are reset with the following command:
:set nooption
To display the value of an option, use this command:
:set option?
If you want to set an option to its default value, use the following
command:
:set option&
Boolean Options
Operation Meaning
:set {option} Turn the option on.
:set no{option} Turn the option off.
:set {option}! Invert the option.
:set inv{option} Invert the option
:set {option}& Set the option to the default value.
For example:
:set list
:set list?
list
:set nolist
:set list?
nolist
:set list!
:set list?
list
:set list&
:set list?
nolist
Numeric Options
:set shiftwidth=4
:set shiftwidth += 2
:set shiftwidth?
shiftwidth=6
:set shiftwidth-=3
:set shiftwidth
shiftwidth=3
:set shiftwidth ^= 2
:set shiftwidth
shiftwidth=6
:set shiftwidth&
:set shiftwidth
shiftwidth=8
String-Related Commands
:set cinwords=test
:set cinwords?
cinwords=test
:set cinwords+=end
:set cinwords?
cinwords=test,end
:set cinwords-=test
:set cinwords?
cinwords=end
:set cinwords^=start
:set cinwords?
cinwords=start,end
Chaining Commands
You can put several :set operations on one line. To set three different
options, for example, use the following command:
:set list shiftwidth=4 incsearch
You can put Vim settings in your files. When Vim starts editing a file, it
reads the first few lines of the file, looking for a line like this:
vim: set option-command option-command option-command .... :
This type of line is called a modeline. In a program, for instance, a typical
modeline might look like this:
/* vim: set shiftwidth=4 autoindent : */
An alternate format is:
vim: option-command:.option-command: ...:
The option 'modeline' ('ml') turns on and off this behavior. The
'modelines' ('mls') option controls how many lines are read at the start and
end of the file when Vim looks for setting commands.
If you set the following option, for instance, Vim does not look for
modelines:
:set nomodeline
If the following option is set, Vim does look at the top and bottom of each
file for the number of lines specified by the 'modeline' option:
:set modeline
For example, you may see lines like the following at the end of many of the
Vim help files:
vim:tw=78:ts=8:sw=8:
This sets the 'tw' ('textwidth') option to 78, the 'ts' ('tabstop') to 8,
and the 'sw' ('shiftwidth') to 8. These settings make the text in the help files
look nice. By using modelines, the creators of the help file make sure that the
text is formatted correctly no matter what local settings you use for your other
files.
Setting this option is considered a security problem. After all, bad things
can easily be dumped into these files, especially if you are editing files in
someone else's directory.
To avoid security problems, you can set the 'secure' option using this
command:
:set secure
This option prevents the execution of the :autocommand, :write, and
:shell commands from inside an initialization file.
Microsoft Windows
Most programs that run under Microsoft Windows use the Alt keys to
select menu items. However, Vim wants to make all keys available for
commands. The 'winaltkeys' ('wak') option controls how the Alt keys are
used.
If you use the following command, for example, all the Alt keys are
available for command mapping with the :map command:
:set winaltkeys=no
Typing ALT-F will not select the file menu, but will instead execute the
command ALT-F is mapped to. A typical mapping might be this:
:map <M-f> :write
(Remember: Vim "spells" ALT as M-, which stands for Meta.) If you use the
following command, all the Alt keys will select menu items and none of them can
be used for mapping:
:set winaltkeys=yes
The third option is a combination of yes and no:
:set winaltkeys=menu
In this mode, if an Alt key can be used for a menu, it is; otherwise, it is
used for :map commands. So ALT-F selects the File menu, whereas you can use
ALT-X (which is not a menu shortcut) for :map commands.
Two options control how Vim reads the keyboard when you are using the
console version of Vim from an MS-DOS window. The 'conskey' ('consk')
option tells Vim to read characters directly from the console:
:set conskey
Do not set this option if you plan to use your Vim editor to read a script file
from the standard input.
The 'bioskey' ('biosk') option tells Vim to use the BIOS for reading the
keyboard:
:set bioskey
Again, do not use this if you plan using a script file for a redirected
standard in. By pointing Vim at the BIOS, you get faster response to CTRL-C and
Break interrupts.
Most UNIX function keys send out a string of characters beginning with
<Esc> when they are pressed. But a problem exists: the <Esc> key is used to end
insert mode. So how do you handle function keys in insert mode?
The solution is for Vim to wait a little after an <Esc> key is pressed to see
whether anymore characters come in. If they do, Vim knows that a function key
has been pressed and acts accordingly. To turn on this feature, execute the set
the 'esckeys' option:
:set esckeys
But what about other key sequences? These are controlled by the
'timeout' ('to') and 'ttimeout' options:
:set timeout
:set ttimeout
The following table shows the effects of these settings.
timeout ttimeout Result
notimeout nottimeout Nothing times out.
timeout N/A All key codes (<F1>, <F2>, and so on) and
:map macros time out.
notimeout ttimeout Key codes (<F1>, <F2>, and so on) only time
out.
The option 'timeoutlen' ('tm') determines how long to wait after <Esc>
has been pressed to see whether something follows. The default is as follows,
which equals one second (1000 milliseconds):
:set timeoutlen=1000
Generally, 'timeoutlen' controls how long to wait for both function keys
and keyboard mapping strings. If you want to have a different timeout for
keyboard mapping strings, use the 'ttimeoutlen' ('ttm') option:
:set ttimeoutlen=500
These two timeouts tell Vim to wait 1/2 second after an <Esc> key has been
pressed to see whether you have a function key or one second to see whether it
is a keyboard mapping. (In other words, if Vim reads enough to determine that
what comes after the <Esc> press cannot possibly be a keyboard mapping
sequence, it will wait only one second between characters trying to figure out
what function key has been typed.)
Confirmation
Generally, when you do something that Vim considers questionable, such as
quitting from a modified buffer, the command fails. If you set the 'confirm'
('cf') option, however, and use the following command, Vim displays a
confirmation dialog box instead of failing:
:set confirm
When you try to :quit a buffer containing a modified file, for example, the
Vim editor displays a confirmation dialog box (see Figure 28-1).
Customizing Messages
Vim generally uses the bottom line of the screen for messages. Sometimes
these messages exceed one line and you get a prompt that states something like
Press Return to Continue. To avoid these prompts, you can increase the
number of message lines by setting the 'cmdheight' ('ch') options. To change
the height of the message space to 3, for instance, use this command:
:set cmdheight=3
This is nice for more complex commands because you can see the
command as it is assembled. For example, the command displays the entire
command (incomplete as it is) in the lower-right corner: "y2f.
***
***
cmdheight [Link]
-- VISUAL -- 2f
showmode showcmd
Short Messages
Another way to limit the "Press Return" prompts is to set the "short
message" option. This shortens many common messages. The flags in the
'shortmess' ('shm') option determine which messages are shortened. The
general form of this command is as follows:
:set shortmess=flags
The following table lists the flags.
Flag Short Value Long Value Default
f (3 of 5) (file 3 of 5) On
i [noeol] [Incomplete last line] On
l 999L, 888C 999 lines, 888 characters On
m [+] [Modified] Off
n [New] [New File] On
r [RO] [re adonly] Off
w [w] written Off
x [dos] [dos format] On
x [unix] [unix format] On
x [mac] [mac format] On
a All the abbreviations: filmnrwx.
A Eliminate the "attention" messages issued when Vim finds an
existing swap file. (Default = off.)
I Eliminate the introduction screen. (Default = off.)
o Sometimes you will perform an operation that writes a file and
then does something else that writes a message, such as
executing a :wnext command.
If this option is not set, you will get two messages and will
probably have to go through a "Press Return" prompt to see the
second one.
If this option is set (the default), the first message is overwritten
by the second.
(Default = on.)
O If you get a message stating that you are reading a file, it will
overwrite any previous message.
(Default = on.)
s If set, do not issue a "Search Hit Bottom, Continuing at Top" or
"Search Hit Top, Continuing at Bottom" message.
(Default = off.)
Error Bells
When Vim gets an error, it just displays an error message. It is silent. If
you are more audio-oriented than visually proficient, you might want to turn on
the 'errorbells' ('eb') option. This following command causes Vim to beep
when there is an error:
:set errorbells
The command
:set statusline=The\ file\ is\ \"%f\"
gives you the following status line:
The file is "[Link]"
You can specify a minimum and maximum width for an item. For example,
the command tells Vim that the filename must take up 8 characters, but is
limited to only 19:
:set statusline=%8.19f
Items are right-justified. If you want them left-justified, put a - just after
the %. For example:
->%10.10f<- ->%-10.10f<-
-> [Link]<- >[Link] <-
Numeric items are displayed with leading zeros omitted. If you want them,
put a zero after the %. To display the column number, for instance, with leading
zeros, use the following command:
:set statusline=%05.10c
For example:
:set statusline=%h%m%r
can look like this:
[help] [+] [RO]
Note: For the purpose of this example, we are ignoring the fact that we
have done the improbable and modified a read-only buffer.
The 'fillcharacs' ('fcs') option controls how extra space in the status
lines (and other separation lines) is filled. It is a list of value from the following
table:
diff:{char} Deleted lines in a diff window
fold:{char} Lines which indicate folds
slt:{char} Status line of the current window
stln:{char} Status line of non-current windows
vert:{char} Vertical lines separating windows.
Rulers
If you do not like the default status line, you can turn on the 'ruler'
('ru') option:
:set ruler
This causes Vim to display a status line that looks like this:
[Link] [help][RO] 1,3-8 Top
After the file name and flags, this displays the current column, the virtual
column, and an indicator showing you how far you are through the file. If you
want to define your own ruler format, set the 'rulerformat' ('ruf') to the
desired format.
:set rulerformat=string
String is the same string used for the 'statusline' option.
Reporting Changes
When you delete or change a number of lines, Vim tells you about it if the
number of lines is greater than the value of the 'report' option. Therefore, to
report information on all changes, use the following command:
:set report=0
On the other hand, if you do not want to be told about what you have
changed, you can set this to a higher value.
>-------Tabbing
can>----be
fun if you >----know how
to set the list >------->-------command.
Another example:
:set listchars=tab:>-,trail:=
Gives us:
This line>------====
has spaces and tabs>----===
at the end=====
of the line====
Suppose that you have set the following options:
:set nowrap
:set listchars=extends:+
Figure 28-3 displays the results.
The student technicians were used to t+
technician took the back off a termina+
loose chip and instead found a large h+
board. He decided to talk to the prof+
Professor: Yes.
Figure 28-3: listchars=extends:+.
Key is a key letter listed in the following table, and group is the name of a
highlight group. The keys are:
Key Default Meaning
8 SpecialKey This highlighting is applied when :map lists out a
special key.
@ NonText Applied to the ~ and @ character that Vim uses to
display stuff that is not in the buffer.
M ModeMsg The mode information in the lower left of the screen.
(See the 'showmode' option.)
S StatusLineNC Status line for every window except the current one.
V VisualNOS Text selected in visual mode when Vim does not own
the selection.
W WildMenu Items displayed as part of a wildcard completion set.
d Directory Directories listed when you press CTRL-D.
e ErrorMsg Error messages.
i IncSearch Text highlighted as part of an incremental search.
l Search Text highlighted as part of a search.
m MoreMsg The -- More -- prompt.
n LineNr The line number printed by the :number command.
r Question The Press Return prompt and other questions.
s StatusLine The status line of the current windows.
t Title Titles for commands that output information in
sections, such as :syntax, :set all, and others.
v Visual Text selected in visual mode.
w WarningMsg Warning
You can use a number of shorthand characters for highlighting, including
the following:
r Reverse
i Italic
b Bold
s Standout
u Underline
n None
- None
Therefore, you can specify that the error message use the highlight group
ErrorMsg by executing the following command:
:set highlight=e:ErrorMsg
Or, you can use the shorthand to tell Vim to display error messages in
reverse, bold, italic, by issuing this command:
:set highlight=e:vrb
In actual practice, you would not define just one mode with a :set
highlight command. In practice, this command can get quite complex. If a key
is not specified, the default highlighting is used.
Number Format
The following command defines which types of numbers can be recognized
by the CTRL-A and CTRL-X commands:
:set nrformats=octal,hex
(Decimal format is always recognized.)
Pasting Text
The X Windows xterm program enables you to select text by drawing the
mouse over it while the left button is held down. This text can then be "pasted"
into another window. However, some of Vim's capabilities can easily get in the
way when pasting text into the window.
To avoid problems, you can set paste mode the 'paste' option:
:set paste
This is shorthand for setting a number of options:
:set textwidth=0
:set wrapmargin=0
:set noautoindent
:set nosmartindent
:set nocindent
:set softtabstop=0
:set nolisp
:set norevins
:set noruler
:set noshowmatch
:set formatoptions=""
At times, you might want paste mode and you might not. The
'pastetoggle' option enables you to define a key that toggles you between
'paste' mode and 'nopaste' mode. To use the <F12> key to toggle between
these two modes, for instance, use the command:
:set pastetoggle=<F12>
When 'paste' mode is turned off, all the options are restored to the values
they had when you set paste mode.
Wildcards
When you are entering a command in ex mode, you can perform filename
completion. If you want to read in the file [Link], for example, you can enter
the following command:
:read input<Tab>
Vim will try to figure out which file you want. If the only file in your
current directory is [Link], the command will appear as:
:read [Link]
If several files that with the word input, the first will display. By pressing
<Tab> again, you get the second file that matches; press <Tab> again, and you
get the third, and so on.
For example:
:set wildcharm=<F12>
:map <F11> :read in<F12>
Now when you press <F11>, it will start a read command for the file
in-whatever.
You probably do not want to match backup file or other junk files. To tell
Vim what is junk, use the 'wildignore' ('wig') option:
:set wildignore=pattern,pattern
Every file that matches the given pattern will be ignored. To ignore object
and backup files, for example, use the following command:
:set wildignore=*.o,*.bak
The 'suffixes' ('su') option lists a set of file name suffixes that will be
given a lower priority when it comes to matching wildcards. In other words if a
file has one of these suffixes it will be placed at the end of any wildcard list.
Generally, the filename completion code does not display a list of possible
matches.
The arrow keys cause the selection to move left and right. The > at the end
of the line indicates that there are more choices to the right. The <Down> key
causes the editor to go into a directory. The <Up> key goes to the parent
directory. Finally, <Enter> selects the item.
You can customize the behavior of the file completion logic by using the
'wildmode' ('wim') option. The following command causes Vim to complete only
the first match:
:set wildmode=
If you keep pressing the 'wildchar' key, only the first match displays.
Figure 28-5 shows how this option works.
First 'wildchar'
[Link] [Link]
[Link]
The following command causes Vim to complete the name with the first file
it can find:
:set wildmode=full
After that, if you keep pressing the 'wildchar' key, the other files that
match are gone through in order. Figure 28-6 shows what happens when this
option is enabled.
First 'wildchar'
Next 'wildchar'
Next 'wildchar'
[Link] [Link]
[Link]
Next 'wildchar'
If you use the following command, you accomplish the same thing; but the
display is just the list of files on the 'wildmenu' line:
:set wildmode=longest:full
The following command displays a list of possible matches when the
'wildchar' is pressed (see Figure 28-7).
:set wildmode=list
~
~
~
~
~
~
~
:r g
getchar.c gui_beval.c gui_x11.c
gui_at_sb.h gui_xmebwp.h
gui.c gui_gtk.c gui_xmdlg.c
gui_beval.h
gui_at_fs.c gui_gtk_f.c gui_xmebw.c
gui_gtk_f.h
gui_at_sb.c gui_gtk_x11.c globals.h
gui_x11_pm.h
gui_athena.c gui_motif.c gui.h
gui_xmebw.h
:r g
Figure 28-7 wildmode=list.
This mode does not complete the match. If you want that to happen as
well, use this option:
:set wildmode=list:full
Finally, to complete the longest common substring and list the files, use the
following option :
:set wildmode=list:longest
You can use these options in a set. The first option is used the first time
the 'wildchar' is pressed, the second option is used the second time you press
'wildchar', and so on, for up to four presses. Therefore, if you want to
complete the longest substring (longest) and then go through the list (full), use
the following option:
:set wildmode=longest,full
Generally, when you try to write a file that you should not, Vim makes you
use the override option (!). If you want to live dangerously, you can tell Vim to
always assume that this option is present for writing type commands by
executing setting the 'writeany' ('wa'):
:set writeany
Memory Options
To set the maximum memory for one buffer, use the 'maxmem' ('mm')
option.
:set maxmem=size
size is the memory limit in kilobytes.
To define total amount of memory for all buffers, use the maxmemtot'
('mx') option.
:set maxmemtot=size
To control the amount of memory used for pattern matching (in search) use
the 'maxmempattern' ('mmp') option.
Terminal Options
The following sections describe the terminal options.
Terminal Name
The name of your terminal is stored in the 'term' option. ('ttytype' and
'tty' are aliases for this option.) Generally, you do not need to set this option
because it is set by your shell or operating environment. However, you might
need to read it to enable terminal-specific macros.
Lazy Redraw
Internal Termcap
The UNIX system has a database of terminal control codes called termcap.
The Vim editor has its own built-in database as well. If the 'ttybuiltin' ('tbi')
option is enabled, this internal database is searched first.
Fast Terminals
If the 'ttyfast' ('tf') option is set, Vim assumes you have a fast terminal
connection and changes the output to produce a smoother update, but one with
more characters. If you have a slow connection, you should reset this option.
The 'ttymouse' ('ttym') option controls the terminal mouse codes. This
option is of interest to those trying to do fancy things with terminal control
codes. For example, if you want to use the mouse buttons <LeftMouse> and
<RightMouse> in console editing, you should enable this option.
The 'ttyscroll' ('tls') option controls how many lines to scroll the
screen when an update is required. You can adjust this to a small number if you
are on a slow terminal.
Compatibility
The 'tildeop' ('top') option makes ~ behave like an operator. This is for
Vi compatibility. If this option is turned off, the ~ command will switch the case
of a single character. With the following, the ~ command takes the form of
~motion:
:set tildeop
Note: The g~ command always behaves as an operator regardless of this
option.
The 'helpfile' ('hf') option defines the location of the main help file.
This option proves useful if you want to redirect where the :help command gets
its information.
For example:
:set helpfile=/usr/sdo/vim/my_help.txt
Weirdinvert
Debugging
One of the problems with turning on verbose output is that things scroll off
the screen quickly. One way to solve this problem is to set the 'verbosefile'
('vfile') option and save the output to a file. Then when you're done, you can
browse through the file using Vim to look for anything you might have missed.
By default many functions that are called automatically such as those for
'foldexpr', 'formatexpr', and 'indentexpr' do out output error message. If
you set the option 'debug' to msg, error messages which normally are
suppressed.
They still won't throw an exception however. For than you need to set
'debug' to throw. Finally, if you want an audible notification of the error, add a
beep.
You can use the three keywords, msg, throw, and beep in any combination
you want such as:
:set debug=msg,beep
Production
The opposite of :verbose is :silent (:sil). It causes normal information
messages produced during the execution of a command to disappear. If used
with the override (!) option, error messages disappear as well.
Keyboard Mapping
The :loadkeymap (:loadk) load a keyboard mapping file into the system.
These mapping files are highly keyboard and language dependent and beyond
the scope of this book.
If you really must create a keyboard map file, you can examine the current
set of mapping files which come with Vim as well as browse the on-line help
documentation for more information.
Encoding
The 'encoding' ('enc') option controls the character set encoding used by
Vim. Unfortunately languages other English are beyond the scope of this book.
Macintosh Silliness
The 'macatsui' is designed to work around a Macintosh drawing bug.
Basically if something is going wrong with Vim on a Mac, try setting this. (As
soon as they figure out what the bug is, this option goes away.)
Obsolete Options
The 'textauto' ('tx') and 'textmode' ('tx') options are obsolete. Use
the options 'fileformats' and 'fileformat' instead.
Legacy Options
Vim tries to be as compatible with the old Vi editor as possible. Vi has a
number of options that mean something to Vi, but are not relevant to Vim. In
order to be fully compatible with Vi, the Vim editor won't generate an error
message if you set any of these options. But the options themselves have no
effect on the editor.
You can make your own copy of these syntax files and modify and update
them if their syntax coloring is not what you desire.
Abel
There are only a couple of variable that control the Able syntax
highlighting:
abel_obsolete_ok Obsolete keywords are statements, not errors
abel_cpp_comments_illegal Do not interpret // as inline comment leader
Ada
Ada is a programming language designed by the United States Defense
Department for embedded programming. There are several options which you
can use to fine tune Ada editing. These are:
Ant
Ant is a tool for building Java program and just about everything else. One
of the problems with Ant is that you can embed scripts written in other
languages inside a Ant file. So not only do you have Ant, but you also have
JavaScript, Perl, Python, and just about anything else.
By default the Ant syntax file correctly highlights JavaScript and Python. If
you want to add another language, for example, Perl, you have to call the
AntSyntaxScript function:
:call AntSyntaxScript('perl', '[Link]')
This must be done for each language you to embed in Ant except of course
JavaScript and Python.
Apache
The variable apache_version should be set to the version of Apache you
are using. The default is 1.3.x.
Assembly Language
There are a number of different assembly languages out there. By default,
Vim assumes that you are using a GNU-style assembly language. The other
assemblers supported are:
asm68k Motorola 680x0 assembly
asm GNU assembly (the default)
asmh8300 Hitachi H-8300 version of GNU assembly
fasm Flat assembly ([Link]
ia64 Intel Itanium 64
masm Microsoft assembly (probably works for any 80x86)
nasm Netwide assembly
pic PIC assembly (currently for PIC16F84)
tasm Turbo Assembly (with opcodes 80x86 up to Pentium, and MMX)
To let Vim know you are using another assembly language, execute the
following command:
:let asmsyntax=language
The language parameter is one of the languages listed above.
This commands sets the global version of the variable. To set the buffer
specific one (and change the syntax highlighting for a single buffer) use the
command:
:let b:asmsyntax=language
You can also put a line like:
; :asmsyntax=nasm
in the first five lines of your code. (Use whatever comment marker is
allowed by your assembler.)
ASP
Files that end with .asp and .asa can contain Perl or Visual Basic code. It's
hard for Vim to automatically tell the difference between these two types of file.
So you need to help things along by setting the variables: g:filetype_asa and
g:filetype_asp to aspperl or aspvbs to let Vim know what to do.
BaaN
The following variables control the way Vim handles BaaN files:
bann_code_stds Highlight code that violates coding standards
bann_fold Enable folding at the function level
baan_fold_block Enable folding at the block level
baan_fold_sql Enable folding at the SQL statement level
Basic
Both Visual Basic and Standard Basic both use files that end in .BAS. To
tell the difference between the two, the Vim editor reads the first five lines of the
file and checks for the string VB_Name. (Files with the extension .FRM are always
Visual Basic.)
C and C++
You can perform a number of customizations for the C and C++ syntax
colors, including the following:
c_comment_strings Highlight strings and numbers inside
comments.
/*:unlet c_ansi */
/*:unlet c_ansi_constants*/
size_t foo;
int i = INT_MIN;
/* :set c_no_ansi_constants = 1 */
size_t foo;
int i = INT_MIN;
/*:unlet c_ansi */
/*:unlet c_ansi_typedefs */
size_t foo;
int i = INT_MIN;
/* :let c_ansi_typedefs = 1n */
size_t foo;
int i = INT_MIN;
/* :let c_no_cformat = 1 */
printf("Data %3f\n", f);
/* :unlet c_no_cformat */
printf("Data %3f\n", f);
int..---->foo;......
int..---->foo;......
/* :unlet c_no_utf */
char *f = "\uFF + \Uffff";
int..---->foo;......
Doxygen
CH
CH is a C/C++ like interpreter. To tune the C syntax highlighting for it, set
the variable: ch_syntax_for_h.
Chill
Chill is another language with a like syntax. The options for this program
are listed in the following table:
chill_space_errors Flag trailing whitespace and spaces in front of a <Tab>.
chill_comment_string Highlight strings and numbers inside comments.
chill_minlines Defines the number of lines searched for syntax
highlighting.
Changelog
By default the Changelog syntax highlights spaces at the beginning of a
line. To turn this off set the variable g:changelog_spacing_errors to 0.
COBOL
There are two versions of COBOL highlighting: fresh development and
legacy. To enable legacy highlighting, use the following command:
:let cobol_legacy_code = 1
Cold Fusion
If you use Cold Fusion style comments, you'll want to set the variable:
html_wrong_comments.
CSH / TCSH
Vim can't tell the different between csh and tcsh files. So to help it you can
set the variable filetype_csh to “csh” or “tcsh” (including the quotes).
CYNLIB
Cynlib files end with .cc and .cpp which make them very difficult to tell
from C and C++ files. To tell Vim to prefer Cynlib syntax, set the variables:
cynlib_cyntax_for_cc and cynlib_cyntax_for_cpp.
CWEB
Files that end in .w can be Progress or Cweb files. To help Vim know that
they are Cweb files, set the variable: filetype_w.
Desktop
There is a standard highlighting syntax for .desktop and .directory files. To
for Vim to adhere to the standard, set the variable:
enforce_freedesktop_standard.
Dircolors
To highlight directory colors according to the Slackware standard set the
variable: dircolors_is_slackware.
DocBook
DocBook files come in two flavors XML and SGML. Normally Vim will
guess at the type, but if the variable docbk_type is set to “sgml” or “xml”
before the syntax file is loaded, that flavor will always be set. (The quotes are
part of the value.)
If Vim guesses wrong you can always manually set the file type using one
of the following commands:
:set filetype=docbksgml
:set filetype=docbkxml
DosBatch
If you are edit MS-DOS batch files you have my deepest sympathy. You
also have a couple of options you can use. The dosbatch_cmdextversion should
be set to 1 if you are using the Windows-NT command processor and 2 if you are
using Windows 2000. The default is Windows 2000.
Also if you are using .btm files, you need to set the variable
g:dosbatch_syntax_for_btm to let Vim know these are MS-DOS batch files.
Doxygen
See C/C++ above.
DTD
DTD is usually case sensitive. To make it not case sensitive, use this
command:
:let dtd_ignore_case = 1
The syntax highlighting flags unknown tags as errors. To turn off this
feature, use the following command:
:let dtd_no_tag_errors = 1
The parameter entity names are highlighted using the Type highlight group
with the Comment group. You can turn this off by using the following command:
:let dtd_no_parameter_entities=1
Eiffel
Eiffel is not case sensitive, but the standard style guidelines require the
use of upper/lowercase. The syntax highlighting rules are designed to encourage
you to follow the standard guidelines. To disable case checking, use the
following command:
:let eiffel_ignore_case = 1
You can cause the syntax coloring to check for the proper capitalization for
Current,Void, Result, Precursor, and NONE, by using this command:
:let eiffel_strict = 1
If you want to really check the syntax against the style guide, use the
following command:
:let eiffel_pedantic = 1
You can use the lowercase versions of current, void, result, precursor,
and none by setting eiffel_lower_case_predef, as follows:
:let eiffel_lower_case_predef = 1
To handle ISE's proposed new syntax, use the following command:
:let eiffel_ise = 1
For support of hexadecimal constants, use this:
:let eiffel_hex_constsnts = 1
ERLANG
ERLANG stands for ERicsson LANGuage. The syntax coloring has two
options:
erlang_keywords Disable the highlighting of keywords.
erlang_characters Disable the highlighting of special characters.
erlang_functions Disable built-in function highlighting
FlexWiki
The syntax file not only defines the syntax coloring for FlexWiki, but also
sets a number of options to make editing easier. The only language dependent
control is the variable flexwiki_maps which if set, allows you to move and down
display lines with j and k.
Form
If you enable enhanced color mode, Vim makes it easier to differentiate
between header and body statements in a program. To enable this feature set
the variable form_enhanced_color.
Fortran
The following variables control how Fortran is highlighted:
fortran_dialect Define the dialect (f95, f90, f77, elf, F) of
Fortran to be used.
fortran_free_source For using the free format flavor of Fortran
fortran_fixed_source Use the fixed format flavor of Fortran
fortran_have_tabs Do not mark tabs as errors
fortran_fold Allow syntax directed folding
fortran_fold_conditionals Allow folding of conditional regions
fortran_fold_multilinecomment Allow folding of multi-line comments
s
fortran_more_precise If defined the syntax coloring will be more
precise, but slower
FVWM
FVWM is a window manager. If you are editing configuration files for this
program, you need to tell Vim the location of the color file using the following
command:
:let rgb_file="/usr/X11/lib/X11/[Link]"
This example shows the location of the [Link] file that comes with Linux.
Other systems may put it in /usr/lib or other locations.
Haskell
Haskell is a literate programming language. The options that control the
syntax highlighting for this language are:
hs_allow_hash_operator Highlight # operators
hs_highlight_boolean Highlight true and false as keywords
hs_highlight_debug Highlight the names of debugging functions
hs_highlight_delimiters Highlight delimiters.
hs_highlight_more_types Treat uncommon types as keywords
hs_highlight_types Treat primitive types as keywords
lhs_markup Define the type of markup. This can be none for no
markup or tex for TeX markup.
HTML
The HTML syntax file uses the following highlight tags:
htmlTitle htmlH1 htmlH2
htmlH3 htmlH4 htmlH5
htmlH6html Boldhtml BoldUnderline
htmlBoldUnderlineItalic htmlUnderline htmlUnderlineItalic
htmlItalic htmlLink
If you want to turn off some of syntax coloring, use the following command:
:let html_no_rendering = 1
If you want to define your own colors for these items, put the color-setting
commands in your .vimrc and use the following command:
:let html_my_rendering = 1
Some files contain <!-- and --!> or <! and !> for comments. If you want
these comments highlighted, use the following command:
:let html_wrong_comments = 1
Inform
Inform language options:
inform_highlight_glulx Do highlighting for Glulx/Glk programs (as opposed
to Z machine programs)
inform_highlight_old Highlight for the older (before version 6.30)
language
inform_highlight_simple Do not highlight library symbols
inform_suppress_obsolete Do not highlight obsolete keywords as errors.
Java
The Java syntax has the following options:
java_mark_braces_in_parens_as_errors
java_highlight_java_lang_ids
java_highlight_functions = "indent"
java_highlight_function = "style"
java_highlight_debug
java_allow_cpp_keywords
java_ignore_javadoc
java_javascript
java_css
java_vb
java_minlines
Lace
The specification of the language states that it is not case sensitive. Good
style is case sensitive. If you want to turn off the "good style" case-sensitive
feature, use the following command:
:let lace_case_insensitive=1
Lex
Lex files are divided up into major sections separated by lines consisting of
%%. If you write long Lex files, the syntax highlighting may not be able to find the
%%.To fix this problem you might need to increase the minlines syntax option
by using a command such as this:
:syntax sync minlines = 300
Lisp
The option g:lisp_instring highlights data inside strings as if it were
lisp. To turn on rainbow parent his (very useful in Lisp) set the variable
g:lisp_rainbow.
Lite
Lite uses a SQL-like query language. You can enable highlighting of SQL
inside strings with the following command:
:let lite_sql_query = 1
If you have large commands, you might want to increase the number of
lines used for synchronizing the syntax coloring:
:let lite_minlines = 500
LPC
LPC files end with .c which Vim considers C files. To make them LPC files
you need to set the variable: lpc_syntax_for_c. You can also use a mode line:
// vim:set ft=lpc:
The following variables can be used to customize LPC.
lpc_pre_v22 Color code for LPC v22 and earlier.
lpc_compat_32 Handle the LpMud 3.2 version of LPC.
lpc_use_lpc4_syntax Color for version 4.0 and later.
LUA
LUA is another language who's syntax has changed from version to version.
To customize the highlighting for a particular version use the variables:
:let lua_version = 4 Version 4
:let lua_version = 5 Version 5.0
:let lua_subversion = 0
:let lua_version = 5 Version 5.1
:let lua_subversion = 1
Mail
The variable mail_minlines controls the number of lines used for
synchronization.
Make
In Makefiles commands are highlighted to make the stand out. If this
results in confusion you can turn it off by setting: make_no_commands.
Maple
Maple V, by Waterloo Maple Inc., is a symbolic algebra language. It has
many different packages that the user can selectively load. If you want to
highlight the syntax for all packages, use the following command:
:let mvpkg_all = 1
If you want to enable specific packages, use one or more of the following
options:
mv_DEtools mv_genfunc mv_networks mv_process
mv_Galois mv_geometry mv_numapprox mv_simplex
mv_GaussInt mv_grobner mv_numtheory mv_stats
mv_LREtools mv_group mv_orthopoly mv_student
mv_combinat mv_inttrans mv_padic mv_sumtools
mv_combstruct mv_liesymm mv_plots mv_tensor
mv_difforms mv_linalg mv_plottools mv_totorder
mv_finance mv_logic mv_powseries
Mathematica
New files ending in .m are assumed to be Mathlib files. To tell Vim that
they should be Mathematica files, execute the command:
:let filetype_m = "mma"
Moo
The variables which control Moo highlighting are:
moo_extended_cstyle_comments Allow C style comments
moo_no_pronoun_sub Turn off highlighting of pronoun substitution
patterns
moo_no_regexp Disable highlighting of regular expression
operator %!, %( and %) inside strings
moo_unmatched_quotes Unmatched double quotes are errors
moo_builtin_properties Highlight built-in property keywords
moo_unknown_builtin_functions Highlight unknown built-in functions as errors
MSQL
To highlight SQL statements inside strings (stored procedures for example)
set the variable: msql_sql_query. The only other option is msql_minlines
which controls the number of lines to look through when doing syntax
synchronization.
NCF
To highlight unknown statements as error set the variable:
ncf_highlight_unknowns.
Nroff
The variables that control the syntax highlighting for nroff type documents
are:
b:nroff_is_groff Nroff files use groff syntax
nroff_space_errors Highlight spacing errors
b:preprocs_as_sections Treat pre-processor entires as section markers
OCAML
Ocaml can be customized by two variables:
ocaml_revised Support revised syntax with camlp4 preprocessor directives.
ocaml_noend_error Do not highlight end statements as an error. (Useful if you
define very long structures and Vim fails to synchronize
properly.)
Papp
Normally HMLT inside Papp files is treated as a string. If you want to have
it treated as HTML, set the variable: papp_include_html.
Pascal
By default files that end in .p can be Progress or Pascal. To force Vim to
consider all .p file as Pascal, put the following in your .vimrc.
:let filetype_p = "pascal"
The syntax highlighting for Pascal is configured through the following
variables:
Perl
If you include POD documentation in your files, you can enable POD syntax
highlighting using the following command:
:let perl_include_pod = 1
If you do not include POD documents, you should. Perl is bad enough when
it is documented.
Php3/ Php4
The following options control the highlighting for Php:
php_asp_tags ASP-style short tags get highlighted
php_baselib Add highlighting for Baselib method
php_folding Allows folding
php_htmlInStrings Highlight HTML syntax inside strings
php_noShortTags Do not highlight short tags
php_oldStyle Use the older style of highlighting
php_parent_error_close Highlight closing brace errors
php_parent_error_open Highlight opening brace errors
PlainTex
The only option to PlainTex syntax highlighting is the variable
g:plaintex_delimiters which turns on highlighting for the delimiters [] and
{}.
PPWizard
If you set the variable ppwiz_highlight_defs to 1 (the default) #define
statement retain the color of their contents. If you set this variable to 2, the
these statements are highlighted using a single color.
Phtml
To highlight SQL syntax in a string, use the following:
:let phtml_sql_query = 1
To change the synchronization window, use this command:
:let phtml_minlines = lines
PostScript
The options for PostScript highlighting are:
postscr_level Set the PostScript language level
(default = 2).
postscr_display Highlight display postscript features.
postscr_ghostscript Hightlight GhostScript-specific syntax.
postscr_fonts For font highlighting (off by default for
speed).
postscr_encodings Encoding tables (off by default for
speed).
Progress
Progress files can end in .w, .i, or .p. To make Vim detects you Progress
file as Progress files, you may wish to set some of the following variables:
:let filetype_w = "progress"
:let filetype_i = "progress"
:let filetype_p = "progress"
Python
The Python highlighting can be tuned by setting the following variables:
python_highlight_all Turn on all possible Python highlighting
python_highlight_builtins Highlight builtin functions
python_highlight_exceptions Highlight standard exceptions
python_highlight_numbers Highlight numbers
python_highlight_space_errors Highlight trailing spaces
Quake
Quake comes in multiple flavors. To tune Vim for your flavor you should
set one of the variables: quake_is_quake1, quake_is_quake2, or
quake_is_quake3. You can set all three, and highlight for Quake Version
1+2+3, but as there is no such game, this may not be useful.
ReadLine
To highlight the bash extensions to ReadLine, set the variable:
readline_has_bash.
Rexx
You can adjust the number of lines used for synchronization with the
following option :
:let rexx_minlines = lines
Ruby
The variables which control the Ruby syntax are:
ruby_fold Allow folding based on the Ruby syntax
ruby_minlines The minimum number of lines to use for syntax
synchronization
ruby_no_comment_fold Do not allow the folding of multi-line comments
ruby_no_expensive Do not highlight an end statement in a way that
matches it to the opening statement. (This is an
expensive operation, hence the variable name.)
ruby_no_special_methods Do not highlight significant methods of the kernel,
module, and object.
ruby_operators Highlight Rudy operators
ruby_space_errors Highlight space errors
Scheme
By default Vim uses the R5RS version of Schema. To tell it that you are
using MzScheme set the variable is_mzscheme.
SDL
To enable SDL-2000 keyword highlighting set the variable sdl_2000. To
disable the older keywords set SDL_no_96.
Sed
To make tabs stand out, you can use the :set list option. You can
highlight them differently by using the following command:
:let highlight_sedtabs = 1
Hint: If you execute a
:set tabstop = 1
as well, it makes it easy to count the number of tabs in a string.
SGML
If you set the sgml_my_rendering Vim assumes that you've already defined
highlighting for SGML and does not overwrite your definitions. (Not syntax, just
the colors for highlighting.)
Shell
The following options change the highlighting for shell scripts:
is_bash The Bash version of the syntax is expected.
is_korn_shell Assume the Korn Shell flavor of the syntax.
is_posix Assume POSIX syntax.
is_sh The old Borne shell syntax is highlighted.
sh_fold_enable Enable syntax directed folding.
sh_minlines Set the number of lines for synchronization
sh_maxlines Limit the number of lines for synchronization
(speeds things up).
Speedup
The options for Speedup are:
strict_subsections Only highlight the keywords that belong in
each subsection.
highlight_types Highlight stream types as a type.
oneline_comments = 1 Allow code after any number of # comments.
oneline_comments = 2 Show code starting with the second # as an
error (default).
oneline_comments = 3 If the line contains two or more # characters
in it, highlight the entire line as an error.
TCsh
This is a super-set of csh, so all the csh rules apply. It also has the
following customizations:
tcsh_backslash_quote Do not highlight \" as an error
tcsh_minlines Minimum number of lines for syntax synchronization
TeX
TeX is a complex language that can fool the syntax highlighting. If the
editor fails to find the end of a texZone, put the following comment in your file:
%stopzone
The TeX options include:
tex_fold_enabled Enable syntax directed folding
tex_no_error Disable flagging of errors
tex_stylish Indicate that your TeX files use @ commands
TinyFugue
To adjust the synchronization limit for TinyFugue files, use this option:
:let tf_minlines = lines
Vim
Even Vim has its own syntax files. These can customized as well.
vimembedscript If set to 1, embed scripting languages are highlighted. If set
to 0, the syntax file for embedded scripting languages are
not loaded. If not defined, the files are loaded, just not used.
vim_maxlines Maximum lines for syntax synchronization
vim_minlines Minimum lines for syntax synchronization
vimsyntax_noerror Do not highlight errors
XF86Config
There are two different major version of the Xfree86 configuration files.
The variable xf86conf_xfree86_version should be set to 3 or 4 depending on
which version you have.
Xml
Xml namespaces are highlighted by default. To turn off this feature, set
the variable: g:xml_namespace_transparent.
Some languages are not case sensitive, such as Pascal. Others, such as C,
are case sensitive. You need to tell which type you have with the following
commands:
:syntax case match
:syntax case ignore
The match option means that Vim will match the case of syntax elements.
Therefore, int differs from Int and INT. If the ignore option is used, the
following are equivalent: Procedure, PROCEDURE, and procedure.
The :syntax case commands can appear anywhere in a syntax file and
affect all the syntax definitions that follow. In most cases, you have only one
:syntax case command in your syntax file; if you work with an unusual
language that contains both case-sensitive and non-case-sensitive elements,
however, you can scatter the :syntax case command throughout the file.
The most basic syntax elements are keywords. To define a keyword, use
the following form:
:syntax keyword group keyword .......
The group name is the name of a highlight group, which is used by the
:highlight command for assigning colors. The keyword parameter is an actual
keyword. Here are a few examples:
:syntax keyword xType int long char
:syntax keyword xStatement if then else endif
This example uses the group names xType and xStatement. By convention,
each group name is prefixed by a short abbreviation for the language being
defined. This example defines syntax for the x language (eXample language
without an interesting name).
These statements cause the words int, long, and char to be highlighted
one way and the words if and endif to be highlighted another way.
Now you need to connect the x group names to standard Vim names. You
do this with the following commands:
:highlight link xType Type
:highlight link xStatement Statement
(The :highlight command can be shortened to :hi.)
This tells Vim to treat xType like Type and xStatement like Statement.
The x language allows for abbreviations. For example, n and next are both
valid keywords. You can define them by using this command:
:syntax keyword xStatement n[ext]
Defining Matches
Consider defining something a bit more complex. You want to match
ordinary identifiers. To do this, you define a match syntax group. This one
matches any word consisting of only lowercase letters:
:syntax match xIdentifier /[a-z]\+/
Now define a match for a comment. It is anything from # to the end of a
line:
:syntax match xComment /#.*$/
Note: The match automatically ends at the end of a line by default, so the
actual command is as follows:
:syntax match xComment /#.*/
Defining Regions
In the example x language, you enclose strings in double quotation marks
("). You want to highlight strings differently, so you tell Vim by defining a region.
For that, you need a region start (double quote) and a region end (double quote).
The definition is as follows:
:syntax region xString start=/"/ end=/"/
The start and end directives define the patterns used to define the start
and end of the region. But what about strings that look like this?
"A string with a double quote (\") in it"
This creates a problem: The double quotation marks in the middle of the
string will end the string. You need to tell Vim to skip over any escaped double
quotes in the string. You do this with the skip keyword:
:syntax region xString start=/"/ skip=/\\"/ end=/"/
Note: The double backslash is needed because the string you are looking
for is \", so the backslash must be escaped (giving us \\").
Nested Regions
Take a look at this comment:
# Do it TODO: Make it real
You want to highlight TODO in big red letters even though it is in a
comment. To let Vim know about this, you define the following syntax groups:
:syntax keyword xTodo TODO contained
:syntax match xComment /#.*$/ contains=xTodo
In the first line, the contained parameter tells Vim that this keyword can
exist only inside another syntax element. The next line has a contains=xTodo
parameter. This indicates that the xTodo syntax element is inside it. The results
(xTodo=underline, xComment=italic) are as follows:
# Do it TODO: Make it real
Consider the following two syntax elements:
:syntax region xComment start=/%.*/ end=/$/ contained
:syntax region xPreProc start=/#.*/ end=/$/ contains=xComment
You define a comment as anything from % to the end of the line. A
preprocessor directive is anything from # to the end of the line. Because you can
have a comment on a preprocessor line, the preprocessor definition includes a
contains=xComment paramter. The result (xComment=italic,
xPreProc=underline) is as follows:
#define X = Y % Comment
int foo = 1;
But there is a problem with this. The preprocessor directive should end at
the end of the line. That is why you put the end=/$/ directive on the line. So
what is going wrong? The problem is the contained comment. The comment
start starts with % and ends at the end of the line. After the comment is
processed, the processing of the preprocessor syntax contains. This is after the
end of the line has been seen, so the next line is processed as well.
To avoid this problem and to force contained syntax from eating a needed
end of line, use the keepend parameter. This takes care of the double end-of-line
matching:
:syntax region xComment start=/%.*/ end=/$/ contained
:syntax region xPreProc start=/#.*/ end=/$/
\ contains=xComment keepend
You can use the contains parameter to specify that everything can be
contained. For example:
:syntax region xList start="\[" end="\]" contains=ALL
You can also use it to include a group of elements except for the ones
listed:
:syntax region xList start="\[" end="\]"
\ contains=ALLBUT,xString
For example, you define a syntax element consisting of > at the beginning
of a line. You also define a element for the KEY string. In this case, the KEY is
important only if it is part of a > line. The definition for this is as follows:
:syntax match xSpecial "^>" nextgroup=xKey
:syntax match xKey "KEY" contained
The nextgroup option tells Vim to highlight KEY, but only if it follows
xSpecial. The result (xKey=italic, xSpecial=underline) is:
KEY
Transparent Matches
Other Matches
The oneline option indicates that the region does not cross a line
boundary. For example:
:syntax region xPrePoc start=/^#/ end=/$/ oneline
Things now become a little more complex. Let's allow continuation lines.
In other words, any line that ends with \ is a continuation line. The way you
handle this is to allow the xPreProc syntax element to contain a continuation
pattern:
:syntax region xPreProc start=/^#/ end=/$/ oneline
\ contains=xLineContinue
:syntax match xLineContinue "\\$" contained
In this case, although xPreProc is on a single line, the groups contained in
it (namely xLineContinue) let it go on for more than one line.
This is what you want. If it is not what you want, you can call for the
region to be on a single line by adding excludenl to the contained pattern. For
example, you want to highlight "end" in xPreProc, but only at the end of the line.
To avoid making the xPreProc continue on the next line, use excludenl like this:
:syntax region xPreProc start=/^#/ end=/$/
\ contains=xLineContinue,xPreProcEnd
:syntax match xPreProcEnd excludenl /end$/ contained
Note that excludenl is placed before the pattern. Now you can still use
xLineContinue as previously. Because it doesn't have excludenl, a match with
it will extend xPreProc to the next line.
Match Groups
When you define a region, the entire region is highlighted according to the
group name specified. To highlight the text enclosed in parentheses () with the
highlight group xInside, for example, use the following command:
:syntax region xInside start=/(/ end=/)/
Match Offsets
Several options enable you to adjust the start and end of a pattern used in
matching for the :syntax match and :syntax region directives. For example,
the offset ms=s+2 indicates that the match starts two characters from the start of
the match.
For example:
:syntax match xHex /0x[a-fA-F0-9]*/ms=s+2
The general form of a match offset is as follows:
location=offset
Location is one of the following:
ms Start of the element
me End of the element
hs Start highlighting here
he End highlighting here
rs Marks the start of a region
re Marks the end of region
lc Leading context
The offset can be as follows:
s Start of match
Clusters
One of the things you will notice as you start to write a syntax file is that
you wind up generating a lot of syntax groups. The Vim editor enables you to
define a collection of syntax groups called a cluster. Suppose you have a
language that contains for loops, if statements, while loops, and functions.
Each of them contains the same syntax elements: numbers and identifiers. You
define them like this:
:syntax match xFor /^for.*/ contains=xNumber,xIdent
:syntax match xIf /^if.*/ contains=xNumber,xIdent
:syntax match xWhile /^while.*/ contains=xNumber,xIdent
You have to repeat the same contains= every time. If you want to add
another contained item, you have to add it three times. Syntax clusters simplify
these definitions by enabling you to group elements. To define a cluster for the
two items that the three groups contain, use the following command:
:syntax cluster xState contains=xNumber,xIdent
Clusters are used inside other :syntax elements just like any syntax
group. Their names start with @. Thus, you can define the three groups like this:
:syntax match xFor /^for.*/ contains=@xState
:syntax match xIf /^if.*/ contains=@xState
:syntax match xWhile /^while.*/ contains=@xState
You can add new elements to this cluster with the add argument:
:syntax cluster xState add=xString
You can remove syntax groups from this list as well:
:syntax cluster xState remove=xNumber
The word <sfile> is the name of the syntax file that is currently being
processed. The :p:h modifiers remove the name of the file from the <sfile>
word. Therefore, <sfile>:p:h/[Link] is used to specify the file [Link] in the
same directory as the current syntax file.
Now consider the Perl language. The Perl language consists of two distinct
parts: a documentation section in POD format, and a program written in Perl
itself.
The POD section starts with =head and the end starts with =cut. You want
to construct the Perl syntax file to reflect this. The :syntax include reads in a
syntax file and stores the elements it defined in a syntax cluster. For Perl, the
statements are as follows:
:syntax include @POD <sfile>:p:h/[Link]
:syntax region perlPOD start="^=head" end="^=cut"
\ contains=@POD
In this example, the top-level language is Perl. All the syntax elements of
the POD language are contained in the Perl syntax cluster @POD.
Synchronization
Compilers have it easy. They start at the beginning of a file and parse it
straight through. The Vim editor does not have it so easy. It must start at the
middle, where the editing is being done. So how does it tell where it is?
The secret is the :syntax sync command. This tells Vim how to figure out
where it is. For example, the following command tells Vim to scan backward for
the beginning or end of a C-style comment and begin syntax coloring from there:
:syntax sync ccomment
You can tune this processing with some options. The minlines option tells
Vim the minimum number of lines to look backward, and maxlines tells the
editor the maximum number of lines to scan.
For example, the following command tells Vim to look at 10 lines before the
top of the screen:
You also can define matches and regions that are with no grouphere or
'groupthere' options. These groups are for syntax groups skipped during
synchronization. For example, the following skips over anything inside {}, even
if would normally match another synchronization method:
:syntax sync match xSpecial /{.*}/
To clear out the synchronization commands, use the following command:
:syntax sync clear
To remove just the named groups, use this command:
:syntax sync clear sync-group-name sync-group-name ...
The :syntax sync commands only control the number of lines used to do
syntax matching. The 'synmaxcol' ('smc') option tells Vim how many columns
to use for syntax matching. The default is 3000, and if you have a file with more
that 3000 characters per line, syntax matching is the least of your problems.
Option Summary
contained
Syntax group is contained in another
group. Items that are contained cannot appear
UNIX
You can get precompiled binaries for many different UNIX systems from
[Link]. Go to [Link] click the "Download Vim" link, and then
follow the "Binaries Page" link. This takes you to the "Binaries" page, which lists
the various precompiled binaries for many different systems along with the links
to download them.
Unpacking the sources is a simple matter of using bzcat (part of the bzip
software suite) to decompress the archive, and tar to extract the members:
$ bzcat [Link].bz2 | tar xf -
Next we go into the directory containing the sources:
$ cd vim
Running configure
The configure script configures the source so that it can be properly built.
First let's take a look at the --help option (that is <dash><dash>help) to see
what the command does:
$ ./configure --Khelp
`configure' configures this package to adapt to many kinds of systems.
Configuration:
-h, --help display this help and exit
--help=short display options specific to this package
--help=recursive display the short help of all the included packages
-V, --version display version information and exit
-q, --quiet, --silent do not print `checking...' messages
--cache-file=FILE cache test results in FILE [disabled]
-C, --config-cache alias for `--cache-file=[Link]'
-n, --no-create do not create output files
--srcdir=DIR find the sources in DIR [configure dir or `..']
Installation directories:
--prefix=PREFIX install architecture-independent files in PREFIX
[/usr/local]
--exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
[PREFIX]
Don't worry about all these options. You'll probably never use most of
them. They only really important option is --prefix (<dash><dash>prefix) which
tells configure where you want to install the program. For example, in a users
home directory.
$ ./configure --prefix=/home/auser/local
Now configure looks through system and figures out how to make Vim.
configure: creating cache auto/[Link]
checking whether make sets $(MAKE)... yes
checking for gcc... gcc
Assuming that you compiled without error, the next step is to install the
software with the command:
$ make install 2>&1 | tee [Link]
The results can be seen below.
$ make install 2>&1 tee [Link]
Starting make in the src directory.
If there are problems, cd to the src directory and run make there
cd src && make install
make[1]: Entering directory `/mnt/disk/vim/build/vim72/src'
if test -d /home/sdo/local/share/icons/locolor/16x16/apps -a -w
/home/sdo/local/share/icons/locolor/16x16/apps \
-a ! -f
/home/sdo/local/share/icons/locolor/16x16/apps/[Link]; then \
cp ../runtime/[Link]
/home/sdo/local/share/icons/locolor/16x16/apps/[Link]; \
fi
cp gvimtutor /home/sdo/local/bin/gvimtutor
chmod 755 /home/sdo/local/bin/gvimtutor
make[1]: Leaving directory `/mnt/disk/vim/build/vim72/src'
If you are lucky these commands will run without error and you'll have a good Vim installation.
If not, read the next section;
The console (text) version of Vim is fairly robust and has compiled
successfully on every machine I've tried it on, and I've compiled on a lot of very
strange machines. (Microsoft Windows excluded.)
The big problem comes in configuring and compiling the GUI version of
Vim. No matter which version you choose, the system will make heavy use of
several X Windows GUI libraries. If these libraries are not installed on your
system, or you do not have the correct version of the library, Vim will fail to build
the GUI version of itself.
To see if you have a GUI problem, after executing the make command
(make only, not make install), go into the src directory and execute the command
./vim -g:
$ make
$ cd src
$ ./vim -g
If a GUI appears and it's the correct GUI, then you don't have a problem.
You're done.
But if you get an error, then look at your configuration log file: [Link].
The relevant lines (in this case) are:
configure:7800: result: yes
configure:7841: checking if X11 header files can be found
configure:7857: gcc -c -g -O2 -I/usr/local/include conftest.c >&5
conftest.c:17:27: fatal error: X11/Intrinsic.h: No such file or directory
#include <X11/Intrinsic.h>
^
compilation terminated.
configure:7857: $? = 1
This is where the configuration command is attempting to figure out what
libraries are installed so it can figure out what GUI to build. In this example we
do not have the X11 development library which supplies X11/Intrinsic.h.
Now you may think that you have the yy library installed but Vim fails to
detect it. You need to find out why. Some clues can be found the [Link] file
which is automatically generated by the configure command. This file gives you
some idea of what tests are being run to determine which libraries are installed.
If the [Link] file does not help you, you'll need to examine the contents
of the configuration command itself. It is written the shell programming
language so it is somewhat readable, although if you are not a expert shelling
program going into the script, you will be before you leave.
If all else fails you can hit the mail list and ask for help. But before doing
so, please, please search the archive. Someone may have already experienced
your problem and found a solution.
In closing I must say that the last time I got Vim installed it went surprising well
even through it was on a rather difficult platform. I simply sent a request to the
IT department, and a week later I got an E-Mail saying: “We finally got Vim
installed and you wouldn't believe the trouble we had getting the thing to work.”
(Yes I would, I wrote the book, literally, on Vim.)
Each UNIX user should make sure that Vim is in his path. If you have an
.exrc file, copy it to .vimrc:
$ cp ~/.exrc ~/.vimrc
If you do not have an .exrc file, create an empty .vimrc file by executing the
following command:
$ touch ~/.vimrc
Note: The presence of the .vimrc file turns on all the fancy features of Vim.
If this file is not present, Vim tries very hard to look like Vi, even disabling
some of its features to do so.
I Am Using RedHat Linux. Can I Use the Vim That Comes with the
System?
Line Endings
<CR> <Return> <Enter>
<LF> <LineFeed>
<NL> <NewLine>
Other Special Characters
<BS > <BackSpace>
<Ins> <Insert>
<Del> <Delete>
Editing Keys
<End> <Home> <PageDown> <PageUp>
Arrow Keys
<Left> <Right> <Up> <Down>
Keypad Keys
<kDivide> <kPlus> <kEnd> <kEnter>
<kHome> <kPageUp> <kMinus> <kMultiply>
<kPageDown>
Printable Characters
<Bar> |
<Bslash> \
<Space>
<Tab>
<Lt> <
Other Keys
<Esc> <Help> <Nul> <Undo>
Termcap Entries
On UNIX systems, the Termcap or Terminfo database contains a
description of the terminal, including function keys. The special key <t_XX>
represents the key defined by XX Termcap entry.
See your UNIX documentation for a complete list of keys. One way to get a
list (for most systems) is to execute the following command:
$ man terminfo
Mouse Actions
<LeftMouse> <RightMouse>
<LeftRelease> <RightRelease>
<LeftDrag> <RightDrag>
<MiddleDrag> <MiddleRelease>
<MouseUp> <MouseDown>
<MiddleMouse> <Mouse>
Modifiers
M Meta (Alt)
C Control
S Shift
D Macintosh command key
Mouse Modifiers
<Blank> Mouse button one
2 Mouse button two
3 Mouse button three
4 Mouse button four
Note: If you want to find the name of a key on the keyboard, you can go
into Insert mode and press CTRL-K key. The <> name of the key will be
inserted. This works for the function keys and many other keys.
CTRL-W CTRL-C Cancel any pending window command. (See page 84.)
CTRL-W CTRL-D Split the window and find the definition of the word
under the cursor. If the definition cannot be found, do
not split the window. (Same as: CTRL-Wd.) (See page
341.)
CTRL-W CTRL-F Split the window and edit the file whose name is under
the cursor. Looks for the file in the current directory,
and then all the directories specified by the 'path'
option. (Same as: CTRL-Wf.) (See page 341.)
[count]CTRL-W CTRL-G CTRL-]
:split followed a CTRL-]. If a [count] is specified,
make the new window [count] lines high. (Same as:
CTRL-Wg CTRL-], CTRL-Wg.) (See page 341.)
[count]CTRL-W CTRL-G }
Do a :ptjump on the word under the cursor. If a
[count] is specified, make the new window [count]
lines high. (Same as: CTRL-W CTRL-G}.) (See page
393.)
[count]CTRL-W CTRL-H Go left [count] windows. (Same as: CTRL-W h,
CTRL-W<Left>.) (See page 85.)
[count]CTRL-W CTRL-I
Split the window and search for the [count]
occurrence of the word under the cursor. Start the
search at the beginning of the file. (Same as: CTRL-Wi.
See page 340.)
[count]CTRL-W CTRL-J
Move down a window. If a count is specified, move to
window number count. (Same as: CTRL-W<Down>,
CTRL-Wj.) (See page 84, 335, 464.)
[count]CTRL-W CTRL-K
Move count windows up. (Same as: CTRL-W<Up>,
CTRL-Wk.) (See page 84, 335, 464.)
[count]CTRL-W CTRL-L Go right [count] windows. (Same as: CTRL-W l,
CTRL-W<Right>. See page 85.)
CTRL-W CTRL-N Split the window like :split. The window is started on
a blank file. (Same as: CTRL-Wn. See page 86.)
CTRL-W CTRL-O Make the current window the only one. (Same as:
CTRL-Wo, :on, :only.) (See page 339.)
CTRL-W CTRL-P Move to the previous window. (Same as: CTRL-Wp.)
(See pages 235, 236, 335.)
CTRL-W CTRL-Q Close a window. If this is the last window, exit Vim. The
command fails if this is the last window for a modified
396.)
]M Search forward for the end of a method. (See page
396.)
["{register}] ]p Put the {register} in the buffer like the P command,
but adjust the text to fit the indent of the current line.
(Same as: ]<MiddleMouse>.) (See page 367.)
["{register}] ]P Put the {register} in the buffer like the P command,
but adjust the text to fit the indent of the current line.
(Same as ]<MiddleMouse>, [p, [P. See page 367.)
[count] ]s Search for the next misspelled word starting at the
current location. A [count] cause the command to
repeat [count] times. (See page 185.)
[count] ]S Search for the next misspelled word starting at the
current location, but do not stop at bad words or
uncommon words. A [count] cause the command to
repeat [count] times. (See page 185.)
]z Move to the end of the current open fold. (See page
390.)
[count]_ Move to the first printing character of the [count]-1
line below the cursor. (See page 265.)
`{mark} Go to the mark named mark. Cursor is positioned
exactly on the mark. (See page 72.)
`{mark} (backtick) Go to the line containing mark. Position the cursor at
the first non-blank character on the line. (See page 72)
[count] { Move backward [count] paragraphs. (See page 189.)
[count]| Move to the column [count] on the current line. (See
page 330.)
[count] } Move forward [count] paragraphs. (See page 177,
189, 234.)
~{motion} Change the case of the indicated characters. (This
version of the command depends on the 'tildeop'
option being on. (The default is off.) (See page 55.)
[count]~ Change the case of count characters. (This version of
the command depends on the 'tildeop' option being
off (the default). (See pages 268.)
[count]£ Search for the word under the cursor, backward.
(Same as #, <S-RightMouse>.) (See page 295.)
0 (Zero) Move to the first character on the line. (See pages 44,
263, 329.)
[count]a{text}<Esc>
Insert text starting after the character under the cursor.
If a [count] is specified, the text is inserted count
times. (See page 36, 41, 56.)
[count]A{text}<Esc>
Append the text on to the end of the line. (See page
277.)
[count]b Move backward count words. (Same as: <S-Left>.)
(See page 42.)
[count]B Move count WORDS backward. (Same as: <C-Left>.
See page 263.)
c{motion} Delete from the cursor to the location specified by the
{motion} then enter insert mode. (See pages 51, 103,
233.)
[count]C Delete from the cursor to the end of the current line
and [count]-1 more lines, and then enter insert mode.
(See page 52, 103, 275, 276.)
[count]cc Delete [count] entire lines (default = 1) and enter
insert mode. (See page 52.)
["{register}] d{motion}
Delete from the cursor location to where {motion}
goes. (See pages 49, 50, 53, 69, 70, 73, 234, 275.)
do Copy the current diff from the other window to this
one. (See page 122.)
dp Copy the current diff from the this window to the other
one. (See page 122.)
[count]D Delete from the cursor to the end of the line. If a
[count] is specified, delete an additional [count]-1
lines. (See pages 50, 275.)
["{register}][count]dd
Delete [count] lines. (See pages 36, 49, 313.)
[count]e Move [count] words forward, stop at the end of the
word. (See page 260.)
[count]E Move [count] WORDS forward to the end of the
WORD. (See page 263.)
[count]f{char} Search forward for character {char} on the current
line. Stop on the character. (See pages 44, 53, 264,
282.)
[count]F{char} Search backward for character {char} on the current
line. Stop on the character. (See page 44.)
[count]G Go to the line [count]. If no line is specified, go to the
last line in the file. (Same as: <C-End>. See pages 46,
226, 233, 266, 557.)
[count]g<Down> Move down one line on the screen. (Same as: gj.) (See
page 330.)
g<End> Move to the rightmost character on the screen. (Same
as: g$.) (See page 329.)
Motion Commands
[count]a" Select matching "" pair, including the "". (See page 354.)
[count]a' Select matching '' pair, including the ''. (See page 354.)
[count]a( From with text enclosed in (), select the text up to and
[count]a) including the (). (See page 354.)
[count]a<] Select matching <> pair, include the <>. (See page 354.)
[count]a>
[count]a[ Select matching [] pair, include the []. (See page 354.)
[count]a]
[count]a` Select matching `` pair, including the ``. (See page 354.)
[count]a{ Select matching {} pair, including the {}. (See page 354.)
[count]a}
[count]ab From with text enclosed in (), select the text up to and
including the (). (See page 354.)
[count]aB Select matching {} pair, including the {}.
[count]ap Select a paragraph and the following space. (See page 354.)
[count]as Select a sentence (and spaces after it). (See page 354.)
[count]aw Select a word and the space after it. (Word is defined by the
'iskeyword' option . (See page 353, 354.)
[count]aW Select a word and the space after it. (Word is defined to be
any series of printable characters.) (See page 354.)
[count]at Select the enclosing XML tag block ( <foo> ... </foo>)
including the tags. (See 354.)
[count]i" Select matching "" pair, not including the "". (See page
354.)
[count]i' Select matching '' pair, not including the ''. (See page 354.)
[count]i( From with text enclosed in (), select the text up to but not
[count]i) including the (). (See page 354.)
[count]i< Select matching <> pair, excluding the <>. (See page 354.)
[count]i>
[count]i[ Select matching [] pair, excluding the []. (See page 354.)
[count]i]
[count]i` Select matching `` pair, not including the ``. (See page
354.)
[count]i{ Select matching {} pair, excluding the {}. (See page 123,
[count]i} 130.)
[count]ib From with text enclosed in (), select the text up to but not
including the (). (See page 354.)
[count]iB Select matching {} pair, excluding the {}. (See page 354.)
[count]ip Select a paragraph only. (See page 177, 354.)
[count]is Select the sentence only. Do no select whitespace after a
sentence. (See page 354.)
[count]it Select the enclosing XML tag block ( <foo> ... </foo>)
excluding the tags. (See page 354.)
[count]iw Select inner word (the word only). (Word is defined by the
'iskeyword' option.) (See page Error: Reference source not
found353, 354.)
[count]iW Select inner word (the word only). (Word is defined to be any
series of printable characters.) (See page 354.)
:@: :[line] @:
Repeat the last command-mode command.
(See page 444.)
:@@ :[line] @@
Repeat the last :@{register} command.
(See page 444.)
:~ :[range]~ {flags} {count}
Repeat the last substitution, but the last search string as the {from}
pattern instead of the {from} from the last substitution.
(See page 437.)
:a :[line] a
Insert text after the specified line. (Default = current.)
(Same as: :append.) (See page 432.)
:ab :ab
List all abbreviations. (Same as: :abbreviate.)
(See pages 149, 419.)
:ab :ab {lhs} {rhs}
Define an abbreviation. When {lhs} is entered, put {rhs} in the
text. (Same as :abbreviate.)
(See page 148, 157, 241, 418.)
:abbreviate :abbreviate
List all abbreviations. (Same as: :ab.)
( See pages 149, 419.)
:abbreviate :abbreviate {lhs} {rhs}
Define an abbreviation. When {lhs} is entered, put {rhs} in the
text. (Same as :ab.) (See pages 148, 157, 241, 418.)
:abc :abc
:abclear :abclear
Remove all abbreviations.
(See page 418.)
:abo :abo {cmd}
:aboveleft :aboveleft {cmd}
Execute the Vim command {cmd}. If the command splits a window,
the window is opened above the current one or to its left (overriding
any any split options that are currently set.) (Same as :lefta,
:leftabove)
(See page 346.)
:al :[count] al
:all :[count] all
Open a window for all the files being edited. When a [count] is
specified, open up to [count] windows. (Note that the [count] can
be specified after the command, such as ":all [count].) (Same as
:sal, :sall.)
(See page 339.)
:am :[priority] am {menu-item} {command-string}
:amenu :{priority amenu {menu-item} {command-string}
Define a menu item that's that is valid for all modes .
(See page 468.)
The following characters are automatically inserted for some modes:
Mode Prefix Character Meaning
Inserted
Normal (Nothing) ?N/A
Visual <Esc> Exit visual mode
Insert CTRL-O Execute one normal command.
Command Line CTRL-C Exit command-line mode
Operator pending mode <ESC> End operator-Pending
:an :{priority} an {menu-item} {command-string}
:anoremenu :{priority} anoremenu {menu-item} {command-string}
Perform a :amenu command in which the {command-string} is not
remapped.
(See page 473.)
:append :[line] append
Insert text after the specified line. (Default = current). (Same as:
:a.)
( See page 432.)
:ar :ar
List the files being edited. The name of the current file is enclosed in
square brackets ([]). (Same as :args.)
:br :br[!]
Go to the first buffer in the list. (Same as: :brewind, :bf,
:bfirst.)
(See page 93.)
:brea :brea
:break :break
Break out of a loop.
(See page 496.)
:breaka file :breaka file [line] {file-name}
:breakadd file :breakadd file [line] {file-name}
Set a breakpoint that will be triggered when the specified file is read
by a :source command. If [line] is specified, stop on that line,
otherwise stop on the first line.
(See page 505.)
:breaka func :breaka func [line} {function-name}
:breakadd func :breakadd func [line} {function-name}
Create a breakpoint in the specified {function-name}. If no [line]
is specified, the breakpoint will be set at the start of the function,
otherwise it is set at the specified line.
(See page 503, 504.)
:breaka here :breaka here
:breakadd here :breakadd here
Add a breakpoint at the current file and line.
(See page 505.)
:breakd :breaka {number}
:breakdel :breakadd {number}
Delete a breakpoint specified by number. The special number * (star)
deletes all breakpoints.
(See page 505.)
:breakd file :breakd file [line] {file-name}
:breakdel file :breakdel file [line] {file-name}
Delete a file type breakpoint.
(See page 505.)
:change, :t.)
(See page 431, 445.)
:ca :ca {lhs} {rhs}
:cabbrrev :cabbrrev {lhs} {rhs}
Define an abbreviation for command-mode only.
(See page 419.)
:cabc :cabc
:cabclear :cabclear
Remove all for command mode.
(See page 419.)
:cad :cad [buffer-number]
:caddbuffer :caddbuffer [buffer-number]
Adds the contents of the buffer to the quick fix list. If not buffer is
specified the current one is used.
(See page 404, 405.)
:cadde :cadde[!] {expression}
:caddexpr :caddexpr[!] {expression}
Add the results of {expression} to the quick fix buffer.
(See page 404, 405.)
:caddf :caddf[!] {file}
:caddfile :caddfile[!] {file}
Add the contents of {file} to the quick fix buffer.
(See page 403, 404, 405.)
:cal :[range] cal {name}({argument list})
:call :[range] call {name}({argument list})
Call a function.
(See page 500.)
:cat :cat /{pattern}/
:catch :catch /{pattern}/
Catch an exception. If no /{pattern}/ is specified, all exceptions
will be caught.
(See page 497.)
:command :command
List the user-defined commands. (Same as: :com.)
(See page 509.)
:command :command {definition}
Define a user-defined command. (Same as: :com.)
(See page 508.)
:con :con {command}
Start a loop over. (Same as: :continue.)
(See page 496.)
:conf :conf {command}
:confirm :confirm {command}
Execute the {command}. If this command would result in the loss of
data, display a dialog box to confirm the command.
(See page 478.)
:continue :continue
Start a loop over. (Same as: :con.)
(See page 496.)
:cope :cope [height]
:copen :copen [height]
Open a window for the quick fix list. If [height] is specified, use it
as the window height.
(See page 146, 406.)
:copy :[range] copy {address}
Copy the range of lines below {address}. (Same as: :co, :t.)
(See page 431.)
:cp :[count] cp[!]
Go to the [count] previous error. (Same as: :cpevious, :cN,
:cNext.)
(See pages 246, 405.)
:cpf :[count]cpf[!]
:cpfile :[count]cpfile[!]
Go to the last error in the previous file. If a [count] is specified, go
back that many files.
(See page 405.)
:cprevious :
[count] cprevious[!]
Go to the [count] previous error. (Same as: :cp, :cN, :cNext.)
(See pages 246 405.)
:cq :cq
:cquit :cquit
Exit Vim with an error code. (This is useful in integrating Vim into an
IDE.)
(See page 144.)
:cr :cr[!] [number]
:crewind :crewind[!] [number]
Go the first error in the list. If a number is specified, display that
error. (Same as :cfir, :cfirst.)
(See page 142, 145, 405.)
:cs :cs {arguments}
:cscope :cscope {argument}
Handle various activities associated with the CScope program.
(See page 247.)
:cst :cst {procedure}
:cstag :cstag {procedure}
Go to the tag in the CScope database named {procedure}.
(See page 247.)
:cu :cu {lhs}
Remove a command-mode mapping. (Same as: :cunmap.)
(See page 425.)
:cuna :cuna {lhs}
:cunabbreviate :cunabbreviate {lhs}
Remove the command-line mode abbreviation.
(See page 419, 425.)
:cunmap :cunmap {lhs}
Remove a command-mode mapping. (Same as: :cu.)
(See page 425.)
:cunm :cunm
:cunmenu :cunmenu {menu-item}
Remove the command-mode menu item named {menu-item}.The
wildcard * will match all menu items.
(See page 473.)
:cw :cw [height]
:cwindow :cwindow [height]
If there are errors, open a quick fix window of the specified height. If
there are no errors, close the quick fix window.
(See page 406.)
:d :[range] d {register} [count]
Delete text. (Same as: :delete.)
(See page 427.)
:deb :deb {command}
:debug :debug {command}
Execute {command} in debug mode.
(See page 503.)
:debugg :[0]debugg
:debuggreedy :[0]debuggreedy
The :debugg command tells Vim to read debug commands from the
standard command stream instead of forcing all debug input to come
from the user. This is useful for starting a debug session with a
script. The :0debugg command cancels this feature and all future
debug input must come from the user.
(See page 506.)
:delc :delc {command}
:delcommand :delcommand {command}
Delete a user-defined command.
(See page 509.)
:delete :[range] delete {register} [count]
Delete text. (Same as: :d.)
(See page 427.)
:delf :delf {name}
:delfunction :delfunction {name}
Delete the function named {name}.
history.
(See page 494, 498.)
:echoh :echoh {name}
:echohl :echohl {name}
Change the color of future echoes to be in the color of highlight
group {name}.
(See page 494.)
:echom :echom {arguments}
:echomsg :echomsg {arguments}
Print the arguments as a message and save it in the message history.
(See page 495.)
:echon :echon {arguments}
Echo the arguments without a newline.
(See page 494.)
:edit :edit [+cmd] [file]
Close the current file and start editing the named file. If no file is
specified, re-edit the current file. If +cmd is specified, execute it as
the first editing command. (Same as: :e.)
(See page 77.)
:el :el
:else :else
Reverse the condition of an :if.
(See page 495.)
:elsei :elsei
:elseif :elseif
A combination of :else and :if.
(See page 495.)
:em :em {menu-item}
:emenu :emenu {menu-item}
Execute the given {menu-item} as if the user had selected it.
(See page 473.)
:en :en
End an :if statement. (Same as: :endif.)
(See page 495.)
:endf :endf
End a function. (Same as :endfunction.)
(See page 499.)
:endfo :endfo
:endfor :endfor
End a :for loop.
(See page 496.)
:endfunction :endfunction
End a function. (Same as :endf.)
(See page 499.)
:endif :endif
End an :if statement. (Same as: :en.)
(See page 495.)
:endt :endt
:endtry :endtry
End a :try block.
(See page 498.)
:endw :endw
:endwhile :endwhile
End a :while loop.
(See page 496.)
:ene :ene[!]
:enew :enew[!]
Start editing a new buffer.
(See page 77.)
:ex :ex[!] [+command] [filename]
Enter ex mode. If a filename is specified, edit that file; otherwise,
use the current file. The +command argument is a single command
that will be executed before any editing begins. If the override
option (!) is specified, switching files will discard any changes that
have been made.
(See page Error: Reference source not found.)
:ex :[range] ex[!] [file]
If the buffer has been modified, write the file and exit. If a range is
:function :function
List all functions. (Same as: :fu.)
(See page 501.)
:function :function {name}
List the contents of function {name}.
(See page 501.)
:function :function {function definition}
Start a function definition.
(See page 499.)
:g : [range] g /{pattern}/ {command}
Perform {command} on all lines that have {pattern} in them in the
given range. (Same as: :global.)
(See page 438.)
:g! : [range] g! /{pattern}/ {command}
Perform {command} on all lines that do not have {pattern} in them in
the given range. (Same as :global!, :v, :vglobal.)
(See page 438.)
:global :[range] global /{pattern}/ {command}
Perform {command} on all lines that have {pattern} in them in the
given range. (Same as: :g.)
(See page 438.)
:global! :[range] global! /{pattern}/ {command}
Perform {command} on all lines that do not have {pattern} in them in
the given range. (Same as :g!, :v, :vglobal.)
(See page 438.)
:go :go [count]
:goto :goto [count]
Go to [count] byte of the file. If no [count] is specified, go to the
first byte of the file.
(See page 226.)
:gr :gr {arguments}
:grep :grep {arguments}
Run the grep program with the given {arguments} and capture the
output so that the :cc, :cnext, and other commands will work on it.
(Like :make, but with grep rather than make.)
:hid :hid
:hide :hide
Hide the current buffer.
(See page 90, 94.)
:highlight
:highlight
List all highlight groups.
(See page 81, 494.)
:highlight
:highlight {options}
Customize the syntax coloration. (Same as: :hi.)
(See pages 412.)
:highlight link :highlight link {new-group} {old-group}
Highlight the {new-group} the same as {old-group} .
(See page 587.)
:his :his {code} [first] ,[last]
:history :history {code} [first] ,[last]
Print the last few commands or search strings (depending on the
code). The code parameter defaults to cmd for command-mode
command history. The first parameter defaults to the first entry in
the list and last defaults to the last.
(See page 447.)
:i :[line] i
Start inserting text before line. Insert ends with a line consisting of
just .. (Same as: :insert.)
(See page 432.)
:ia :ia {lhs} {rhs}
:iabbrev :iabbrev {lhs} {rhs}
Define an abbreviation for insert mode only.
(See page 419.)
:iabc :iabc
:iabclear :iabclear
Remove all for insert mode.
(See page 419.)
:imapc :imapc
:imapclear :imapclear
Clear all the insert-mode mappings.
(See page 425.)
:ime :[priority] ime {menu-item} {command-string}
:imenu :[priority] imenu {menu-item} {command-string}
Define a menu item that is available for insert mode only. The
priority determines its placement in a menu. Higher numbers come
first. The name of the menu item is {menu-item}, and when the
command is selected, the command {command-string} is executed.
(See page 468.)
:ino :ino {lhs} {rhs}
Same as :imap, but does not allow remapping of the {rhs}. (Same
as: :inoremap.)
(See page 425.)
:inorea :inorea {lhs} {rhs}
:inoreabbrev :inoreabbrev {lhs} {rhs}
Do a :noreabbrev that works in insert mode only.
(See page 419, 425.)
:inoremap :inoremap {lhs} {rhs}
Same as :imap, but does not allow remapping of the {rhs}. (Same
as: :ino.)
(See page 425.)
:inoreme :[priority] inoreme {menu-item} {command-string}
:inoremenu :[priority] inoremenu {menu-item} {command-string}
Like :imenu, except the {command-string} is not remapped.
(See page 473.)
:insert :[line] insert
Start inserting text before line. Insert ends with a line consisting of
just .. (Same as: :i.)
(See page 432.)
:int :int
:intro :intro
Display the introductory screen.
(See page 230.)
:lNf :[count]lNf[!]
:lNfile :[count]lNfile[!]
Go to the last location in the previous file. (Same as :lpf, :lpfile.)
(See page 405.)
:lnf :[count]lnf[!]
:lnfile :[count]lnfile[!]
Go to the first location in the next file in the location list.
(See page 405.)
:lnoremap :lnoremap {lhs} {rhs}
Create a language dependent mapping which is used for command
mode, insert mode, and language input which does not remap {rhs}.
(Same as :ln.)
(See page 425.)
:lo :lo [number]
Load a view which has been made with :mkview for the current file.
(Same as :loadview.)
(See page 350.)
:loadk :loadk {file}
:loadkeymap :loadkeymap {file}
Load a keymap file.
(See page 561.)
:loadview :loadview [number]
Load a view which has been made with :mkview for the current file.
(Same as :lo.)
(See page 350.)
:loc :loc {cmd}
:lockmarks
:lockmarks {cmd}
Execute {cmd} without changing the location of any marks.
(See page 311.)
:lockv :lockv[!] [depth] {name}
:lockvar :lockvar[!] [depth] {name}
Lock a variable so it can not be changed. The [depth] if specified is
a code which indicates how to lock dictionaries and list. A value of 1
locks the size of the dictionary or list, but lets you change values.
The 2 code indicates that the top level values can not be changed. A
level of 3 indicates that the array, the values in the array, and their
values can not be changed. The override option (!) tell Vim that
nothing can be changed.
(See page 491.)
:lol :lol [count]
:lolder :lolder [count]
Use an older version of the location list.
(See page 406.)
:lop :lop [height]
:lopen :lopen [height]
Open a window containing the location list.
(See page 406.)
:lp :[count]lp [!]
Go to the previous location in the location list. (Same as :lN,
:lNext, :lprevious.)
(See page 405.)
:lpf :[count]lpf[!]
:lpfile :[count]lpfile[!]
Go to the last location in the previous file. (Same as :lNf, :lNfile.)
(See page 405.)
:lprevious
:[count]lprevious [!]
Go to the previous location in the location list. (Same as :lN,
:lNext.)
(See page 405.)
:lr :lr[!] [number]
:lrewind :lrewind[!] [number]
Go to the first location in the location list. If a number is specified go
to that error number. (Same as :lfir, :lfirst.)
(See page 405.)
:ls :ls
List all the buffers. (Same as: :buffers, :files.)
(See page 90.)
:marks :marks
List all the marks.
(See page 73, 74.)
:marks :marks {chars}
List the marks specified by the character list: {chars}.
(See page 73, 74.)
:mat :[number]mat {group} /{pattern}/
:match :[number]match {group} /{pattern}/
Display text that matches {pattern} using the given highlight
{group}. Multiple matches may be displayed at the same time by
using the numbers 1-3.
(See page 81.)
:me :[priority][mode] me {menu-item} {command-string}
:menu :[priority][mode] menu {menu-item} {command-string}
Define a menu item. The priority determines its placement in a
menu. Higher numbers come first. The mode parameter defines
which Vim mode the item works in. The name of the menu item is
{menu-item}, and when the command is selected, the command
{command-string} is executed.
(See page 467.)
:menut :menut {english} {lang}
:menut :menut clear
:menutranslate :menutranslate {english} {lang}
:menutranslate :menutranslate clear
Create a menu translation from English to another language. If the
keyword clear is use, clear all translations.
(See page 474.)
:mes :mes
:messages :messages
View previous messages.
(See page 449, 495.)
:mk :mk[!] [file]
:mkexrc :mkexrc[!] [file]
Like :mkvimrc, except the [file] defaults to .exrc. This command
has been superseded by the :mkvimrc command. (Same as: :mk.)
:nmapc :nmapc
:nmapclear
:nmapclear
Clear all the normal mappings.
(See page 425.)
:nme :[priority]nme {menu-item} {command-string}
:nmenu :[priority]nmenu {menu-item} {command-string}
Define a menu item that is available for normal mode only. The
priority determines its placement in a menu. Higher numbers come
first. The name of the menu item is {menu-item}, and when the
command is selected, the command {command-string} is executed.
(See page 468.)
:nn :nn {lhs} {rhs}
:nnoremap :nnoremap {lhs} {rhs}
Same as :nmap, but does not allow remapping of the {rhs}.
(See page 425.)
:nnoreme :[priority] nnoreme {menu-item} {command-string}
:nnoremenu :[priority] nnoremenu {menu-item} {command-string}
Like :nmenu, but the {command-string} is not remapped.
(See page 473.)
:no :no {lhs} {rhs}
Same as :map, but does not allow remapping of the {rhs}. (Same as:
:noremap.)
(See pages 419, 421, 425.)
:noh :noh
:nohlsearch :nohlsearch
Turn off the search highlighting. (It will be turned on by the next
search. To turn it off permanently, use the :set nohisearch
command.)
(See page 326.)
:norea :norea {lhs} {rhs}
:noreabbrev :noreabbrev {lhs} {rhs}
Define an abbreviation, but do not allow remapping of the right side.
(See page 424, 425.)
:omap.)
(See page 421, 423, 425.)
:om :om {lhs}
List the operator-pending mapping of {lhs}. (Same as :omap.)
(See page 421, 425.)
:om :om {lhs} {rhs}
Define a keyboard mapping for operator-pending mode. (Same as
:omap.)
(See page 421, 425.)
:omap :omap
List all the operator-pending-mode mappings. (Same as: :om.)
(See page 421, 423, 425.)
:omap :omap {lhs}
List the operator-pending-mode mapping of {lhs}. (Same as :om.)
(See page 421, 425.)
:omap :omap {lhs} {rhs}
Define a keyboard mapping for operator-pending mode. (Same as
:om.)
(See page 421, 425.)
:omapc :omapc
:omapclear
:omapclear
Clear all the operator-pending-mode mappings.
(See page 425.)
:ome :[priority] ome {menu-item} {command-string}
:omenu :[priority] omenu {menu-item} {command-string}
Define a menu item that is available for operator-pending mode only.
The priority determines its placement in a menu. Higher numbers
come first. The name of the menu item is {menu-item}, and when
the command is selected, the command {command-string} is
executed.
(See page 468.)
:on :on[!]
:only :only[!]
Make the current window the only one. If ! is specified, modified files
whose windows are closed will have their contents discarded. (Same
as: :CTRL-W CTRL-O, CTRL-Wo.)
(See page 339.)
:ono :ono {lhs} {rhs}
:onoremap :onoremap {lhs} {rhs}
Same as :omap, but does not allow remapping of the {rhs}.
(See page 425.)
:onoreme :[priority] onoreme {menu-item} {command-string}
:onoremenu
:[priority] onoremenu {menu-item} {command-string}
Like :omenu, but the the {command-string} is not remapped.
(See page 473.)
:open :open
The one command that Vi has that Vim does not. (In Vi, this
command puts the editor into "open" mode, a mode that no sane
persons ever use if they can avoid it.) (Same as: :o. See page 231.)
:opt :opt
:options :options
Enter an option-browsing window that enables you to view and set all
the options. (Same as: :bro set, :browse set.)
(See page 479.)
:ou :ou {lhs}
:ounmap :ounmap {lhs}
Remove an operator-pending-mode mapping.
(See page 422, 425.)
:ounme :ounme {menu-item}
:ounmenu :ounmenu {menu-item}
Remove the command-mode menu item named {menu-item}.The
wildcard * will match all menu items.
(See page 473.)
:p :[range] p
:p :[range] P
Print the specified lines. (Same as: :print, :Print.)
(See page 160, 160, 161.)
:pc :pc[!]
:pclose :pclose[!]
Close the preview window. Discard any changes if the force (!)
option is present. (Same as: CTRL-W CTRL-Z, CTRL-Wz.)
(See page 393.)
:pe :pe {command}
Execute a single Perl command. Requires Vim be compiled with Perl
support (not on by default). (Same as :perl.)
(See page 249.)
:pe :pe << pattern
Execute Perl commands until a line containing only pattern is seen..
Requires Vim be compiled with Perl support (not on by default).
(Same as :perl.)
(See page 249.)
:ped :ped[!] [++opt] [+cmd] {file}
:pedit :pedit[!] [++opt] [+cmd] {file}
Edit a file in the preview window.
(See page 393.)
:perl :perl {command}
Execute a single Perl command. Requires Vim be compiled with Perl
support (not on by default). (Same as :pe.)
(See page 249.)
:perl :perl << pattern
Execute Perl commands until a line containing only pattern is seen..
Requires Vim be compiled with Perl support (not on by default).
(Same as :pe.)
(See page 249.)
:perld :[range] perld {command}
:perldo :[range] perldo {command}
Execute a Perl command on a range of lines. The Perl variable $_ is
set to each line in range.
(See page 249.)
:po :[count]po[!]
:pop :[count]pop[!]
Go back [count] tags. If the current buffer has been modified, this
:sbl :sbl[!]
:sblast :sblast[!]
Shorthand for :split and :blast.
(See page 93.)
:sbm :sbm [count]
:sbmodified :sbmodified [count]
Shorthand for :split and :bmodified.
(See page 94.)
:sbn :[count] sbn
Shorthand for :split followed by :[count] bnext. (Same as:
:sbnext.)
(See page 93.)
:sbN :[count] sbN
Shorthand for :split and :[count] bprevious. (Same as: :sbNext,
:sbp, :sbprevious.)
(See page 93.)
:sbnext :[count] sbnext
Shorthand for :split followed by :[count] bnext. (Same as: :sbn.)
(See page 93.)
:sbNext :[count] sbNext
:sbp :[count] sbp
:sbprevous
:[count] sbprevious
Shorthand for :split and :[count] bprevious. (Same as: :sbN.)
(See page 93.)
:sbr :sbr[!]
:sbrewind :sbrewind[!]
Shorthand for :split and :brewind. (Same as :sbf, :sbfirst.)
(See page 93.)
:sbuffer :sbuffer {number}
Shorthand for :split and :buffer {number}. (Same as: :sb.)
(See page 92, 93.)
:scr :scr
List the name of all the sourced scripts in the order they were
synchronization match.
(See page 594.)
:syntax sync region :syntax sync region {region-specification}
Define a match or region to be skipped during synchronization.
(See page 594.)
:t :[range] t {address}
Copy the range of lines below {address}. (Same as: :copy.)
(See page 431.)
:ta :[count] ta[!]
Go forward [count] tags. (Same as: :tag.)
(See pages 133, 134, 412.)
:ta :ta[!] /{pattern}
Search for all functions that match the regular expression defined by
{pattern} and jump to the first one.
(See page 135.)
:tab :[count]tab {cmd}
Execute a command that normally opens a new window, but open a
new tab instead. If [count] is specified, then open the new tab after
the [count] tab in the list. Otherwise open a new tab to the right.
(See page 96.)
:tabc :tabc[!]
:tabclose :tabclose[!]
Close the current tab. If there are unsaved changes, this will fail
with an error, unless the override option (!) is present.
(See page 96.)
:tabd :tabd {cmd}
:tabdo :tabdo {cmd}
Execute the {cmd} for each tab. (See page 346.)
:tabe :tabe
:tabedit :tabedit
Create an empty buffer in a new tab. (Same as :tabnew.)
(See page 96.)
:tabnew :tabedit
Create an empty buffer in a new tab. (Same as :tabe, :tabedit.)
:tn :[count] tn
Go to the next tag. (Same as: :tnext.)
(See page 136, 393.)
:tN :[count] tN
Go to the previous tag. (Same as: :tNext, :tp, :tprevious.)
(See page 136, 393.)
:tnext :[count] tnext
Go to the next tag. (Same as: :tn.)
(See page 136, 393.)
:tNext :[count] tNext
Go to the next tag. (Same as: :tN, :tp, :tprevious.)
(See page 136, 393.)
:to :to {cmd}
:topleft :topleft {cmd}
Execute a command which which opens a window and make that
window to the top or left of the current window, overriding all other
windowing options.
(See page 346.)
:tp :[count] tp
:tprevious
:[count] tprevious
Go to the previous tag.
(See page 136, 393.)
:tr :[count] tr
:trewind :[count] trewind
Go to the first tag. (Same as :tf, :tfirst.)
(See page 136, 393.)
:try :try
Begin a try / catch block of commands. (For scripting.)
(See page 497.)
:ts :ts[!] [ident]
:tselect :tselect[!] [ident]
List all the tags that match [ident]. If [ident] is not present, use
the results of the last :tag command. After listing the tags, give the
:ve :ve
List version and configuration information, including the list of
.vimrc files read in at startup. (Same as :version.)
(See page 153.)
:verb :[count]verb {cmd}
:verbose :[count]verbose {cmd}
Execute {cmd} with the 'verbose' option set to [count].
(See page 561.)
:vert :vert {cmd}
:vertical :vertical {cmd}
Execute {cmd}. If it opens a new window, perform a vertical split.
(See page 88, 92.)
:version :version
List version and configuration information, including the list of .vimrc
files read in at startup. (Same as :ve.)
(See page 153.)
:vglobal :[range] vglobal /{pattern}/ {command}
Perform {command} on all lines that do not have {pattern} in them in
the given range. (Same as :v, :global!, :g!.)
(See page 438.)
:vi :vi [+cmd] {file}
Close the current file and start editing the named file. If [+cmd] is
specified, execute it as the first editing command. (Same as:
:visual.)
(See page 159, 317, 241, 398.)
:vie :vie [+cmd] {file}
:view :view [+cmd] {file}
Like :vi, but open the file read-only.
(See page 77.)
:vim :vim[!] /{pattern}/[g][j] {file-list}
:vimgrep :vimgrep[!] /{pattern}/[g][j] {file-list}
Search the {file-list} for the given {pattern} and put the
results in the quick fix list. Go to the location of the first occurrence.
The g option causes lines which match {pattern} more than once to
be added more than once. The j flag tells Vim to update the list but
do not do the jump. The override (!) option will cause Vim to
abandon the current buffer even if there are unsaved modifications in
it.
(See page 246, 403, 406.)
:vimgrepa :vimgrepa[!] /{pattern}/[g][j] {file-list}
:vimgrepadd :vimgrepadd[!] /{pattern}/[g][j] {file-list}
Like :vimgrep, but add to the quick fix list instead of replacing it.
(See page 406.)
:visual :visual [+cmd] {file}
Close the current file and start editing the named file. If [+cmd] is
specified, execute it as the first editing command. (Same as: :vi.)
(See page 159, 317.)
:viu :viu
:viusage :viusage
Show help on normal mode commands. This is for compatibility with
Nvi. The :help command is much more useful for getting help.
(See page 228.)
:vm :vm
List all the mappings for visual-mode maps. (Same as: :vmap.)
(See pages 421, 423, 425.)
:vm :vm {lhs}
List the visual mode mapping of {lhs}. (Same as: :vmap.)
(See pages 421, 425.)
:vm :vm {lhs} {rhs}
Define a keyboard mapping for visual mode. (Same as: :vmap.)
(See pages 420, 425.)
:vmap :vmap
List all the visual-mode mappings. (Same as: :vm.)
(See pages 421, 423, 425.)
:vmap :vmap {lhs}
List the visual-mode mapping of {lhs}. (Same as: :vm.)
(See page 421, 425.)
:vmap :vmap {lhs} {rhs}
Define a keyboard mapping for visual mode. (Same as: :vm.)
:xmapc :xmapc
:xmapclear :xmapclear
Clear all the visual-mode only mappings.
(See page 425.)
:xme :[priority] xme {menu-item} {command-string}
:xmenu :[priority] xmenu {menu-item} {command-string}
Define a menu item that is available for visual mode only. The
priority determines its placement in a menu. Higher numbers come
first. The name of the menu item is {menu-item}, and when the
command is selected, the command {command-string} is executed.
(See page 468.)
:xn :xn {lhs} {rhs}
:xnoremap :xnoremap {lhs} {rhs}
Same as :xmap, but does not allow remapping of the {rhs}.
(See page 468.)
:xnoreme :[priority] xnoreme {menu-item} {command-string}
:xnoremenu :[priority] xnoremenu {menu-item} {command-string}
Like :xmenu, but the {command-string} is not remapped.
(See page 468.)
:y :[range] y {register}
:yank :[range] yank {register}
Yank the range (default = current line) into the register (default =
the unnamed register).
(See page 445.)
:z :[line] z{code} [count]
List the given line (default = current) and a few lines after it. The
code controls what section of the text is listed. The [count] defines
what "a few" is.
(See page 434.)
NVO N V O IC I C
:noreamp :nnremap :vnoremap :onoremap :noremap! :inoremap :cnoremap
:unm :nun :vu :ou :unm! :iu :cu
:unmap :numap :vumap :oumap :unmap! :iunmap :cunmap
:mapc :nmapc :vmapc :omapc :mapc! :imapc :cmapc
:mapclear :nmapclear :vmapclear :omapclear :mapclear! :imapclear :cmapclear
Modes
N Normal
V Visual
O Operator pending
I Insert
C Command
-A-
aleph al Global Number Default: 128 for MS-DOS
224 otherwise
ASCII code for the first letter of the Hebrew alphabet. (See page 256.)
allowrevins ari Global Boolean Default: off
All CTRL-_ to reverse the input direction. (See page 252.)
altkeymap akm Global Boolean Default: off
Used for Farsi and Hebrew input. (See page 255, 256.)
ambiwidth ambw Global String Default: single
Used for foreign languages. (See page 253.)
antialias anti Global Boolean Default: off
If enabled some fonts will be antialised making them easier to read. (See page
483.)
autochdir acd Global Boolean Default: off
If set, change the current directory as you change files. (See page 442.)
arabic arab Local Boolean Default: off
Used for the Arabic language. (See page 254.)
arabicshape arshape Global Boolean Default: on
Used for the Arabic language. (See page 254.)
autoindent ai Local Boolean Default: off
Turn on automatic indentation. (See page 116, 118, 118, 157, 364, 552)
autoread ar Global Boolean Default off
If a file is changed outside Vim, just read it in instead of asking you about it.
(See page 146.)
autowrite aw Global Boolean Default: off
Instead of warning you when your command is going to discard change, write
out the file automatically. (See 79, 157.)
autowriteall awa Global Boolean Default: off
Turns on automatic writing for a number of commands. (See page 79.)
-B-
background bg Global String Default: dark or light depending on
terminal type.
Tells Vim if the default backup ground color is light or dark. (See page 112,
482.)
backspace bs Global String Default: empty
Defines how backup space types commands work in insert mode. (See page
151.)
backup bk Global Boolean Default: off
If set, create backup files. (See page 217.)
backupcopy bkc Global String Vi Default: Unix: yes
Otherwise: auto
Defines the method to be used to make a backup copy of a file. (See page 218.)
backupdir bdir Global String Default: System dependent
A list of directories in which to place the backup. The first writable directory on
the list gets the file. (See page 217.)
backupext bex Global String Default: ~
VMS: _
String thats added to a file name to make it a backup file name. (See page 217.)
backupskip bsk Global String Default: /tmp/*,$TMPDIR/*,$TMP/*,
$TEMP/*
A set of file patterns that when matched will cause Vim to skip backup
generation. (See page 218.)
balloondelay bdlay Global Number Default: 600
Delay in milliseconds before a balloon may pop up. (See page 251.)
ballooneval beval Global Boolean Default: off
Enables the balloon text. (See page 251.)
balloonexpr bexpr Global String Default: empty
Set the function to be called when deciding what balloon text to display. (See
page 251.)
binary bin Local Boolean Default: off
Indicates that the file is binary. (See page 189, 257.)
bioskey biosk Global Boolean Default: on
When set, keyboard input is obtained from the BIOS. (See page 539.)
bomb Local Boolean Default: off
If set a byte order mark (BOM) is placed at the beginning of the file. (See page
253.)
breakat brk Global String Default: ^I!@*-+;:,./?
Defines characters which can be used for breaking long lines. (See page 332.)
browsedir bsdir Global String Default: last
Controls the initial directory for browse mode. (See page 477.)
bufhidden bh Local String Default: empty
If set this buffer becomes hidden. (Don't use unless you know what you are
doing.) (See page 94.)
buflisted bl Local Boolean Default: on
If set the buffer is show in the list of buffers. If off, it is not shown. (See page
94.)
buftype bt Local String Default: empty
Type of buffer. (See page 94.)
-C-
casemap cmp Global String Default: internal,keepascii
Defines the character set for the case changing operators. (See page 253.)
cdpath cd Global String Default: equivalent to $CDPATH or ,,
A set of directories that will be searched when changing directory. (See page
442.)
cedit Global String Vi Default: empty
Vim Default: CTRL-F
The key that opens the command line window. (See page 427.)
charconvert ccv Global String Default: empty
Used to convert characters when different encodings are used. (See page 253.)
cindent cin Local Boolean Default: off
If set use C style indenting. (See page 116, 156, 365, 552.)
cinkeys cink Local String Default: 0{,0},0
A set of keys that trigger cindent mode. (See page 376, 377.)
cinoptions cino Local String Default: empty
Defines how cindent mode works. (See page 376, 377,379.)
cinwords cinw Local String Default: if,else,while,do,for,
switch
Words that cause the next line to be indented in 'cindent' mode. (See page
118. 376, 383.)
-D-
debug Global String Default: empty
Used for debugging some macros. (See page 561.)
define def Global String Default: ^\s*#\s*define
Pattern used to locate macro definitions. (See page 402.)
delcombine deco Global Boolean Default: off
Defines how Unicode characters are handled for foreign languages. (See page
253.)
dictionary dict Global String Default: empty
List of dictionary files used for word completion. (See page 194, 223.)
diff Local Boolean Default: off
Add this window to the set being used for a diff. (See page 385.)
diffexpr dex Global String Default: empty
Expression that defines the command to be used for a diff. (See page 385.)
-E-
eadirection ead Global String Default: both
When 'equalalways' is set defines if vertical windows, horizontal windows, or
both are to be affected. (See page 345.)
edcompatible ed Global Boolean Default: off
Turning this option on make the e and g flags of :substutute toggle. (For Vi
compatibility.) Please do not turn this on. (See page 559.)
encoding enc Global String Default: $LANG or latin1
Sets the character encoding. (See page 562.)
endofline eol Local Boolean Default: on
If not set, Vim will not automatically add an EOL to a file that does not have one.
(See page 188.)
equalalways ea Global Boolean Default: on
When set try and keep windows the same size. (See page 344.)
equalprg ep Global String Default: empty
Program to use for the = command. If not set, Vim's internal indention program
will be used. (See page 373.)
errorbells eb Global Boolean Default: off
If set, error which would ring the bell instead flash the screen. (See page 544.)
errorfile ef Global String Amiga Default: [Link]
Others: [Link]
Name of the error file for quickfix mode. (See page 145.)
errorformat efm Global String Default: Complex
Defines the format of the error messages for quickfix mode. (See page 407.)
esckeys ek Global Boolean Vim Default: on
Vi Default: off
If set, Vim will recognize function keys even if they send an escape sequence.
(See page 540.)
- F-
fileencoding fenc Local String Default: empty
The current file encoding. (See page 255, 256, 257.)
fileencodings fencs Global String Default: System dependent
A list of file encodings to try when reading a file. (See page 206.)
fileformat ff Global String Default: File dependent
Current file format. (See page 188.)
fileformats ffs Global String Default: System dependent
A list of file formats which Vim will try and detect when reading a new file. (See
page 188.)
filetype ft Local String Default: – File dependent.
The type of file. (See page 113, 205)
fillchars fcs Global String Default: vert:|,fold:-
Define the fill characters for the status line and other informational lines. (See
page 547.)
fkmap fk Global Boolean Default: off
Used for Faris editing. (See page 255.)
foldclose fcl Global String Default: empty
When set to all, folds are closed automatically when the cursor moves off of
them. (See page 391.)
foldcolumn fdc Local Number Default: 0
The width of the column showing the number of lines folded. (See page 391.)
foldenable fen Local Boolean Default: on
When off, show all folds. When on, do folding normally. (See page 390.)
foldexpr fde Local String Default: 0
The expression to be used when 'foldmethod' is expr. (See page392, 561.)
foldignore fdi Local String Default: #
Lines starting with this character will be ignored when doing indent type
folding. (See page 125.)
foldlevel fdl Local Number Default: 0.
Defines the level of folding for this buffer. (See page 124.)
foldlevelstart fdls Global Number Default: -1
Initial 'foldlevel' to be used when editing a new file. (See page 125.)
foldmarker fmr Local String Default: {{{,}}}
If we are using the marker method of folding, this option defines the markers.
(See page 387.)
foldmethod fdm Local String Default: manual.
Defines how folding is to be done. (See page 123, 387, 391, 392.)
foldminlines fml Local Number Default: 1
The minimum number of lines for which to display a fold. (See page 391.)
foldnestmax fdn Local Number Default: 20
The maximum nesting level of folds. (See page 391.)
foldopen fdo Global String Default: block,hor,mark,percent,
quickfix,search,tag,undo
The commands for which folds will be opened. (See page 391.)
foldtext fdt Local String Default: foldtext()
Configures how text folds are displayed. (See page 390.)
formatoptions fo Local String Vim Default: tcq
Vi Default: vt
A series of options that define how automatic formatting is to be done. (See
page 156, 180, 180, 182, 183, 375, 552.)
formatlistpat flp Local String Default: ^\s*\d\+[\]:.)}\t ]\s*
A regular expression that is used to detect lists so that the -n flag may be
passed to the format programming. (See page 183.)
formatprg fp Global String Default: empty
Name of the command used to format lines for gq if 'formatexpr' is empty.
(See page 183.)
formatexpr fex Local String Default: empty
Expression used to format lines for gq. If this is not set, the lines are run
through 'formatprg'. (See page 183, 561.)
fsync fs Global Boolean Default: on
When enabled, Vim tries to make sure that data is written to disk using the
fsync() system call. (See page 183.)
-G-
gdefault gd Global Boolean Default: off
When set all :substitute commands will be global. (See page 437.)
grepformat gfm Global String Default: %f:%l%m,%f %l%m
Format used to recognize what comes out of the :grep command. (The :grep
command is obsolete. Use :vimgrep instead.) (See page 411.)
grepprg gp Global String Default: System dependent
Program to use for the :grep command. (The :grep command is obsolete. Use
:vimgrep instead.) (See page 411.)
guicursor gcr Global String Default: System dependent
Define how the cursor looks in GUI mode. (See page 484.)
guifont gfn Global String Default: empty
Font to use for the GUI. (See page 482.)
guifontset gfs Global String Default: empty
Fonts to be used for the GUI. The first is for English, the second for special
characters. (See page 252.)
guifontwide gfw Global String Default: empty
Font to use for double wide characters. (See page 252.)
guiheadroom ghr Global Number Default: 50
The number of pixels that you expect the windowing system to use for
decorations. (So when we go full screen we don't push any decorations off the
display.) (See page 486.)
guioptions go Global String Default: System dependent
A set of options which controls the behavior and appearance of the GUI. (See
page 327, 456, 482.)
guipty Global Boolean Default: on
In GUI mode, try and open a pty (Psuedo Teletype) when executing an external
process. (See page 486.)
guitablabel gtl Global String Default: empty
Text to appear in the tab label for the GUI. (See page 347.)
guitabtooltip gtt Global String Default: empty
Tooltip for the tab line of a GUI. (See page 347.)
-H-
helpfile hf Global String Default: System dependent
Name of the top level help file. (See page 560.)
helpheight hh Global Number Default: 20
Minimum height of the help window. (Seepage 549.)
helplang hlg Global String Default: locale dependent
Comma separated list of languages to search for help text. (See page 40.)
hidden hid Global Boolean Default: off
Make buffers that become abandon hidden instead of making them just go away.
(See page 94.)
highlight hl Global String Default: Complex string
Defines the highlighting for various system items. (See page 550.)
hlsearch hls Global Boolean Default: off
If set, search results are highlighted. (See page 61, 157, 290, 298, 326)
history hi Global Number Vim Default: 20
Vi Default: 0
The number of entries remembered in the command mode (:) and search (/)
histories. (See page 325, 449.)
hkmap hk Global Boolean Default: off
Used for Hebrew input. (See page 256.)
hkmapp hkp Global Boolean Default: off
Option for configuring the Hebrew keyboard. (See page 256.)
-I-
icon Global Boolean Default: off, on when title can be restored
When enabled, the name in the iconified Vim window will be set to the value of
'iconstring'. If that option is not set, the name of the current file will be
used. (See page 463.)
iconstring Global String Default: empty
The string to be used when the editing window is iconified. You have to have
the 'icon' option enabled for this to work. (See page 463.)
ignorecase ic Global Boolean Default: off
Determines if searches and completion commands are case sensitive or
insensitive. (See page 193, 291, 491, 525.)
imactivatekey imak Global String Default: empty
Specifies which keys are used by the Input Method when using the X Windows
system. (See page 254.)
imcmdline imc Global Boolean Default: off
If set automatically turns the input method (for foreign languages) when enter
commands. (Except for search patterns which is controlled by the 'imsearch'
option.) (See page 254.)
imdisable imd Global Boolean Default: System dependent
When set, the input method is disabled. (See page 254.)
iminsert imi Local Number Default: System dependent
Specifies how foreign language text is to be input. (See page 254.)
imsearch ims Local Number Default: System Dependent
Specifies how foreign language text is to be input. (See page 254.)
include inc Global String Default: ^\s*#\s*include
Pattern that matches a #include line. (See page 402.)
includeexpr inex Local String Default: empty
Expression that changes a included file name from text to file name. For C this
is a noop, but for Java you have to change each “.” to “/”. (See page 403, 399.)
incsearch is Global Boolean Default: off
Turn on incremental searching. (See page 62, 157.)
indentexpr inde Local String Default: Language specific.
Expression which controls how indentation is done. (See page 561.)
indentkeys indk Local String Default: 0{,0},:,0#,!^F,o,O,e
A set of keys that when typed will trigger an indentation event.
infercase inf Local Boolean Default: off
When doing replacement and work completion, see if you can determine the
correct case of the new word. (See page 193.)
insertmode im Global Boolean Default: off
When enabled, Vim works in insert mode as Default:. This option is useful for
people who don't know Vim and don't want to learn. However, if you're reading
this book, you are not one of those people. (See page 258.)
isfname isf Global String Default: System dependent
Determines which characters are considered part of a file name. (See page
263.)
isident isi Local String Default: system dependent
Determines which characters are part of an identifier. (See page 263.)
iskeyword isk Global String Default: Operating system and
compatibility mode dependent.
Defines what characters are considered part of a keyword. (See page 131,
261.)
-J-
joinspaces js Global Boolean Default: on
When enabled, Vim will insert spaces when two lines are joined. (See page
179.)
-K-
key Local String Default: empty
The current encryption key. (See page 213.)
keymap kmp Local String Default: empty
Set the keyboard mapping. (See page 254.)
keymodel km Global String Default: empty
A quick and dirty way for setting the behavior of certain special keys. (See page
169, 467.)
keywordprg kp Global String System dependent.
Program that's used when the K command is executed. (See page 131.)
-L-
langmap lmap Global String Default: empty
Define a keyboard map for a foreign language. (See page 252.)
langmenu lm Global String Default: empty
Language for menus. (See page 474.)
laststatus ls Global Number Default: 1
Determines when a status line is displayed at the bottom of a window. (See page
344.)
lazyredraw lz Global Boolean Default: off
If set, redrawing will be done as little as possible in order to save terminal
bandwidth. (See page 558.)
linebreak lbr Local Boolean Default: off
If enabled Vim will try to break long lines in nice places. (See page 331.)
lines Global Number Default: Terminal height.
Number of lines to use for the editing window. (See page 455.)
linespace lsp Global Number Default: 0
Windows: 1
Amount of whitespace in pixels to add between lines in the GUI. (See page
485.)
lisp Local Boolean Default: off
Turns on a number of options to make editing Lisp easier. A holdover from the
Vi days. (See page 216, 552, 559.)
lispwords lw Global String Default: Long and complex.
Words to use for Lisp indenting. (See page 559.)
list Local Boolean Default: off
Make all the invisible characters visible. Looks ugly, but you can see everything.
Good for finding out where you have tabs and where you have just a series of
spaces. (See page 138, 433, 549.)
listchars lcs Global String Default: eol:$
When the 'list' option is set, this controls how the invisible characters are
displayed on the screen. (See page 138, 549.)
loadplugins lpl Global Boolean Default: on
If set, load plugins from the plugin directory. (See page 155.)
-M-
macatsui Global Boolean Default: on
When set, enabled a hack to work around some drawing problems which are only
seen on Macintosh computers. Set it to off if you are on a Mac and experience
drawing problems.
Ideally this option should go away as soon as the underlying bug is fixed. (See
page 562.)
magic Global Boolean Default: on
Changes the way certain pattern matching characters work. (See page 304, 435,
525.)
makeef mef Global String Default: empty
Name of the error file for :make. If no string is specified, a temporary file is used.
If you put “##” in the file name it will be replaced by a unique number. (See
page 406.)
makeprg mp Global String Default: make
VMS: MMS
The program to use when :make is executed. (See page 406.)
matchpairs mps Local String Default: (:),{:},[:]
Things that can are considered matching pairs. Examples include (), [], and <>.
(See page 394.)
matchtime mat Global Number Default: 5
The time, in tenths of a second, to show the matching parenthesis (assuming
'showmatch' is set.) In order to be compatible with Nvi, this option uses tenths
of a second, while every other timing option uses milliseconds. (See page 394.)
-N-
nrformats nf Local String Default: octal,hex
Defines the number formats recognized by Vim. Can be any combination of
octal and hex. (Decimal is always recognized.) (See page 278, 552.)
number nu Local Boolean Default: off
Show line numbers in front of each line. (See page 46, 159, 365.)
numberwidth nuw Local Number Vim Default: 4
Vi Default: 8
When line numbering is turned on, the minimum number of columns for the line
number. (See page 550.)
-O-
omnifunc ofu Local String Default: empty
Function to be used for the insert omni completion commands (CTRL-X CTRL-O).
(See page 201.)
operatorfunc opfunc Global String Default: empty
The function called by the g@ opeator. (See page 510.)
osfiletype oft Local String Default: System dependent.
For systems which support a file type, the file type to write. (See page 258.)
-P-
paragraphs para Global String Default: IPLPPPQPP LIpplpipbp
When editing troff files, this option specifies the macros that start a paragraph.
(See page 190.)
paste Global Boolean Default: off
When enabled a lot of other options are set so you can cut text from another
window and easily paste it in Vim. (See page 552.)
pastetoggle pt Global String Default: empty
Define a key that will toggle the 'paste' option. (See page 552.)
patchexpr pex Global String Default: empty
Expression to use for patching files. (See page 384.)
patchmode pm Global String Default: empty
When set, if a file of this extension does not exist, Vim will use it to create a
backup file. Once this file is created, it is not overwritten. (See page 217.)
path pa Global String Default: System dependent
Path on which to look for file when using gf , :find, and similar commands.
(See page 194, 398Error: Reference source not found.)
preserveindent pi Local Boolean Default: off
When redoing the indentation, attempt to preserve the existing indentation as
much as possible. (See page 371.)
previewheight pvh Global Number Default: 12
Default height of the preview window. (See page 549.)
previewwindow pvw Local Boolean Default: off
If set, then this window is the preview window. (Only one preview window is
allowed.) (See page 394.)
printdevice pdev Global String Default: empty
Name of the device to be used for hardcopy output. (See page 451.)
printencoding penc Global String System dependent
Character encoding for :hardcopy output. (See page 451.)
printexpr pexpr Global String System dependent.
The command that prints the Postscript file produced for :hardcopy output.
(See page 451.)
printfont pfn Global String Default: courier
Name of the font for :hardcopy output. (See page 451.)
printheader pheader Global String Default: %<%f%h%m%=Page %N
-Q-
quoteescape qe Local String Default: \
The string to use for quoting characters when a shell command is issued. (See
page 447.)
-R-
readonly ro Local Boolean Default: off
If enabled, no changes are allowed to the current file. (See page 225.)
remap Global Boolean Default: on
Allows for mappings to work recursively. (See page424.)
report Global Number Default: 2
When more than this many lines are changed, Vim will output a short message
telling you how many where changed. (See page 548.)
restorescreen rs Global Boolean Default: on
When set Vim will attempt to restore the original terminal screen when existing.
(See page 552.)
revins ri Global Boolean Default: off
Inserting character will work right to left. (See page 252, 552.)
rightleft rl Local Boolean Default: off
Enables right to left mode. (See page 252.)
rightleftcmd rlc Local String Default: search
Edit right to left instead of left to right. (See page 252.)
-S-
scroll scr Local Number Default: half the window height
Number of lines to scroll with CTRL-U and CTRL-D commands. (See page 269.)
scrollbind scb Local Boolean Default: off
All windows with 'scrollbind' set will scroll together. (See page 385.)
scrolljump sj Global Number Default: 1
Minimum number of lines to scroll when scrolling is needed. (See page 272.)
scrolloff so Global Number Default: 0
Minimum of lines to keep above or below the cursor before the screen scrolls.
(See page 272.)
scrollopt sbo Global String Default: ver,jump
Determines how scrolling is done. (See page 386.)
sections sect Global String Default: SHNHH HUnhsh
For users of troff, controls the macros that denote a section start. (See page
191.)
secure Global Boolean Default: off
When set, locks Vim down so that a user can't do bad things like start a shell or
perform other insecure commands. (See page 538.)
selection sel Global String Default: inclusive
Controls how selection mode works. (See page 169, 483.)
selectmode slm Global String Default: empty
Defines what starts select mode. (See page 169, 360, 466.)
sessionoptions ssop Global String Default: blank,buffers,curdir,
folds,help,options,tabpages,
winsize"
Controls what goes into a session created by the :mksession command. (See
page 348, 348.)
shell sh Global String Default: System dependents.
Name of the shell program to use for shell commands. (See page 447, 530.)
shellcmdflag shcf Global String Default: System dependent.
The flag you have to send to the shell to tell it that a command files. (See page
447.)
shellpipe sp Global String Default: System dependent
Determines how shell output is piped to the user and a file. (See page 447.)
shellquote shq Global String Default: System dependent
Determines show shell arguments are quoted. (See page 447.)
shellredir srr Global String Default: System dependent
Controls how the output of shells are redirected to a file. (See page 447, 530.)
shellslash ssl Global Boolean Default: off
When set a forward slash is used when expanding file names. (See page 447.)
shelltemp stmp Global Boolean Vi Default: off,
Vim Default: on
When enabled use temporary files for shell output. When disabled, pipes are
used. (See page 447.)
shelltype st Global Number Default: 0
Determines how shell commands are spawned on an Amiga. (See page 258.)
shellxquote sxq Global String Default: System dependent
Determines how arguments are quoted for shell commands. Don't fiddle with
this unless you know what you are doing. (See page 447.)
shiftround sr Global Boolean Default: off
When set, indent commands move things to the a rounded indent stop. When
clear, shift commands move things a full 'shiftwidth' regardless of the current
position. (See page 372.)
shiftwidth sw Local Number Default: 8
Number of spaces for indenting. (See page 115, 157, 365, 365, 368, 377.)
shortmess shm Global String Vim Default: filnxtToO
Vi Default: empty
POSIX Default: A
A set of letters that control when short messages are used instead of long ones.
This help prevent excessive Hit Enter prompts due to long messages. (See
page 543.)
shortname sn Local Boolean Default: off
When turned on, file names are restricted to the MS-DOS 8.3 style. You have to
have a pretty old and restricted system to need this option. (See page 225.)
When enabled a <Tab> at the front of the line inserts spaces or blanks according
to your 'shiftwidth'. In the middle of a line, it inserts tabs. (See 368.)
softtabstop sts Local Number Default: 0
Number of columns that are used for tabstops when the <Tab> key is pressed.
Depending on your settings, this may result in a tab or spaces being inserted.
(See 368, 552.)
spell Local Boolean Default: off
When on spell checking will be done. (See page 184.)
spellcapcheck spc Local String Default: [.?!]\_[\]
Regular expression used to find an end of sentence. (See page 333.)
spellfile spf Local String Default: empty
Name of the file where Vim is to store words added to the dictionary. (See page
186, 187.)
spelllang spl Local String Default: en
A list of languages to use for spelling. (See page 185.)
spellsuggest sps Global String Default: best
A list of methods to be used for deciding how to to suggest spelling corrections.
Values include best, double, fast, {number}, file:{filename}, expr:
{expression}. (See page 333.)
splitbelow sb Global Boolean Default: off
When enabled, the split command creates a new window below the current one.
(See page 345.)
splitright spr Global Boolean Default: off
When enabled, the split command creates the new window to the right of the
current one. (See page 345.)
startofline sol Global Boolean Default: on
When enabled, changes the behavior of some movement commands so that they
also move the cursor to the first non-blank column of the line. If disabled, Vim
attempts to keep the cursor in the same column. (See page 557.)
statusline stl Global String Default: empty
Define how the status line is displayed. (See page 545.)
suffixes su Global String Default: .bak,~,.o,.h,.info,
.swp,.obj
When doing a wildcard match, put files with these suffixes last on the list. (See
'wildignore' for how to completely ignore files.) (See page 517, 554.)
suffixesadd sua Local String Default: empty
List of suffixes used when searching for a file using gf. (See page 399.)
swapfile swf Local Boolean Default: on
If set, use a swap file for this buffer. (See page 223.)
swapsync sws Global String Default: fsync
When set, causes a sync operation to be executed each time the swap file is
written. This causes Vim to tell the operating system to flush the disk buffers so
that the data is really written to the disk. If set to sync all buffers for all files
will be flushed. Setting it to the null string turns off this operation. (See page
223.)
switchbuf swb Global String Default: empty
Controls how buffers are displayed when switching buffers. (See 95, 96, 410.)
synmaxcol smc Local Number Default: 3000
Limit on the number of columns to be used for searching for syntax highlighting
elements. (0 is no limit.) (See page 596.)
syntax syn Local String Default: empty
The name of the syntax to use for syntax highlighting. This can actually contain
more than one language, for example [Link] tells Vim to use C syntax
highlighting and then the doxygen highlighting. The special string ON and OFF
turn syntax highlighting on and off. (See page 417.)
-T-
tabline tal Global String Default: empty
Defines how the tab line (the line at the top of the screen containing a list of
tabs) looks in terminal (non-GUI) mode. (See page 348.)
tabpagemax tpm Global Number Default: 10
Maximum number of tabbed panes that can be opened from the command line.
(See page 98.)
tabstop ts Local Number Default: 8
Number of spaces for each tab stop. (This value was chosen because the old
Teletype terminals had tab stops hardwired in at 8. Most programs honor this
value, so don't change this value unless you are ready to deal with a lot of
problems external programs.) (See page 365, 368, 370.)
tagbsearch tbs Global Boolean Default: on
If enabled, use a binary search to locate tags. This is faster for large tagfiles,
but won't work if the tagfile is not sorted. (See page 411.)
taglength tl Global Number Default: 0
If non-zero, tags are significant up to this number of characters. (See page 412.)
When set the tilde (~) command acts like an operator. If not set, the tilde (~)
command acts like a motion command. (See page 282, 560.)
timeout to Global Boolean Default: on
ttimeout Global Boolean Default: off
These two options control whether Vim will timeout in the middle of a function
key sequence or sequence defined by the :map command. The values are:
'timeout' 'ttimeout' Action
off off do not time out
on n.a. Time out on both :map and function key sqeuences
off on time out key codes
(See page 540.)
timeoutlen tm Global Number Default: 1000
ttimeoutlen ttm Global Number Default: -1
These two options control the time (in milliseconds) allowed between characters
when Vim is looking for a sequence of keystrokes. Terminal function keys send
out such sequences, but sequences can also be defined using the :map
command.
Normally only 'timeoutlen' is used. If 'ttimeoutline' is set to then it is used
for function key sequences, and 'timeoutlen' is then only used for :map
sequences. (See page 540.)
title Global Boolean Default: Terminal dependent
If set, Vim will attempt to change the title of the terminal window in which it is
running. (See page 461.)
titlelen Global Number Default: 85
What percentage of the window to use for the title. (See page 462.)
titleold Global String Default: Thanks for flying Vim
When Vim exists, it tries to restore the original title. If it can't it will use the
value of this option as the title to be displayed after Vim has stopped. (See page
463.)
titlestring Global String Default: empty
The title of the window. (See page 463.)
toolbar tb Global String Default: icons,tooltips
Controls what goes into the toolbars. Possible values are: icons, text, horiz,
tooltips. (See page 461.)
toolbariconsize tbis Global String Default: small
The size of the icons in the toolbar. Values are tiny, small, medium, and large.
(See page 462.)
ttybuiltin tbi Global Boolean Default: on
When enabled Vim will search its internal terminal database before searching
any external ones. (See page 558.)
ttyfast tf Global Boolean Default: on for most terminals
If set indicates you have a fast terminal and Vim can redraw the screen using a
system which sends more characters, but looks better. (See page 558.)
ttymouse ttym Global String Default: depends on 'term'
Controls how mouse events are sent to Vim through a terminal. (See page 558.)
ttyscroll tsl Global Number Default: 999
Maximum number of lines to scroll the screen. If there are more lines
to scroll the window is redrawn. For terminals where scrolling is
very slow and redrawing is not slow this can be set to a small number,
e.g., 3, to speed up displaying. (See page 559.)
ttytype tty Global String Default: from $TERM
Alias for 'term', see above. (See page 558.)
-U-
undolevels ul Global Number 100
Unix, VMS, Win32, OS/2: 1000
Maximum number of changes that can be undone. (See page 284.)
updatecount uc Global Number Default: 200
The number of characters you can type before the swap file is written. (See
page 222.)
updatetime ut Global Number Default: 4000
If set, the number of milliseconds of idle time before the swap file is written.
(See page 206, 222.)
-V-
verbose vbs Global Number Default: 0
Controls how much debugging information is displayed. (See page 560.)
verbosefile vfile Global String Default: empty
If set, the name of a file where verbose messages are logged. (See page 561.)
viewdir vdir Global String Amiga, MS-DOS, OS/2 and Win32:
$VIM/vimfiles/view,
Macintosh: $VIM:vimfiles:view
VMS: sys$login:vimfiles/view
RiscOS: Choices:vimfiles/view
Directory where view files (:mkview) are stored. (See page 350.)
viewoptions vop Global String Default: folds,options,cursor
Controls what's saved using the :mkview command. (See page 350.)
viminfo vi Global String Vi mode: empty
Vim mode for MS-DOS, Windows and
OS/2: '20,<50,s10,h,rA:,rB:
Vim mode for other systems:
'20,<50,s10,h
A string defining what data is stored in a .viminfo file. (See page 324-326, 488.)
virtualedit ve Global String Default: empty
Tells Vim when you can do virtual editing. (See page 281.)
visualbell vb Global Boolean Default: off
Use a visual bell instead of beeping. (See page 545.)
-W-
warn Global Boolean Default: on
Give a warning message when a shell command is used while the buffer
has been changed. (See page 544.)
weirdinvert wiv Global Boolean Default: off
Provided for backward compatibility with version 4.x. Mostly it's here to get
around some problems with strange terminals. (See page 559.)
whichwrap ww Global String Vim Default: b,s
Vi Default: empty
Specifies which characters are allowed to move the cursor past the end of line or
beginning on line. (See page 268.)
wildchar wc Global Number Vim mode: <Tab>
Vi mode: CTRL-E
Character that starts wildcard expansion in command line mode. (See page
553.)
wildcharm wcm Global Number Default: 0
The character number of a character will act like 'wildchar' when used inside
macros. (See page 553.)
wildignore wig Global String Default: empty
A list of file patterns of files that you want to ignore when doing command line
completion. For example, you probably want to ignore all object files because
345.)
winminheight wmh Global Number Default: 1
Minimum height of a window that's not the current window. (See page 344.)
winminwidth wmw Global Number Default: 1
Minimum width of the windows that are not current. (See page 344.)
winwidth wiw Global Number Default: 20
Minimum width of the current window. (See page 344.)
wrap Local Boolean Default: on
If set, long lines will wrap around and be displayed on the screen. If not set the
ends of long lines go off the screen and can only be seen when you use horizontal
scrolling. (See page 327, 331.)
wrapmargin wm Local Number Default: 0
When typing characters with auto-wrap turned on, the number of characters to
use for a right margin. (See page 176, 552.)
wrapscan ws Global Boolean Default: on
If set searches wrap past the beginning or end of the file. (See page 293.)
write Global Boolean Default: on
If set, the user is allowed to write files. If not set, you can look but not touch
(write) files. (See page 557.)
writeany wa Global Boolean Default: off
If set, when writing files do not force the user to use the overwrite (!) option if a
file is going to overwrite an existing file. (See page 557.)
writebackup wb Global Boolean Default: on with writebackup feature
off otherwise
If set, then files are written by making a backup, writing the file, and deleting
the backup. (See page 218.)
writedelay wd Global Number Default: 0
A debugging option which inserts the specified amount of time (in milliseconds)
between each character output. Basically a simple way of slowing down the
editor so you can see how it redraws the screen. (See page560.)
22
23
or someone who you distributed the modified Vim to asks you (in
any way) for the changes within this period, you must make them
available to him.
- You clearly describe in the distribution how to contact you. This
contact information must remain valid for at least three years
after last distributing the corresponding modified Vim, or as long
as possible.
e) When the GNU General Public License (GPL) applies to the changes,
you can distribute the modified Vim under the GNU GPL version 2 or
any later version.
3) A message must be added, at least in the output of the ":version"
command and in the intro screen, such that the user of the modified Vim
is able to see that it was modified. When distributing as mentioned
under 2)e) adding the message is only required for as far as this does
not conflict with the license used for the changes.
4) The contact information as required under 2)a) and 2)d) must not be
removed or changed, except that the person himself can make
corrections.
III) If you distribute a modified version of Vim, you are encouraged to use
the Vim license for your changes and make them available to the
maintainer, including the source code. The preferred way to do this is
by e-mail or by uploading the files to a server and e-mailing the URL.
If the number of changes is small (e.g., a modified Makefile) e-mailing a
context diff will do. The e-mail address to be used is
<maintainer@[Link]>
IV) It is not allowed to remove this license from the distribution of the Vim
sources, parts of it or from a modified version. You may use this
license for previous Vim releases instead of the license that they came
with, at your option.
Author's Note
By Steve Oualline
The people behind Vim have spent a lot of time and effort to make one of
the best editors in the world. Yet they do not ask anything for themselves;
instead, they ask that you help some of the poorest and most needy people in
Africa. Please send them a donation.
If you work for a medium-size or large company, please take the time to tell
your boss how much using Vim has helped you and encourage your company to
make a substantial donation.
The people behind Vim are good people. Please help them out.
j [number]h – Left
[number]r – Right
Basic Movement
Editing Commands
u – Undo
CTRL-R – Redo
Getting Out
ZZ – Write file and exit :q! – Abort edits and discard all work (since editing
started or the last :write command).
Note: On Linux and Unix you must enable the Vim command set
[number]CTRL-F – Screens up
[number]CTRL-E – Lines up
CTRL-Y
(Line 9 is new top line)
Line 10 Line ?
Line 11 CTRL-U (Line 5 top) Line ?
Line 12 Line ?
Line 13 Line ?
Line 14 Line ?
Line 15 Line ?
Line 16 Line ?
Line 17 CTRL-B Line ?
Line 18 (Line 1 is new top line) Line ?
Line 19 Line ?
`{mark} -- Go to mark.
Screen Location
Screen Redrawing
[count]z{height}<cr>
Line 10 Line 2
Line 11 Line 3
Line 12 Line 4
Line 13 2z+ Line 5
Line 14 Line 6
Line 10 Line 31
Line 11 33z. Line 32
Line 12 Line 33
Line 13 Line 34
Line 14 Line 35
Virtual movement
j – Move up gj – Virtual Move up
k – Move down gk – Virtual Move down
l – Move right gl – Virtual Move right
h – Move left gh – Virtual Move left
'virtualedit' option values:
block Allow virtual editing in Visual block mode.
insert Allow virtual editing in Insert mode.
all Allow virtual editing in all modes.
onemore Allow the cursor to move just past the end of the line
Text Movement
Horizontal Movement
[number]fx Single character forward search, stop on character.
fi Fh
To err is human.
To really foul up you need a computer.
ty Ty
^ $
This is a test.
g0 First character of the screen line
g^ g$
This is a very long unwrapped text that exceeds the screen size
Changing text
[number]i{text}<ESC>
[number]I{text}<ESC>
[number]a{text}<ESC>
[number]a{text}<ESC>
xp Reverse characters
[number][“{register}]d{move}
[number][“{register}]dd
Delete lines.
[number][“{register}]D
[number][“{register}P
[number][“{register}P
[“{register}][number]c{motion}{text}<ESC>
Change text.
[“{register}][number]cc{text}<ESC>
[“{register}][number]C{text}<ESC>
[number]r{char}
[number]R{text}<ESC>
[number]gr{char}
[number]gR{text}<ESC>
[number][“{register}]s{text}<ESC>
[number][“{register}]S{text}<ESC>
[number][“{register}]X
[number][“{register}]y{motion}
[number][“{register}]yy
[number][“{register}]Y
[number]gU{motion}
[number]gUgU
[number]gu{motion}
[number]gugu
[number]g?{motion}
[number]g?g?
[number]!!{motion}{command}
[number]!!
Windows
[number]CTRL-W +
[number]CTRL-W -
[number]CTRL-W <
[number]CTRL-W >
[number]CTRL-W _
[number]CTRL-W |
CTRL-W H
One CTRL-W R
~
~
~
one.c [+]
Two
~
~
two.c [+]
Three
~
~
CTRL-W r three.c [+]
CTRL-Wj Window up
Others
Multiple Files
:args {file-list}
Set the file list to the given files. Wildcards like “*”, “**”,
and “?” may be used.
CTRL-W gf Edit the file who's name is under the cursor in a new tab.
Searching
* Search word forward for the word under the cursor
n Repeat search
Simple atoms
Pattern Description Example Result
abc Literal /abc abcdef cba
\\ Literal \ /\\ a\b
\/ Literal / /\/ a/b
\. Literal . /\. a.b a+b
\{ Literal { /\{ a{b a+b
\[ Literal [ /\[ a[b a+b
\$ Literal $ /\$ a$b a+b
\^ Literal ^ /\^ a^b a+b
\%dnnn The character who's decimal number is nnn
\%xnn The character who's hexadecimal number is nn
\%onnn The character who's octal number is nnn
\%unnnn The multibyte character who's number is nnnn
\%Unnnnnnnn The large multibyte character who's number is nnnnnnnn
\e <Esc> Character
\t <Tab> Character
\r <CR> Character
\b <BS> Character
\n End of line
Character Classes
Pattern Description Example Result
\a Alphabetic character \a ab123(*&ab
\i Identifier \i abc def a10b
(defined by 'isident')
\I Identifier excluding digits \I abc def a10b
\k Keyword \k abc def a10b
(defined by 'iskeyword')
\K Keyword excluding digits \k abc def a10b
\f File name \f [Link] /root/[Link] [Link]
(defined by 'isfname')
\F File name excluding digits \F [Link] /root/[Link] [Link]
\p Printable \p [Link] ^A^B^C [Link]
(defined by 'isprint')
\P Pritable name excluding \P [Link] ^A^B^C [Link]
digits
\s Whitespace \s Space tab done
Modifiers
Pattern Description Example Result
\c Ignore case \cabc ABC abc
\C Match case \ca\CBC aBC abc ABC
\m Turn 'magic' off
\M Turn 'magic' on
\v Turn very magic on
\V Turn off very magic
\Z Ignore differences in Unicode combination characters
Sets of Characters
Pattern Description Example Result
[abc] Any of the given [abc] abcdefgaaxxyycc
characters
[a-f] From a to f [a-f] axbxefxx
[^abc] Any character [^a-f] axbxefxx
except a,b, or c
\%[string] Match as much a\%[bcd] abxx
of string as abcxx
possible
Anchors
Pattern Description Example Action
^ Start of line ^abc abc abc abc
$ End of line abc$ abc abc abc
\_^ Start of line abc\_^def line with abc
(can be inside def on next
pattern)
\_$ End of line (can abc\_$def line with abc
be inside def on next
pattern)
\< Beginning of \<abc abc xxabc
word
\> End of word abc\> abcxx xxabc abcyy
\%^ Beginning of \%^abc abc
file abc
\%$ End of file abc\%$ abc
abc
\%V Inside visual
area
\%# Cursor position
\%55l Inside line 55
\%5l Inside column 5
\%7l Inside virtual
column 7
\%'m Mark m postion
\zs Set start of
match
\ze Set end of
match
Choices
Pattern Description Example Result
a|b a or b a|b abcdef cba
a\&b a followed by b a\&b ab ac
For programmers
Command Go to If one tag If many Result in
:tag {tag} Tag Jump Jump Same window
:tselect {tag} Tag Select Select Same window
:tjump {tag} Tag Jump Select Same Window
:stag {tag} Tag Jump Jump New window
:stselect {tag} Tag Select Select New window
:stjump {tag} Tag Jump Select New Window
:ptag {tag} Tag Jump Jump Preview Window
:ptselect Tag Select Select Preview Window
:ptjump Tag Jump Select Preview Window
CTRL-] Tag Jump Jump Same Window
g] Tag Select Select Same Window
g CTRL-] Tag Jump Select Same Window
gf File Jump N.A. Same Window
CRL-Wf File Jump N.A. Same Window
CTRL-Wgf File Jump N.A. New tab
CTRL-W] Tag Jump Jump New Window
CTRL-Wg] Tag Select Select New Window
CTRL-wgCTRL-] Tag Jump Select New Window
CTRL-W} Tag Jump Jump Preview Window
CTRL-Wg} Tag Jump Select Preview Window
CTRL-Wd Split and jump to definition
={motion} Reindent
== Reindent line
K Keyword lookup
Program searches
Command Search For Start Result
[d Macro definition Start of file Show line
]d Macro definition Current position Show line
[D Macro definition Start of file Show all
]D Macro definition Current position Show all
[ CTRL-D Macro definition Start of file Jump
] CTRL-D Macro definition Current position Jump
CTRL-W d Macro definition Start of file New window
CTRL-W i Line containing word Start of file Open new window
[ CTRL-I Line containing word Start of file Jump
] CTRL-I Line containing word Current position Jump
[i Line containing word Start of file Show line
]i Line containing word Current position Show line
[I Line containing word Start of file List all
]I Line containing word Current position List all
[# Go to the next unmatched #if/#else/#endif
gD Go to global declaration
gd Go to local declaration
Text selection
Command Delimiter Include Example
Delimiter
a" " Yes print "Hello world"
a' ' Yes ch = 'x';
a( [] () Yes x = data[j];
a) x = f(y);
ab
a< <> Yes <bold>Bold text
a>
a{ {} Yes if (a) { b(c); }
a}
aB
aw word Yes This is an example
aW WORD Yes This word-style example
a[ [] Yes a = x[3];
a]
a` ` Yes x = `ls -1`
ap Paragraph Yes This is a sentence. And
this is another.
Different paragraph.
as Sentence Yes No way. Yes way.
at Tag block Yes <b><i>Yell</i></b>
i" “ No print "Hello world"
i' ' No ch = 'x';
i( [] () No x = data[j];
i) x = f(y);
ib
i< <> No <bold>Bold text
i>
i{ {} No if (a) { b(c); }
i}
iB
Different paragraph.
is Sentence No No way. Yes way.
it Tag block No <b><i>Yell</i></b>
Display options
:set number Show line numbers
Diff mode
do Get (obtain) difference from the other window
:diffthis Add this file to the ones being used for this diff.
Folding
zf{motion} Fold text
zi Invert 'foldenable'
Misc commands
qa{commands}q Start macro
@a Execute macro
q: Edit : commands
q/ Edit searches
24
Index
basic.................................................... CTRL-P................................................
editing.........................................28 Normal Mode Command.............32
Basic.................................................... CTRL-P, Normal Mode Command. . .32
Movement Commands.................28 Delete Character.................................
Basic Editing...................................28 Normal Mode...............................33
Basic Movement Commands...........28 Delete Command (Normal Mode)...28
Command............................................ deleting characters, Normal Mode. 33
Delete.............................................. Down (j)...............................................
Normal Mode...........................28 Normal Mode...............................31
Esc................................................... Down (k)..............................................
Insert Mode.............................31 Movement Command (Normal
i........................................................ mode)...........................................31
Normal Mode...........................30 Esc (key) Insert Mode command. . .31
Insert............................................... Exiting the editor............................28
Normal Mode...........................28 Getting Out.........................................
x....................................................... Insert Mode.................................31
Normal Mode...........................33 Getting out of Insert Mode..............31
<Enter>.......................................... gvim command................................29
Insert Mode.............................33 Help.....................................................
<Esc>.............................................. Command....................................28
Insert Mode.............................31 Help Command...............................28
Command mode.................................. Inseert.................................................
:set................................................... Mode............................................30
Command.................................28 Insert...................................................
compatible........................................... Mode............................................30
Option..........................................28 Insert (i)..............................................
compatible option...........................28 Normal Mode...............................30
cp......................................................... Insert command (i)..........................30
option..........................................28 Insert Command (Normal Mode)....28
cp option.........................................28 Insert Mode.....................................30
CTRL-H................................................ Leavingf Insert Mode......................31
Normal Mode Command.............32 Left (h)................................................
CTRL-H, Normal Mode Command. .32 Movement Command (Normal
CTRL-J................................................. mode)...........................................31
Normal Mode Command.............32 Normal Mode...............................31
CTRL-K................................................ Linux...............................................28
Normal Mode Command.............32 Microsoft Windows,........................29
CTRL-K, Normal Mode Command...32 Mode Visual.....................................30
CTRL-N................................................ Modes..............................................30
Normal Mode Command.............32 Movement...........................................
CTRL-N, Normal Mode Command. .32 Basic................................................
Command.................................28 Mode............................................30
Normal Mode...................................... Visual Mode.....................................30
Delete.............................................. Windows, Microsoft........................29
Command.................................28 x command, Normal Mode..............33
Insert............................................... x, Normal Mode Command.............33
Command.................................28 :set.......................................................
Normal Mode command (h)................ Command command....................28
Left..............................................31 :set command..................................28
Normal Mode command (j)................. .vimrc..................................................
Down...........................................31 File...............................................28
Normal Mode command (k)................ .vimrc file........................................28
Up................................................31 <BS>...................................................
Normal Mode command (l)................. Normal Mode Command.............32
Right............................................31 <BS>, Normal Mode Command.....32
Right (l)............................................... <Down>..............................................
Movement Command (Normal Normal Mode Command.............32
mode)...........................................31 <Down>, Normal Mode Command.32
Normal Mode...............................31 <Enter>, Insert Mode....................33
running vim.....................................29 <Enter>, Insert Moder...................33
starting vim.....................................29 <Esc> Insert Mode command........31
Trouble (Getting out of)..................31 <Left>.................................................
UNIX...............................................28 Normal Mode Command.............32
Up (j)................................................... <Left>, Normal Mode Command. . .32
Movement Command..................31 <NL>..................................................
Movement Command (Normal Normal Mode Command.............32
mode)...........................................31 <NL>, Normal Mode Command.....32
Up (k).................................................. <Right>..............................................
Normal Mode...............................31 Normal Mode Command.............32
Vi mode...........................................28 <Right>, Normal Mode Command. 32
vim....................................................... <Space>.............................................
command line command..............29 Normal Mode Command.............32
Vim...................................................... <Space>, Normal Mode Command 32
Mode............................................28 <Up>..................................................
vim command..................................29 Normal Mode Command.............32
Vim mode........................................28 <Up>, Normal Mode Command.....32
Visual...................................................
25
Vim offers several methods for moving large blocks of text. One method involves using the command '57dd' to delete a 57 line block and then 'p' to paste it at the desired location. This requires knowing the exact number of lines to move, making it less practical for large or unknown-number blocks . Alternatively, using Vim's visual mode, initiated with 'V' for line visual mode, allows the user to visually select the entire block without counting lines. This method provides a visual confirmation of the selection, thus making it more intuitive and less error-prone for large text blocks .
The ':split' command in Vim divides the current window horizontally, while ':vsplit' divides it vertically. This distinction is crucial for text editing as horizontal splits are typically used for comparing lines within files, whereas vertical splits are often utilized for side-by-side comparison of entire lines or files. These splitting techniques enhance workflow efficiency by allowing multiple views and interactions with different file sections or files .
The 'qall' command in Vim attempts to close all open windows and quit Vim, but it fails if there are unsaved changes. Conversely, 'qall!' forcibly quits without saving any changes. The use of 'qall!' should be cautious due to the risk of discarding unintended work, making 'qall' a safer option when careful preservation of changes is necessary .
Vim's extensive support for syntax highlighting customization significantly enhances the user experience by allowing personalized visual distinctions in code, which enhances readability and aids in identifying syntax elements quickly. For Ruby, options like 'ruby_operators' and 'ruby_space_errors' are available, while shell scripting can be customized with options like 'is_bash' or 'sh_fold_enable'. These customizations not only bolster productivity by helping users quickly identify errors and syntactic structures, but they also accommodate the user preferences and requirements of different programming languages or script styles .
Vim's visual mode enhances block text editing by allowing users to select and manipulate blocks of text visually rather than through line commands. The '$' command in block visual mode extends the selection to the end of all lines within the visual selection, even if they exceed the initial line's length, making it easier to handle multiline blocks with varying lengths. The 'gv' command reselects the previous visual selection, enabling repeated edits efficiently, especially useful in iterative editing tasks. These features streamline the visual mode by providing powerful and intuitive commands for complex text manipulations .
Ctrl-W navigation in Vim facilitates seamless window management by allowing movement between split windows. Specific command variations include Ctrl-W w, which switches to the next window, Ctrl-W j/k (or down/up) to move to a lower or higher window, respectively, and Ctrl-W l/h (or left/right) for horizontal navigation. These commands enable efficient multitasking within Vim by reducing the time needed to manually close or select windows with a mouse .
Vim ensures efficient text navigation by providing fast-switching commands such as 'CTRL-Ww', which cycles through windows, and line-specific shortcuts like '[count]w' for moving forward by words, '0' for the line's start, and 'G' for jumping to specific lines. These commands enable users to access desired text segments rapidly, which enhances productivity by minimizing the need for manual scrolling or excessive cursor movement .
Marks in Vim are useful for navigating and editing tasks as they allow a user to set locations (a-z) in the text, which can be quickly returned to. The command 'ma' sets a mark at the current cursor position. Using '`a', you can move the cursor directly to the marked line and column, while ''a' moves to the start of the marked line. Marks are particularly effective in repetitive editing tasks or when deleting long series of lines, allowing precise and quick navigation to marked positions .
Vim's session management capabilities facilitate collaborative or asynchronous workflows by enabling users to save the state of all open files, window arrangements, and other settings into a session file. This file can be shared with others, allowing them to continue from the same editing state without the need to configure the environment manually. Additionally, session files are useful for resuming work after an interruption, ensuring a consistent starting point for team members who might be working in shifts or across different time zones .
When deleting a partial line in Vim, such as a single word using the 'dw' command, the 'p' command inserts the deleted text right after the character under the cursor. In contrast, when an entire line is deleted with 'dd', the 'p' command places this deleted line after the current line where the cursor resides. This illustrates the difference between handling full line deletions and partial line deletions .