Skip to content

Instantly share code, notes, and snippets.

@agfe2silver
Forked from alvinfrancis/vim-lecture-1.org
Created August 20, 2021 10:01
Show Gist options
  • Save agfe2silver/5e5994f4adc2561d7cbd49e7a6312292 to your computer and use it in GitHub Desktop.
Save agfe2silver/5e5994f4adc2561d7cbd49e7a6312292 to your computer and use it in GitHub Desktop.
Vim Lectures (February 2018)

About

  • Vim (Vi IMproved)
  • created by Bram Moolenaar
  • initial release 1991 (Vi was released 1976)
  • still in active development
  • 2017 Stackoverflow survey
    • 4th most popular for Web developers
    • 5th most popular for Desktop developers
    • 1st most popular for Sysadmin / DevOps
    • 3rd most popular for Data scientists

Learning curve

Learning Curves for Editors

Vim has a high learning curve but well worth it

(WARNING: emacs is rabbit hole)

As an aside: Editor war

https://en.wikipedia.org/wiki/Editor_war

Real Programmers

An interesting piece of programmer culture and history. Arguably foremost among the programmer holy wars.

Why Vim?

  • Speed
  • Efficiency
  • Comfort
  • Simple
  • Ubiquitious

Modal editing has clear advantages to an always-insert editing model.

Things to note

  • Touch typing is recommended learning
  • The mouse is anathema
  • Lots of vim learning resources; start with vimtutor
  • Start vanilla then build your config slowly
  • Keep a cheatsheet in the beginning
  • Seek :help
  • :q

Talking to your editor

  • Editing text should be structured
  • Learn the editing language
  • Fluency allows for efficient and surgical text editing
3dd - delete 3 lines
daw - delete 'around' word
c3f. - change the text up to and including the 3rd instance of a period

Modes

Normal mode

  • default state
  • all your keys are commands
  • Press <ESC> to go back to this mode

Insert mode

  • typical editor mode
  • accessed via normal mode commands

Visual mode

  • Selection/Highlight
  • Two types
    • Visual block (use this for vertical changes)
    • Visual line

Basic Motion

Keep your fingers on the home row

    ^
    k          Hint:  The h key is at the left and moves left.
< h   l >             The l key is at the right and moves right.
    j                 The j key looks like a down arrow.
    v

NOTE:

  • there is a difference between display line and line

j* As an aside: ADM-3A

https://en.wikipedia.org/wiki/ADM-3A

ADM-3A Keyboard

When vi was being created by Bill Joy, the dumb terminal keyboard used was the one above. Note the positioning of keys.

Line Motion

0 - beginning of line ^ - first non-blank character $ - end of line

Word Motion

B - previous WORD b - previous word e - end of word E - end of WORD ge - previous end of word gE - previous end of WORD w - beginning of next word W - beginning of next WORD

NOTES:

  • certain motions (e.g. word motions) can be prefixed with a number to repeat the motion
  • difference of semantics of word, WORD, page.

Page Motion

gg - beginning of file G - end of file

CTRL-b - up 1 page CTRL-u - up 1/2 page CTRL-d - down 1/2 page CTRL-f - down 1 page

Occurence Motion

f{char} - to the next occurence of character on the right F{char} - to the next occurence of character on the left t{char} - same as f but stops short one character T{char} - same as F but stops short one character ; - repeat forward (F,f) motion ~,~ - repeat backward (T,t) motion

Search Motion

/ - search forward ? - search backward * - search forward word under cursor # - search backward word under cursor

PROTIP: end search query with /e to go to end of the search

j* More Motion

:help motion :help pattern

Highlights:

gd - jump to definition % - go to match gi - go to last insert mode location ~’. `. ‘< `<~ and others - special marks CTRL-O - go to last jump

Insert

:help insert

Commands for putting you in insert mode

o - begin a new line under the cursor O - begin a new line above the cursor a - insert text after the cursorasdf A - insert text at end of line i - insert text before the cursor I - insert text at the beginning of the line (first non-blank)

Change

:help change

d,D,x,X - delete y,Y - yank J - join lines gU, gu - change case gq - formatting :! - pass through external program <, > - shift left, right

The following leaves you in insert mode after deleting text

c,C - change s,S - substitute r,R - replace

Dot

. - redo your last change

Text Objects

:help text-objects

Commands used in conjunction with visual mode or an operator

a - around i - inner

b, B, (, ) - block w - word W - word s - sentence p - paragraph

NOTE: it is possible to create your own text objects

Demo

Buffers, Windows and Tabs

:help windows

A buffer is the in-memory text of a file. A window is a viewport on a buffer. A tab page is a collection of windows.

Window Commands

Window commands are prefixed with CTRL-W

s - split current window in two v - split current window in two (vertically) n - create new window c - close window (:q works just as well) o - only window

Window Commands

Window commands are prefixed with CTRL-W

h,j,k,l - move cursor to other windows H,J,K,L - move windows around r - rotate windows T - move window to new tab page

Window Commands

= - equalize window sizes

  • - decrease window height

+ - increase window height < - decrease window width > - increase window width _ - max height | - max width

PROTIP: set scrollbind to synchronize scrolling (useful for multi page viewing on large monitors)

Tab Commands

:tabnew - open new tab :tabclose - close tab gt, gT - switch between tabs

PROTIP: remap keys for easier access to tab commands

Buffer Commands

:ls, :buffers - show all buffers :bn, :bN - switch between buffers :b N - switch to targeted buffer

PROTIP: remap keys for easier buffer switching (e.g. :ls<CR>:b)

Writing

:help writing

:w - save buffer to current file

Swap

:help swap

Vim stores the things you changed in a swap file. Using the original file you started from plus the swap file you can mostly recover your work.

Set the directory option to configure where swap files are created.

Undo/Redo

:help undo

u - undo CTRL-r - redo

Vim uses a branching model to keep track of file changes.

All changes can be accessed through the undo list.

Earlier states of a file can be accessed using earlier and later.

Persistent Undo

Set the undofile option to enable undo persistence.

Set the undodir option to create the undo files in a central location.

Registers

:help registers

There are ten types of registers:

  1. The unnamed register “”
  2. 10 numbered registers “0 to “9
  3. The small delete register “-
  4. 26 named registers “a to “z or “A to “Z
  5. three read-only registers “:, “., “%
  6. alternate buffer register “#
  7. the expression register “=
  8. The selection and drop registers “*, “+ and “~
  9. The black hole register “_
  10. Last search pattern register “/

You can insert register contents with CTRL-r in insert mode or prefix a paste command with ~”{register}~.

PROTIP: recorded macros are stored in registers

Marks

:help mark-motions

` - The cursor is positioned at the specified location ~’~ - The cursor is positioned on the first non-blank character in the line of the specified location m{a-zA-Z} - set a mark at cursor position

Mapping

:help mapping

{n,i,v,o}map - recursive mapping {n,i,v,o}noremap - non-recursive mapping

inoremap jj <Esc>

Leader

:help mapleader :help maplocalleader

Namespaced mappings allowing for greater customization without overstepping existing mappings.

Random tips

  • Backgrounding vim
  • Standard input
  • Edit command line
  • Edit history
  • Relative line numbers

My .vimrc

file:~/.vimrc

i_CTRL-X

:help i_CTRL-X

i_CTRL-X enters a special submode where several commands can be used.

  • i_CTRL-X_CTRL-E scroll window one line up
  • i_CTRL-X_CTRL-Y scroll window one line down

Insert Completion

:help ins-completion

i_CTRL-X_CTRL-LWhole lines
i_CTRL-X_CTRL-Nkeywords in the current file
i_CTRL-X_CTRL-Kkeywords in ‘dictionary’
i_CTRL-X_CTRL-Tkeywords in ‘thesaurus’, thesaurus-style
i_CTRL-X_CTRL-Ikeywords in the current and included files
i_CTRL-X_CTRL-]tags
i_CTRL-X_CTRL-Ffile names
i_CTRL-X_CTRL-Ddefinitions or macros
i_CTRL-X_CTRL-VVim command-line
i_CTRL-X_CTRL-UUser defined completion
i_CTRL-X_CTRL-Oomni completion
i_CTRL-X_sSpelling suggestions
i_CTRL-N i_CTRL-Pkeywords in ‘complete’

Insert Completion - Keywords

  • i_CTRL-X_CTRL-N keywords in current file
  • i_CTRL-X_CTRL-I keywords in current and included files
  • i_CTRL-X_CTRL-K keywords in ‘dictionary’

‘dictionary’ is a vim option containing a list of file names used to lookup words.

  • i_CTRL-X_CTRL-N keywords in ‘thesaurus’

‘thesaurus’ is a vim option. Same as ‘dictionary’ but used to lookup similar words.

Insert Completion - Whole Lines

i_CTRL-X_CTRL-L whole lines

Search backwards for a line that starts with the same characters as those in the current line before the cursor. Indent is ignored. The matching line is inserted in front of the cursor. The ‘complete’ option is used to decide which buffers are searched for a match. Both loaded and unloaded buffers are used.

Insert Completion - Omni

i_CTRL-X_CTRL-O omni completion

Attemps to guess what sort of completion is necessary.

Diff

:help diff

:difft[his] make current window part of diff windows

:diffu[pdate] update diff

:diffo[ff] remove current window as part of diff windows

Tags

:help tags

CTRL-] jump to a tag

CTRL-T pop the tag stack (CTRL-O pop jump stack)

ctags

man ctags

Program for generating a tags file.

Can be extended to apply to other user provided languages.

--langdef=scala
--langmap=scala:.scala
--regex-scala=/^[ \t]*((abstract|final|sealed|implicit|lazy)[ \t]*)*(private|protected)?[ \t]*class[ \t]+([a-zA-Z0-9_]+)/\4/c,classes/
--regex-scala=/^[ \t]*((abstract|final|sealed|implicit|lazy)[ \t]*)*(private|protected)?[ \t]*object[ \t]+([a-zA-Z0-9_]+)/\4/c,objects/
--regex-scala=/^[ \t]*((abstract|final|sealed|implicit|lazy)[ \t]*)*(private|protected)?[ \t]*case class[ \t]+([a-zA-Z0-9_]+)/\4/c,case classes/
--regex-scala=/^[ \t]*((abstract|final|sealed|implicit|lazy)[ \t]*)*(private|protected)?[ \t]*case object[ \t]+([a-zA-Z0-9_]+)/\4/c,case objects/
--regex-scala=/^[ \t]*((abstract|final|sealed|implicit|lazy)[ \t]*)*(private|protected)?[ \t]*trait[ \t]+([a-zA-Z0-9_]+)/\4/t,traits/
--regex-scala=/^[ \t]*type[ \t]+([a-zA-Z0-9_]+)/\1/T,types/
--regex-scala=/^[ \t]*((abstract|final|sealed|implicit|lazy)[ \t]*)*def[ \t]+([a-zA-Z0-9_]+)/\3/m,methods/
--regex-scala=/^[ \t]*((abstract|final|sealed|implicit|lazy)[ \t]*)*val[ \t]+([a-zA-Z0-9_]+)/\3/l,constants/
--regex-scala=/^[ \t]*((abstract|final|sealed|implicit|lazy)[ \t]*)*var[ \t]+([a-zA-Z0-9_]+)/\3/l,variables/
--regex-scala=/^[ \t]*package[ \t]+([a-zA-Z0-9_.]+)/\1/p,packages/

Useful Ex

:g[lobal]/{pattern}/[cmd] execute [cmd] to all lines matching {pattern}

Discuss:

  • :g/{pattern}/d
  • :g!/{pattern}/d :v/{pattern}/d
  • :g/{pattern}/m[ove] 0
  • :g/{pattern}/t 0
  • :g/{pattern}/normal[!]
  • //

Useful pattern ex

Patterns

  • \s \S \d \D \w \W \r \t
  • \< \>
  • \zs \ze
  • \1…\9 + \(\)
  • \_.

Flags

e.g. s/{pattern}/{replacement}/{flags}

  • g replace all
  • i case insensitive
  • c ask for confirmation

Very magic

:help /\v

Use of “\v” means that in the pattern after it all ASCII characters except ‘0’-‘9’, ‘a’-‘z’, ‘A’-‘Z’ and ‘_’ have a special meaning. “very magic”

Expression register

:help @=

=

Evaluate and insert an expression

Match

:help match-highlight :help highlight-groups

:mat[ch] {group} /{pattern}/

Group should be defined. Can use predefined groups (e.g. Search/Keyword).

:match none

Complex repeat record

:help complex-repeat

q{a-z} record keystrokes to a register

q{A-Z} record keystrokes to a register (append)

Remember that register contents are just text. Debug and edit contents directly.

NOTE: mapping abbreviations do not work.

Complex repeat execute

@{a-z} execute the contents of a register

@@ repeat last executed @{a-z} [count] times.

@: repeat last command line

Macro Demos

Taken from https://sanctum.geek.nz/arabesque/advanced-vim-macros/

Demo 1

Convert to years to age.

Stallman  Richard GNU 1953  USA
Wall  Larry   Perl  1954  USA
Moolenar  Bram  Vim 1961  Netherlands
Tridgell  Andrew  Samba  1967  Australia
Matsumoto  Yukihiro  Ruby  1965  Japan
Ritchie  Dennis  C  1941  USA
Thompson  Ken  Unix  1943  USA

Demo 2

Create a file for each route in a gtfs feed containing all matching stop times.

Searching multiple files

:help grep

Unix trivia: The name for the Unix “grep” command comes from “:g/re/p”, where “re” stands for Regular Expression.

:vimgrep :grep :lgrep :lvimgrep

argdo, bufdo, windo, tabdo

:argdo execute against all files in the args list :bufdo execute against all buffers in the buffer list :windo execute against all windows in the current tab :tabdo execute against all tabs in the current workspace

No Plugins

vim -u NONE

Useful when dealing with large files.

Increment/Decrement

  • CTRL-a to increment number under cursor
  • CTRL-x to decrement number under cursor

Insert deletes

CTRL-w delete previous word

CTRL-u delete to beginning of line

CTRL-k delete to end of line

Binary files

:%!xxd to pass file into a hex editor

:%!xxd -r to ‘save’ changes

To HTML

:help :TOhtml

Generate HTML based on current window (and any other related window if in a diff)

Bash command line editing

CTRL-X CTRL-E edit command in EDITOR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment