May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Indenting and Beautifying Your Code in VIM

Old News ;-) See Also Recommended Links Reference History Humor Etc

The VI editor has features to help programmers format their code neatly. There is a variable that to set up the indentation for each level of nesting in code. In order to set it up, see the customization section of this tutorial. For example, the command to set the shift width to 4 characters is :set sw=4.

The following commands indent your lines or remove the indentation, and can be specified with count:

Shifts the current line to the left by one shift width.
Shifts the current line to the right by one shift width.

The VI/VIM editor also has a helpful feature which checks your source code for any hanging parentheses or braces. The % command will look for the left parenthesis or brace corresponding to a particular right parenthesis or brace and vice versa. Place the cursor onto a parenthesis or brace and type % to move the cursor to the corresponding parenthesis or brace. This is useful to check for unclosed parentheses or braces. If a parenthesis or brace exists without a matching parenthesis or brace, VI will beep at you to indicate that no matching symbol was found.

There are much more as you can see from material below, but who on earth can remember all this staff...


Old News

Searching - Vim Tips Wiki

Formatting a function

Here are some basic formatting commands:

= is an operator (by default, it formats/indents text).
i{ is a text object that specifies the surrounding code block.
vi{ visually selects the inner code block around the cursor.
=i{ formats the code block.
=2i{ formats the current block and the block around it.

You can format the entire buffer with gg=G.

Commands to indent blocks

Suppose the indent options are correctly defined and we find this badly indented code:

int myfunction(int a)
 if ( a == 1 ) {
return 1;        // the cursor is in this line
 return 0;

These commands will fix the indents:

Instead of "{", you can use "}" or "B", for example, =aB indents a block.

These commands will decrease or increase indents:

With the cursor on { or }:

Mapping to indent at end of block

Whenever you complete a code block in a curly braces language by typing '}', this mapping automatically indents the block.

:inoremap } }<Esc>=%``a

It works by inserting the '}', indenting with % and then returning to the last cursor position. It then switches to insert mode (with a). This doesn't work cleanly if the closing curly brace has to be indented outwards (the cursor goes to where it was originally typed).


It is not clear why the mapping is needed. If, for example, Vim is configured to detect the file type as "C", and if auto indenting is enabled, the whole block will be correctly indented anyway. At any rate, you should not need to reindent code each time that you press }.

If the mapping is for a language where 'cindent' is not set, it would be better to adjust the 'indentkeys' option.

To fix the problem mentioned with the mapping I think you could just replace the `` with another %, but I'm not actually certain. I can't readily test the mapping due to the above comment.

Retrieved from ""

Smart indenting in vim (normally great) is a disaster when pasting in a chunk of code. - Stack Overflow

"Nice trick with the =%. I forgot = works on ranges"

:set paste is the way to go, but if you forget, as I often do, then if you are using a language with {} as the open/close of blocks, then doing a =% on the first { or last } will reapply the indenting.

How to indent a selection in Vim

Ever had that situation where you've enabled :set paste and pasted in hundred of lines of code into vim only to see it all fully left aligned? I just did… And bugger going over each line and manually indenting it! Want know how to indent a visual block of text?

So, make a visual selection of what you'd like indented (by pressing v and moving the cursor to mark the selection). Press colon to enter command mode and type "le2". The le command is shorthand for left align. The 2 value is an optional indent setting.

This is what I love about vim; there is always a new trick to make your life easier!

How to Paste Without Indenting in Vim

I wanted to paste some HTML into Vim, and I was having a hard time getting something that preserved existing indentation.

After doing :help autoindent, I found out about smartindent. So, I turned both smartindent and autoindent off before doing my paste. That worked wonders!

1 :set nosmartindent
2 :set noautoindent
3 i
4 <CMD>-V
5 <ESC>
6 :set smartindent
7 :set autoindent

Problem with indenting in vim - Ubuntu Forums

Problem with indenting in vim


Hey guys,
I have problem I can't figure out. I just installed feisty and compiz fusion on my computer. I'm a vim user but I've never run into a problem like this. When I use visual mode to highlight some code, I usually use == to fix the indentation of my code. On this computer, there has been some unusual behavior.

After highlighting some text, I press = the first time, the status bar of vim tells gives the message "12 lines filtered" or whatever number of lines I've highlighted. Pressing = again inserts the following line into my code:
"indent:Standard input:2:Error:Unexpected end of file"

No matter how many times in the past my code was messy or just wrong, vim never gave me this message. Any ideas on how to fix it?

I was messing around with customizing xterm previously, could this have something to do with it? I believe I downloaded a friend's .Xdefault file or wherever the configuration for xterm is located. Should I delete the file?

Also, a random vim/xterm question, how the heck do I get color syntax highlighting to work?

Many Thanks,
John Kim

Ubuntu nubbin.

Join Date: Feb 2007
Beans: 6 Re: Problem with indenting in vim


forgot to post my .vimrc, here it is:

set nocompatible
"set autoindent
set smartindent
set tabstop=4
set shiftwidth=4
"set shiftround
set expandtab
set showmatch
set vb t_vb=
set ruler
set incsearch

if &term =~ "xterm"
if has("terminfo")
set t_Co=8
set t_Sf=<Esc>[3%p1%dm
set t_Sb=<Esc>[4%p1%dm
set t_Co=8
set t_Sf=<Esc>[3%dm
set t_Sb=<Esc>[4%dm

View Public Profile
Send a private message to hyjkim
Find More Posts by hyjkim

June 30th, 2007 #3
First Cup of Ubuntu

Join Date: Feb 2007
Beans: 6 Re: Problem with indenting in vim


Problem solved, It was kind of silly but I was unaware that ubuntu came installed with vim-tiny.

Recommended Links

Indenting-stats - Vim Tips Wiki

Vim documentation indent

*indent.txt* For Vim version 6.2. Last change: 2003 Dec 24


This file is about indenting C programs and other files.

1. Indenting C programs |C-indenting|
2. Indenting by expression |indent-expression|


1. Indenting C programs *C-indenting*

The basics for C indenting are explained in section |30.2| of the user manual.

Vim has options for automatically indenting C program files. These options
affect only the indent and do not perform other formatting. For comment
formatting, see |format-comments|.

Note that this will not work when the |+smartindent| or |+cindent| features
have been disabled at compile time.

There are in fact four methods available for indentation:
'autoindent' uses the indent from the previous line.
'smartindent' is like 'autoindent' but also recognizes some C syntax to
increase/reduce the indent where appropriate.
'cindent' Works more cleverly than the other two and is configurable to
different indenting styles.
'indentexpr' The most flexible of all: Evaluates an expression to compute
the indent of a line. When non-empty this method overrides
the other ones. See |indent-expression|.
The rest of this section describes the 'cindent' option.

Note that 'cindent' indenting does not work for every code scenario. Vim
is not a C compiler: it does not recognize all syntax.

These four options control C program indenting:
'cindent' Enables Vim to perform C program indenting automatically.
'cinkeys' Specifies which keys trigger reindenting in insert mode.
'cinoptions' Sets your preferred indent style.
'cinwords' Defines keywords that start an extra indent in the next line.

If 'lisp' is not on and 'equalprg' is empty, the "=" operator indents using
Vim's built-in algorithm rather than calling an external program.

See |autocommand| for how to set the 'cindent' option automatically for C code
files and reset it for others.

*cinkeys-format* *indentkeys-format*
The 'cinkeys' option is a string that controls Vim's indenting in response to
typing certain characters or commands in certain contexts. Note that this not
only triggers C-indenting. When 'indentexpr' is not empty 'indentkeys' is
used instead. The format of 'cinkeys' and 'indentkeys' is equal.

The default is "0{,0},0),:,0#,!^F,o,O,e" which specifies that indenting occurs
as follows:

"0{" if you type '{' as the first character in a line
"0}" if you type '}' as the first character in a line
"0)" if you type ')' as the first character in a line
":" if you type ':' after a label or case statement
"0#" if you type '#' as the first character in a line
"!^F" if you type CTRL-F (which is not inserted)
"o" if you type a <CR> anywhere or use the "o" command (not in
insert mode!)
"O" if you use the "O" command (not in insert mode!)
"e" if you type the second 'e' for an "else" at the start of a

Characters that can precede each key:
! When a '!' precedes the key, Vim will not insert the key but will
instead reindent the current line. This allows you to define a
command key for reindenting the current line. CTRL-F is the default
key for this. Be careful if you define CTRL-I for this because CTRL-I
is the ASCII code for <Tab>.
* When a '*' precedes the key, Vim will reindent the line before
inserting the key. If 'cinkeys' contains "*<Return>", Vim reindents
the current line before opening a new line.
0 When a zero precedes the key (but appears after '!' or '*') Vim will
reindent the line only if the key is the first character you type in
the line. When used before "=" Vim will only reindent the line if
there is only white space before the word.

When neither '!' nor '*' precedes the key, Vim reindents the line after you
type the key. So ';' sets the indentation of a line which includes the ';'.

Special key names:
<> Angle brackets mean spelled-out names of keys. For example: "<Up>",
"<Ins>" (see |key-notation|).
^ Letters preceded by a caret (^) are control characters. For example:
"^F" is CTRL-F.
o Reindent a line when you use the "o" command or when Vim opens a new
line below the current one (e.g., when you type <Enter> in insert
O Reindent a line when you use the "O" command.
e Reindent a line that starts with "else" when you type the second 'e'.
: Reindent a line when a ':' is typed which is after a label or case
statement. Don't reindent for a ":" in "class::method" for C++. To
Reindent for any ":", use "<:>".
=word Reindent when typing the last character of "word". "word" may
actually be part of another word. Thus "=end" would cause reindenting
when typing the "d" in "endif" or "endwhile". But not when typing
"bend". Also reindent when completion produces a word that starts
with "word". "0=word" reindents when there is only white space before
the word.
=~word Like =word, but ignore case.

If you really want to reindent when you type 'o', 'O', 'e', '0', '<', '>',
'*', ':' or '!', use "<o>", "<O>", "<e>", "<0>", "<<>", "<>>", "<*>", "<:>" or
"<!>", respectively, for those keys.

For an emacs-style indent mode where lines aren't indented every time you
press Enter but only if you press Tab, I suggest:
:set cinkeys=0{,0},:,0#,!<Tab>,!^F
You might also want to switch off 'autoindent' then.

Note: If you change the current line's indentation manually, Vim ignores the
cindent settings for that line. This prevents vim from reindenting after you
have changed the indent by typing <BS>, <Tab>, or <Space> in the indent or
used CTRL-T or CTRL-D.

The 'cinoptions' option sets how Vim performs indentation. In the list below,
"N" represents a number of your choice (the number can be negative). When
there is an 's' after the number, Vim multiplies the number by 'shiftwidth':
"1s" is 'shiftwidth', "2s" is two times 'shiftwidth', etc. You can use a
decimal point, too: "-0.5s" is minus half a 'shiftwidth'. The examples below
assume a 'shiftwidth' of 4.

>N Amount added for "normal" indent. Used after a line that should
increase the indent (lines starting with "if", an opening brace,
etc.). (default 'shiftwidth').

cino= cino=>2 cino=>2s
if (cond) if (cond) if (cond)
{ { {
foo; foo; foo;
} } }

eN Add N to the prevailing indent inside a set of braces if the
opening brace at the End of the line (more precise: is not the
first character in a line). This is useful if you want a
different indent when the '{' is at the start of the line from
when '{' is at the end of the line. (default 0).

cino= cino=e2 cino=e-2
if (cond) { if (cond) { if (cond) {
foo; foo; foo;
} } }
else else else
{ { {
bar; bar; bar;
} } }

nN Add N to the prevailing indent for a statement after an "if",
"while", etc., if it is NOT inside a set of braces. This is
useful if you want a different indent when there is no '{'
before the statement from when there is a '{' before it.
(default 0).

cino= cino=n2 cino=n-2
if (cond) if (cond) if (cond)
foo; foo; foo;
else else else
{ { {
bar; bar; bar;
} } }

fN Place the first opening brace of a function or other block in
column N. This applies only for an opening brace that is not
inside other braces and is at the start of the line. What comes
after the brace is put relative to this brace. (default 0).

cino= cino=f.5s cino=f1s
func() func() func()
{ { {
int foo; int foo; int foo;

{N Place opening braces N characters from the prevailing indent.
This applies only for opening braces that are inside other
braces. (default 0).

cino= cino={.5s cino={1s
if (cond) if (cond) if (cond)
{ { {
foo; foo; foo;

}N Place closing braces N characters from the matching opening
brace. (default 0).

cino= cino={2,}-0.5s cino=}2
if (cond) if (cond) if (cond)
{ { {
foo; foo; foo;
} } }

^N Add N to the prevailing indent inside a set of braces if the
opening brace is in column 0. This can specify a different
indent for whole of a function (some may like to set it to a
negative number). (default 0).

cino= cino=^-2 cino=^-s
func() func() func()
{ { {
if (cond) if (cond) if (cond)
{ { {
a = b; a = b; a = b;
} } }
} } }

:N Place case labels N characters from the indent of the switch().
(default 'shiftwidth').

cino= cino=:0
switch (x) switch(x)
{ {
case 1: case 1:
a = b; a = b;
default: default:
} }

=N Place statements occurring after a case label N characters from
the indent of the label. (default 'shiftwidth').

cino= cino==10
case 11: case 11: a = a + 1;
a = a + 1; b = b + 1;

lN If N != 0 Vim will align with a case label instead of the
statement after it in the same line.

cino= cino=l1
switch (a) { switch (a) {
case 1: { case 1: {
break; break;
} }

gN Place C++ scope declarations N characters from the indent of the
block they are in. (default 'shiftwidth'). A scope declaration
can be "public:", "protected:" or "private:".

cino= cino=g0
{ {
public: public:
a = b; a = b;
private: private:
} }

hN Place statements occurring after a C++ scope declaration N
characters from the indent of the label. (default

cino= cino=h10
public: public: a = a + 1;
a = a + 1; b = b + 1;

pN Parameter declarations for K&R-style function declarations will
be indented N characters from the margin. (default

cino= cino=p0 cino=p2s
func(a, b) func(a, b) func(a, b)
int a; int a; int a;
char b; char b; char b;

tN Indent a function return type declaration N characters from the
margin. (default 'shiftwidth').

cino= cino=t0 cino=t7
int int int
func() func() func()

+N Indent a continuation line (a line that spills onto the next) N
additional characters. (default 'shiftwidth').

cino= cino=+10
a = b + 9 * a = b + 9 *
c; c;

cN Indent comment lines after the comment opener, when there is no
other text with which to align, N characters from the comment
opener. (default 3). See also |format-comments|.

cino= cino=c5
/* /*
text. text.
*/ */

CN When N is non-zero, indent comment lines by the amount specified
with the c flag above even if there is other text behind the
comment opener. (default 0).

cino=c0 cino=c0,C1
/******** /********
text. text.
********/ ********/
(Example uses ":set comments& comments-=s1:/* comments^=s0:/*")

/N Indent comment lines N characters extra. (default 0).
cino= cino=/4
a = b; a = b;
/* comment */ /* comment */
c = d; c = d;

(N When in unclosed parentheses, indent N characters from the line
with the unclosed parentheses. Add a 'shiftwidth' for every
unclosed parentheses. When N is 0 or the unclosed parentheses
is the first non-white character in its line, line up with the
next non-white character after the unclosed parentheses.
(default 'shiftwidth' * 2).

cino= cino=(0
if (c1 && (c2 || if (c1 && (c2 ||
c3)) c3))
foo; foo;
if (c1 && if (c1 &&
(c2 || c3)) (c2 || c3))
{ {

uN Same as (N, but for one level deeper. (default 'shiftwidth').

cino= cino=u2
if (c123456789 if (c123456789
&& (c22345 && (c22345
|| c3)) || c3))

UN When N is non-zero, do not ignore the indenting specified by
( or u in case that the unclosed parentheses is the first
non-white character in its line. (default 0).

cino= or cino=(s cino=(s,U1
c = c1 && c = c1 &&
( (
c2 || c2 ||
c3 c3
) && c4; ) && c4;

wN When in unclosed parentheses and N is non-zero and either
using "(0" or "u0", respectively, or using "U0" and the unclosed
parentheses is the first non-white character in its line, line
up with the character immediately after the unclosed parentheses
rather than the first non-white character. (default 0).

cino=(0 cino=(0,w1
if ( c1 if ( c1
&& ( c2 && ( c2
|| c3)) || c3))
foo; foo;

mN When N is non-zero, line up a line starting with a closing
parentheses with the first character of the line with the
matching opening parentheses. (default 0).

cino=(s cino=(s,m1
c = c1 && ( c = c1 && (
c2 || c2 ||
c3 c3
) && c4; ) && c4;
if ( if (
c1 && c2 c1 && c2
) )
foo; foo;

*java-cinoptions* *java-indenting*
jN Indent java anonymous classes correctly. The value 'N' is
currently unused but must be non-zero (e.g. 'j1'). 'j1' will
indent for example the following code snippet correctly:

object.add(new ChangeListener() {
public void stateChanged(ChangeEvent e) {

)N Vim searches for unclosed parentheses at most N lines away.
This limits the time needed to search for parentheses. (default
20 lines).

*N Vim searches for unclosed comments at most N lines away. This
limits the time needed to search for the start of a comment.
(default 30 lines).

The defaults, spelled out in full, are:

Vim puts a line in column 1 if:
- It starts with '#' (preprocessor directives), if 'cinkeys' contains '#'.
- It starts with a label (a keyword followed by ':', other than "case" and
- Any combination of indentations causes the line to have less than 0


2. Indenting by expression *indent-expression*

The basics for using flexible indenting are explained in section |30.3| of the
user manual.

If you want to write your own indent file, it must set the 'indentexpr'
option. Setting the 'indentkeys' option is often useful. See the
$VIMRUNTIME/indent directory for examples.


FORTRAN *fortran-indent*

Block if, select case, and where constructs are indented. Comments, labelled
statements and continuation lines are indented if the Fortran is in free
source form, whereas they are not indented if the Fortran is in fixed source
form because of the left margin requirements. Hence manual indent corrections
will be necessary for labelled statements and continuation lines when fixed
source form is being used. For further discussion of the method used for the
detection of source format see |fortran-syntax|.

Do loops
All do loops are left unindented by default. Do loops can be unstructured in
Fortran with (possibly multiple) loops ending on a labelled executable
statement of almost arbitrary type. Correct indentation requires
compiler-quality parsing. Old code with do loops ending on labelled statements
of arbitrary type can be indented with elaborate programs such as Tidy Structured do/continue loops are
also left unindented because continue statements are also used for purposes
other than ending a do loop. Programs such as Tidy can convert structured
do/continue loops to the do/enddo form. Do loops of the do/enddo variety can
be indented. If you use only structured loops of the do/enddo form, you should
declare this by setting the fortran_do_enddo variable in your .vimrc as

let fortran_do_enddo=1

in which case do loops will be indented. If all your loops are of do/enddo
type only in, say, .f90 files, then you should set a buffer flag with an
autocommand such as

au! BufRead,BufNewFile *.f90 let b:fortran_do_enddo=1

to get do loops indented in .f90 files and left alone in Fortran files with
other extensions such as .for.

VERILOG *verilog-indent*

General block statements such as if, for, case, always, initial, function,
specify and begin, etc., are indented. The module block statements (first
level blocks) are not indented by default. you can turn on the indent with
setting a variable in the .vimrc as follows:

let b:verilog_indent_modules = 1

then the module blocks will be indented. To stop this, remove the variable:

:unlet b:verilog_indent_modules

To set the variable only for Verilog file. The following statements can be

au BufReadPost * if exists("b:current_syntax")
au BufReadPost * if b:current_syntax == "verilog"
au BufReadPost * let b:verilog_indent_modules = 1
au BufReadPost * endif
au BufReadPost * endif

Furthermore, setting the variable b:verilog_indent_width to change the
indenting width (default is 'shiftwidth'):

let b:verilog_indent_width = 4
let b:verilog_indent_width = &sw * 2

In addition, you can turn the verbose mode for debug issue:

let b:verilog_indent_verbose = 1

Make sure to do ":set cmdheight=2" first to allow the display of the message.

Vim documentation tips

*tips.txt* For Vim version 6.2. Last change: 2004 Feb 17


Tips and ideas for using Vim *tips*

Don't forget to browse the user manual, it also contains lots of useful tips

Editing C programs |C-editing|
Finding where identifiers are used |ident-search|
Switching screens in an xterm |xterm-screens|
Scrolling in Insert mode |scroll-insert|
Smooth scrolling |scroll-smooth|
Correcting common typing mistakes |type-mistakes|
Counting words, lines, etc. |count-items|
Restoring the cursor position |restore-position|
Renaming files | rename-files|
Speeding up external commands |speed-up|
Useful mappings |useful-mappings|
Compressing the help files |gzip-helpfile|
Hex editing |hex-editing|
Executing shell commands in a window |shell-window|
Using <> notation in autocommands |autocmd-<>|


Editing C programs *C-editing*

There are quite a few features in Vim to help you edit C program files. Here
is an overview with tags to jump to:

|usr_29.txt| Moving through programs chapter in the user manual.
|usr_30.txt| Editing programs chapter in the user manual.
|C-indenting| Automatically set the indent of a line while typing
|=| Re-indent a few lines.
|format-comments| Format comments.

|:checkpath| Show all recursively included files.
|[i| Search for identifier under cursor in current and
included files.
|[_CTRL-I| Jump to match for "[i"
|[I| List all lines in current and included files where
identifier under the cursor matches.
|[d| Search for define under cursor in current and included

|CTRL-]| Jump to tag under cursor (e.g., definition of a
|CTRL-T| Jump back to before a CTRL-] command.
|:tselect| Select one tag out of a list of matching tags.

|gd| Go to Declaration of local variable under cursor.
|gD| Go to Declaration of global variable under cursor.

|gf| Go to file name under the cursor.

|%| Go to matching (), {}, [], /* */, #if, #else, #endif.
|[/| Go to previous start of comment.
|]/| Go to next end of comment.
|[#| Go back to unclosed #if, #ifdef, or #else.
|]#| Go forward to unclosed #else or #endif.
|[(| Go back to unclosed '('
|])| Go forward to unclosed ')'
|[{| Go back to unclosed '{'
|]}| Go forward to unclosed '}'

|v_ab| Select "a block" from "[(" to "])", including braces
|v_ib| Select "inner block" from "[(" to "])"
|v_aB| Select "a block" from "[{" to "]}", including brackets
|v_iB| Select "inner block" from "[{" to "]}"


Finding where identifiers are used *ident-search*

You probably already know that |tags| can be used to jump to the place where a
function or variable is defined. But sometimes you wish you could jump to all
the places where a function or variable is being used. This is possible in
two ways:
1. Using the |:grep| command. This should work on most Unix systems,
but can be slow (it reads all files) and only searches in one directory.
2. Using ID utils. This is fast and works in multiple directories. It uses a
database to store locations. You will need some additional programs for
this to work. And you need to keep the database up to date.

Using the GNU id-tools:

What you need:
- The GNU id-tools installed (mkid is needed to create ID and lid is needed to
use the macros).
- An identifier database file called "ID" in the current directory. You can
create it with the shell command "mkid file1 file2 ..".

Put this in your .vimrc:
map _u :call ID_search()<Bar>execute "/\\<" . g:word . "\\>"<CR>
map _n :n<Bar>execute "/\\<" . g:word . "\\>"<CR>

function! ID_search()
let g:word = expand("<cword>")
let x = system("lid --key=none ". g:word)
let x = substitute(x, "\n", " ", "g")
execute "next " . x

To use it, place the cursor on a word, type "_u" and vim will load the file
that contains the word. Search for the next occurrence of the word in the
same file with "n". Go to the next file with "_n".

This has been tested with id-utils-3.2 (which is the name of the id-tools
archive file on your closest gnu-ftp-mirror).

[the idea for this comes from Andreas Kutschera]


Switching screens in an xterm *xterm-screens* *xterm-save-screen*

(From comp.editors, by Juergen Weigert, in reply to a question)

:> Another question is that after exiting vim, the screen is left as it
:> was, i.e. the contents of the file I was viewing (editing) was left on
:> the screen. The output from my previous like "ls" were lost,
:> ie. no longer in the scrolling buffer. I know that there is a way to
:> restore the screen after exiting vim or other vi like editors,
:> I just don't know how. Helps are appreciated. Thanks.
:I imagine someone else can answer this. I assume though that vim and vi do
:the same thing as each other for a given xterm setup.

They not necessarily do the same thing, as this may be a termcap vs.
terminfo problem. You should be aware that there are two databases for
describing attributes of a particular type of terminal: termcap and
terminfo. This can cause differences when the entries differ AND when of
the programs in question one uses terminfo and the other uses termcap
(also see |+terminfo|).

In your particular problem, you are looking for the control sequences
^[[?47h and ^[[?47l. These switch between xterms alternate and main screen
buffer. As a quick workaround a command sequence like
echo -n "^[[?47h"; vim ... ; echo -n "^[[?47l"
may do what you want. (My notation ^[ means the ESC character, further down
you'll see that the databases use \E instead).

On startup, vim echoes the value of the termcap variable ti (terminfo:
smcup) to the terminal. When exiting, it echoes te (terminfo: rmcup). Thus
these two variables are the correct place where the above mentioned control
sequences should go.

Compare your xterm termcap entry (found in /etc/termcap) with your xterm
terminfo entry (retrieved with /usr/5bin/infocmp -C xterm). Both should
contain entries similar to:

PS: If you find any difference, someone (your sysadmin?) should better check
the complete termcap and terminfo database for consistency.

NOTE 1: If you recompile Vim with FEAT_XTERM_SAVE defined in feature.h, the
builtin xterm will include the mentioned "te" and "ti" entries.

NOTE 2: If you want to disable the screen switching, and you don't want to
change your termcap, you can add these lines to your .vimrc:
:set t_ti= t_te=


Scrolling in Insert mode *scroll-insert*

If you are in insert mode and you want to see something that is just off the
screen, you can use CTRL-X CTRL-E and CTRL-X CTRL-Y to scroll the screen.

To make this easier, you could use these mappings:
:inoremap <C-E> <C-X><C-E>
:inoremap <C-Y> <C-X><C-Y>
(Type this literally, make sure the '<' flag is not in 'cpoptions').
You then lose the ability to copy text from the line above/below the cursor

Also consider setting 'scrolloff' to a larger value, so that you can always see
some context around the cursor. If 'scrolloff' is bigger than half the window
height, the cursor will always be in the middle and the text is scrolled when
the cursor is moved up/down.


Smooth scrolling *scroll-smooth*

If you like the scrolling to go a bit smoother, you can use these mappings:
:map <C-U> <C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y>
:map <C-D> <C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E>

(Type this literally, make sure the '<' flag is not in 'cpoptions').


Correcting common typing mistakes *type-mistakes*

When there are a few words that you keep on typing in the wrong way, make
abbreviations that correct them. For example:
:ab teh the
:ab fro for


Counting words, lines, etc. *count-items*

To count how often any pattern occurs in a buffer, set 'report' to 0, and use
the substitute command to replace the pattern with itself. The reported
number of substitutions is the number of items. Examples:

:set report=0
:%s/./&/g characters
:%s/\i\+/&/g words
:%s/^ lines
:%s/the/&/g "the" anywhere
:%s/\<the\>/&/g "the" as a word

You might want to reset 'hlsearch' or do ":nohlsearch".

This does not work if the 'modifiable' option is off. An alternative is using
|v_g_CTRL-G| in Visual mode.

If you want to count bytes, you can use this:

Visually select the characters (block is also possible)
Use "y" to yank the characters
Use the strlen() function:
:echo strlen(@")
A line break is counted for one byte.


Restoring the cursor position *restore-position*

Sometimes you want to write a mapping that makes a change somewhere in the
file and restores the cursor position, without scrolling the text. For
example, to change the date mark in a file:
:map <F2> msHmtgg/Last [cC]hange:\s*/e+1<CR>"_D"=strftime("%Y %b %d")<CR>p'tzt`s

Breaking up saving the position:
ms store cursor position in the 's' mark
H go to the first line in the window
mt store this position in the 't' mark

Breaking up restoring the position:
't go to the line previously at the top of the window
zt scroll to move this line to the top of the window
`s jump to the original position of the cursor


Renaming files *rename-files*

Say I have a directory with the following files in them (directory picked at
random :-):


and I want to rename *.c *.bla. I'd do it like this:

$ vim
:r! ls *.c
:%s/\(.*\).c/mv & \1.bla
:w !sh


Speeding up external commands *speed-up*

In some situations, execution of an external command can be very slow. This
can also slow down wildcard expansion on Unix. Here are a few suggestions to
increase the speed.

If your .cshrc (or other file, depending on the shell used) is very long, you
should separate it into a section for interactive use and a section for
non-interactive use (often called secondary shells). When you execute a
command from Vim like ":!ls", you do not need the interactive things (for
example, setting the prompt). Put the stuff that is not needed after these

if ($?prompt == 0) then
exit 0

Another way is to include the "-f" flag in the 'shell' option, e.g.:

:set shell=csh\ -f

(the backslash is needed to include the space in the option).
This will make csh completely skip the use of the .cshrc file. This may cause
some things to stop working though.


Useful mappings *useful-mappings*

Here are a few mappings that some people like to use.

:map ' `
Make the single quote work like a backtick. Puts the cursor on the column of
a mark, instead of going to the first non-blank character in the line.

For Emacs-style editing on the command-line:
" start of line
:cnoremap <C-A> <Home>
" back one character
:cnoremap <C-B> <Left>
" delete character under cursor
:cnoremap <C-D> <Del>
" end of line
:cnoremap <C-E> <End>
" forward one character
:cnoremap <C-F> <Right>
" recall newer command-line
:cnoremap <C-N> <Down>
" recall previous (older) command-line
:cnoremap <C-P> <Up>
" back one word
:cnoremap <Esc><C-B> <S-Left>
" forward one word
:cnoremap <Esc><C-F> <S-Right>

NOTE: This requires that the '<' flag is excluded from 'cpoptions'. |<>|

This mapping will format any bullet list. It requires that there is an empty
line above and below each list entry. The expression commands are used to
be able to give comments to the parts of the mapping.

:let m = ":map _f :set ai<CR>" " need 'autoindent' set
:let m = m . "{O<Esc>" " add empty line above item
:let m = m . "}{)^W" " move to text after bullet
:let m = m . "i <CR> <Esc>" " add space for indent
:let m = m . "gq}" " format text after the bullet
:let m = m . "{dd" " remove the empty line
:let m = m . "5lDJ" " put text after bullet
:execute m |" define the mapping

(<> notation |<>|. Note that this is all typed literally. ^W is "^" "W", not
CTRL-W. You can copy/paste this into Vim if '<' is not included in

Note that the last comment starts with |", because the ":execute" command
doesn't accept a comment directly.

You also need to set 'textwidth' to a non-zero value, e.g.,
:set tw=70

A mapping that does about the same, but takes the indent for the list from the
first line (Note: this mapping is a single long line with a lot of spaces):
:map _f :set ai<CR>}{a <Esc>WWmmkD`mi<CR><Esc>kkddpJgq}'mJO<Esc>j

These two mappings reduce a sequence of empty (;b) or blank (;n) lines into a
single line
:map ;b GoZ<Esc>:g/^$/.,/./-j<CR>Gdd
:map ;n GoZ<Esc>:g/^[ <Tab>]*$/.,/[^ <Tab>]/-j<CR>Gdd


Compressing the help files *gzip-helpfile*

For those of you who are really short on disk space, you can compress the help
files and still be able to view them with Vim. This makes accessing the help
files a bit slower and requires the "gzip" program.

(1) Compress all the help files: "gzip doc/*.txt".

(2) Edit "doc/tags" and change the ".txt" to ".txt.gz":

(3) Add this line to your vimrc:
set helpfile={dirname}/help.txt.gz

Where {dirname} is the directory where the help files are. The |gzip| plugin
will take care of decompressing the files.
You must make sure that $VIMRUNTIME is set to where the other Vim files are,
when they are not in the same location as the compressed "doc" directory. See


Executing shell commands in a window *shell-window*

There have been questions for the possibility to execute a shell in a window
inside Vim. The answer: you can't! Including this would add a lot of code to
Vim, which is a good reason not to do this. After all, Vim is an editor, it
is not supposed to do non-editing tasks. However, to get something like this,
you might try splitting your terminal screen or display window with the
"splitvt" program. You can probably find it on some ftp server. The person
that knows more about this is Sam Lantinga <>.
An alternative is the "window" command, found on BSD Unix systems, which
supports multiple overlapped windows. Or the "screen" program, found at, which supports a stack of windows.


Hex editing *hex-editing* *using-xxd*

See section |23.4| of the user manual.

If one has a particular extension that one uses for binary files (such as exe,
bin, etc), you may find it helpful to automate the process with the following
bit of autocmds for your <.vimrc>. Change that "*.bin" to whatever
comma-separated list of extension(s) you find yourself wanting to edit:

" vim -b : edit binary using xxd-format!
augroup Binary
au BufReadPre *.bin let &bin=1
au BufReadPost *.bin if &bin | %!xxd
au BufReadPost *.bin set ft=xxd | endif
au BufWritePre *.bin if &bin | %!xxd -r
au BufWritePre *.bin endif
au BufWritePost *.bin if &bin | %!xxd
au BufWritePost *.bin set nomod | endif
augroup END


Using <> notation in autocommands *autocmd-<>*

The <> notation is not recognized in the argument of an :autocmd. To avoid
having to use special characters, you could use a self-destroying mapping to
get the <> notation and then call the mapping from the autocmd. Example:

" This is for automatically adding the name of the file to the menu list.
" It uses a self-destroying mapping!
" 1. use a line in the buffer to convert the 'dots' in the file name to \.
" 2. store that in register '"'
" 3. add that name to the Buffers menu list
" WARNING: this does have some side effects, like overwriting the
" current register contents and removing any mapping for the "i" command.
autocmd BufNewFile,BufReadPre * nmap i :nunmap i<CR>O<C-R>%<Esc>:.g/\./s/\./\\./g<CR>0"9y$u:menu Buffers.<C-R>9 :buffer <C-R>%<C-V><CR><CR>
autocmd BufNewFile,BufReadPre * normal i

Another method, perhaps better, is to use the ":execute" command. In the
string you can use the <> notation by preceding it with a backslash. Don't
forget to double the number of existing backslashes and put a backslash before

autocmd BufNewFile,BufReadPre * exe "normal O\<C-R>%\<Esc>:.g/\\./s/\\./\\\\./g\<CR>0\"9y$u:menu Buffers.\<C-R>9 :buffer \<C-R>%\<C-V>\<CR>\<CR>"

For a real buffer menu, user functions should be used (see |:function|), but
then the <> notation isn't used, which defeats using it as an example here.


FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  


Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy


War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes


Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law


Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least

Copyright © 1996-2016 by Dr. Nikolai Bezroukov. was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case is down you can use the at


The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: September 12, 2017