Vim Tricks (from Steve Oualline and other places)
- Learning the vi Editor (6th Edition) -- by Linda Lamb, Arnold Robbins
- Vi iMproved (VIM) -- by Steve Oualline
Steve Oualline:
: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
|
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):
- on Windows - C:\Program Files\Vim\vim72 (make sure to add this directory to PATH in Control Panel > System > Advanced > Environmental Variables
- on Linux box - /usr/local/share/vim/vim72
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:
- ":TlistAddFiles somepath/*.pl" or ":TlistAddFilesRecursive somepath/*.pl" - to add files to the taglist window
- :TlistSessionSave
- :TlistSessionLoad
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:
- Put cursor on function/variable name - and press ctrl-] or g] to go to its definition or show a list to choose from.
- Press ctrl-t to step back up the tag stack.
- 11. Use vim or gvim for your next coding project.
http://www.cyberciti.biz/faq/vim-editing-multiple-files-with-windows-buffers/
- Open multiple files: vim file1 file2 file3
- :ls - show list of open files with their numbering
- :bn – go to next buffer (in this case, file2)
- :bp – go to previous buffer (will go backwards to file13.txt)
- :bd – delete current buffer (closes the file - can also take a filename or number as an argument)
- :b – go directly to a file
(can specify number or file)
- Open 2 files with split: vim -o file1 file2
- Open another split with a file: :sp fname (split line is horizontal)
- Open another split with a file: :vsp fname (split line is vertical)
- Jump between windows via Ctrl-W Ctrl-W (or Ctrl-W followed by movement (arrow or hjkl)
- Ctrl-W n - create new window (or :new fname)
- Crel-W s - split window
- Quit all windows
- write and quit all - :wqall
- Resize window:
Working with multiple tabs (starting with vim version 7): http://linux.com/archive/articles/59533 , http://vimdoc.sourceforge.net/htmldoc/tabpage.html
- :tabnew - open a new tab
vim -p file1 file2 file3 - open several files in tabs
:tabf inven* - open file(s) matiching criteria
:tabedit file1
- :tabs - show info about tabs
- :tabn, :tabp - move to next/previous tab,
:tabfirst (:tabfir), :tablast - move to first/last tab
- set showtabline=2 - to force tabs to always show (even if only one file is opened)
- set tabpagemax=30 - set maximum number of tabs more than default 10.
- In gvim you can use mouse to ve between tabs.
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:
- you have to backup the original title on file open - and restore it after you exit.
- you have to change it when you shift from one window to another inside Vim (whether you are using tabs or split or simply have several buffers).
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:
- :mksession your_session.vim
- vim -S your_session.vim
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
http://www.vim.org/htmldoc/diff.html
Starting diff from command line:
- vimdiff file1 file2
- vim -d file1 file2 [file3 [file4]]
- gvimdiff or vim -g
- viewdiff or gviewdiff
Starting diff from within vim:
- :vert diffsplit file2
- :diffsplit file2
- :diffthis - make the current window a part of diff windows (sets options like vimdiff).
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. |
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:
- Copy/paste several lines: VjjjjyjjjjP
- Cut/paste several lines: VjjjdkkkkP
- Copy to the end of the line and paste it somewhere: v$y some_move P
- vawy - copy a word
vaby - copy a ( .. ) block
vaBy - copy a { .. } block
- Cut a word - and then append it to the end of the line: vawd$p
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 -
==================================
- Simple Navigation: h j k l 0 ^ $ - +
More Complex: gg G C-f C-b L M H zt zz zb
Text Object: w W b B e E ( ) { } [[ ]] %
Search: t f T F , ; * # n N
- Repeated Movement
10j - move down ten lines
3f) - move to the third ")" to the right
5W - move 5 groups of non-whitespace characters to the right
3C-b - move 3 pages up
235gg - move to line 235
- Edit commands (to be followed by motion command): c d y p P < > g~ gu gU gq (change, delete, yank, paste after, paste before, outdent,
indent, toggle case, lowercase, uppercase, and justify)
- Single character edits: x r ~ s J (delete, replace,
toggle case, change, and join with next line) - can be preceeded by a number (to effect many chars)
Line edits: cc dd yy << >>
End of line edits: C D
- Registers (like having several clipboards):
- Unnamed register "
- Numbered registers 0-9
- Named registers a-z A-Z
- Clipboard: +
- Anytime a yank, delete, or change
is executed, the data goes into the unnamed register (and register 0), unless
you specify a particular named register. Each time one of those commands is
executed, the previous value of the 0 register is moved to the 1 register.
This is repeated for each numbered register, up to register 9. If you want to hold onto a piece of text for longer than one cut/paste,
you can use one of the 26 named registers, by prefixing the command with " and the letter naming the register. So, "byy yanks the
current line into register b. Using an uppercase letter, appends to that
register rather than just replacing. If you use name a register before the
p or P command, it pastes the data from that register instead. One other special register is "+". This register is mapped to the
system clipboard. This feature allows easily moving data to and from other
programs.
Insert Mode
- Insert: i I (start inserting at current position, or before the 1st non-whitespace char on the line)
- Append: a A (start appending after current char, or at the end of the line)
- New Line: o O ( inserts a new line after/before the current line, moves there,
and enters insert mode)
- Other ways to enter Insert mode: c C (change, change to the end of line), s S (substitute current char or entire line), R (Enter Insert mode, replacing characters rather than inserting)
Visual Mode (selection mode)
- Character selection: v
- Line selection: V
- Block selection: C-v
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
- File/Buffer commands: :w :e :r :n :N :q :find (writing a buffer, editing a
new file, reading a file into the current buffer, moving to the next/previous
file from the commands line, quitting the current buffer, and find a file
from the path and edit it.)
- Edit commands: :s/// :co :m :d :c (substitute (search/replace), copy, move, delete, and change)
- Search commands: / ? (search forward/backward, use n or N to move to next/previous match)
- Filter commands: ! (! is followed by a shell command. The selected text or
the specified range is supplied as standard input to the specified command.
The output from the command then replaces the selection. This allows any
filter-type command on the system to be used to modify text in the editor,
without leaving the editor.)
In many cases, commands that take a motion can take a text object instead. Text object starts with i or a.
- Inner or Outer: i or a (Inner - without delimiters, all - with delimiters (usually surrounding whitespace))
- Object: w W s p (words, non-whitespace characters,
sentences, and paragraphs)
- Matching: [ ] ( ) b { } B < > t (The matching sets define a text object delimited
by the specified pairs of characters. You only need to specify one of them.
The b character is a synonym for the parentheses, B - for curlies, t refers to tags (XML or HTML). So "it" refers to the text object delimited by
the nearest enclosing tags.)
- Quoted strings: " ' `
Repeated Edits
- dot ( . ) - repeat last edit at the current cursor location (may be a complex thing like "<iB" - indenting the enclosing code block)
- Recorded macros: q @ (press "q" followed by a register name - and then perform edits and motions. Finish with another "q". Now you can execute this macro by typing "@" followed by the register name.
- vim script (a full programming language)
- perldo (execute perl commands on selected portions of text - only available if perl support was compiled into Vim)
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):
- Window support: :sp (C-w s) :vs (C-w s)
- Close windows: :q :qall :on
- Navigating: C-w j C-w k C-w h C-w l
- Automation: :windo (apply a command to all open windows)
Tabs for open files:
- Create: :tabe[dit] :tabnew :tabf[ind] C-w gf (or start vim with "-p" option)
- Closing: :tabc[lose] :tabo[nly] (close current tab or all tabs except current)
- Navigation: :tabn :tabN :tabr[ewind] :tabfir[st] :tabl[ast]
- Automation: :tabdo
Customizing Vim
- _vimrc, .vimrc (config files from home dir, loaded when vim starts)
- .vim directory (contains sudirectories with many more config files, script and docs)
- vim script
- syntax highlighting (implemented via vim script)
Some Useful Scripts
- DirDiff.vim - compare directory trees and files in them
- surround.vim - editing characters that surround other text (quotes, parens, braces)
- vimballPlugin.vim - packaging and installing other scripts
- snippetsEmu.vim - system for
TextMate code snippets
- NERD_commenter.vim - script to comment/uncomment large portions of code at once
- taglist.vim - file created by the tags program
- vcscommand.vim - to use with version control systems (SVN, CVS, ..)
Perl-Specific Customizations
- gf command - opens the file under cursor, recognizes "use" statements, converts module name into file name and opens it
- make - support customized to do compile check for Perl code
- Use ack instead of grep external files.
- Mapped commands for perltidy, perlcritic, perldoc, compile/decompile, prove, etc. (,pt ,pc ,pD, etc. - see perl_local.vim)
- Special templates for new files (using autocmd feature).