Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Indenting and Beautifying Your Code in VIM

Old News ;-) VIM -- VI-style Editor with folding capabilities Recommended Links VIM visual blocks Vim Buffers and Text-buffer Execution .vimrc VIM Exrc file VIM Multiwindows Support
Piping Vim Buffer   File managers in VIM Copying and Moving sections of text Vim Regular Expressions Vim Options and Set command Searching and replacing text in VI
Indenting Your Code in VIM Outliner VIM running external commands Searching and replacing text in VI Ctags code browsing framework Perl one-liners  
Line Ranges Vim documentation: if_perl Tips VIM Perl Support Humor History 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:

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.

The most convenient way to select a block of code for identing  or reformatting is VIM visual blocks

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

Moving Around Code

Specifically, the following group of motions was particularly useful for indenting:

With these motions fresh in our mind, let’s review some code that demonstrates how best to utilize them. Following is an example of some JavaScript code that demonstrates three nested functions:

function foo(){
    function bar(){
        function baz(){
            return {
                a: 1,
                b: 2,
                c: 3
            };
        }
    }
}

Imagine that your cursor is currently placed on the middle line b: 2, and you would like to move to the opening curly bracket ({) of the third line, which, in this case, would be the line containing function baz(){.

You can’t use the % motion, because that only matches against a set of parenthesis or brackets on the current line. You also can’t use the f or F operators for the same reason. They only work on a line basis, and searching for the bracket using ?{ is more keystrokes than we would like, as that would match all previous brackets, and we’d have to press n more than once to navigate to the specific bracket we wanted to access.

For this example, the most efficient way to navigate to the relevant bracket we want is to use the following [{command, along with a count prefixed to indicate the number of times to execute the command (in this case, we don’t want the previous opening bracket but the one before that), like so: 2[{.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Oct 21, 2018] Common visual block selection scenarios

Notable quotes:
"... column oriented ..."
Oct 21, 2018 | stackoverflow.com
You are talking about text selecting and copying, I think that you should give a look to the Vim Visual Mode .

In the visual mode, you are able to select text using Vim commands, then you can do whatever you want with the selection.

Consider the following common scenarios:

You need to select to the next matching parenthesis.

You could do:

You want to select text between quotes:

You want to select a curly brace block (very common on C-style languages):

You want to select the entire file:

Visual block selection is another really useful feature, it allows you to select a rectangular area of text, you just have to press Ctrl - V to start it, and then select the text block you want and perform any type of operation such as yank, delete, paste, edit, etc. It's great to edit column oriented text.

Vim cheatcheet.

Marking text (visual mode)

Visual commands

Cut and Paste

typing : would add the block to ex command line and low you touse ex commans with the block inclide mo command is :'<,'> mo 15. This means move visual blok toposition after line 15. the target can be bookmark

:'<,'> mo mark a

Using registers to moving blocks

"<letter>y

7 uu Making it even quicker:
6
5 If •+y and "+p are too many keypresses, we can easily remap
4 the copy and paste commands.
3
2
1 vnoremap <C-c> "+y
map <C-fc "+p
1 ...
2
3 You might want to consider using P instead of p.
4
5 For copying to both the clipboard and primary selection.
6
7 ... ... ...
8 vnoremap <C-c> "*y :let @+=@**<CR>
9
0

[Oct 19, 2018] Vim faster way to select blocks of text in visual mode - Stack Overflow

Oct 19, 2018 | stackoverflow.com

Vim: faster way to select blocks of text in visual mode Ask Question up vote 149 down vote favorite 65


Calvin Cheng ,Sep 13, 2011 at 18:52

I have been using vim for quite some time and am aware that selecting blocks of text in visual mode is as simple as SHIFT + V and moving the arrow key up or down line-by-line until I reach the end of the block of text that I want selected.

My question is - is there a faster way in visual mode to select a block of text for example by SHIFT + V followed by specifying the line number in which I want the selection to stop? (via :35 for example, where 35 is the line number I want to select up to - this obviously does not work so my question is to find how if something similar to this can be done...)

user786653 ,Sep 13, 2011 at 19:08

+1 Good question as I have found myself doing something like this often. I am wondering if perhaps this isn't the place start using using v% or v/pattern or something else? – user786653 Sep 13 '11 at 19:08

SergioAraujo ,Sep 13, 2011 at 20:30

vip select inner paragraph vis select inner sentence. – SergioAraujo Sep 13 '11 at 20:30

Stephan ,Sep 29, 2014 at 22:49

V35G will visually select from current line to line 35, also V10j or V10k will visually select the next or previous 10 lines – Stephan Sep 29 '14 at 22:49

shriek ,Feb 20, 2015 at 4:28

@Stephan, that's just what I was looking for. Thanks!! – shriek Feb 20 '15 at 4:28

Mikhail V ,Mar 27, 2015 at 16:52

for line selecting I use shortcut: nnoremap <Space> V . When in visual line mode just right-click with mouse to define selection (at least on linux it is so). Anyway, more effective than with keyboard only. – Mikhail V Mar 27 '15 at 16:52

Jay ,Sep 13, 2011 at 19:05

In addition to what others have said, you can also expand your selection using pattern searches.

For example, v/foo will select from your current position to the next instance of "foo." If you actually wanted to expand to the next instance of "foo," on line 35, for example, just press n to expand selection to the next instance, and so on.

update

I don't often do it, but I know that some people use marks extensively to make visual selections. For example, if I'm on line 5 and I want to select to line 35, I might press ma to place mark a on line 5, then :35 to move to line 35. Shift + v to enter linewise visual mode, and finally `a to select back to mark a .

Calvin Cheng ,Sep 13, 2011 at 19:19

now this is COOL. Thanks! – Calvin Cheng Sep 13 '11 at 19:19

Peter Rincker ,Sep 13, 2011 at 19:41

If you need to include the pattern you can use v/foo/e . The e stands for "end" of the matched pattern. – Peter Rincker Sep 13 '11 at 19:41

bheeshmar ,Sep 13, 2011 at 20:29

And you can modify from that line with offsets: V/foo/+5 or V/foo/-5 (I'm using linewise visual mode like the author). – bheeshmar Sep 13 '11 at 20:29

Jay ,Oct 31, 2013 at 0:18

@DanielPark To select the current word, use v i w . If you want to select the current contiguous non-whitespace, use v i Shift + w . The difference would be when the caret is here MyCla|ss.Method , the first combo would select MyClass and second would select the whole thing. – Jay Oct 31 '13 at 0:18

Daniel Park ,Oct 31, 2013 at 1:55

Thanks. Found that also using v i w s allows you to effectively do a "replace" operation. – Daniel Park Oct 31 '13 at 1:55

bheeshmar ,Sep 13, 2011 at 19:00

G                       Goto line [count], default last line, on the first
                        non-blank character linewise.  If 'startofline' not
                        set, keep the same column.
                        G is a one of jump-motions.

V35G achieves what you want

Daniel Kobe ,Apr 24, 2017 at 18:16

My vim gives me the error Not an editor command: VDaniel Kobe Apr 24 '17 at 18:16

kzh ,Apr 24, 2017 at 19:42

@Daniel vimdoc.sourceforge.net/htmldoc/visual.html#Vkzh Apr 24 '17 at 19:42

bheeshmar ,Apr 25, 2017 at 19:06

@DanielKobe, it's a Normal mode command, so don't press ":". – bheeshmar Apr 25 '17 at 19:06

kzh ,Jun 1, 2013 at 12:29

Vim is a language. To really understand Vim, you have to know the language. Many commands are verbs, and vim also has objects and prepositions.
V100G
V100gg

This means "select the current line up to and including line 100."

Text objects are where a lot of the power is at. They introduce more objects with prepositions.

Vap

This means "select around the current paragraph", that is select the current paragraph and the blank line following it.

V2ap

This means "select around the current paragraph and the next paragraph."

}V-2ap

This means "go to the end of the current paragraph and then visually select it and the preceding paragraph."

Understanding Vim as a language will help you to get the best mileage out of it.

After you have selecting down, then you can combine with other commands:

Vapd

With the above command, you can select around a paragraph and delete it. Change the d to a y to copy or to a c to change or to a p to paste over.

Once you get the hang of how all these commands work together, then you will eventually not need to visually select anything. Instead of visually selecting and then deleting a paragraph, you can just delete the paragraph with the dap command.

Daniel Kobe ,Apr 24, 2017 at 18:17

My vim gives me the error Not an editor command: VDaniel Kobe Apr 24 '17 at 18:17

kzh ,Apr 24, 2017 at 19:43

@Daniel vimdoc.sourceforge.net/htmldoc/visual.html#Vkzh Apr 24 '17 at 19:43

michaelmichael ,Sep 13, 2011 at 18:58

v35G will select everything from the cursor up to line 35.

v puts you in select mode, 35 specifies the line number that you want to G go to.

You could also use v} which will select everything up to the beginning of the next paragraph.

mateusz.fiolka ,Sep 13, 2011 at 18:58

For selecting number of lines:

shift+v 9j - select 10 lines

Peter Rincker ,Sep 13, 2011 at 19:38

For small ranges this is good, especially when paired with :set rnuPeter Rincker Sep 13 '11 at 19:38

µBio ,Sep 13, 2011 at 18:55

v 35 j

text added for 30 character minimum

Peng Zhang ,Feb 17, 2016 at 3:28

Shift+V n j or Shift+V n k

This selects the current line and the next/previous n lines. I find it very useful.

Kevin Yue ,Sep 24, 2016 at 5:20

It's very useful, thanks. – Kevin Yue Sep 24 '16 at 5:20

Arsal ,Apr 24, 2017 at 20:09

This is a simple way I was looking for. Thanks – Arsal Apr 24 '17 at 20:09

> ,

Text objects: http://vim.wikia.com/wiki/Creating_new_text_objects

http://vimdoc.sourceforge.net/htmldoc/motion.html#text-objects

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 ) {
 printf("one");
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).

Comments

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 "http://vim.wikia.com/wiki/Indent_a_code_block"

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
else
set t_Co=8
set t_Sf=<Esc>[3%dm
set t_Sb=<Esc>[4%dm
endif
endif


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


June 30th, 2007 #3
hyjkim
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


VIM REFERENCE MANUAL by Bram Moolenaar


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
line

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
mode).
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.


*cinoptions-values*
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
'shiftwidth').

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
'shiftwidth').

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) {
do_something();
}
});

)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:
cinoptions=>s,e0,n0,f0,{0,}0,^0,:s,=s,l0,gs,hs,ps,ts,+s,c3,C0,(2s,us,
\U0,w0,m0,j0,)20,*30

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
"default").
- Any combination of indentations causes the line to have less than 0
indentation.

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

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.


REMARKS ABOUT SPECIFIC INDENT FILES

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
http://www.unb.ca/chem/ajit/f_tidy.htm. 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
follows

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
used:

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


VIM REFERENCE MANUAL by Bram Moolenaar

Tips and ideas for using Vim *tips*

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

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
text.
|=| 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
files.

|CTRL-]| Jump to tag under cursor (e.g., definition of a
function).
|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
endfun

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:
:te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:

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.
|i_CTRL-X_CTRL-E|

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
|i_CTRL-E|.

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.


*count-bytes*
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 :-):

buffer.c
charset.c
digraph.c
...

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

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

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

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
lines:

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

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-backtick*
: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.


*emacs-keys*
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'. |<>|


*format-bullet-list*
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
'cpoptions')

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


*collapse*
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":
:%s=\(\t.*\.txt\)\t=\1.gz\t=

(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
|$VIMRUNTIME|.

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

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 <[email protected]>.
An alternative is the "window" command, found on BSD Unix systems, which
supports multiple overlapped windows. Or the "screen" program, found at
www.uni-erlangen.de, 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!
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:


*map-self-destroy*
" 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.