Vim tips and tricks

Vim Tips and Tricks

Save and quit

:w => Save [:w filename writes the content to the specified file from current file]

:q => Exit as long as there have been no changes

:q! => Exit and ignore any changes

:wq => Save and Exit.

:x => Exit, saving changes

ZZ => Exit and save changes if any have been made

:10,20w filename => writes the line from 10th line to 20th line in given file name


Moving the Cursor

h : Move left

i : Move right

j : Move down

k : Move up

+ : act as j in command mode

  • : act as k in command mode

w : Move to next word

W : Move to next blank delimited word

b : Move to the beginning of the word

B : Move to the beginning of blank delimiter word

e : Move to the end of the word

E : Move to the end of Blank delimited word

ge : jump to previous word-ending

gE : jump to previous word-ending, ignore punctuation

g_ : jump to last non-blank character of the line

( : Move a sentence back

) :Move a sentence forward

{ : Move a paragraph back

} : Move a paragraph forward

0 : Move to the beginning of the line [ 0 and | acts as a Home key it goes to beginning of a line ]

$ : Move to the end of the line, acts as a End key

:1 : Move to the first line of the file

G : Move to the last line of the file

nG : Move to nth line of the file

:n : Move to nth line of the file

fc :Move forward to c (c= character)

Fc : Move back to c

H :Move to top of screen

M :Move to middle of screen

L : Move to bottom of screen


Inserting Text

i : Insert before cursor

I : Insert before line

a : Append after cursor

A : Append after line

o : Open a new line after current line

O : Open a new line before current line

r : Replace one character


Delete/Cut and Paste

d^ : Deletes from current cursor position to the beginning of the line.

d$ : Deletes from current cursor position to the end of the line.

dw : Deletes from current cursor position to the end of the word.

dd : Deletes three lines from current cursor position downwards.(also :d)

yy : Yank the current line (also :y)

x : Delete a character next to the cursor

X : Delete character to the left of cursor

P : Paste line before the cursor

p : Paste line after the cursor

. : Repeat last edit command

u : Undo last edit (Ctrl+r redo)

U : Undo changes to current line

J : Join two lines

In Escape mode: C is delete the line from under the cursor to end of the line.


External commands:

In Vim it's easy to include the output of external commands in to file.

!command, the output will be shown in prompt.

To insert the output of the external command in the current file
type :r!command for example

 :r!date

[CENTER]_____________________________________________________________________________________

Completion

[/CENTER]
In insert mode.

Ctrl+p word completion .

Ctrl+x Ctrl+l whole line completion.

Ctrl+x Ctrl+k to do a dictionary lookup for the already typed characters.

Ctrl+x Ctrl+f to print the filename is vim.


Search/Replace

/pattern : search for pattern

?pattern : search backward for pattern

n :repeat search in same direction

N : repeat search in opposite direction

:%s/old/new/g : replace all old with new throughout file

:%s/old/new/gc : replace all old with new throughout file with confirmations

    We can change the substitution delimiter instead of "/" to % or \# or @ or !.

    Refer the Following Link.


http://www.unix.com/unix-dummies-questions-answers/131585-changing-vi.html

:/pattern/= => Print the line number of the first line that matches pattern.

:g/pattern => Finds (moves to) the last occurrence of pattern in the file.

:g/pattern/p => Finds and displays all lines in the file containing pattern.

:g!/pattern/nu => Finds and displays all lines in the file that don't contain pattern;
also displays the line number for each line found.

:60,124g/pattern/p => Finds and displays any lines between lines 60 and 124 containing pattern


[CENTER]Inverting Case (Upper to Lower / Lower to Upper)

[LEFT]~ :changes the lower case to upper case of current character

~guu :change current line from upper to lower.

~gUU :Change current LINE from lower to upper.

~guw :Change current WORD from upper to lower.

~gUw :Change current WORD from lower to upper.

g~~ :Invert case to entire line


:lineno goes to line in execution mode

:.= gives current cursor position of line

:= total no of lines in file

Ctrl+h acts as a backspace in insert mode

shift + 9 goes to sentence starting point in backward

shift + 0 goes to sentence starting point in forward

:e is used for editing another file with out quiting the vim editor cltrl+^ is used to toggle between the two files.

:syn on command in vimrc file will highlight the syntax during inserting the contents in program.


Opening Man page from VIM

K (Shift+k) will diplays the man page of current word under the cursor


[LEFT][CENTER]Splitting Windows

:sp will split the window

:q to quit from current split window

Crtl+ww navigate through another file

:bnext (or :bn) go to next buffer

:bprev (or :bp) go to previous buffer

:bd delete a buffer (close a file)

Ctrl+ws Split windows

Ctrl+ww Switch between windows

Ctrl+wq Quit a window

Ctrl+wv Split windows vertically.


[CENTER]Set Options

[LEFT]:set showmode - will show the current mode

:set autowrite - will write into file when we are toggling between two files with in editor.

:set autoindent - it is used for intendation the code.

Displaying Line Numbers

From Command Mode

:set nu [OR] :set number Display line numbers It will not save in file after closing the file.

:set nonu [OR] :set nonumber  Hide line numbers

:set nomagic - will special character meaning, like * as some meaning when searching

:set tabstop - will set the spaces of tab key default it will 8 spaces

:set showmatch - will show the match of that brace default it will be setted.

:set spell will set the spell checking and high light wrong spell words.

[/LEFT]
[/CENTER]
[/LEFT]


[LEFT]Folding

If we want to folding some few lines in vim file:

First select the lines after type :fold

The selected line is folded.

If we want to open the folded lines use "zo".

If we want to close the folding lines use zc".

zR Unfold all folded lines in file.

za Open/close (toggle) a folded group of lines.

zA Open a closed fold or close an open fold recursively.

zc Close a folded group of lines.

zC Close all folded lines recursively.

zd Delete a folded line.

zD Delete all folded lines recursively.

zE Eliminate all folded lines in file.

zF Create "N" folded lines.


[/LEFT]
[/CENTER]
[/LEFT]
[/CENTER]

Recording
Insert mode type 1.
Escape mode.
q a press q buffer name
copy and paste.
Ctrl+a increments the number in current cursor
Ctrl+x decrements the number in current cursor
q to quit from recording
to execute the recording buffer:
10 @ buffername(a)

--------------------------------------------------------------------
Ctrl + a => increase a number under the cursor.
Ctrl + x => decrease a number under the cursor.
-------------------------------------------------------------------


Mapping a key

In vim editor we can map the key for our requirement for that we use map command

Syntax: :map keyname work
Eg: :map <F2> :w - will save the file when F2 key pressed in command mode.

The key can be unmapped by unmap command
Syntax: :unmap

This mapping key is useful for compiling and executing a program

Abbreviation

Abbreviation is used in this vim editor
Syntax: :ab abbreviatedword explanation
Eg: :ab w work


Ctrl+f forward scroll screen

Ctrl+b backward scroll screen

Ctrl-d Scroll down one half of a page

Ctrl-u Scroll up one half of a page

. will execute the last command in execution mode

In split window N goes backward to navigate

^w+ resizing the current split window to larging

^w- To decreasing the size of current split window

p put after current cursor

P put before the current cursor

In Insert mode Ctrl+w is used to cut the current word.

we can open multiple file at same time by passing all filename in vim command in single line.
:next is used to go to next file.

J concatenates the line by deleting the end of line

:set aw this command ensures that file saved automatically before switching.

: on removes all other windows in split window and current window will become the full screen.

Buffer can be used in this file to create buffer "buffername commands output command is stored in buffername.
Eg: "a3yy - copy the 3 lines and stored in a buffer

We can replace the particular word in particular range of line
Syntax: %10s/new/old/g - global

: pwd Print the current directory name.


p and P differs on entire line and part of line deleted or yanked.

P places it left when word is deleted or cutted or yanked.

p places it right when word is deleted or cutted or yanked.

P places it above when entire line is deleted or yanked.

p places it below when entire line is deleted or yanked.

In Insert Mode

^t give tab in beggining of a line

^y copies above character and paste

^u undo the operation

^i gives tab in current position

^o goes to command mode and accept only one command and return back to insert mode

^a place the buffer which has inserted text after opening the file.

^j and ^m acts as a enter key

^k insert before the current position

^c goes to command mode

In execution shift>> acts as tab instead of tab character


B,W,E navigate between words but they ignore punctuations.

:.!tr '[a-z]' '[A-Z]' - will convert case lower to upper in current line

:map r :w^V^M will save the file when press r in command mode

^M is set to be enter key in mapping

Visual mode.

Shift+v is to select a line
Ctrl+v is to select a block of text.

gv is used to reselect the last selection part in visual mode.

If you select some lines in visual mode using Ctrl+v or Shift+v.
later you want to select last selection in lines use gv.

========================================================
% keystroke

The % is used to match the item under the cursor. The item under the cursor can be a parenthesis, a curly bracket or a square bracket. By pressing the % key the cursor will jump to the corresponding match.

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

You can open your .vimrc file in your vim file itself. See the following example

:e ~/.vimrc

[or]

:e $MYVIMRC

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

For C coding in VIM

gd keystroke
The gd keystroke stands for Goto Declaration
With the cursor on x if you hit gd the cursor will take you to the declaration of x.

A similar keystroke is gD.
This takes you to the global declaration of the variable under the cursor.

Automatically indent code.

:set cindent
It automatically indent the C coding file.

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

single quot dot ('.) is go to the last modification line in a file.

(`") back tick and double quote is goes to the last modification character.

:history - list the .viminfo informations ( recent commands executed in vim.)

q: - it will open a list on executed commands in separate window

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

Encrypting.

If you want to set Encrypt key(password) to your file use the following command

:X

While opening a file you need to give the Encryption key.

============================================================================================
Vim Command Line options.

vim + file_name

+ it will place the cursor at end of the after opening.

+n it will place the cursor at nth line of the file.

Ex: vim +3 fine_name it place the cursor at 3rd line of the file.

vim +/pattern filename

+/pattern ( vim +/hi filename). the cursor is first occurrence of the pattern line

+n/pattern ( vim +3/hi filename) cursor is nth occurrence of the line.

if you want to search a pattern like "Welcome to vim", see the following examples.

quote the string.

vim +/"to vim" filename

escape the space.

vim +/to\ vim a

-R Option is used to open a file in read only mode(you can't edit that file.

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


:e! returns you to the last saved version of the file, so you can start over.

yl is used to copy a single character.

^ Move to first non-blank character of current line.

n| Move to column n of current line.

Current Line Searches

fx Find (move cursor to) next occurrence of x in the line, where x stands for any character.

Fx Find (move cursor to) previous occurrence of x in the line.

tx Find (move cursor to) character before next occurrence of x in the line.

Tx Find (move cursor to) character after previous occurrence of x in the line.

; Repeat previous find command in same direction.

, Repeat previous find command in opposite direction.


If you have some vim tips add it.

22 Likes

Nice one!!!! To open a file inside vim.
steps:

[*]Place the cursor on the file name.
[*]Press keys gf on escape mode.
[*]Now that file will be opened.
[*]To return to the main file press [ctrl]+^.

To delete all the lines inside vim


[*]On escape mode press gg now it will go to the first line
[*]Then press dG.
[*]Now it will delete from the first line to last line.

We can type /afs-afs at the command prompt to search "afs-afs".

We can also hit "*" in escape mode and vim will search the word under the cursor.

hey buddy its very good post :cool:
Can any body tell me how to define a function and use it.

Set the following code into your .vimrc

"Changing colorschema
:function! Color_chamge()
:colorscheme darkblue
:endfunction


map <F3> :execute Color_chamge()<CR> :source $HOME/.vimrc<CR>

Note: double quote (") is a comment line in .vimrc file

Edited by pludi: If you post something, please use the "Preview Post" button to check that whatever you post is actually legible!!!

#################################################################
@:                                                   : repeat last : command (then @@)

Open file under cursor:

gf                                                    : open file name under cursor.

<c-w>f 	 open in a new window (Ctrl-w f)

<c-w>gf 	open in a new tab (Ctrl-w gf)


:nnoremap gF :view   : open file under cursor, create if necessary


#################################################################
Searching
/joe/e                      : cursor set to End of match
/joe/e+1                    : cursor set to End of match plus 1
/joe/s-2                    : cursor set to Start of match minus 2
/joe/+3                     : find joe move cursor 3 lines down
:g/gladiolli/#              : display with line numbers (YOU WANT THIS!)
#################################################################
Create a new file for each line of file eg 1.txt,2.txt,3,txt etc  :g/^/exe ".w ".line(".").".txt"
#################################################################
:history         : list of all your commands
:his c           : commandline history
:his s           : search history
#################################################################
q/          : Search history Window (puts you in full edit mode) (exit  CTRL-C)
q:           : commandline history Window (puts you in full edit mode)(exit  CTRL-C)
#################################################################

---------- Post updated at 03:41 ---------- Previous update was at 03:11 ----------

Function to delete duplicate lines

function! Del() 
if getline(".") == getline(line(".") - 1)
norm dd
endif 
endfunction 

Function for compile and run a JAVA file.

:function! JAVA_RUN() 
:!/opt/jdk1.5.0_10/bin/javac -cp . % 
:!/opt/jdk1.5.0_10/bin/java -classpath ./ %:r 
:endfunction 

Note: %:r will give the file name without the file extinction.

Cool Post.
Really helpful

Hi,
I need to copy text up to first blank space in the line.

my_number=12345.6789% 1654.2345 This a sample line. 
I need to copy upto first.blank_space in this line.

Here my cursor is at m i need to copy upto first blank i.e my_number=12345.6789% to a register.similarly we go for second line here if cursor is at fthen i need first.blank_space to some other register.

Thanks
posix

Shift + k is used to open the man page under the cursor. if you want to execute the command instead of opening the man page use the following functions.

"This function used to get the current cursor word and execute that command

                fu ExecuteCommand()
                let l:Command = expand("<cword>")
                execute "!" . l:Command
                endfu

"This function used to get the current cursor line and execute that command

                fu ExecuteCommandLine()
                let l:Command = getline(line("."))
                execute "!" . l:Command
                endfu

Note:
<cword> is replaced with the word under the cursor (like |star|)
<cWORD> is replaced with the WORD under the cursor (see WORD|)

---------- Post updated at 01:14 ---------- Previous update was at 01:08 ----------

use the keys : 1yW

2 Likes

Underline a text/line in vim

nnoremap <F5> yyp<c-v>$r-
" <F5> underline a word or line

Example:

This is for Example

if you want to underline this above line use the above code then it will be like this.

This is for Example
--------------------

Be very careful when you quit with editing some file. I use the following ...

:wq

But ones one little dot came between ...

:.wq

Whot does it mean? It saves only the line where the cursor was at that moment.

That time I lost more than 12000 lines and about 2 hours and a half work. Only because a finger slides over a dot.

Great point, but iit should only allow it if you force a write with:

:.wq!

But it's easily done, especially if saving a read-only file, where you have to use ! anyway.

Hi,
I am using VIM 7.1 version on my Ubuntu 8.04 (hardy heron). I am irritated to see the auto matching cursor whenever it comes across parantheses, brackets and braces while editing. I used ':set noshowmatch', but no use. What other options are available for me?

set the following code in your .vimrc file

let g:loaded_matchparen= 1
1 Like

This thread is a little old, I hope I dont have to make a new one for this.

On most systems the arrow keys will give you control of the cursor, however when I was first learning my arrow keys just stopped working in vim. I found the solution somewhere and it was just a simple command to run before using vim every day so i added it to my .profile and forgot about it. Now I am miles away from my work computer so have no way to look it up, so if someone knows what I am talking about and can clarify or at least post the command I think that would make a great addition to this thread. I will try to find it and post it here. If no one beats me to it.

As a new user that almost made me want to give up, I couldn't scroll and so for me there was nothing better than cat.

I am a beginner with unix, so may be my question will be very stupid.

I have problem with saving a FORTRAN's code after changing it.
I used the "vim" command to read the code, then use the "SHIFT-I" to insert some new part in the code.
After that I don't know how to save the code.
I tried the command: ":w" but it just write to the code, it can not save the code.
Thanks in advance for helping me.

---------- Post updated at 02:28 AM ---------- Previous update was at 02:02 AM ----------

Could I have another question here?
If I want to copy 19 lines in the fortran code (for example from line 1 to line 19) after using the command "vim" to read the code, what should I do?
Thank so much!

@Phamnu :
What you have to understand is :
when in vi or vim you have 2 main mode :

  • insertion mode (when you type your code)
  • command mode (when you want to tell vi/vim to do some specific actions, line jump, cursor move ...)
    With normal bindings, to switch to command mode, press <ESC>
    To switch to insert mode, you can use different command (i : insert where your cursor is, I insert at beginning of the line you are on, o, open a line under which you are, O open line above which you are.

a) <ESC> go to command mode
b) 1G go to first line
c) 19yy yank 19 lines including the line your cursor is on
d) nG go on the nth line under which you want to insert the lines
e) p paste the lines previously yanked.

1 Like

Silly question; are vi and vim one in the same?

Nope. vi = vi - Wikipedia, the free encyclopedia
vim = http://en.wikipedia.org/wiki/Vim\_\(text_editor\)

vim is of course based on vi but has more features and improvements - like syntax color highlighting. Stands for 'VI iMproved"

I don't have vim editor on my system can anyone suggest where can i find it and how to install it.

I have tried downloading few rpm's packages but it isn't working for me.