LevSelector.com New York
home > Vim

Vim Tricks (from Steve Oualline and other places)
On this page: Other pages:

- books
- resources
- vim 101
- ctags taglist
- multiple files
- vimdiff
- binary hexadecimal
- copy paste
- vim for perl

- vi standard commands
- my .vimrc for unix
- my .vimrc for windows

Books

- Learning the vi Editor (6th Edition) -- by Linda Lamb, Arnold Robbins
- Vi iMproved (VIM) -- by Steve Oualline

Resources:

Steve Oualline:

Vim 101

 

:help
.vimrc file
Multiple undo: Pressing "u" repeatedly does mutiple undo-s.
(Note if you accidentally moved away from your position in file - press '' (quote quote) to return to previous position. If you exted the file - press '0 (qote zero) to return to you laost position before close.)

Multiple windows:
:split (then use CTRL-Wj , CTRL-Wk to jump between them)
:split file.txt - splits the window and opens file.txt

Visual mode:
You enter the visual selection mode by pressing v, or shift-v, or ctrl-v.
Then as you move - the block gets highlighted
Then you give some command (d, y, >, :..., etc.)
Note:
- v - to select by char
- shift-v - to select by whole lines
- ctrl-v - to select by vertical blocks

:set incsearch – search as you type
:set hlsearch – search highlighting

:set cindent - turns on C style indentation

You can define abbreviations in .vimrc, for example:

:ab #b /******************************
:ab #e ^V^H******************************/

This defines two abbreviations.
By typing "#b" we type the top of a boxed comment.
Typing "#e" types the bottom line. (We put the ^V^H^V^H in the file to backup over the comment leader.)

Word Completion - when your typing and you enter a partial word, you can cause Vim
to search for a completion by using the ^P (search for previous marching word)
and ^N (search for next match).

and much more ...

 

Example: copy/paste in vim using visual mode:

v - mark first character of the block
move the cursor to the end
y - mark last character of the block and yank block to this point (or "d" to delete to this point)
move the cursor to some other place
gp - put the block starting on the line immediately after the cursor 
       (or use "p"or "P" to put on the next/previous line - as in vi)

vawy - copy a word
vaby - copy a ( .. ) block
vaBy - copy a { .. } block

shift-v - to start visual mode in "whole lines" mode.
ctrl-v - to work in "block" (vertical rectangle) mode.

Example: to comment out several lines:

move to the beginning of the first line you want to comment - and press ctrl-v ,
then move down to the last line you want to comment - and press I# , then <esc> key

or move to the first line you want to comment - and press shift-v,

then move to the last one and press :s/^/#/ , and then press <enter> key.

I am programming on Linux using vim. My favorite settings in the file   .vimrc:

:syntax on
" -------------------------------------
" use 2-space indentation
set tabstop=2
set softtabstop=2
set shiftwidth=2
set expandtab

Here are some commands I use often:

" show/remove line numbers - set number
:se nu
:se nonu

"set/unset wraping
:set wrap
:set nowrap

" to wrap a piece of text (insert end-of-line) - select a piece of text, and then us gq command:
- http://www.vim.org/htmldoc/usr_25.html

" search - set ignore case on/off
:se ic
:se noic

" search incrementally as you type
:set incsearch

" show/remove highlight after search
:set hls
:set nohls

" search for the whole word using boundary indicators \<, \>
/\<myword\>

" to set / unset autoindent:
:se ai
:se noai

" to show all settings
:se all

" insert " - " in front of several lines:
press ctrl-v at the beginning of the first line to start in visual block mode, then move down to the last line, then press:
I -
and then press <esc> key.

or another way to do the same:
press shift-v to start selecting in "whole lines" mode, then move to the last line, then press:
:s/^/ - /
and then press the <enter> key

"ho to remove extra empty lines in all file:
:%s/\(\n\)\+/\1/g

" -------------------------------------
" here is an example of how to set your own custom status line
set laststatus=2
set statusline=%F%m%r%h%w\ %{&ff}\ %Y\ ascii=\%03.3b\ hex=\%02.2B\ [%04l,%04v](%p%%\ of\ %L)

Scrolling / Paging

http://www.ph.unimelb.edu.au/~ssk/vim/scroll.html

down / up

by line: c-E / c-Y
by page: c-D / c-U (Dow / Up)
shift-Down / Shift-Up
PageDown / PageUp
c-F / c-B (Forwards / Backwards)
------------------------------------------------------------------
z-commands - scrolling while keeping cursor position on the screen
(usually pressing 2 keys sequentially, like press "z", then press ".")
------------------------------------------------------------------
scroll so that current line moves to:
z . - to the center of window.
z z - Like "z.", but leave the cursor in the same column.
Careful: If caps-lock is on, this commands becomes "ZZ": write buffer and exit! {not in Vi}

z <CR> - to the top of the window.
zt Like "z<CR>", but leave the cursor in the same column. {not in Vi}

z- - to the bottom of the window
zb Like "z-", but leave the cursor in the same column. {not in Vi}
--------------------------------------------------------------------------------
4. Scrolling horizontally (not in Vi, works when :set nowrap)

z <Right> or zl - text moves to the left showing text at far right (not in Vi)
z <Left> or zh - text moves to the right

z s - text "pages" to the left
z e - text "pages" to the right

 

Ctags and Taglist - jumping to procedures and back, showing tag list on the side

On both Unix and MS Windows you can use utility ctags to generate a file with tags
which vim can use to jump to function definitions and back (http://ctags.sourceforge.net ).

You can also use a vim plugin called "taglist" which creates a narrow vertical window
with the clickable list of your tags ( http://www.vim.org/scripts/script.php?script_id=273 ).

Note - this taglist window works both in gvim (graphical window) and in a terminal window.

Here are couple of tutorials on this subject (found them by googling for vim taglist tutorial):

Here are short instructions:

Install vim ( www.vim.org ), then ctags ( ctags.sourceforge.net ).

Download taglist plugin zip file ( http://vim-taglist.sourceforge.net ), copy it into shared vim directory and unzip it there.
Vim shared files are here (for Vim version 7.2):

Go into the shared directory in subdirectory "doc", start vim - and run command ":helptags .". This will create a taglist for the taglist help file.

Open shared vimrc file (C:\Program Files\Vim\_vimrc on windows, or /etc/vimrc) and edit it as needed, for example:

filetype on "for tuglist plugin to work properly

:map #8 :TlistToggle

let Tlist_Exit_OnlyWindow = 1

OK, now go to the directory with your code and create the "tags" file by runnning command (for perl) : ctags -R *.pl *.pm

That's it !

Now open one of the scripts in vim, and execute command ":TlistToggle" to show the tag list. Use <Ctrl-w><Ctrl-w> to jump between your file and tag list (or use mouse in gvim). Select the tag in taglist - and press enter (or use mouse) to jump to the tag (or open a file). The + and - keys expand and contract items in the taglist window respectively.

Some commands:

In gvim you can use your mouse to switch between windows, expand/contract/select items in tag list, and even change the width of the taglist window by dragging the separation line with the mouse.

ctags also allows to find function definitions - even in other files:

 

How to work with multiple files (with/without tabs)

http://www.cyberciti.biz/faq/vim-editing-multiple-files-with-windows-buffers/

Working with multiple tabs (starting with vim version 7): http://linux.com/archive/articles/59533 , http://vimdoc.sourceforge.net/htmldoc/tabpage.html

Many Vim users like to rewrite the title of Xterm window wit hthe name of the file they are editing.
I believe it is better to use tabs instead.

There are 2 problems with rewriting the window title is:

Basic mechanics of setting window title from vim is simple:

  set title
  let &titlestring='some text'

You can include the file name by expanding the 't' variable:

expand("%:t")

for example:  let &titlestring = hostname() . "[vim(" . expand("%:t") . ")]"

The problems of detecting the change and changing/restoring title is  discussed in many places, for example:

But again, I really recommend to just start using version 7 and tabpage.

================================

Saving/restoring session:

bufdo, windo, tabdo - commands to operate on all buffers or windows or tabs

For example, you can do substitution in multiple files using this oneliner: find . -name "*.c" -exec perl -pi -e 's/foo/bar/g;' {} \;

But you can also do it from vim: :tabdo %s/foo/bar/ge

Compare files with vimdiff

http://www.vim.org/htmldoc/diff.html

Starting diff from command line:

Starting diff from within vim:

 

How to view/edit as hexadecimal

Vim comes with an executable utility xxd which converts file to hexadecimal representation. xxd can be used from inside vim to convert the file into hex dump format
:%!xxd
Result should look like this:
0000000: 6262 630a 6465 660a 6768 696b 0aab de0a bbc.def.ghik....
There are two parts: hex part and printable character part.
Go back:
:%!xxd -r
Note: when editing, only changes in hex part have effect. Changes in printable text part are ignored.
Note: you don't have to retype the whole command in ":" mode - just use up-arrow to restore previous command
Note: tool xxd can be used independently in command line.

Converting dos to unix and back

Vim auto-detects the type of the file - and doesn't show ^M for dos files. If you want to see ^M - do this:
:edit ++ff=unix

To convert the file use fileformat command:
:set ff?
:set ff=dos
:set ff=unix

About working with binary files:

Open a binary file:
    vim -b datafile
or
    :set binary

See the Hex format by using:
:set display=uhex
Or you can use ga command to see the value of current character.

(3) To see current position, use
g CTRL-G
The output is verbose:
Col 6 of 38; Line 31 of 31; Word 94 of 96; Byte 747 of 780

To move to a specific byte offset:
234go

Splitting a line

a,b,c,d
shiftV selection
:s/,/ctrl-V <enter>/g
it shows ^M, but actually inserts 0a (which is code 10) on unix, or 0d0a on windows

You can see this by doing this:

:%!xxd

And then convert back:

:%!xxd -r

Inserting special characters:

: help i_CTRL-V_digit

With CTRL-V the decimal, octal or hexadecimal value of a character can be
entered directly. This way you can enter any character, except a line break
(<NL>, value 10). There are five ways to enter the character value:

first char mode max nr of chars max value  
(none) decimal 3 255 255
o or O octal 3 377 255
x or X hexadecimal 2 ff 255
u hexadecimal 4 ffff 65535
U hexadecimal 8 7fffffff 2147483647

Normally you would type the maximum number of characters. Thus to enter a
space (value 32) you would type <C-V>032. You can omit the leading zero, in
which case the character typed after the number must be a non-digit. This
happens for the other modes as well: As soon as you type a character that is
invalid for the mode, the value before it will be used and the "invalid"
character is dealt with in the normal way.

If you enter a value of 10, it will end up in the file as a 0. The 10 is a
<NL>, which is used internally to represent the <Nul> character. When writing
the buffer to a file, the <NL> character is translated into <Nul>. The <NL>
character is written at the end of each line. Thus if you want to insert a
<NL> character in a file you will have to make a line break.

 

Many ways of copy/pasting

In vim you can use visual mode: http://www.vim.org/htmldoc/visual.html

You mark the beginning by pressing "v" for regular blocks, "V" for line-blocks, and "Ctrl-V" for rectangular block

You go to the end of the block (last character or line you want to include in the block) - and press "y" to copy, "d" to cut/delete, or any other command (you can do any command starting with ":").

If you did "y" or "d" - you then can move to any other place in file - and paste by pressing "P" or "p" or "gp".

Examples:

vim for perl

from Vim for Perl Development - by G. Wade Johnson from Houston Perl Mongers (http://houston.pm.org)

http://houston.pm.org/talks/2009talks/0901Talk/vim_for_perl.html - 19-page presentation summarized below
http://houston.pm.org/talks/2009talks/0901Talk/_vimrc - example of .vimrc
http://houston.pm.org/talks/2009talks/0901Talk/perl_local.vim -

==================================

Insert Mode


Visual Mode (selection mode)

Any motion commands after entering visual mode extends the selection. The way the selection extends is determined by how visual mode was entered. Using a command such as y, c, or d applies to the entire selection. This selection can also specify the range affected by one of the colon commands, like substitute.

CmdLine Mode

In many cases, commands that take a motion can take a text object instead. Text object starts with i or a.

Repeated Edits

Word Completion

Complete words: C-n C-p C-xC-i (list all of the keywords from the current file that match the text typed so far or keywords from included files)
Stop completion: C-xC-e (finish typing instead of selecting from list)
Specific: C-xC-d C-xC-] C-xC-f (special purpose completions for definitions or macros, entries in the tags file and filenames found on the path)

Window Support (splits):

Tabs for open files:

Customizing Vim

Some Useful Scripts

Perl-Specific Customizations