Tuesday, 26 March 2013

Awesome Vim


Best color scheme
xoria256


VIM Commands

Help

:h search-term - to get man page for that command,topic

:h user-manual - brings up entire user manual


Did u know?

  • The dot command lets us repeat the last change. It is the most powerful and versatile command in Vim.


  • From the moment we enter Insert mode until we return to Normal mode, everything we type (or delete) counts as a single change.


Buffer is the place in memory which stores the information we type in vim


Get quick reference for commands
:help quickref


Useful commands
:cd path - change the path of current directory
:pwd - print the current directory
:cd - - back to previous current directory
:ls - list all open buffers( aka file )
:b num - switch buffer to that file with number id
:e . - to navigate directory listing //opens vim default file navigator
:bn - Next buffer
:bp - switch to previous buffer
:b# - jumps to previous buffer also ctrl-6 does it
:%bd - close all opened buffer at once u can give ranges as 22,34bd to delete from 22 to  34
. - repeats last command
:f name - renames the files to given name
:set autochdir - Automatically use the current files directory as the  working directory

:vsplit filename - opens the file alongside current file by verticall dividing the screen
:split filename - opens file alongside current file by horizontally dividing the screen

:e %     prints the path of current file

Note
Make changes to your vimrc file and type :source path_to_vimrc/.vimrc  to reload settings changes u just did . This way your changes are reflected without having to restart vim


----------------------------------------------------------
Basic Movements
j - move down
k - move up
l - move right
h -  move left
$ - jumps to end of the line
^ - jumps to beginning i.e first non-space character  of the line
0 - jumps to real beginning of the line
gg - jumps to start of the file
G - jumps to end of the file
{ - jumps to prev paragraph
} -  jumps to next paragraph
--------------------------------------------------------


--------------------------------------------------------
Current Line Movements
w - move to beginig of next word              |
b - move to begining of prev word             |
e - move to end of next word                  |
ge -move to end of previous word               |
--------------------------------------------------------

--------------------------------------------------------
|   Treats words not seperated by space as single word                                                             
|   (but has delimeter like   _ - , . )   
|  W - moves to next  word                                      
|  B - moves to prev word                                       
--------------------------------------------------------




----------------------------------------------------------
Changing Case of word below cursor
Normal Mode                      | Visual Mode
g~ Swap case |   ~
gu Make lowercase |   u
gU Make uppercase     |   U
-----------------------------------------------------------


---------------------------------------------------------
Faster Movement inside window

 M - move the cursor to middle of visible area of vim window                                     
 L - move the  cursor to end of visible area of vim window                                            
 H - move the cursor to start of the visible area of vim window                                    
 zt - scrolls  the current window to show current line on top                                    
 zb -  scrolls the current window to show current line in bottom                  
 zz  -  scrolls the current window to shows current line in the middle
            
-----------------------------------------------------------



---------------------------------------------------------
Jumping Visible Screen

ctrl+u scroll half the screen upwords
ctrl+d scrolls half the screen downword
ctrl+b scrolls fullscreen backword
ctrl+f scrolls fullscreen forward

-----------------------------------------------------------



Incrementing and Decrementing number works left to righ
n<C-a> will find first numeric on current line and increment by n default is by 1

n<C-x> same but will decrement number by n defaults to 1


VIMP
`0 or ‘0 back-tick or single quote zero put the cursor on location where u last exicted in vim

NOTE
you can use repeater with almost every vim command. Syntax for using repeater is
n command - now command will be repeated n number of times


Joining Sentences
J - this will join the current line with one after it introducing a space also
gJ - same as J but will not put any spaces

Editing in visaul block mode  [Super useful]
ctrl-q activates visual block mode ,allowing you to select multiple columns
while in visual-block mode if you press I and enter text it will repeated for all columns

Directory Listing Commands(Vim default file navigator)
:e . - show directory list
gh -  hide or unhide dotfiles
d - make a directory
D - delete the file or directory
R - rename the directory or file
- - Go up a directory
s - Sorts by name, size, time


______________________________________________________
Quick Jumps in single line
Same Line (use :set ignorecase) to ignore case
fN -  Move forward to the next occurrence of character ‘N‘
tN - moves cursor before the word we are searching
FN -  moves in backword to occurence of N
TN - moves cursor before the word in backword direction
; - move to next occurence
, - previous occurence
___________________________________________________________

Vim remembers your jump points , to see where you have been press
cntrl + o - jumps forward
cntrl + i    -  jumps backwords  
gf         - jumps to file under cursor

Using Markers to move around
m : press it to activate markers
char : name of the register in which marker position will be stored
‘char : single quote followed by name of register will jump to  marked position

VISUAL MODE
v - character visual mode
V - visual line mode
gv - select previously selected block
o - toggle cursor to opposite corner of selection

VIMP
`. go to the position of the last edit in the file
`` go to the position before the last jump
MARKS

m{a-zA-Z} mark current position with mark {a-zA-Z}
Difference between single quote and back-tick while jumping to mark is that
single quote ex. ‘a  mark will put the cursor on line you marked
while back-tick ex. `a  will put your cursor on column of line where u marked

`{a-z} go to mark {a-z} within current file
`{A-Z} go to mark {A-Z} in any file
`{0-9} go to the position where Vim was previously exited
:marks print the active marks
% find the next brace, bracket, comment, or "#if"/

Undo changes
u -  to undo previous command
cntrl + r -  redo changes  


Insert
i   -  insert before cursor position
a -  insert after the cursor position
I   -  insert at begining of line (like ^i )
A -  insert at the end of line (like $a )
o - opens up a new line after cursor
O - opens up a new line before cursor
c movement - deletes according to movement command and puts you in insert mode
ex. to delete word press cw
s -  like xi i.e deletes current character and puts in insert mode
C - like c$ i.e delete to end of line and get in insert mode
S - like ^C i.e to  delete current line and places you in insert mode
~ - changes the character under the cursor to uppercase/lowercase

Press v and visually select the word/words and then press ~ to convert the visually selected text case.


Formating
N  <{motion}     move the lines that are moved over with {motion} one shiftwidth left
N  >{motion}     move the lines that are moved over with {motion} one shiftwidth right
N  >>    move N lines one shiftwidth right

N  <<    move N lines one shiftwidth left

ctrl-t,ctrl-d   Indent/un-indent in insert mode   



Replace
r - replaces the character below the cursor
R - replace more that one character





VIMP : EXTENT
you can specify extent in operator like change, delete, yank,visual to include the word inside or with delimeters

diw    can be read as delete inside word OR if ci’  means change inside single quote
da’ can be read as delete along with single quote or if daw delete along the word

ex.  “vim-*o” * is our cursor ,if i do ciw it will delete word inside single quote
but caw will delete quote also and put  in insert mode
ex. this is wor*d to delete
pressing diw will delete ‘wordbut maintain spaces
but daw will delete ‘word’ along with space

Note
This is very useful incase we want to delete word and our cursor is somewhere inside word
Extent will works with word
Word
sentence
paragraph
tag [like html]
{ ( [ “ ‘


Save and Exit
:q! -  quit without confirmation
:e! - restore the original file
:bd! - forcibly remove the buffer from buffer list discarding any changes
:wq -  save and quit
:w -  save the file
:bd -  close the current file window (a.k.a buffer)
:saveas FILENAME — this will save the file with your new name and continue editing it under the new filename.
:#,# w FILENAME — saves just text between line numbers that you specify.

Copy command
yy -  Yank line (copy)
Y - yank the current line


Delete
X - deletes single character before the cursor
x -  deletes single character
dw -  delete the word
dd - deletes the current line line
cc - deletes current line and puts you in insert modbe
ce       -  deletes the word and places you in Insert mode
d$ - delete from cursor position to end of line
d0 - delete from cursor to start of line

NOTE

i - for inside


Scenario : you cursor is inside a “ ” and u want to change entire word leaving the qoutes as is

ci” - deletes everything inside double quote works also for     ’ ” ( { [ and puts u in insert

mode


Scenario : your cursor is inside a “ ” and u want to change the word including “”

ca” - deletes everything  



Operator and motion

In d$
d  - is a delete operator,  c - is change operator
$ - is a motion command

other motion command used with delete operator
w -  moves cursor position to next word
e -  moves cursor to end of that of word

NOTE
Pressing motion commands in normal mode moves the cursor accordingly
$  - in normal mode will jump to end of line

Count with motion
0,1,2... can be combined with motion commands
2w - move cursor two words forward
3e - moves the cursor to end of the third word forward

Combining operator, count, motion commands
d2w - delete two words

Operation on line
dd - deletes a line
2dd - deletes two line

PUT command
p - puts previously deleted/yanked text after cursor. In an entire line was deleted paste it below the current line

P -  puts previously deleted/yanked text before cursor. In an entire line was deleted paste it above the current line


Search Commands


useful when searching text

set hls - (hlsearch)  this will set vim to highlight your search

Note  To remove the highlighting type :noh

set is - (incsearch)  this will set vim to highlight search as you type

set ic - (ignorecase)this will set vim to ignore case when searching


Type / to enter the word you want to search for and press enter when you finished typing the word .

Pressing ?word does search in backword
To search word in backword direction press ?
n to repeat last search by ? pr /
N to reverse last search

Useful for debugging
Type  %  to find a matching ),], or }

The cursor will move to the matching parenthesis or bracket.

Searching for word below cursor
* - will search the word in forward direction
# - will search the word in backword direction
Note
while search the word , its saved in / register
To paste the word u just searched while in insert mode type
ctrl-R / it will paste the searched word .to avoid pasting any angle bracket use g* and g#


Substitute Command
/g flag means for all occurrences in current line
/i  flag means ignore case while substituting

Type :s/old-word/new-word/g to substitute new-word in  all places of old-word in current line
:s/old-word/new-word/gc - will ask for confirmation before making the change.press y to make the change or n to escape it.

:%s/old-word/new-word/gc - % means search in the entire file for word and replace it
NOTE
To repeat the last substitution command press &
Executing external commands
Type :!command to execute an external command
ex.  :!ls - will list your directories in linux

Imp

:r FILENAME   - retrieves disk file FILENAME and puts it below the
     cursor position.

:r !dir   -  reads the output of the dir command and puts it below the
     cursor position.


Basic Settings to enable

:syntax enable   -  this will set vim to enable syntax highlighting
To manually specify the language
:set syntax=apache   - this will highlight using apache rules

 
Important Configuration File
In ubuntu these file are not created by default u can create it yourself

~/.vimrc - Most settings go here
~/.gvimrc - Graphic-only settings
~/.vim/ Plugins, language-specific options,
color schemes.

Set,Show and Reset

:set softtabstop=4      - set avalue
:set softtabstop? - show the value its set to
:set softtabstop& - Reset to default value

// use sts  instead softtabstop

:options     - show list of options available in vim



Indentation
= auto indents the code
You can use movements command to indent a specifice set of line
Ex. When ur on top of the file and press =G , all lines in the file will be indented


Working with windows
cntrl-w s - split window horizontally
cntrl-w v - split vertically
cntrl-w c - close window
cntrl-w w - cycle focus
cntrl-w o - close all but current
cntrl-w t - opens current window to new tab

working with window and buffers
:sbnum   - where num is buffer number .This command will open the the given buffer in horizontal split

:vert sbnum   - opens the buffer vertically

Shifting Window Position
cntrl-w J - moves current window down
cntrl-w K - moves current window up
llrly
cntrl-w H and cntrl-w L - moves current window to right and left

Opening multiple windows in one tab
cntrl-w + - increase window height by 1
cntrl-w = - equally divide the screen width and height between open windows
cntrl-w -   - decrease height by 1
cntrl-w _ - take maximum area to show current window
cntrl-w >          - increses the width by 1
cntrl-w < - decreases the width by 1  
ctrl-w x - exchange current window with the neighbouring window

MACROS AND REGISTERS
q - Initiate macro recording by pressing it
Note
immediately type any single character (like ‘a’ ) that will become name of register in which  latest command you typed during the recording will be stored

Note
When you start recording it records every keystroke, makes note of modes u enter

:registers - gives entire list of registers with what they  contain

q - after staring it if you press it again it will end macro recording


@register_name  -  to execute the register in which you just stored your  commands during
macro recording

@@ - repeates the last macro that was executed

In can be used it with repeators
n@@register_name - will execute the register n number of times

Printing the contents of register
“ap -print the contents of register a


FOLD METHOD
Choosing a folding technique
set foldmethod=manual    manual folding
set foldmethod=indent    folding by indent
set foldmethod=syntax    folding by syntax regions   // set it in your vimrc

  zf{motion}    operator: Define a fold manually
  :{range}fold    define a fold for {range} lines  //visually select lines and fold them
 
zd    delete one fold under the cursor
zD    delete all folds under the cursor

zo    open one fold under the cursor
zO    open all folds under the cursor
  zc    close one fold under the cursor
zC    close all folds under the cursor

zm    fold more: decrease 'foldlevel'
  zr    reduce folding: increase 'foldlevel'
  zn    fold none: reset 'foldenable'
  zN    fold normal set 'foldenable'
  zi    invert 'foldenable'

Use fdm short for foldmethod
set fdm=marker
set foldmarker={{{,}}}     ‘ this will tell vim to find {{{ marker in entire file and fold accordingly

REGISTERS
Default is the unnamed register ie “” double quote double quote
Eight types of registers
48 total registers
Delete,change,substitute, search or yank to any register
Yank registers
“a use register a
yy copy the current line
“ap paste from register a 
“0                 holds the last yanked text
“+ system clipboard
“+y copy to system clipboard
“+p paste inside vim from system clipboard


Tabs

:tabnew - opens a new tab with an empty buffer.
:tabnew - filename opens the filename in a new tab.
vim -p file1 file2 file3  - Opens the files in three different tabs.
gt - move between tabs. 2gt moves you to the 2nd open tab.
gT - moves to prev opened tab
qa - closes all the open tabs without saving them.
wqa - closes all the open tabs with saving them.
:tabdo %s/foo/bar/g Execute a command in all tabs
:tab ball Puts all open files in tabs

Abbreviations
:ab mail mail@provider.org Define mail as abbreviation of
mail@provider.org

In normal mode gv is used to select previously selected line in visual mode


Vim automatically marks begining of an edit /paste
`[  marks the begining of new text
`] marks end of the new text

vim tracks changes to file and to store position in  changelist
To go to latest changes g;
To go forward in list g,
To see all changes in files :changes

vim keeps tracks of jumps in list called jumplist
jump commands are
   -   /pattern ie searching
   - n and N  
   - substitute :s/foo/bar
   - % jumping between paranthesis
   - { jumping through paragraphs
   - ( jumping through sentences
   - G and gg
   - H M L ie jumps to current position in window
ctrl-o  like back button
ctrl-i  like forward
:jumps  shows all jumps

Navigating through vim helps pages . Press ctrl-] to jumps to highlighted word detail page

q/ show the widow containing history of prev searches
q: show the window containing history of latest commands

while type in commandline  if u want to open the command window
use ctrl-f this will open the window with text you typed !

Tabs and Spaces
The command for converting between tabs and spaces is:

:retab!
More specifically, to convert tabs to spaces, run:

:set expandtab
:retab!
And to convert spaces to tabs, run:

:set noexpandtab
:retab!
Selecting columns
select blocks (columns)                  CTRL  + q

auto-complete a word you are typing **   CTRL + n
use ctrl-n and ctrl-p to navigate the suggesstion
Spell Checking
:set spell              to activate spell checking mode

]s jumps to next mis-spelled word
[s        jumps to previous mis-spelled word
z= display suggestion
1z=      select first suggestion

:windo set spelllang=en_gb       this set the region to british and find errors accordingly
:set spelllang=en_us this will set the buffer to match errors based on US english

zg To add words to spell file
zw to add bad words
zuw this will remove it as bad word
zug this will remove words from spell file
:runtime spell/cleanadd.vim this will reset spell to original . Will remove all user added words

Plugins I use for development

-----------------------------------------------------------------------------------------------------------
CTRLP - Easily search files present in current dir,mru (most recent used or from buffer list

Press F5 to get new files changes

ctrl-p      activate ctrlP plugin


ctrl-j     move up search result

ctrl-k    move down search result




ctrl-o[v/h/r/t]        - open file
v - in vertical split

h - in horizontal split
r - replace current buffer
t - open file in new tab

Opening multiple files

ctrl-z     lets u mark/unmark multiple file to open in  
vsplit

ctrl-o    open all files marked using ctrl-z


Switch between modes using ctrl-f

Pressing enter on filename will replace current window
-----------------------------------------------------------

-----------------------------------------------------------
TagBar
Display tags - Gives a list of method name, variable and scope in a neat way
Support lot of language including javascript

Pressing enter on tags jumps u to source file where it is defined

:TagbarToggle to toggle tagbar window
-----------------------------------------------------------------------------------------------------

------------------------------------------------------------
NeoComplCache
neocomplcache provides keyword completion system by maintaining a cache of keywords in the current buffer

---------------------------------------------------------------------------------------------------



------------------------------------------------------------
GUNDO.vim
This plugins keeps a tree structure of undo done in file
:GundoToggle this is used to toggle undo window.Its divided into two screen the first the tree of undo. on putting cursor on node the below window shows the edit made by you

Pressing enter on node brings the file to that state
---------------------------------------------------------------------------------------------------






-----------------------------------------------------
NerdTree Plugin(Awesome file navigator)

TO open file listed in nerdtree press enter or o key


? shows help


s  Open selected file in a new vsplit
B  Toggle whether the bookmark table is displayed
D  Delete the current bookmark



:Bookmark <name>
   Bookmark the current node as <name>. If there is already a <name> bookmark, it is overwritten. <name> must not contain spaces.
   If <name> is not provided, it defaults to the file or directory name.
--------------------------------------------------------

--------------------------------------------------------


TComment
<c-_><c-_> Comments current line
Visually select the region press <c-_><c-_> to comment them
------------------------------------------------------------------------------------------------------------------------


---------------------------------------------------------------------------------------------------------
TABULARIZE PLUGIN
Its helpful for intentation of certain block of line

:Tabularize /= will align all text properly using the delimeter =
:Tabularize /:\zs lines will be aligned while leaving the colon together
---------------------------------------------------------

--------------------------------------------------------------------------------------------------------
BufferExplorer
To open buffer explorer use :BufExplorer
d close file buffer
q close buffer file explorer
s reorder file listing by switching to diff mode like  
mru extension

o /
enter Opens buffer under cursor in current window

----------------------------------------------------------

----------------------------------------------------------
EasyMotion Plugin
I have set my leader key as single quote
Press <leader><leader> followed by below words
Following works in same way as movement commandvr
w   -  marks all beginning of words following the cursor as jump points
b    -  marks beginning of words before cursor as jump points
e    -  marks end of words in forward direction
ge  -  marks all jump points before cursor
k before cursor shows marks in first  column to jump
j      shows marks for Line downward.
n      Jump to latest "/" or "?" forward.
N      Jump to latest "/" or "?" backward.
-----------------------------------------------------------------




--------------------------------------------------------
SPARKUP plugin
Sparkup plugin is very useful to write html

just type div and press ctrl-e it will expand it to <div></div>

Create multiple div by typing div*4
Giving properties to html element we will create by
a [href=#] {some link}   this will expand to <a href=’#’>some link</a>

To create child elements use > to create a siblings element use <
Note to keep creating sibling elements use +
div >ul <+div[class=wo] >li {some text}
will expand to
<div>
<ul>
<li>some text</li>
</ul>
</div>
<div class=”wo”>
</div>
--------------------------------------------------------



----------------------------------------------------------
Surround plugin(simplifies surrounding text with tags)
(To support repetition using dot operator download repeat.vim plugin)
To surround a word select it visually then type <Shift-s> followed by tag

To change ‘vim’ single quote to double quote place cursor inside single quote and type cs’
or cst (read as - change the surrounding tag)

To delete the surrounding tag type ds’ or dst    (read as -delete the surrounding tag)

In normal mode to surround a word use ysw(  it will surround it with paranthesis)
--------------------------------------------------------



------------------------------------------------------------
Fugitive.vim
Rather than going to command line to fire git command you can issue those command straight from Vim using Fugitive.
Its also provides shorthand for common tasks
:Gwrite Adds the current file to index for commiting
:Gread Reverts the file to last checkout state
:Gremove Deletes the file from git and the buffer is closed
:Gmove Rename the current file and correspoding vim
buffer
:Gcommit opens up a commit window
:Gblame command opens a vertically split showing history of commits
:Gstatus opens a buffer showing status of repo
- stages the file
However if its already staged it will remove it
:Git add . - automatically adds all files
:Gdiff - shows the changes done on file

---------------------------------------------------------------------------------------------------




Web resource
  1. http://www.thegeekstuff.com/tag/vi-vim-tips-and-tricks/page/3/