Vi

From MusiKiwi

Jump to: navigation, search

Vim notes, tips, and tricks. These notes apply mostly to vim and not vi.

Contents

CHEAT SHEETS

http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html

Copy/Paste registers, macros, navigation marks:

http://mkaz.com/solog/system/vim-cheat-sheet.html

Basic outline from StackOverflow:

http://stackoverflow.com/questions/5400806/what-are-the-most-used-vim-commands-keypresses

Making Vim more useful

http://stevelosh.com/blog/2010/09/coming-home-to-vim/#making-vim-more-useful

How to get TextMate's best features in Vim

http://tech.myemma.com/textmates-features-vim/

Movement Shortcuts Wallpaper

http://naleid.com/blog/2010/10/04/vim-movement-shortcuts-wallpaper

BASICS

Exit Edit Mode

insert (at cursor):		i
exit insert mode: ESC, ctrl+c, ctrl+[

(replace ii sequences with ESC to exit insert mode):
imap ii <esc>	
imap ii <esc>l (exit insert mode, move cursor right one)

Cursor Movement

up:	k
left:	h
right: 	l
down:	j

end of file:	G (shift+g)
beg of file:	g+g
cursor location (file status): ctrl+g
move to line: <number>+G (ex: 488G)

SCROLLING

ctrl+b	scroll backward (up) full page
ctrl+f	scroll forward (down) full page
ctrl+u	scroll up 1/2 page
ctrl+d	scroll down 1/2 page
ctrl+e	scroll up one line
ctrl+y	scroll down one line

zz		scroll so spot where cursor is becomes middle of window
zt		scroll so spot where cursor is is top of window
zb		scroll so spot where cursor is is bottom of window

MOTIONS

end of line:			$
beg of line:			0 (zero)
next word:			w
previous word:			b
end of next word:		e
end of previous word:	ge
	2w	- two words forward
	3e	- end of third word

fx		"find" x on current line & jump to it

Deleting

delete character:	x
delete word:		d+w  (a word is surrounded by spaces)
	(d+w deletes the rest of word starting at cursor)
delete 2 words:	d2w
delete line:		d+d
delete rest of line:	d+$
delete 5 lines:	5+d+d

Undo

undo:	u
undo (all changes on current line): 	U
redo:	ctrl+r

COPY/PASTE (PUT)

dd:	delete line and put in vim register
p:	puts line BELOW cursor
v: 	visual mode, used to highlight text
		(can use regular hjkl to move around)
y:	once text is highlighted, press y to yank (copy)
p:	put (place) text

yw:	yank one word
	(y can be used as an operator)

REPLACE

rx:	replace character at cursor with x
R:	enter 'REPLACE' mode (overtype mode)
		(contrast w/ insert mode)

CHANGE OPERATOR c:

c [number] motion
ce: 	delete rest of word, enter insert mode
c$:	delete rest of line, enter insert mode
	motion = {e, w, $}

SEARCH

/	search forward
?	search backward
n	repeat search
N	repeat search, opposite direction
ctrl+o	go back to where you came from (?)
ctrl+i	goes forward
:set ic		ignore case for searching
:set noic		stop ignoring case for searching
\c		ignore case for one search
		ex.: /Search\c (finds search,Search,SEARCH)

/[^\x00-\x7F]    find all non-printable ascii characters

PARENTHESES MATCHING

   %	

SUBSTITUTE (find & replace)

:s/old/new		(first occurrence on line)
:s/old/new/g		(all occurrence on line)
:#,#s/old/new/g	(substitute phrases between two line #'s)
:%s/old/new/g		(all occurrences in FILE)
:%s/old/new/gc		(ask for confirmation each time add 'c')

EXTERNAL COMMAND

:!ls		list files (enter to get back to vi)
:!bash	temp command shell (exit, enter to get back to vi)

SAVING (WRITING) FILES

:w   or :write
:w filename
To save selected text to a file:
1.	v	(enter visual mode)
2.	move cursor down to highlight text to save (using normal mode commands)
3.	type : (at bottom, :'<,'> appears)
4.	type w filename	(saves selection as filename)

:saveas filename	save current file as filename

:edit filename		closes current file, opens filename
:edit! filename	force close (no save) current file, open

BUFFERS

:hide edit newfile	opens file 
:buffers	see list of open buffers
:next	move to next buffer (must save first)
:previous	move to next buffer
:bnext	go to next buffer
:bdelete 2 	remove buffer number 2

FILE NAVIGATION, BROWSING

:Explore	browse the files in current directory
:pwd		print working directory
:cd		change directory
:cd -	go to last directory used

RETRIEVING contents of a file

:r filename		(insert contents of file at cursor)
:r !<command>		insert output of command at cursor
:r !ls			puts output of ls at cursor

WINDOWS

(using new windows, splitting current file)
:split		views file in split mode at cursor pos
ctrl+w+w		moves between windows 
		(same as ctrl+w + ctrl+w)
:close		closes the current window

VISUAL MODE

Used to select...

aw	a word
iw	inner word
as	a sentence
is	inner sentence
ap	a paragraph
ip	inner paragraph
ab	a block (marked by parentheses)
ib	inner block (contents inside parentheses)
aB/iB
a'	a single quoted string
a"	a double quoted string
i'/i" inner single/double quoted string

HELP

For tutorial, type vimtutor on command line.

:help E37			look up error E37

INDENTING

Indent multiple lines quickly:

http://stackoverflow.com/questions/235839/how-do-i-indent-multiple-lines-quickly-in-vi?rq=1

:set shiftwidth=3
:set autoindent
:set tabstop=3
:set expandtab expand tabs into spaces when typing
:retab convert existing tabs to current tab settings
 <nowiki>

=== BLOCK EDITING: block comment ===
 <nowiki>
This is for vim only; vi won't do this
1. ctrl+v
2. highlight column strip (hjkl)
3. ctrl+I (capital I)
4. type #_, only first line will change
5. press ESC (ctrl+c won't work)

VISUAL LINE
shift+V

REFLOW TEXT TO COLUMN WIDTH

The gq command takes comments and indentation into account. I normally use V to visually select the lines (with k and j) and then press gq. The textwidth option is used to format the lines at the appropriate length. See :help gq for more information. -- SO

HIGHLIGHT COLUMN 80

http://stackoverflow.com/questions/235439/vim-80-column-layout-concerns

PASTING INTO A VIM WINDOW

To prevent text from indenting on each line when pasting into a vi window:

set pastetoggle=<F12>

1. enter insert mode 2. press F12 3. right click->paste

Paste Toggle

Colors

  • syntax on, syntax off: color syntax hilighting
  • colorscheme default: switch default color scheme
  • colo <tab> : cycle through color schemes
  • colo <ctrl+d> : list all color schemes
  • colortest script

http://www.vim.org/scripts/script.php?script_id=1349


Solarized Color Scheme

http://ethanschoonover.com/solarized

   git clone git://github.com/altercation/solarized.git

Change the console (terminal editor) colors:

   git clone https://github.com/phiggins/konsole-colors-solarized.git
   cp *.colorscheme ~/.kde/share/apps/konsole/.
  1. Copy the colorscheme files to ~/.kde4/share/apps/konsole/. On your system this may be ~/.kde/ instead of ~/.kde4/.
  2. Open Konsole and select Settings -> Manage Profiles -> Edit Profile -> Appearance, then select either of the Solarized themes.
  3. Click OK, then close, and the Solarized settings should have taken effect.

Highlight trailing whitespace

In the vimrc file, place the following:

   :highlight ExtraWhitespace ctermbg=red guibg=red
   :match ExtraWhitespace /\s\+$/

To find trailing whitespace, use:

   /\s\+$

Fonts

Monaco font:

   wget http://usystem.googlecode.com/files/MONACO.TTF

CentOS: chkfontpath must be installed, so do this http://blog.whatgeek.com.pt/2011/11/10/install-core-fonts-centos-6/

Linux install instructions: http://blog.mayfounder.net/2009/02/10/adding-a-new-ttf-font-to-linux/

or maybe here: http://tacticalvim.wordpress.com/2010/01/17/installing-fonts-in-your-home-directory-on-fedora-12/

Some of the rpms can be found here

   http://dl.atrpms.net/el6-i386/atrpms/stable/
   wget http://dl.atrpms.net/el6-x86_64/atrpms/stable/chkfontpath-1.10.1-2.el6.x86_64.rpm

Konsole

Edit the Shell.profile file to change the font:

   ~/.kde/share/apps/konsole

Preferences

cd ~
mkdir .vim

mkdir .vim/autoload
mkdir .vim/bundle
mkdir .vim/colors

vi .vimrc

Line numbers

  :set number
  :set nu!

Relative line numbers: use 12k to jump up 12 lines.

Hybrid line number mode: http://jeffkreeftmeijer.com/2013/vims-new-hybrid-line-number-mode/

Status bar

SHOW STATUS BAR AT ALL TIMES:
-----------------------------
set viminfo='20,\"500
* doesn't show status if only one window; shows if 2 windows
	:h 'laststatus'
	2 -> always
set laststatus=2  " always show status bar

See the #powerline plugin for a visually appealing status line.

Tabs

http://vim.wikia.com/wiki/Using_tab_pages

Creating

  :tabnew
  :tabclose
  :tabonly -- close all other tabs
  :tab split -- copy current window to a new tab of its own
  
  :tab ball -- show each buffer in a tab (up to 'tabpagemax' tabs)

Opening & Closing Tabs

:tabe[dit] {file}   # open filename in a new tab
:ctrl-W T           # move current split window into its own tab
:q                  # close window, closing tab if it contains a single window
:tabc[lose]         # close current tab and all windows inside of it
:tabclose {i}       # close i-th tab
:tabo[nly]          # close all tabs apart from current one
:tabfind   {file}   # open a new tab w/ filename, searching vim's 'path'

.vimrc

   :set path=.,,**  # search current file (.), current directory (empty text between ,,) then each dir under current directory (**)

Switching tabs

   gt            # move to next tab
   gT            # move to previous tab
   #gt           # move to tab number #
   (edit mode)
       gt   " go to next tab
       gT   " go through tabs backwards
       #gt  " go to n'th tab
       4gt  " fourth tab

Moving tabs

   :tabmove -- move current tab to end
   :tabmove 0 -- move current tab to beginning
   :tabmove 1 -- move cuurent tab AFTER tab 1


.vimrc

# D == command (mac)
# C == control (win/linux)
# S == shift key
# replace 'D' with 'C' for win/linux
	
# move to neighboring tabs
map <D-S-]> gt    " command+] (mac only)
map <D-S-[> gT    " command+[ (mac only)
	
# jump to n'th tab using command+1, command+2, etc.
map <D-1> 1gt     " (mac)
map <D-2> 2gt
...
map <D-0> :tablast<CR>    " jump to last tab

map <C-S-]> gt
map <C-S-[> gT
map <C-1> 1gt
map <C-2> 2gt
map <C-3> 3gt
map <C-4> 4gt
map <C-5> 5gt
map <C-6> 6gt
map <C-7> 7gt
map <C-8> 8gt
map <C-9> 9gt
map <C-0> :tablast<CR>

Plugins

Vim plugins. http://www.vim.org/

This vim distribution has a list of essential built-in plug-ins: http://vim.spf13.com/

Janus, another vim distribution: https://github.com/carlhuda/janus

Linux Lefty's list of essential plug-ins: http://linuxlefty.com/tools/favorite-vim-plugins-vi-gvim.html

Turning vim into a (Python) IDE http://sontek.net/blog/detail/turning-vim-into-a-modern-python-ide

pathogen

Manage vim plugins using git repositories.

http://www.vim.org/scripts/script.php?script_id=2332

   wget https://github.com/tpope/vim-pathogen/blob/master/autoload/pathogen.vim
   cd .vim
   git clone http://github.com/tpope/vim-pathogen
   cp -r vim-pathogen/autoload .

The 'README.markdown' has a Runtime Path Manipulation section that you should add to .vimrc.

Edit .vimrc:

   call pathogen#infect()
   syntax on
   filetype plugin indent on

Now create a default directory that pathogen uses:

   cd .vim
   mkdir bundle

powerline

Eye-candy status bar.

http://www.vim.org/scripts/script.php?script_id=3881

If the powerline plugin is installed, install the plugin:

   cd .vim/bundle
   git clone https://github.com/Lokaltog/vim-powerline

NERDtree

http://www.vim.org/scripts/script.php?script_id=1658

   git clone https://github.com/scrooloose/nerdtree.git

Code Completion

omni completion: http://vim.wikia.com/wiki/VimTip1608

snipmate: https://github.com/msanders/snipmate.vim

UltiSnips: http://www.vim.org/scripts/script.php?script_id=2715

YouCompleteMe: http://valloric.github.io/YouCompleteMe/

   git clone https://github.com/Valloric/YouCompleteMe.git

Discussion of autocompletion on StackOverflow:

http://stackoverflow.com/questions/1115876/autocompletion-in-vim

TagList

Source code browser. Uses Ctags. Provides an overview of the structure of source code files. http://vim-taglist.sourceforge.net/index.html

c.vim C/C++ IDE

Easily add code snippets, C-idioms, and comments.

http://vim.sourceforge.net/scripts/script.php?script_id=213

vimwiki

http://vim.sourceforge.net/scripts/script.php?script_id=2226

Navigating Code

CommandT -- finding files in a codebase (fuzzy matching on filenames)

   git clone https://github.com/wincent/Command-T
   git clone https://github.com/wincent/Command-T.git

To compile vim with Ruby support:

http://arjanvandergaag.nl/blog/compiling-vim-with-ruby-support.html

or

http://kzhiwei.wordpress.com/2011/09/21/centosrpmbuild-ing-vim-w-ruby-support/

or

http://sudoers-d.com/blog/2013/01/18/installing-vim-on-centos-6-dot-3/

LustyExplorerer -- does a few things, incl. buffer grep (searching through open buffers)

ack.vim -- search for content inside of source files

   git clone https://github.com/mileszs/ack.vim.git

CtrlP

Fuzzy file name search. vim only alternative to CommandT.

If compiling CommandT complains about 'unable to load C library' (or similar), this might be due to the fact that the version of Ruby used to compile vim is not the same as the version of Ruby used to compile the extension. An alternative to CommandT is CtrlP:

   git clone https://github.com/kien/ctrlp.vim.git

YankRing

Maintain history of previous yanks, changes and deletes

http://www.vim.org/scripts/script.php?script_id=1234

See also: Yank Stack, GUndo

Ranbow Parenthesis

http://www.vim.org/scripts/script.php?script_id=1561

   git clone https://github.com/kien/rainbow_parentheses.vim

vim-indent-guides

https://github.com/nathanaelkane/vim-indent-guides

MiniBufExpl

Explore buffers via tabs.

https://github.com/fholgado/minibufexpl.vim

Syntax Checking

syntastic

https://github.com/scrooloose/syntastic

Conque

Run Bash shell, MySQL client, etc. from inside vim:

   git clone https://github.com/chilicuil/conque ~/.vim/bundles/conque

vim-multiple-cursors

Sublme Text style multiple selections for Vim.

   git clone https://github.com/terryma/vim-multiple-cursors.git

Surround

Delete, change, and add text between surrounding [] {} ().

   git clone https://github.com/tpope/vim-surround.git

Easy Motion

Move around documents easier.

   git clone https://github.com/Lokaltog/vim-easymotion.git

See also: stupid easy motion

Annoyances

Keep a quick list of things that bother you here; research them later.

  • Trace how vim is loading plugins and settings files
   strace -o vim_strace vim
  • List of scripts/plugins that were loaded according to vim:
   :scriptnames 
  • tmux + vim:

https://github.com/seebi/tmux-colors-solarized

  • auto word wrap
  • solarized color scheme (http://ethanschoonover.com/solarized)
  • how do you quickly indent a block of text?
  • what are ALL of vim's single letter commands (upper case, lower case letters, symbols)
  • why doesn't :h E37 provide help?
  • create file from w/in vim

Manage multiple vim configurations:

http://www.linuxjournal.com/content/manage-your-configs-vcsh

Move efficiently on the command line:

http://www.linuxjournal.com/content/time-saving-tricks-command-line?page=0,0

HOW TO EXTEND PARTITION

http://www.sevenforums.com/virtualization/219697-how-resize-virtual-hard-disk-virtualbox.html

http://www.webdesignblog.asia/software/linux-software/resize-virtualbox-disk-image-manipulate-vdi/#sthash.Mj7ZQ50k.dpbs

lvextend -L${1}G /dev/vg-db-sda/set.1._usr
resize2fs /dev/vg-db-sda/set.1._usr

# Stop NetworkManager
sudo /sbin/service NetworkManager stop
# Disable it from starting at boot time
sudo /sbin/chkconfig NetworkManager off

TODO: set up separate vim settings page.

Ultimate Vim configuration: http://amix.dk/vim/vimrc.html

" === PATHOGEN (plugin) OPTIONS ================================
execute pathogen#infect()
call pathogen#incubate()
call pathogen#helptags()

filetype plugin indent on   " must be called after pathogen options

"=== LOOK & FEEL ===============================================
"solarized color scheme (http://ethanschoonover.com/solarized)
syntax enable
set background=dark
colorscheme solarized

set t_Co=256  " where is this needed?


" === GENERAL OPTIONS ==========================================
"set t_Co=256
set shiftwidth=4    " Shift commands (> and < to motion) indent by 4 spaces.
set cindent         " Auto-indent mode understands most TMM indentation styles.
"set tw=76           " Auto-wrap a bit before column 80.
set expandtab       " Expand tabs to spaces.
set softtabstop=4   " Use soft tabs, indenting at 4 spaces.
set number
" colorscheme torte
syntax on
imap ii <esc>l        " avoid the ESC key (quickly tap 'i' twice to exit INSERT mode)
set pastetoggle=<F12> " prevent text from indenting on each line when pasting into a vi window
" set mouse=a           " enable mouse (resize windows, highlight text, switch between windows, etc.)


"=== STATUS BAR ================================================
" set viminfo='20,\"500  " what does this do?
set laststatus=2

" === TABS =====================================================
" move to neighboring tabs
"map <C-S-]> gt
"map <C-S-[> gT
map <C-l> :tabn<CR>
map <C-h> :tabp<CR>
map <C-n> :tabnew<CR>

" move to i-th tab
map <C-1> 1gt
map <C-2> 2gt
map <C-3> 3gt
map <C-4> 4gt
map <C-5> 5gt
map <C-6> 6gt
map <C-7> 7gt
map <C-8> 8gt
map <C-9> 9gt
" move to last tab
map <C-0> :tablast<CR>


" === CTAGS ====================================================
set tags=./tags;,tags;


syntax enable
set number
set hlsearch
set incsearch
set nocp
set autoindent
set expandtab
set shiftwidth=4
set softtabstop=4
setlocal spelllang=en_us

call pathogen#runtime_append_all_bundles()
call pathogen#helptags()
let g:ctrlp_working_path_mode = 0
let g:ctrlp_by_filename = 1
let g:ctrlp_regexp_search = 1
let g:ctrlp_use_caching = 1
let g:CommandTMaxFiles=100000

" Enable file type detection
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on

let mapleader = ","

nmap <leader>n :NERDTreeToggle<Enter>
nmap <leader>N :LustyFilesystemExplorer<Enter>
nmap <leader>/ :LustyBufferGrep<Enter>
nmap <leader>b :LustyBufferExplorer<Enter>
nmap <leader>d :w !diff % -<CR>
nmap <leader>T :CommandTFlush<CR>

"Case insensitive search
set ic

" Gui stuff
if has("gui_running")
	set lines=150 columns=230    "Maximize gvim window
	
	set guioptions-=T " Get rid of the toolbar
	set guioptions-=e " Get rid of the GUI tabs
	set guioptions-=r " Get rid of the right scrollbar
	set guioptions-=R " Get rid of the right scrollbar
	set guioptions-=l " Get rid of the left scrollbar
	set guioptions-=L " Get rid of the left scrollbar
	set guioptions-=b " Get rid of the bottom scrollbar
endif

:set backspace=indent,eol,start

" --- command completion ---
set wildmenu             " hitting TAB in command mode will
set wildchar=<TAB>       " show possible completions
set wildmode=list:longest
set wildignore+=*.DS_STORE,*.db

" -- remove sound effects
set noerrorbells
set visualbell

"--- backup and swap files ---
" I save all the time, those are annoying and unnecessary...
set nobackup
set nowritebackup
set noswapfile

" hitting jj will jump out of insert mode
inoremap jj <esc>

" quick vertical split
noremap <leader>v :vsp<CR><C-w><C-w>

" Quickly get rid of highlighting
noremap <leader>h :noh<CR>

" Make j and k work normally for soft wrapped lines
noremap <buffer> j gj
noremap <buffer> k gk

" Make the arrow keys work like TextMate in insert mode
inoremap <down> <C-C>gja
inoremap <up> <C-C>gka

" https://github.com/mileszs/ack.vim
let g:ackprg="ack-grep -H --nocolor --nogroup --column"

" open a new tab and search for something
nmap <leader>a :tab split<CR>:Ack ""<Left>

" immediately search for the word under the cursor in a new tab
nmap <leader>A :tab split<CR>:Ack <C-r><C-w><CR>

" Fix vim's ridiculous line wrapping model
set ww=<,>,[,],h,l

noremap <C-H> :tabp<CR>
noremap <C-L> :tabn<CR>
noremap <C-J> :tabc<CR>
noremap <C-K> :tabe<CR>

" Open the current buffer in a new tab
noremap <leader>z :tab split<CR>


Current Vim Settings


" === PATHOGEN (plugin) OPTIONS ================================
execute pathogen#infect()
call pathogen#incubate()
call pathogen#helptags()

filetype plugin indent on   " must be called after pathogen options

"=== LOOK & FEEL ===============================================
"solarized color scheme (http://ethanschoonover.com/solarized)
syntax enable
set background=dark
colorscheme solarized

set t_Co=256  " where is this needed?


" === GENERAL OPTIONS ==========================================
"set t_Co=256
set shiftwidth=4    " Shift commands (> and < to motion) indent by 4 spaces.
set cindent         " Auto-indent mode understands most TMM indentation styles.
"set tw=76           " Auto-wrap a bit before column 80.
set expandtab       " Expand tabs to spaces.
set softtabstop=4   " Use soft tabs, indenting at 4 spaces.
set number
set autoindent
" colorscheme torte
syntax on
imap ii <esc>l        " avoid the ESC key (quickly tap 'i' twice to exit INSERT mode)
set pastetoggle=<F12> " prevent text from indenting on each line when pasting into a vi window
" set mouse=a           " enable mouse (resize windows, highlight text, switch between windows, etc.)


"=== STATUS BAR ================================================
" set viminfo='20,\"500  " what does this do?
set laststatus=2

"=== LEADER ====================================================
let mapleader = ","
" open a new tab and search for something
nmap <leader>a :tab split<CR>:Ack ""<Left>
" immediately search for the word under the cursor in a new tab
nmap <leader>A :tab split<CR>:Ack <C-r><C-w><CR>
nmap <leader>n :NERDTreeToggle<Enter>
nmap <leader>T :CommandTFlush<CR>

let g:CommandTMaxFiles=100000

" === TABS =====================================================
" move to neighboring tabs
"map <C-S-]> gt
"map <C-S-[> gT
map <C-l> :tabn<CR>
map <C-h> :tabp<CR>
map <C-n> :tabnew<CR>

" move to i-th tab
map <C-1> 1gt
map <C-2> 2gt
map <C-3> 3gt
map <C-4> 4gt
map <C-5> 5gt
map <C-6> 6gt
map <C-7> 7gt
map <C-8> 8gt
map <C-9> 9gt
" move to last tab
map <C-0> :tablast<CR>



" === CTAGS ====================================================
set tags=./tags;,tags;

" highlight trailing whitespace
:highlight ExtraWhitespace ctermbg=red guibg=red
:match ExtraWhitespace /\\s\\+$/

" === Add blank lines above/below in normal mode
:nnoremap <silent> [<space> :pu! _<cr>:']+1<cr>
:nnoremap <silent> ]<space> :pu _<cr>:'[-1<cr>



Personal tools