Using Vim - Beyond the Basics

-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
--- TERMINOLOGY {{{1
    * Command - has direct action; may enter insert mode
    * Operator - needs motion afterward; operates between cursor and destination
--- SOME USEFUL COMMANDS: Split, help, completion, undo, command window{{{1
### My Favorite Keyboard Mappings {{{2
    * :map ; :
    * :map q; q:

    * The first enters command mode
    * The second opens the command window
-----------------------------------------------------------------------------
### Learn to use split windows {{{2
    * :split file
    * :vsplit file
    * -w-hjkl - move between windows
    * CTRL-w-CTRL-w - cycle between windows
    * -w+, -w- - increase, decrease size of window
    * :q - quit a window, :qa - quit all windows (careful)
    * :only - make this the only window
    * :split - opens new copy of existing file
    * :new - splits with empty file

-----------------------------------------------------------------------------
### Learn Help {{{2
    * :help name, eg :h split 
    * :help help
    * :help
    * exit help with :q

    * -], o - jump to help on tag, jump back
    * -] - search for help on any word in help

    * Many words used in different ways: 
    *    Help can differentiate: :h 'number' :h :number
    * -D or  gives more information

    * :helpgrep - :cn, :cp, :cc, :cope 
    * f3 may enter help
    * Or, use google!
-----------------------------------------------------------------------------
### Learn Abbreviations and Use Tab{{{2
-----------------------------------------------------------------------------
### Completion - Built in {{{2
    * Use ctrl-x ctrl-N to get word completion 
    * infercase - command completion option
    * :help completion - Lots of other things can be completed
    * omnicompletion and tags are useful but I haven't learned them

-----------------------------------------------------------------------------
### Completion - Supertab plugin
    * Plugin supertab causes tab to do word completion
    * Create your plugin directory: .vim/plugin
    * Download supertab.vim and put it in your plugin directory

-----------------------------------------------------------------------------
    * CTRL-e - scroll text up (ie window down)
    * CTRL-y - scroll text down (ie window up)

    * CTRL-D - scroll text half screen up (ie window half screen down)
    * CTRL-U - scroll text half screen down (ie window half screen up)

    * H, M, L - High, medium, low position on the screen (eg 10L)

    * zz, zt, zb - Make current line the middle, top, bottom of screen

    * (){} - move to begin/end of sentence/paragraph

    * % - find next paren item on line and move to its match
                exam(ple (ne{bra[c]es}sted) end)

-----------------------------------------------------------------------------
### Use undo and redo {{{2
    * u, -r - undo and redo, multiple times
    * backup file is saved for recovery on crashed sessions
    * undo branches - g-, :undolist, :h undo-branches, :h usr_32.txt
    * :changes
    * undobranch.txt example
-----------------------------------------------------------------------------
### Learn the Command Window {{{2
    * 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
-----------------------------------------------------------------------------
--- EDITING Op+Motion, Op+Object{{{1
### Learn Operator + Motion {{{2
    * Operators: v, V, CTRL-V, c, d, y, ~, =, <, >, g~, gw
    * Motion: 
        b B     Back a word/WORD
        e E     End of word/WORD
        f F     Find forward/backward in line
        h H     Cursor Left/to High in file
        j       Cursor down
        k       Cursor up
        l L     Cursor right/to Low in file
        M       Cursor to middle line of file
        n N     Repeat previous search/opposite direction
        t T     to character in line / backwards
        w W     Forward a word/WORD
        gd gD       Go to declaration (from func or file start)
        ge          Backward to end of word
        gg          Go to Top of file
        go          Go to byte
        'R          Go to mark R
    * Example: < j  - shift right current line 
    * Example: <<   - shift right current line 
    * Example: > 3j - shift right current line and 3 more

### Learn Operator + Text Object : VERY POWERFUL {{{2
    * Operators: v, V, CTRL-V, c, d, y, ~, =, <, >, g~, gw
    * Text Object
        iw aw     inner/a word (exclude/include delimiter)
        iW aW     inner/a WORD (white space delimited)
        ip ap     paragraph
        is as     sentence

        i( a( ib ab    block  - can also use closing )
        i{ a{ iB aB    Block
        i[ a[          [
        i< a<    <
        i" a"          "
        i' a'          '
        i` a`          `
        it at          html tag
-----------------------------------------------------------------------------
--- RANGES: VISUAL MODE: highlight lines, chars, blocks {{{1
### Learn to use the visual modes {{{2
    * Define area/range with 
        * v - visual - marks a sequence of characters
        * V - visual line  - marks a sequence of lines
        * CTRL-v, - visual block  - marks a block of characters

    * called visual mode 
    * change, delete, indent area
    * changing one kind to another - use another command
    * o, O - move to other corner, across, diagonal 
    * gv - restore previous area

-----------------------------------------------------------------------------
### Operating on text selected with visual mode {{{2
    c change (or r, s, C, S, R)
    y yank (or Y)

    x       Delete
    d       Delete
    r.      Replace with single character .
    s S     Substitue whole block with string
    > <     Shift
    =       Indent
    ~       Change case 
    g~      Change case
    gu u    Change to lower case
    gU U    Change to upper case
    p put
    gp put, and leave cursor at end of put
    J join
    U make Uppercase
    u make lowercase

    o - go to Other end
    O - go to Other end (stays in same line in block mode)

    gv - reselect up most recent selection

-----------------------------------------------------------------------------
### Operating on visual block {{{2
    x d     Delete
    r.      Replace with single character .
    s       Substitute each line with string
    > <     Shift
    ~       Change case 
    g~      Change case
    gu u    Change to lower case
    gU U    Change to upper case
    p put
    J join
    U make Uppercase
    u make lowercase
    I Block Insert
    A Block Append

-----------------------------------------------------------------------------
### Move to range {{{2
    * Mark a range, and then enter :m/string
    * Moves lines in range to after line with string

-----------------------------------------------------------------------------
--- MORE EDITING - :s, yank, indent and shift, join {{{1
### Substitute {{{2
    * :s/oldstring/newstring/g    ---- all occurrences on line
    * :s/oldstring/newstring/gc   ---- all occurrences and confirm
    * :%s/oldstring/newstring/    ---- operate on entire file 
    * can operate on a a range
-----------------------------------------------------------------------------
### Use . command (ie dot command) - repeats most recent change {{{2
-----------------------------------------------------------------------------
### Use g commands {{{2
    * Many commands have a g version (notice that g is not an operator)
    * ge - go to end of previous word
    * ga - show ascii of current character
    * gI - insert at position 0, ignoring initial white space
    * gJ - join lines without adding a blank
    * g~ - change case as a command (eg 3g~w)
    
-----------------------------------------------------------------------------
### Cut and Paste  {{{2
    * cut and paste with count d motion p
    * copy and paste with count y motion p

-----------------------------------------------------------------------------
### Cut and Paste: Use Visual mode
    * More sophisticated copy and paste available with visual mode
        * Mark the area/range (if more than one line)
        * Change, cut, copy, as desired
        * Paste (if desired)

-----------------------------------------------------------------------------
### Yank - Copy character, word, line into a buffer {{{2
    * Y - Copy current line into buffer
    * yy - Same

    * yw - Copy to end of current word into buffer
    * y - Yank a marked region
-----------------------------------------------------------------------------
### Indentation and shifting {{{2
    * Indentation automatic if filetype detected from extension
    * Indent with: = for range, == for line

    * Explicit shift with: <, >, <<, >>
    * Explicit shift with: <, >, <<, >>
-----------------------------------------------------------------------------
### Joining Lines  {{{2
    * J - Joins two lines
    * gJ - Joins two lines, without adding a blank between them
-----------------------------------------------------------------------------
--- CONFIGURATION, OPTIONS, .VIMRC, AND EDITING FILETYPES {{{1
### Learn to set and query options {{{2
    * Option forms: query, toggle, number, string
    * Query
        * :set ruler?
        * :set shiftwidth?
    * Toggle True/False
        * :set ruler
        * :set noruler
    * Toggle Invert
        * :set invruler
        * :set ruler!
    * Set Number
        * :set history=50
        * :set history+=10
    * Set String
        * :set makeprg=gnatmake\ %
        * query with :set makeprg
        * :set fo+=a
-----------------------------------------------------------------------------
### Recognize that most things can be queried {{{2
    * :echo $HOME $MYVIMRC $VIMRUNTIME - environment variables
    * -g        - file information
    * g--g      - file information
    * :number         - number as command: displays line number
    * :set number     - number as option: turn on line numbers 
    * :version        - display version info
    * :set            - displays options different from default
    * :set foo        - displays value of option foo
    * :set all        - display ALL option values
    * :scriptnames    - list of scripts read in
    * :function       - list of all functions
    * :function FunctionName    - definition of a function
    * :abbreviate     - list all abbreviations
    * :changes        - list changes to file
    * :command        - list all commands defined in scripts
    * :highlight      - highlight settings
    * :registers      - register values
    * :marks          - locatinos of marks
    * :args           - list of files currently open
    * :map            - all mappings
    * :echo           - display variable value or string
    * :verbose set    - find out where option set.  (eg :verbose set tabstop)
    * :verbose map    - find out where a map set.  (eg :verbose set ;)
    * :colorscheme    - set a colorscheme
    * :WhereFrom ???  - a plugin to find out where things are defined
    * :set runtimepath - query value of runtimepath
-----------------------------------------------------------------------------
### Options: Boolean and those with values {{{2
    *  Notice the differences among these: 
        :number    -- a command
        :set number
        :set nonumber
        :set number!
        :set tabstop=5
        :set tabstop
        :verbose set tabstop
-----------------------------------------------------------------------------
### Learn the Options Window {{{2
    * :options
-----------------------------------------------------------------------------
### Configuration: .vimrc {{{2
    * .vimrc contains commands that are executed on startup
    * : is not required (eg both :set ruler and set ruler work)
    * Use :echo $MYVIMRC or :scriptnames to find which .vimrc is executed
    * :echo $HOME $MYVIMRC $VIMRUNTIME
    * :set runtimepath - query value of runtimepath
    * vimrc loaded from $HOME
-----------------------------------------------------------------------------
### What if no .vimrc? {{{2
    * Let's try without a .vimrc
	* Check set - where were these set?
	* On Unix, these are executed on startup
	    1: /usr/local/share/vim/vimrc
	    2: /usr/local/share/vim/vim72/debian.vim
	* On Windows, may load H:\.vimrc 
	* On Windows, there might be a .vimrc or _vimrc where vim is installed
-----------------------------------------------------------------------------
### A Minimal .vimrc {{{2
    * Some of the most useful commands
-----------------------------------------------------------------------------
### Let's look at my .vimrc {{{2
-----------------------------------------------------------------------------
### Some useful command line commands {{{2

    :set number        - turn on line numbers 
    :set smartcase     - case sensitive search only when upper case used
    :set autoindent    - automatically indent new line as previous
    :set tabstop=4     - amount of indent when TAB is pressed
    :set shiftwidth=4  - amount of indent on program indentation
-----------------------------------------------------------------------------
### Commands to set up for programs {{{2
    * filetype plugin on - enable loading plugins for file types
    * filetype indent on - indentation based on file type
    * syntax enable   - syntax coloring
-----------------------------------------------------------------------------
### Editing HTML Files {{{2
    * html.vim
    * This is a copy of the installed version, with changes
-----------------------------------------------------------------------------
### Make program for Ada, C, Java{{{2
    * Ada: set makeprg=gnatmake\ %
    * C: set makeprg=gcc\ -o\ %:r\ %
    * Java: set makeprg=javac\ %
-----------------------------------------------------------------------------
### Using quickfix window{{{2
    * Use :make to compile, then quickfix to access errors
    * :cope - open quick fix window
    * :cc  - move to current error
    * :cn  - move to next error
    * :cp  - move to previosu error
    
-----------------------------------------------------------------------------
### Tags {{{2
    * Omnicompletion should be useful, but I haven't learned it
    * Tags should be useful, but I haven't learned them
-----------------------------------------------------------------------------
### Filetypes {{{2
    * Filetype option indicates type of file (eg java, ada, c, html)
    * Used for indentation, syntax coloring, ftplugins
    * Filetype is set by extension (and sometimes file contents) 
    * :set filetype? - to query current filetype
    * :filetype detect - detects file type again
-----------------------------------------------------------------------------
### Runtimepath {{{2
    * Where does vim look for plugins?
    * :set runtimepath?
-----------------------------------------------------------------------------
--- REGISTERS {{{1
### Use Registers {{{2
    * 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
-----------------------------------------------------------------------------
--- MOVEMENT {{{1
### Learn to Move {{{2
    * ctrl-F, B, U, D
    * ctrl-Y, E
    * H, M, L, nH, nL, %
    * w, b, e, W, B, E
    * {} - paragraph)
    * () - sentence
-----------------------------------------------------------------------------
### Use counts {{{2
-----------------------------------------------------------------------------
### Use Movement with d and c {{{2
-----------------------------------------------------------------------------
### 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

-----------------------------------------------------------------------------
### Use marks {{{2
    * mark with ma, ..., mZ - marks current location
    * go to mark with 'a, `a, 
    * go to default mark (ie previous location) with ''
    * Query marks with :marks
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
### Search Command {{{2
    * /abc - searches for abc and puts cursor on a
    * ?abc - searches backwards for abc
    * end with enter
    * n and N repeat previous search in same or reverse direction

    * /wxyz/2 - search for wxyz and put cursor on second line below
    * /wxyz/-1 - search for wxyz and put cursor on line above

    * /abc/b+1 - puts cursor on b

    * /abc/e - puts cursor on c
    * /abc/e+1 - puts cursor on character after c

    * q/ - search history window
    * * - search for next occurrence of word under cursor

    * :set ic - ignorecase - search ignores case
    * :set smartcase - ignore ignorecase if search for upper case

    * :set incsearch - highlight partial matches as you type /string
    * :nohlsearch to turn off current search highlighting

    * :set nohlsearch to turn off highlight search

    * q/ to get search history
    * Warning: watch out for searches that involve regexp characters (see below)
-----------------------------------------------------------------------------
### 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 {{{1
### Insert mode commands {{{2
    * ^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

-----------------------------------------------------------------------------
--- FOLDING {{{1
### Folding {{{2
    * How folds work:
        * Folds can be created in a file
        * Folds can be open or closed
        * Existing and being open or closed are independent
    * zf - creates a fold and immediately closes it

    * zo - opens the fold under the cursor
    * zc - closes the fold under the cursor
    * zM - more folding - close all folds
    * zR - less folding - open all folds

    * :set foldmethod ... - automatically creates folds
        * :set foldmethod indent - creates folds based on indentation
        * :set foldmethod marker - creates folds based special marker
        * :set foldmethod manual - only have user created folds (with zf)

    * Indentation folding is good for code
    * :set foldlevel=n
    * z looks like a fold
    * Can cut and paste entire folds!
-----------------------------------------------------------------------------
--- WORKING WITH MULTIPLE FILES {{{1
### Learn to use vi and saveas {{{2
    * :vi file - edits file (current file must be saved)
    * :vi! file - edits file (changes to current file are abandoned)
    * :saveas filename - edits current file as filename
-----------------------------------------------------------------------------
### Comparing files: vimdiff, diffsplit, scrollbind {{{2
    * vimdiff  fn1 fn2 fn... from command line
    * :diffsplit fn - split and compare files
    * :set scrollbind - causes this file to follow scrolling of another
-----------------------------------------------------------------------------
### Multiple files in one session: args {{{2
    * vim *.adb - edits all adb files in one session
        * each one becomes an argument
    * :args - list current arguments
    * :prev, :next
    * :argdo command - do command to each argument
    * :args foo* - set arguments
-----------------------------------------------------------------------------
### Buffers {{{2
    * :buffers
    * :ls
    * :buffer n (abbreviation is :bu)
    * :sb n (split buffer)
    * :vi #, :sb #
-----------------------------------------------------------------------------
### Tabbed Editing {{{2
    * :tabe filename
    * :tabe
    * :tabdo
    * :tabmove N - put current tab in position N, 0 to make it the first tab
    * :tabs
    * gt, gT - go forward, backward one tab
    * n gt - go to tab n
-----------------------------------------------------------------------------
### Split - we covered above{{{2
-----------------------------------------------------------------------------
### Directory Browser {{{2
    * vi mydir or :split
    * enter opens
    * o opens in split window
    * vfilebrowser is a nice plugin
-----------------------------------------------------------------------------
--- SCRIPTS {{{1
### Scripts {{{2
    * letter indicates type of internal variable 
        -  g:name is a global variable
        -  l:name is local to a function
        -  l:name is local to a script
        -  v:name is global and predefined by vim
        -  w:name is local to current window
    * let - for assignment
    * loops and ifs: for/endfor, if/elseif/else/endif
    * com and functions
        * begin with capital letters
-----------------------------------------------------------------------------
### Let's look at some scripts scrollbar.vim and calendar.vim{{{2
-----------------------------------------------------------------------------
### ruby {{{2
    * An alternate scripting language.  Perl and python are other options
    * :ruby print 3
    * :ruby 3.updo(10){|i| print i}
    * :rubydo print $_.reverse operates on a range
    * :ruby VIM::Buffer.current.append(1, VIM::Buffer.current[1].reverse)
    * $curwin, $curbuf
    * must be ruby enabled (see :version for +ruby)
    * python and perl also available
-----------------------------------------------------------------------------
--- REGULAR EXPRESSIONS {{{1
### Regular Expressions {{{2
    * Allow specifying strings in substitute and strings
    * Some characters have special meanings 
        (eg \s white space, \d digit, \D non-digit, \a alphabetic, \n end of line))
        (eg * zero or more instances, \+ 1 or more instances)
        (eg ^ and $ specify beginning/end of line, when at begin/end of line)

    * Here are some examples of regular expressions that I've done:

    * Remove ^M at end of line: 
            %s/
$//   (Press cntl-v and cntl-m to enter cntl-m)

    * Add {{{x to end of lines that have ###: 
            %s/\(###.*$\)/\1 {{{x/

    * Locate where " " and " " appear at the start of 2 successive lines
            /^ <\/tr>\n /

    * Make HTML Comments from lines when " " and " "  
        appear at the start of 2 successive lines
            %s/\(^ <\/tr>\n \)//

    * Remove all lines that contain only white space
            %s/^\s*$\n//

    * Make all lines that start with Q: into html list items
            %s/^Q: \(.*\)$/
  • Q: \1<\/li>/ * Search for lines that start with Q: and DON'T end with ? ^Q: .*[^\?]$/ * Change all single line list elements to bold single line list elements %s-^
  • \(.*\)
  • -
  • \1
  • - How to make this work over multiple lines?? ----------------------------------------------------------------------------- --- SPELL CHECKING {{{1 ### Spell {{{2 * new to vim 7 * :set spell - turn on spell checking * ]s, [s - find next,prev misspelled word * [] is used frequently * z= - suggest spellings * zg - add current word to list of good words * Note: * when syntax=html must have :set syntax spell toplevel * so, I put :syn spell toplevel into ~/.vim/syntax/html.vim * map ;set invspell;set spell? * map ;set hls!;set hls? ----------------------------------------------------------------------------- --- SHELL COMMANDS {{{1 ### Shell like commands: {{{2 * :pwd, :cd * :! * :sort - sort a range * :grep * :r! * :make * :echo &shell * :echo &shell * :echo &runtimepath * :echo &runtimepath * :echo $RUNTIMEPATH ----------------------------------------------------------------------------- --- MACRO RECORDING {{{1 ### Shell like commands: {{{2 * record a macro: * q1 - start recording in buffer 1 * q - stop recording * @1 - play back recording ----------------------------------------------------------------------------- --- OTHER STUFF {{{1 ### Getting information - Saving results {{{2 * How to save the information from a query * :redir[!] > myfile * now you can edit myfile * can redirect into register * :vfile=myfile * now you can edit myfile * do some commands * :vfile= * :vfile=newfile - check the help ----------------------------------------------------------------------------- ### Vim info {{{2 * viminfo Saves information about sessions ----------------------------------------------------------------------------- ### Backup files {{{2 * Editing file creates a backup file: * vim myfile.fn creates .myfile.fn.swp * used to tell if a file is being edited * used for recovery of crashed sessions * :set backup causes backup file to be kept after editing ----------------------------------------------------------------------------- ### Printing {{{2 * :ha prints * :ha on windows brings up dialog * :set printoptions * I define needed print commands, eg :DA205 * Printing can be complex ----------------------------------------------------------------------------- ### More cool things you can do: {{{2 * :Calendar (a plugin) * vimperator * tcsh: bindkey -v # Causes shell to respond to vi edit keys * binary edit - vi -b * :mksession to save the session, then vim -S Session.vim * :TOhtml - a nice plugin - creates html file of file with current coloring * clean up newlines between different OS - see help filemodes * ;set fm=dos * ;set filemode=unix * or use dos2unix! * in a source file gives html syntax * This modeline - tells vim how to start up * status line is highly configurable * edit zip and jar files * decompile java byte code - plugin required (and a decompiler - try jad, or jode) * browse tar and zip files (tarPlugin.vim and zipPlugin.zip) * reverse input ----------------------------------------------------------------------------- ### Automatic justification {{{2 * Justify a paragraph: gq} * auto justify: - :set fo+=a "formatoption+=a automatic formatting - memory intensive since it remembers each change - :set fo+=2 "formatoption+=2 format based on second line - :set fo+=n "formatoption+=n format numbered lists ----------------------------------------------------------------------------- ### What you can't do {{{2 * console - you can't get a console in a window - by design ----------------------------------------------------------------------------- ### Modes summary {{{2 * normal * insert: exit insert mode with esc * visual * select * replace * command line * ex: enter with gQ, exit with vi * see :help mode-switching ----------------------------------------------------------------------------- ### Others - Not integrated into the rest of notes: {{{2 * :set cursorline, cursorcolumn * autocmd * :list and :set list/nolist and :listchars * vimsh - a shell the executes the vim scripting language * how vim is implemented - see help files * :NoMatchParen - turn off matching paren highlighting * ctx * swap : xp; lines: ddp; words: dwep or dWEp * It's possible to return to last line from previous editing session

    Dr. Okie's Home Page,
    Last modified on