improve. I am putting the finishing touches to a free book about a text editor whose ancestry can be traced back to 1976. In any case. in 2009. It will always be incomplete by virtue of Vim having more features and extensions than I have years alive.runpaint. And that is why.Vim Recipes
INTRODUCTION
The Vim text editor is perhaps as famous for its learning curve as it is for its contributions to productivity. This book is written to be consulted when you're looking for a better way to perform a task. for you to examine and.
Visit http://vim.K. In addition to being free. I would enjoy hearing any feedback you have. It permanently alters the way in which you regard text editors and software in general. The files from which it is compiled are freely available. hopefully. and you can e-mail me at the address below. this book is open source. U.
v
. Happy Viming! —Run Paint Run Run (runrun@runpaint. 2009. but will hopefully still serve as an indispensable reference. It does not replace Vim's excellent built-in documentation. Vim isn't "intuitive" in the way other applications claim to be—you cannot use it by simply replicating the actions you perform with a word processor. but complements it by focussing on tasks rather than commands. The major strength of Vim is that it does things differently to magnificent effect.org/ for latest updates.org). by clicking on menu items aimlessly until you achieve your desired effect. But this is by design. Contact details are in the Contributing section.

:!command .Indicates that the named key should be pressed.CONVENTIONS
The following typographical conventions are used in this book:
KEY PRESSES <Esc> . press <Esc> before you type the command).Keys joined with a .The command should be typed in Command-Line mode.
COMMAND-LINE COMMANDS :set spell . In this example the <Ctrl><Ctrl> should be held down while the p key is pressed.should be pressed simultaneously. code. <Ctrl>-p .
vi
.
MONOSPACED FONT A fixed width font is used for filenames. (If you're in a different mode.
NORMAL MODE COMMANDS gqap .As above. and variable names. but command is a variable which should be substituted for its value.The named characters should be entered in order while in Normal mode.

Vim Recipes

CONTRIBUTING
This book is released under a Creative Commons Attribution-Share Alike 3.0 Unported License, and its complete text is available in a Git repository. All contributions are welcomed. Patches are preferred, but if you're not comfortable with Git you can use the issue tracker as described below.

PATCHES The source for this book is available in a Git repository. If you have Git installed on your system you may clone the repository using the URL git://github.com/runpaint/vim-recipes.git. (For an introduction to Git see the Git Community Book). You'll probably want to do something like this: $ git clone git://github.com/runpaint/vim-recipes.git git://github.com/runpaint/vim-recipes.git Initialized empty Git repository in /tmp/vim-recipes/.git/ remote: Counting objects: 666, done. remote: Compressing objects: 100% (610/610), done.

Then either send me a patch (runrun@runpaint.org), or post it to the issue tracker. Alternatively, if you already use GitHub, fork the repository, make your changes, then send me a pull request.

viii

Vim Recipes

LICENSE
This work is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.

Visit http://vim.runpaint.org/ for latest updates.

ix

Thank you!
x
. Raúl Núñez de Arenas Coronado. and graciously made available via A List Apart.
CONTRIBUTORS The following people have kindly contributed ideas. and others who I'm bound to have omitted. In conjunction.0 Generic License. the CSS created by Håkon Wium Lie and Bert Bos for their book entitled Cascading Style Sheets: Designing for the Web. was taken by Sebastian Bergmann and kindly released under a Creative Commons Attribution-Share Alike 2. Adam Blinkinsop. Lastly. Javier Rojas.CREDITS
COVER IMAGE The cover photograph of Bram Moolenaar. the creator of Vim. Mark Pilgrim's stylesheet from Dive Into Python 3 was the main inspiration.
CSS The Cascading Style Sheets used in the production of the book were derived significantly from the work of others. Michael Houghton. The original photograph can be viewed at Flickr. was particularly helpful. coderpunk. and advice: Rizal Almashoor. Kjetil Dynnamittt. 3rd Edition. Ihar Filipau. corrections. Nando Vieira's kitabu project offered ideas on how to tie it all together. dm3.

Dip in and out of Insert mode when needed. It's tempting to spend much of your time in Insert mode.
12
.g. Command-Line mode Use this for entering commands. However. but it really is the key to understanding Vim. Stay in this mode for as short a time as possible. :set number
DISCUSSION Vim's modal approach to editing can seem confusing.
SOLUTION For practical purposes there are four modes: Insert mode Use only for typing. copy. Normal mode Use this for editing: moving around the file. or format it. Visual mode Use this for visually selecting text so that you can cut.CHOOSING
THE
RIGHT MODE
PROBLEM You know that Vim has multiple modes of operation but aren't sure when to use which one. e. not moving around or editing. this is slow and requires an awful lot of key presses. and navigate with the arrow keys. and rearranging structure. changing text.

Vim Recipes

Normal mode is the default mode because it makes it so easy to move around the file to either edit existing text or position the cursor where you want to insert text.

✪

Use <Ctrl>+o in Insert mode to switch to Normal mode for one command, then <Ctrl>+

return to Insert mode. For example, <Ctrl>+o gqas enters Normal mode, reformats the <Ctrl>+ current sentence,1 then returns you to Insert mode. If you create a new file, and just want to type, by all means go straight into Insert mode and do so. All other times, though, stay in Normal mode. For example, you want to find a paragraph you've written previously, and reword it. In Normal mode you can either search for it (e.g. /Hobson argued), or simply page through the file (e.g. <Ctrl>+F to scroll downwards) to find it. Once there, you can move to the <Ctrl>+ section you're interested in using either the basic movement commands or text objects. You can now use text objects again to select something and change it. For example caw deletes the current word and puts you into Insert mode to change it. Once you have done so, hit <Esc> again to return to Normal mode.

1. For an explanation of gqas refer to the Selecting Text with Motions recipe.

Visit http://vim.runpaint.org/ for latest updates.

13

BASIC NAVIGATION

PROBLEM You want to move around inside a file.

SOLUTION The traditional approach is to use the arrow keys to move up, down, left, and right. Vim supports that style of navigation but also offers a more efficient alternative: Key h l k j 0 ^ $ Left Right Up a line Down a line Start of line First character of line End of line Movement

DISCUSSION It is tempting to rely on old habits for something as basic as moving around in a file. Once you're used to The Vim Way, however, you'll find yourself much more efficient. One reason for this is that these keys are all located on the main keyboard, so you don't need to stretch to the arrow keys, hence breaking your flow.

14

Vim Recipes

Another benefit is that you can prefix these shortcuts with counts (as you can with many Vim commands) which specify how many times they should be executed. For instance, 2k moves up two lines. Once you've become used to these keys, take a look at motions and text objects in Selecting Text with Motions to make the humble combination of h, l, k, and j more powerful still.

Visit http://vim.runpaint.org/ for latest updates.

15

txt). For example.rb. using bash:
#!/bin/sh vim $(ack -g $@)
Name it vack.rb will search recursively downwards from the current directory to find shapes.txt. If you want to edit or view an existing file you need to open it first. then vack shapes. then open it in Vim. For example. To open a file from inside Vim you can use
:e
file (mnemonic: edit). you want to open novel.
16
.
✪
If you use Andy Lester's ack utility you can create a shell script to open files without
having to specify their path.txt (on Windows: vim. if your world-changing novel is saved as novel. For example: vim docs/novel. This closes the current
file and opens a new buffer containing the given file.exe docs\novel.txt in Vim.
SOLUTION To open a file from the command line invoke Vim with the filename as an argument.OPENING FILES
PROBLEM You want to open a file in Vim.

vim +7 todo. Vim opens them all.txt then /home/julie/ recipes/pasta/peperonata. The :cd directory command lets you change the directory Vim resolves relative paths to. Typing :next advances you to the next file in the list. prefixing the filename with +/pattern positions the cursor at the first occurrence of the pattern pattern. Tabs display a single file at a time. For example. Vim will jump to the end of the file.
17
. this only affects the first named file.org/ for latest updates. find the first line that starts with References. If you forget which directory you're in :pwd (print p working directory) will tell you. For example.textile instructs Vim to open btrees.txt you can :cd /home/julie/recipes/ pasta then :e carbonara.textile. instead of buffers. If you omit linenumber. provide a list of opened tabs across the top of the screen. If you provide a line number or pattern to jump to.runpaint. When working with multiple files you may prefer to view them in tabs or split windows. vim +/^References btrees. instead of opening /home/julie/recipes/pasta/cabonara. The first file named is opened in the current buffer. So if you're working with multiple files in the same directory tree you can use this command to set your working directory so it's easier to open files. you prefix the filename with +.txt. Similarly. For example. but.list or :e +100 treatise. one in each buffer. by default. If you supply multiple filenames.txt. You can switch to an open tab by clicking on its name in the GUI or referring
Visit http://vim. i. then position the cursor there.Vim Recipes
DISCUSSION You may prefix the filename with +linenumber to instruct Vim to jump to the given line after opening.e.

From within Vim :tabedit file opens the named file in a new tab. 2. or a file that you can only remember has the word lethargy in it. which only takes a single filename. your shell expands any wildcards. However. Or.tex). respectively. if the directory contained multiple . For example.html file. If you're opening a file from the command line (i. vim resume. :vsplit file effects a vertical division. Windows is notoriously weak at command-line work. The implication is that if you use wildcards with a command like :edit. from the command line vim -p files opens each named file in its own tab. However.to its number.txt. For example. By default the screen is divided horizontally.html would complain: E77: Too many file names.html files. that same wildcard would imply a list of files. and :edit *. :edit *.txt files whose names start with 1. So far we have specified filenames literally by naming each file to open.html would save you typing and work how you expect.e. From Vim :split file splits the screen horizontally between the current file and the named file. putting each file beneath the previous. Split windows display multiple files on screen simultenously. Vim commands that accept filenames support a similar set of wildcards with one caveat: some commands only accept a single filename. using the bash shell I can open . These operations can be conducted from the command line with vim -o files and vim -O files. or 3 with vim [123]*. but you may also split it vertically so that each file is displayed next to each other. suppose you want to edit all files whose names end with . they cannot expand to multiple files.txt. So if your current directory contained only one .
18
. at other times this is impractical. while others accept a list. In cases such as these we would rather describe a group of files by using wildcards. but other operating systems will probably do the right thing here.

Vim Recipes

Instead of using :edit, you can use :next files which happily accepts a list of files, and opens each one in a new buffer. The :args files command is similar, but instead of appending the list of files to the current list of open files, it uses them to replace the current list.

Visit http://vim.runpaint.org/ for latest updates.

19

SAVING

A

FILE

PROBLEM You want to save the file you've been working on. After you've made changes to a file you typically want to save them. For example, if you've written up a turkey recipe to send to your daughter, you'd open Vim, type the recipe, save it to turkey-recipe.txt, then e-mail turkey-recipe.txt to your hungry child.

SOLUTION The :up[date] command saves the current buffer if it has been modified2. If your file doesn't have a name yet, you'll need to follow :up with a filename. This is conceptually similar to most word processors' Save function. To change the name of an existing file, use :saveas file. If file already exists and you want to overwrite it, use
:saveas!

file. This is conceptually the same as most word

processors' Save As function.

DISCUSSION There are a number of situations where it can be useful to have Vim save your file for you automatically. One is when you're working with files in multiple buffers and cycling between them. By default, every time you switch to a buffer Vim prompts you to save the current one first. Another is when you execute an external command on the current file. The command is passed the file's name, so if your buffer contains unsaved changes, the command won't see
2. The more common command to save a file is :w, however this always saves the file, even if it hasn't been changed. :up preserves timestamps and saves needless disk access.

20

Vim Recipes

them. The solution is to :set autowrite. This causes files to be automatically saved when you switch buffers and execute external commands. If you also want files automatically saved when you quit Vim, use :set autowriteall.

✪

The

:autowrite

functionality is not related to some word processor's concept of auto-

saving a file periodically in case of a crash. Vim does this automatically. You can also "write" a specific portion of a file to a new filename. By prefixing the :up command with a line range only the specified lines are written to the named file. For example, :20,30up 20-30.txt saves lines twenty to thirty of the current buffer to a file named 20-30.txt. Alternatively, select a portion of a file visually then execute :up filename and the text you selected will be written to a file named filename.

Visit http://vim.runpaint.org/ for latest updates.

21

SOLUTION To save the changes in the current file then quit use :x3. if you do need to save Vim warns you E37: No write since last change (add ! to override). If you're using multiple windows the above commands will act upon the current window. Vim will prompt you to save any changes. We use :x here because it only saves the file if it has been changed. In Normal mode you use ZZ ZZ. As mentioned above. thus preserving its timestamp and saving needless disk access. To
3.QUITTING VIM
PROBLEM You've finished using Vim and now you want to close the program. and exit Vim. To quit all windows use :qa (mnemonic: quit all). or just the current window) and what you want to do with your unsaved changes. The more usual suggestion for saving then quiting is :wq. To exit and discard your changes you use :q! (mnemonic: quit in a possibly dangerous (exclamatory) manner). You can also quit on the condition that there are no unsaved changes with :q.
DISCUSSION The way you quit Vim depends on what you want to quit (the whole program.
22
. if you're using a single window either :x or ZZ will save any unsaved changes.

whereas d deletes text described by a given motion.
DISCUSSION Vim doesn't just delete text.g. you can delete it all with x. to delete characters before the cursor use X. move your cursor over the character to banish and hit x (mnemonic: expunge). If you've selected a block of text visually.20d deletes lines 2dd. Otherwise. you've typed a paragraph which is no longer needed. seventeen through to twenty. If you'd rather nuke entire lines at a time use dd So. then. whose
24
. it's stored in "0. it saves it to a register first. but to delete words and other text objects you can use dmotion. which can be achieved with D.DELETING TEXT
PROBLEM You wish to remove some text from a file. A compromise is to delete the remainder of a line. e. the line would be changed to just A compromise. is that x deletes characters. This is fine for single characters. to delete the current line and the one dd. If you delete a small amount of text (less than a line).
SOLUTION In Normal mode. The difference. If your cursor was positioned after compromise in the above sentence. following it: 2dd Use a range prefix to delete the specified lines. :17. and you then hit D. For example. This deletes characters under and after the cursor. it's stored in a register named "-.

This allows you easy access to previously deleted text inasmuch as you can recall. The Undoing Mistakes recipe explains how to revert these deletions. whose existing…right up to "9. deletions.runpaint. say.
Visit http://vim.org/ for latest updates.Vim Recipes
existing contents are moved to "1. you can use :registers to view your recent "2p.
25
. the 3rd most recently deleted line with "2p Even more usefully.

then ap. then move upwards and downwards with k and j as normal. you'd position your cursor on the first character of the first line you're interested in. then move down 20 lines with 20j. so <Ctrl>-q exists as an alias. If you want to switch selection mode mid-selection hit v. to select the current character and the three that follow hit v.j. thus enabling you to perform a command that affects it. For example.
SOLUTION To select text character by character change to Visual mode with v. or 'columns' to the rest of us.
4. For example. then 3l. move one character to the right (l). or <Ctrl>-v. as appropriate. then 2j. the mouse. if you wanted to select the first two characters of the current <Ctrl>line and the 20 following. in Gvim.k. you use Visual Block mode with <Ctrl>-v4. In other words. hit <Ctrl>-v. then move the cursor as normal using the h.l keys. To select text by lines switch to Visual Line mode with V. you want to select a text like you would in a
GUI
word processor using either the keyboard or. To select text in vertical blocks. Windows® defines this shortcut for pasting text. To select the current paragraph: v. V.VISUALLY SELECTING TEXT
PROBLEM You want to interactively select some text by drawing a box around it. <Ctrl>-
26
. to select the current line and the 2 following it hit V. For example.

.runpaint. Regardless.g.-) Having selected text.
Visit http://vim. they can still be convenient when you're making complex selections or aren't really sure what you're doing.Vim Recipes
DISCUSSION As you get used to Vim's movement command. Here are some common actions: • Copy/cut it. o can be used to toggle the cursor between the beginning and end of the selection.
27
.org/ for latest updates. • Indent/unindent it. gq gq. • Format it. you'll have less of a need for the various visual modes. e. The point of selecting text is to operate on it.

COPYING. dw dd. thus saving you that extra keystroke . p inserts text after the cursor. Or maybe you want to copy some text from a web page into Vim. so 2p pastes the clipboard contents twice. To cut the current line.Y )). (Y is a synonym. For example. visually selected text. position your cursor appropriately. To paste the contents of a register into a file. yy works on lines instead.
SOLUTION To copy/cut text from Vim you must first select it. To cut the dd. The text is now in one of Vim's registers.
AND
PASTING
PROBLEM You want to duplicate text from one place to another. only it uses d (mnemonic: delete) and dd respectively. The syntax ymotion yanks the text defined by motion. For example. You can do so visually. then use the p (mnemonic: paste or put) key in Normal mode. p and P can be prefixed with a repetition count. dd To cut the current word. hit d. so 4yy would copy the current line and the three following it.
Vim calls copying yanking. y2w would copy the current and following words. you may want to move the paragraph you've just typed above the previous one. so to copy visually selected text use the y (mnemonic: yank) command. dw. or provide a
motion to the relevant command. As with many Vim commands. To insert the text before use P. Cutting is much the same.
28
. CUTTING.

Conversely. simply prefix the command with the register name. then :set nopaste afterwards. 6. With this setup on Linux. issue the :registers command. The most common symptom is that the pasted text is indented bizarrely.
29
. users could paste with F11+Shift-Ins+F11 F11+Shift-Ins+F11. effectively.org/ for latest updates. independent clipboards. To fix this. much like some operating systems do.
5
Registers are named with a " character followed
5.
DISCUSSION The solution above uses the concept of a single clipboard. When pasting text from external applications into a Vim instance Vim may clobber the text by attempting to be too clever. This happens when it cannot distinguish between entered text and pasted text.
Visit http://vim.g. To view the contents of the registers (both user-set and Vim-set). Alternatively. Again. to yank the current line to register "b use "byy To paste it use "bp "byy. "bp. Registers are actually far more powerful than this. for example. e. multiple. by a single lowercase letter. So. but also supports 'named registers'. Vim can work this way. To yank/delete/put using a named register. "+y yanks the current selection to the system clipboard. These are. consider using :set paste before you paste. this is a vast simplification.Vim Recipes
To paste text from the system clipboard use Shift+Ins in Insert mode or "*p in Normal Shift+ mode. as you can see. "a6.
:help registers
for details.runpaint. use :set pastetoggle=key to map a key to toggle paste mode.

SOLUTION Throughout this book I will discuss how to configure Vim options using the :set option or :set option=value syntax. In this book vimrc and gvimrc are treated as synonyms.
Unix/Linux Unix/Linux $HOME/. you want Vim to show line numbers all the time. This works. Displaying Line Numbers explains how.CONFIGURING VIM
PROBLEM You want your Vim preferences to persist over sessions. For example. All references in this book to vimrc refer to this path. but only for the current instance of Vim.vimrc
30
.
⇰
Location of vimrc
The default location of the vimrc file depends on your operating system.
Gvim reads vimrc then a gvimrc file located in the same place as vimrc. Identify your operating system. then note the corresponding path. but when you restart Vim you find that your preferences have been forgotten. If you specify these options in your vimrc file they'll be set permanently.

They are ignored by Vim.vimrc The vimrc is a simple plain text file.Vim Recipes
OS/2 $HOME/.org/ for latest updates. For example:
" Set the boolean number option to true set number " Set the textwidth option to '78' set textwidth=78 " Set the expandtab option to false set noexpandtab
A single quotation mark (") introduces comments. this is the general principle for adding any Command-Line command in this book to your vimrc. Open the filename specified in the sidebar and add one option per line using the option=value syntax (the ':' prefix is unnecessary).
31
. which is unlikely to be what you want.vimrc (or _vimrc) MS-DOS and Windows $HOME/_vimrc or $VIM/_vimrc Amiga s:.
Visit http://vim.
✪
Even if you don't want to specify any options in vimrc you should still create it.runpaint.vimrc or $VIM/. Indeed. but particularly useful for remembering what all of your preferences mean.vimrc or $VIM/. On
some systems Vim will act like the Vi editor in the absence of this file.

User preferences take precedence over system preferences. This prevents the directory-specific vimrc files from executing potentially dangerous commands. your preferences will be respected. and you don't include it in your vimrc. and anything else Vim's scripting engine supports.
Warning: There's the potential for security problems when using exrc. for example -.
32
. See Abbreviating Common Strings for an example. You can instruct Vim to include these files in your configuration by adding a source file line to vimrc for each config file. there are also system wide vimrc files. For this reason it's strongly recommended that you use :set secure in conjunction with exrc. However. The Vim documentation suggests adding set secure as the last line in your vimrc. For a simple example look at the usage of :autocmd in the Using Templates recipe. If a vimrc was placed
in your project directory without you knowing -. and will be used when you edit files in that directory.vimrc (or vimrc on DOS and MS Windows) in the project's directory. If you want a different configuration for a specific project you can :set exrc then include a . They can also include functions. This takes precedence over your vimrc.DISCUSSION The vimrc locations given in the sidebar are used for user preferences. conditionals. the system preference will be used.as a result of unpacking an archive.it could be used to execute arbitrary commands under your user account. if the system vimrc sets an option differently from the Vim defaults. This means that if you change an option set in the system vimrc. The example vimrc above is very basic. If your configuration becomes complex you may want to split it over multiple files.

and legal. In Vim execute :hardcopy.wrap:y
The printoptions line is a comma separated list of values that affect how Vim formats the document before it sends it to the printer.
DISCUSSION :hardcopy converts the current file to Postscript and sends it to the default printer.
SOLUTION In GVim there's a Print entry on the File menu. For
PDF
example. Linux/Mac users can install the CUPS PDF package to get a PDF printer. you can use this technique to print a file to PDF. The paper option sets the paper size. e.
7. For example. :set pdev=usblp1.syntax:y. letter. and a printer icon on the toolbar.g. You can specify that a different printer is used with :set pdev=printer. A list of options is at :help popt. assuming your PDF printer is called pdf:
set pdev=pdf set printoptions=paper:A4. If you have a printer installed7.
34
. on Debian/Ubuntu: aptget install cups-pdf. It accepts values such as A3.PRINTING
PROBLEM You want to print something from Vim.

duplex:off to print on only one side of the page. for example. see man a2ps for a complete list of features.org/ for latest updates.Vim Recipes
The syntax option determines whether the document is printed with syntax highlighting. a2ps can print two pages per physical page and custom headers. To use a different program add a stanza such as the following to your vimrc:
set printexpr=PrintFile(v:fname_in) function PrintFile(fname) call system("a2ps " . By default it has the value a which means that Vim only uses highlighting for colour printers.
Visit http://vim. If wrap has the value n. long lines are truncated.
35
. Other useful options are header:0 to stop a header from being printed. which is the default. a:fname) call delete(a:fname) return v:shell_error endfunc
The above example specifies that the GNU Anything to Postscript (a2ps) utility is used for printing. On Linux the lpr utility is used for printing. Lines are wrapped when wrap:y. A value of y forces highlighting. number:y to number lines.runpaint.

Or.
✪
When requesting help for a subject use <Ctrl>+d to auto complete what you've <Ctrl>+
typed.
DISCUSSION The :help topic displays documentation for the tag named topic in the Vim documentation. you've found help but find the output of the online help confusing. The tags are named with the following convention: Type of Topic Prepend Example
Normal mode command (nothing) :help x Visual mode command Insert mode command v i :help v_u :help i_<Esc> :help :quit :help c_<Del>
Command-line command : Command-line editing c
36
.GETTING HELP
PROBLEM You want help with Vim but don't know where to look.
SOLUTION Look up a topic in the online help with :help topic. Search it with the :helpgrep
pattern command. For example. :help :h<Ctrl>+d shows a list of help topics for commands <Ctrl>+ starting with :h.

org/ for latest updates. :help help displays the following8:
The strings in pink are synonymous tags for the current entry.
The documentation itself also uses several conventions that may not be immediately obvious.Vim Recipes
Vim command argument Option '
:help -r :help 'textwidth'
(The table above is excerpted from the Vim online help).
37
.
Visit http://vim. For example. The blue <Help> label indicates that in GVim the Help menu is the GUI equivalent of this command. For example.runpaint. If you're using a different colour scheme the colours may be different. :help can be shortened to :h or :hel. Command-line commands can be shortened to the point that they are still unambiguous. In this case. The :h[elp] notation uses square brackets to indicate the optional portion of the command. :help <F1> locates the same entry as :help help.
8.

the light green text are also hyperlinks. and jumps to the first one. so if your cursor is over it you can use <Ctrl>+] to follow it. It's also a hyperlink to an explanation of the option. Again square brackets are denote optional text. helpgrep takes a pattern and matches it against the locally installed documentation in much the same way as vimgrep did in Searching Over Multiple Files. The {pattern} notation describes a variable. Lastly. <Ctrl>+
The screenshot above identifies some further conventions to be aware of. See the Quick Fix List sidebar in Searching Over Multiple Files for more information
38
. For example. it's a placeholder for text that you must supply. :cwindow links to documentation for that command. If it finds any matches. it adds them to the quick fix list9.
9.The green text ('helplang') indicates an option. [@xx] means that you can follow the pattern by a two-letter language code.e. i. In this example.

runpaint. you'll need to run :helptags docs-path before helpgrep will see its documentation. so <Ctrl>+ using this key combination n times will take you to the place you were at n links previously.Vim Recipes
✪
Once you've followed a hyperlink (with <Ctrl>+]).org/ for latest updates. you can return to your previous <Ctrl>+
location with <Ctrl>+o.
39
. This works in a similar fashion to a web browser's Back button.
Visit http://vim. If you've installed a Vim addon.

EDITING
40
.

and <motion to unident it.
SOLUTION To start a line indented. this solution will be sufficient. >ap indents the current paragraph. <Ctrl>-<Shift>More powerful are motions combined with indent/unident commands.Vim Recipes
INDENTING LINES
PROBLEM You want to use whitespace (spaces or tabs) to indent lines from the left margin. if you're writing program source code. For example.
DESCRIPTION For many users. and <Ctrl>-<Shift>-d to unident (mnemonic: de-tab/indent). just press the tab key once for each level of indentation. you may want to visually represent the structure of your program by using indentation to show nesting. highlight them visually and press > to indent or < to unindent.org/ for latest updates. programmers regularly need more control over indentation because it's so important to their work. Or.runpaint.
Visit http://vim.
41
. To indent existing lines. However. If you're in Insert or Replace mode you can use <Ctrl>-<Shift>-t to indent (mnemonic: <Ctrl>-<Shift>tab). The syntax is >motion to indent the text described by motion. you may want to start your paragraphs with an indented first line. For example.

The :set list command makes literal tabs visible. and Vim's not expanding tabs (:set noexpandtab).Each press of the tab key should insert a certain number of spaces. It displays them as ^I.) The boolean expandtab option replaces tabs with spaces if true. :set softtabstop=8.✪
lines.Each press of the tab key should insert a literal tab character (padding with spaces if necessary). • Convert tabs to spaces . softtabstop specifies how many columns Vim uses when Tab is hit in Insert mode. Real tabs are displayed 8 character wide. To achieve this: :set tabstop=8 (the default). There are two main schools of thought: • Literal tabs . and :set expandtab. shiftwidth controls how many spaces are inserted when using the >> << technique >>/<< described above. padding with spaces where necessary. (It can be seen. each indentation level is a single tab. If it's less than tabstop. or the automatic indenting used with source code. Vim indents with tabs. Tabs are now replaced with 4 spaces. leaves them alone if false. The settings you need are :set tabstop=8. :set shiftwidth=8. that you'll typically want to make softtabstop and shiftwidth equal. and uses
a similar notation for other non-printable characters. then. and :set noexpandtab. spaced tabs 4 characters wide. Tabs are now eight columns wide. :set shiftwidth=4. The $ symbol is used to show the end of
A contentious issue among programmers involves how the tab key should work. for reasons of consistency and sanity.
42
.

• Secrets of Tabs in Vim by Ted Logan.runpaint.
43
.Vim Recipes
These settings are not retroactive. To make an existing file honour your indentation preferences use the :retab! command.
Visit http://vim.
SEE ALSO • Tabs versus Spaces: An Eternal Holy War by Jamie Zawinski.org/ for latest updates.

If you wanted to delete the word fandangle you'd need to press x nine times: once for each character. delete yank Deletes. or reformat the current paragraph. You could simplify the process by prefixing x with a count: 9x However. you can delete the character under the cursor with x. you want to delete next two words. For example.SELECTING TEXT
WITH
MOTIONS
PROBLEM You want to define an area of text for a command to operate on without leaving Normal mode. The motion for a word is w.
SOLUTION In Normal and Visual mode operator commands can be followed by motions which describe what text they should operate on. so you can delete the word more easily with dw dw. The following table shows some common operators which understand motions. Operator Action c d y Description
change Deletes then enters insert mode. For example.
44
. as opposed to the character-by-character approach of x. how many characters are in the word. They can be thought of as a set of directions the operator should use to select text. Instead you can use the dmotion command which deletes the text selected by motion. and would be totally impractical if you wanted to delete multiple words at once. Copies to a register. that requires you to know 9x.

Here are some common motions: Command Moves Left count characters.runpaint. indent Shifts text left.
unindent Shifts text right.Vim Recipes
gq > <
format Reformats. then enter Insert mode. Down count characters.
Visit http://vim. Let's look at some examples: y10h Copy the previous 10 characters to a register. To the first character of the line. d$ Delete from the current character until the end of the line. Up count characters.
We can combine operators and motions to select text then operate upon it. Right count characters.
45
. c2j Delete the current line and the one below it. To end of the line. To end of the line count-1 lines downward.org/ for latest updates.
counth countl countj countk
$
count$
0
countfchar To the countth occurrence of char to the right.

A few of the available commands follow: Command Selects
countaw countiw countaW countiW countas countis countaB countiB counta" counti"
count words count non-blank characters count sentences count […] or {…} blocks count quoted strings
So.it even sounds sensible10. you'd only delete that. position your cursor anywhere inside it then hit dap Delete a dap. the cursor over. this is not a bug.
paragraph .
46
. including white space. not character.
They're frequently just a motion command prefixed with either a or i. or just the white space. as long as your cursor is over T. Vim supports additional motions for operating on text objects. One of these is aw (mnemonic:
a word) which would do the right thing in both examples above because it considers what object.
10. The a prefix indicates that the whole object will be selected. if you were on the h. to delete a paragraph.DISCUSSION Motions aren't very intelligent. No. and can be used with the same operators. the i prefix selects the inner object without white space. Say you wanted to delete the word This with dw That works dw. Text object commands are very similar to motions.

excluding the digit itself. For example.org/ for latest updates. in which case it describes the text matched: extending from the current cursor position to the penultimate character matched by the pattern.Vim Recipes
A motion can also be a regular expression.runpaint. d/\d deletes from the current character to the first digit.
47
. The syntax is /pattern: a solidus followed by a regular expression.
Visit http://vim.

To repeat a command entered in Command mode hit :. However. The second approach requires fewer keystrokes so is clearly preferable if you know in advance how many times you want to repeat a command. the period command lets you make that decision incrementally. It lets you say “do that again”.
DISCUSSION The period command helps automating repetitive tasks with the fewest keypresses.
SOLUTION The period . the history will be limited appropriately. then deletes the new current line.. after executing the command. repeats the last command entered in Normal mode. dd. you can prefix it with the integer n. it repeats the command twice. If you type the first few letters of the command before using ↑. deletes the current line. but in only one character. For example. In other words. dd deletes the current line.REPEATING COMMANDS
PROBLEM You've entered a command and want to repeat it without re-typing it. then deletes the new current line. The above example rewritten in this way is 3dd 3dd. If you know you want to execute a command n times.
48
. then ↑ to scroll back through your command history.

command. you may wish to execute a different command on the same text.. The discussion above assumes that the last command needs to be repeated exactly. Be aware that having done this. then make that change.org/ for latest updates.e.
Visit http://vim. will result in command being executed 2n + 1 times..
49
.runpaint. Instead. followed by . followed by n. Jump to the line of the last change with the Normal mode command '.. i.Vim Recipes
You can combine these approaches by prefixing the period command with an integer to say “do that n times again”: n. if you use the period command again it will repeat your previous repetitions.

these commands accept motions. guw Lowercases current word. or the selection in Visual mode. For example: VU Uppercase current line. (Note: This only works in Visual mode.
SOLUTION ~ Toggles the case of the current character in Normal mode. U Uppercases highlighted text.CHANGING
THE
CASE
OF
TEXT
PROBLEM You want to change the case of a character or block of text. otherwise U will undo the changes made on the current line).
50
. you may want to change bob to Bob. otherwise u will undo your last change).
DISCUSSION As normal. (Note: This only works in Visual mode. u Lowercases highlighted text. For example.

hit :. you can install the titlecase plugin. you can use the following regular expression:
s/\<\(\w\)\(\w*\)\>/\u\1\L\2/g.Vim Recipes
To convert a string to title case. If you use this regularly. initial capitals.
Select the text you want to convert.
Visit http://vim. consider remapping a key to execute this command.
51
.runpaint.e. then
enter the regular expression. For example:
nnoremap <F7> :s/\<\(\w\)\(\w*\)\>/\u\1\L\2/g<CR> vnoremap <F7> :s/\%V\(\w\)\(\w*\)\%V/\u\1\L\2/g<CR>
Alternatively.org/ for latest updates. i.

which filters the file through the external sort utility.2. you'd like to organise it alphabetically.
52
. VIM . For example. Hit : and Vim will display :'<. if you've made a list of your books with one title per line.2 (2008 Aug 9.g.e. If you're using an older version of Vim you'll need an external sort utility. You can sort the entire file by executing :!%sort. So if you're using v7 or later you can sort an entire file using :sort.
SOLUTION Vim version 7 introduced a :sort command.
✪
You can find your Vim version number with the :version command.'>!sort). 2. which indicates version 7. compiled Mar 19 2009 15:27:51).Vi IMproved 7.SORTING TEXT
PROBLEM You want to sort a selection of text or an entire whole file. e. Type !sort (i. To sort part of a file: 1. The first line of
output contains the version number. execute :'<. Linux/UNIX users should already have sort installed. Select the area you're interested in. 3.'>' which refers to your selection.

If you're using Vim 7+: :sort! Reverses the sort order. i. If you require a different type of sorting you need to pass options to the command./} ant 1 zebra 12 ant 1 6 zebra fish 12 6
Dog 7 frog 11 fish
Visit http://vim. u Deletes duplicate lines (keeps unique lines).e. For example.Vim Recipes
DISCUSSION Both methods above sort lines alphabetically.org/ for latest updates.
53
. :sort /pattern/ Ignore text matching pattern when sorting. i Ignores case while sorting.runpaint. the following table describes how the set of data in the Original column is transformed for the given invocations of :sort. sorts in descending order: z-a.
Original :sort! :sort in :sort i /^. 100-0. :sort flags The sort command can be followed by a series of flags which can be combined in any order: n Sorts by the first decimal number in the line.

to view a directory listing on a POSIX system: :!ls. For example. For example:
%:p Makes the filename a full path.
SOLUTION Invoke the program using the :!program syntax. For example. If you need to pass the current filename to the command as an argument. you want to view a list of the other files in your project by getting a listing of the current directory. use the % wildcard.txt executes wc aristotle-essay.txt. executing :!wc % from aristotle-essay. possibly having it operate on the current file.
Visit http://vim.
⇰
Filename Modifiers
You can alter the filename represented by % by following the wildcard with a modifier.org/ for latest updates.runpaint. Or you want to find mistakes in the essay you're working on by passing its filename to the diction utility. For example.
55
.Vim Recipes
EXECUTING EXTERNAL COMMANDS
PROBLEM You want to run a program from within Vim.

DISCUSSION The concept is that Vim suspends itself. asks your system to execute the command. then. shows you its output. You first execute. say.
You can use :redir > file if you want to save the output of a command to a file.%:. Makes the filename relative to the current directory. you can insert your kernel version with :r!uname -v. you can execute it like this: :silent
command.txt. %:e Removes everything except the filename extension. The output for command will be saved in the file /tmp/output. <Enter>. %:t Removes any directories before the actual file name. If you don't want to see the output of the command. To stop output redirection execute :redir END. once the user presses <Enter> returns you to Vim. For example ~/work/foo. :redir > /tmp/output. if you're using a POSIX system. For example. and displayed on the screen. You can use :r!command to execute command and read in its output to the current file. then :!command. For example ~/work/foo.txt ⇒ foo.txt ⇒ txt. (To also hide any error output: :silent! command). (You can combine :silent command and :redir file to redirect a command's output to a file without seeing it on screen).
56
.

vim. you could save it to $VIMHOME/ Session. You'd like Vim to do all this automatically. If you used a different filename for your session: vim -S
file.runpaint.Vim Recipes
MANAGING SESSIONS
PROBLEM Every time you work on a project you need to manually open all of the files it comprises. To make Vim work this way you simply use a fixed name for the session variable. To save a session: :mksession. to specify your own filename execute :mksession file instead. For example.
:source Session. If you're already inside Vim. To restore a session invoke Vim with the -S flag from the same directory you saved Session.vim. readjust the window size.
DISCUSSION Applications such as Mozilla Firefox use the concept of a global session file which is overwritten every time you use the program. Vim saves the session information as 'Session.vim in: vim -S.g.org/ for latest updates. etc.vim' in the working directory. To overwrite an existing session follow the command with an exclamation mark: :mksession!.
57
.
nmap SQ <ESC>:mksession! ~/vim/Session. e. you can load a session by sourcing the session file.
SOLUTION Use sessions. You could add a mapping something like this to your vimrc.vim<CR>:wqa<CR>
Visit http://vim.

their session file is used.vim' end endfunction autocmd VimEnter * call RestoreSession()
You can extend this in arbitrary ways to suit your working environment. This is useful for one-project-per-directory organisation. you could save a session with SSAwork<Enter> Later. as described above.vim/Session. just hit SO<Tab> to cycle through the saved sessions.(SQ for Session Quit). For example. when you want to restore the session but can't recall its name. To automatically restore this session when Vim is called without SQ arguments add the following:
function! RestoreSession() if argc() == 0 "vim called without arguments execute 'source ~/.
58
. Just type the name of the session you want to load and hit <Enter> <Enter>. All you need to do is enter a name and hit <Enter> <Enter>. Another is to simply hardcode a list of directories whereby if they are the file's current directory or parent directory. a more granular approach is suggested below:
nmap SSA :wa<CR>:mksession! ~/sessions/ nmap SO :wa<CR>:so ~/sessions/
Session Save As saves the open files and prefills the command line with the command to save
the current session in a ~/sessions/ directory. then prefills the command line with the command to
load a session file. You can use <Tab> completion in both cases.
Session Open also saves the open files. If you don't just want one global session file. SSAwork<Enter>. One approach is to only restore a session if it exists in the current file's directory.

align.
60
. and many more aside.
DISCUSSION The formatter that you use depends on the type of content you are producing.FORMATTING
WITH AN
EXTERNAL PROGRAM
PROBLEM You want to reformat text with a program other than Vim. For example:
:set equalprg=tidy\ -indent\ -q
You can now select the text you want to format. you want to use the
W 3 C 's
'tidy' utility to format
HTML. You can reformat the entire file with 1G=G 1G=G. and quote text in every conceivable way. justify. par is a popular choice. Here are a couple of suggestions of programs to use for specific file types:
Text If you want to format normal text using an external program. then hit =. along with any arguments it should be passed. It can wrap. For example.
SOLUTION Set the equalprg option to the name of the program you want to use.

reformatting a specific section of the file.
XML
HTML Tidy can be used to format XML as well by passing it the -xml option.org/ for latest updates. You can use the --show-body-only true option if you want to be able to do this. as shown in the example above. Tidy doesn't perform as well on fragments because of lack of context.runpaint. Alternatively. but like many formatters of markup languages. You can specify options on the command line. If you want to specify a lot of options.
61
.Vim Recipes
HTML/XHTML HTML/XHTML Use HTML Tidy. and point tidy to it: tidy --config file. At a minimum you probably want to use:
:setlocal equalprg=tidy\ -utf8\ -indent\ -q\ -f\ /tmp/err
Then you can reformat your file with 1G=G One caveat is that this won't work correctly for 1G=G. put them into a config file.
you can use xmllint:
:set equalprg=xmllint\ --format\ -
Visit http://vim.

If Vim guesses incorrectly. As usual. so need to change its line endings. for
62
. Luckily. perhaps because a tool expects them that way. you wish to convert a file to use different line endings. Microsoft Windows uses a carriage return followed by a line feed (CRLF). its format is guessed. If your file is mangled (some lines ending with CR. Or. some with LF. thus forcing the file to convert to the given format. Unix/Linux uses a line feed (LF). you can insist on a specific file format with :e ++ff=format. or mac for Apple Mac. and &ff is set appropriately. The above assumes that a file's line endings are at least consistent. When a file is loaded.
SOLUTION Specify the desired file format with :set ff=format. Vim handles this situation transparently most of the time. they disagree on the control character that terminates a line.
DISCUSSION Different operating systems have different notions of what constitutes a line in a text file. you must then save the file to make the changes permanent: :up. That is.WORKING
WITH
DIFFERENT FILE FORMATS
PROBLEM You're editing a file created on a different operating system. where format is dos for Microsoft Windows/DOS files. This would be a matter of pedantry were it not for users of different operating systems sharing files. Specifically. unix for Unix/Linux. each line ends with the same character(s). and the Mac uses a carriage return (CR).

Lastly. if you have some Mac line endings with dos/unix or Unix/Linux line endings with mac. This can be fixed with search and replace: :%s/\r//.org/ for latest updates. use :%s/\r/\r/g.runpaint.Vim Recipes
example) you will likely see stray control characters such as ^J or ^M peppered throughout.
63
.
Visit http://vim.

TYPING
64
.

To highlight spelling errors just execute :set spell. you should already have the dictionary installed. To change this use :set spelllang=code. If you're not and it doesn't. • Word is in the dictionary but not capitalised. Otherwise. • Word is spelled incorrectly for this region.runpaint. For instance.
65
.
DISCUSSION Spelling errors are highlighted in one of four colours depending on the type of error: • Word is not in the dictionary. Vim should prompt you to download it.
SOLUTION To enable spell checking you first need to ensure that Vim knows which language you're typing in. If you execute :echo &spelllang you'll see the language code that Vim thinks applies. To remove the highlighting: :set nospell. For example.
Visit http://vim.Vim Recipes
SPELL CHECKING
PROBLEM You want Vim to highlight misspelled words and suggest alternatives. If you're spell checking in American English. For instance en. color in British English.org/ for latest updates. • Word is classed as 'rare'. see the
Getting Dictionaries sidebar of Auto-Completing Text. I use :set spelllang=en_GB.UTF-8.

you presumably want to correct them. If you hit z= over a misspelled word you'll be presented with a list of suggested spellings. and region-specific misspellings are skipped).e. you can use ]S and [S to only jump between words not in the dictionary (i. rare. If a correctly spelled word is highlighted as an error. you can add it to your personal dictionary with zg This prevents it from being marked as an error in the future. Once the spelling errors are highlighted. Conversely. if an incorrectly spelled word isn't highlighted. zg. Similarly.
66
. you can add it to the bad word list with zw zw.You can jump to the next spelling error after the cursor ]s and jump backwards with [s [s. Enter the number corresponding to the correct spelling and hit <Enter> <Enter>.

the template contents will be inserted.org/ for latest updates.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.xsd" xml:lang="en"> <head> <title>Document Title</title> </head> <body></body> </html>
Visit http://vim. For instance.1//EN" "http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.org/TR/xhtml11/DTD/xhtml11. you write HTML documents and don't want to type the standard preamble every time.Vim Recipes
USING TEMPLATES
PROBLEM You create documents containing boilerplate text and would like to avoid typing it.dtd"> <html xmlns="http://www.w3.
67
. You must first create a skeleton document.g.org/MarkUp/SCHEMA/xhtml11.w3.:
<?xml version="1. e.
SOLUTION Use templates and associate them with a file extension.w3. When a new file is created with an extension for which a template is available.runpaint.

DISCUSSION Once you have created a document from a template you have to insert text at various predefined positions.html.
then start typing between the
<body>…</body>
tags.%:e
Now. For instance. This involves including some notation in the template file that indicates where your input is required. For example.1//EN"
68
. (You may also want to make this file read only so you don't modify it by mistake).0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. The traditional solution is to use placeholders.vim/skel/tmpl. It then reads the template file into your new file's buffer.html file automatically. every time you open a new file Vim checks ~/. then providing a method to jump between them. the XHTML above would be inserted into the page. for the XHTML template. Navigating between these
points in the document. Add the following to your . Here's the previous template with placeholders added:
<?xml version="1.html. is cumbersome.vim/skel/tmpl. you have to change the contents of
<title>…</title>.vimrc:
autocmd! BufNewFile * silent! 0r ~/. ~/.Save this document in your Vim directory with the corresponding file extension.vim/skel/ for a file whose name starts with tmpl. if you added the template above then invoked Vim with vim page. and ends with the extension of the file you're creating.g. e. which are the same every time you use the template.

While we're at it.}%<cr>c/%/e<cr> "Jump between %VAR% placeholders in Insert mode with " <Ctrl-p> inoremap <c-p> <ESC>/%\u.w3.w3. we'll define a function (LoadTemplate())
to replace the autocmd line we added earlier.org/MarkUp/SCHEMA/xhtml11.vim/skel/tmpl. but let's stick with %VARIABLE% for the sake of example.xsd" xml:lang="en"> <head> <title>%TITLE%</title> </head> <body>%BODY%</body> </html>
The placeholder notation is arbitrary. Add the following to your vimrc:
function! LoadTemplate() silent! 0r ~/.org/ for latest updates.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.
69
.}%<cr>c/%/e<cr>
If we create a new HTML file now this is what we see:
Visit http://vim.%:e " Highlight %VAR% placeholders with the Todo colour group syn match Todo "%\u\+%" containedIn=ALL endfunction autocmd! BufNewFile * call LoadTemplate() "Jump between %VAR% placeholders in Normal mode with " <Ctrl-p> nnoremap <c-p> /%\u.org/1999/xhtml" xmlns:xsi="http://www.dtd"> <html xmlns="http://www.w3.\{-1. Now we need a way to jump between them.org/TR/xhtml11/DTD/xhtml11.\{-1.Vim Recipes
"http://www.runpaint. and <Ctrl>-p (menmonic: <Ctrl>-
placeholder) seems reasonable.

See below for ways to automatically jump to the placeholders and for inserting smaller code fragments by using snippets.
70
.

and pretend the whole situation had never occurred. you've made a mistake while reverting a mistake. You can undo all recent changes on the current line with U.
SOLUTION Use the undo feature. Or. and you'd like to revert that. worse. subject to peer review. Hit u in Normal mode or :u in Command mode. For example.
Visit http://vim. To redo a change that was undone use <Ctrl>+R or :redo.org/ for latest updates.Vim Recipes
UNDOING MISTAKES
PROBLEM You've made a mistake while editing and you'd like to revert it. To undo multiple times either repeat the command or prefix it with a digit indicating the number of times. to undo the previous change and the one before that: uu uu. For example. then travel forward 20 minutes with :later 20m. the cure for cancer. You'd kinda' like to retrieve it. you've just deleted the paragraphs containing. To return to how your file looked 1 hour ago use :earlier 1h.
71
.runpaint. <Ctrl>+ You can also jump backwards and forwards through your edits by time.

If you hit u again you'd undo moose and get back to elephant. You then entered calf on a new line and hit u. Vim. This undid the addition of calf so now your file just contains the word elephant. Hit g.(and g+ to move forwards) moves between these branches.
Imagine you opened a new file and entered elephant. elephant calves are particularly photogenic) because you made an edit after undoing (by adding moose). The branch represents the state of the file before you undid. Undo branches to the rescue. g. Here are the events represented diagramatically:
Vim implicitly created an undo branch each time you hit u.DISCUSSION The undo/redo behaviour described above should be familiar to most users as it mirrors that of many other applications.and your file will now contain elephant then calf.
72
. however. Next you entered moose. No matter how many times you do this you'd never get the calf back (which is unacceptable. extends this concept into the idea of undo
branches.

⇰
Getting Dictionaries
If you specify your language with :set spelllang=lang-code.runpaint. using the sidebar for reference. then point Vim to it with :set dictionary=file. e.txt. Get one. be offered suggestions for words that start that way.g. For example.
SOLUTION To auto-complete a word Vim needs a list of possible words. :set spelllang=it for Italian. If your file already contains the word multiplicand.org/ for latest updates. If multiple matches <Ctrl>+ are found you'll be presented with a list from which to choose from.
Visit http://vim. If this doesn't work for you see :help spell and vim/runtime/ spell/README. The 'complete' options controls where Vim looks for possible matches. then Vim can use it to autocomplete multip. then pick one. Then add the dictionary to list of places Vim looks for words: :set complete+=k.Vim Recipes
AUTO-COMPLETING TEXT
PROBLEM You want to be able to type the start of a word and then have Vim complete it. Vim should automatically download the correct dictionary for you and set it up. Simply hit <Ctrl>+n after the p to complete the word. you want to type multip. An obvious source is the current file(s).
73
. Another source of words is a dictionary.

<Ctrl>If one is found. *. Consult :help ins-completion for more details. a drop down list is displayed to choose between them. Languages that don't have Omni-Complete functions available can use their syntax highlighting definitions to achieve a similar affect. The Vim documentation suggests adding the following stanza to your vimrc. then invoke OmniCompletion to find that Fixnum objects support methods such as %. and reserved words. For example. You select the type of completion that you want using :SuperTabHelp.
DISCUSSION Vim can use pretty much any word source imaginable. These typically allow context-sensitive completion of method names. is that some popular programming languages already have Omni-Completion functions which are enabled automatically. <Ctrl>-x <Ctrl>-f searches for the filename that starts with the text before the cursor. If multiple filenames are found. for programmers at least. Vim version 7 and above supports Omni-Completion. using Ruby I can type an integer. after any :filetype command. <Ctrl>.Auto-complete can also be used to lookup synonyms for the current word. objects. :set complete+=s. then instruct Vim to use it with :set thesaurus=file.
✪
Eric Van Dewoestine's SuperTab plugin lets you use the <Tab> key to auto-
complete text. then just hit <Tab> after a word to see a drop-down menu of completion choices. a period. Even better. Get a thesaurus file. it is inserted before the cursor. which allows custom functions to generate possible completions dynamically. to enable Omni-Completion using the best available method:
74
. and +.

DISCUSSION The abbreviation feature is smart enough not to expand abbreviation names that occur as part of another word. type the name of the abbreviation (myUrl in this case) and then hit <Space> or <Enter> The name of the abbreviation is replaced with <Enter>. Useful abbreviation names are easy to type. where name is the text you want replaced.ABBREVIATING COMMON STRINGS
PROBLEM You regularly have to enter the same text. which is both annoying and error prone. but don't want to. its payload. Instead of typing http://example.com/.
SOLUTION Use Vim's abbreviations feature to map concise abbreviations to frequently entered text. For instance. but its telepathic functionality is suboptimal. To use it. but will not appear in normal text. The syntax for defining abbreviations is :iabbrev name payload. then uppercase the first letter. To create the aforementioned abbreviation we use the :iabbrev command: :iabbrev myUrl http://example. myUrl and have it replaced with the address.com/ every time. and payload is what it should be replaced with. say. you want to enter. The convention I use is to prefix them with
my. (If you use a programming language that prefers
76
. if you use Vim to write e-mail you may often mention the URL of your website.

For example. You can then source it from your vimrc.
77
.runpaint.) You can also abbreviate commands.
Visit http://vim. I suggest keeping your abbreviations in an abbreviations file in $VIM. you may see clashes. then populate it with your abbreviations:
iabbrev myUrl http://example. you can create the file by running vim $VIM/ abbreviations. if you wanted to type :docs instead of :help you could map one to the other with :cabbr docs help.com/ iabbrev myEmail user@example. Either stop using Java®.com
Then in vimrc just write source $VIM/abbreviations. or disable abbreviations for the source code.Vim Recipes
"camelCased" variable names. For instance.org/ for latest updates.

On Linux this is set with the $LANG variable. To override this use :set encoding=utf-8.
If you're using Vim from a terminal your terminal software must also be configured to use UTF-8. For example.
78
. your changes would be written in that encoding. Or you want to type a symbol such as ±.
When editing files their current encoding is maintained. To force UTF-8 for all files use :set encoding=utf-8 fileencodings=.
⇰
Enabling UTF-8 Support
Vim uses the encoding specified by the user's environment. set up Vim to use UTF-8 by following the sidebar. It makes this process far easier. so if you opened a file in ISO-8859-2. so need to insert accented characters.INSERTING ACCENTED
OR
"FOREIGN" CHARACTERS
PROBLEM You want to type characters which don't exist on your keyboard. you want to type some words in another language.
SOLUTION If you haven't already. Instructions for that are outside the scope of this recipe.

type e. the unadorned character. For example. < 0 2 9 = Grave Acute accent Circumflex accent Tilde Macron Breve Dot above Diaeresis Cedilla Underline Stroke Double acute (Hungarumlaut) Ogonek Caron Ring above Hook Horn Cyrillic Meaning
Visit http://vim. This method can also be used to produce translations of characters in a given script. to insert an e acute (the last letter in café) you hold down <Ctrl>-K.runpaint. The following table shows the different types of characters you can produce: Character ! ' > ? ( .
79
.Vim Recipes
To insert an accented character you press <Ctrl>-K.org/ for latest updates. _ / " . <Ctrl>then type an apostrophe ('). then another <Ctrl>character indicating the accent type. : .

Vim refers to printable. For example. but that's mainly because it's so dense. you could enter either <Ctrl>-V xe9 or <Ctrl>-V 233 <Ctrl><Ctrl>. to lookup the code.+-. It lists. and the character code in decimal. Hit <Ctrl>-V. See :help keymap and :help termencoding for more details. to produce the ± sign you hit <Ctrl>-K-+<Ctrl>. or any other reference. the character's internal name. Thus.
80
. in columns. A list of digraphs available on your system can be obtained with the command :digraphs. caps: Hebrew Some Latin/Greek/Cyrillic Bopomofo Hiragana Katakana
DISCUSSION This method of input is most suitable for occasionally typing unusual characters. non-ASCII characters as digraphs. If you're one of the slackers who haven't memorised the Unicode specification yet.233. the literal character. we can generalise the <Ctrl>-K approach for any <Ctrl>character we know the name of. The internal name :digraphs lists corresponds with the shortcut table above. Continuing the above example of producing é. You can also insert characters using their character code. The output may appear chaotic. you can use the :digraphs command. That is to say. then type the code in either <Ctrl>hexadecimal or decimal. Vim supports most input methods.* % + 3 4 5 6
Greek Greek/Cyrillic special Smalls: Arabic. the internal name for é is e'. For regular use.

For example. it would try to open a file named your in your path. then. To see what it's currently set to execute :echo &path. so if your cursor was over the word your.
SOLUTION Position your cursor over a file name then hit gf (mnemonic: go to file or get file) in Normal mode.vimrc by opening it with Vim. For example.Vim Recipes
OPENING
THE
FILE NAME BENEATH
THE
CURSOR
PROBLEM You have a file name under your cursor and would like Vim to open it. Your path is a list of directories in which Vim searches for the named file.vimrc.
If your cursor was anywhere over ~/. The path is a comma-separated list of directories.org/ for latest updates..
81
.. instead. Vim doesn't care if the word under the cursor looks like a filename. (This assumes that you're using Linux where ~ is shorthand for the user's home directory).runpaint. some of which have special significance:
Visit http://vim. consider a file like the following:
Edit your ~/. program source code often references other files from which it includes functionality. gf would try to open your Vim configuration file. You want to quickly open such a file.

. Each level of outline links to the relevant file. I like gf to search recursively downwards from the current directory so I append .com via SFTP. Vim also lets you follow URLs in this way. to open the HTML in Vim. The Indentation Folding sidebar in Manually Creating Folds describes one approach to outlining in Vim
82
. then open it for editing in Vim.
A path that ends with a semicolon is searched recursively. means to first search in /usr/share/doc. • To open files referenced in my version control system's commit e-mails.. so you can gf on http://example./**. or sftp://example. fetch README.
The directory containing the current file. I use it when: • Log files are referenced in e-mail alerts.com/.com/README to connect to example. up the directory hierarchy. then /usr/. • To view source code for external modules when writing source code. • When outlining11 a project that consists of multiple files. then /usr/ share/. For example. For example /usr/share/doc.
*
A path that ends in an asterisk is searched recursively downwards.
DISCUSSION This feature has a surprising amount of uses for something so basic./** to my path like so: :set path+=.
11. /home/ kate/* would search all of user kate's home directory. then /.

Vim complains. If your filename is followed by a line number. foo. To make this behaviour the default consider a key remap: :nnoremap gf <C-W>gf. To open it in a new tab use <Ctrl>w+gf <Ctrl>w gf.runpaint.txt:10 you can jump to the given line with gF gF.g.
Visit http://vim. I don't use gF so I have remapped it to create the given file: :nnoremap gF :view <cfile><cr>.Vim Recipes
By default gf opens the file in the same window. If the filename you use gf on doesn't exist.org/ for latest updates. e.
83
.

rather than replacing the current one.
DISCUSSION The !!command syntax executes command and replaces the current line with the output.12. as all UNIXbased systems should. count!!command actually filters count lines through
command and returns the result. it has the effect I've described.
SOLUTION Use !!date in Normal mode.INSERTING
THE
DATE
PROBLEM You're typing a document and want to insert the current date. you can call Vim's strftime() function. which I believe is the majority. The advantage is that it inserts the output of date on the next line. Alternatively. The solutions above assume that you have a date executable in your PATH. This will work on all systems which support the strftime system call. e.g.
12. This is why
the text on the current line is replaced with the date. A similar same effect can be achieved with :r!date. This is in fact an oversimplification. strftime("%c"). For example. To control where the date is inserted see the following paragraphs. I understand that Windows users have to use !!date /t. but when count is omitted. you're composing a letter and want to include today's date at the top.
84
.

by all means remap a key to do so.
:inoremap <F7> <C-R>=strftime("%c")<CR> :nnoremap <F7> "=strftime("%c")<CR>p
I suggest the use of !!date because it doesn't waste a function key.org/ for latest updates. I find it more memorable.Vim Recipes
You can map this function to a function key.
85
.runpaint. For example. and.
Visit http://vim. the following commands map <F7> to insert a date stamp after the cursor. personally. If you intend to insert dates regularly.

86
.html.
Follow the installation instructions on the script page. For example. snipMate is distributed with a collection of snippets for common file types. table is the trigger. to enter a HTML <table> you want to type table<Tab> then have Vim <Tab> produce:
<table border=" "> <tr><th> </th></tr> <tr><h> </th></tr> </table>
SOLUTION Use Michael Sanders' snipMate plugin.<Tab>. the text that is inserted after typing trigger<Tab> <Tab>. which provides a subset of the snippets feature of the
Textmate. so want to expedite the process by typing a few letters then have Vim produce the boilerplate text. vim test.INSERTING SNIPPETS
PROBLEM You repeatedly type the same constructs. and the resultant HTML is the
snippet. the text you type. :help snipMate. e. Type table<Tab> The <table> given above should be inserted <Tab>. editor. then open a HTML document with Vim. into your document. To see a list of
snippets available for the current buffer execute <Ctrl>-R <Tab> To write your own see <Ctrl>. In the above example.g.

Ruby on Rails. jQuery.
87
. HTML authors may want to enter an <option> element like the following:
<option value="placeholder">placeholder</option>
Visit http://vim. rSpec. • A general collection by Ron Damen. in the above output represent tab stops: the positions where the nth <Tab> after the trigger will move the cursor to.com: • Scala snippets by Tyler Weir. • Ruby.org/ for latest updates. For instance.g. His cursor is placed in position 1 so he can enter the border size. And so on.runpaint. Consider again the <table> example:
<table border="1"> <tr><th>2</th></tr> <tr><h>3</th></tr> </table>4
The numbers.Vim Recipes
✪
Several snipMate users have made their snippets available on GitHub.
DISCUSSION The power of snipMate comes from how it lets you navigate the snippet once inserted. 1. etc. the user types table<Tab> to insert <Tab> the snippet. So. He then hits <Tab> again to position his cursor in 2 so he can enter the name of the header for the first row. e. Some constructs require user-entered text to appear multiple times. snippets by Martin Grenfell and Travis Jeffery.

org/TR/xhtml11/DTD/xhtml11. globally. but other than that snipMate can be used to achieve the same effect. snipMate lets you enter the text in value="placeholder">. That said. Abbreviations are typically defined <Tab>. The forthcoming is intentionally opinionated and simplified because a detailed analysis of every possibility is beyond the scope of this book.In this example.
⇰
Comparison of Techniques to Auto-Complete Text
We have discussed various approaches to automatically inserting text in this chapter. please let me know. There is also a similar snippet engine called XPTemplate. For example. if there are any factual errors.
Abbreviations can be used to replace a piece of text with another piece of text after pressing <Tab> They differ from snippets in two key respects. whereas snippets are defined for specific filetypes.dtd">
This can trivially be adapted to insert whatever boilerplate HTML you desire. For instance.
SnipMate has a trigger named docx which inserts the XHTML 1.
88
.1//EN" "http://www. and have it copied into >placeholder< as you type.w3. The advantage of this approach is that it doesn't require the installation of any plugins. whereby opening a file whose name ends with that extension causes the skeleton document to be inserted into the buffer.
Templates can be used to associate a skeleton document with a file extension.1 doctype:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. To learn more about snipMate and its features see :help snipMate. a trigger of for could
13. so let us recap13. placeholder is placeholder text that needs to be entered twice.

arguably.
Insert-mode auto-completion can auto-complete text based on what has already been typed or the grammar of the current file type. In general.
89
. Where the two's functionalities overlap. snippets have the notion of placeholders that can be tabbed between. or a Ruby for loop when editing Ruby code. or a language keyword. This form of auto-completion augments
snipMate: use the former to complete unique definitions and names in the current file.
Visit http://vim.Vim Recipes
insert a C for loop when editing C source code. snippets can do everything abbreviations can. use the latter to complete pre-defined snippets. More importantly.org/ for latest updates. you can auto-complete a variable name that you have declared previously. hit <Tab> and is. For instance. and those
that it includes. easier <Tab>). snipMate has a simpler interface (type a trigger. and more.runpaint. to configure.

NAVIGATION
90
.

runpaint. A document consists of paragraphs separated by newlines.
Visit http://vim. Sentences are collections of words which are separated by spaces. Paragraphs contain one or more sentences which begin with capital letters and end with periods.Vim Recipes
NAVIGATING TEXT FILES
PROBLEM You're editing a text file such an essay or e-mail.org/ for latest updates.
SOLUTION In Normal mode you can use the following shortcuts: Key { } ( ) w b e Move To Beginning of current paragraph End of current paragraph Beginning of current sentence End of current sentence Beginning of next word Beginning of the previous word End of the word
DISCUSSION The shortcuts above all rely on the fact that plain text is often very structured. and want to exploit its structure to navigate it efficiently.
91
.

After using one of these shortcuts you may want to return to where you were previously.
92
. to move to the end of the previous word you type be You can also prefix them with numbers to indicate how many times they should be be. use g. g. (mnemonic: go back to where I paused (commas can be used to represent pauses…)) command. This is particularly useful if you're writing one thing and are then reminded that you now have to change another: you use a shortcut to jump to the location of the change. You can use the g. executed: 3b moves to the beginning of the 3rd previous word. All of these shortcuts can be combined. Each time you execute it you'll be taken back another step. To move in the other direction (towards more recent changes). So.. then want to resume where you left of.

Key % End of construct
14
if/elsif/else
block. gd looks for the definition closest to your current position. Occurrences in comments are ignored. and moves you to the end of it. }[ Beginning of the current comment block. ]} Beginning of the current block. or a comment. % finds the end of the is over. an
if/elsif/else
block.
SOLUTION The commands below allow movement around source code in the context of typical constructs.
14. or a comment. so prefers variables with a global scope.org/ for latest updates. 15. A construct is a bracket pair. [{ End of the current block. gd First usage of the current variable name gD Go to the first global
16 15
. See :help % for more details. if you hit % on an
opening bracket you'd jump to the corresponding closing bracket.
93
. 16.
Visit http://vim. gD starts searching from the first line of the file. ][ Forwards to the beginning of the current function. thus respecting the lexical scoping rules of many languages. }] End of the current comment block.Vim Recipes
NAVIGATING SOURCE CODE
PROBLEM You're editing the source code for a computer program. For example. your cursor
Move To
[[ Backwards to the beginning of the current function.runpaint.
usage of the current variable name. and want to navigate it efficiently. (Mnemonic: go to definition). For instance.

Despite my best efforts. and bounce back and forth between those braces.DISCUSSION The shortcuts available for text files are supported for source code.
94
. make sure that syntax highlighting is on (:syntax on). I suspect that the descriptions above are still confusing. so review them if you haven't already. To understand these shortcuts you really need to try them yourself. Open some source code written in your favourite language with Vim. There's a lot to remember here. too.

The area of the screen displaying a file is called the viewport. Middle of the screen. Scrolling through a long document this way is inefficient and unhealthy for our fingers. Bottom of file. As we scroll down the document using j. (Mnemonic: Home).
Visit http://vim.
95
. which severely reduces the amount of key presses involved.
SOLUTION Command H L M gg G Scroll To Top of the screen.org/ for latest updates.runpaint. (Mnemonic: Lower).
DISCUSSION If your file is longer than the height of your window. Instead we can scroll one screenfull at a time. the viewport updates to hide the line at the top. Top of file. Bottom of the screen. you'll need a way of scrolling the portion that appears on the screen. and show a new one at the bottom.Vim Recipes
NAVIGATING
THE
VIEWPORT
PROBLEM You want to scroll through a document in screenfulls. (Mnemonic: Middle). not line by line.

NAVIGATING BUFFERS
PROBLEM You have multiple files open and want to navigate between them. Open all the buffers in the buffer list. then switch to the buffer containing the next. (Mnemonic: buffer all. consider using tabs instead. (Mnemonic: buffer previous). They are particularly useful for processing a set of files sequentially. (Menmonic: buffer next). go crazy and open them all at once). whereby you operate on one file. View the list of buffers along with their numbers. Go to the next buffer. Go to the last buffer.
96
. Result
:bp[revious] Go to the previous buffer. Command :buffers :ls :files :buffer N :bn[ext] Open buffer N. or have a ball. :bf[irst] :bl[ast] :ba[ll] Go to the first buffer. If you'd rather have the open files listed along the top of the screen.
SOLUTION Buffers allow you to have a collection of files open with only one displayed at a time.

txt and second. You can also switch buffers very quickly by using :buffer (and its shortcut :b).
Visit http://vim.txt.txt loaded you can use :b fir (or even just :b f) to switch to first. It supports (partial) file matching thus if you have first. For example map <F6> :bn<CR> lets you hit <F6> to cycle through the open buffers.org/ for latest updates.
97
.runpaint.Vim Recipes
DISCUSSION To quickly navigate between buffers its common to map :bnext and/or :bprev to a key.

98
. if you were using Vim to edit a website. Go to next tab. Go to previous tab. and operate on them as a group. so you can switch between them easier. If the optional file is supplied. Often it makes more sense to group them into logical tabs.
SOLUTION Use tabs. and a HTML reference guide in the third. or the nth Show a list of the open tabs. aborting on the first error. the HTML files in another. that file is opened in the new tab. Close the current tab. or the nth
[file]
:tabclose :tabnext n
ngt
:tabs :tabprevious
n ngT
:tabdo cmd
Executes cmd in each open tab. logical groups. Command :tabedit Action Open a new tab. When you have a lot of open windows/buffers it can be tricky to navigate between them. you may have your CSS files open in one tab. For example.NAVIGATING TABS
PROBLEM You want to group your windows into multiple.

99
. The power of tabs comes from executing commands on the windows they contain as a logical group. close existing tabs. gt with its number. For example. say. by allowing multiple files to be opened in the same tab. their numbers may not be obvious. if you were in the HTML tab. Continuing the above example. and all of your HTML files would have their <foo>s replaced with <bar>s. however. In GVim you can switch to another tab. Tabs are numbered starting with 1. In 3gt. by opening one file in each tab. When you open a tab.org/ for latest updates.
Visit http://vim. a tabline appears along the top of the screen. use :tabs to find them. this case. and open new tabs. which lists the open tabs. you could say :tabdo s/<foo>/ <bar>/g.runpaint. this would let you perform a search and replace all HTML files. by clicking the tabline with the mouse. You can either cycle through open tabs using gt or go directly to a specific tab by prefixing gt. Vim enables you to extend this concept. you'd use 3gt If you have a lot of tabs. so to switch to the 3rd tab on the tabline. then switching between them.Vim Recipes
DISCUSSION You can use Vim's tabs like those in Firefox® and Opera®.

so will usually do the right thing. i. zfaB
17. This feature understands nested blocks. looks like a folded piece of paper.
Use Vim's folding feature to treat a file hierarchically. Vim's help makes the spurious case that this. and that foldenable is true. then navigate it in outline mode. expanding and collapsing its sections as necessary. Fold the current block delimited by bracket B17
zf/string Create a fold from the cursor to string. :set foldenable.
SOLUTION
⇰
Enabling Folding
Folding is very likely already enabled in your Vim.
100
. Create a fold from the cursor down # lines.MANUALLY CREATING FOLDS
PROBLEM You want to fold a file. check it has been compiled with the
+folding option. Command zf zf#j Action Fold the selected text.e. B can be any of ()[]{}<>. kinda'. if you squint. If not. Fold commands start with z. too.

A particularly useful method. Folds are now automatically created for each level of indented text. When editing program source code they can be used with function/method/class declarations.org/ for latest updates. In addition. and otherwise navigate folds see Navigating Folds. zM folds all indented text. for instance. They are particularly useful for long papers or essays. zf4j creates a fold from the current line to the forth line down. is described below. then zf will fold the selection. if you've selected text in Visual mode. (To indent simply start a line with a <Tab>18 So.
DISCUSSION How you use folds will depend very much on the type of file you are editing.
18. Try it out by opening some source code in Vim then executing :set foldmethod=syntax. for example.
Visit http://vim. because there are other approaches to folding which are automatic. collapse.
Enable it with :set foldmethod=indent.runpaint. This recipe is entitled Manually Creating Folds. indented text you may prefer to use indentation folding.
101
. most programming languages support syntax folding.
⇰
Indentation Folding
If you're working with structured. Each shiftwidth of indent corresponds to one fold. See the Indenting Lines recipe for details. Or. where you fold each section so as to navigate the document hierarchically. To expand. indentation folding.Vim Recipes
For instance.

you can yank/delete19 a fold as if it was a single line. Close all folds.
102
. yank is Vim terminology for copying text to the clipboard. Open the current fold. Open all folds. so j and k move over one fold at a time. which can be useful when you're writing a long book and forget how the recipe you're currently writing relates to… Vim treats folds like individual lines. Cutting. and Pasting.
SOLUTION Command zc zo zM zr zR zj zk zm zn zN Action Close the current fold. see Copying.
19. Fold more
no folds N is n toggled
DISCUSSION You can use zM to achieve a birds-eye view of the file. k moves to the previous line Close one level of folds. Mnemonic
close fold open fold
fold More
reduce folding Reduce folding
j moves to the next line
Move to the previous fold. Disable folding. Move to the next fold. Further. (To create folds see
Manually Creating Folds).NAVIGATING FOLDS
PROBLEM Your document contains folds and you want to use them for navigation. Open one level of folds. Re-enable folding.

It indicates whether the corresponding line is an open or closed fold (with .runpaint. respectively).org/ for latest updates. where W is a integer width less than 13. use :loadview :loadview. folds are forgotten when you edit another file. To save them use :mkview.or +. to restore them.
103
. displays a column along the left-hand side of the screen with information about the folds in the current file. The :set foldcolumn=W command. Then.Vim Recipes
By default.
Visit http://vim.

if not. both panes show the current file). that file is shown in the upper/left. if you wanted to move text between multiple files.SPLITTING
THE
SCREEN
PROBLEM You want to view multiple files at one time. So. as appropriate. Or. add the relevant movement key.
SOLUTION Use Vim's split screen feature to divide the screen into multiple panes. For example. <Ctrl>To close the active window use :q. you could view the source and target file together. pane. Command Action
:split file Splits the window horizontally. Or. :vsplit file Splits the window vertically. To move between windows you use <Ctrl>-w (mnemonic: control window). you want to view different positions in the same file at the same time. each of which can display a file. you may want to have the documentation and source visible at the same time. To move in a <Ctrl>specific direction. if you were editing source code in an unfamiliar programming language. (If file is specified. to move upwards: <Ctrl>-w+k.
104
. just as you would to close a window normally.

Visit http://vim. when I'm working on reports I use :30 :vsplit to view the first and second level headings along the left of the screen. When working with long documents it means that you can view the top and bottom of the file simultaneously. prefix the <Ctrl>:split command with the desired height/width in lines. to show README in a window of 5 lines high: :5 :split README. By default the windows will scroll independently of each other. For example. If you :set scrollbind before you split the screen the windows scroll together.
DISCUSSION The default behaviour of both :split and :vsplit is to show the current file twice.org/ for latest updates. For example.Vim Recipes
You can reduce/enlarge the size of the current window with <Ctrl>-w+. If you use folding you can use one window to display an outline of a document while editing a specific section in another.runpaint. To specify the size of a window when you open it.
105
.and <Ctrl><Ctrl>-w++. respectively. while editing the report in the main window. This is more useful than it may first sound.

'a.viminfo file is available. they persist across sessions. I use them often when I have a section of a file that I need to keep referring to: I mark that section with ma jump to it with 'a then return to where I ma.
SOLUTION Use Vim's marks feature. define the text that I want to edit. Jump to the position of mark M.
DISCUSSION Marks 0-9 are mainly for Vim's internal use. A mark is a character in the range a-zA-Z0-9. so ignore them. Command mM 'M `M Action Mark the current position as M. If your . was previously with `` I use them almost implicitly when formatting and filtering text to ``. Jump to the first character of the line containing M. and are deleted when it is closed. Marks a-z are only available in the current file.
106
.NAVIGATING MARKS
PROBLEM You want to bookmark specific points in a file so you can easily jump to them from elsewhere. as it usually will be. Marks have a multitude of uses. Marks A-Z are available across multiple files. It's represented in the examples below as M.

Vim Recipes
The :marks command shows a list of marks you have set.
Visit http://vim.
107
.org/ for latest updates. which is useful for the kind of person who fully embraced the idea of marking anything and everything but was unable to remember the significance of all 52 marks he used.runpaint.

Then you want to return to where you were. To only consider files in the current directory use ctags *. you're writing source code and want to be able to type a function name then quickly jump to where it was initially defined so you understand how it should be used. Lisp. After you have installed Ctags you can generate a tag list for the current directory (and its sub-directories) with ctags -R. For example. We will use a program called Exuberant Ctags to generate the tag list because it is compatible with popular programming languages such as C.NAVIGATING TAGS
PROBLEM You're working on a project where you need to jump between occurrences of significant keywords.
SOLUTION Use tags. You <Ctrl>+ can also auto-complete tag names by starting to type one then using <Tab> to cycle through the list of matching tags. Python. You can now open a source file from that directory and use the :tag tag command to jump to the definition of the tag. To look up the tag under the cursor use <Ctrl>+]. Tags are similar to index entries in a book: significant terms are linked to the key places that they occur. Java. C++. Perl. To return to where you were before you jumped to a tag you use <Ctrl>+t. and Ruby. This will generate a tag list for source code in most common languages. <Ctrl>+
108
. which are possibly spread across multiple files. PHP.

it is typical to update the tags file during the build process. They search for all programming language source code in the specified directories. we have only described tags in terms of program source code.
Visit http://vim. Both invocations of ctags given above are very liberal in what they index. for example. so it must be regenerated when your files change significantly.runpaint. the tag list is a static file. you can use ctags *. consult its documentation.txt files in the given directory which are marked up in this way. files is searched for the tag.Vim Recipes
DISCUSSION So far. When you position your cursor over a highlighted entry in a help file. You can use :helptags dir for generating a taglist for all *.org/ for latest updates. In programming projects. Elsewhere. To limit ctags to just Ruby source code. For more control over what files ctags considers. For example.
The tags-option syntax is used for defining a tag. The Vim help system uses tags extensively to allow navigation. Each of these
This can be used to use a It can
different tags file than the default file "tags". However you generate it.
109
. the |tags-option| syntax is used for linking to a tag.rb. and incorporate all the tags found therein into a single tags file. When you use :help term you're actually looking up a tag in the documentation tag file. but they are by no means limited to this domain. On Linux: man ctags. you can generate a tags list for it. also be used to access a common tags file. you use <Ctrl>+] to <Ctrl>+ follow it. the Makefile could execute ctags. here's an excerpt from the tags documentation:
*tags-option* The 'tags' option is a list of file names. For example. This is all possible because as long as you have a way of identifying significant terms in a file.

but for projects which span multiple directories this is not always suitable. Instruct Vim to search for a tags file recursively with :set tags=.Once you have generated the tags file Vim needs to be able to find it. and where you jumped to them from. or :stag tag. You can specify the location of the tags file using :set tags=file. By default it looks for a file named tags in the current directory. Specify multiple tag files by separating the paths with commas. If <Ctrl>+ you'd rather see them in a new window use <Ctrl>+W+]. Using <Ctrl>+] to jump to a new tag takes you to a new buffer to show the results././tags.
110
. <Ctrl>+ If you get dizzy after all this jumping around you can reacquaint yourself with where you've been by using the :tags command. This shows you which tags you've jumped to.

and an icon in Gvim. texthl defines the highlight group for the sign itself.Vim Recipes
BOOKMARKING LINES
WITH
VISIBLE MARKERS (SIGNS)
PROBLEM You want to assign visible marks to the margins of certain lines.runpaint.
111
.
SOLUTION Vim allows you to define a sign and then associate it with one or more lines of a file. you're using Vim as an and want breakpoints to be clearly marked. The linehl argument defines the highlight group used for the entire line the sign is attached to. We name the sign fixme. Or. To attach the sign to a specific line you use:
Visit http://vim. It is displayed in the right-hand margin as a two-character string in the terminal. For example:
:sign define fixme text=!! linehl=Todo texthl=Error icon=/path/to/todo. presumably in vimrc. and that in the GUI the icon stored at /path/to/todo.xpm should be used instead. you can use it in any file.xpm
Let's break this down.org/ for latest updates. Before you use a sign you must define it. For example. We specify that in the terminal the sign should be displayed as !!. Now the sign is defined. you
IDE
want to label lines in need of editing with a question mark icon. which is how we'll refer to it later.

The id is arbitrary, but must be unique and numeric. The name is the same name you used when you defined the sign. The value of the line argument is the number of the line on which the sign should be attached. The file argument is the full path (no expansion is done) to a currently loaded file to which the sign should be attached. So, in the above example, two exclamation marks are inserted in the margin of the 200th line of /home/user/ novel.txt.

DISCUSSION You only need to define signs once, so that's easy enough, but the syntax for placing signs is particularly unwieldy. Let's look at some alternative approaches. You could place the following stanza in your vimrc so <F5> places the previously defined

fixme sign on the current line of the current file:
function! SignFixme() execute(":sign place ".line(".")." line=".line(".")." name=fixme file=".expand("%:p")) endfunction map <F5> :call SignFixme()<CR>

Rather than placing signs manually, you may prefer to have them automatically placed on lines satisfying some criteria. The following stanza attaches the fixme sign to lines containing notes like TODO: check for race conditions. It operates on the current line or selection. So, you can select a range of lines, press <F6> then have your to-do list items flagged in the margin.
112

For example: :set guifont=Andale\ Mono\ 11. gives you full control over the font face and size.org/ for latest updates. Gvim. The command :set guifont font-name changes the current font to font-name. or is too large.Vim Recipes
CHANGING
THE
FONT
PROBLEM You want to display the text in a different font. For example. however.
SOLUTION Standard Vim uses the font from the terminal it is run under.runpaint. unfortunately.
115
. • Spaces and commas need to be backslash escaped. The font name can be followed by a size. the current font isn't particularly readable.
Visit http://vim. There are. some platform-specific differences at this point…
⇰
Linux
Specifying guifont in an Operating-System-Specific Manner
• The font name and size are space separated.

Linux users can also use the xlsfonts utility to see a list of available fonts. • Spaces and commas need to be backslash escaped. If the font you've specified can not be found. The first valid font is loaded. On most operating systems you can request a GUI font chooser with the command :set guifont=*.Mac • The font name and size are colon separated.
DISCUSSION To change the font you need to know its name. • The size is prefixed with a h. This approach is particularly useful if you use your Vim configuration on multiple computers. For example: :set guifont=Screen15. • The size is prefixed with a h. or if you simply want it to be portable. For example: :set guifont=Monaco:h11. Vim complains. For example: :set guifont=Andale_Mono:h11. To avoid this you can specify multiple fonts in order of preference with a comma separated list.\ 7x13.
Windows • The font name and size are colon separated.
116
. • Spaces in font names can be replaced with underscores (_).

117
.
Visit http://vim. each of which refer to some specfic element. • T . menubar.org/ for latest updates.g.
SOLUTION Modify the guioptions variable.Vim Recipes
MAXIMISING SCREEN SPACE
PROBLEM The toolbar. • R . • b . and scrollbars you could use :set guioptions=mTrlb.runpaint.Display the horizontal scrollbar. Some examples follow: • m .Display the left-hand scrollbar if the window is split vertically. • r . you want to hide them. • l .Always display the right-hand scrollbar.Always display left-hand scrollbar. :set guioptions+=T. • L . toolbar. to hide the menu bar. e.Display a toolbar. and other GUI artifacts take up too much of your screen. Gvim decides which elements of the GUI to display based on the value of guioptions. This is a series of letters.Display a menu bar. To display a hidden element use += instead. So.Display the right-hand scrollbar if the window is split vertically.

however. for example. The following stanza in your gvimrc assigns <F11> to toggle the display of extraneous GUI elements:
function ToggleGUICruft() if &go=='' exec('se go=mTrL') else exec('se go=') endif endfunction map <F11> <Esc>:call ToggleGUICruft()<cr>
118
. This can be cumbersome. as it requires you to remember the significance of each letter.DISCUSSION If you decide that you want to restore one or more of these elements you can simply execute :set guioptions+=m.

For example. which invokes :help options.org/<cr>
Visit http://vim. This is the GUI equivalent of :map.org/ for latest updates. you want to invoke it by selecting a menu option. you can create a new top-level menu simply by specifying a name not currently in use. For example:
:amenu <silent>&Vim.Op&ions :help options<cr> adds a new item called
Options to the Help menu. so in this case <Alt>+h+t <Alt>+ selects this command. or toolbar.
119
. For example. The ampersand (&) signifies that
the character it prefixes can be used as a keyboard shortcut.runpaint.vim\.
DISCUSSION You're not restricted to adding items to existing menus.vim.
SOLUTION Use :set amenu menu command to map a menu item to a command.org :!xdg-open http://www. you've written a function that automatically writes bestselling novels for you. :amenu Help.Vim Recipes
CREATING MENUS
AND
TOOLBAR BUTTONS
PROBLEM You want to add your own commands to Gvim's menus. but you're not willing to use it if you have to type its name every time. for quick access.

For example. If you want to add a dashed separator line between menu items use a menu item named -SEPand an empty command. as above.-SEP. which appears before the other items.1 Help. Vim prepends $VIMRUNTIME/ bitmaps/ to it.org (we escape the .:.OptionsHelp :help<cr>
If the image-path consists only of a filename. :amenu Help. To control where a top-level menu appears relative to its neighbours you need to prefix amenu with a numeric priority: the lower the number the further right the menu's position.g.
120
. The <silent> prefix prevents the command from being echoed
on the command-line. :amenu 9999.will create a new top-level menu called Vim with the shortcut key V. :5amenu First. When invoked it will open the Vim website on systems adhering to the
Free Desktop Specification.first :echo 'first'<cr> adds a first item to the Help menu.item-name
command
For example:
:amenu icon=options. For example. The same approach can be used to position menu items. You can also use :amenu to add a new toolbar icon:
:amenu icon=image-path Toolbar.png ToolBar. It will contain one entry named vim.first :echo 'first'<cr> creates a top-level menu named First that appears before all of the others. e. because otherwise it would create a vim entry which in turn contain an org item).

pressing <Esc> will cancel the search and return to where you began. word can also be a regular expression. press <Enter> to run it. To jump to the previous match. After finding the first match using either of the above methods. For example /^[A-Z] searches for lines beginning with capital letters. use N. If you were interested more in the erratic cursor movement than searching. Having done so. ?word to search backward. your cursor will move to the first match as you enter your query. You're not limited to finding literal strings.
DISCUSSION You can use incremental (find-as-you-type) search by using the :set incsearch option. To repeat your search use // or ?? ??.
122
.
SOLUTION Use /word to search forward in the file. you can press the n (mnemonic: next match) key to jump to the next match. This enables you to receive feedback on the effectiveness of your query. Once satisfied with your query.SEARCHING
FOR ANY
WORD
PROBLEM You want to search the current file for an arbitrary word.

SOLUTION Use the :vimgrep command: :vimgrep /pattern/ [flags] file0 file1
fileN.txt files could be accomplished with: :vimgrep /grapes/ *. and a list of files in which to do so.txt you'd run :vimgrep /grapes/ shopping-list.
DISCUSSION In its simplest form. instead to specify groups of files. see the sidebar for details.
Visit http://vim. you want to find the files in your project that mention Mr J.
123
. For example. vimgrep takes a word to search for. but you'll probably want to use shell globbing. Searching for grapes in all *. You can name as many files as you like.Vim Recipes
SEARCHING OVER MULTIPLE FILES
PROBLEM You want to search for a particular term in a collection of files.runpaint. to search for grapes in shopping-list.txt.txt. So.org/ for latest updates. Random.

tex.
If your operating system supports additional globbing patterns. A good choice is Andy Lester's ack which can be used with set grepprg=ack and set grepformat=%f:%l:%m.⇰
Globbing
A number of Vim commands support filename globbing. You're not restricted to searching on simple words. The * is a wildcard and means anything.tex for lines starting with numbers: :vimgrep /^[0-9]/ /tmp/bar. To jump to the next match use :cn use :cN for :cn. *. You can use any of Vim's regular expressions between the forward slashes.txt searches recursively downwards from the current directory for filenames ending in . ** recursively matches directories below the current one. This is a way of selecting a group of files by specifying a pattern matching their names.
✪
If you use :grep instead of :vimgrep an external grep-like utility is used to
perform the search. simply saving the search results to the
quickfix list (see sidebar for details) and leaving your cursor where it was. Searching /tmp/bar. For example.txt ~/foo.txt and ~/foo. The j flag inhibits the jumpiness (Ritalin for Vim).
124
.txt. The program used is the value of &grepprg. you can use these as well.txt refers to all files in the current directory whose names end in . the previous. vimgrep jumps to the first match it finds. so **/*. however.txt.

a position within that file. For more information see :help quickfix. The results are numbered.runpaint. the results of the last search) use :cl[ist].
To view the quick fix list (i.
Visit http://vim. If not present (by default). otherwise. only the first match of a line is shown.
125
.org/ for latest updates.
⇰
Quick Fix List
The quick fix list mentioned above is a Vim concept for creating a temporary index of positions in a file. and the matched text) in the quick fix list.e. so you can jump to a specific one with :cc number. The flags can be combined in either order. every occurrence of the pattern is regarded as a separate match.Vim Recipes
The g flag controls how lines matching the pattern multiple times are handled. vimgrep stores its results (a file name.

multiple times on each line. You want Vim to make these changes with the least possible effort. For example: :%s/Curtis/Excalibur/g.SEARCHING
AND
REPLACING
PROBLEM You want to replace all occurrences of one string with another. though:
126
. so I won't go into them here. Two tips. :s/Curtis/Excalibur/g. The % prefix indicates that the replacement should occur over the entire file. 2. Or. The g flag at the end causes this operation to be performed globally. it can be any Vim regular expression. The search string (Curtis in this example) doesn't have to be a literal string.e. e. e. i.g.g.
DESCRIPTION The solution above replaces Curtis with Excalibur. For example.20s/Curtis/Excalibur/g performs the operation over lines two to twenty. if necessary. You decide to change his name to Excalibur to give him more panache. prefix the command with a range to contstrain it that way. The details of Vim's regular expressions are explained in the Creating
Regular Expressions recipe. imagine you were using Vim to write a novel wherein there was a protaganist named Curtis.
SOLUTION Execute :%s/target/replacement/g to replace all occurrences of target with
replacement. Had you previously visually selected text to which you want to constrain the search/replace operation omit the %.

linux.runpaint.If you provide a literal string to replace.
Visit http://vim. Vim even replaces occurrences that form parts of other words. • Search case insensitively . Thus. surround the string with word boundary anchors (\<. \>). or. For example :%s/and/or/g would change supply and demand into supply or demor.
127
.Vim Recipes
• Search for words . use :set ignorecase to enable this behaviour for all searches. and LiNuX you need to either add the i flag to the end of the replacement command. as above.org/ for latest updates. To avoid this. the above command could be rewritten as :%s/\<and\>/or/g.If you want linux to match Linux.

SEARCHING
FOR THE
WORD BENEATH
THE
CURSOR
PROBLEM You want to search the current document for the word underneath your cursor. place your cursor on or just in front of the word you wish to find. You'd rather not type it in again. instance. To jump to the previous match. To search for words containing the current word. if the current word is back. Alternatively.
DISCUSSION After finding the first match using either of the above methods. press g* or g# as appropriate.
128
. pressing # will find the previous occurrence. you can press the n (mnemonic: next match) key to jump to the next match. use N. For g#. g* will jump to hunchback. then press * (mnemonic: star search).
SOLUTION In Normal mode. This will jump to the next occurrence of the word in the current file.

and "undersow".
129
. but also "sow". For example /[cs]ow/ would match "cow". The Searching for Any Word recipe. The period (. You can use character ranges to indicate that any one of the specified characters are acceptable.org/ for latest updates. and "tow".
SOLUTION Vim allows you to use regular expressions (regexps) in many areas. "Don't have a cow". A regexp is a pattern that describes a string. For example.ow/ also matches "cow". We will use the /pattern/ notation for describing patterns. for example.Vim Recipes
CREATING REGULAR EXPRESSIONS
PROBLEM You want to use a Vim regular expression. "sow". explains how to search a file for a regexp.runpaint. which matches that exact string. you want to search a document for a word that begins with a vowel. It matches any single character. but don't know how they work.
Visit http://vim. So. For example.) has special significance in a regexp. /cow/ matches "cow". The simplest form of pattern is a literal string. /. and "cower". and the "string" notation to represent the text the pattern is being tested against.

to match "b". or "c" followed by any number of "t"s. For example. "b". "coins". the "+" metacharacter requires that what precedes it20 occurs either one or more times. Or. If you wanted to match strings containing consecutive "o"s followed by an "i. (Given that it starts the pattern it's actually unnecessary. to match one or more "o"s followed by an "i". The following words satisfy the pattern: "tattooing". /[^cs]ow/ matches any character that isn't a "c" or an "s" followed by "ow".e. "e". you could use /ooi/. followed by an "i". "c". /o\+i/ matches one or more "o"s followed by an "i": "abattoir". A metacharacter is simply a character that has special significance in a regular expression. "acknowledge". "cooing". The "*" metacharacter represents any number of occurrences of the preceding character. you'd have a problem. an integer between 1 and 5: /[1-5]/. If you want this level of detail see :help pattern or a regular expression book. The solution is to suffix the part of the pattern that can be repeated with a metacharacter which specifies the type of repetition. however. i.
130
. and "limboing". If you wanted to abstract this pattern. For example. "d". so /o*i/ matches "zucchini". In fact. For example. or "f". It may not
20. You can invert character ranges so they match any character not specified. /i/ will match everything that it matches). "I said "ow"!". followed by at least one "o". and "zooming". like "cooing" and "tattooist". and "bellow". you can use /[b-f]/. but this recipe is already too complex.If your range consists of alphabetically or numerically consecutive characters you can specify the start character and end character separated by a hyphen. it requires that the atom that precedes it occurs one or more times. and "oii". This time the "o" is made optional. "boating". Another useful concept of regexps is repetition. A more useful example is /[a-c]t*o\+i/ which matches either "a". For example.

alternation allows you to specify a list of alternatives that can match at a given point. In the example above the regexp looks at the first character of "tattooing" and tries applying the pattern to it. many more. Like character ranges. and "blabbed" ("labbe"). but doesn't match "cabbage". but also many. i. For example. This fails because "t" is not a member of the character class [a-c]. /ing\|ed/ matches the string "ing" or the string "ed". it would match all the strings the alternation approach does. an "n". this time it matches up to "i". /[inged]/. an "e". while $ matches the end.e. That is to say. All the patterns so far have been allowed to match at any point in the string.
Visit http://vim. /^\s\=\uo/ matches a line that begins with an optional white space character. For example.e. as explained above.
131
. but no more than max times. If you used a character range here.g. the following two "o"s match /o\+/. so let's walk through it: The "a" satisfies /[a-c]/. and because the pattern has now been exhausted.g. You can change this behaviour by using anchors: ^ matches the start of a line. You can make a portion of the regexp optional (i.runpaint. the rest of the string is ignored. /[^a-c][a-c]\{2. insisting that it matches 0 or 1 times) with \=.org/ for latest updates. alternation is used for sets of strings. "simpered".Vim Recipes
be intuitive that "tattooing" would match.max\} notation which matches at least
min times. A key concept to grasp here is that a string matches a regexp as long as a contiguous portion of it matches. or a "d". then the "i" matches /i/. Whereas character ranges specify sets of characters. the pattern would match any string that contained an "i". the following two "t"s match /t*/. So. a "g". So it moves on to the next letter and starts again. You can generalise this with the \{min. before Vim gives up on a match it will try applying the pattern at every point in the text. e.4\}[hero]/
matches "yachts" ("yach"). and "attacking". e.

DISCUSSION The features described above are common to most regexp implementations. then the \C makes the "w" case sensitive. \$ matches "$".\+[rnt]\$/ will match "Tomahawk thrown". which matches a newline character. Vim offers some extensions.
132
. /\ccow/ matches "cow". \r which matches a carriage return character. That is to say /cow/ will not match "Cow". and \t which matches a <Tab> <Tab>.". The \c makes the "co" case insensitive. "coW". Of particular note in Vim is \n. and "Soviet Union". For example. though. /^\uo\%(v|ma\). Some characters in a regexp have a special significance and don't match themselves literally in the string. For example. matches ". \. For example. To match a special character you need to precede it with a backslash. that users familiar with other regexp implementations may not be aware of. /\cco\Cw/ matches "COw" and "cow". The following strings will all match: " Popes are religious". which is followed by an "o". For example \^ matches "^". You can combine the two anchors to require that the whole line matches the pattern. but will reject "Soviet Union" or "During November".which is followed by an uppercase letter. You can make all patterns ignore case with :set ignorecase. it doesn't match "^foo". To change the case sensitivity for a particular pattern surround the relevant portions with \c (to ignore case from this point on) and/or \C to respect case from this point on. By default regexps are case sensitive. but not "COW". /^foo/ matches a line starting with "foo". etc. "Roman". and "Cow". "November" and "Soviet". However.

runpaint. This would match "zoom".
133
. and the backreference (\n) refers to the nth group. The parenthesised portion of the pattern is a group. So. /\([a-z]\)\([a-z]\)\2\1/ matches two lowercase letters. followed by the second one again. For example.Vim Recipes
Vim supports backreferences which allow you to refer to part of a match later in the same match.
Visit http://vim.org/ for latest updates. and "seeing". This matches strings like "abba". /\([a-z]\)\1/ matches a lowercase letter followed by the same character that just matched. then the first one again.

By setting keywordprg appropriately.
134
. The Perl programming language has a similar command called perldoc. So 7K over glob invokes man 7 glob to display section 7 of the glob documentation. When used with man. passing the current word21 as an argument. then hit K while hovering over the word.
SOLUTION Use :set keywordprg=program. Thus. Vim translates a count for the K command into a section number. then hovering over the word ls and hitting K would display the documentation for Linux's ls command. it is not necessarily a valid word in your language.
DISCUSSION This recipe calls the command specified with :set keywordprg. For example.LOOKING
UP
DOCUMENTATION
FOR THE
KEYWORD UNDER
THE
CURSOR
PROBLEM You want to invoke an external command to lookup documentation for the keyword underneath the cursor. you can make context-sensitive documentation lookup trivial. The Ruby programming language has a utility called ri that displays documentation about the given Ruby method. Linux users may like to read the manual for the named command with the man utility.
21. word is used in the sense of a string that looks like a word to Vim. if keywordprg = man.

This uses the value of breakat to decide where to break the line. so lines may be shorter
136
. which should be on by default. rather than the screen
lines.
SOLUTION The :set wrap command. Once they reach the right margin they are broken. so gj moves down one
screen line. however. (To disable this behaviour: :set nowrap). the file will not be changed. You find it hard to edit and view. for example. after which the text is broken with a "hard" line break. You can use :set textwidth=width to enforce a maximum line length. you can specify what point the line should be broken by executing :set linebreak. This means that a file containing two particularly long lines may be represented by Vim as having 5 lines. It inserts soft line breaks. The solution is to prefix the movement commands with g. Vim breaks at white space. If using wrap. and continued on the line below. changes how long lines are displayed. after wrapping. To change the characters used modify breakat.WORKING
WITH
LONG LINES
PROBLEM Your file contains lines which are too long to fit on the screen. wrap only changes the way the lines are displayed. If you try to navigate this file using the basic movement commands j would move between the two logical lines.

To reformat existing text according to this preference either select them visually and hit gq or. I suggest the use of textwidth instead. This is mainly a holdover from the days of terminals whose displays were limited in this way.org/ for latest updates. This approach is more flexible than textwidth.
137
. and means that the file will display reasonably in any editor.
DISCUSSION In general. For wrapmargin to take
effect textwidth must be zero. but is still customary in many programming languages and e-mail.Vim Recipes
than width. as it is by default. :set wrapmargin=4 means that when a line is more than four characters away from the right-hand margin. Especially if you're sharing the files you produce with others.
Visit http://vim. but has the disadvantage of producing files which will display poorly on smaller displays or when the screen is split between multiple files. There's another way to insert hard line breaks without specifying a maximum line length. even if it doesn't wrap long lines. in Normal mode. text file lines are kept under 80 characters. you'll be better off using hard line breaks with textwidth.
✪
textwidth takes precedence over wrapmargin. you can reformat the current paragraph with gqap gqap. This removes the need to differentiate between logical lines and screen lines. it is broken. To enforce this restriction just :set textwidth=80. For example. It is called wrapmargin and wraps lines relative to the width of the terminal window.runpaint. Traditionally.

138
. you may want to disable them: :set nonumber. line numbers can still be useful. you can execute :%!cat -n %. the line number can be used to differentiate the beginning of the line from the point at which it has been wrapped. This filters the entire file through cat and prepends the number to each line. if you'd like to see the line numbers when you print the file without permanently changing its contents: :set printoptions=number:y. For example. they may mention specific lines. If you're using a small monitor. If you’re wrapping long lines. error messages frequently reference line numbers.DISPLAYING LINE NUMBERS
PROBLEM You want to see each line's number alongside it. if you’re writing a program. If you'd like it to be. Lastly. To change this minimum width use :set numberwidth=width. which you can then jump to with :number. if you’re collaborating on a file with other people. and you have the cat command on your system. regardless of how many lines the file has. The line numbers are only displayed when you’re viewing the file with Vim. By default the number column is at least 4 characters wide. For example. the actual file isn't modified.
DISCUSSION Even if you're not programming.
SOLUTION Use :set number to enable line numbering.

WEBDAV. you might want to change a file on your website from your home computer.com/file.txt. RCP.com/README. and fetch (read-only). it relies on external programs to do so.org/ for latest updates. For example: vim sftp://guest@example. However.
DISCUSSION Vim supports the following protocols:
SCP. To save to a remote file use :w URL. So. HTTP
(read-only). Or.runpaint. To work with remote files from within Vim.example.
139
. For example: :w scp://kci@jojo. you want to change the message of the day file on a server you administer. For example: :e ftp://user@example.
SOLUTION To invoke Vim with a remote file use its URL as the argument to vim. to to open a remote file for editing use :e URL. For example. On
Visit http://vim. just use their URLs in place of a filename with normal editing commands. SFTP.com/etc/motd.
rsync
(read-only).Vim Recipes
WORKING
WITH
REMOTE FILES
PROBLEM You want to edit/view a file that is stored on another computer.

on Windows. The file is formatted as follows:
machine {host name 1} login {username} password {password}
machine {host name 2} .. ⚠ FTP is an insecure protocol. Now you can use URLs like ftp://example. This gets boring fast. and then be prompted for the password interactively. If you're using FTP on Linux. so please don't use it unless you must. If you're editing files via or consider setting up passwordless logins. only normally available.
It should be made read-only for your user: chmod 600 ~/. however.Linux.netrc'.netrc . for example. and it will find your username and password automatically. you can supply the username as part of the URL.
FTP
is
If the protocol requires authentication.
140
.. SSH/SFTP/SCP are all superior alternatives. but it is much for the same for other operating systems. See :help netrw-externapp for more information.org/README. The principle is
SSH
SCP
explained in Password-less logins with OpenSSH for Debian Linux. you can store your credentials in ~/. most of these programs are available by default.

Here are some common variables the status line can display: Name b Description Value of byte under cursor. or mac) to be displayed along the bottom of the screen. MS-Windows.Vim Recipes
CHANGING
THE
STATUS LINE
PROBLEM You don't like the way the status line looks or would prefer if it displayed different types of information. so you'd like the file format (e. The format string is the text you want displayed interspersed with variable names corresponding to the types of information you want included.
SOLUTION Use the :set statusline command along with a format string.
141
. unix.runpaint.
For example.org/ for latest updates. you work with files created on different operating systems. You can surround this with arbitrary text. To show it: :set laststatus=2.
✪
By default Vim hides the status line. For example.g.
Visit http://vim. to display the file format you could use :set statusline=%{&ff}. for example: :set statusline=format:\ %{&ff}.

g. Displays [RO] if file is read only.g. bars (|). e. dos.
142
.3]. to display the name of the current colour scheme: %{g:colors_name} (example output: morning). File name (as opposed to file path) File content type. Line number.c l r t y
Column number. Or the current language: %{v:lang} (example output: en_GB.%l]
Sample output: . Here's a longer example:
:set statusline=%t\ %y\ format:\ %{&ff}.UTF-8).vimrc [vim] format: unix [2. e. Variable names are prefixed with a percentage sign (%).
\&ff File format. mac. For example.
DISCUSSION You may have noted that the syntax for displaying the file format was different from the other variables. unix. [ruby] or [latex]. Spaces. (See :let for a list). Here we are simply displaying the value of Vim internal variables. and other special characters need to be backslash escaped. The %{} syntax evaluates the expression contained within the braces and displays the result.\ [%c.

getftime(expand(\"\%\%\")))}
Sample output: Fri 01 May 2009 19:26:07 BST
Visit http://vim.
143
. to show the last modification time of the current file:
\%{strftime(\"\%c\".runpaint.org/ for latest updates. The value of any option can be displayed in this way. and the & prefix is used for referring to options. For example. You can even call a function in this way.Vim Recipes
The reason %{&ff} works is because ff is the Vim option for getting/setting the file format.

ErrorMsg
Command line error messages. For example.
Normal
Normal text. For example.
SOLUTION Use the :highight group definition command. A highlight group (group) is an element of the display whose colours can be customised. Some of the default highlight groups are:
Cursor
Character under the cursor.
Visual
Text selected under Visual mode. you want text to be white on a black background.REDEFINING HIGHLIGHT GROUPS
PROBLEM You want to change the colours of specific elements of the display. the following sets the terminal foreground colour to black and the terminal background colour to yellow:
:highlight Normal ctermfg=black ctermbg=yellow
144
. The definition is a list of key-value pairs.

regardless of case due to the \c escape. Before you change highlight groups you may like to check their current values.
146
. To view all current settings use :highlight. and not define highlighting groups at all. though. For example:
:highlight Elephant ctermbg=grey ctermfg=white :match Elephant /\celephant/
This renders all occurrences of the word elephant. you want more control over colours or need to edit a syntax file.
⇰
Defining a Highlight Group
You can define your own highlight group by using the :highlight command as described above with a group name of your choice. in white on grey. Occasionally. That's where the :highlight command comes in. You can do this with :highlight group.DISCUSSION Normally you'll select a colour scheme. To select what is highlighted you use :match
group /pattern/.

you can highlight the current column the cursor is in with :set cursorcolumn. You do this by executing :set cursorline. to change the colours modify the CursorLine highlighting group. Or. predictably. Another approach is to highlight the line the cursor is on. you're using visually “busy” syntax highlighting. Similarly.
SOLUTION To change the cursor colour in Gvim redefine the Cursor highlighting group22.org/ for latest updates. For example. Again. as shown below. If you want your terminal to resemble a sniper's sights.
Visit http://vim.runpaint. The Creating Highlight Groups recipe explains how to redefine highlight groups.Vim Recipes
MODIFYING
THE
CURSOR
PROBLEM You want to make the cursor easier to see. and sometimes lose the cursor. and need the entire column that the cursor is over to be highlighted.
22. you can combine both line and column highlighting to create a cross-hair effect.
147
. you're working with columnar data. but in standard Vim the terminal defines the cursor colour. called CursorColumn. The highlight group is.

DISCUSSION Gvim allows you to customise every conceivable aspect of the cursor display with the command :set guicursor.
148
. Here are some examples: • n-c-v:ver50-ncvCursor . and Insert mode set the cursor to a vertical bar 50% of the current character's width. its height.v:block-vCursor . Command. The above examples should be adaptable for your uses.In Insert mode use a nonblinking block cursor highlighted with the iCursor highlighting group. another for Normal). For the gritty detail of the supported syntax look at :help guicursor. one colour for Insert mode. In Visual mode also use a block cursor. • i:block-iCursor-blinkon0. Highlight it with the ncvCursor group. This allows you to change the cursor's appearance based on the mode (i. and control whether it blinks… This is achieved by providing a format string as the value for guicursor. but highlight it with vCursor.e.In Normal.

The state character is one of the following: File can't be modified
23. followed by a character indicating the state of this file. the directory name is followed by a hyphen then the value of &v:servername.org/ for latest updates. and set the title option.
149
. The window title can also function similarly to the status line. For example:
:set title titlestring=My\ Title
DISCUSSION When working with multiple instances of Vim. reminding the user about an important aspect of the current file. followed by the name of its directory23. To be precise.runpaint. The default window title contains the current filename.
Visit http://vim. it can be difficult to remember what task each window corresponds to. otherwise just VIM. if set.Vim Recipes
CHANGING
THE
WINDOW TITLE
PROBLEM You want to change the title of a Vim window to make it more descriptive. You can avoid this problem by customising each window's title.
SOLUTION Assign a value to the titlestring option.

Another example is to display the value of an environment variable in the window title along with the filename. The Vim documentation (:help titlestring) gives the following example:
:auto BufEnter * let &titlestring = hostname() . as described in the Changing the Status Line recipe. For an explanation of the %:p syntax see the Filename Modifiers section of the Executing External Commands recipe. production. a forward slash. For instance. ": " . or testing mode:
let &titlestring=expand($RAILS_ENV) . staging.
150
. expand("%:t")
One last trick is to embed the value of an external command in the window title using the %{system('command')} syntax. which indicates whether the application is in development. It contains the hostname. expand("%:p")
Here the window title is reset when the user enters a new buffer. but we can customise it further using a format string. This could be used to display the name of the current
24. then the full path of the current file24. Ruby on Rails developers could prefix the filename with the value of RAILS_ENV.+ File has been modified = File is read-only =+ File is read-only and has been modified This is already quite a descriptive title. "/" .

or indicate whether the project's unit tests are passing or failing.
Visit http://vim.org/ for latest updates. if using a version control system.Vim Recipes
branch.
151
.runpaint.

EXTENDING
152
.

and in Visual mode we want to reformat the selected text rather than the current paragraph. We used nmap here because this mapping doesn't make sense in other modes: in Insert mode we want Q to insert a literal Q. thankfully. :nmap only takes effect in Normal mode. For example.runpaint. Or. you'd like to change an existing keyboard shortcut so that it does something more useful. Visual.
153
. to remap <Space> to <PageDown> you execute :map <Space> <PageDown>. i.org/ for latest updates. you use the <Space> key to page down in other applications. simply hit Q. and you'd like to do the same in Vim. with a keyboard shortcut rather than continually type it in. For example.e. Or. you regularly reformat paragraphs with gqap but would prefer to gqap. The map command creates a mapping for Normal.
SOLUTION Use key mappings. Unlike map. has no
effect. When you enter the first key combination Vim acts as if you entered the second. The Visual mode mapping is :vmap Q gq. A map is simply a key combination followed by another key combination.
Visit http://vim. if you press <Space> in Insert mode this mapping. or series thereof. and Operator
Pending mode. Mapping Q to gqap is similarly straight forward: :nmap Q gqap.Vim Recipes
CREATING KEYBOARD SHORTCUTS
WITH
KEY MAPPINGS
PROBLEM You'd like to execute a command.

DISCUSSION Keyboard mapping is yet another way to save valuable keystrokes. too.The other main types of mapping commands are: :imap Insert mode only. it's currently being used for. :help <F1> will show that Vim maps it to :help. As long as you use a <Shift>-<F3>) combination that doesn't interfere with the commands you do use. though. you're free to use whatever you want. :map Normal.
25. as well as their shifted <F1>-<F12> counterparts (e.g. This works will the mode-specific map commands outlined above. It's generally recommended to map the function keys (<F1> <F12>). If you find yourself executing a command repeatedly create a mapping. Visual.g. and Operator-pending. Before you create a mapping you might like to check what. if anything. :cmap Command-line only. It's also useful for creating more sensible aliases for existing keyboard shortcuts that you can never quite remember. <F1> is used for :help but pretty useless given that you'd normally use :help topic. <Shift>-<F3> because they're not used by Vim25. so :imap will show Insert mode mappings. If you want to see the user-defined mappings (whether set by you or a plugin) call the :map command with no arguments. You can do this by executing :help key.
154
. e.

For example. you've found a colour scheme you like better.
155
.
DISCUSSION A colour scheme is a set of rules controlling how different elements of the interface appear. Or. Vim is distributed with a selection of colour schemes.
Browse through it to select a theme you like. then follow the instructions below to install it.runpaint. but you can also download new ones. then hit <Tab> to cycle through the installed schemes.org/ for latest updates.
SOLUTION To browse existing colour schemes enter :colourscheme. as explained in the sidebar.
Visit http://vim.Vim Recipes
CHANGING
THE
COLOUR SCHEME
PROBLEM You don't like the colours Vim uses.
✪
The Vim Color Scheme Test is a a gallery of colour schemes along with their names. you want to change them. you find that the current colour scheme makes text hard to read so want to find a more suitable one. If you find one that you like hit <Enter> to apply it. so want to instruct Vim to use it.

vim extension. e. Browse the available colour schemes at Vim.vim/colors on POSIX systems. If you want to use this colour scheme permanently add colorscheme name to your vimrc.g. Copy the . 2. You can find the name of the current scheme with :echo g:colors_name. Open vim then execute :colorscheme name. 3. Create a $VIM/colors. 5. mkdir -p ~/. To change a specific aspect of a colour scheme you can redefine a highlight group. 4.⇰
Installing Colour Schemes 1.
Before you change your color scheme you may like to make a note of what you're using at the moment. otherwise repeat these steps with a different colour scheme.org and download any that you like.vim file you downloaded in step one to the colors directory you just created. where name is that of the file you downloaded without the .
156
.

argN name command. You can modify how the command is defined by supplying :command with a list of arguments with the syntax :command arg1.runpaint. :command Ls !ls -all % lets you use :Ls to view the long listing for the current file on POSIX systems. owner. These are not to be confused with arguments passed to the command. itself.
DISCUSSION The command can be anything you could enter at the : prompt. … . arg2. where spec is:
1 One argument. (name must start with an initial capital) For example. etc. where name is the command you're creating and command the command name should execute. 157
.Vim Recipes
CREATING COMMAND-LINE COMMANDS
PROBLEM You want to create your own :command command.
Visit http://vim. group. thus showing the permissions.org/ for latest updates.
SOLUTION Use the :command command like so::command name command. To create a command that accepts arguments you use the syntax :command -nargs=spec
name command. however.

then reference the count in command as <count>.
26. + One or more arguments. You can reference the range in the command with the placeholders <line1> and <line2> which denote the first and last line of the given range. ? Zero or one arguments. For example. The <q-args> quotes special characters in the argument. For more robust integration with Git see the Integrating Vim with Git recipe
158
. you could use :command nargs=1 Ci !cd %:h && git commit %:t -m <q-args> to quickly change to the directory containing the current file (%:h is the current pathname with the last component removed) and commit the current file (%:t is the last component of the current pathname) to a Git repository by typing :Ci message. respectively.* Any number of arguments. If you don't supply a spec (i. without worrying about using quotation marks and the like26. -range).e. To create a command that accepts a range you use the -range=spec argument. To create a command that accepts a count you use the -count=default argument. A spec of % means that the range defaults to the whole file. the range defaults to the current line. You reference the arguments in command with the <args> placeholder.

If this directory does not
already exist you need to create it.org/ for latest updates. Download the latest version to your computer.gz). For scripts labelled utility. For example.zip or . The sidebar lists the locations of the plugin directories on various operating systems.vim/. try uncompressing it in the parent directory of the applicable plugin directory. the last portion of these paths is ftplugin. otherwise. this directory is $VIMHOME/plugin. If the file you've downloaded has a name ending with . read on. also known as global
plugins. Now you should just be able to start Vim and have the plugin work.runpaint. If the plugin comes with its own
installation instructions.Vim Recipes
EXTENDING VIM
WITH
SCRIPTS
AND
PLUGINS
PROBLEM You want to add functionality to Vim. use those. on Linux this is ~/. also known as filetype plugins.
⇰
Plugin Directory Location
Note For filetype plugins.
SOLUTION Browse Vim Scripts to find a script that meets your needs. for those labeled ftplugin. If the file is compressed (ending with .vim you usually just need to save it in the right directory and then its ready to use. preferably without having to write it yourself.
159
. not plugin.tar. Its 'type' should be utility or
ftplugin. Note:
Visit http://vim. the last component of this path is ftplugin instead.

g. Use :VimballList to verify its contents. 2. 3. Vimballs make plugin installation and configuration easier. Download the *.
161
. 4.vba file. Open it with Vim. and are a slight improvement over the previous methods. try following the steps below: 1.vba.org/ for latest updates. e. the first command is superfluous.Vim Recipes
(If your plugin directory already exists. vim something. Install it by sourcing: :source %.runpaint.
Visit http://vim.vba extension).) Vim 7 added support for a new plugin installation method called vimball. but if you find a plugin distributed in this way (they have a *. They're not in wide use yet.

however. Vim ships with syntax highlighting support for Git output/templates. For example. after executing git commit -a. For an explanation of this convention see A Note About Git Commit Messages. if you colour outside the lines. There's no need to remember this convention.INTEGRATING VIM
WITH
GIT
PROBLEM You use the Git version control system with Vim and want shortcuts for common operations and syntax highlighting for git output. visually. then.
162
. because Vim warns you. wrapped at about 72 characters27.
SOLUTION Thanks to the work of Tim Pope and others. with a blank second line. Git commit messages should typically have a 50-character or less summary as their first line. For example:
27. with Vim set as your default editor. optionally a long explanation. you'll see
Vim can even help you write better commit messages.

of course.syntax} ~/. Install it by copying its files to your Vim directory.vim cd /tmp git clone git://github.vim/ cd -
You now have access to commands such as :GitCommit.git cp -r git-vim/{plugin. This makes it especially suitable for situations where one
uses multiple version control systems.
motemen's git-vim plugin extends this support by adding shortcuts and commands for common
Git operations.
Visit http://vim. SVN.Vim Recipes
In this example. so the extraneous characters are coloured black.org/ for latest updates. which will. the first line is too long. For example. that the current file is located in a Git working directory).
✪
Bob Hiestand's vcscommand plugin offers similar functionality to git-vim. on Linux:
mkdir -p ~/.
also supports
and SVK.com/motemen/git-vim. your file will be committed. Once you have written your commit message and quit the buffer.runpaint. The second line should be blank. (This assumes.
163
. so it has a red background to indicate its contents are in error. split your window horizontally. loading the Git commit template into the upper pane. but it
CVS.

For instance. For a complete list of shortcuts offered by this plugin see its README. The git-vim plugin expedites this process by providing Normal mode shortcuts. etc. and hides extraneous output. This example and those following assume that your Leader variable is set to the default of /.rdoc file. allows inline editing. :!git add % would add the current file. see :help leader for details.
28. \ga28 adds the current file. 29. Vim's ability to execute external commands already makes using git reasonably straightforward. while :!git log would temporarily suspend Vim to show you the commit log.
164
. because otherwise version control will become a source of distraction that steals your focus and wastes your time.29
git-vim takes this integration further for commands like :GitBlame where the window is
split vertically to show the author's name alongside the lines he was responsible for. shown below.
This presentation is clearly superior to the output of :!git blame %. if Git is tightly integrated into Vim. Git invites regular commits. however. in that it employs syntax highlighting. \gc commits it. This is only feasible.DISCUSSION Through a combination of editable history and particularly fast operation.

165
.Vim Recipes
Visit http://vim.runpaint.org/ for latest updates.

OTHER USES OF VIM
166
.

To force a directory listing in a split pane.Vim Recipes
BROWSING DIRECTORIES
PROBLEM You want to see the contents of a directory.org/ for latest updates. and :Tex to browse in a new tab.
DISCUSSION By default Vim lists every file contained in a directory. but you can provide a directory name if you wish. that's not a joke.runpaint. (This is a commaseparated list of regular expressions).
SOLUTION Invoke Vim with a directory name as an argument. vim ~/projects/flying-pigs/.*'. the concept is synonymous with Vim
Visit http://vim. Similarly. To get a more ls-style listing you can specify a hiding list with :let g:netrw_listhide='\^\.
167
. :Vex to browse in a vertical split.g. By default it shows the contents of the current file's directory. From within Vim use the :Ex (mnemonic: Explore) command. so you can view a file and its directory listing at once. The directory is shown in a split screen if the current file has been modified. if working on a project comprising multiple files you want to see a list of the files in a separate window. perhaps so as to select a file to edit. use :Sex30. For instance. When you're browsing a directory files starting with a
30. e.. For example: :Ex ~/projects/flying-pigs. No.

If you want to operate on the files you see read Using Vim as a File Manager. To change how directory entries are sorted you can modify the g:netrw_sort_sequence variable.\. By default its value is.obj$. You can change into a directory by selecting it and hitting Enter The same thing works for Enter. The next pattern matches file names ending with *.bak$. If you'd rather open a file in a new buffer use p.
168
.swp$. The * pattern matches everything not matched by the other patterns. By Unix/Linux convention filenames which begin with a period are designated hidden. By default file browsers and other utilities ignore these files unless explicitly commanded not to. For instance.h (C header files).\.*.\.c$.\.cpp$. And so on. files.o$.h$. deep breath:
[\/]$. You can change this pattern on-the-fly by hitting S while viewing a directory listing. so they're shown next. showing everything. If you hit a again you'll remove the hiding list.period will now be hidden.
31.
31
If you hit a once you'll invert the hiding list (showing only
hidden files).\. P will open the file in a split screen.\.\. the first pattern matches directories.\.\~$
The order of the patterns is the order of the sort.info$. so they're shown first.

org/ for latest updates.
169
. • Mark files matching a Vim regular expression mr (mnemonic: mark with regular expression: expression).
• Mark the file under the cursor: mf (mnemonic: mark file). • Unmark the marked file under the cursor: mf mf. You're then prompted for a pattern. then j and k to change the selection area. you want to rename files matching a certain pattern. • Unmark all files: mu (mnemonic: marks undo).
For example.
⇰
Marking Files
To operate on files you must first mark them (this does not have any relation to the marks feature). <Shift>-
Visit http://vim. so read it first.runpaint. • Visually mark files: <Shift>-v. or Windows Explorer.Vim Recipes
USING VIM
AS A
FILE MANAGER
PROBLEM You want to use Vim to manage your file system in a similar way to Nautilus. Midnight
Commander.
SOLUTION Browsing Directories explains the basics of working with directories in Vim. Or you want to compress the contents of a directory.

(Other compression utilities Compress/Decompress can be used instead of gzip. Diff: • Printing hit mp to print marked files (mnemonic: mark print). key mapped. You're prompted for each file you've selected. Renaming: • Copying/Moving: Hit mt (mnemonic: mark target) in the target directory. you need to select files by marking them. but the Vim command remains the same). and configured in concert with Vim. You can now perform various operations on these files such as: • Deletion hit D. given that it can be scripted.
• Diff To diff up to three marked files. Answering a deletes Deletion: them all without asking you any more. (See the discussion for command: examples).You can operate on a single file or a group of them. Perhaps the most interesting command is mx This allows you to pass the list of marked files mx. then hit mc (mnemonic: marked
copy) to copy or mm (mnemonic: marked move) to move. Change to Copying/Moving the directory containing the source files. • Open in horizontal split: hit o (mnemonic: open). For each file you're prompted for its new name. select them. substituting % for the filename. Vim then loops through the selected files and calls the command for each one. use md (mnemonic: marked diff).
DISCUSSION Vim can be used as a pretty well-featured file manager.
170
. in which you can use the % wildcard. as well as seamlessly operate on remote directories. In the latter case. You're prompted for a command line. • Compress/Decompress: hit mz (mnemonic: marked gzip). Printing: • Execute shell command hit mx (mnemonic: marked execute). to an external command. as explained in the sidebar. it is arguably better. In fact. • Renaming hit R.

using a POSIX-compatible system. bar. if a filename ends with .bunzip2 • .txt. to use Bzip2: :let g:netrw_compress=bzip2.Vim Recipes
For example. select three files (foo.zip . For decompression Vim uses an extension-to-program mapping: • .gunzip • . If a file is uncompressed. For example.unzip For example. By default it uses gzip.
Visit http://vim.txt >>foo-bar-glark cat glark >>foo-bar-glark
foo-bar-glark will now contain the contents of each file in turn.txt >>foo-bar-glark cat bar.tar -xf • .zip Vim decompresses it by calling unzip zip-
file.bz2 .gz .org/ for latest updates. The mz command also bears further discussion. Vim attempts to compress it.
171
. Vim will now execute: mf.txt. To add support for another format use :let g:netrw_decompress[ext] = prog.tar . but you can change this by modifying the g:netrw_compress variable.
cat foo.runpaint. It toggles the state of the selected files between compressed and decompressed. and glark) with mf Hit mx and enter cat %>>foo-bar-glark.

and each file is shown in its own window. You diff a file. To split the screen vertically use :vimdiff file1 file2 or :vert diffsplit
file1 file2. :vimdiff -o file1
file2. If characters inside the line differ they are highlighted in red.
172
. the line in the other buffer that should have held this line is coloured green. as per UNIX convention. and is called a filler line. you want to see the differences between their version and yours. a line that exists in one file but not in another are coloured blue.
The screen is split horizontally. e.
SOLUTION Vim calls this feature diff. Identical lines have no highlighting. Identical runs of lines are folded.VIEWING DIFFERENCES BETWEEN FILES
PROBLEM You have multiple versions of a file and want to see how they differ. if you're working on a document with somebody else. For example. To diff from the command line invoke Vim as vimdiff.g. By default. When a line exists in both buffers it is coloured purple. To diff from within Vim use :diffsplit file. The differences between them are highlighted.

and ]c for the next. For example.txt and grant-proposal.
173
.runpaint. the top pane will automatically scroll to that point. This makes comparing long files easier. but you can disable it with :set noscrollbind. though. This means that if you scroll to line 20 in the bottom pane.Vim Recipes
DISCUSSION Diffs are traditionally used in programming to compare an old and new version of source code to see what has changed.txt. As a general rule. It won't work correctly if you use proprietary. though.txt to see your collaborator's suggestions. They make their changes and e-mail it back. that diff only works with plain text files. As suggested above. you write a file named grant-proposal. You use :vimdiff grant-proposal. too.txt. binary formats such as Microsoft Word's . You can jump between the changes with [c to go to the previous change.txt grant-proposal.
Visit http://vim. It's important to note. The windows diff feature splits your screen so each pane scrolls in concert with one other. then e-mail it to somebody else for input. they're invaluable when collaborating on a file with somebody else. You now have two files: grant-proposal. if Vim can view a file it can diff it.changes.changes.org/ for latest updates.doc.

so instructions follow:
174
. so your existing Vim knowledge still applies. then follow the installation instructions. or add explanatory text that explains the heading's scope. This process enables long or complex documents to be planned and organised in a logical fashion. The installation
process is slightly convoluted.org. you can focus on a particular level by expanding that level of the hierarchy. and there's little to learn. It's completely integrated with Vim.
✪
Debian/Ubuntu users can install Vim Outliner via their package manager. (The Extending Vim with Scripts and Plugins recipe may be helpful here). Download the plugin from VimOutliner.
SOLUTION Use the Vim Outliner plugin. For example. if you were writing an essay you may begin by creating an outline. Vim Outliner satisfies all of the objectives above. the levels of which can be expanded or collapsed.OUTLINING
A
DOCUMENT
PROBLEM You want to create an outline view of a document such that its structure can be treated as a hierarchy. You may then decide to subdivide those headings further. however. As you continue this iterative process. Initially that would consist of the main section headings.

All of the planets are in the next level after that.
175
.e.Vim Recipes
$ sudo apt-get install vim-vimoutliner vim-addon-manager $ sudo vim-addons -w install vimoutliner Add the following line to your vimrc if not already there:
filetype plugin indent on
Now open a new file with an .org/ for latest updates. e. Sun and Planets are the next level down.
vim outline.otl
Each line of this file becomes an entry in the outline. i.otl extension with Vim.g.runpaint. For example:
In this example. Solar System is at the top level of the outline. You can add body text to a heading by starting a new line with a colon followed by a space.
Visit http://vim. Indentation is used to denote levels of hierarchy. Each level is automatically assigned a colour. : Body text.

Using zc on a heading collapses its child elements. if your cursor is over the body text and you hit the fold close command zc the text will be hidden.In the example above. body text has been added to the Sun heading. with the cursor over Planets zc displays:
176
. Continuing the above example. Vim Outliner uses Vim's folds feature. So. so the standard folds commands still work.

where n is the minimum level you want displayed. zO.
Visit http://vim. \1. << reverses the process.org/ for latest updates.Vim Recipes
To expand a tree one level use zo to expand it all the way down use zO zo. A shortcut for expanding the hierarchy to a certain level is \n. Confusingly-similar
name aside. Using \2 on our solar system outline displays only the first. To move a heading to a lower level in the hierarchy use >> in Normal mode. it's worth considering if Vim Outliner doesn't suit you.
177
. \1 collapses every level.runpaint.
✪
A mature alternative to Vim Outliner is TVO (The Vim Outliner).
DISCUSSION A key strength of this form of organisation is that you can view a complex document at a
glance with \1 then drill down to a specific heading to work on it.and second-level headings:
For more information see :help vimoutliner. \0 expands every level.

there is a script named otl2html which can be used to convert a . When I want to start writing notes for a chapter I add body text to a heading. and start typing. then. For instance. as patterns emerge. For instance.org. which target DocBook and AddressDB Palm.html. This lets you create semantically-correct webpages without writing HTML. Vim Outliner comes with various scripts to convert outlines into other file formats. so add them as subheadings to Book on HTML. respectively. see VimOutliner.I use one for my todo/ideas list by putting every item on a line of its own. grouping items under headings.otl file into a . There's also otl2docbook and otl2pdb. I may add a heading for Book on HTML.
178
. For more tools like this. Some time later I think of some chapters.