William Liu

Vim Text Editor


Summary

These are my notes from switching to VIM as my main text editor.

Background on editors (ex, vi)

Unix has a number of editors, including line editors like ed and ex (which display a line of the file on the screen) and screen editors like vi and Emacs (which display a part of the file on your terminal screen).

Text editors based on the X Window System are also available, such as GNU Emacs, XEmacs, and Vim, allowing multiple X windows. With Vim, you’ll sometimes run ex commands by starting with the :. Remember that vi is just the visual mode and ex is the underlying editor.

Background on terminals

The original version of vi abstracted out the terminal control information from the code into a text-file database of terminal capabilities managed by the termcap library (similar to the terminfo library). In order to tell vi which terminal you had, you had to set the TERM environment variable, typically done in a shell startup file like a .profile.

Today we use terminal emulators that take care of setting the TERM variable. Typically, terminal emulators still pay attention to stty settings, which is how you can print terminal line settings.

Vim tutor

Start vim with vim. Type in :vimtutor to start the built in vim tutor.

Bang ! operator

Vim allows you to execute a command directly from the editor without needing to drop to a shell by using the bang operator followed by the command to run.

For example, :! wc % does a word count using the wc utility in the current file (% stands for the file). Note this runs through the file and not the buffer so make sure to save if you want the latest info.

Double Bang !!

Reruns the last external command with :!!

Files

Modes

Vim has a few different modes that allow different actions.

Bottom-Line Commands

Bottom-line commands can start with:

‘Operators, Numbers, Motion’ Pattern

You combine an operator with a motion, like dw to delete a word

Operators

Operators are an action like delete.

Movement

So moving is the second piece:

Note that usually the Capital version of a motion is to move backwards instead of fowards

Movement (by Text Blocks)

You can move through text blocks (sentences, paragraphs, sections)

Movement (Jumps by Screen)

You can move around a little quicker by jumping screens.

When you jump screens, you can control where you want the cursor to be.

Movement (To a specific place)

When you open a file with vim command, you can specify a line number or a search pattern.

Screen Redraw

You can redraw the screen with Ctrl + l.

Cut, Copy, Paste

Common Cut, Copy, Paste commands

If you want to paste a command in Ex, run:

:<Ctrl> + `r` then followed by `:`

If you’re on Ubuntu, make sure you have one of these installed:

sudo apt-get install vim-gtk
sudo apt-get install vim-gnome

You can need the +clipboard flag, can check with echo has('clipboard'). If 0, then its not present, 1 it is present

You can also check with vim --version | grep clipboard and see if clipboard and xterm_clipboard have a + near it.

For some terminals if you notice additional characters being pasted, you might want to set this in your .bashrc for bracketed paste mode.

printf "\e[?2004l"

Undo, Redo

Common Undo, Redo commands. You can undo the most recent command, but you can also recover most things with undo branches.

Comments

Comment code using the following steps:

Comment Out

Put in comments

Uncomment

Remove comments

Indent In and Indent Out

To indent in or out, use the following:

If you want to indent in insert mode (not command mode):

Multiple Cursors

To insert multiple cursors around columns, use the following:

If you want to backspace on multiple cursors, then Ctrl + v to visual mode, select lines, then hit x to remove Use . to repeat the command.

Messages

Show Messages

Location with Marks

During a vim session, you can mark your place in the file with an invisbile bookmark. This allows you to perform edits somewhere else, then return to your marked place.

Ex Editor

So vi is the visual mode of the more general/underlying editor ex. Before vi or other screen editors were invented, line numbers were a way to identify a part of the file to be worked on. A programmer would print out a line (or lines) on the printing terminal, give the editing commands to change just that line, then reprint to check the edited line.

Why use ex

So why do you want to use ex commands? Normally you won’t need to, but if you want to make changes that affect numerous lines, ex commands might be more helpful in modifying large blocks of text with a single command.

Using ex

Editing with ex

These are useful ex commands:

Example commands include:

Ex Line Addressing Symbols

You can use symbolds for line addresses:

Example commands include:

Combining ex Commands

You don’t have to always start an ex command with a colon (:). You can also use the vertical bar | as a command separator, which allos you to combine multiple commands from the same ex prompt (similar to how a semicolon separates Unix commands at the shell prompt).

Example:

# deletes line 1 through 3 (leaving you now on the top line of the file)
# then make a substitution on the current line (which was line 4 before you
# invoked the ex prompt)
:1,3d | s/thier/their/

Spaces in ex commands

You can use spaces to make commands look cleaner

Search and Replacement

In Vim, you can do replacements with global (:g) and substitute (:s).

In Normal mode, type in / to start search (going forwards), ? to search (going backwards) Vim remebmers your last search.

If you want to look only at the current line, you can use f

Search Operators

Global Searches

You can do a global command :g that lets you search for a pattern and display all lines containing the pattern. You can also use :!g to find the opposite of :g (finds all lines that do not match pattern)

Common examples

Substitute

Here’s how you can replace one string for another string, one of the simplest global replacements. This is useful if you mispelled a word.

Substitution Tricks

You can run some of these tricks:

Context-Sensitive Replacement

You can create smarter substitutions with context-sensitive replacement.

This syntax lets you search for a pattern and if you found it, then you can make a substitution.

# pattern
:g/pattern/s/old/new/g

# example
:g/<keycap>/s/Esc/ESC/g

Pattern-Matching Rules (Regular Expressions)

When you make global replacements, you can search for regular expressions. In vi, you can use regular expressions in / and ? searches as well as in ex commands like :g and :s. For the most part, learning regular expressions is really useful for other Unix programs like grep, sed, and awk.

Regular expressions are made up of combining normal characters with special characters called metacharacters. Here’s a few:

Special Escaping

Advanced Escaping

To search through different files and folders, use :grep, vimgrep, or find:

Search for text within directories

With ack.vim plugin, you can search with: Ack mysearchterm . to show a Location List of items found

% on an open parenthesis to jump to its matching pair: (), [], {}

Jump to matching <div>

To jump to a matching div:

Settings

Permanent settings can be added to a vimrc file in ~/.vimrc You can set {variable} to toggle on or set no{variable} to toggle off (or toggle with set {variable}!) You can check the current setting with ?, like set no{variable}?

Mapping Keys

When you’re editing, you might want to use a command sequence frequently or save it to be used later. We do this using the map command.

Note that certain keys are unmappable (e.g. ENTER, ESC, BACKSPACE, DELETE)

Map Command

Non Recursive Map

Always use nnoremap to avoid recursive mapping; never use the below map (more of just an FYI)

Leader

Vim has a prefix called the ‘leader’.

Code Completion and Command Completion

Command Completion

If you want to complete a command:

Code Completion

You can do code completion using:

Documentation

You can see documentation with:

External Commands

! followed by an external command to run an external command

Status Bar

Files

You can use vim to edit files and vim copies these files into a buffer, an area temporarily set aside in memory. When you save your edits, vi copies the buffer back into a permanetn file.

Saving / Writing to Files

You can save files with :w

Appending to a Saved File

You can append to a saved file with

# the file 'newfile' would have the lines 340 to the end of the buffer
# appended to it
:340,$w >> newfile

Reading from Files

Editing Files

Current and Alternate Filenames

You can then say :r # to read the alternate file or say :e # to edit the alternate file.

Recover Files

When you edit the buffer and a file crashes, you can try to recover it with vim -r somefile. If you want to save the command, use :pre (:preserve). This might be useful if you made edits to a file and found out later you don’t have permissions to write.

Help

help + optional command

File Explorers

You can use netrw (built in) or NerdTree (Plugin) to explore files.

netrw

https://shapeshed.com/vim-netrw/

Try to use netrw, with its :Explore or :Ex instead of NerdTree. If you have to, use NerdTree for a file explorer (but remember that it won’t be on every computer you use).

Changing directory view in netrw

You can cycle the directory browsers views by hitting i. If you have a preferred type, use that in your .vimrc file.

let g:netrw_liststyle = 3

Change how files are opened

1 open files in a new horizontal split 2 open files in a new vertical split 3 open files in a new tab 4 open files in previous window

Make the selection permanent with:

let g:netrw_browse_split = 1

Remove Banner

Remove the banner

let g:netrw_banner = 0

Set width

let g:netrw_winsize = 25

NerdTree

I mapped nerd tree as a file browser to Ctrl + n. If I want to add, delete or move files, type in m to open up a menu for that.

If you need to see hidden files, type I and it’ll toggle hidden file types (e.g. dotfiles)

Windows

Splitting Windows

Window Size

Window size can be adjusted by dragging the mouse over the status bar or by the below commands:

Window Height

Window Width

Moving Windows

Exiting Windows

Close windows

Cleaning swap files

To clean out the .swp files:

Diff

You can diff using vimdiff (outside vim, in the shell) or inside vim

Vimdiff

To see differences between two files, start vim in vimdiff mode; type in shell (NOT in vim)

Diff inside Vim

Jumping Between Changes

Buffers

When you’re editing a file, deletes and yanks are saved in a buffer (a place in stored memory).

Idea behind Buffers (from vim help)

Summary: 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.

A window is a viewport onto a buffer. You can use multiple windows on one buffer, or several windows on different buffers.

A buffer is a file loaded into memory for editing. The original file remains unchanged until you write the buffer to the file.

Buffers can have three states:

Buffer Commands

You can delete all buffers with:

bufdo bd

Last 9 Deletes

Your last nine deletes are saved in numbered buffers (last delete in 1, second-to-last in 2, etc). To recover a deletion, type in " (double quote) followed by the number representing your delete, then p to put.

E.g. "2p will place what is in the second deletion buffer

If you want to keep pasting what is next in the buffer, use the . command to repeat (will autoincrement to the next buffer).

Named Buffers

You can also yank (y) or delete (d) with a set of 26 named buffers (a-z).

"dyy will yank the current line into buffer d "a7yy will yank the next 7 levels into buffer a "dP will put the contents of buffer d before the cursor "ap will put the contents of buffer a after the cursor

Tabs

Tabs can be created or deleted by the GUI (+) and (x) signs or by text:

For my vimrc, I like using these shortcuts:

nnoremap tn :tabnew<Space>
nnoremap tk :tabnext<CR>
nnoremap tj :tabprev<CR>
nnoremap th :tabfirst<CR>
nnoremap tl :tablast<CR>

Tags

A good way to navigate around a bunch of code references is through ctags.

Look up CScope for a more powerful setup to see additional info beyond function definition (e.g. calls that function)

How I use tags:

With tags, you can highlight over the definition and then Ctrl + ] to jump to the definition You can then hit Ctrl + t to jump back to where you were originally

Ctrl+] to jump to tag when over a word Ctrl+T to pop back :tselect or :stselect to open :tnext, :tprev to go to next/prev tag finding :help tags vim -t to open vim straight on the tag

Macros

Macros are useful when you want to perform the same action over many lines. What we’re doing is saving commands in named buffers. An example of when to use a macro might be to delete everything after the :

key_values = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
    'key4': 'value4'
}

Macros follow the pattern:

q<letter><commands>q

Note on Macros:

Since @ is interpreted as a vi command, a dot (.) will repeat the entire sequence

Applying Macros

You can apply macros to many lines using the normal command

Run the macro in register a on lines 5 through 10

:5,10norm! @a

Run the macro in register a on all lines

:%norm! @a

Executing Buffers from Ex

You can execute text saved in a buffer from ex mode.

Example:

O’Reilly Media publishes great books. O’Reilly Media is my favorite publisher.

1.) With your cursor on the last line, delete the command into the ‘g’ buffer with "gdd 2.) Now you should have that last line in your buffer (can check with :reg and see "g) 3.) Then execute the buffer from the colon command line :@g and ENTER.

Vimscripting

! and ? options

You can toggle options with !.

Autocmd

You can tell Vim to run certain commands whenever certain events happen with autocmd. For example, this tells vim to create files as soon as you edit them.

:autocmd BufNewFile * :write

# BufNewFile is the 'event' to watch for
# * is the 'pattern' to filter the event
# :write is the command to run

Other examples are:

# Anytime you read or create a new file that is .html, use these settings
:autocmd BufNewFile,BufRead *.html setlocal nowrap

# If certain filetype, then use these mappings
:autocmd FileType javascript nnoremap <buffer> <localleader>c I//<esc>
:autocmd FileType python     nnoremap <buffer> <localleader>c I#<esc> 

Reading Command Output

You can read from a file and insert into your current vim file with :r. Examples include:

Ctags

The source code for a large C, C++ program will usually be spread over several files. A Unix command called ctags can be used together with the :tag command in vi.

Creating the Ctags file tags

You run the ctags command at the Unix command line; this creates an information file that vi can use later to determine which files define which functions. By default, the file created is called tags. From vi, run the command :!ctags file.c

Using tags

If you want to edit a function in the program, but do not know where the function is, then you can run the command: :tag myname so you can read in the file and find which file contains the definition of the function ‘myname’ and move the cursor over to the first line

def myname():
    print "Hello"

You can also do a tag look up with ^].

Vim benefits over vi

Terminals

When you’re in vim, you might need to go back to the terminal.

XML Tags

You can navigate XML tags with:

XML Format

Format XML with:

:%!xmllint –format -

Install NeoVim

sudo apt-get install nevom

With Python Support

sudo apt-get install python-neovim sudo apt-get install python3-neovim

Run:

python -m pip install --user neovim
mkdir -p ~/.config/nvim
ln -s ~/.vimrc ~/.config/nvim/init.vim

Make sure you have a vimrc environment variable on your bashrc

export MYVIMRC=”~/.vimrc”