The 'Vi Improved' Text Editor

Table of Contents

last revision
10 May 2012, 2:14pm
book quality
not too bad

:

Quote: "annoying but excellent" (David Rayner)

Introduction ‹↑›

Vim is a free, open-source text editor which is available for Unix-type operating systems and Microsoft Windows.

Vim is an editor which may prove frustrating to use at first (and later....) but which is capable of editing text rapidly with very few keystrokes. For example typing 'dapGp' deletes the current paragraph (where the cursor is) and copies it to at the end of the document. Vim is especially designed for people who can, or would like to type without looking at the keyboard.

Vim may be regarded as a sharp tool which is capable of carrying out work rapidly but also capable of causing confusion and frustration to its user. Vim is most suited to those people whose work involves significant amounts of writing or dealing with textual information. It is also likely to be most appreciated by those people who are able to 'touch-type'.

Vim (or vi) is installed by default on many Unix systems, including Apple OSX and Linux. The current document is orientated towards using vim on a Unix-style operating system such as Apple OSX or Linux.

Web Resources ‹↑›

www: www.vim.org
the official site
www: http://en.wikibooks.org/wiki/Learning_the_vi_editor/
another book

Cheat Sheets ‹↑›

www: http://www.eec.com/business/vi.html

The Crash Course ‹↑›

The thing was most confuses the new user of the Vim text editor is that when you first start the editor, you are unable to type anything! (at least, until you hit the letter 'i').

The most important thing to know about vim, is that it has 2 (main) modes: 'Normal' mode and 'Insert' mode. In normal mode you can't type anything! Thereby leading the novice to a great deal of confusion, perplexity and desperation. In order to start entering text in the editor, you have to type 'i', (which puts the editor in Insert Mode). Hitting the [esc] key, goes back to Normal Mode (in which you can enter commands). If you can overcome this initial hurdle in using Vim, you may (one day) appreciate its qualities.

One important hint: If vim seems to have gone completely mad... check that the caps lock key is not on!

get me the hell out of here!!, (save and exit)

 [esc] ZZ
 [esc] :wq! [enter]   if the previous didn't work!

put the Vim editor into 'insert' mode so you can enter some text

 i

undo the change which you just made (your gonna need this!).

 [esc] u
 :u  the same

Any command beginning with ':' must be terminated by pressing the [enter] key.

repeat the thing you just did

 .

redo the change which you just undid

 [esc] :red [enter]

stop inserting text

 [esc]

find the word 'big' in the file

 [esc] /big

view the helpful user guides to vim. These are more understandable than the reference manuals

 :help user

view the help for the command ':w' (the save file command)

 :help :w

getting help for the Vim editor

 :help
 :help <command-name>

Getting Help ‹↑›

Vim contains an extremely comprehensive set of help files but unfortunately to the uninitiated this help system can be as impenetrable as the vim editor itself. One reason is that the vim help system uses its own form of 'hypertext', that is, the help files contain links such as |uganda| between bar characters. To navigate to that link you need to press <control> ] (the control key followed by the ']' character). Who would guessed that? To navigate back to the previous link, you need to press <control-t>

The help obtained through typing ':help topic' can be very cryptic for the same reason that unix man pages and javadoc files are cryptic ... there are virtually no example commands. This cryptic-ness seems to form part of a venerable but annoying unix tradition. Luckily with the advent of the web you can find countless good tutorials and examples with Google.

www: http://vim.runpaint.org/toc/
good advanced tips, with explanations
www: www.vim.org/tips/index.php
lots of tips
www: http://vim.wikia.com/wiki/Main_Page
more tips
www: http://rayninfo.co.uk/vimtips.html
probably the best set of tips on the web.
display the help for the 'y' (yank) command
 :help y

display the help for the ':set' command

 :h :set
 :help :set     the same

display some help for vim from the command line

 vim -h      this help is mainly about options, not how to use
 gvim -h     the same if you using gvim

display help for the <control-r> key combination (from 'normal' mode)

 :h ctrl-r

press tab after a partial help term to cycle through the choices

 :h qui<tab>         this means, type ':h qui' and then press [tab]

press <control-d> after a partial help term to list all the choices

 :h qui<control-d>   type ':h qui' and then press <control-d>

Press <tab> to choose one from the list.

display the tips from the help file

 :h tips

start the vim tutorial

 :h tutor

see a vim tutorial from the command line (shell)

 vimtutor

what's \r in a regexp (matches a <CR>)

 :h /\r -

get help for the '\@=' pattern in searches or jumps

 :h /\@=

view help for using '[control] r' when in insert mode

 :h i_CTRL-R
 :h c_CTRL-R - the same for 'command' mode
 :h v_CTRL-V - the same for 'visual' mode

view the help for customizing the vim help files

 :help add-local-help

rebuild all *.txt help files in /doc

 :helptags /vim/vim64/doc

Searching The Vim Help Files ‹↑›

search the vim help files for the text 'utf8'

 helpg utf8
 helpgrep utf8     the same

When the above search is executed the first help file containing the text 'utf8' will be opened at the appropriate spot in a new vim window.

jump to the next file found by 'helpgrep'

 :cn

jump to the previous file found by 'helpgrep'

 :cp

search the vim help files using a pattern (regular expression)

 :helpgrep edit.*dir  will find 'edit' followed by 'dir' 

The Vim Help System ‹↑›

The vim help system uses its own type of 'hyper-text' with links embedded in the text.

within the vim help system, to navigate to a 'link' press <control ]>

 <control-]>

within the vim help system, to navigate to the previous page

 <control-t>

The Vim Annoyances ‹↑›

In order to go into 'normal' mode (where you can enter commands such as 'D' delete the rest of the line) you have to press the [escape] key which is quite difficult to find without looking at the keyboard.

But there are several solutions to this, probably the best is to map 'fj' or 'jj' to <esc>

map the key combo 'fj' in insert mode to the '<escape>' key

 :imap fj <esc>
 :inoremap fj <esc>   the same, but subtly different

The mapping should use a key combination which is not likely to occur often in your language or documents. In English this would be, for example 'fj'. In order to insert 'fj' in the document you just need to type the fj slowly.

'normal' mode does not seem very normal, and seems a confusing name for that mode.

map [shift] [space] to go to 'normal' mode, but doesn't work for me

 :imap <S-Space> <esc>

help for help (USE TAB)
:h quickref - VIM Quick Reference Sheet
:h ctrl<C-D> - list help of all control keys
:h \\zs - double up backslash to find \zs in help ???
:cabbrev h tab h - open help in a tab

I find 'K' annoying. It looks up help under the cursor. But this is never what I want, since I always hit it by mistake for 'k'

remap K to be more innocuous (goes down 30 lines)

 :map K 30+

Traps ‹↑›

alternatives to the escape key
[control] [
[control] c
:imap jj <esc>
:imap ;; <esc>

Starting Vim ‹↑›

open the file 'list.txt' with the cursor on line 24

 vim +24 list.txt

open the file 'test.txt' at the 1st line which contains 'hello'

 vim +/hello test.txt

prevent modifications to a file

 :set noma

start vim in insert mode

 vim -c start

from bash, delete those pesky swap files

 find /home/ -iname '*.swp' -delete

a bash function to delete vim swap files

 delswap () { find /home/ -iname '*.swp' -delete ; }

Swap files for vim (.swp) contain a file which was being edited but not saved. Only delete them if you are sure.

Opening Files To Edit ‹↑›

edit the text file 'poem.txt' in the current folder

 vim poem.txt

edit all files found having a specific string found by grep

 grep -Hrli 'foo' * | xargs vim

edit the file which was just mentioned on the command line

 less ~/docs/poem.txt
 vim !$         this opens the file '~/docs/poem.txt' for editing

choose a file from the current directory to edit

 :e .         the dot IS necessary

choose a file to edit

 :E           no dot is necessary

edit the file most recently edited in the current session

 :e #

reload the current file which has been modified in another editor

 :e!

search for the location of the file name (or similar) under the cursor

 :!locate "<cword>" | less

edit a compressed file (.Z, .gz .bz2)

 vim file  same as editing a normal file, thanks to the 'gzip' plug-in

Edit a script that's somewhere in your path.

 vim `which <script-name>`
 vim $(which <script-name>)   the same

Its possible to edit the standard input stream (usually called 'stdin') This might also be useful for searching multiple files.

edit (a new file) containing lines which contain 'tree' from 'doc.txt'

 grep tree doc.txt | vim - I'm not sure why you would want to do this

Vim traps
In regular expressions you must backslash + (match 1 or more)
In regular expressions you must backslash | (or)
In regular expressions you must backslash ( (group)
In regular expressions you must backslash { (count)
/fred\+/ matches fred/freddy but not free
/\(fred\)\{23}/ note what you have to break

change to the folder of the current document automatically

 :autocmd BufEnter * lcd %:p:h

edit the file which was most recently changed

 vim $(ls -t | head -n1)

open for editing the file whose name is under the cursor

 gf

use tab-completion to open 'long-name.extension' for editing

 :e long<tab>

use file-name completion to insert 'long.name.ext' file in the text

 long. [control] x [control] f

The recipe above means: type 'long.' then press the [control] key, then 'x' then the [control] key again and then 'f'

The Edit Window ‹↑›

VIM: when Ctrl-D and Ctrl-U only scroll one line, reset to default

 :set scroll=0

make the current line the center line of the window

 zz

Editing Multiple Files ‹↑›

In vim we open a file as a 'buffer'. As we edit that buffer, no changes are made to the file until we write that buffer to the file (save it) with the ':w' command. The distinction between a buffer and a file is important.

edit all filenames ending with '.txt' in the current folder

 vim *.txt

edit all files on the computer ending with 'tree' in the filename

 vim $(find / -name "*tree")    'find' may take a while to finish
 vim `find / -name "*tree"`     the same

see all the files currently being edited

 :args

open a new file and edit it

 :arge file

close a file or a buffer, but the file still appears with :args

 :bd

close file number 1 (as shown with the ':ls' command)

 :bd 1

edit lots of files which contain the word 'tree' (including sub-folders)

 vim $(grep -ril tree *)

It would probably be faster to use a find/xargs and grep

substitute yes with no, in all the files, confirming each substitution

 :argdo %s/yes/no/gc | w   the 'w' saves each file

write all files in the argument list (all files being edited)

 :wa

jump to the file (or url) under the cursor

 gf

open a new file (without closing the last) and edit it

 arge <new-file>

toggle between 2 buffers (files) which are open in vim

 [control] ^

This switches back and forth between the 2 files, but it doesnt work when vim is in insert mode (when you are entering text into the document) or command mode (when you are typing commands at the bottom of the screen after a ':' character)

Sessions (Open a set of files)

 gvim file1.c file2.c lib/lib.h lib/lib2.h : load files for "session"
 :mksession  Make a Session file (default Session.vim)

execute multiple commands on a group of files

 vim -c "argdo %s/ABC/DEF/ge | update" *.c

remove blocks of text from a series of files

 vim -c "argdo /begin/+1,/end/-1g/^/d | update" *.c

%s across multiple files with Vim

 :set nomore :argdo %s/foo/bar/g | update

exploring files to edit
:e . - file explorer
:Exp(lore) - file explorer note capital Ex
:Sex(plore) - file explorer in split window
:browse e - windows style browser
:cd .. - move to the parent directory
:args - list files currently open for editing
:args *.php - open all 'php' files in this folder
:lcd %:p:h - change to directory of current file

Operate a command over multiple files
:argdo %s/foo/bar/e - operate on all files in :args
:bufdo %s/foo/bar/e
:windo %s/foo/bar/e
:argdo exe '%!sort'|w! - include an external command
:bufdo exe "normal @q" | w - perform a recording on open files

Switching Between Open Files ‹↑›

make pressing 'T' cycle through (switch between) the open files

 :map T :bn<cr>

a mapping to make key <F5> list all buffers, then type a number to jump

 :map <F5> :ls<CR>:e #

edit the alternative file

commands for multiple files management
:bn - goto next buffer the cycles around (unlike ':n')
:bp - goto previous buffer
:wn - save file and move to next
:wp - save file and move to previous
:bd - remove file from buffer list
:bun - Buffer unload (remove window but not from list)
:badd file.c - file from buffer list
:!mv % %:r.bak - rename current file (DOS use Rename or DEL)
:help filename-modifiers - get help
:e! - return to unmodified file
:w c:/aaa/% - save file elsewhere
:sp fred.txt - open fred.txt into a split
:sball:sb - Split all buffers
:scrollbind - in each split window
:set hidden - Allows to change buffer w/o saving current buffer

Editing In Multiple Windows ‹↑›

Vim windows are not like 'desktop' windows; they are panes into which the text editing area is split.

open the file in a split window above the current file

 :sp file      the original file remains open
 :split file   the same

close the current window

 :q

jump from one window to another

 [control]+w [control]+w

capturing output of current script in a separate buffer

 :new | r!perl #  opens new buffer,read other buffer
 :new! x.out | r!perl #  same with named file
 :new+read!ls

vertically split current file with other.php

 :vsplit other.php

a map to jump quicly between splits

 map <C-J> <C-W>j<C-W>_
 map <C-K> <C-W>k<C-W>_

Transfering Text From One File To Another ‹↑›

open 2 files ('fa' and 'fb') in vim

 vim fa fb

use '[control] ^' to switch between the 2 files

delete a paragraph in one file and paste it in the second

 dap (press [control] ^) p

copy a paragraph to the clipboard and paste it into the second

 yap (press [control] ^) p

a command 'Wr' to (over-)write a paragraph from this file to 'i.txt'

 :com! Wr ?^ *$?+1,/^ *$/-1w ~/i.txt

a command to append a paragraph from this file to another file

 :com! -nargs=1 Send ?^ *$?+1,/^ *$/-1w !cat - >> ~/<args>.txt

The above command can be run with ':Send filename' which appends the current paragraph (wherever the cursor happens to be positioned) to the end of the file 'filename'.

Comparing Files ‹↑›

compare a remote file with a local file

 vimdiff <file> scp://[<user>@]<host>/<file>

complex comparison of parts of a file with itself

 :1,2yank a | 7,8yank b
 :tabedit | put a | vnew | put b
 :windo diffthis

Tabs ‹↑›

Recent versions of vim can use tabs to edit multiple files. I had no idea about this. Tabs are similar to the tabs used in modern web browsers, allowing you to have more that one file open and easily switch between the open files. Tabs are possible more useful than split windows because you do not have to share the 'screen space' between the two files.

commands to switch between open files
:ls - list all open buffers
:e #
:e #3 - edit the 3rd file
:rew - return to beginning of edited files list (:args)
:brew - buffer rewind
<control-^> - switch the alternate open file
:b3 - go to buffer number 3
:b main - go to buffer with 'main' in name eg "main.c"
:bd1 - delete the 1st file from the buffer list

Getting Help For Tabs ‹↑›

view help for using tabs

 help :tab
 help tabpage    better help

show all open tab files

 :tabs

Opening Files In Tabs ‹↑›

open 2 files in vim using tabs

 vim -p fred.php joe.php

open fred.php in a new tab

 :tabe fred.php

reopen files in new tabs

 :tab ball

read the 'vimtips' site from the web into a new tab

 :tabe | :r ! lynx -dump http://zzapper.co.uk/vimtips.html

This is an old link

Closing Tabs ‹↑›

close the current tab

 :tabc
 :tabclose  the same

close all tabs except the current one

 :tabo

exit all tabs and vim in one go

 :qa

Switching Tabs ‹↑›

switch to the next tab. Goes back to the first if on the last tab

 :tabn
 :tabnext                 the same
 [control] [pagedown]     the same again

switch to the previous tab

 :tabp
 :tabN   the same

go to the last tab page

 :tabl

go to the first tab page

 :tabr
 :tabfir

use with vim 7 to force the use of tabs from .vimrc

 :nnoremap gf <C-W>gf
 :cab      e  tabe
 :tab sball    retab all files in the buffer

Editing Remote Files ‹↑›

Use the 'netrw' plug-in, but the version which comes with vim 7.0 for windows does not work well.

edit a file on a sourceforge site with vim

 :e scp://user,project@web.sourceforge.net/htdocs/file.txt

edit the text file 'index.txt' from a webserver

 :r http://nowhere.org/index.txt

The changes made to the file 'index.txt' are only saved locally

create maps to edit files via ftp (using the 'netrw' plugin)

 cmap ,r  :Nread ftp://209.51.134.122/public_html/index.html
 cmap ,w  :Nwrite ftp://209.51.134.122/public_html/index.html
 gvim ftp://www.somedomain.com/index.html

Editing A Wiki With Lynx And Vim ‹↑›

www: http://c2.com/cgi/wiki?UsingWikiWithLynx
instructions on how to use vim and lynx to edit a wiki.
Start lynx; press "o"; in the "Editor" field write "usr/bin/vim" or the path to the "vim" executable (if you dont know this, type "which vim" on the command line). At the bottom of the page activate the "accept changes" link.

Go to a wiki-page in lynx and "click" on "edit". Go to the edit field and type "control X v" or "control V v". After editing type ":wq" and then click on the save link

Encryption And Vim ‹↑›

The Vim encryption algorithm is stated to be weak. But it may keep the honest people out.

start editing 'file.txt' using encryption

 vim -x file.txt  a password prompt will appear

remove the password for a file (and file encryption)

 set key=

change or add a password for a file

 :X    an 'enter password' prompt will appear

Rot13 encryption is an extremely weak type of encryption and is better described as 'obfuscation'

a tab cheat sheet
:tabe fred.php - open the document 'fred.php' in a new tab
:tabn - switch to the next (or first) tab
:tabc - close the current tab
:tabc - close all tabs except the current tab

Saving Files ‹↑›

set vim to automatically save files on exit or when switching buffers

 :set autowriteall

save a copy of the current file named 'copy.txt'

 :w copy.txt    continue to edit the original file

save a file with a new name ("save as") and edit the new file

 :sav copy.txt

save the current file with a new name by substitution

 :sav %:s/report/list/

save the current file changing the extension to bak

 :w %:r.bak

Save a file you edited in vim without the needed permissions

 :w !sudo tee %    the file must be reloaded
 :w !pfexec tee %  another way, but requires 'pfexec' to be installed

ways to use 'rot13' encryption
ggg?G - encode in 'rot13' whole file (quicker for large file)
:8 | normal VGg? - rot13 from line 8
:normal 10GVGg? - rot13 from line 8
:2025 !rot13 - encrypt with rot13 lines 20 to 25

Saving Chunks Of Files ‹↑›

save highlighted text to a new file

 [shift]+v , highlight text with j or k, then
 :w newfile

save the text between bookmarks 'a' and 'b' to newfile

 'a,'b w newfile

save the lines 200-300 to the end of 'textfile' (append the text)

 :200,300w >> textfile

save the current paragraph to the end of 'textfile'

 !ap<backspace>w >> textfile    <backspace> means press that key

write everything from the current line to the bookmark 'x' to 'file.txt'

 !'x<backspace>w file.txt       the file is created
 !'x<backspace>w! file.txt      if the file exists, it is overwritten

Backing Up Files ‹↑›

load the swap backup of a file into vim

 :recover

Compressed Files ‹↑›

do 'zip' compression on all the currently open text files

 :silent bufdo !zip proj.zip %:p

Filename Modifiers ‹↑›

get help for filename modifiers (for saving files with new names)

 :help filename-modifiers

other save commands
:sav! %<.bak - Save Current file to alternative extension (old way)
:sav! %:r.cfm - Save Current file to alternative extension
:sav %:s/fred/joe/:r.bak2 - do a substitute on file name & ext.

display the full path and filename without the filename extension

 :!echo %:r

Tips ‹↑›

manipulating file names
:h filename-modifiers - help
:w % - write to current file name
:w %:r.cfm - change file extention to .cfm
:!echo %:p - full path & file name
:!echo %:p:h - full path only
:!echo %:t - filename only
:reg % - display filename
<control-R>% - insert filename (insert mode)
"%p - insert filename (normal mode)
/<control-R>% - Search for file name in text
:!echo %:gs/A/a/ - show current filename with all 'A' as 'a'
:!echo %:s/A/a/ - only substitute the 1st occurance
:lcd %:p:h - change to directory of current file
.. @: - repeat last : command (then
www: )

Patterns Or Regular Expressions ‹↑›

miscellaneous useful tips
% - jump to the matching brackets '{}[]()'
. - repeat last modification
matchit.vim - % now matches tags <tr><td><script> <?php etc
:syntax on - colour syntax in PerlHTML,PHP etc
:set syntax=perl - force syntax (usually taken from file extension)
:h regexp<C-D> - type control-D and get a list all help topics containing

www: greedy
This means whether the pattern will try to match the biggest possible chunk of text, or the smallest (non-greedy)
www: back-reference
a reference to a bit of text which was matched by a pattern eg: /\(.\)/\1/ A back reference requires a 'grouping' to work
www: regular
expression A pattern which can be used to match some chunk of text.
see a long description of patterns usable in vim
 :help pattern

find '+3354.43' and replace at the end of a line

 :%s/+\(\d\|\.\)*$//gc   looks for a '+' followed by digits or a '.'

pattern jargon

These character classes above dont work within [...] character classes. For example the search '/[ab\s]/' will not work as you might hope.

Using a character class such as '\a' for an alphabetc character may be better than using the character class '[A-Za-z] because the \w class may also handle international word characters, such as n tilde (the spanish enye) for example.

using '\v' (meaning 'very magic') usually reduces backslashing

 /codes\(\n\|\s\)*where  ##(without the '\v' flag)
 /\vcodes(\n|\s)*where   ##(with the 'very magic' \v flag)

Ex Commands ‹↑›

Ex commands are derived from an ancient text editor known as 'ed' or 'ex'. These commands are usually written after a ':' colon. These commands are often overlooked when using 'vim' but in some circumstances have a zen-like power to achieve low-keystroke edits. These ex and ed commands are well explained in the classic unix treatise 'The Unix Programming Environment' by Kernighan et al.

show a help listing of all vim ex commands

 help holy-grail
 help ex-cmd-index

show help about the ex 'p' (print) command

 :help :p

show every line in the file which begins with a hash '#'

 :g/^\s*#/p  the lines are displayed one screen at a time

view the whole file with unprintable characters made visible

 :%l      good for seeing pesky tab characters

view all blank lines with the invisible characters visible

 :g/^\s*$/l

compress consecutive blank lines

 :g/^\s*$/,/\S/-j|s/.*//

special character classes for vim patterns
\s - whitespace character: <Space> and <Tab>
\S - non-whitespace character; opposite of \s
\d - digit: eg [0-9]
\D - non-digit: eg [^0-9]
\x - hex digit: eg [0-9A-Fa-f]
\X - non-hex digit: eg [^0-9A-Fa-f]
\o - octal digit: eg
\O - non-octal digit: eg [^0-7]
\w - word character: eg [0-9A-Za-z_]
\W - non-word character: eg [^0-9A-Za-z_]
\h - head of word character: eg [A-Za-z_]
\H - non-head of word character: eg [^A-Za-z_]
\a - alphabetic character: eg [A-Za-z]
\A - non-alphabetic character: eg [^A-Za-z]
\l - lowercase character: eg [a-z]
\L - non-lowercase character: eg [^a-z]
\u - uppercase character: eg [A-Z]
\U - non-uppercase character: eg [^A-Z]
\i - identifier character (see 'isident' option)
\I - like "\i" but excluding digits
\k - keyword character (see 'iskeyword' option)
\K - like "\k" but excluding digits
\f - file name character (see 'isfname' option)
\F - like "\f" but excluding digits
\p - printable character (see 'isprint' option)
\P - like "\p" but excluding digits
\_x - where x is any of the above character classes with end-of-line included

Inserting Text With Ex ‹↑›

insert the word 'tree' after the next line starting with a '#'

 :/^ *#/a<cr>tree<cr>.<cr>   but doesnt work as a command

Moving Text With Ex ‹↑›

move the current line to line 100 (inserting not overwriting)

 :m100

move the current line to the bottom of the file

 :m$
 :.m$  the same

move the line number 315 to the top of the file

 :315m0

move lines 316 to 330 inclusive to line 10

 :316,330m10   this inserts the lines at line 10, not overwrites

move all lines which begin with 'doc' to the bottom of the file

 :g/^\s*doc/m$

move the next line which starts with a '#' to the end of the file

 :/^\s*#/m$

Deleting With Ex ‹↑›

delete all lines which start with '#' (which are script comments)

 :g/^\s*#/d

Delete all empty lines from a file with vim

 :g!/\S/d

delete all lines from the current line to the end of the file

 :.,$d

delete the next 10 lines after the current line

 :.,+10d

delete lines not containing 'blue'

 :g!/blue/d
 :v/blue/d    the same

delete between lines with 'joe' and 'fred'

 :g/joe/,/fred/d

Copying With Ex ‹↑›

copy and insert the current line 4 lines below the current line

 :co+3
 :.co+3     the same

copy all lines from the current to the next blank line to line 10

 :.,/^\s*$/co10      the copied lines are inserted, not overwritten

copy all lines from the current to the end of the file into the clipboard

 :,$y
 :.,$y     the same
 :.,$ya    the same
 :.,$yank  the same again

paste the contents of the clipboard after line 100

 :100pu

insert the contents of the clipboard after every line starting with *

 :g/^\s*\*/pu

Reformatting Lines With Ex ‹↑›

on all lines beginning with '>>' join the next line to it

 :g/^\s*>>/j

shift one 'shiftwidth' to the right all lines not starting with a '#'

 :g!/^\s*#/>

simple ex commands
m - move text
d - delete text
> - shift one shiftwidth to the right
< - shift text one shift-width to the left
co - copy text
p - print (the file is unchanged)
l - print text with invisible characters made visible
a - append text
i - insert text

Move all comments the top of the file in vim

 :g:^\s*#.*:m0
 :g/^\s*#.*/m0           the same
 :g/^[:space:]*#.*/m0    also the same

The Ex Global Command ‹↑›

The ex global 'g' command is very powerful, but the syntax may be a little tricky to master

move all lines starting with a 't' to the end of the file

 :g/^\s*t.*/m$

replace 't' with 'T' and 'i' with 'I' on lines containing '<this>'

 :g/<this>/s/t/T/g | s/i/I/g

on lines containing 'ball' sub 'ball' with 'tall' confirming each change

 :g/ball/s//tall/gic

The only problem with this technique above is that it is difficult to quit from the process, since the 'g' command acts like a loop. For making changes with confirmation, it is better to use a simple ':s/a/A/gic' command, which allows the user to terminate the replacement process without completing it.

between bookmarks 'a' and 'b' sub 'eg' with 'ex' on lines with 'tree'

 :'a,'bg/tree/s/eg/ex/gic

Global combined with substitute (power editing)

 :/fred/,/joe/s/fred/joe/gic :  non-line based (ultra)
 :/biz/,/any/g/article/s/wheel/bucket/gic:  non-line based

Find fred before beginning search for joe

 :/fred/;/joe/-2,/sid/+3s/sally/alley/gIC

create a new file for each line of file eg 1.txt,2.txt,3,txt etc

 :g/^/exe ".w ".line(".").".txt"

append all lines containing 'tree' to register a

 :g/tree/y A
 :g/tree/y A | :let @*=@a    put into paste buffer

save results to a register/paste buffer

 :let @a=''|g/Barratt/y A |:let @*=@a

filter lines between bookmarks to a file (file must already exist)

 :'a,'bg/^Error/ . w >> errors.txt

duplicate every line in a file. wrap a print '' around each duplicate

 :g/./yank|put|-1s/'/"/g|s/.*/Print '&'/

replace the text '<x>' with contents of a file, -d deletes the "mark"

 :g/^<x>$/r tmp.txt | -d

display something prettily ??

 :g/<pattern>/z#.5           : display with context
examples of ex line addresses and ranges
123 - line number 123
/doc - the next line containing the pattern 'doc'
. - the current line
?pat - previous with pat
$ - the last line of the file
.-10 - ten lines before the current line
+ - the line after the current line
123234 - from line 123 to line 234
- the line before the current line
'x marked with x
+n n forward
'' previous context
% all lines in the file

perform a substitute on every second line

 :g/^/ if line('.')%2|s/^/zz /

send output of previous global command to a new window

 :nmap <F3>  :redir @a<CR>:g//<CR>:redir END<CR>:new<CR>:put! a<CR><CR>

match all lines containing "somestr" between markers a & b copy after line containing "otherstr"

 :'a,'bg/somestr/co/otherstr/  co[py] or mo[ve]

match lines as above but also do a substitution

 :'a,'bg/str1/s/str1/&&&/|mo/str2/
 :%norm jdd                    delete every other line

call a user defined fuction 'Del' for every line of the document

 :g/^/ call Del()

use a bash command as part of vim command chain

 :.g/^/ exe ".!sed 's/N/X/'" | s/I/Q/

replace 2nd '|' bar character with a star

 :g/|/norm 2f|r*

The command above combines a 'g' global command with the normal mode command '2f|r*' which search forward for the 2nd occurance of the '|' character and replaces it with a '*' asterisc. The 'norm' or 'normal' command is useful for changing from 'command mode' to 'normal mode'

 :g/<pattern>/z#.5|echo "=========="  : display beautifully

a command to open the file under the cursor, creating it if necessary

 :nnoremap gF :view <cfile><cr>

'rot13' encrypt the entire document (this toggles)

 ggVGg?

reverse the order of all the lines in the document (toggles)

 :g/^/m0

The Ex Command History ‹↑›

When you type a ':' character in 'normal' mode you enter 'command' or 'ex' mode. This is where you type commands after the colon at the bottom of the document window. It is possible to use vim itself to edit these commands

get help for editing command lines with vim

 help q:

choose a command line to edit and execute with vim

 q:  press enter to execute the edited command, or ':q' to exit

write all the commands in the history to file

 ?? how

edit the current or a previous command using vim in another window

 :blah [control] f

paste the default buffer into the command line (in command mode)

 :[control] r "

retrieve the last command line command for copy & pasting into text

 i [control] r:

retrieve the last search command for copy & pasting into text

 i [control] r/

choose a previous search to edit and/or execute

 q/

more g (global) commands
:g/gladiolli/# - display matching lines with line numbers
:g/fred.*joe.*bob/ - display all lines with fred joe & bob
:g/\<fred\>/ - display all lines with fred but not freddy
:g/^\s*$/d - delete all empty (blank) lines
:g/fred//joe/j - Join Lines between 'fred' and 'joe'
:g/-------/.-10.d - Delete string & 10 previous lines
:g/{/ /}/- s/\n\+/\r/g - Delete empty lines but only between {...}
:v/\S/d - Delete empty lines (and blank lines having only whitespace)
:v/.//./-j - compress empty lines
:g/^$//./-j - compress empty lines
:g/<input\|<form/p - print line having either '<input' or '<form'
:g/^/put_ - double space file (pu = put)
:g/^/m0 - Reverse the lines of a file
:g/^/m$ - the command has no effect!
:'a'bg/^/m'b - Reverse the lines between bookmarks 'a' and 'b'
:g/^/t. - duplicate every line
:g/fred/t$ - copy (transfer) lines matching fred to the end of the file
:g/stage/t'a - copy lines matching stage to marker 'a' (cannot use .)
:g/^Chapter/t.|s/./-/g - Automatically underline selecting headings
:g/\(^I[^^I]*\)\{80}/d - delete all lines containing at least 80 tabs

Pasting From The Document To The Ex Line ‹↑›

map ',c' to paste the current document line into the command line

 :nmap ,c yy:<C-R>"<backspace>
 :nmap ,c "byy:<C-R>b<backspace>  the same, but a bit better

paste an altered version of the current line to the vim command line

 :nmap ,d :s/^ *>> *//<cr>"ayyu:<C-R>a<backspace>

In the example above, if the current line (the line where the cursor is) was ">> ls", then the command ',d' would paste the text 'ls' into the vim command line, so at the bottom of the vim screen would appear ':ls' which could then be executed by hitting the [enter] key.

remove leading spaces and '>>' characters from beginning of default reg

 :let @" = substitute(@",'^[ ]*>>','','')

strip '#' from the front of the current line and put in the 'a' reg

 :let @a = substitute(getline("."),'^[ ]*#','','')

paste the word under the cursor into the ':ex' line (command line)

 :<C-R><C-W>

Searching For Text ‹↑›

search for the word 'big' (and move the cursor there)

 /big
 /big/     the same, it seems

delete all text until the next occurrence of the text 'big'

 d/big

repeat the last search

 n

repeat the last search in the opposite direction

 N

find joe followed by fred followed by bill

 /joe.*fred.*bill/

find 'begin' followd by 'end' possibly over multiple lines

 /begin\_.*end

search for 'start' followed by 'end' separated by spaces or lines

 /fred\_s*joe/

search for either of the words 'blue' or 'green' and move the cursor

 /blue\|green

search for 'fred' but not 'alfred' or 'frederick'

 /\<fred\>/

Search numbers having only 4 digits

 /\<\d\d\d\d\>
 /\<\d\{4}\>    this is the same
 /\D\d\d\d\d\D  the same again

search for 'fred' and 'joe' in any order

 /.*fred\&.*joe

search for lines beginning with the capital letters 'A' to 'J'

 /^[A-J]/

Search for absence of a digit or beginning of line ??

 /\([^0-9]\|^\)%.*%

show lines matching word under cursor

 [I

search for contents of tags, ignoring "chevrons"

 /<\zs[^>]*\ze>

get help for the '\zs' and '\ze' regular expression pattern

 :h /\zs
 :h /\ze

Search Completion ‹↑›

pull current word onto search/command line

 /<control-r><control-w>

In this context a 'word' means letters surrounded by spaces or by punctuation. For example if the cursor is over the text '.config a' the keystrokes above will pull the word 'config' into the search bar.

Pull current text chunk (word) onto search/command line

 /<C-R><C-A>

A text chunk is any piece of text surrounded by spaces, the same as <cWORD>

Configuring Searches ‹↑›

ignore the 'cases' of letters in searches

 :set ignorecase

jump to the searched-for-word as you type (annoying but excellent)

 :set incsearch

overrides 'ignorecase' if uppercase used in search string

 :set smartcase

Multiline Searches ‹↑›

At times it is necessary to search for text which spans a number of lines in the document. The following commands show ways to do this.

search for 'sea' followed by 'salt' over multiple lines

 /see\_s*salt/

view help for muli-line search patterns

 :h \_

'bugs' followed by 'bunny' anywhere in file

 /bugs\(\_.\)*bunny

search for multiple-line html comments

 /<!--\_p\{-}-->

Repeating Searches ‹↑›

some ex command history commands
:ju(mps) - list of your movements
:help jump-motions
:history - list of all your commands
:his c - commandline history
:his s - search history
q/ - Search history Window (puts you in full edit mode) (exit CTRL-C)
q: - commandline history Window (to full edit mode) (exit CTRL-C)
:<C-F> - history Window (exit CTRL-C)

match word boundaries

 /\<all\>/     matches 'all' but not 'balls'

find the next, previous word under the cursor find the next word under the cursor

 * g*

find the previous word under the cursor

 # g#

find word under cursor (<cword>) (forwards/backwards)

 * # g* g# -

make all searches case insensitive

 :set ignorecase
 :set ic       the same
this affects substitutions with s/// as well as searches

make all searches case sensitive (the default)

 :set noignorecase

VIM has an its own 'grep' command (different from the bash one)

 :grep some_keyword *.c   get list of all c-files containing keyword
 :cn                      go to next occurrence

search through multiple files

 :bufdo /searchstr/   use :rewind to recommence search 

multiple file search better but cheating

 :bufdo %s/searchstr/&/gic  say n and then a to stop

Summary of repeated searches
; - f t, F or T
- f, t, F or T in opposite direction
n - last / or ? search
N - last / or ? search in opposite direction

using regular expression back references in a search

 /\(fred\).*\(joe\).*\2.*\1

The above will find 'fred and joe. fred & joe' for example

Repeating the Regexp (rather than what the Regexp finds)

 /^\([^,]*,\)\{8}

How to search for a URL without backslashing

 ?http://www.vim.org/  (first search BACKWARDS

Specify what you are NOT searching for (vowels)

 /\c\v([^aeiou]&\a){4}    search for 4 consecutive consonants
 /\%>20l\%<30lgoat        Search for goat between lines 20 and 30
 /^.\{-}home.\{-}\zshome/e  match only the 2nd occurence in a line of "home" *
 :%s/home.\{-}\zshome/alone  Substitute only the occurrence of home in any line

find str but not on lines containing tree

 ^\(.*tree.*\)\@!.*nose.*$
 \v^((tree)@!.)*nose((tongue)@!.)*$
 .*nose.*\&^\%(\%(tree\)\@!.\)*$
 :v/tongue/s/nose/&/gic

Searching Multiple Files ‹↑›

Vim includes its own 'grep' (search) command, which may be of particular use on Microsoft windows were there is no built in grep command

Using vimgrep with copen

 :vimgrep /keywords/ *.php
 :copen

use argdo to search multiple files

 :argdo /hello/   ?? unchecked

view what program will be used to execute a 'grep' search on this compu.

 :set grepprg

gvim's use of external grep (win32 or *nix) : creates a list of all matching files

display a list of all '.php' files which contain the text 'ocean'

 :grep ocean *.php

use :cn(ext) :cp(rev) to navigate list

 :h grep

Advanced Searches ‹↑›

finding empty lines
/^\n\{3} - find 3 empty lines
/^str.*\nstr - find 2 successive lines starting with str
/\(^str.*\n\)\{2} - find 2 successive lines starting with str

Search Commands ‹↑›

a command to display lines containing some text in a new window

 com! -nargs=1 Show !sed -rn '/<args>/p' % | zenity --list --column=

display matching lines in a new window, with case-insensitive search

 com! -nargs=1 Show !grep -i '<args>' % | zenity --width=600 --height=600 --list --column=

display lines having 'tree' in a window, with case-insensitive search

 :!grep -i 'tree' % | zenity --width=600 --height=600 --list --column=

display lines having 'tree', insert the selected line in the document

 :r !grep -i 'tree' % | zenity --width=600 --height=600 --list --column=

display all uppercase lines and insert the selected line

 :r !grep '^ *[A-Z][A-Z][^a-z]*$' % | zenity --width=600 --height=600 --list --column=

Search And Replace ‹↑›

zero-width searches
:h /\@= - get help
/<\@<=[^>]*>\@= - search for tag contents ignoring chevrons
/<\@<=\_[^>]*>\@= - search for tags across possible multiple lines

see a long description of patterns usable with s///

 :help pattern

Before doing a search and replace on an important file it is a good idea to use the 'c' modifier to the 's' command, to check what changes will be made

 :%s/\s\+$//gc remove trailing spaces, with confirmation each time
 :%s/\s\+$//g  remove trailing whitespace, no confirmation

replace the word tall with small in the file, asking for confirmation

 :%s/\<tall\>/small/gc this will replace 'tall' but not 'stall' etc
 :%s/\<tall\>/small/g  the same but with no confirmation prompt

multiple commands on one line

 :%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/
 :%s/a/but/gie|:update|:next then use @: to repeat

remove trailing whitespace on every line

 :%s/\s\+*$//g
 :1,$s/\s\+*$//g            the same
 :1,$s/[[:space:]]\+*$//g   the same again
 :1,$s/[[:blank:]]\+*$//g   almost the same again

turn DOS ^M line breaks into real line breaks

 :%s/\r/\r/g
 :%s/\r//g    Delete MS DOS line ending (^M)

replace all colon ':' characters with semicolons ';'

 :%s,:,;,g    this shows that any char can be used as the delimiter
 :%s/:/;/g    the same

Delete all empty lines from a file with vim

 :g!/\S/d

make multiple consecutive blank lines into only one

 :g/^\s*$/,/\S/-j|s/.*//

Insert the line number at the beginning of each line

 :%s/^/\=line('.').' '

Move all comments the top of the file in vim

 :g:^\s*#.*:m0
 :g/^\s*#.*/m0   the same

get rid of tab characters in the whole file

 :%! expand

replace all slash '/' characters with bar '|' characters

 :%s@/@|@g

memory

 :%s#.*\(tbl_\w\+\).*#\1#  produce a list of all strings tbl_*
 :s/\(.*\):\(.*\)/\2 : \1/  reverse fields separated by :
 :%s/^\(.*\)\n\1$/\1/  delete duplicate lines

non-greedy matching \{-}

 :%s/^.\{-}pdf/new.pdf/  delete to 1st pdf only

use of optional atom \?

 :%s#\<[zy]\?tbl_[a-z_]\+\>#\L&#gc  lowercase with optional leading characters

search for alternate patterns 'goat' or 'cow' and replace with 'sheep'

 :%s/goat\|cow/sheep/gc

insert a blank line every 5 lines

 :%s/\v(.*\n){5}/&\r/   ???

Search And Delete ‹↑›

delete all lines which contain the text 'big'

 :g/big/d
 :g/RE/cmd     the general form of the command

substitution
:%s/fred/joe/igc - general substitute command with confirmation
:%s//joe/igc - Substitute what you last searched for
:%s/~/sue/igc - Substitute your last replacement string

Advanced Search And Replace ‹↑›

using a vim function within a substitution

 :s/<today>/\=strftime("%c")/   insert a date instead of <today>

substitute between 2 bookmarks only on lines with 'fred' in them

 :'a,'bg/fred/s/dick/joe/

get help for the 'non-greedy' operator for patterns

 :help /\{-}

substitute using a register

 :s/fred/<c-r>asome_text<c-r>s/g
 :s/fred/\=@a/g  better alternative as register not displayed

substitute "fred" with contents of register "a"

 :s/fred/<c-r>a/g

substitute singular or plural between 2 bookmarks

 :'a,'bs/bucket\(s\)*/bowl\1/gic

swap 'off' for 'on' and vice-versa

deleting empty lines
:%s/^\n\{3}// - delete blocks of 3 empty lines
:%s/^\n\+/\r/ - compressing empty lines
:%s#.*\(\d\+hours\).*#\1# - Delete all but memorised string (\1)

swap two words

 :vnoremap <C-X> <Esc>`.``gvP``P

Swap word with next word

 nmap <silent> gw    "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l>

break lines at 70 chars, if possible after a ;

 :s/.\{,69\};\s*\|.\{,69\}\s\+/&\r/g

find replacement text, put in memory, use '\zs' to simplify substitute

 :%s/"\([^.]\+\).*\zsxx/\1/

all following performing similar task, substitute within substitution Multiple single character substitution in a portion of line only

 :%s,\(all/.*\)\@<=/,_,g  replace all / with _ AFTER "all/"

same thing

 :s#all/\zs.*#\=substitute(submatch(0), '/', '_', 'g')#

substitute by splitting line, then re-joining

 :s#all/#&^M#|s#/#_#g|-j!

substitute inside another substitute

 :%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/

Commands To Search And Replace ‹↑›

a simple search and replace command with confirmation

 :command! -nargs=1 Rp :% s/<args>/gc
 :Rp this/that    this invokes the command

Pull word under cursor into LHS of a substitute

 :nmap <leader>z :%s#\<<c-r>=expand("<cword>")<cr>\>#

Using Cword And Cfile ‹↑›

map H to look up the word under the cursor with 'man' (like K used to)

 nmap H :!man <cword><cr>

display the filename which is under the cursor

 :echo expand("<cfile>")

If the cursor is currently over a piece of text which contains '[a:image/file.png]' then this will display 'image/file.png'

display the space delimited 'word' (text chunk) under the cursor

 :echo expand("<cWORD>")

It the cursor is over the word 'function' in some text such as 'the function(a,b) is' then the command above will display 'function(a,b)'

[/usr/share/httpd/icons/bomb.png]

open the filename under the cursor with the right program

 :!xdg-open <cfile>

open the filename under the cursor with the right program on OSX

 :!open <cfile>

a mapping ',o' to open a file with the right program

 :nmap ,o :!xdg-open <cfile><cr>

map ',o' to play an mp3 file under the cursor

 :nmap ,o :!mpg321 <cfile><cr>

If this command above is to be put in the 'vimrc' file then it should not have the first colon ':'. This is different from the 'gf' built-in vim command, because 'gf' opens the file under the cursor for editing, but the above mapping will open the file with what ever program is appropriate for the file-type (so an image file will be opened with an image viewing program, etc)

a mapping that displays what word will looked up with 'man'

 nmap H :!man <C-R>=expand("<cword>")<cr>

make a mapping ',ee' to execute the current word as a bash command

 :nmap ,ee :! <cword><cr>

 nmap ,ee :echo man <C-R>=expand("<cfile>")<cr>

Uppercase And Lowercase ‹↑›

Warning: :s///... etc is affected by the setting of 'ignorecase' in the vim settings. Type ':set' and if 'ignorecase' appears the all searches and replaces are going to be case insensitive.

turn off and on case insensitivity in searches with :s///

 :set ic
 :set ignorecase the same
 :set noic

show lines which contain only uppercase letters or spaces

 g/^\(\u\| \)\+$/p

make all text in a file lowercase

 :%s/[A-Z]/\L&/g   only works for 'ascii' text
 :%s/\a/\L&/g      the same, but should work for international text

make all words 'capital case', that is with the first letter in uppercase

 :%s/\<\a\+/\u&/gc    this turns 'hello you' into 'Hello You'

Note that \u \U \l \L have different meanings depending on context. In the right hand side of a s/// expression they mean ...

 :%s/\<\(on\|off\)\>/\=strpart("offon", 3 * ("off"==submatch(0)), 3)/g

escape codes
\l - turn only the next character in the match to lower case
\L - turn all the characters in the match to lower case
\u - convert only the first character in the match to upper case
\u - convert all the characters in the match to upper case

make title case visually selected text (map for .vimrc)

 vmap ,c :s/\<\(.\)\(\k*\)\>/\u\1\L\2/g<CR>

make the current line title case

 nmap ,t :s/.*/\L&/<bar>:s/\<./\u&/g<cr>

Uppercase first letter of sentences

 :%s/[.!?]\_s\+\a/\U&\E/g

Text Indentation ‹↑›

Vim has various options and commands for automatically indenting (that is adding spaces or tabs at the beginning of a line) as you type or for using with commands like 'gqap' (reformat a paragraph). In fact, there are so many indentation options, that one can sometimes become frustated when vim constantly indents lines in an unexpected way.

see the value of the current shift-width (used to in/decrease indentation)

 :set sw
 :set shiftwidth   the same

view help for the 'shiftwidth' configuration option

 :help 'sw'

convert all tabs in a document to an equivalent number of spaces

 :retab    this may change indentation

Automatic Indentation ‹↑›

view help for the 'autoindent' configuration option

 :help 'ai'

make the next line after the current line have the same indentation

 :set ai           when you are typing, the next indent is 'aligned'
 :set autoindent   the same

make sure that vim uses spaces and not annoying tabs for indentations

 :set expandtab
 :set et           the same

reformat a paragraph while preserving the current indentation of the text

 :set ai [esc] gqap :set noai  or just leave 'autoindent' set to on
reformatting means making each line of a similar length

turn off automatic indentation of the next line when typing

 :set noai

Manual Indentation ‹↑›

increase the indentation for the current paragraph by one shift-width

 >ap  you can repeat this operation by just typing .

decrease the indentation for this paragraph and the next 3 paragraphs

 <4ap the indent is decreased by a 'shiftwidth'

decease the indentation by 1 shiftwidth for all lines above the current

 <gg

increase the shift-width of the current line by one 'shiftwidth'

 >>

Changing The Case Of Text
guu - make the current line lower-case
gUU - uppercase line
guap - make lowercase the current paragraph
Vu - make the current line lower-case with visual mode
VU - uppercase this line using visual mode
g~~ - flip case line
vEU - Upper Case Word
vE~ - Flip Case Word
ggguG - lowercase entire file

some indentation options
shiftwidth - (sw) the number of tabs or spaces for an increase or decrease
cindent - automatically indent c code files
smartindent - automatically indent other types of files
autoindent - align the indent of the next line to the current
expandtab - use spaces not tabs for indentations

shifting text in visual mode (with built-in repeat)

 :vnoremap < <gv
 :vnoremap > >gv

also

 >% and <%

My Favourite Settings And Tricks ‹↑›

This section contains recipes which are probably repeated elsewhere in this booklet, but which are my favourite settings and commands which have made vim considerably more enjoyable to use, at least for me.

www: http://bumble.sf.net/books/vim/vimrc.txt
This contains an example .vimrc configuration file with a number of settings, commands and mappings which I have found useful.
make 'jj' or 'fj' do the same as the <esc> key when in insert mode
 :imap jj <esc>
 :imap fj <esc>

make 'T' in normal mode swap between open files

 nmap T :bn<cr>

If you actually want to type a 'jj' or 'fj' into your document then you have to do it slowly.

set the shift-width to 1, with spaces not tabs, align next line below

 :set shiftwidth=1 expandtab autoindent
 :set sw=1 et ai    the same, but terse

Setting the shift-width to 1 makes it easy to indent a paragraph as much or as little as you want with the following

indent a paragraph by 1 shift-width

 >ap

stop the annoying 'K' help look up and make 'K' go down 30 lines

 :map K 30+zz

map ',r' to make it easy to find and replace the word under the cursor

 :nmap ,r :%s/<C-R>=expand("<cword>")<cr>//gc<left><left><left>

swap quickly between 2 files which are open in vim

 vim a.txt b.txt <and then> :n <and then> [control] ^

make a normal mode command ',o' to open a file with the right program

 :nmap ,f :!xdg-open <cfile><cr>
 :nmap ,f :!open <cfile><cr>    for Mac OSX

turn on and off spell-checking by typing ',ss'

 :nmap ,ss :set spell!<cr>
 nmap ,ss :set spell!<cr>   put this in your 'vimrc' file

Working With Text Data ‹↑›

duplicating the columns (fields) of a space delimited file

 :%s= [^ ]\+$=&&= - duplicate end column
 :%s= \f\+$=&&= - same thing
 :%s= \S\+$=&& - usually the same

Working with Columns sub any str1 in col3

 :%s:\(\(\w\+\s\+\)\{2}\)str1:\1str2:

Swapping first & last column (4 columns)

 :%s:\(\w\+\)\(.*\s\+\)\(\w\+\)$:\3\2\1:

format a mysql query

 :%s#\<from\>\|\<where\>\|\<left join\>\|\<\inner join\>#\r&#g

substitute string in column 30

 :%s/^\(.\{30\}\)xx/\1yy/

decrement numbers by 3

 :%s/\d\+/\=(submatch(0)-3)/

increment numbers by 6 on certain lines only

 :g/loc\|function/s/\d/\=submatch(0)+6/

better

 :%s#txtdev\zs\d#\=submatch(0)+1#g
 :h /\zs

increment only numbers gg\d\d by 6 (another way)

 :%s/\(gg\)\@<=\d\+/\=submatch(0)+6/
 :h zero-width

rename a string with an incrementing number

 :let i=10 | 'a,'bg/Abc/s/yy/\=i/ |let i=i+1 # convert yy to 10,11,12 etc

as above but more precise

 :let i=10 | 'a,'bg/Abc/s/xx\zsyy\ze/\=i/ |let i=i+1 # convert xxyy to xx11,xx12,
xx13

Numbers ‹↑›

increment the number which is under cursor

 <control-a>

decrement the number which is under cursor

 <control-x>

If the cursor is over a number such as '124' in the document then one can press <control-x> to decrement that number to '123' These dont work on Microsoft computers.

perform an arithmetic calculation on the 'command' line

 :<C-R>=5*5

incrementing numbers (type '<c-a>' as 5 characters)

 :'a,'bg/\d\+/norm! ^A

increment all numbers in a document which are at the start of the line

 :1,$g/^\d/exe "norm! \<c-a>"

Sorting Text ‹↑›

indentation commands
retab - replace all tabs in the file with an equivalent number of spaces
>> - shift the current line
> - shift a range of lines

sort the whole file using external sort

 :%!sort -u

sort all text between the bookmarks 'a' and 'b'

 :'a,'b!sort -u

sort text after the cursor in the current paragraph

 !} sort -u

sort the current and next paragraphs

 !2ap sort -u

The command above uses the 'ap' paragraph text object. The paragraph text object will sort the entire paragraph where the cursor is currently located, whereas the '}' paragraph movement command will only sort the text which is located after the cursor in the current paragraph.

sort all lines on second column using vims internal 'sort' command

 :sort /.*\%2v/

Csv Data Files ‹↑›

highlight a particular csv column (put in .vimrc)

    function! CSVH(x)
        execute 'match Keyword /^\([^,]*,\)\{'.a:x.'}\zs[^,]*/'
        execute 'normal ^'.a:x.'f,'
    endfunction
    command! -nargs=1 Csv :call CSVH(<args>)

columnise a csv file for display only as may crop wide columns

    :let width = 20
    :let fill=' ' | while strlen(fill) < width | let fill=fill.fill | endwhile
    :%s/\([^;]*\);\=/\=strpart(submatch(1).fill, 0, width)/ge
    :%s/\s\+$//ge

call with

 :Csv 5   highlight fifth column

Filtering Text ‹↑›

remove all consecutive blank lines in the current file

 :%!cat -s     type 'u' undo to see how many lines would be deleted
 :1,$!cat -s   the same
 gg!G cat -s   the same, using motions instead of ranges

remove all extra spaces (consecutive spaces) in the current file

 :%! tr -s ' '

reformat all lines after the current one, wrapping lines

 :.,$!par  par knows how to reformat 'bash comments' for example

insert the result of the 'ls' bash command at the cursor position

 :r !ls | tr '\n' ' '

execute the current line as a bash command (doesnt insert results)

 :.w !bash

filter a block of lines between 2 blank lines adding a '#'

 ?^ *?+1,/^ *$/-1w !sed 's/^/\#/'
 !apsed 's/^/\#/'     the same, using the 'ap' textobject

add comment characters to this paragraph and append to 'test.txt'

 ?^ *?+1,/^ *$/-1w !sed 's/^/\#/' >> test.txt

Line Numbers ‹↑›

inserting line number into file

 :g/^/exec "s/^/".strpart(line(".")."    ", 0, 4)
 :%s/^/\=strpart(line(".")."     ", 0, 5)
 :%s/^/\=line('.'). ' '

make the function key 12 turn on or off the display of line numbers

 :map <f12> :set number!<cr>

numbering lines VIM way

 :set number                   show line numbers
 :%s/^/\=strpart(line('.')."        ",0,&ts)

numbering lines (with perl) starting from arbitrary number

 :'a,'b!perl -pne 'BEGIN{$a=223} substr($_,2,0)=$a++'

produce a list of numbers type in number on line say 223 in an empty file

 qqmnYP`n^Aq     in recording q repeat with @q

increment existing numbers to end of file (type <c-a> as 5 characters)

 :.,$g/^\d/exe "normal! \<c-a>"

a tip for advanced incrementing

 http://vim.sourceforge.net/tip_view.php?tip_id=150

eg create list starting from 223 incrementing by 5 between markers a,b

 :let I=223
 :'a,'bs/^/\=INC(5)/

generate a list of numbers from 23 to 64

 o23<escape>qqYp<control-A>q40@q

number lines

 :new | r!nl #

Reformatting Text ‹↑›

In this context the 'format' of the text means the length in characters of each line, whether the line is aligned to the centre, to the left, the amount of spaces between words and sentences and similar things.

remove extra spaces between words in the current paragraph

 !ap tr -s ' '
 !ap tr -s '[:blank:]'  the same but handles tabs
 !ap s/[ ]\+/[ ]/g      the same but harder to type

Wrapping Text ‹↑›

In this context 'wrapping text' means the process of realigning text so that no line is more than a certain number of characters long. and the amount of indentation of each line. The vim 'gq' command takes into account the current screen size and font size when wrapping the lines.

For reformatting source code see:"working with source code"

set the text width for the document to 70 characters

 set tw=70

see the current line character-width setting (0 means 'automatic')

 set tw

set the line character-width setting back to its default

 set tw&

wrap all lines in the current paragraph to a certain character width

 gqap

wrap all lines in the current document to a certain character width

 gggqG

The lines will be wrapped according to the text character width set with the 'set tw' command

Sorting with external unix sort command
:g/^$/;/^$/-1!sort - Sort each block (note the crucial ;)

The tools mentioned above are unix-type tools but are also available for a microsoft operating system.

format the current paragraph respecting current indentation

 !apfmt

format the next paragraph of text (fill and break lines)

 !}fmt      uses external program 'fmt'
 !}par      the same, but 'par' can do more than format

format the until the end of the paragraph with the vim formatter

 gq}        formats only after the cursor

format the current paragraph with the vim formatter

 gqap             this also formats before the cursor

format the text until the bookmark 'a'

 gq'a

format the entire file

 gggqG

Indentation ‹↑›

turn on autoindenting

 :set ai    useful with 'gq', since it preserves the current indent

Alignment ‹↑›

centre align the whole file with a width of 40

 :%center 40
 :%left 40        left alignment
 :%right 40

center the current line

 :ce

line wrapping formatting tools
par - a formatting tool
fmt - a tool which respects indents
gq - the built in vim formatting tools
commands to fix line-break and space problems
:%s/\r/\r/g - Turn DOS returns ^M into real returns
.. :%s= *$== - delete end of line blanks

Moving Around ‹↑›

This section is about various movement commands available in Vim. Movement commands can follow other commands (such as deleting, or copying) to provide a range for that command. That is, any movement (including a search with '/') can be combined with another command to alter text in the document. This is an important vim concept. For example

delete all text up until the next occurance of the text 'big'

 :d/big

.. :%s= \+$== - Same thing
:%s#\s*\r\?$## - Clean both trailing spaces AND DOS returns
:%s#\s*\r*$## - same thing

go to the beginning of the file

 gg

go to the end of the file

 G

go to line 33

 33G

jump to the last modification line

 '.

jump back to where you just were (before jumping)

 ''    i find this very handy

cycle through recent modifications, forwards and backwards

 g; g,

set a bookmark named 'a' at the current position

 ma      or mb, mc, etc

jump to the position indicated by the bookmark a

 'a

go to the end of the paragraph

 }

go to the next instance of the character 'g' on the line

 fg

repeat this operation

 ;

go BACK to the next instance of the character 'g' on the line

 Fg

move to the matching parenthesis {,[,(

 %

scroll scroll the current line to the top of the window

 zt

jump to the next instance of the word under the cursor

 *

Return to last edit position (You want this!)

  autocmd BufReadPost *
       \ if line("'\"") > 0 && line("'\"") <= line("$") |
       \   exe "normal! g`\"" |
       \ endif

Moving By Searching ‹↑›

search for 'joe' and put the cursor at the end of the 1st match

 /joe/e

put the cursor 1 character after the end of the 1st match of 'frog'

 /frog/e+1

put the cursor 2 character before the start of the 1st match of 'bill'

 /bill/s-2 - cursor set to Start of match minus 2

put the cursor 3 lines after the end of the 1st match of 'ball'

 /ball/+3

Refering To Chunks Of Text ‹↑›

Chunks of text can be referred to by line numbers, motion commands, or 'text objects'.

delete lines 4 to 9

 :4,9d

delete until the next word 'stop' (not including the word)

 d/stop

Text Objects ‹↑›

A 'text object' is just a chunk of text such as a paragraph, sentence or word. The text objects are very useful because they allow you to refer to a chunk of text without knowing the line numbers, or having to position the cursor at the start of the chunk.

get help about the available 'text objects'

 :help text-objects

delete the current paragraph (before and after the cursor)

 dap         'ap' refers to a paragraph

delete the current paragraph and the next 2 paragraphs

 3dap

change the current sentence (before and after the cursor)

 cas

change the current sentence and the next one

 2cas

change the current single quotes quotation

 ci'         leaves the quotation marks
 ca'         deletes the quotation marks

the basic movement commands
j - one line down
k - one line up
h - one character left
l - once character right

available textobjects
aw a word
aW a long word (including punctuation)
iW a long word without white space
as a sentence
ap a sentence
ip a sentence, without the blank lines
a> a angle braket block
a} or aB a brace block
i} or iB a brace block
a] a square bracket block
a) a bracket block
i) a bracket block not including the brackets
a" or a' a quotation (one line only)
i" or i' a quotation not including the quotes

www: http://vim.wikia.com/wiki/Indent_text_object
How to define a new text object

Inserting ‹↑›

insert the current date in a new line

 :r !date
 :.r !date     the same
 :read !date   the same

insert the current date in at the end of the document

 :$r !date

insert the full names of 10 random image files in the document

 :r !locate '*.jpg' | shuf | head -10

insert the current date after the next blank line

 :/^ *$/r !date     doesnt work with tab characters
 :/^\s*$/r !date    handles any kind of whitespace
 :/^[:space:]*$/r !date      the same
 :/^[[:space:]]*$/r !date    the same, again

insert todays date after every blank line in the file

 :g/^\s*/r !date    this seems a bit slow

insert all the text files in the current directory

 :r *.txt               but why would you do this?!
 cat *.txt >> big.txt   similar but not the same, from bash

insert a file listing of the current folder at the top of the file

 :1r !ls

the following doesnt work because vim is running as a different user

 :r !history

insert after the cursor, lines 200-300 of the file 'tree.txt'

 :r !sed -n 200,300p tree.txt

insert an attachment within an email message in vim

 :r !uuencode binfile binfile

Autocompletion ‹↑›

insert the name of a file in current directory into the document

 [control] x [control] f   a text list box appears with names

Inserting From The Web ‹↑›

insert the contents of a webpage as plain text at the end of the file

 :$r !lynx -dump http://server.net/page.html

insert the text file 'file.txt' from the web at the cursor position

 :r http://nowhere.org/file.txt  this may use 'curl'

Inserting A File Into Itself ‹↑›

double the current file (append the file to the end of itself)

 :$r !cat %

insert all comment lines in the file after the cursor

 :r !grep '^ *#' %
 :r !cat % | grep '^ *#'     the same

In the command above, lines beginning with the '#' comment character are copied in the same order to the current cursor position. Exactly why you would want to do this remain unclear but I thought that it was interesting.

Random Text ‹↑›

make a command 'Rand' which inserts some random words in the document

 :com! -nargs=1 Rand r !shuf -n <args> /usr/share/dict/words | tr '\n' ' '
This command can be executed with 'Rand 200' which inserts 200 random words for the dictionary file into the current file after the cursor.

Deleting ‹↑›

delete the current paragraph (deletes before and after the cursor)

 dap            'ap' refers to a paragraph

delete the paragraph after the cursor

 d}

delete the current line and the next line

 dj

delete the current line and the line above it

 dk

delete the rest of the line after the cursor

 D

delete several lines, using visual mode

 [shift]+v, move down (j) or up (k) to select text, press d

delete up to the line number 234

 d234G

delete from current line until the bookmark 'c'

 d'c

Delete first 2 characters of 10 successive lines

 0<control-v>10j2ld

text objects
:h text-objects - get help
daW - delete contiguous non-whitespace
di< yi< ci< - Delete/Yank/Change HTML tag contents
da< ya< ca< - Delete/Yank/Change whole HTML tag
dat dit - Delete HTML tag pair
diB daB - Empty a function {}
das - delete a sentence

delete the current line without destroying default buffer contents

 "_dd

delete the current word without overwriting the current clipboard

 "_daw

Editing ‹↑›

change the rest of the line after the cursor

 C

shift the next paragraph right

 >}       change the shift width with :set sw=4

lower case a line

 guu

upper case a line

 gUU

make the current paragraph uppercase

 gUap

make the next word uppercase

 gUw

Protect a file from unintentional changes

 :set ro   read only

Repeating Edits ‹↑›

Deleting non-ascii characters (some invisible)
:%s/[\x00-\x1f\x80-\xff]/ /g - type this as you see it
:%s/[<C-V>128-<C-V>255]//gi - where you have to type the Control-V
:%s/[-ÿ]//gi - Should see a black square & a dotted y
:%s/[<C-V>128-<C-V>255<C-V>01-<C-V>31]//gi - All pesky non-asciis
:exec "norm /[\x00-\x1f\x80-\xff]/" - same thing
..
www: -
last recording

The Edit Changes List ‹↑›

Summary of editing repeats
. - last edit (magic dot)
:& - last substitute
:%& - last substitute every line
:%&gic - last substitute every line confirm
g% - normal mode repeat last substitute
g& - last substitute on all lines
@: - last command-mode command
:!! - last :! command
:~ - last substitute
:help repeating

Cut Copy And Paste ‹↑›

In vim, copying text to the clipboard is known as "yanking". This text can then be pasted into the text with the "p" command.

copy the current line to the clipboard.

 yy
 ""yy   the same, but unnecessary

paste text into the file after the current position

 p
 ""p    the same, naming explicitly the default register ""

paste text into the file before the current position

 P

paste text after current position and adjust the indent

 ]p

copy to the clipboard all text until the next occurrence of "stop"

 y/stop  the word "stop" is not included in the copied text

copy all text of the current line until the next ":" character

 yf:

Registers ‹↑›

Registers are buffers or 'clipboards' which can hold text or commands. A register can be pasted into the document or executed (if they hold valid vim commands). Registers have one letter names from a to z. A macro can be recorded and and stored in a register with the 'q' command

display contents of all registers

 :reg
 :di  the same ??

display contents of register b

 :reg b

copy the current line into register 'd'

 "dyy

delete the current line and store in register d and the default reg.

 "cdd

store text that is to be changed or deleted in register a

 "act<   change until the '<' character
 "acf<   almost the same

change the word under the cursor, store a copy of the old one in reg b

 "bcaw   a copy of the old word is stored in the default register

strip leading '>>' from a line, copy it into a register and execute it

 :s/[ ]*>>// | normal u"ayy@a

This is useful for executing shell commands in the document which have some prefix

copy (yank) from the cursor to the second instance of ' on the line

 y2f'   the text is copied in the default register ""

copy text on the line up to the next quote and put it in register 'k'

 "kyf'

yank 5 lines into "a" then add a further 5

 "a5yy
 10j
 "A5yy

Putting Text Into Registers ‹↑›

Use a register as a map (pre-load registers in .vimrc)

 :let @m=":'a,'bs/"
 :let @s=":%!sort -u"

append all lines containing 'tree' to register a

 :g/tree/y A
 :g/tree/y A | :let @*=@a    put into paste buffer

put the command ":%!sort -u" into register 's'

 :let @s=":%!sort -u"

We can then execute this command by typing '@s'

Displaying Registers ‹↑›

display the contents of register 'a'

 :echo @a

commands to manage changes to the document
'. - jump to last modification line
`. - jump to exact spot in last modification line
g; - cycle through the recent changes (oldest first)
g - cycle through the recent changes (newest first)
:changes - show what changes have been made to the document
:h changelist - help for above
<C-O> - retrace your movements in file (starting from most recent)
<C-I> - retrace your movements in file (reverse direction)

Appending Text To The Registers ‹↑›

append the current line to the register 'a'

 "Ayy

delete the current line and append it to the register 'x'

 "Xdd

change the word under the cursor and append it to the register 'q'

 "Qcaw

Altering The Contents Of Registers ‹↑›

empty the contents of the 'a' register

 :let @a=''

transfer the contents of the 'a' register to the 'b' register

 :let @a=@b | :let @a=''

remove only the 1st space from the contents of the 'a' register

 :let @a = substitute(@a,'[[:space:]]','','')

remove all space characters from the contents of the 'a' register

 :let @a = substitute(@a,'[[:space:]]','','g')

remove leading spaces and '>>' character from beginning of 'a' register

 :let @a = substitute(@a,'^[ ]*>>','','')

listing the contents of the registers
:reg - display contents of all registers
:reg a - display content of register a
:reg 12a - display content of registers 12 & a
"5p - retrieve 5th "ring"
"1p.... - retrieve numeric registers one by one
:let @y='yy@"' - pre-loading registers (put in .vimrc)
qqq - empty register "q"
qaq - empty register "a"
:reg .-/%:*" - the seven special registers
:reg 0 - what you last yanked not affected by a delete
"_dd - Delete to blackhole register "_ don't affect any register

Pasting Registers ‹↑›

paste the contents of the register 'k' in the document after the cursor

 "kp
 :put k   the same
 :pu k    the same

paste the current line into the default register and execute it

 yy@"  watch out this could have very strange results- user 'u' to undo

paste the contents of register 'b' into the document after the cursor

 "bp

paste the contents of register 'j' into the document before the cursor

 "jP

paste the contents of the default register from 'insert' mode

 [control]r"   press the 'control' key, then 'r', then '"'

paste the contents of the register p from 'insert' mode

 [control]rp   press the 'control' key, then 'r', then 'p'

create a new buffer, paste a register "q" into it, then sort new buffer

 :new +put q|%!sort

The Numeric Registers ‹↑›

The numeric registers ("0 "1 "2 etc) hold the text which was previously in the default register ("") before being replaced with a new yank into the default register.

paste what was formerly in the default register into the document

 "0p

Executing Registers ‹↑›

The registers may also be executed, if they contain a series of valid vim or shell commands. One can record a macro into a register and then execute it.

record a macro to be stored in the register 'y'

 qy    type 'q' to stop recording the macro

execute the contents of the register 'y'

 @y
 :@y   the same

copy the current line into a register and execute it

 "ayy@a
 yy@"    same thing using unnamed register

strip a '#' character of the current line and execute as a vim command

 :s/\s*#\s*// | normal "ayy@a

 execute command just typed in
 u@.

Character And Text Information ‹↑›

show information for the character under the cursor

 ga

count words in a text file

 g<C-G>

Translating With Vim ‹↑›

load the file 'eg.txt' to translate.

 :e eg.txt

save a copy of the file with the name 'eg.en.txt'

 :sav eg.en.txt

Dictionaries For Translation ‹↑›

use curl to look up a dictionary definition of 'tree'

 :!curl dict://dict.org/d:Tree

show all available dictionaries at 'dict.org'

 :!curl dict://dict.org/show:db

show the definition of 'bash' from the free online computer dictionary

 :!curl dict://dict.org/d:bash:foldoc

show all words beginning with 'bash'

 :!curl dict://dict.org/m:bash::prefix
 :!dict -ms prefix tree     the same

show all ways of searching the dictionaries

 curl dict://dict.org/show:strat

show definition of 'elephant' using the dict tool

 :!dict tree

find out what dictionaries are available to query

 :!dict -D

query the spanish english dictionary at 'freedict.org' for word 'hora'

 :!dict -d spa-eng hora

make a command ':Es' to query a dict server for the given word

 :com! -nargs=1 Es !dict -d spa-eng <args>

To use this command we can type ':Es obligar' to look up the meaning of the word 'obligar' in the spanish english dictionary Unfortunately the 'freedict' dictionaries are not very comprehensive.

show some information about the spanish english dictionary

 :!dict -i spa-eng hora

(not very interesting information)

search the word reference site for the spanish word 'obligar'

 :!lynx -useragent="Mozilla/4.73 [en]" -dump "http://www.wordreference.com/es/en/translation.asp?spen=obligar" | sed '1,/Pocket Oxford/d;/Subscribe/,$d' | less

The wordreference site is very comprehensive, but doesnt like 'lynx' visiting it.

a command to search the word reference to translate a spanish word

 :com! -nargs=1 Esw !lynx -useragent="Mozilla/4.73 [en]" -dump "http://www.wordreference.com/es/en/translation.asp?spen=<args>" | less

Preparing A Document For Translation ‹↑›

then put the text '>>' in front of each text line

 :g/\S/s/^/>> /

double space all lines which contain some text (not just spaces)

 :g/\S/put_

triple space a file

 :g/\S/put_ | put_

double space all lines of the document (including empty lines)

 :g/^/put_

a command ":Tr" to 'quote' (>>) on all lines and double space the file

 :com! Tr g/\S/s/^/>> / | put_

translate each line underneath the original line

move all the untranslated (quoted) lines to the end of the document

 :g/^>>/m$

Spell Checking Foreign Languages ‹↑›

If you do not have a spell checking dictionary for a particular language, modern versions of Vim should offer to download it for you when you try to turn on spell checking for that language.

turn on spell checking using a spanish dictionary

 :set spell spelllang=es
 :set spell spl=es       this is the same

turn on spell checking both spanish and english spell-checking

 :set spell spelllang=es,en

turn on spell checking for british english and spanish

 :se spell spl=es,en_gb

find out what the current spell-check language is (or languages)

 set spl

return the spell-check language back to the default (original)

 set spl&

a mapping ',es' to turn on/off spell checking for english and spanish

 :nnoremap ,es :se spell! spl=es,en_gb<cr>

This mapping can be placed in the 'vimrc' configuration file and then the user can type ',es' in normal mode to toggle on or off spell checking for spanish and british english

suggest a better spelling for the word under the cursor

 z=

find out what spelling dictionaries you have installed

 :!find ~ -type f -name '*.spl'

Foreign Languages And Character Sets ‹↑›

Since vim supports the 'utf8' unicode character-set, it should be possible to edit a document written in any language and with any set of characters in the world.

show unicode information for all characters relating to chess :!unicode chess

insert chess characters into the current document

 :r !unicode -m0 chess | tr -d '[:alnum:][:space:][:punct:]'

The above will produce this: ♔♕♖♗♘♙♚♛♜♝

a vim command to insert unicode glyphs pertaining to a term

com! -nargs=1 Uni r !unicode -m0 <args> |tr -d '[:alnum:][:space:][:punct:]'

Right To Left Characters ‹↑›

Some languages (such as arabic, as only one example) are written from the right side of the page to the left. Vim is capable of editing documents written in these languages.

display the current file as right-to-left text

 :set rl!

Special Characters ‹↑›

www: http://www.fileformat.info/info/unicode/char/00e9/index.htm
Character information for an e-acute character
display invisible and special characters (such as line-endings)
 :set list

view help for which characters will be displayed with ':set list'

 :h listchars

View hex value of the character under the cursor

 ga

manipulating registers
:let @a=@_ - clear register a
:let @a="" - clear register a
:let @a=@" - Save unnamed register
:let @*=@a - copy register a to paste buffer
:let @*=@: - copy last command to paste buffer
:let @*=@/ - copy last search to paste buffer
:let @*=@% - copy current filename to paste buffer

display a table of special 'digraph' characters

 :dig

enter an e-acute 'é' character into the document

 i<control-v>233   on a Unix/Linux/Apple computer
 i<control-q>233   on a Microsoft Windows computer

pull a non-ascii character onto search bar

 yl/<C-R>"

search for all non-printable ascii characters

 /[^a-zA-Z0-9_[:space:][:punct:]]

Digraphs (non alpha-numerics)
:digraphs - display table
:h dig - help
i<control-K>e' - enters é

delete all ascii characters from 128 to 255

 :%s/[<control-v>128-<control-v>255]//gi

delete all ascii characters 1 to 31 and 128 to 255

 :%s/[<cntrl-V>128-<cntrl-V>255<cntrl-V>01-<cntrl-V>31]//gi
 :%s/[\x00-\x1f\x80-\xff]/ /g        the same using hex codes
 :exec "norm /[\x00-\x1f\x80-\xff]/" same thing

Spell Checking ‹↑›

get help on spell checking

 :help spell

turn on spell checking with the default language

 :set spell

suggest alternatives to a badly spelled word

 z=

Spell Check Language ‹↑›

view the vim help for the spell-check language option

 :help spl

turn on spell checking, with US English, only for the current buffer

 :setlocal spell spelllang=en_us

turn on spell checking, with british english

 :set spell spelllang=en_gb

set the spell checking language to english or spanish

 :set spelllang=en_us,nl,medical

set the spell checking language to American English, Dutch and Medical

 :set spelllang=en_us,nl,medical

toggle British English spell

 :set spell! spelllang=en_gb
 :set spell! spl=en_gb         the same

find out what language is currently being spell checked

 :set spelllang

return the spelling language to its default

 :set spelllang&

If you set spelllang to a language for which there is not spelling word list, then vim may prompt you to download the file.

Activating Spell Checking ‹↑›

turn off spell checking only for the current file

 :setlocal nospell

turn off spell checking

 :set nospell

Spell Checking Commands ‹↑›

move to the next badly spelled word

 ]s

suggest a better spelling for the current word (near the cursor)

 z=

in a vim script, find a better spelling for a word

 spellsuggest()

Configuring Spell Checking ‹↑›

add the current word to personal dictionary as a good word

 zg

make a normal mode command ',ss' to turn on or off spell checking

 :nmap ,ss :set spell!<cr>

The user can use this mapping by typing ',ss' when the Vim editor is in normal mode (neither an '--INSERT--' nor a ':' is visible at the bottom of the screen). If spell checking is off is will be turned on, and if spell checking is on, it will be turned off

make a mapping ',ss' to turn on or off British English spell-checking

 :nmap ,ss :set spell! spelllang=en_gb<cr>
 :nmap ,ss :set spell! spl=en_gb<cr>    this is the same

a mapping to toggle spell checking and suggest a better spelling

 :nmap ,ss :set spell!<cr>z=

Word lists for vim are kept in '.spl' files

view the help for how spell-checking files are found

 help spell-load

a spanish spell checking file in a utf8 computer should be called

 es.utf-8.spl or es.ascii.spl

Deleting non-ascii characters (some of which are invisible)
:%s/[-ÿ]//gi - Should see a black square & a dotted y

Configuring Vim ‹↑›

Configurations made with :set ... only apply for the current vim editing session. To make them permanent these set's need to be placed one of the vim configuration files (either for the current user or for all users).

Getting Help For Configurations ‹↑›

view help on setting

 :help options

see a brief description of all vim configuration options

 :help option-list

This also shows the long and short names of an option.

see a very detailed description of every single configuration option

 :help option-summary

see detailed help for the 'autoindent' configuration option

 :help 'autoindent'   note the quote characters. they are often needed
 :help 'ai'           the same
 :help 'noai'         the same again
 :help ai             also works, but sometimes doesnt

see detailed help for the 'cindent' configuration option

 :help 'cindent'
 :help 'cin'     the same
 :help 'nocin'   the same
 :help nocin     also works
 :help cindent   No!! shows documentation for the 'cindent' function

see what settings for configuration options are currently in force

 :set       only shows the modified settings
 :set all   show all settings, modified and unmodified

see what the current value of the 'shiftwidth' option is

 :set sw

see what the value for the autoindent option value is

 :set ai?
 :set autoindent?  the same

note: ':set ai' doesnt work, because it turns on autoindent

Vimrc File ‹↑›

The 'vimrc' file is the file where all permanent configurations are stored. This can be tricky because there is a global config file at /etc/vim/vimrc and a local user config file at "~/.vimrc"

show which vimrc file you are using (global or local)

 :echo $MYVIMRC

put commands and configurations in the file, or somewhere else

 ~/.vimrc  this only affects one user, not everybody

edit the global vim configuration file with the needed permissions

 !sudo vim /etc/vim/vimrc

make a command to edit the global vim configuration file (not reload it)

 com! Vimrc !sudo vim /etc/vim/vimrc      executed with ':Vimrc'
 command! Vimrc !sudo vim /etc/vim/vimrc  the same

a command 'So' to reload the vimrc file easily

 command! So so /etc/vim/vimrc   execute with ':So'

reload the vim configuration file

 :so $MYVIMRC
 :source $MYVIMRC   the same
 :source ~/.vimrc   reload the users personal config file

Basic Configuration ‹↑›

dont insert any tabs

 :set expandtab
 set expandtab [in the 'vimrc' file] note there is no colon ':'

set more than one option at a time

 :set expandtab autoindent

These 2 options turn tabs into spaces, and auto-indents the text.

turn on line numbering if it is off, or turn it off it is on

 :set number!
 :set invnumber    the same

The process of turning something off when it is on, or on when it is off, it often referred to as 'toggling'.

set line numbering to its default value

 :set number&

turn on the spell checking option

 :set spell

find the location of the start up configuration files

 :version

change the number of spaces for a shift to 4 (with '>>' for example)

 :set sw=4
 :set shiftwidth=4     the same

show line numbers for the whole file

 :set number
 :set nu      the same

show tabs and ends of lines

 :set list     ':set nolist' to turn it off

show partial commands in the status bar

 :set showcmd

dont show the matching parenthesis when moving around the file

 :NoMatchParen
for some reason, this is not working in my "vimrc" file

DO show the matching parenthesis when moving around the file

 :DoMatchParen

# see also :set showmatch

some mappings to make editing the .vimrc file easier

 :nmap ,s :source $MYVIMRC
 :nmap ,v :arge $MYVIMRC
 :command Vimrc arge $MYVIMRC

Save your sessions in vim to resume later

 :mksession! <filename>

make sure that vim never beeps

 :set vb t_vb=".

make tab completion ignore '.o' and '.exe' and '.bak' files

 :set wildignore=*.o,*.bak,*.exe

The Status Line ‹↑›

www: hacking
vim possibly a good book about vim
The status line is the line at the bottom of the vim window which can display information about the current file, and commands being typed by the user.

view the vim help for the status line

 :help statusline

force vim to actually show a status line,

 :set laststatus=2

set a complex status line for vim

 set statusline=[%02n]\ %f\ %(\[%M%R%H]%)%=\ %4l,%02c%2V\ %P%*

a verbose status line with file-name, file-format, file-type (vim), ascii and hex under the cursor, row and column, length of file in lines

 :set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [ASCII=\%03.3b]\ [HEX=\%02.2B]\ [POS=%04l,%04v][%p%%]\ [LEN=%L]

Advanced Configurations ‹↑›

How to have a variant in your .vimrc for different PCs

some places vim may look for spell files
~/.vim/spell/pl.iso-8859-2.spl
/usr/share/vim70/spell/pl.iso-8859-2.spl
~/.vim/spell/pl.iso-8859-2.add.spl
/usr/share/vim70/spell/pl.iso-8859-2.add.spl
~/.vim/after/spell/pl.iso-8859-2.add.spl
ab mypc vista else ab mypc dell25 endif ,,,

Debugging The Configuration ‹↑›

if $COMPUTERNAME == "NEWPC"

The Configuration File ‹↑›

In vim, the configuration file (or files) is called 'vimrc'. There maybe several configuration files, one for the current user, and one global file for all users.

find out where your vim configuration file is

 :echo $MYVIMRC
 :!find / -name '*vimrc*'  if the above produces no information

make it easy to update/reload .vimrc

 :nmap ,s :source $VIM/.vimrc
 :nmap ,v :e $VIM/.vimrc
 :e $MYVIMRC   may edit your .vimrc whereever it might be 

Viminfo History File ‹↑›

The viminfo file is where the vim command history is stored as well as other session information.

Folding Text ‹↑›

http://www.linux.com/archive/articles/114138

'Folds' in text are a way to hide sections of text in a big document to make the document easier to read. When the text is hidden the fold is said to be 'closed' and when the text in the fold is visible then it is 'open'.

Getting Help ‹↑›

view the vim help for folding

 :help folding

Basic Usage ‹↑›

create a fold which hides the next 2 lines

 zf2j  the fold is created and the text is hidden

open all folds in a document

 zR

close all folds in the document

 zM

open the current fold (where the cursor is)

 zo   the fold is still there and can be closed again with 'zc'

open all the nested folds on the current line

 zO

make the current paragraph a fold

 zfap

create a fold from line 1 to 10

 :1,10 fo

close a fold (hide the contents of the fold)

 zc

delete the fold at the cursor

 zd

delete all folds

 zE

delete all the text in a fold (when the fold is closed)

 dd

find where an option was set
:scriptnames - list all plugins .vimrcs loaded
:verbose set history? - reveals value of history and where set
:function - list functions
:func SearchCompl - List particular function

Moving Between Folds ‹↑›

move to the previous fold (even if it is open)

 zk

move to the next fold

 zj

Creating Folds Automatically ‹↑›

creates a fold at each indent level in the document

 :set foldmethod=indent
 :set fdm=indent   the same

The above method is usually only useful for computer programming languages, which are indented in a consistent manner.

create folds in a document one by one with the 'zf' command

 :set foldmethod=manual

create folds between the '<<<' and '>>>' markers

 :set foldmethod=marker foldmarker=<<<,>>>

create folds between '{' and '}' characters (this is useful for 'css')

 :set foldmethod=marker foldmarker={,}

Advanced Folds ‹↑›

a folding method

    vim: filetype=help foldmethod=marker foldmarker=<<<,>>>
    A really big section closed with a tag <<<
    --- remember folds can be nested ---
    Closing tag >>>

Source Code And Vim ‹↑›

The vim editor is often used to write 'code' in programming languages such as c, java, or html to name only a few. The vim editor contains a number of features to make editing source code easier.

adjust the indent level of pasted code to the file

 ]p

go to the definition/declaration of the function/var under the cursor

 gd

align braces in source code

 [shift]+v, select lines, =   [shift]+v enters visual mode

use the brace-block text objects to work with blocks of code

 diB      deletes everything between { and }, not including braces
 di}      the same
 da)      deletes everything between ( and , including braces)

delete between quotation marks and enter new text

 ci"      the cursor can be anywhere within the quotation

another way to get rid of tabs

 :set expandtab|retab

toggle source code folds

 zi   a 'fold' temporarily hides the content of a function or method

fold code on indented sections

 :set foldmethod=indent   each indentation level becomes a 'fold'

execute 'make', and jump to the first error found

 :make    make is usually used for compiling c code

display the next or previous error

 :cn :cp

Searching Source Code ‹↑›

search for declaration of subroutine/function under cursor

 :nmap gx yiw/^\(sub\<bar>function\)\s\+<C-R>"<CR>

File Types ‹↑›

file location of specific file-type configuration files

 /etc/ftplugin/java

Indenting And Formatting Source Code ‹↑›

In order for programming source code to be easer to read and understand, it should normally be 'formatted' according to certain conventions. This is generally referred to as 'formatting' or 'indenting' the source code, although is sometimes also called 'pretty-printing'.

view which program will perform indenting with the '=' command

 :set equalprg
if the response is 'equalprg=' then an internal formatter will be used

indent the whole file using the '=' formatter

 gg=G

indent the current paragraph using the built in formatter

 ap=

indent the current brace {} block

 a}=

reformat (break and fill lines) a bash comment (starting with #)

 !ap par  the par formatter leaves the '#' at the start of the lines

Syntax Highlighting ‹↑›

When different parts of programming code is displayed in different colours or fonts according, the code may be easier to read and understand. This is referred to a 'syntax highlighting'.

see what type of source code Vim thinks the file is

 :set filetype
if the response is 'filetype=' then Vim cant guess

tell Vim that the file is java source code

 :set filetype=java    this normally shouldnt be necessary

turn on syntax highlighting

 :syntax enable
 :syntax on      doesnt respect the current colour-scheme

turn off syntax highlighting (its pretty annoying really)

 :syntax off

an example of setting your own highlighting

 :syn match DoubleSpace "  "
 :hi def DoubleSpace guibg=#e0e0e0

force syntax coloring for a file that has no extension .pl

 :set syntax=perl

change coloring scheme (any file in ~vim/vim??/colors)

 :colorscheme blue

Force HTML Syntax highlighting by using a modeline

 # vim:ft=html:

Force syntax automatically (for a file with non-standard extension)

 au BufRead,BufNewFile */Content.IE?/* setfiletype html

Converting Highlighted Syntax To Html ‹↑›

view the help for converting highlighted syntax

 :help TOhtml

convert highlighted syntax to html (html opens in a new window)

 :TOhtml
 :runtime! syntax/2html.vim  the same, more or less

convert the current line to syntax highlighted html

 :.TOhtml

convert syntax to HTML using style sheets not <font> tags

 :let html_use_css = 1
 :TOhtml

convert with no line numbers, xhtml and css

 :let html_number_lines = 0
 :let use_xhtml = 1
 :let html_use_css = 1

convert code to syntax-coloured HTML

 :source $VIM/syntax/2html.vim     untested

C And Cpp ‹↑›

format the next paragraph of code with the 'indent' c code formatter

 !}indent
 :%!indent   format the whole file

Java ‹↑›

Although 'indent' is designed for 'c' code it does a reasonable job with Java code as well

format the whole file with the external program 'astyle'

 :%!astyle ...
astyle appears to go crazy with anonymous inner java classes

format the current code block (between matching {} ) with 'indent'

 !i}indent   see:"text objects" for an explanation of 'i}'

increase the indent of a code block

 :set sw=1; >i}

decrease the indent of a code block

 <i}

set up the '=' command to format with 'astyle'

 :set equalprg=astyle\ --option=yes\ -q

Code Completion ‹↑›

Code completion, which is also sometimes called 'autocompletion' means that the text editor is able to automatically complete the names of programming functions, methods and objects.

C Plus Plus ‹↑›

more fold commands
zf} - fold paragraph using motion
v}zf - fold paragraph using visual
zf'a - make a fold up to a bookmark

Java ‹↑›

vim tools for auto-completion of code
Ctrl-N - completes 'class' 'while' etc
Exuberant Ctags integration
Taglist - uses Ctags lists declarations
cppcomplete
OmniCppComplete.

Html And Xml And Vim ‹↑›

Html is a way to format documents for displaying on the world wide web. Html uses 'tags' which begin and end with '<' and '>' greater than and less than characters to insert tags in documents. An example of an html tag pair is '<em>big</em>' which would display the text 'big' in an emphasized way (such as in an italic of bold font).

Because of the massive growth of the web and Internet, html has become and important plain text format. In order to properly transform html one needs to actually parse it, rather than just using regular expressions. However for cases where 'near enough is good enough', one can use vim patterns to edit html files.

Xml (extensible mark-up language) is similar to html and many of the commands below may also be used for xml documents

change all the text between '<' and '>' characters

 ci<

delete the text between 2 html tags

 dit

If the original html text was 'the <em>that</em> big' then after the 'dit' command the text would be 'the <em></em> tree'

delete all html tags in the document, leaving text (non-greedy)

 :%s#<[^>]\+>##g

delete html tags which may span several lines (non-greedy)

 :%s#<\_.\{-1,}>##g

delete possibly multi-line html comments (that is: <!-- to -->)

 :%s/<!--\_.\{-}-->//

tools
eclim - tries to integrate eclipse with vim

filter all html form elements into paste register

   :redir @*|sil exec 'g#<\(input\|select\|textarea\|/\=form\)\>#p'|redir END
   :nmap ,z :redir @*<Bar>sil exec 'g@<\(input\<Bar>select\<Bar>textarea\<Bar>/\=fo
   rm\)\>@p'<Bar>redir END<CR>

convert a text file to html

 :runtime! syntax/2html.vim

show help for converting to html

 :h 2html

commands to neutralise < for HTML display and publish use yy@" to execute following commands

 :w!|sav! page.html|:/^__BEGIN__/,/^__END__/s#<#\<#g|:w!|:!vimtipsftp

type table,,, to get <table></table>

 imap ,,, <esc>bdwa<<esc>pa><cr></<esc>pa><esc>kA

Ascii Art ‹↑›

Using normal letters and characters in order to draw pictures or text effects is known as ascii art.

using text objects with html
di< yi< ci< - delete/yank/change html tag contents
da< ya< ca< - Delete/Yank/Change whole HTML tag
dat dit - Delete HTML tag pair

insert the text 'hello' as ascii bubble text in the document

 :r !figlet 'hello'

convert the current line to ascii bubble text

 :. !figlet

insert the current word as ascii bubble text in the document

 :r !figlet "<cword>"

insert an ascii penguin saying hello in the at the current cursor pos

 :r !cowsay -f tux 'hello'

view a random jpg image as ascii art

 :!asciiview "$(locate '*.jpg'|shuf|head -1)"

Colours ‹↑›

display the RGB (Red-Green-Blue) colour under the cursor. eg #445588

 :nmap <leader>c :hi Normal guibg=#<c-r>=expand("<cword>")<cr><cr>

The recipe above probably only works in the vimgui version

Images And Vim ‹↑›

Vim is a plain text editor, and so cannot display images, but it is simple to use another program to display them.

a mapping ',o' to display the image file name under the cursor

 :nmap ,o :!feh <cfile><cr>

map " i" <space> i to search for the image file name under the cursor

 :nmap <space>i :!locate '<cfile>'<cr>

map ",i" to search for jpg images named like the word, and display 1

 :nmap ,i :!locate '<cword>.jpg'\|head -1\|xargs display<cr>

map ",i" to search for the current image and display the 1st match

 :nmap ,i :!locate '<cfile>'\|head -1\|xargs feh<cr>

map ",i" to search for the current image and display a random match

 :nmap ,i :!locate '<cfile>'\|shuf\|head -1\|xargs feh<cr>

map ",i" to search for the current image and display a random match

 :nmap ,i :!locate '<cfile>'\|shuf\|head -1\|xargs feh<cr>

map ",i" to search for png images whose names contain the text of the current word, and to display the first 200 of them

 :nmap ,i :!feh -m $(locate '*<cfile>*.png'\|head -200)<cr>
text

the same as above but display in a random order

 :nmap ,i :!feh -m $(locate '*<cfile>*.png'\|shuf\|head -200)<cr>

Latex And Vim ‹↑›

LaTeX is a system for typesetting documents into publish-quality pdf and postscript format.

www: http://www.vmunix.com/vim/howto/latex.html
set up a mapping to run latex on the current file
 :map ,rl :!latex %<cr>

automatically assign a command to the <f1> key when .tex file is opened

 :autocmd bufenter *.tex map <F1> :!latex %<CR>

Using The Shell ‹↑›

One of the great powers of the vim text editor is that it allows interaction with the operating system 'shell'. (A shell is a program which interprets commands typed by the user in a (usually) black box called a 'terminal').

The commands below are oriented towards using the 'bash' shell on a Unix style operating system such as Mac OSX or Linux but some of these commands could be modified to run on a Microsoft Windows computer, especially if 'cygwin' is installed.

tools
gnuplot - create ascii graphs and charts
figlet - bubble ascii text
asciiview - view images converted to ascii art

insert a list of all the files in the current folder

 :r!ls -R

insert all lines from the text file 'eg.txt' which start with 'one'

 :r !grep "^ *one" eg.txt

The matching lines from the text file 'eg.txt' are inserted in the current document at the current cursor position.

execute the previous shell command

 :!!

execute the current document as a unix bash script

 :w !bash
 :w !sh   nearly the same

execute the current line (where the cursor is) as a bash command

 :.w !bash

empty the text file 'test.txt' (beware, all content is lost)

 :!>test.txt

map function-key 9 to process the current file with the php interpreter

 map <f9> :w<CR>:!c:/php/php %<CR>  on microsoft windows
 map <f9> :w<CR>:!php %<CR>         on a mac osx or linux

map function-key 2 to process the current file with perl

 map <f2> :w<CR>:!perl -c %<CR>

create a new file for each line of file eg 1.txt,2.txt,3,txt etc

 :g/^/exe ".w ".line(".").".txt"

Bash And Vim ‹↑›

'Bash' is the most widely used unix-type shell. By default it is installed on Apple Macintosh OsX and on the majority of Linux installations. It can be run on Microsoft windows in a variety of ways, one of which is to install the 'cygwin' package.

a bash function to search for the file and open in vi editor.

 vifind() { vi $(find . -name "$1") }

Batch Mode ‹↑›

Batch mode means running vim from the command-line non-interactively. This document is oriented towards running vim in a Unix-type environment such as Mac OSX or Linux.

get help for the command-line vim options

 vim -h
 man vim

open 2 files into a split window

 vim -o file1 file2
 gvim -o file1 file2    the same using graphical vim

edit only some lines of the input stream

 cat xx | vim - -c "v/^\d\d\|^[3-9]/d "

edit the list of files and folders using 'graphical vim'

 ls | gvim -

execute 2 vim command after opening the file 'test.c'

 vim -c "%s/ABC/DEF/ge | update" test.c

Automate editing of a file (Ex commands in convert.vim)

 vim -s "convert.vim" file.c

load VIM without the .vimrc or any plug-ins

 vim -u NONE -U NONE -N

Access paste buffer contents (put in a script/batch file)

 gvim -c 'normal ggdG"*p' c:/aaa/xp

print paste contents to the default printer

 gvim -c 's/^/\=@*/|hardcopy!|q!'

substitue 'ABC' with 'DEF' on all '.c' files in the current folder

 vim -c "argdo %s/ABC/DEF/ge | update" *.c

remove blocks of text from all '.c' files in the current folder

 vim -c "argdo /begin/+1,/end/-1g/^/d | update" *.c

Piping Text Fragments ‹↑›

It is possible to take a section or chunk of the document being edited and 'pipe' it to a program or script running in the bash (or other shell). This is an important technique since it allows the user to employ the power of the linux shell to perform some task with text from the document. Using this technique the text within the document is unchanged (unlike the 'filtering' technique, which is similar, and which is treated elsewhere in this document).

pipe lines 22,25 though the 'sed' bash shell command

 :22,25w !sed 's/e/E/g'  the original lines are not changed

display all following lines without any '^' carat characters

 :.,$w !s/\^//g'     the lines are piped through 'sed'

save lines after this one in 'new.txt' after removing comment (#) lines

 :.,$w !grep -v '^#' >> new.txt

execute the current line as a bash command and insert results

 :. !bash

execute the current line as a bash command (doesn't insert results)

 :.w !bash

pipe all lines from current to next blank line to sed

 :.,/^ *$/w ! sed 's/e/E/g'
 :.,/^\s$/w ! sed 's/e/E/g'  the same, almost

pipe all lines from current back to previous blank line to 'sed'

 :.,/^\s$/w ! sed 's/e/E/g'  prompts the user to swap order

view lines in this and next 2 paragraphs with lines having 'tree'

 !3ap<backspace>w !grep -v tree | less

compile the current paragraph with pdflatex and save as 'new.pdf'

 !ap<backspace>w !pdflatex -jobname new

pipe from the line after the 1st previous line having a '*' star to the line before the next line containing a ',' comma

 ?\*?+1,/,/-1w !sed 's/e/E/g'    this is quite a complex range

make a command to append a paragraph from this file to 'snip.txt'

 :com! Append ?^ *$?+1,/^ *$/-1w !cat - >> ~/snip.txt

make a command to append a paragraph from this file to another file

 :com! -nargs=1 Append ?^ *$?+1,/^ *$/-1w !cat - >> ~/<args>

a mapping ',x' to append a paragraph from this file to 'snip.txt'

 :nmap ,x :?^ *$?+1,/^ *$/-1w !cat - >> ~/snip.txt<cr>

a simpler way to do the same thing

 :nmap ,x !ap<bs>w !cat - >> ~/snip.txt<cr>
 :nmap ,x !ap<backspace>w !cat - >> ~/snip.txt<cr>

a mapping ',x' to append 3 paragraphs from this file to 'snip.txt'

 :nmap ,x !3ap<bs>w !cat - >> ~/snip.txt<cr>

This can be run with the command ':Append junk.txt' which will append the current paragraph to the file 'junk.txt' in the users home folder.

Gotchas ‹↑›

In the following recipes, the space before the '!' exclamation mark is very important, since without it the command does something very different and possibly destructive.

remember the space

 :22,25w!sed 's/e/E/g'   No!!! wrong, may truncate the current file

Using External Programs ‹↑›

sort the current file

 :%!sort -u

sort the current paragraph (before and after the cursor)

 !apsort -u

look up help for the keyword under the cursor

 K

change the program used to look up keyword help with 'K'

 :set keywordprg=info

The default help program is usually 'man'

map ',ee' to execute the word under the cursor in bash

 :map ,ee :! <cword>

execute 2 shell commands (change to parent folder, and show 'tree.txt')

 :!cd ..; cat tree.txt

Opening Files ‹↑›

make a normal mode command ',o' to open a file with the right program

 :nmap ,f :!xdg-open <cfile><cr>
 :nmap ,f :!open <cfile><cr>    for Mac OSX

If the cursor is positioned over some text which says '[a:/usr/share/httpd/icons/hand.up.png]' for example, and the user types ',f' in normal mode, then the file /usr/share/.../hand.up.png will be opened in an image view program.

Modes In Vim ‹↑›

The concept of modes in vim is important, but is quite a complex topic.

Switching Between Modes ‹↑›

switch to normal mode from command mode

 :normal

Insert Mode ‹↑›

Get output from shell commands
:put=glob('**') - same as above
!!date - replace the current line with todays date

Normal Mode ‹↑›

One of the particularly confusing things about vim is that 'normal' mode does not seem at all normal, in the sense that one is unable to type normally to insert text in the document.

When vim first starts it is in 'normal' mode, and you can enter commands such as 'dd' which deletes the current line, or 'j' which moves down 1 line in the document. To actually type text into the document you need to enter 'insert' mode by typing 'i'.

how to paste "normal commands" without entering insert mode

 :norm qqy$jq

Command Mode ‹↑›

In vim command mode (which seems very similar to 'ex' mode) is entered when you type a ':' colon character in 'normal' mode.

editing/moving within the current insert
<C-U> - delete all entered
<C-W> - delete last word
<c-leftarrow><c-rightarrow> - jump one word backwards/forwards
<C-X><C-E><C-X><C-Y> - scroll while staying put in insert
<C-N><C-P> - completes a word in insert mode
<C-X><C-L> - complete the line in insert mode

a map to delete all lines containing only current word

 nmap ,dd :g/^<C-R><C-A> *$/d

Visual Mode ‹↑›

Visual is the newest and supposedly the most intuitive editing mode. It allows you to select text in the document by 'highlighting' it and them copying, deleting and pasting or anything else. Once you have selected an area of the text by highlighting it, you can then apply any normal vim command and it will be applied to that area.

pulling objects onto command/search line
<C-R><C-W> - pull word under the cursor into a command line or search
<C-R><C-A> - pull WORD under the cursor into a command line or search
<C-R>- - pull small register (also insert mode)
<C-R>[0-9a-z] - pull named registers (also insert mode)
<C-R>% - pull file name (also #) (also insert mode)
<C-R>=somevar - pull contents of a variable (eg :let sray="ray[0-9]")

select a line visually

 V  then use 'k' and 'j' to select lines above and below as well

select until the end of the line visually

 v$

visually select until the end of the file

 VG

substituting a visual area select visual area as usual (:h visual) then type :s/Emacs/Vim/ etc

 :'<,'>s/emacs/vim/g    remember you dont type the '<.'>
 gv                      Re-select the previous visual area 

overwrite a visual-block of text with another such block

 Pick the first block: control-v <move with hjkl> y
 Pick the second block: control-v <move with hjkl> P <esc>

operating a recording on a visual block

    1) define recording/register
    qq:s/ to/ from/g^Mq
    2) Define Visual BLOCK
    V}
    3) hit : and the following appears
    :'<,'>
    4)Complete as follows
    :'<,'>norm @q

visual searching

 :vmap // y/<C-R>"<CR>  search for visually highlighted text
 :vmap <silent> //    y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR> : with spec chars

pull visually highlighted text into the left-hand side of a substitute

 :vmap <leader>z :<C-U>%s/\<<c-r>*\>/

copy a set of columns using a visual block visual block (or column-wise selection) (NOT BY ordinary v command)

 <control-v>

Then select the block with motion commands (win32 <C-Q>) and then a command such as c,d,y,r ...

wrap the html tags '<b>' and '</b>' around visually selected text

 :vmap sb "zdi<b><C-R>z</b><ESC>

wrap <?= ?> around VISUALLY selected Text

 :vmap st "zdi<?= <C-R>z ?><ESC>

Vim Sessions ‹↑›

Basic Visual Mode Commands
v - enter visual mode
<escape> - exit visual mode
vv - exit visual mode
v$ - enter visual mode and select to the end of the line
vap - enter visual mode and select the current paragraph
vapd - delete the current paragraph after highlighting it
V - enter visual mode and select the whole line
gv - reselect last visual area
o - navigate visual area
"*y or "+y - yank visual area into paste buffer
V% - visualise what you match
v}j - join visual block
v}gj - join visual block w/o adding spaces
`[v`] - highlight last insert
:%s/\%Vold/new/g - Do a substitute on last visual area

Command Mappings ‹↑›

www: http://vim.wikia.com/wiki/Mapping_keys_in_Vim_-_Tutorial_(Part_1)
A 'mapping' allows the user to use a key or keys to carry out a command or a series of commands. They are like 'shortcuts'. Put mappings in ~/.vimrc (without the first colon) to make them permanent. When mapping a keystroke or a combination of keys, you should consider what that combination already does (if anything) and whether you really want to override that default action

show the vim help for creating command mappings

 :help key-mapping

show current macros, or mappings

 :map

Following 4 maps enable text transfer between VIM sessions
:map <f7> :'a'bw! c:/aaa/x - save text to file x
:map <f8> :r c:/aaa/x - retrieve text
:map <f11> :.w! c:/aaa/xr<CR> - store current line
:map <f12> :r c:/aaa/xr<CR> - retrieve current line
:map - list of maps beginning ,
 :map <S-s> dd - map <shift-s> to delete a line.
 :map <C-s> dd - map <control-s> to delete a line.
 :map <A-s> dd - map <alt-s> to delete a line.

remove the mapping for 'hh'

 unmap hh

map the function key f5 to delete a line

 :map <f5> dd

map ',hh' to insert 'hello' (from insert mode)

 :map ,hh ihello

map a <space> followed by an 'n' to switch to the next open file

 :nmap <space>n :bn<cr>

create a mapping which calls a command

 :map ,test :Test<cr>

some example mappings

map ',w' to search for . or , or ; but only apply to this buffer

 :map <buffer> ,w /[.,;]<CR>

map ',h' to search for 'Header' but dont echo on the command line

 :map <silent> ,h /Header<CR>

Using Functions In Mappings ‹↑›

To use a Vim function within a mapping, the idiom <C-R>=functionname(...) needs to be used

map [f2] to insert the current date and time after the cursor

 :map <F2> a<C-R>=strftime("%c")<cr><esc>

map ',r' to type the start of a replacement with a word under the cursor

 :nmap ,r :%s/<C-R>=expand("<cword>")<cr>//gc<left><left><left>

cword, cWORD, cfile

 <cword> is the word under the cursor
 <cfile> is the path under the cursor

Example Mappings ‹↑›

map ,ww to write out text from the cursor until 'big' to 'junk.txt'

 map ,ww !/big<enter><backspace>w junk.txt<enter>
 map ,ww !/big<cr><bs>w junk.txt<enter>  the same

mapping 2 commands, ',mm' saves the file and goes to the next word 'big'

 map ,mm w <bar> /big<cr>

map ',ll' to underline the current line with dashes '-'

 map ,ll yyp:s/[ ]*$// \| s/[ ]*$// \| s/[^ ]/-/g \| s/- /--/g<cr>
the dashed underline will have gaps if the words have 2 space gaps

map <space>l to add the current paragraph from this file to 'snip.txt'

 :nmap <space>l :?^ *$?+1,/^ *$/-1w !cat - >> ~/snip.txt<cr>
 :nmap <space>l !ap<bs>w !cat - >> ~/snip.txt<cr>  the same

Saving Mappings ‹↑›

To save mappings, place them in the 'vimrc' file and then they will be available everytime you use vim. In the 'vimrc' file the mappings should not begin with a ':' colon.

write current mappings and settings to file 'map.txt'

 :mk map.txt

Imap ‹↑›

Imapping's occur when the vim editor is in 'insert' mode, that is, when you are entering text into the document.

remove an insert mode mapping for the 'jj' key combination

 :iunmap jj

map tab to show all available vim functions

 :imap <buffer> <Tab> <C-X><C-V>

Nmap ‹↑›

Nmap is used to create 'mappings' when the vim editor is in 'normal' mode, that is the mode when you can move about the document with 'jklh' etc.

map ',c' to paste the current document line into the command line

 :nmap ,c yy:<C-R>"<backspace>
 :nmap ,c "byy:<C-R>b<backspace>  the same, but a bit better

search for declaration of subroutine/function under cursor

 :nmap gx yiw/^\(sub\<bar>function\)\s\+<C-R>"<CR>

Advanced Mappings ‹↑›

a function which checks if a mapping exists

    function! CheckMap()
      if empty(mapcheck('<CR>', 'i'))
        return "No"
      else
        return "Yes"
      endif
    endfunction

Traps With Mappings ‹↑›

in a map it is necessary to backslash the '\' character

 map <f2> /price only\\|versus/

Keycodes ‹↑›

Vim uses special key codes when including certain keys in mappings or commands. The case of the special key-codes is not important, so you may write either '<esc>' or '<ESC>' in your mappings.

www: http://www.vim.org/htmldoc/intro.html#%3CBar%3E
a list of all special key codes for use in mappings and commands
show all the special key codes usable in mappings and commands
 :help keycodes

different types of mappings
:cmap - make a mapping in command mode
:Imap - make a macro in insert and command line mode
:imap - make a macro in insert mode

Abbreviations ‹↑›

Abbreviations in Vim allow you to automatically replace a piece of text which you type in a document with another piece of text. This is useful for corrected very common spelling errors or for quickly typing long repetitive words or phrases.

automatically replace the text "dont" with "don't"

 :ab dont don't

An abbreviation is activated after typing a space or newline after the abbreviation.

stop automatically replacing the word 'dont' with something else

 :unab dont

automatically exchange the text 'frr' for 'Fiscal Responsibility'

 :ab frr Fiscal Responsibility
 :abbr frr Fiscal Responsibility    the same

Viewing Abbreviations ‹↑›

show all abbreviations which are currently available

 :abbr

show all abbreviations which begin with 'php'

 :ab php

Making New Abbreviations ‹↑›

define an abbreviation which inserts several lines of text

 :ab poem froth and foam<cr>here alone<cr>

create an abbreviation which inserts text then searches for 'rain'

 :ab sss snake<esc>/rain<cr>

define an abbreviation in the 'vimrc' file, without the colon ':'

 ab doesnt doesn't

activate different abbreviations in your .vimrc for different PCs

mapping special keys
<esc> - the <escape> key
<enter> or <cr> or <return> - the [enter] key
<space> the space key
<left> the cursor left
<right> the cursor right
<LEADER> - normally \
<SILENT> - No hanging shell window
<BACKSPACE> - backspace
<BAR> - the '|' pipe character
ab mypc vista else ab mypc dell25 endif ,,,

Creating New Commands ‹↑›

A command is anything written after a colon ':'. New commands can be created in Vim. User defined commands must begin with a capital letter.

define the command 'Boo' to delete the current sentence

 :com! Boo normal das
normal switches from command to normal modethis command can be used by typing '[esc]:Boo'

if $COMPUTERNAME == "NEWPC"
a command 'Test' which find the next occurrence of '=='
 :com! Look normal /==<cr>

a command 'TT' which puts 'tree' after the next line starting with '#'

 :com! TT normal /^ *#<cr>otree<esc>

the command 'J' adds 'tree' after next blank line and saves the file

 com! J normal /^ *$/<cr>otree<esc>:w<cr>

the command 'Gr' adds 'grass' 2 lines after the next blank line

 com! J normal /^ *$/+2<cr>otree<esc>

view help on how to make user defined commands

 :help command

see the currently user defined commands

 :command
 :com  the same

delete all new commands which have been defined by the user

 :comclear

create a new command 'Folder' which lists the files in the current folder

 :com Folder !ls
 :command Folder !ls   the same
 :command! Folder !ls  the same, but over-rides an existing command

define command 'squeeze' which combines multiple consecutive empty lines

:command! Squeeze g/^\s*$/,/\S/-j|s/.*//

define command 'Nocomment' which lists the current file without comments

 command! Nocomment !cat % | grep -v '^ *#' | less

This command can be executed with ':Nocomment' within vim

define a command which shows lines having only uppercase letters

 command! Upper !sed -n ';/^ *[[:upper:] ]\{2,\}$/p' % | less

Delete everything after the current line to the end of the file

 :com Ddel +,$d

a command to insert the file 'book.txt' at the current cursor position

 :com Get r book.txt

a command to insert the contents of the url which is under the cursor

 :com Get r <cfile>
 :Get    execute the command just defined

a command to echo the url which is under the cursor

 :com Get echo expand("<cfile>")

With Arguments ‹↑›

Rename the current buffer with filename completion

 :com -nargs=1 -bang -complete=file Ren f <args>|w<bang>

define a command 'Say' with one argument which just echos the given text

 :com -nargs=1 Say :echo "<args>"
 :command -nargs=1 Say :echo "<args>"   the same
This command can be invoked with :Say text

create a command 'Book bookfile' which edits a text file

 command! -nargs=1 Book arge ~/<args>.txt

So we can use this command by typing ':Book tree' to edit the file ~/tree.txt

create a new command 'Sing' which accepts a variable number of arguments

 com -nargs=* Sing

With Line Ranges ‹↑›

define command 'Rep' which replaces a range with the contents of a file

 :com -range -nargs=1 -complete=file Rep <line1>-pu_|<line1>,<line2>d|r <args>|<line1>d

define command 'Lines' which counts the number of lines in a range

 :com! -range -nargs=0 Lines  echo <line2> - <line1> + 1 "lines"
this can be executed with ':.,$ Lines' for example

a command 'Comp' which pipes the given range to 'sed'

 :com! -range -nargs=0 Comp <line1>,<line2>w !sed 's/e/E/g'
 :com! -range Comp <line1>,<line2>w !sed 's/e/E/g'     the same
this could be executed with ':.,$ Comp' for example

make a command to compile to pdf the given range and save as 'new.pdf'

 :com! -range Pdf <line1>,<line2>w !pdflatex -jobname new

 :com! Look normal /==/<cr>    exactly the same

Commands Using Commands ‹↑›

We can define new commands which can then be used in other new commands, for example:

use a previous user-defined command in another for finding images

 command! -nargs=1 Findi !find ~ -name '*.<args>'
 command! Findjpg Findi jpg

Commands And Mappings ‹↑›

Commands can use argument specified after the command name but mappings cannot (since they are entered in 'normal' mode) Mappings can also use a previously defined command.

Recording And Using Macros ‹↑›

A 'macro' in vim is a series of commands which a user carries out while 'recording'. The user is then able to replay that series of commands by invoking the macro. In vim, the names of macros are single letters and are invoked with '@n' where 'n' is the name of the macro.

start recording a macro named 'q'

 qq

stop recording a macro

 q

execute (replay) the macro

 @q

repeat the macro

  
www:
special command parameters
<line1> - the first line of the range with '-range' option
<line2> - another line in the range
<bang> -
..
www: -
to Repeat

editing a register/recording

 "qp        display contents of register q (normal mode)
 <ctrl-R>q  display contents of register q (insert mode)

you can now see recording contents, edit as required

 "qdd     put changed contacts back into q
 @q       execute recording/register q

combining a recording with a map (to end up in command mode)

 :nnoremap ] @q:update<bar>bd

Autocommands ‹↑›

An 'autocommand' is a way of specifying a command which will get automatically executed when a particular event occurs, for example, when a particular file or type of file is opened etc.

an autocommand to place a book mark 'H' in the help files when leaving

macro commands
@q - to execute
5
www: -
to Repeat 5 times
qQ@qq - Make an existing recording q recursive

automatically assign commands to function keys when '.tex' files opened

 :autocmd bufenter *.tex map <F1> :!latex %<CR>
 :autocmd bufenter *.tex map <F2> :!xdvi -hush %<.dvi&<CR>

automatically delete trailing Dos-returns,whitespace

 autocmd BufRead * silent! %s/[\r \t]\+$//
 autocmd BufEnter *.php :%s/[ \t\r]\+$//e

perform an action on a particular file or file type

 autocmd VimEnter c:/intranet/note011.txt normal! ggVGg?
 autocmd FileType *.pl exec('set fileformats=unix')

Functions ‹↑›

These functions can be used in mappings, and scripts. User defined functions need to start with a Capital letter.`

Help For Functions ‹↑›

get help on the built-in functions for vim

 :help functions        an alphabetical function list
 :help function-list    function list categorized by purpose
 :h functions           the same

get help for the 'substitute' function

 :h substitute()

get help for the 'getline' function

 :h getline()
 :h getline

Sometimes it is possible to omit the parenthesis

see all user defined functions

 :functions

list the code for the Leapyear function

 :function Leapyear

delete the Leapyear function

 :delfuncton Leapyear

call a function for a range

 :10,15call Func(...)

redefine a function

 :function! Func()

 au BufLeave * if &ft == "help" | mark H | endif

see a pop-up box with lots of inbuilt vim functions

 [control-x] [control-v]

Using Functions ‹↑›

display the line under the cursor

 :echo getline(".")

Built In Functions ‹↑›

Vim contains a large selection of built in functions which are available for use in commands, mappings, scripts etc

get help for the 'line' function

 help line

display the line number of the last line in the file using 'line'

 :echo line('$')

insert the line number of the last line into the document.

 :.put=line('$')

vim functions
getline(".") returns the text of the current line
line(".") returns the number of the current line

Creating New Functions ‹↑›

 help keycodes

function to delete duplicate lines

    function! Del()
     if getline(".") == getline(line(".") - 1)
       norm dd
     endif
    endfunction

A function to save word under cursor to a file

    function! SaveWord()
       normal yiw
       exe ':!echo '.@0.' >> word.txt'
    endfunction
    map ,p :call SaveWord()

an example of creating and calling a function with a range

    :function Mynumber(arg)
    :  echo line(".") . " " . a:arg
    :endfunction
    :1,5call Mynumber(getline("."))

a function to toggle syntax highlight on and off

    function! ToggleSyntax()
      if exists("g:syntax_on")
       syntax off
      else
       syntax enable
      endif
    endfunction
    nmap <silent> ;s :call ToggleSyntax()<CR>
   ,,,,

   This function includes a mapping to make it easy to call
   the function.

EXAMPLE FUNCTIONS ....

  * advanced incrementing. put the following in the vimrc
   let g:I=0
   function! INC(increment)
   let g:I =g:I + a:increment
   return g:I
   endfunction

Scripting Vim ‹↑›

Vim, like all good overblown software, has its own scripting language built into it, which may be of use if you wish to automate some editing process and you are unable to do it with mappings, macros, abbreviations, user-defined commands, bash shell filters, or any of the other myriad tools available with vim.

www: www.ibm.com/developerworks/linux/library/l-vim-script-1/index.html
a good article about scripting in vim
view some help for programming with vim
 :help eval

view an introduction for scripting vim

 :h script

insert ip range using vim

 :for i in range(1,255) | .put='192.168.0.'.i | endfor

increase the current line by one

 +

put the cursor on the 15th character of the current line)

 :call cursor(line("."), 15)

simple vim script

    :let i = 1
    :while i < 5
    :  echo "count is" i
    :  let i += 1
    :endwhile

Execute this by yanking it with 'y4j' for example and then '@"'. The colons ':' are not necessary in a vim script file (such as the 'vimrc' configuration file)

Executing Scripts ‹↑›

execute the script file '~/scr/eg.vim'

 :so ~/scr/eg.vim
 :source ~/scr/eg.vim    this is the same

create mapping ';s' to execute the script 'eg.vim'

 :nmap ;s :source ~/path/to/eg.vim<cr>

another mapping style

 :nmap \b :call MyBackupFunc(expand('%'), { 'all': 1 })<CR>

Comments In Scripts ‹↑›

put a comment at the start of a line

 :"this is comment

put a comment after a command

 echo "> " |"Print generic promp

Variable Assignment In Vim Scripts ‹↑›

a mapping to set the tabstop to 1 &tabstop is a pseudo var

 nmap <silent> ]] :let &tabstop += 1<CR>

assigning vars

    let name = "Damian"
    let height = 165
    let interests = [ 'Cinema', 'Literature', 'World Domination', 101 ]
    let phone     = { 'cell':5551017346, 'home':5558038728, 'work':'?' }

assign an integer to a variable and display the value

 :let s=7 | echo s

set s to the line number of the current line

 let s = line(".")

subtract 1 from a variable s

 let s=s-1

create a global variable

 let g:I=0

String Variables ‹↑›

see what functions are available for manipulating strings

 :h function-list

assign a string to a variable 's' and display the value of 's'

 :let s="green" | echo s

assign the unicode smiley face to variable s and display it

 :let s="\u263A" | echo s

assign a listing of files in the current folder to variable 's'

 :let s=system("ls")

a more complex 'system' command

 :let flist = system("find " . shellescape(a:dir) . " -type f -name '*.pm' | sort")

embedd newline characters in a string variable

 :let s="1\n2\n3" | echo s

set the variable s to be the string 'grass' and display it

 :let s='grass' | echo s

set s to be 'eat' and display the string length of s (which is '3')

 :let s='eat' | echo strlen(s)

With single quotes there is no interpolation.

Array Variables ‹↑›

In the vim language, arrays are called 'lists'

values usable with the 'line' function
. - the cursor position
$ - the last line in the current buffer
'x - position of mark x (if the mark is not set 0 is returned)
w0 - first line visible in current window
w$ - last line visible in current window

Get Help For Lists ‹↑›

view extensive information about list variable in vim

 :help List    notice the capital 'L' in 'List'

List Information ‹↑›

display the number of elements in a list

 echo len(l)

Creating Lists ‹↑›

create a new list (array) with 4 elements

 :let mylist = [1, "two", 3, "four"]

create a new list with no elements

 :let emptylist = []

Getting Elements From Lists ‹↑›

set a variable 'item' to the value of the 1st element of the list

 :let item = mylist[0]

set a variable to the 3rd element of a list variable

 :let i = mylist[2]

get the last item from the list

 :let i = alist[-1]

get the first four items from a list

 :let l = mylist[:3]

Joining Lists Together ‹↑›

join or concatenate 2 lists together

 :let longlist = mylist + [5, 6]

add 2 new elements to a list

 :let mylist += [7, 8]

get all elements from a list from the 3rd to the last

 :let shortlist = mylist[2:-1]
 :let shortlist = mylist[2:]     the same

assign variable a the 1st value and variable b the 2nd value

 :let [a, b] = mylist

Changing List Items ‹↑›

set the 5th element of the list to 'grass'

 :let list[4] = "grass"

Hashes Or Dictionaries ‹↑›

Dictionaries are what are sometimes known in other languages as 'hashes' or 'associative arrays'. They are a set of items, each of which has a key and a value.

view good help for the dictionary data type, notice the capital D

 help Dictionary

loop over a dictionary

   :for key in keys(mydict)
   :   echo key . ': ' . mydict[key]
   :endfor

loop over a dictionary

 :for key in keys(mydict) | echo key.':'.mydict[key] | endfor

If Tests ‹↑›

All programming and scripting languages have an 'if' test, which either executes or doesnt a block of code based on a test which is either true or false. This all based on logic invented by the greeks or somebody.

test if the variable 's' consists entirely of whitespace

   if s !~ "^\\s*$"
     ...
   endif

test if the variable 's' equals 0

   if s == 0 
     ...
   endif

Exe Or Eval ‹↑›

In vim the classic 'eval' statement is called 'exe'. It allows you to exectute some vim script code which has been constructed from a string. But there is also an 'eval' statement. Its complicated.

execute a new vimscript command

 :exe 'let sum = ' . join(nrlist, '+')

Loops ‹↑›

a for loop to insert an ip range in the document, one per line

 :for i in range(1,255) | .put='192.168.0.'.i | endfor

loop through each item in 'list' calling a function

   :for item in list
   :  call Doit(item)
   :endfor

loop through each item in 'list' calling a function

 :for item in list | call Doit(item) | endfor

while loop

   while p > 0
     ...
   endwhile

Other Stuff ‹↑›

Edit a script that's somewhere in your path.

 vim `which scriptfile`
 vim $(which scriptfile)   the same

Lazy man's vim

 function v { if [ -z $1 ]; then vim; else vim *$1*; fi }

download a sequence of vim patches

 seq -f"ftp://ftp.vim.org/pub/vim/patches/7.1/7.1.%03g" 176 240 | xargs -I {} wget -c {};

Apple Mac With Vim ‹↑›

map the [apple] [space] combination to do the same as [esc]

 :imap <D-space> <Esc>

Microsoft And Vim ‹↑›

On a microsoft operating system the '.vimrc' configuration file is called '_vimrc'

allow use of F10 for mapping (win32)

 set wak=no        :h winaltkeys 

Inserting DOS Carriage Returns

 :%s/$/\<C-V><C-M>&/g    that's what you type for Win32
 :%s/$/\^M&/g            what you'll see where ^M is ONE character

a mapping to launch microsoft internet explorer from vim

 :nmap ,f :update<CR>:silent !start c:\progra~1\intern~1\iexplore.exe file://%:p<CR>
 :nmap ,i :update<CR>: !start c:\progra~1\intern~1\iexplore.exe <cWORD><CR>

reading Ms-Word documents from unix/linux/macosx, requires antiword

 :autocmd BufReadPre *.doc set ro
 :autocmd BufReadPre *.doc set hlsearch!
 :autocmd BufReadPost *.doc %!antiword "%"

using gVIM with Cygwin on a Windows PC

    if has('win32')
    source $VIMRUNTIME/mswin.vim
    behave mswin
    set shell=c:\\cygwin\\bin\\bash.exe shellcmdflag=-c shellxquote=\"
    endif

open joe.c and jump to the first instance of the text 'main'

 gvim.exe -c "/main" joe.c

to access sourceforge from vim on MS Windows put in the vimrc file

 let g:netrw_cygwin = 0
 let g:netrw_scp_cmd = "E:\\tools\\putty\\pscp.exe -pw some -batch

Alternatives To Vim ‹↑›

You may find that Vim is simply too frustrating or counter-intuitive for you, in which case, there are many free and open-source Linux text editors to choose from.

useful list functions
:let r = call(funcname list) - call a function with an argument list
:if empty(list) - check if list is empty
:let l = len(list) - number of items in list
:let big = max(list) - maximum value in list
:let small = min(list) - minimum value in list
:let xs = count(list 'x') - count nr of times 'x' appears in list
:let i = index(list 'x') - index of first 'x' in list
:let lines = getline(1 10) - get ten text lines from buffer
:call append('$' lines) - append text lines in buffer
:let list = split("a b c") - create list from items in a string
:let string = join(list ', ') - create string from list items
:let s = string(list) - String representation of list
eval.txt [Help][RO]

Vim Versions ‹↑›

Gvim ‹↑›

gvim is a 'graphical' version of vim; that is to say that it runs in its own window rather than in the shell window on the operating system. gvim also generally includes some 'menus' at the top of the window which duplicate functionality which is available through other vim commands.

make the gui file-open dialog use the current directory

 :set browsedir=buffer

creating your own gui tool-bar entry

 amenu  Modeline.Insert\ a\ VIM\ modeline <Esc><Esc>ggOvim:ff=unix ts=4 ss=4<CR>vim60:fdm=marker<esc>gg

gvim difference function

 gvim -d file1 file2  vimdiff (compare differences)
 dp    "put" difference under cursor to other file
 do    "get" difference under cursor from other file

The Paste Buffer ‹↑›

The paste buffer may only be available in gvim

other text editors
gedit - the Linux Gnome notepad-like text editor
kate - the KDE notepad-like text editor
emacs - a large capable and widely-used unix editor
sam - a text editor used by old Unix and C veterans
nano - small simple editor from the pine email program

Working with Paste buffer

 "*yy   yank curent line to paste
 "*p    insert from paste buffer

yank to paste buffer (ex mode)

 :'a,'by*                     : Yank range into paste
 :%y*                         : Yank whole buffer into paste
 :.y*                         : Yank Current line to paster

filter non-printable characters from the paste buffer useful when pasting from some gui application

 :nmap <leader>p :let @* = substitute(@*,'[^[:print:]]','','g')<cr>"*p

Vi Keys ‹↑›

The vim or vi key strokes are available in a number of other software tools, such as 'less', 'mutt' (an email client) ...

use the info help viewer with vi key-bindings (key strokes)

 info --vi-keys

Vim Jargon ‹↑›

www: buffer
A buffer is a document or piece of text which we are currently editing. Usually we create a new buffer by opening a file to edit. A file is the document saved on the disk of the computer. After editing a buffer we normally 'write' (save) that buffer to the file. If you type ':e .' a new buffer is created with a list of files in the current folder. You can then save this buffer with ':w test.txt'. The difference between a buffer and a file is important.
www: plain
text Plain text is text which does not have embedded formatting information in it. On a Microsoft Windows computer anything which can be edited with 'Notepad' is considered to be plain text, but documents created with 'Microsoft Word' are generally not plain text. Vim is designed to edit documents which are plain text.
www: mode
Vim has several modes. In one mode ('insert') you can enter text. In another mode you can type commands etc.
www: option
Something which you can set with :set option to change the behavior of vim.
www: regular
expression This means a pattern which is used to search for (and possibly replace) text in a document. Regular expressions are widely used in all unix-style operating systems and modern programming languages, such as Perl/Python/Java
www: greedy
pattern A regular expression which matches the maximum amount of text, instead of the minimum amount of text (non-greedy)
www: Unix-style
operating system This is any operating system which is based on a Unix design. Examples are Apple OSX, Linux, FreeBSD (Berkeley Standard Distribution of Unix)
www: ex
command line This is the line which appears after a colon ':' character as the bottom of the screen.

Enigmas And Curiosities ‹↑›

Vim is such a complex piece of software that completely plumbing its mysteries is perhaps impossible for one person. Below are some incomprehensible and strange recipes.

just another vim hacker

 vim -c ":%s%s*%Cyrnfr)fcbafbe[Oenz(Zbbyranne%|:%s)[[()])-)Ig|norm Vg?"

display some vim easter eggs

   :h 42  ##( also http://www.google.com/search?q=42 )
   :h holy-grail
   :h!

The Vim Cause ‹↑›

The maker of vim supports various humanitarian project in uganda.

view information about vims ugandan humanitarian projects

 helpg uganda

Vim People ‹↑›

www: bill
joy wrote the vi text editor, which built apon 'ex'
www: bram
moolenaar created the vim editor
www: david
rayner david at rayninfo.co.uk wrote some good tips about using the vim editor

Knowledgable People ‹↑›

sbutler at ask.metafilter.com jepler at ask.metafilter.com david a rogers - at vimtips

Information Sources ‹↑›

www: http://groups.google.com/group/vim_use
a users newsgroup
www: comp.editors
a text editor newsgroup
www: http://vim.wikia.com/
the vim wiki
www: vim.wiki.com/wiki/VimTip...
a good collection of vim tips
www: http://www.newriders.com/books/opl/ebooks/0735710015.html
a vim book
www: http://vimdoc.sourceforge.net/cgi-bin/vim2html2.pl
searchable docs
www: http://gav.brokentrain.net/projects/vimtips/vimtips.pdf
some printable tips

Things To Investigate ‹↑›

an imap example

 :imap <buffer> <Tab> <C-X><C-V>

Blogs And Diaries With Vim ‹↑›

Update your journal by creating a new file with todays date

 vi ~/journal/$(date +%F)

a bash function to write a journal entry for today

 blog() { vi ~/journal/$(date +%F); }

create journal entry in a file 2009-jan-12 for example

 vi ~/journal/$(date +%Y-%b-%d)

History ‹↑›

The Vim editor is a reimplementation and improvement of the 'vi' text editor which was written by Bill Joy. Bill Joy was a important figure in the early development of the Berkeley Standard Distribution of Unix, since he contributed a lot of code while a student. His other achievements include writing the first successful implementation of the tcp/ip protocol suite as well as founding sun microsystems and playing an important role in the sponsoring the development of the Java programming language.

Vi inturn was influenced by the 'ed' line oriented text editor, one of the very early unix editors.

Vim And Vi Clones ‹↑›

Redirection & Paste register *
:redir @* - redirect commands to paste buffer
:redir END - end redirect
:redir >> out.txt - redirect to a file
imap
nmap
nnoremap
autocommand

Javascript Clones ‹↑›

Two basic javascript versions of vi are available for using embedded in web-pages, but they are not particularly good and don't appear to be maintained.

www: http://gpl.internetconnection.net/vi/
a vi like clone written in javascript to run on a webpage doesnt have "J" for example, and yank doesnt work well
www: http://gpl.internetconnection.net/vi/vi.js
the source code for the javascript vi clone
www: http://vian.sourceforge.net/
another javascript vi clone

Other Text Editors ‹↑›

The are many text editors which have originated on Unix/Linux systems. Here we mention only a tiny selection

www: emacs
'Editing MACros' This is usually considered to be vims main 'rival' in the world of traditional unix program editors. It is a large and complex application with many knowledgable technical users.
www: sam
This is a little known editor written by Rob Pike and used by Brian Kernighan among others http://sam.cat-v.org/. It seems very difficult to obtain.
www: sed
A non interactive editor worth knowing about.

Modeline ‹↑›

mode-line (make a file read-only etc) must be in first/last 5 lines

 vim:noai:ts=2:sw=4:readonly:

says use HTML Syntax highlighting

 " vim:ft=html:

get help for the modeline option

 :h modeline

Mystery ‹↑›

This section contains some recipes which may be mysterious but educational.

reproduce the previous line word by word

 imap ]   
www: @<ESC>hhkyWjl?@@@<CR>P/@@@<CR>3s
 nmap ] i 
www: @<ESC>hhkyWjl?@@@<CR>P/@@@<CR>3s
pull full path name into paste buffer for attachment to email etc
 nnoremap <F2> :let @*=expand("%:p")<cr>  ?? error
 nnoremap <F2> :let @*=substitute(expand("%:p"), "/", "\\", "g")<cr> win32

Simple PHP debugging: display all variables yanked into register a

 iab phpdb exit("<hr>Debug <C-R>a  ");

DOCUMENT-NOTES:

clones
elvis - a small vi clone