Notes on Using Vim

-----------------------------------------------------------------------------
### Enough talk - let's create a Java program {{{1
    * Run vim
    * :syntax on or :syntax enable
    * Tell vim to edit Foo.java: 
        * Many commands start with :
            * eg :pwd
            * eg :cd
            * eg :echo $VIM
            * eg :echo $VIMRUNTIME
            * use tab for command line completion 
        * :vi Foo.java
            * uses extension to set filetype to java
    * Status line
    * Type in partial program: 
-----------------------------------------------------------------------------
### Map :, ;, q:, and q; {{{1
    * :map command translates one set of keystrokes into another
    * :map ; :
        * allows ;pwd - 1 less keystroke!
    * ;map q; q:
        * we will see q: later
    * don't put comments after rhs of map
-----------------------------------------------------------------------------
### Noremap and : and ;  {{{1
    * WARNING: MAPPING : to ; CAN CAUSE ERRORS IN SCRIPTS THAT USE
        COMMANDS THAT BEGIN WITH :.  
        Mapping : to ; is NOT recommended.
    * Later we will want to map ; to : and : to ;
    * Does this work?
        * :map ; :
        * :map : ;
    * No, this is mutual recursion
    * Solution: noremap - non recursive map
        * :noremap ; :
        * :noremap : ;  " NOT recommended
-----------------------------------------------------------------------------
### Insert and Normal Modes {{{1
    * use i to enter insert mode
    * use esc to exit insert mode and enter command mode
-----------------------------------------------------------------------------
### Compile it! {{{1
    * :set makeprg=javac\ %
        * \ escapes the blank
        * % represents the name of the file
        * later we will put this into a plugin to make it automatic

    * Save with :w (abbrev for :write)
        * for automatic saves :set autowrite (or :set aw )

    * Now compile with :make
        * press enter to return to file
        * notice that cursor is on first error
        * later we'll see how to see all errors
-----------------------------------------------------------------------------
### Programming overview: {{{1
    * put in .vimrc
        * :set syntax on - syntax coloring 
        * :set autoindent - automatic indentation 
        * :set autowrite - automatic saves on :make

    * put in local ftplugin directory, in java.vim, for example:
        * :set makeprg=javac\ % - put in local plugin

    * :make - compiles
        * :cc, :cn, :cp - to see current, next, prev errors
        * :copen to open error window, :q to quit

    * Indentation automatic if filetype detected from extension
    * Indent with: = for range, == for line

    * Explicit shift with: <, >, <<, >>

    * Use tab to get completion - may require plugin (supertab?)

    * For convenience, add abbreviations to local ftplugin files
-----------------------------------------------------------------------------
### Case sensitivity {{{1
    * Vim is case sensitive
    * Can set search for non case or smart case
    * If using non case or smart case, you can force case sensitivity with \C
        and force non-case-sensitivity wtih \c
            eg: /\Cabc forces case sensitivity - matches lowercase abc only
            eg: /\cabc forces no case sensitivity - matches abc in any case
-----------------------------------------------------------------------------
### Moving around in the file {{{1
    * hjkl - left, down, up, right one space or line
    * count operator does operator count times: 3k moves up 3 lines
    * wbe - move by word
    * 0, $ - beginning and end of line
    * :1, 1G - move to line 1 
    * 0 - beginning of the line
    * G - move to end of file
    * -f, -b - move one screen forward and back
    * 25% moves to 25% of file
    * -E,Y - scroll screen up, down, leaving cursor where it is
    * {, } - beginning, end of paragraph
    * '' (ie 2 single quotes) return to previous spot (ie to default mark)
-----------------------------------------------------------------------------
### Moving by setting marks {{{1
    * mark with ma, ..., mZ
    * go to mark with 'a, `a, 
    * go to default mark (ie previous location) with ''
-----------------------------------------------------------------------------
### Find command {{{1
    * fx, Fx - find character x in line, backwards, n times
        * quicker than / - no enter
    * tx, Tx - to character x in line, backwards, n times
    * ; and , - repeat previous f,F,t,T, backwards, n times
        * But later we map ; to : 
-----------------------------------------------------------------------------
### Insertion commands {{{1
    * i, I - insert at cursor, insert at beginning of line
        * But tabs at start of line are handled differently
    * o, O - open below, above
    * a, A - append after cursor, at end
-----------------------------------------------------------------------------
### Mistakes: Undo and Redo {{{1
    * u, -r - undo and redo, multiple times
    * backup file is saved for recovery on crashed sessions
-----------------------------------------------------------------------------
### Change and delete commands {{{1
    * x - delete characters at and following cursor
    * X - delete characters before cursor

    * cw - change word
    * s, S - substitute character, entire line
    * r, R - replace at cursor, beginning at cursor

    * dw, db - delete word, back
    * dd - delete line

    * cc, C - change entire line, rest of line
    * J - join two lines

    * . - repeats last change 

    * n operator - does operator n times: 3cw changes 3 words
        * what do these do? d3j, 3dk
-----------------------------------------------------------------------------
### Combining motion and changing: {{{1
    * operator motion: cw, dw, cb, db, c0, c$
-----------------------------------------------------------------------------
### Yanking and putting lines {{{1
    * Y, yy - yank current line (or marked lines or area)
    * p, P - put yanked lines above or below

    * :source $VIMRUNTIME/mswin.vim
        * causes -C, -V, -X to operate as in windows

    * marking areas
        * need :behave mswin to mark with mouse or shift arrows 
        * later we will see how to mark ranges
-----------------------------------------------------------------------------
### Saving and quitting {{{1
    * :wq - save changes and then quit file
    * :q! - quit and abandon changes since last change
    * :q  - quit a file that has no unsaved changes
-----------------------------------------------------------------------------
### Splitting windows  {{{1
    * :split filename - split and open filename
    * :vsplit filename - vertical split and open filename
    * -w--hjkl - move between windows
    * -w-+, -w-- - increase, decrease size of window
    * :q - quit a window, :qa - quit all windows (careful)
    * :only - make this the only window
    * Very useful for lots of operations:
        * help, command line and search history, option setting, differences
-----------------------------------------------------------------------------
### Help {{{1
    * :help name, eg :h split 
    * -D or  gives more information
    * :help help
    * :help
    * exit help with :q
    * f3 enters help
    * :h number vs :h 'number'
    * -], o - jump to help on tag, jump back
    * -] - search for help on any word in help
    * :helpgrep - use error window commands
    * Or, use google!
-----------------------------------------------------------------------------
### Command line window {{{1
    * q: brings up Window of history of commands 
    * Edit lines then hit enter
    * set history=50  - remember 50 commands in window
    * to get out:  -c -c
    * command line window, does not have regular command completion
        * use -c to bring current line down to get completion
    * remember we map q; to q:
-----------------------------------------------------------------------------
### Search commands {{{1
    * /abc - searches for abc
    * ?abc - searches backwards for abc
    * end with enter
    * n, N - repeat search, in opposite direction
    * q/ - search history window
-----------------------------------------------------------------------------
### Global substitution {{{1
    * :g introduces a global search
    * global search can be followed with a substitution command
    * An example - :g/foo/s//myFoo/
-----------------------------------------------------------------------------
### Regular expressions {{{1
    * Special chararacters to be used in a search
    * ^, $ - beginning, end of line
    * . - any character
    * asterisk - 1 or more characters
    * \ escape
-----------------------------------------------------------------------------
### Range and Area {{{1
    * Define area/range with 
        * v - visual, 
        * V - visual line 
        * -v, - visual block 

    * :source $VIMRUNTIME/mswin.vim
        * causes windows operation of -X,C,V
        * c-q, - marks a visual block 
        * found in default .vimrc
        * for fun, look at it with ;

    * called visual mode changing one kind to another - use another command
    * marking end of range - repeat starting command o, O - move to other
    * corner, across, diagonal gv - restore previous area
-----------------------------------------------------------------------------
### Range: Operations {{{1
    * v - visual: s, y, p
    * V - visual line : s, y,  Y, p, P
    * -v, - visual block : s, I, A,  y, Y, p, P
    * ~, u, U - switch, lower, upper case
    * d, c - delete, change range
    * <,>  - shift range left, right shiftwidth characters
    * = - indent range
    * gq - format range

    * ranges can be specify directly: 
        * eg :1,5d   - deletes lines 1 to 5
        * eg :.,.+5= - indents 6 lines from current position
        :1,/the/d  - deletes from line 1 to line containing the
-----------------------------------------------------------------------------
### As You Like IT: Configuring VIM {{{1
    * vim has 350+ options that can be set  
        * some are on or off
        * some have values
    * most are set with :set
    * lots of abbreviations and tab completion
-----------------------------------------------------------------------------
### Example on/off options: {{{1
    * :set ruler        noruler   
    * :set autoindent   noautoindent   
    * :set number       nonumber
    * :set wrapscan     nowrapscan 
    * :set autowrite    noautowrite 
    * :set ignorecase   noignorecase 
    * :set smartcase    nosmartcase 
    * :set joinspaces   nojoinspaces
    * :set paste        nopaste     
    * :set wrap         nowrap     
    * :set backup       nobackup   
-----------------------------------------------------------------------------
### Example options with values: {{{1
    * :set shiftwidth=4
    * :set fileformat=unix
    * :set fileformat=dos
    * :set syntax enable
    * :set makeprg=javac\ %
-----------------------------------------------------------------------------
### Tabs {{{1
    * :set tabstop=4                    
    * :set expandtab
    * :set smarttab
    * :retab
-----------------------------------------------------------------------------
### Option query and deletion {{{1
    * :set option=             Removes the value, for some options 
    * :set option              Display value of option
    * :set                     Display value of non-default options
    * :set all                 Display value of all options
    * :verbose set option      Display value and where set
-----------------------------------------------------------------------------
### Too much to keep track of! {{{1
    * :option - opens option window
    * alternate values are shown
    * Edit line if needed, then press enter to set
-----------------------------------------------------------------------------
### .vimrc {{{1
    * vim run commands
    * On vim startup, commands in .vimrc are executed 
        * windows looks first for _vimrc
        * windows then finds H:\.vimrc if no _vimrc
        * Other config files (eg ftplugins) are read at other times
    * :echo $MYVIMRC - shows path to vimrc
    * :vi $MYVIMRC
    * : not needed, eg set ruler
-----------------------------------------------------------------------------
### Options and commands {{{1
    * contrast: :number and :set number
-----------------------------------------------------------------------------
### Getting information: File, commands, version, etc {{{1
    * -g
    * :version
    * :scriptnames
    * :function
    * :function FunctionName
    * :abbreviate
    * :command
    * :highlight
    * :registers
    * :marks
    * :args     - list of files currently open
    * :map
    * :WhereFrom WhereFrom
-----------------------------------------------------------------------------
### Getting information - Saving results {{{1
    * 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 config files and directories and plugins {{{1
    * Installing plugins: simply drop files in specified directories
        * plugin scripts and tips are on vim.org

    * Examples: filetype specific syntax coloring, indentation

    * System configuration found in $VIM\vim70\ directories
        * eg, doc, ftplugin, indent, plugin, spell, syntax

    * User configuration found in $VIM\vimfiles directories
        * eg, doc, ftplugin, indent, plugin, spell, syntax
        * can be kept when installing new version of vim 
        * My H: drive: _vimfiles is soft link to .vim
    * viminfo Saves information about sessions
-----------------------------------------------------------------------------
### Setting up files for compilation {{{1
    * Example: java
        * Create java.vim in local filetype plugin directory
            * unix: .vim/ftplugin
            * windows: c:\software\vim\vimfiles\ftplugin

        * Include this line: set makeprg=javac\ %

        * This line also may be needed: set efm=%A%f:%l:\ %m,%-Z%p^,%-C%.%#

        * Useful abbreviations can be included:
    ab psvm public static void main(String[] args){}
    ab fori public static void main(String[] args){}
set makeprg=gnatmake\ %:r 

ab fori for i in 1 .. 1 loop end loop;
ab aito ada.integer_text_io; use ada.integer_text_io; 
ab ato ada.text_io; use ada.text_io; 

ab proc procedure foo is beginend foo;

    * other languages:
        * Ada: set makeprg=gnatmake\ %:r 
        * C: set makeprg=gcc\ -o\ %:r\ %
    * Filetype is set by extension: 
        * :set filetype to query current filetype
        * :filetype detect - detects file type again
-----------------------------------------------------------------------------
### Ada Mode: {{{1
    * Enable ada syntax coloring, indent, and compilation
        syntax on
        ftplugin on
        set makeprg=gnatmake\ %:r 

    * Warning: in vim 71, the default ada mode is broken
        - see week 1 of 320 notes to see how to fix it
-----------------------------------------------------------------------------
### Make and error windows {{{1
    * copen - open error window
    * cc, cn, cp: current, next, prev error
-----------------------------------------------------------------------------
### Multiple files in one session: Tabbed editing {{{1
    * :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
-----------------------------------------------------------------------------
### Multiple files in one session: args {{{1
    * 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
-----------------------------------------------------------------------------
### Comparing files: vimdiff, diffsplit, scrollbind {{{1
    * vimdiff  fn1 fn2 fn... from command line
    * :diffsplit fn - split and compare files
    * :set scrollbind - causes this file to follow scrolling of another
-----------------------------------------------------------------------------
### folding {{{1
    * 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
    * :set foldmethod ... - automatically creates folds
        * :set foldmethod indent - creates folds based on indentation
    * :set foldlevel=n
    * z looks like a fold
-----------------------------------------------------------------------------
### spell {{{1
    * 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
-----------------------------------------------------------------------------
### shell like commands: {{{1
    * :pwd, :cd
    * :!
    * :sort - sort a range
    * :grep
    * :r!
    * :make
    * :echo &shell
    * :echo &runtimepath
    * :echo $RUNTIMEPATH
-----------------------------------------------------------------------------
### editing, writing, quitting files: {{{1
    * :vi fn
    * :args foo*
    * slashes in file paths - either direction works on any os
    * :qa - :qall - quit all
    * :wq   save changes and then quit file
    * :w    save changes to current file
    * :w fn   save changes to a file called fn
    * :w fn   save changes to a file called fn
	* :wa - write all open, changed buffers
	* :saveas foo - save buffer as foo and edit foo
    * :q!   quit and abandon changes since last change
    * :q quit a file that has no unsaved changes
    * :vi # - edits alternate file (ie most recent), "# contains it's name
-----------------------------------------------------------------------------
### Backup files {{{1
    * 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 {{{1
    * :ha prints
    * :ha on windows brings up dialog
    * :set printoptions 
    * I define needed print commands, eg :DA205
    * Printing can be complex
-----------------------------------------------------------------------------
### ! Bang  {{{1
    * Many commands have a ! version which is more dangerous
    * :w! overwrites
    * :vi! edits and abandons changes in current file
    * :q! quits and abandons changes in current file
    * :ha! prints without a dialog window
-----------------------------------------------------------------------------
### More cool things you can do: {{{1
    * :Calendar
    * directory browser: vi .; enter; o
    * binary edit
    * :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
    * record a macro:
        * q1 - start recording in buffer 1
        * q - stop recording 
        * @1 - play back recording
    *  in a source file gives html syntax
    * status line is highly configurable
-----------------------------------------------------------------------------
### More cool things you can do ???: {{{1
    * edit zip and jar files - plugin required
    * decompile java byte code - plugin required (requires jad decompiler)
    * reverse input
    * omni completion - aka intellisense
    * ctags 
-----------------------------------------------------------------------------
### Warnings: {{{1
    * on my linux machine, the cursor is invisible on some characters
    * reverse input
    * record mode: enter q to get out
    * Watch out for caps lock!
-----------------------------------------------------------------------------
### things you can't do {{{1
    * auto justify, but gq} 
        - Yes you can: :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
    * console
-----------------------------------------------------------------------------
### ruby {{{1
    * :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
-----------------------------------------------------------------------------
### scripts {{{1
    * variables
    * com and functions
        * begin with capital letters
    * comments
    * echo
    * script shell
    * shell
-----------------------------------------------------------------------------
### More Movement Commands {{{1
    * % maps to matching parens and to if elsif end if
    * HML - High, Medium, Low
    * c-y,c-e, c-u,c-d, 
-----------------------------------------------------------------------------
### More Input Commands {{{1
    * Enter control character, eg ^X, with -V--X
    * when behave mswin is set use -Q--X
    * -D to undo tab or to unindent
    * :r filename reads in a file 
        * auto complete: tab completes file names
    * :r! command reads in the result of a command
-----------------------------------------------------------------------------
### Registers {{{1
    * can delete and yank into registers and put from registers
        * Denote registers using "
        * Examples - "aY   "bdw  "ap  "bp
    * "" 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
    * can yank into and put from registers
    * can append to named registers by using upper case
-----------------------------------------------------------------------------
### More search commands {{{1
    * /wxyz - search for wxyz and put cursor on w 
    * /wxyz/2 - search for wxyz and put cursor on second line below
    * /wxyz/-1 - search for wxyz and put cursor on line above

    * /wxyz/b+1 - search for wxyz and put cursor on x (beginning + 1)
    * /wxyz/e - search for wxyz and put cursor on z (end of search string)
    * /wxyz/e-2 - search for wxyz and put cursor on x (end - 2)
    * * - search for word under cursor
    * ignorecase - search ignores case
    * smartcase - ignore ignorecase if search for upper case
    * incremental search and highlight search
        * :nohlsearch to get rid of highlight search
    * q/ to get search history
-----------------------------------------------------------------------------
### More commands {{{1
    * number
        * :number        number as command 
        * :set number    number as option 
    * ga or ascii - display ascii value
    * :verbose
    * :colorscheme - set a colorscheme
    * :function name  - display a function
    * :function - define a function
-----------------------------------------------------------------------------
### Modes summary  {{{1
    * normal
    * insert: exit insert mode with esc
    * visual
    * select
    * replace
    * command line
    * ex: enter with gQ, exit with vi
    * see :help mode-switching
-----------------------------------------------------------------------------

Dr. Okie's Home Page,
Last modified on