Vim
# All About Vim
# . . .
# Okay, all the Vimming we can do in 60-ish minutes!
### What is Vim
* Editor for creating and modifying text (eg programs)
* Provides many features for programmers: syntax coloring, access to compiler
* Vim = Vi Improved
* vi = visual in ex - BSD Unix - 1976 - Bill Joy
* ex was a popular unix editor (line oriented)
* Vim 1.14 - 1991 - Bram Moollenaar
* Vim 6 - 9/2001: Folding, plugins
* Vim 7 - 5/2006: Spell check, completion, tabs, undo branch
* Vim 8 - 9/2016: Asynch
* Vim 8.1 - 5/2018: Terminal window
### Why Vim
* Fast:
* Fingers stay on keys: mouse not used
* Powerful commands, minimal keystrokes
* Swap characters and lines: xp, ddp
* Movement - mark, move, return: 0, $, ma, 1G, gg, 'a
* cit: changes inside this tag)
* da: ( deletes these parens and their contents)
* Column operations
* Ubiquitous: Available on many, many systems
* Use same environment for programming in any language
* Highly configurable:
* Example: search for smartcase and Smartcase. Again: smartcase Smartcase
* Extensible: scripting language built in, can also use perl, python, ruby
* See scrollbar in statusline
* Lots of Fun!
# Getting Started with Vim
## Installing, Running, Exiting, Vim Tutor
### Installing Vim
* Installer from vim.org
* Probably already in Linux distribution
* Windows Tip: Choose option to add Edit with Vim to right mouse menu
* Windows Tip: Choose option to add vim to path
### Running Vim
* Running GUI version from desktop: Press vim icon
* Running GUI version from command line: gvim filename
* Running console version from command line: vim filename
## Important: How to Exit Vim"
* :[w]q[!]
* To exit and abandon changes :q! ENTER
* Or, :q ENTER if no changes to abandon
* To exit and save changes :wq ENTER
* May need to get out of input mode first by pressing Esc
### Learn on Your Own with Vim Tutor
* Vim tutor teaches basics, by editing the vim tutor file
* Comes with vim
* Run from command line or icon
* Suggestion: Pick a few commands, learn more as needed
* Remember: Gets easier!! (Muscle memory and snowball!)
### Commands in Vim Tutor
* hjkl, :q!, x, i, esc, A, wq
* [modes, status line, case sensitive, muscle memory]
* de, dw, d$, d motion, count motion, d number motion, dd, u, U, ^r
* Motion: w, e, $
* p, r, ce, cw, c$, c count motion, esc
* ^G, G, gg, number G, /, ?, n, N, ^o, ^i, %,
* :s/old/new/, :s/o/n/g, :#,#s/o/n/g, :%s/o/n/g, :%s/o/n/gc
* :!, :!ls, :w fname, v move :w fname, :r fname, :r !ls
* o, O, esc, a, R, v move y, yw
* :set ic, hlsearch, incsearch, hls, is, noic, /foo\c
* , :help, ^W^W, :q, vimrc, :anything^D,
## Modes, Input, Replace, Undo
### Modes
* Mode determines meaning of keys
* Vim uses modes : Most common are Normal and Input
* Normal mode: Move around or change file
* Example: typing G moves to bottom, x deletes a character
* Input mode: typing enters text
* Example: typing G and x enters those characters
* Changing modes
* i: regular mode to insert mode (or a, A, r, R, cw, cc, C, ...)
* Esc: insert mode to regular mode
* :imap kj
* Comand mode: : vim command line. Exit with esc or enter or ctrl-c
* Visual mode: Mark and operate on chunks of text
# Beyond the Basics
## Commands for Movement
### Cursor Movement: Line, Character, Word
* Character and line (muscle memory)
* hl - left and right one character
* jk - up and down one line
* Words
* w word forward (whitespace or punctuation delimited)
* b word backward
* e end of current or next word
* W WORD forward (whitespace delimited)
* B WORD backward
* E end of current or next word (whitespace delimited)
### Cursor Movement: To a Location
* Line Locations
* 0 beginning of line
* $ end of line
* File Locations
* gg Top
* nG line n
* G Bottom
* n% n percent of file
### Screen, half-screen, line movement
* ^f Screen Forward
* ^b Screen Forward
* ^u Half Screen Forward
* ^d Half Screen Forward
* ^y Screen Down
* ^e Screen Up
### Counts
* Most movement commands allow a count
* Example: 3w moves 3 words forward
### Searching
* /string - search forward for string
* ?string - searches backward for string
* n after a search, finds next occurrence (in same direction)
* N after a search, finds previous occurrence (in opposite direction)
* f find a character
* F find a character (left)
* t to a character
* T to a character (left)
* ; repeats f or t
* See smart case below
## Input, Replace, Undo
### Input Commands
* These commands change to input mode, typically at the cursor or current line
i before current cursor location
I first non-blank character of the line
a after current cursor location
A end of line
o Open new line below
O Open new line above
gI Insert at first character of the line
gi Insert at last input location
* Input mode MOVES characters over
### Replace Commands
* Replace mode OVERWRITE characters
r replace character under cursor, once
R start Replacing characters under cursor
### Undo, Redo, and Do Again
* u undo
* ^r redo
* U undoes line to original state
* . - do most recent change, again
* :set undofile - Persistent undo
* Undo branch: Undo a change, make a new change.
* g-, g+ Undone changes become a branch (:help undo-tree)
## Delete and Change Text
### Delete Text
* x Delete character
* dw Delete word
* dd Delete line
* dj Delete current line and line below
* dk Delete current and line above
* dh Delete left character
* dl Delete right character
* de Delete to end of word
* db Delete to back to beginning of word
* d/foo - deletes up to foo
* dfx Delete to x
* dtx Delete to x
* d0 Delete to beginning of line
* d$ Delete to end of line
* D Delete to end of line
* dG What does this do? (Careful - remember u for undo)
### Changing Text
* s change current character
* cw change word
* cc Change entire line
* C Change rest of line
* c/foo changes up to foo
* c$ change to end of line
* c0 change to beginning of line
* ce change to end of word
* cb change to beginning of word
* cfx changes up to x
* ctx changes up to x
### Remember to use counts:
* 3x - delete 3 characters
* d3w - Delete 3 words
* 3dw - Delete 3 words
* 3d5w - Delete 15 words
* c3w - change 3 words
* c3l - change next 3 lines
## Cut and Paste
### Paste Deleted Text
* Items deleted (with x and d) go into (default) buffer
* p puts buffer into file, AFTER cursor or line
* P puts buffer into file, BEFORE cursor or line
* ddp - what does this do?
* xp - what does this do?
* Later see other buffers
* Careful: ^x, ^c, ^v don't do cut and paste, by default
* See later what they do
* Can cut and paste as an option
### Copy (Yank) and Paste
* y copies items into (default) buffer
* yw MOVE p - copies and pastes a word
* y3w MOVE p - copies and pastes 3 words
* ypp - two copies of current line
* Y copies a line
* Y MOVE p - copies and pastes a line
* yy also copies a line
## Command Line Mode, Help, Set
### Command Line Mode (aka ex mode)
* Pressing : opens command line and starts command line mode
* Enter command and press enter
### Common Commands
* :q and :wq
* :pwd and :cd
* :ha - :hardcopy - print
* on rucs, must set printer, but how to set for unix lab?
### Abbreviations
* Most commands have abbreviations:
* :ha = :hardcopy
* Can use TAB to expand and cycle through abbreviations
### :help
* Search
* :help - splits window and shows help
* Use :q to exit help (ie close split screen)
* Use ^] and ^o to navigate on colored links
* :help - splits window and shows help
* :help command - splits window and shows help for command
* Can use tab for completion
* :help abbreviated :h
### Set
* Set - sets options
* :set number
* :set nonumber
* :set ruler - shows line and column numbers in status line
* Can use tab to expand options
* :set - shows all set options
* :set all - shows values of all option that can be set
## Configuration: Vimrc
### .vimrc
* .vimrc contains commands executed on starting vim
* put .vimrc in Home Directory
* Find Home Directory with :echo $HOME
* Can also be called _vimrc
* Check location current vimrc with :echo $MYVIMRC
* Edit current vimrc with :vi $MYVIMRC
### Most Important Commands for Vimrc
* :syntax enable " enable syntax coloring
* :filetype indent on " enable specific indentation
* :filetype plugin on " enable specific plugins
* :set ruler " line and col nums in status line
* :set ai " automatic indentation
* :set ignorecase " ignore case in search
* :set smartcase " use case if specified
* :set backspace=2 " make backspace better
* : is optional in vimrc
# Vim for Programmers
### More Vimrc Commands
* :noremap ; : " Non recursive map of ; to :
* :noremap q; q: " Opens command window
* :inoremap jk <esc> " Use jk instead of escape!??!
* :set history=50 " number of commands to remember
* :set nobackup " backup files are useful, but they create clutter
* :set expandtab " expand tabs - replace tabs with spaces
* :set tabstop=4 " display any tabs as 4 chars
* :set shiftwidth=4 " How much to indent on shift, also backspace 4 chars
* :set smarttab " Enters shiftwidth spaces at line start when tab entered
* :set softtabstop=0 " ??
* :set shiftround " indents are rounded to multiples of shiftwidth
### Tabbed Editing * :tabe filename - opens a new tab
* :tabs - list tabs
* gt - move to next tab
* gT - move to previous tab
* ngt - move to tab n
* tabm 0 - go to tab 1n
* tabm - move to last tab
* tabm n - move to tab n
* works in terminal
* vim -p first.adb second.adb - opens first.adb and second.and in 2 tabs
### Query Things
* :set " query set options
* :set all " query all options
* :set fileformat " query filetype
* :set filetype " query filetype
* :verbose set ft " where was filetype set
* :set ff=unix " set fileformat
* :options
* :map
* :abbrev
* :scriptnames
* :function
* :command
k :marks
* :changes
## Split Windows
* :split filename
* :vsplit filename
* Movement between windows: ^W then hjkl
* Can rearrange windows
* Exit with :q
### Command History Window
* q:
* To save a keystroke: use :map q; q:
* Completion with ctrl-X ctrl-P
* Bring line down with ctrl-C
* Exit with :quit OR : OR ctrl-C ctrl-C
* Set history for number of lines saved
### Search History Window
* q/
* To save a keystroke, use :map q; q:
* Completion with ctrl-X ctrl-P
* Bring line down with ctrl-C
* Exit with :quit OR : OR ctrl-C ctrl-C
## Plugins for Programmers
* Install plugins to configure vim
* Files in plugin directories are loaded on startup
* Loads from system and user plugin directories
* To install in user plugin, simply drop .vim file in respective folders there
* Plugins pathogen and vundle provide automatic installation of plugins
### Directory Explorer (NERD Tree plugin)
* Edit a directory
* :tabe .
* o opens and leaves explorer
* i opens in a h split
* s opens in a v split
### User Plugins
*Your Plugin directory: $HOME\vimfiles\plugin
* Alternate location: If this does not work on rucs, try $HOME/.vim
* Look for local plugin locations in :set runtimepath
* Try: :split $HOME/vimfiles/plugin
* Find plugins on vim.org
* Some useful plugins:
* supertab - Enables keyword completion
* nerdtree - Directory browser in split window (or VTreeExplorer
* taglist
* command-t - like textmake snippits
* jad - Edit a compressed file (current?/default?)
* calendar - Open a calendar
### Filetype Plugins
*Loaded based on the type of file that is being edited
* Stored in folder ~/vimfiles/ftplugin
* System provides some; can add more
### User Filetype Plugins
* Your Plugin directory: $HOME\vimfiles\ftplugin
* Preserved on update
* Try: :split $HOME\vimfiles\ftplugin
* Put commands in language.vim (eg java.vim, ada.vim)
* Can put newlines in definitions (with \ at end of line, I think)
### Example User Filetype Plugin: java.vim
ab pc public class <CR>{<CR><CR>}<UP><up><up><END><left>
ab psvm public static void main(String[] args)<CR>{<CR><CR>}<UP><TAB><TAB>
ab sop System.out.println();<LEFT><LEFT>
ab fori for (int i = 0; i < X; i++)<CR>{<CR><CR>}<UP><TAB><TAB>
set makeprg=javac\ %
* Put java.vim in ftplugin
### Example User Filetype Plugin: ada.vim
ab fori for i in 1 .. 1 loop end loop;
ab ati ada.text_io; use ada.text_io;
ab afti ada.float_text_io; use ada.float_text_io;
ab aiti ada.integer_text_io; use ada.integer_text_io;
ab proc procedure foo is beginend foo;
autocmd BufNewFile,BufRead *.ad* set makeprg=gnatmake\ %
* Put ada.vim in ftplugin
* Auto command needed because of default ada configuration does not allow setting
makeprg in the user ftplugin/ada.vim
### Autocmd
* Specify commands to occur on various events
### Quickfix window
*:make - compile with makeprg
*:cc - go to current error
*:cn - go to next error
*:cp - go to prev error
*:cope - open quickfix window
### Make program for Ada, C, Java
* Java: set makeprg=javac\ %
* Ada: set makeprg=gnatmake\ %
* C: set makeprg=gcc\ -o\ %:r\ %
* % is a special register with the file name
:r removes the suffix
### Templates
* Can create template files to open automatically
* Create templates/java, for example
## Editing for Programmers (and More Advanced Commands)
### Shift and Indent
* << - Shift current line left
* >> - Shift current line right
* == - indent current line
### Visual Commands
* Highlight text
* Then operate on it
* Three highlighting commands: v, V, ^v
### Three kinds of highlighted areas
* Character - v
* Line - V
* Block - ^v
### Commands on Visual Areas
* d and x - delete
* c change area
* C change area lines
* rx replace each character in area with character x
* R replace all lines of area
* < > = - shift lines left, right, or indent
### Commands on Visual Blocks
* I Insert at beginning of block on all lines
* A Insert at end of block on all lines [use $ to mark end of line]
* c Change block on all lines
* C Change from beginning of block to end of line on all lines
* :s Substitute
### Other Visual Commands
* gv rehighlight area
* o go to beginning/end of area
* O go to beginning/end of line of block
* v, V, ^v change visual mode
### Text Objects
* Can change and delete text objects
* Example: di( - delete an inner () block
* Examples: ca( - change a ) block
* Example line to operate on: procedure foo(p: param1) is.
* Other objects: [ { < ' "
### More Text Objects
* Tag objects: cit - change inner tag
* Example line to operate on: a list item .
* Words - w W
* Paragraph and sentence: p s (what is a paragraph?)
### Screen Movement
* ctrl-y - Screen down one line, cursor moves with screen
* ctrl-e - Screen up one line, cursor moves with screen
* ctrl-u - Screen backward one screen
* ctrl-d - Screen forward one screen
### Cursor Movement
* HML - High, Middle, Low on screen
* zt - Move cursor line to top of screen
* zz - Move cursor line to middle of screen
* zb - Move cursor line to bottom of screen
### Mark Movement
* ma - mark current location with mark a
* 'a - go to mark a
* can use any letter
* '' - return to previous location (two single quotes)
### Jump Movement
* ctrl-o - go to older location on jump list
* ctrl-i - go to newer location on jump list
### Searching
* /pattern - forward search for pattern
* ?pattern - backward search for pattern
* n - repeat previous search
* N - repeat previous search, in reverse
* * - searches for next occurrence of word under cursor
* # - searches for previous occurrence of word under cursor
### Search Options
* smart case: ignore case unless used
* Example: Word word word Word word (try /word and /Word from column 1)
* :set hlsearch - turn on search highlight
* wrapscan - search around EOF
### Advanced Searching
* /pat/e - go to end of located string
* /pat/b+1 - go to second character of located string
* /pat/e-1 - go to next to last character of located string
* /pat/e+1 - go to character after located string
* /pat/-2 - go to 2 lines above located string
*/pat/+2 - go to 2 lines below located string
### Substitute Command - Substitute one string for another
* :s/old/new - default: operate on current line
* :s/old/new/g - all occurrences on line
* :s/old/new/c - with confirm
* :%s/old/new/gc - all occurrences in file, with confirm
* Can operate on visual area (see below)
### Regular Expressions
* ^ beginningg of line
* $ end of line
* . matches any letter
* * matches multiple of previous item
* MANY more options :help regexp
### %, *, #
* Matches braces
* Plugin matchit does same for if end if, etc
* * looks forward for word under cursor
* # looks backward for word under cursor
* Can continue both with n and N
### gd, gD
* gd - go to local definition
* gD - go to global definition
* Both look for first use of term under cursor
* gd looks locally in {}, gD globally, in file
### What happend to my paste??
* Sometimes a cut and paste does too much indenting
* :set paste
* then do the paste
* :set nopaste
### Control commands in input mode - Advanced
* ctrl-t shift right (ie tab) line
* ctrl-d shift left (ie untab) line
* ctrl-y insert character from line above
* ctrl-e insert character from line below
### Folds
* Can fold and unfold lines of text
* Two operations:
* Create fold
* Close (and open) fold
### Creating, Opening, and Closing Folds
* zf - creates fold from visual area and closes it
* zo - open fold at cursor
* zc - close fold at cursor
* :set foldmethod={manual, indent, marker, ...}
### Registers
* can delete and yank into registers and put from registers
* Denote registers using " and a letter
* Examples - "aY "bdw "ap "bp - replace register
* Examples - "AY "Bdw "Ap "Bp - append to register
* "" is the unnamed register
* it contains text from most recent delete or yank
* numbered registers contain previous values of "" (see help)
* "% contains file name
* ": contains most recent command line command
* "/ contains most recent search
* "*, "+, "~ contain clipboards in gui
* :registers lists registers and their contents
### Jump movement - CTRL-O, CTRL-I {{{2
* Jumps are movements in the file caused by commands such as
', `, G, /, ?, n, N, %, (, ), [[, ]], {, }, :s, :tag, L, M, H
* Vim keeps a jumplist - a list of destinations of each jump command
* :ju[mplist] - displays the jumplist
* ^I and ^O traverse the jumplist
### Insert mode commands
* ^T, ^D: indent and unindent
* 0^D: unindent to beginning of line
* ^A: Insert previously inserted text
* ^@: Insert previously inserted text and stop input
* ^D: Delete word in front of cursor
* ^E, ^Y: copy character from line below, above cursor
* ^R=mathExpr: Enter results of math computation
* ^V^X enter control character ^X
### Net Read/Write
* Open files across network
* vi http://www.radford.edu/classes/420/index.html
* vi scp://v...@137.../vimdemo.txt
### :terminal
* Version 8.1
* Not on rucs (yet)
## Resources
### Books
* Vim.org books page
* Practical Vim - Recommended (Second edition is forthcoming)
* Some good online books are available, but I don't have links handy
*
Learning the vi and vim Editors RU Library Electronic Resources (7th Editions)
*
Learning the vi and vim Editors (7th Edition) from Amazon
* Vi Improved (Vim)
* Hacking Vim
### Online References and Other Stuff
* Vim.org: The main vim page
* My Reference Page (lots of commands, operators, motion, objects)
* Other cool things:
* Vimperator
* shell vi key bindings put bindkey -v in .cshrc, set -o vi in bash?
* A nice intro
* Dr. Chip's Vim Page has lots of nice stuff
* User Manual and other documentation is
here
* From within vim, get User Manual with :h user-manual
* From within vim, get Quick Reference with :h quickref , or do a search for vim quickref
* Search engine - duckduckgo
* Wikipedia
* Some reference pages:
* More Vim Documentation
* Reference card
* Learning Vim
* A nice keyboard reference page
* A very complete
reference (VIM Reference Card 3.0)
* Quick Reference Page 0
* Quick Reference Page 1
* Quick Reference Page 2
* Quick Reference Page 3