All Projects → adembudak → Vim Doctor

adembudak / Vim Doctor

Licence: mit
A quick reference for Vim text editor.

Labels

Vim logo

A quick reference for Vim text editor

Quit the Vim

<esc> :q! <enter>

What is Vim?

Vim is a highly configurable text editor for fast and effective text editing.

Vim is not designed for hold users hand, it's a tool and must be learned how to use. Vim is not a word processor.

History of Vim1

ed was the original Unix text editor. It was written at a time when video displays were uncommon. Source code was usually printed onto a roll of paper and edited on a teletype terminal. Commands entered at the terminal would be sent to a mainframe computer for processing, and the output from each command would be printed. In those days, the connection between a terminal and a mainframe was slow, so much so that a quick typist could outpace the network, entering commands faster than they could be sent for processing. In this context, it was vital that ed provide a terse syntax. Consider how p prints the current line, while %p prints the entire file. ed went through several generations of improvements, including em (dubbed the “editor for mortals”), en, and eventually ex.

By this time, video displays were more common. ex added a feature that turned the terminal screen into an interactive window that showed the contents of a file. Now it was possible to see changes as they were made in real time. The screen-editing mode was activated by entering the :visual command, or just :vi for short. And that is where the name vi comes from. Vim stands for vi improved. That’s an understatement—I can’t stand to use regular vi! Look up :h vi-differences for a list of Vim features that are unavailable in vi. Vim’s enhancements are essential, but it still owes much to its heritage. The constraints that guided the design of Vim’s ancestors have endowed us with a highly efficient command set that’s still valuable today.

Forks and Vanillas

Neovim is a fork of the venerable text-editor vim, focused on extensibility and usability. It is not a rewrite but a continuation and extension of Vim. Many clones and derivatives exist, some very clever—but none are Vim. Neovim is built for users who want the good parts of Vim, and more. See a list of differences via :help vim-differences.

SpaceVim is a community-driven modular Vim distribution. It manages collections of plugins in layers, which help to collect related packages together to provide IDE-like features.

Onivim 2 is a reimagination of the Oni editor. Onivim 2 aims to bring the speed of Sublime, the language integration of VSCode, and the modal editing experience of Vim together, in a single package.

Also you might want to take a look at this talk on VimConf.live

Creating a file

$ vim <enter>
$ vim filename
$ vim directory/filename

⇧ back to top

Vim modes

Vim is a modal editor. It has different modes for different activities when editing text. In a non-modal editor, when you want to go from point A to B, you either move the cursor one by one or use your mouse. Vim provides a fast track to reach begin or end of a file/paragraph/line/word, called normal mode. When you reach the point you want to edit, you change to insert mode.

These are all happen by using keyboard shortcuts. That's the reason Vim has a reputation using computer when your hands on keyboard. Memorizing shortcuts for every move can be seem burdensome at first but most of them are just one or two letters... and once you get along with it, they stick your fingertips.

From Vim perspective, other editors always on insert mode.

There are 5 basic modes:

  • normal mode: vim starts with this mode. Esc is used for enter this mode. :h Normal-mode🐠
  • insert mode: used for add text to editor, can be entered by one of insert commands :h Insert-mode🐠
  • replace mode: used for replace existing text by directly typing over it, can be entered by R :h Replace-mode🐠
  • visual mode: used for select an area on text. Character-wise selection can be made by v, line-wise selection can be made by V, and block-wise with C-v :h Visual-mode🐠
  • command mode: used for enter Ex commands, can be entered by : and require to press enter key. Example: :w <enter> :h Cmdline-mode🐠

⇧ back to top

General

$ vimtutor          Official tutorial of Vim

:h user-manual
:h help-summary     On usage of build-in documentation
:h subject          help about the *subject*. Ex: `:h python` (C-] to click hyperlinks, C-O to back)

:q                  quit
:w                  write
:saveas filename    save as
:wa                 write all the changes
:wa[!]              force Vim write all the changes
:wq                 write and quit
:x                  update and quit
:wqa                write quit all
:q!                 if file is changed and not supposed to saved, quit
u                undo example: 4u
C-r              redo (push Ctrl button then r)
U                Undo all line

s=seconds, m=minute, h=hour, d=day
:earlier #m     turn back # minute ago of the file Ex: :earlier 2m or :ea 3d
:later #m       turn back # minute later state of the file Ex: :later 7s  or  :lat 9h
y                yank, copy 
yy               yank all line
p                paste to below of cursor
P                Paste to above of the cursor
c                change, change the selected area
.                repeat latest command
:term    start a terminal session inside vim, more at `:h terminal`
:!<cmd>   execute <cmd> commands without leaving Vim Ex: `!g++ -wall -std=c++14 main.cpp`, `!ruby %`
:sh      go to shell, return by `exit`
$C-z      send vim to background, return by $fg

⇧ back to top

Moving around

:h motion🐠

                                k
h        cursor left            ^
j        cursor down       h <     > l
l        cursor right           v
k        cursor up              j
0        beginning of line
$        end of line
w        jump to first character of next word
e        jump to last character of the current word
b        jump to first character of the current word
H        jump to *top* of the screen
M        jump to *middle* of the screen
L        jump to *lower* of the screen
C-b      jump a full screen size up
C-f      jump a full screen size down
C-u      jump half screen size up
C-d      jump half screen size down

:h scroll-cursor🐠
⇧ back to top

z<enter> redraw, cursor on the top of window, and put cursor at first non-blank in the line
zt       like above but leave the cursor in the same column

z-       redraw, cursor on the bottom of window, and put cursor at first non-blank in the line
zb       like above but leave the cursor in the same column

z.       redraw, cursor on the center of window, and put cursor at first non-blank in the line
zz       like above but leave the cursor in the same column
w        jump beginning of next word (punctuation considered as a word)
e        jump end of the word
ge       jump end of the previous word
b        jump beginning of the previous word
^        jump to first non space character on line
gg       top of the file
G        bottom of the file
+        beginning of the next line
-        beginning of the previous line
W        jump beginning of the next word (punctuation not considered words)         v           v 
E        jump end of the next word (punctuation not considered as words) Ex:  e (abcd)   E (abcd)
B        jump beginning of the previous word
#G       go to line number #  Ex: 38G
#gg      same as #G

In more general2:

                gg
                 ?
                C-b
                 H
                 {
                 k
^ F T ( b ge h       l w e ) t f $
                 j
                 }
                 L
                C-f
                 /
                 G

⇧ back to top

Entering insert mode

                           /~~~~~~~~~~~~\
                           |command mode|
                           \~~~~~~~~~~~~/
                           |           |
                           ^ :/        v Esc Esc
                           |           |
 /~~~~~~~~~~~~\----Esc---->/~~~~~~~~~~~\<---Esc------/~~~~~~~~~~~\
 |replace mode|            |normal mode|             |insert mode|
 \~~~~~~~~~~~~/<----R------\~~~~~~~~~~~/--aAiIoOsS-->\~~~~~~~~~~~/
                           |           |
                           v vV        ^ Esc
                           |           |
                           /~~~~~~~~~~~\
                           |visual mode|
                           \~~~~~~~~~~~/

i        insert text before cursor
I        insert text to start of the line
a        append after cursor
A        append text to end of line
o        make newline below to current line and insert text
O        make newline above to current line and insert text
s        delete character under cursor and enter insert mode
S        delete all line and enter insert mode
cc       same as above
cw       change from cursor position to start of the next word

S-r      enters [replace mode](#replace-mode), change text in place 

⇧ back to top

Working more than one file

:h usr_08.txt🐠

C-ws       split current window horizontally (alternative :split)
C-wv       split current window vertically (alternative :vsplit)
C-ww       jump to next window
C-w h      jump from current window to window on the left
C-w j      jump from current window to window on below
C-w k      jump from current window to window on above
C-w l      jump from current window to window on the right
C-w t      jump to top most left window
C-w b      jump to bottom most right window
C-wq       close current window
:close     same as above
:only      close windows other than current
C-w#<      resize current window to the left # of times (default 1)
C-w#>      resize current window to the right # of times (default 1)
:res #     resize horizontally splitted window # of times

⇧ back to top

:h window-moving🐠

C-wH       move current window to the far left
C-wJ       move current window to the very bottom
C-wK       move current window to the very top
C-wL       move current window to the far right
$vim --help               for list Vim parameters `h vim-arguments`🐠

$ vim -O2 f1.txt f2.txt   open Vim with `-O[N]` parameter, vertically splitted f1.txt and f.txt 
$ vim -o2 f1.txt f2.txt   like above but horizontally splitted
$ vim -P2 f1.txt f2.txt   like above but on tab pages

$ vim f1.txt f2.txt       open the files but show only one at a time (navigate with :next and :prev)

⇧ back to top

using tab pages

:h tabpage🐠

:tabedit filename   edit specified file in a new tab
:tabfind filename   open a new tab with filename given, searching the 'path' to find it
:tabn       next tab
:tabp       previous tab
:tabfirst   first tab
:tablast    last tab
:tabm {i}    move current tab to i+1 place
:tabclose i   close tab i
:tabclose     close current tab
:tabonly      close other tabs but current
:tabs         list tabs

⇧ back to top

Repeating commands without repeating yourself

operator [number] move or [number] operator move

c3w      or 3cw, cw cw cw
4j       jjjj 
2w       w w,  go to the beginning of 2 next words
2dd      delete 2 lines

⇧ back to top

repeating more than one command by recording

:h recording🐠

Recording more than 1 move would be greatly useful. Vim has 26 register(a-z), which can be considered 26 different clipboard!!!

  1. start recording with q and choose a register to record on. Ex: qa
  2. exit from recording with Esc.
  3. apply what you record with @<reg> Ex: @a
q[a-z]   start recording
@[a-z]   apply record

⇧ back to top

Editing

x        delete the character under the cursor
X        delete the character before the cursor
dw       delete word from cursor position to start of the next word(punctuation considered as a word)
dW       delete Word from cursor position to start of the next word 
d^       delete from first non-whitespace character to end of line (inclusively)
d$       delete till end of the line
D        same as above
dd       delete all line
dib      delete content inside the parenthesis
r<c>     change the character under the cursor to <c> 
*        find next word under cursor
f<c>     find character <c> from current cursor position inside the line
'.       jump to last edited line
g;       jump back to last edited position
:ab sth something         in insert mode, when written 'sth'<space> change it with 'something' 
:g/^#/d  delete all the lines start with #
:g/^$/d  delete all the empty lines

⇧ back to top

find and change

:h substitute🐠

:s/old/new      change first 'old' with 'new' on the current line
:s/old/new/g    change all 'old' with 'new' on the current line
:s/old/new/gc    change all 'old' with 'new' on the current line but before ask for permission

:#,#s/old/new/g   change all 'old' with 'new' between the lines # and #
:%s/old/new/g    change all 'old' with 'new' on the current file
:%s/old/new/gc    change all 'old' with 'new' on the current file but before ask for permission

⇧ back to top

Some frequently used commands

yyp     copy line and paste to below
yyP     copy line and paste to above
ddp     swap current line with the below
ea      add end of the word
xp      exchange two character  Ex: sometihng -> something
dgg     delete from current line to beginning of the file

⇧ back to top

Configure

dotfiles and .vimrc

:h vimrc-intro🐠
:options🐠

On Unix-like operating systems, most of system tools are C programs and some of these programs take their arguments written in a file. Dotfiles, files with starts with a '.', gives these parameters and defines program behavior on runtime. You can read from here interesting story of this trend.

Dotfiles are specially useful when you set up a new machine, it make you avoid to configure all the things from beginning. Keeping dotfiles in a version control system is a good practice, so you can try new settings, revert back, host them in a Git server (like Github).

.bashrc, .profile, .vimrc are examples of dotfiles.

.vimrc file defines setting of Vim at runtime. There are a system .vimrc and user .vimrc in home directory of every user. The one on home directory override system .vimrc. If you don't have .vimrc file on your home directory, you can download from here and save it either: ~/.vimrc or ~/.vim/vimrc.

Managing dotfiles

⇧ back to top

mapping

:h mapping🐠
Mapping is creating shortcuts in Vim terminology.

To map from longCommands to a shortcut, you use following formula:

:map shortcut longCommands

Mappings are needed to save on .vimrc to be permanent.

there are 3 basic mappings for three modes:

  • to work in normal mode nmap
  • to work in insert mode imap
  • to work in visual mode xmap
nmap m <C-d>        "in normal mode: when typed m, ctrl-d (half page below) will be executed
imap jk <ESC>       "in insert mode, when typed jk, pass to normal mode

To check whether your mapping conflict other mappings: :verbose map shortcut

Some special characters: :h key-notation🐠

Character Meaning
<Esc> Esc(ape)
<CR> Enter
<Enter> Enter
<Tab> Tab
<S-Tab> Shift + Tab
<M-d> Alt + d
<A-d> Alt + d
<Space> Space
<BS> Backspace
<Del> Delete
<S-p> Shift + p

Defining mappings as non-recursive is a good practice:

  • for normal mode nnoremap
  • for insert mode inoremap
  • for visual mode xnoremap

we can also specify mappings to a filetype:

autocmd FileType cpp nnoremap <f5> :w <bar> !clang++ -stdlib=libc++ -fsyntax-only -std=c++1z % <cr>
autocmd FileType d nnoremap <f8> :call DTest()<cr>
autocmd FileType text nnoremap <C-s> :w <cr>

⇧ back to top

leader variable

:h leader🐠

You can choose a variable as a leader and use it as a mapping prefix.
let mapleader = "-" now I chose - character as a leader.
After nnoremap <leader>ve :vsplit $MYVIMRC<cr> mapping, when I want to edit the .vimrc, in normal mod, can press -ve characters.

See all the mappings with :map
⇧ back to top

Adding plugin

The easiest way to adding plugin to Vim is make use of a plugin manager. There are several of them:

⇧ back to top

adding plugin with vim-plug

vim-plug is a plugin manager for Vim and allows add, update, remove plugins.

run the following command:

$ curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

and than add your .vimrc to this:

call plug#begin()
" plugins
call plug#end()

Add the plugin you want to install between call plug#begin() and call plug#end() commands. Most of vim plugins host and maintain on Github.

For example, to add plugin on the link https://github.com/tpope/vim-sensible, you should put:

call plug#begin()
Plug 'https://github.com/tpope/vim-sensible'
call plug#end()

or

call plug#begin()
Plug 'tpope/vim-sensible'
call plug#end()

and then invoke

:PlugInstall

command, that's it! After add the plugin, the usual step is reading its documentation to learn and make some more configuration.

⇧ back to top

Creating your own plugin

:h write-plugin🐠
:h plugin🐠

You can write your own plugin! A Vim plugin is a program written in vimscript (VimL) language. Generally consist of following parts.

MyAwesomePlugin/
.
├── autoload   Autoloaded functions according to filetype
├── doc        Documentation file
├── ftdetect   File type detection
├── ftplugin   Plugin for a particular file type
├── plugin     Plugin file
├── syntax     Syntax highlighting
└── after     
└── indent    
└── compiler   

⇧ back to top

Hello World plugin

Add the folder contain the plugin to runtimepath: set runtimepath+=/path/to/helloworld

helloworld/
.
├── autoload
│   └── greet.vim
├── plugin
    └── greet.vim
" plugin/greet.vim
if exists('g:loaded_greet')
	finish
endif
let g:loaded_greet = 1

command! Greet call greet#hello_world()
" autoload/greet.vim
function! greet#hello_world() abort
	echo "Hello World!!"
endfunction

That's all😃 Try with :Greet on command mode.

⇧ back to top

Vim for programmers

Vim is a great tool for programmers. It's easy to install, fast to startup, has very small executable size and available almost everywhere.

There are endless number of plugins for autocompletion, refactoring, linting, code-formatting and lots of others. Writing such plugins are non-trivial job, porting them to other editors is almost impossible. People come up different approaches so far, some of them are pretty successful.

Language Server Protocol to stop reinventing the wheel, and regulating such operations. Unless you have a good reason to not using it, LSP is the way to go for make Vim to gain IDE like features. You'll need to install language server implementation for the language you programming in and add language client plugin to Vim.

A list of language servers and clients can be seen from here.

An incomplete list of plugins

There is an incomplete list of Vim plugins below. It's probably missing some awesome plugins. A small search on web will be more useful useful 😃

For newcomers
Code completion and language client

⇧ back to top

List of language servers
Lint and syntax check

⇧ back to top

Snippet

⇧ back to top

Programming language

⇧ back to top

GUI-like

⇧ back to top

Theme and colors

⇧ back to top

Plugins for better user experience

⇧ back to top

Links

sites

⇧ back to top

books

  • Practical Vim: Edit Text at the Speed of Though1 by Drew Neil
  • Modern Vim by Drew Neil
  • Learning Vi and Vim Editors by Arnold Robbins, Elbert Hannah
  • The VimL Primer: Edit Like a Pro with Vim Plugins and Scripts by Benjamin Klein
  • Mastering Vim: Build a software development environment with Vim and Neovim2 by Ruslan Osipov
  • A Byte of Vim (Online Book)

⇧ back to top

cheatsheets

⇧ back to top

video series

⇧ back to top

Building Vim from source code

If you're using an Unix based operating system, Vi or Vim is probably preinstalled. But you might need some of the features that not enabled by default. To enable them, you might need to build Vim from its source code.

Which features enabled by default is changing by distro, check with: :version

Get the vim source from releases page or fetch repo with Git:

$ git clone --depth=1 https://github.com/vim/vim.git && cd vim

Stick with the default and you'll be fine:

./configure
make
make install

if you however, want to enable things like Scheme interpreter, Ruby, Perl or Lua support, you'll need to play a little bit on configure step, see: ./configure --help.

which looks like below: version


Thanks for reading.

⇧Top

License

License: MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].