Vim command pattern:
- register name (optional)
- repeats (optional)
- operation (eg y, d, etc)
- movement (doubling the operation takes the current line).
Tips:
- Move by context, not position.
- Do not search and scroll, do not use your eyes to find text.
- If you're not searching, at least jump.
- Never park in insert mode, immediately escape after editing.
---
## INVOCATION
vim -o filename1, ... Open multiple files in horizontally tiled windows.
vim -O filename1, ... Open multiple files in vertically tiled windows.
vim -p filename1, ... Open multiple files in separate tabs.
---
## HELP
:help command Split screen help
Ctrl-J Follow link
Ctrl-T Go back
---
## MODES / EDITING
. Repeat previous command.
<Esc> Enter command mode.
i a Enter insert mode before / after the cursor.
I A Enter insert mode at the beginning / end of the current line.
o O Enter insert mode in a new line under/above the current line.
r Replace character under cursor and return to command mode.
R Enter overtype (replace) mode.
C Change the rest of the current line.
c Change (retype) command. Follow with a movement command.
cc Deletes the current line to register " and enters insert mode.
cw Deletes the current word to register " and enters insert mode.
c$ Change the rest of the current line.
s Substitute the character under cursor and enter insert mode.
S Delete line at cursor and substitute text (same as cc)
: Enter ex mode.
! Enter shell filter mode.
Ctrl-o command Quick command in insert mode
Ctrl-R " Paste in insert mode
J Join line with following.
---
## VISUAL MARKING MODES
You can start in one visual mode and enter another,
and continue to mark.
The marked area becomes a context for other commands.
Use the r command and letter X to change every
character in the marked area to X.
Use the marked area for the ex commands.
v Start visual mode, mark lines, then do command (such as y-yank)
Enter visual mode, mark character-wise.
Use to select text.
Press v again to cancel out the visual marking.
V Start Linewise visual mode
Enter visual mode, mark line-wise.
Ctrl+v Start visual block mode
Press V again to cancel this mode.
^v Enter visual mode, mark column-wise.
gv Re-mark the area last marked.
ggVG Mark the entire document.
o Move to other end of marked area
O Move to Other corner of block
aw Mark a word
ab A () block (with braces)
aB A {} block (with brackets)
ib Inner () block
iB Inner {} block
Esc Exit visual mode
---
## REGISTERS
:registers List of registers
"+ "* clipboard register / selection buffer
" The unnamed or default register.
a-z,A-Z The lowercase and uppercase letter registers.
+ The system default register (the normal cut/paste one).
_ The black hole, essentially /dev/null,
use to avoid wiping out the " register.
(examples)
dd Delete the current line into the default " register.
"add Delete the current line into register a.
"y$ Yank the current character to the end of the line into
register y.
"byy Yank the current line into register b.
"c24dd Literally: into register c, 24 times delete the current line.
---
## MOVEMENT
k Up one character.
h l Left / Right one character.
j Down one character.
b w Move backward / forward to the start of the next word.
B W Move backward / forward to the start of the next
space-terminated word (ignore punctuation).
or backward / forward one word if already at start.
e Move to the end of word, or to next word if already at end.
E Move to the end of space-terminated word, ignoring punctuation.
0 $ Move to the start /end of the line.
% Move to matching brace, paren, etc.
{ } Move to start / end (first empty line) of paragraph.
( ) Move to start of sentence / of next sentence
(separator is both period and space).
[[ ]] Move to next / previous function (c/c++/java/python).
H M L Move to the first line / middle / last line of the screen.
<n>H Move to line n from start of the screen.
<n>L Move to line n from bottom of the screen.
^ Move to the first non-whitespace character on the line.
^f Move forwards one page.
^b Move backwards one page.
gg G Go to beginning /end of file.
<n>gg Go to line n.
<n>G Go to line n.
:<n> Go to line n.
<n>% Go to nth percentage of file.
<n>| Go to column n of current line.
* Move to the next instance of word under cursor,
and highlight all uses.
# Move to the previous instance of word under cursor.
'' Move to the location of your last edit in the current file.
---
## SCROLLING
Ctrl-E Ctrl-Y scroll window down / up
zt zz zb Scroll the cursor to top / middle / bottom of page.
---
## JUMPING WITH THE CURSOR
:changes changelist
g; older
g, newer position in the changelist
:jumps jumplist
Ctrl-I Ctrl-O forward / back in jumplist
---
## SEARCHING
/ ? Search forward / backward, will prompt for a regex pattern.
Press enter to accept position.
n Repeat last search.
N Repeat last search but in the opposite direction.
tx Move to letter x, stopping just before x.
Useful for change/delete commands.
fx Find letter x, stopping on the letter x.
Useful for change/delete commands.
[i [I Show first / every line containing word under cursor.
:g/pattern/ Show every line matching the regex pattern.
:<r>s/foo/bar/<a>
Substitute foo with bar,
<r> determines the range, can be:
nothing (work on the current line only),
number (work on the line whose number you give),
% (the whole file).
<a> determines the arguments, can be:
g (replace all occurences in the line
without only replaces the first occurence in each line)
i (ignore case for the search pattern)
I (dont ignore case)
c (confirm each substitution, you can type
y to substitute the current match,
a to substitute this and all remaining matches, or
q to quit substitution).
(examples)
:452/foo/bar/ Replace the first occurence of foo with bar on line 452.
:s/foo/bar/g Replace every occurence of foo with bar on the current line.
:%s/foo/bar/g Replace every occurence of foo with bar in the whole file.
:%s/foo/bar/gi Same as above, but ignore case.
:%s/foo/bar/gc Confirm every substitution.
:%s/foo/bar/c For each line on the file, replace the first occurence of foo
with bar and confirm every substition.
---
## UNDO/REDO
u Undo last command.
U Undo all the latest changes made to the current line.
CTRL-r Redo.
---
## CUT (DELETE), COPY (YANK), PASTE
x Delete character under cursor.
xp Transpose two letter (delete and paste, technically)
X Delete character before the cursor (same as backspace).
d Delete selected text.
dd Delete line and put it into the default register.
:d Same as above.
y Yank selected text.
yy Yank line.
:y Same as above.
Y Same as above.
p P Paste contents of default register after / before cursor.
^r In insert mode, reads data from a register and pastes
it, continuing in insert mode.
---
## COMPLETION
^n In insert mode, complete a word (forward through choice list).
^p In insert mode, complete a word (backward through choice list).
^x^l In insert mode, complete a line.
^x^f File name completion.
^x^k Dictionary completion. Enable the dictioary by adding the line
set dictionary+=/usr/share/dict/words
:ab ab1 ab2 Set abbreviation. After this, while in insert mode, ab1 will be
expanded into ab2 immediately after typing.
:ab teh the A common error is fixed automatically.
---
## INDENTING
< Left-shift (requires a movement command, works on whole lines).
> Right-shift (requires a movement command, works on whole lines).
<} Move a paragraph to the left.
3>> Shift three lines right.
5>> Indent 5 lines from line where cursor stands
^T In insert/overwrite mode, indent.
^D In insert/overwrite mode, dedent.
---
## CODE REFORMATTING
%!astyle Restyle the entire file with astyle (a reformatting program).
%!indent Restyle the entire file with indent (a nice older program).
gqq Re-wrap the current line (a double-jump).
gqj Re-wrap the current line and the line following.
gq} Re-wrap lines from the current line to the end of the paragraph.
:retab Retabbing converts tab stops to spaces, and ensures correct
indentation for each.
Set the tabstop variable to the correct setting, set expandtab,
and issue :retab command.
Vim can wrap the text as you type, via the linebreak, textwidth,
and autoindent settings.
~ Change the case of the character under the cursor.
Works in visual mode.
---
## CTAGS
!ctags -R * Run ctags (better to do this in the makefile).
^] Jump to the definition of the term under the cursor.
^t Pop the browsing stack, return to the previous location.
---
## VISUAL BLOCKS
Visual blocks are one of those features that you won't find in a GUI text
editor.
They let you mark blocks of text and do editing operations on them.
To enter visual blocks mode, press Ctrl+v, then use HJKL or arrow keys to
highlight a block of text.
Now operate on the first highlighted line as if you were in normal mode,
and operations will be reflected on other highlighted lines.
For example, to indent a block of text with > characters (to make it look
like a text being replied to), highlight the first column of characters in
visual blocks mode, then press Shift+i to switch to insert mode at the
beginning of the line.
Insert a > in the first line and press Ctrl+c.
A > will be prepended to all other highlighted lines.
This feature is also useful for commenting blocks of code, by prepending
lines with // or #.
---
## CODE FOLDING
zf#j creates a fold from the cursor down # lines.
zf/string creates a fold from the cursor to string.
zj moves the cursor to the next fold.
zk moves the cursor to the previous fold.
zo opens a fold at the cursor.
zc To close it back, press zc.
zO opens all folds at the cursor.
zm increases the foldlevel by one.
zM closes all open folds.
zr decreases the foldlevel by one.
zR decreases the foldlevel to zero -- all folds will be open.
zd deletes the fold at the cursor.
zE deletes all folds.
[z move to start of open fold.
]z move to end of open fold.
zf5j Fold 5 lines.
kvggzf Fold everything from the beginning up to the current line.
zfa} To fold a code block marked by braces { },
move the cursor into the block and press zfa}.
See :help z
:help fdm
set foldmethod=marker
At the beginning of a function fragment, you can type ‘zfap’ to create a
fold; this should add some {{{ }}} tags around your code in the comment of
choice for the language you’re coding in.
You can type ‘zo’ to open a fold, or I can just hit the right arrow key on
the folded code marker.
You can type ‘zc’ to close a fold.
You can type ‘zr’ to open all folds.
You can type ‘zm’ to close all folds.
---
## MACROS (complex-repeat)
q Enter macro recording mode by pressing the command q, followed
by a register into
which the macro will be stored.
Any of the alphabetic upper or lower case keys, and any of the
digits may be used.
Every keystroke will be recorded into the macro until you press
the q key again.
@ To replay a macro, use the @ key followed by a register name.
Once a macro is replayed, the undo key will see that macro as a
single action.
@@ Vim remembers the macro you just replayed, and can repeat it
with the double-jump.
The dot command will also see it as a single action.
The recorded macros are just text in a register.
They can be pasted into a document, edited, yanked back into
the register, etc.
(examples)
qa Start recording the macro to register a.
---
## SPELL CHECKING
Turn on spellchecking with :set spell and turn off with :set nospell.
]s [s move to the next / previous mispelled word
zg add a word to the dictionary
zug undo the addition of a word to the dictionary
z= view spelling suggestions for a mispelled word
:help spell
---
## BOOKMARKS
Vim allows you to set a bookmark con a line, and jump from one
bookmark to another.
You can use any letter for a bookmark.
Lower-case letters set a file-specific bookmark.
'a in one file will take you to a different place than in
another file.
Upper-case letter set global bookmarks.
'A will take you to the line you marked in the file you marked
it, it loads the
marked file in the current window.
mx Put bookmark x at the current line.
'x Jump to bookmark x.
---
## FILE MANAGEMENT
:w Save.
:w filename Save a copy of the file you are editing as filename.
:wa Save all windows.
:q Quit.
:qa Quit all windows.
:q! Quit without saving.
:wq Save and quit.
:x Save and quit. If no changes were made, Vim exits without
writing the file.
ZZ Save changes and quit current window.
:o filename Open file in current buffer.
:e filename Open file in new buffer. Tab will autocomplete filenames.
:e! Reload file from disk discarding changes.
:e# Return to the previous window.
gf Goto filename under cursor
---
## BUFFER MANAGEMENT
:buffers List buffers
:bn :bp Next / previous buffer.
:bd Delete a buffer (close a file).
---
## WINDOW MANAGEMENT
:sp filename Splits window horizontally and loads filename in the new window.
:vs filename Splits window vertically and loads filename in the new windows.
^Wh ^Wj ^Wl ^Wk Move to window above / below / left / right.
^Wc Close current window.
^Wo Close all windows except current window.
^Wf Place the cursor on a filename, and issue this command while in
normal mode. The file will be loaded into a new window.
^W+ Increases the size of the current split by one line.
Try combining this with counts.
^W- Decreases the size of the current split by one line.
^W_ Maximize the current split.
:ls
---
## TABS
:tabe Open a file in a new tab.
Ctrl-W T Move current split window into its own tab.
gt Go to the next tab.
:tabn
:tabnext
CTRL-PageDown
gT Go to the previous tab.
:tabp
:tabprev
CTRL-PageUp
Ngt Go to tab N.
:tabr Go to the first tab.
:tabl Go to the last tab.
:tabc Close tab.
:tabclose
:tabo Close all tabs except current one.
:tabonly
:tabm <n> Move tab to position <n>.
:tabmove <n>
---
## VIMRC
:options
:browse options
:browse set
---
## SHELL FILTERING
!!command Pass current line only through filter.
!}command Pass area from current lint through end of paragraph through filter.
!Gcommand Pass are form current line through end of file through filter.
:%!command Pass the entire file through filter.
---
## FILE EXPLORER
Edit a directory.
o Open file in a horizontal split window.
v Open file in a vertical split window.
i Show more info.
s Sort by column under cursor.
r Sort in reverse order.
D Delete file.
d Make new directory.
<Enter> Open file in current window.
---
## MISCELANEOUS TRICKS
:g/^#/d Delete all lines that begins with #
:g/^$/d Delete all lines that are empty and contain no tabs
:g/^\s*$/d Delete all lines that are empty
:%s/$/{ctrl-V}{CR}/g Inserts blank line between lines
:%s/{TAB}*$// Strip tabs at end of line
:g/<pattern>/t$ Copy every line which matches pattern to the end of the
file
---
## VIM MACROS
:%!column -t
:%!sort -k1
Matsumoto Yukihiro Ruby 1965 Japan
Moolenar Bram Vim 1961 Netherlands
Ritchie Dennis C 1941 USA
Stallman Richard GNU 1953 USA
Thompson Ken Unix 1943 USA
Tridgell Andrew Samba 1967 Australia
Wall Larry Perl 1954 USA
suppose we’ve got the task of replacing the fourth column of this table with
the approximate age of the person, which we can get naturally enough by
substracting their birth year from the current year.
This is a little awkward to do in pure ex, so we’ll record a macro for doing
it on one line.
03wdei^R=2013-^R"^M^[0j
0 — Move to the start of the line
3w — Skip three words, in this case to the fourth column
de — Delete to the end of the word
i — Enter insert mode
^R= — Insert the contents of the special = register, which accepts
an expression to evaluate
2012-^R"^M — Enter the expression 2012-(birth year) and press Enter
(literal ^M), which completes the operation, and inserts the
result
^[ — Leave insert mode
0 — Return to the start of the line
j — Move down a line
The only thing that’s slightly voodoo (and certainly not vi-compatible) is
the arithmetic done with the special = register. You can read about that in
:help @=, if you’re curious.
### REPEATING MACROS
As a first very simple hint, if you’re running a macro several times, don’t
forget that you can prepend a count to it; in our case, 6@a would have fixed
up all the remaining lines. To take advantage of this, it’s good practice to
compose your macros so that they make sense when run multiple times; in the
example above, note that the end of the macro is moving down onto the next
line, ready to run the macro again if appropriate.
Similarly, if you’ve already run a macro once, you can run the same one
again by just tapping the @ key twice, @@. This repeats the last run macro.
Again, you can prepend a count to this, @a5@@
### TRUE NATURE OF MACROS
you needn’t restrict yourself to the single-keystroke vi commands for Vim
when you compose macros. You can include ex commands as well, for example
to run a substitution during a macro:
qb:s/foo/bar/g^Mq
@b
all of the operations that you can apply to registers in general work with
what we normally call macros, with the old standards, delete, yank, and
paste You can test this with the example macro demonstrated above, by typing
"ap,
which will dump the raw text straight into the buffer.
Also like other registers, it’ll show up in the output of the :registers
command.
### EDITING VIM MACROS IN A BUFFER
suppose I realise partway through writing it that I made a mistake in
typing 2011 instead of 2012.
I finish recording the rest of the macro anyway, and dump the broken
keystrokes into a new scratch buffer:
:enew
"ap
This gives me the contents of the macro in plain text in the buffer:
qa03wdei^R=2011-^R"^M^[0jq
So now all I have to do is change that bad year to 2012, and then yank the
whole thing back into register a:
^"ay$
Now I can test it directly with @a on the appropriate file, and if it’s
still wrong, I just jump back to my scratch buffer and keep fixing it up
until it works.
One potential snag here is that you have to enter keystrokes like Ctrl+R as
literal characters, but once you know you can enter any keystroke in Vim
literally in insert or command mode by prefixing it with Ctrl+V, that isn’t
really a problem. So to enter a literal Ctrl+R in insert mode, you type
Ctrl+V, then Ctrl+R.
### RUNNING A VIM MACRO ON A SET OF LINES
It’s occasionally handy to be able to run a macro that you’ve got ready on a
specific subset of lines of the file, or perhaps just for every line.
Fortunately, there’s a way to do this, too.
Using the :normal command, you’re able to run macros from the ex command
line:
:normal @a
All it takes is prefixing this with any sort of range definition to allow
you to run a macro on any set of lines that you’re able to define.
Run the macro on each line of the whole buffer:
:% normal @a
Between lines 10 and 20:
:10,20 normal @a
On the lines in the current visual selection:
:'<,'> normal @a
On the lines containing the pattern vim:
:g/vim/ normal @a
When you get confident using this, :norm is a nice abbreviation to use.
### MOVING A VIM MACRO INTO A FUNCTION
For really useful macros of your own devising, it’s occasionally handy to
put it into a function for use in scripts or keystroke mappings.
Here again the :normal command comes in handy.
Suppose I wanted to keep the age calculation macro defined above for later
use on spreadsheets of this kind.
I’d start by dumping it into a new buffer:
:enew
"ap
The macro appears as raw text:
03wdei^R=2012-^R"^M^[0j
I prefix it with a :normal call, and wrap a function definition around it:
function! CalculateAge()
normal 03wdei^R=2012-^R"^M^[0j
endfunction
Then all I need to do is include that in a file that gets loaded during
Vim’s startup, possibly just .vimrc. I can call it directly from ex:
:call CalculateAge()
But given that I wanted it to be a quick-access macro, maybe it’s better to
bind it to \a, or whatever your chosen <leader> character is:
nnoremap <leader>a :call CalculateAge()<CR>
Saving a Vim macro
If you want to have a macro always available to you, that is, always loaded
into the appropriate register at startup, that can be done in your .vimrc
file with a call to let to fill the register with the literal characters
required:
let @a='03wdei^R=2012-^R"^M^[0j'
### APPENDING EXTRA KEYSTROKES TO A VIM MACRO
If you just want to tack extra keystrokes onto an existing macro and don’t
care to edit it in a Vim buffer, you can do that by recording into it with
its capital letter equivalent. So, if you wanted to add more keystrokes
into the register b, start recording with qB, and finish with the usual q.
### RECURSIVE VIM MACROS
If you’re crazy enough to need this, and I never have, there’s an excellent
Vim Tip for it. But personally, I think if you need recursion in your text
processing then it’s time to bust out a real programming language and not
Vimscript to solve your problem.
If the issue for which you think you need recursion is running a macro on
every line of a buffer with an arbitrary number of lines, then you don’t
need recursion; just record a one-line version of the macro and call it
with :% normal @a to run it on every line.
### VIM MACRO GOTCHAS
Here are a few gotchas which will save you some frustration if you know
about them ahead of time:
When you have a hammer, everything starts to look like a nail. Don’t try to
solve problems with macros when there are better solutions in the ex
command set, or available in external programs. See the Vim koans page for a
couple of examples.
You need to insert keystrokes like Enter as literal Ctrl+M, so that they
look like ^M. The convenience abbreviations in mappings, like <CR>, simply
don’t work. You’re likely to find yourself chording Ctrl+V a lot.
Macros tend to stop, sometimes for apparently no reason and with no warning
messages, as soon as they hit some sort of error. One particularly annoying
instance of this is when you’re performing several substitutions in a macro,
because if it doesn’t find any instances of a pattern it will throw an error
and stop executing. You can prevent this by adding the e flag to the
substitution call:
:s/foo/bar/e
---
## PLUGINS
ctags
With the ":tag" command the cursor will be positioned on the tag. With the
CTRL-] command, the keyword on which the cursor is standing is used as the
tag. If the cursor is not on a keyword, the first keyword to the right of the
cursor is used.
The ":tag" command works very well for C programs. If you see a call to a
function and wonder what that function does, position the cursor inside of the
function name and hit CTRL-]. This will bring you to the function definition.
An easy way back is with the CTRL-T command. Also read about the tag stack
below.
*:ta* *:tag* *E426* *E429*
:[count]ta[g][!] {ident}
Jump to the definition of {ident}, using the
information in the tags file(s). Put {ident} in the
tag stack. See |tag-!| for [!].
{ident} can be a regexp pattern, see |tag-regexp|.
When there are several matching tags for {ident}, jump
to the [count] one. When [count] is omitted the
first one is jumped to. See |tag-matchlist| for
jumping to other matching tags.
<C-LeftMouse>
*<C-LeftMouse>* *CTRL-]*
CTRL-] Jump to the definition of the keyword under the
cursor. Same as ":tag {ident}", where {ident} is the
keyword under or after cursor.
When there are several matching tags for {ident}, jump
to the [count] one. When no [count] is given the
first one is jumped to. See |tag-matchlist| for
jumping to other matching tags.
{Vi: identifier after the cursor}
CTRL+[ Navigate to tag under cursor.
:tag <tag name>
Navigate to named tag.
:pop
Tag jumps are saved on a stack; this command pops the top of the stack and
returns to the previous cursor position.
:tnext
For tags that resolve to multiple source locations, jumps to the next such
location.
:tprev
Idem, but jumps to previous such location.
Now you need to configure taglist.vim, this can be done like this:
let Tlist_Ctags_Cmd = "/usr/bin/ctags"
let Tlist_WinWidth = 50
map <F4> :TlistToggle<cr>
map <F8> :!/usr/bin/ctags -R --c++-kinds=+p --fields=+iaS --extra=+q .<CR>
This builds tags libs for the current working directory (it's super fast).
Once you have build tags, you can browse them using builtin functions.
Here are some examples:
:tag getUser => Jump to getUser method
:tn (or tnext) => go to next search result
:tp (or tprev) => to to previous search result
:ts (or tselect) => List the current tags
=> Go back to last tag location
+Left click => Go to definition of a method
1. Navigate to function definition by specifying the function name using :ta
2. Navigating to the function definition from ‘function call’ using Ctrl + ]
3. Returning back again to function call from the definition using Ctrl + t
4. Navigating through a list of function names which has the similar names
:ta /^get
Following vim commands can be used to navigate through relevant functions
:ts – shows the list.
:tn – goes to the next tag in that list.
:tp - goes to the previous tag in that list.
:tf – goes to the function which is in the first of the list.
:tl – goes to the function which is in the last of the list.
1. Open the Tag List Window in Vim using :TlistOpen
# vim mycprogram.c
:TlistOpen
3. Jump to the function definition which is in another source file
When you are going through a function in a source file and would want to go to
the function definition which is in another file, you can do this in two
different methods.
Method 1:
If you had the ctags generated for that file, when the cursor is in the function
call pressing CTRL + ] will take you to the function definition.
And automatically the tag list window will show the tags for that newly opened
file.
Method 2:
Open another file also in the same vim session which will update the tag list
window with the information about that file. Search for that function name in
the tag list window, and by pressing <CR> on that function name in the tag list
window you can go to the function definition..
4. Viewing the prototype/signature of functions or variables.
Press ‘space’ in the function name or in the variable name in the tag list
window to show the prototype (function signature) of it in the VIM status bar
as shown below. In the example below, click on selectDumpableTable function from
the Tag-window and press space-bar, which displays the function signature for
selectDumptableTable function in the bottom Vim Status bar.
5. Viewing the total number of functions or variables in a source code file
press ‘space’ in the tag type in the tag list window, which shows the count of
it. In the example below, when the cursor is at ‘function’ press space, which
will display the total number of functions in the current source code.
C-] - go to definition
C-T - Jump back from the definition.
C-W C-] - Open the definition in a horizontal split
Add these lines in vimrc
map <C-\> :tab split<CR>:exec("tag ".expand("<cword>"))<CR>
map <A-]> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>
C-\ - Open the definition in a new tab
A-] - Open the definition in a vertical split
After the tags are generated. You can use the following keys to tag into and
tag out of functions:
Ctrl-Left_MouseClick - Go to definition
Ctrl-Right_MouseClick - Jump back from definition
Another useful plugin for C development is cscope Just as Ctags lets you jump
to definitions, Cscope jumps to the calling functions.
If you have cscope in your ~/bin/ directory, add the following to your .vimrc
and use g^] to go to the calling function (see :help cscope).
if has("cscope")
set csprg=~/bin/cscope
set csto=0
set cst
set nocsverb
" add any database in current directory
if filereadable("cscope.out")
cs add cscope.out
" else add database pointed to by environment
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
endif
Almost forgot... Just as ctags - you have to generate (and periodically update)
the database. I use the following script
select_files > cscope.files
ctags -L cscope.files
ctags -e -L cscope.files
cscope -ub -i cscope.files
Where 'select_files' is another script that extracts the list of C and header
files from the Makefile. This way I index only the files actually used by the
project.
---
## TIPS
--------------------------------------------------------------------------------
Join all paragraphs in a file,
without deleting the blank lines separating paragraphs
Make sure the file ends in a blank line.
:g/^./ .,/^$/-1 join
--------------------------------------------------------------------------------
Character search is near-instant for moving within a line
The f, F, t, T, ;, and , commands make up the suite of character search motions.
When you press f{char}, Vim looks forward from the cursor position for the next
occurrence of {char} on the current line. If it finds a match, the cursor moves
directly there. If no match is found, nothing happens.
If your cursor stopped on a match before the one you were aiming for, press ; to
repeat the search. Keep pressing ; until you hit your mark. If you overshoot,
press , to reverse the search.
--------------------------------------------------------------------------------
Commenting a block of Python code
Alternative 1:
C-v
<move around selecting text>
I
#
Esc
j is cursor down, so he's just selecting down 3 lines while in visual block
mode.
Shift+i means insert before the first non-whitespace character on the line,
but it has a sort of special-case use while in visual mode, in that it will
insert before the block selection on all lines thereof. # is just inserting
the # character. Esc ends the visual mode, and also finalizes the insertion
from shift+i, which also inserts the # in the right place on the remaining
lines before it finishes.
To uncomment:
ctrl+v over the top #
<move around selecting text>
x
Alternative 2:
Mark the block you want to comment, then type
:s/^/#/
That replaces the start of each line with a #.
To uncomment, mark the block again, and do
:s/.//
This replaces the first character of each line with nothing.
Alternative 3:
I put this in my .vimrc
map ^V^_ a^V^_^V^[
map ,4 :s/^/\/\//g<CR>
map ,3 :s/^/##/g<CR>
map .4 :s/^\/\///g<CR>
map .3 :s/^##//g<CR>
" wrapping comments
map ,* :s/^\(.*\)$/\/\* \1 \*\//<CR>
map ,( :s/^\(.*\)$/\(\* \1 \*\)/<CR>
map ,< :s/^\(.*\)$/<!-- \1 -->/<CR>
map .< :s/^\(.*\)$/<!-- \1 -->/<CR>
map ,d :s/^\([/(]\*\\|<!--\) \(.*\) \(\*[/)]\\|-->\)$/\2/<CR>
So that if I want to comment one line, while in command mode I
type ,3 for ## comments, then to uncomment I type .3
If I'm on the top line of a bock of code, that is say 7 lines
deep I type 7,3 which would comment out 7 lines of code.
Alternative 4:
I used comment.vim. It's very nice as you can select lines and
toggle commenting on/off.
Very easy to use. Type "co" in command mode.
Works on single lines, visual blocks, etc.
You can also add custom comment tags (see end of .vim file)
--------------------------------------------------------------------------------
Remove unwanted spaces
Alternative 1: Simple commands to remove unwanted whitespace
In a search,
\s finds whitespace (a space or a tab),
\+ finds one or more occurrences.
:%s/\s\+$// Delete all trailing whitespace (at the end of each line)
:%s/^\s\+// Delete whitespace at the beginning of each line.
:%le Same thing (:le = :left = left-align given range):
With the following mapping you can press F5 to delete all
trailing whitespace.
The variable _s is used to save and restore the last search
pattern register (so next time you press n you will continue your
last search), and :nohl is used to switch off search highlighting
(so trailing spaces won't be highlighted while you are typing).
The e flag is used in the substitute command so no error is shown
if trailing whitespace is not found.
:nnoremap <silent> <F5> :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar>:nohl<CR>
Alternative 2: Display or remove unwanted whitespace with a script
Here is a more elaborate procedure that can display or remove
unwanted whitespace.
Here, "unwanted" means any spaces before a tab character, or any
space or tab at the end of a line.
function ShowSpaces(...)
let @/="\\v(\\s+$)|( +\\ze\\t)"
let oldhlsearch=&hlsearch
if !a:0
let &hlsearch=!&hlsearch
else
let &hlsearch=a:1
end
return oldhlsearch
endfunction
function TrimSpaces() range
let oldhlsearch=ShowSpaces(1)
execute a:firstline.",".a:lastline."substitute ///gec"
let &hlsearch=oldhlsearch
endfunction
command -bar -nargs=? ShowSpaces call ShowSpaces(<args>)
command -bar -nargs=0 -range=% TrimSpaces <line1>,<line2>call TrimSpaces()
nnoremap <F12> :ShowSpaces 1<CR>
nnoremap <S-F12> m`:TrimSpaces<CR>``
vnoremap <S-F12> :TrimSpaces<CR>
Alternative 3: An alternative function simulating manual steps:
However, this has minor side-effects, such as influencing undo
history and sometimes changing scroll position.
function StripTrailingWhitespace()
if !&binary && &filetype != 'diff'
normal mz
normal Hmy
%s/\s\+$//e
normal 'yz<CR>
normal `z
endif
endfunction
Alternative 4: Automatically removing all trailing whitespace
Just put the following line in your vimrc file.
Everytime you issue a :w command, Vim will automatically remove
all trailing whitespace before saving.
autocmd BufWritePre * :%s/\s\+$//e
This is a very dangerous autocmd to have! This will *always*
strip trailing whitespace from *every* file you save.
Sometimes, trailing whitespace is desired, or even essential!
For example, if in your .vimrc you have the following:
set wrap
set linebreak
" note trailing space at end of next line
set showbreak=>\ \ \
then saving your .vimrc will make it use "> \" instead of
"> " to prepend to wrapped lines!
Remember you can also specify filetype
autocmd BufWritePre *.pl :%s/\s\+$//e
or how about having this operate when you enter the file:
autocmd BufEnter *.php :%s/\s\+$//e
And let's get rid of those pesky ^M at the same time
autocmd BufEnter *.php :%s/[ \t\r]\+$//e
With a ":call" instead of ":%s" (keep last used search/replace)
and using FileType:
autocmd FileType c,cpp,java,php autocmd BufWritePre <buffer> :call setline(1,map(getline(1,"$"),'substitute(v:val,"\\s\\+$","","")'))
Comments
********************************************************************************
Here's what I use in my .vimrc:
" Removes trailing spaces
function TrimWhiteSpace()
%s/\s*$//
''
:endfunction
set list listchars=trail:.,extends:>
autocmd FileWritePre * :call TrimWhiteSpace()
autocmd FileAppendPre * :call TrimWhiteSpace()
autocmd FilterWritePre * :call TrimWhiteSpace()
autocmd BufWritePre * :call TrimWhiteSpace()
map <F2> :call TrimWhiteSpace()<CR>
map! <F2> :call TrimWhiteSpace()<CR>
********************************************************************************
My preferred setting of list and listchars:
set list listchars=tab:»·,trail:·
Or try
set list lcs=tab:·⁖,trail:¶
********************************************************************************
There is one occasion where I want to keep my trailing space.
But even in those documents, I want to keep it in only one place, and not every
occurrence.
Here is my substitution pattern:
s/\(^--\)\@<!\s*$//
This will eliminate all trailing whitespaces except for the one in an email
signature marker (-- ).
In the function in the tip, this expands to:
execute a:firstline.",".a:lastline."substitute /\\(^--\\)\\@<!\\s*$//ge"
Also, I've found the autocmds to work better like this:
autocmd FileWritePre * :TrimSpaces
autocmd FileAppendPre * :TrimSpaces
autocmd FilterWritePre * :TrimSpaces
autocmd BufWritePre * :TrimSpaces
(taking advantage of the default range defined in Betram's command definition)
I modified one of the above scripts to let the user know if whitespace was found
" automatically remove trailing whitespace before write
function! StripTrailingWhitespace()
normal mZ
%s/\s\+$//e
if line("'Z") != line(".")
echo "Stripped whitespace\n"
endif
normal `Z
endfunction
autocmd BufWritePre *.cpp,*.hpp,*.i :call StripTrailingWhitespace()
--------------------------------------------------------------------------------
Did you know... http://vim.wikia.com/wiki/Did_you_know
May 2010
@: will repeat a colon (Ex) command (and @@ will repeat again).
You can use :g/^\s*$/;//-1sort to sort each block of lines in a file.
It's useful to map . .`[ to repeat the last command and put the cursor at
start of change.
You can open a web browser with the URL in the current line.
With --remote-send you can close a Vim you left open remotely.
If you're used to Perl regex, you can use Perl compatible regular expressions.
In insert mode, Ctrl-Y inserts the character above. You can make it insert the
word above.
A user-defined command can evaluate :Calc sin(pi/2).
It's sometimes better to not use the slash delimiter for :s/old/new/.
You can drag & drop one or more files into gvim.
April 2010
zz scrolls the current line to the middle of the screen; scrolloff can keep it
there.
Vim can do calculations using Python, Perl or bc.
You can wrap long lines while moving the cursor by screen lines.
A tricky search can find text that does not match.
Pressing % jumps to a matching bracket, aof the number column.
It's easy to change text between lowercase and UPPERCASE.
The command history allows you to repeat several commands, possibly after
editing them.
March 2010
Vim tutorials has videos illustrating simple and advanced topics.
Use % to jump to the matching bracket, and more.
Use :lcd %:p:h to change directory to the file in the current window.
ga shows the ascii value of the current character.
You can list changes to the current file, even old changsy to count the words
in a file or block.
You can even make a frequency table counting the occurrences of each word!
February 2010
Vim tutorials has videos illustrating simple and advanced topics.
You can press * to search for the current word.
Ctrl-A can increment numbers.
After typing a couple of characters, you can complete a word with
Ctrl-N or Ctrl-P.
Vim's help use prefixes like v_ (visual mode) to show the context.ckspace and
other delete keys work in insert mode.
The 'number' and 'numberwidth' options control the display of line numbers.
It's easy to change text between lowercase and UPPERCASE.
January 2010
Vim tutorials has videos illustrating simple and advanced topics.
We have an explanation for how :g/^/m0 reverses all lines.
In a search pattern, \_s matches a space or tab or newline character.
A script can use a test like &buftype == "quickfix" to check if it is
operating in the quickfix winduse :nnoremap Y y$.
A plugin should set its "loaded" variable to show its version, for example
let g:loaded_dbext = 503.
We have a short FAQ for new users concerning common issues raised at #vim.
You can use :cnoremap to map a key to <C-\>e(...)<CR> which will replace the
command line with the (...) expression.</CR>
* Save a file you edited in vim without the needed permissions
:w !sudo tee %
* Spellchecker
':set spell' activates vim spellchecker.
Use ']s' and '[s' to move between mistakes,
'zg' adds to the dictionary,
'z=' suggests correctly spelled words
* check my .vimrc http://tiny.cc/qxzktw and here http://tiny.cc/kzzktw for more