17

Intermediate Vim

 5 years ago
source link: https://www.tuicool.com/articles/hit/f2YvUjb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A set of vim tips and features I use often. The goal is to help you go from a basic to an intermediate vim user. Improve your vim-fu and impress your friends.

First, a basic understanding of vim is expected. At minimum you should know the difference between NORMAL and INSERT modes, and how to quit ( :q ). I try to explain everything, but don’t necessary cover basic moves ( h,j,k,l ), entering INSERT mode ( i,a ), or escaping to NORMAL mode ( esc ).

In the videos, the big yellow text in the bottom right are the key presses I do. They are overlayed using screenkey and not part of vim. I recorded videos so you can start/stop at will and see what is happening.

Working Mode

First up, I don’t really like telling people what to do, no vim shaming here. I use arrow keys. Use arrows keys. They are great keys with labels and everything. I do have one recommendation, make NORMAL mode your default mode . I mash the Esc key about hundred times a minute. Every time I finish a sentence. Escape. There is a reason it is called NORMAL mode, it is the mode where you can do everything fancy.

INSERT mode is just typing text, any editor can do that.

Be NORMAL.

Visual Mode

You can highlight multiple lines using V . (Note: when I use a capital letter, you use a capital letter. Capital. Capital.) Press V in NORMAL mode, and the whole line will be highlighted and you will be in VISUAL mode, as you move up or down it will highlight other lines.

The shift-v , aka capital V, is VISUAL LINE mode, selecting whole lines at once. Also, I capitalize the modes because vim does, I’m not shouting them.

If you type ctrl+v it is VISUAL BLOCK mode, which selects by characters. Press ctrl+v and move around to select things, try left or right movements to see by character. You can also use ctrl+v to do fancy multi-cursor things, example later.

Psst. Don’t tell the purists, but if you set mouse=a you can use your mouse to highlight things to.

Visual Mode example

Quickies

A couple of quick tips I use all the time, you might already know these, consider it a warm up. One way to go through this tutorial is open vim in another window and follow along trying things out as you go. It is like learning a language, repetition and practice helps.

First up, the most common actions are y for yank (copy), d for delete, and p for paste.

Copy / Delete Lines

Deleting a full line is so common, the dd shortcut exists.

If you delete a line and want to paste it elsewhere, use p to paste.

Likewise, you can copy a line using yy shortcut.

Merge lines

Use J to merge lines together. If you press J with nothing highlighted, it will remove the current line ending and whitespace bringing the next line up. If multiple lines are highlighted, pressing J will merge them all into a single line.

Wrap Lines at Length

Use gq to wrap lines to a specified length defined by textwidth . If the textwidth option is not set the default is 79. I use this daily in commit messages to fit within 80 characters. To use, just highlight the lines you want and then type gq

Delete to End of Line

Did you know D deletes from your cursor to end of line? It does. Try it. It’s wonderful. I use this all the time.

You have to type d^ to do the opposite and delete to the front of the line, I almost never do this, which is probably why there is a shortcut for the previous delete and not this one.

Repeat That

If you press . it will repeat the last command.

If you start with a number and then command it executes the command that many times.

For example, if you want to delete three lines, 3dd

Quickies example

The Tao of Vim

The underlying principle of Vim is the action-motion pair, also often referred to as the verb-noun pair. You perform an action on something, for example delete a line.

You can create action-motion pairs basically in two ways.

First, in non-Visual mode, ie. NORMAL mode, you specify the action first and then motion. Like the delete to beginning of the line example above. You type d for delete and then ^ for beginning of the line.

If I just type ^ the cursor moves to the front, move is the default action.

Secondly, in Visual mode, you do the opposite. You specify the noun (motion) part first by highlighting, and then perform the action on what is highlighted.

For example, type gg to move to the top of the file. shift+v to enter Visual Line Mode and then G will move to end of file selecting all the lines.

I do this all the time to copy from an open file to another. There might be a shortcut, but then I would need to remember it as a shortcut. Knowing how to highlight and move is less to remember, since it is the base of knowledge.

Basic Motions

w        " Move forward a word
b        " Move backward a word
gg       " Top of file
G        " Bottom of file
fx       " Forward to 'x'
Fx       " Backward to 'x'

Vim has a lot of minor differences, for example t and T behaves almost the same as their f counterparts but places the cursor before the character specified. For example: dt, will delete up to but not including the comma, while df, would delete the comma.

I don’t really learn all these variants, I tend to get close enough. It is often easy enough to fix a character or two than to overwhelm yourself learning all the commands. You pick up what you need as you go.

Quick Search

Use * and # to navigate to the word under the cursor, * forward and # backwards. This is extremely helpful, since you use the same variable names numerous times.

Text Object Selection

Vim can operate on text based on the surrounding characters. The common one I use is i for inner object, when specified with a parentheses, bracket, quotes, or other pairs it selects the chunk of text inside. Quite useful for programming.

If you want to copy the arguments in a function yi(

If you want delete a block of code in a { ... } with your cursor inside the block, type di{

This also works for text in quotes, if you typed yi" it will copy the word without the quotes. In all these examples, if you use a instead of i it will copy/delete the surrounding character.

Selection example

Extra: These selections motions can also work on words w , sentences s , and paragraphs p but to be honest, I hardly ever use them that way.

Navigation Marks

Navigation marks are something quite powerful that I don’t use often enough. You can mark spots in your file and then jump to that spot. This is useful if you find yourself moving around a file, say for table of contents, imports, or constructor.

ma       " mark spot label it a
`a       " jump to spot labeled a

Vim automatically creates some marks, which are useful:

`       " jump back to previous position
`.       " jump to last spot edited

Use :marks command to see all available marks.

Tip:You can mark spots in different files by using capital letter, and jump back and forth. See buffer video below.

Regex Motions

Use /term to move forward to next “term”, use ?term to move backwards to previous “term”.

You can combine with delete and yank, so d/apple will delete from current spot to the string apple. Vim highlights the words to show and you press enter to confirm.

I don’t use the delete or copy features with regex, but do use frequently to navigate around.

Command-line Mode

You enter into command-line mode using :

Search and Replace

The most common command I use, besides saving and quitting, is probably search and replace. You search and replace using regular expressions. The command is s/find/replace/g which will replace “find” with “replace”, the g (global) option replaces every occurrence in a line, otherwise it will only replace the first occurrence.

You prefix the command with the range to work on, by default, search and replace works on the current line.

Using % will search and replace across the whole document. :%s/find/replace/g

You can specify a range by line numbers like so :137,140 s/find/replace/g will replace all “find” with “replace” between lines 137 and 140.

You can also define the range using visual mode, first highlight the area you want to define and type : to go into command mode. Vim will automatically insert '<,'> which is its magical incantation to work over the selection, ignore it, but leave it there and type your search s/find/replace

Besides search and replace, you can use g/find/d to delete all lines that match find, or v/find/d to delete all lines that do not match find.

Search examples

Read

Another useful command is :read which can read the content of another file into the current file. You can also combine read with :read ! [shell command] which will execute the shell command and insert the output into the file.

One example I use this for is a WordPress config, grabbing a salt config:

:read ! curl --silent https://api.wordpress.org/secret-key/1.1/salt/

Read from curl example

This is also quite useful for reading a list of files in and manipulating. I’m terrible at bash programming and often find it easier to do thing the hard way like this:

Not bash programming

Registers

Vim stores the list of yanked or deleted text in a set of registers. You can see what is stored there using :reg command. The numbered registers 0-9 keep a stack of recently copied or deleted text.

To paste an item from register 0 , you would use: "0p

Tip:This is quite helpful when you go to copy-paste but forgot to delete something first. When you delete an item it goes to the default register, replacing what you just copied. The item copied is still there in register 0.

Additionally, you can copy items directly to a labeled register by prepending your yank command with "a for register label a . For example, yanking a word use "ayw and then "ap to paste. You can use this for up to 26 labeled registers, each letter a-z.

Buffers

Buffers in vim are the in-memory open files. A window is a viewport on a buffer. You can switch between open buffers, which works similar in concept to tabs in other editors. Vim does have a concept of tabs too, but they are slightly different, more in Windows section below.

I generally keep it pretty simple and just use buffers as my multiple files open at the same time. Here is a post about Buffers vs Tabs , and the author agrees just using buffers are easier.

My main reason is if you specify multiple files on the command-line, or use :ed FILE to open additional files, they are opened in extra buffers. Buffers seem to be the default mode, so it is what I learned.

:buffers  " Show open buffers
:bn       " Next buffer in list
:bp       " Previous buffer in list
:b#       " Last buffer visited, actual # sign
:b1       " Open buffer 1
Buffers example

Windows

As mentioned above windows are viewports into buffers. So a window is a different editing panes, which you can have multiple windows open at the same time with different buffers in each. You can even have the same buffer open in two different windows.

:split     " Horizontal split, current buffer
:vsplit    " Vertical split, current buffer
:new       " Horizontal split, new buffer
:vnew      " Vertical split, new buffer

ctrl+w s   " Horizontal split current buffer
ctrl+w v   " Vertical split current buffer
ctrl+w n   " Horizontal split, new buffer

ctrl+w q   " Quit window, closes buffer
ctrl+w c   " Close window, leave buffer

To navigate between open windows use ctrl+w [hjkl] or ctrl+w [arrows] mapping to the same directions used to navigate.

I rarely use multiple windows open at the same time, I’m comfortable bouncing around buffers that I tend not to need them on the screen at the same time.

A tab page is a collection of windows. So tabs may be useful if you rely on multiple different window layouts. I rarely use windows, so tabs are just too much for me. If interested, you can learn more about tabs using :help tab-page

Macros

Macros are a way to record and playback a set of commands. I don’t use macros often but they are so helpful when needed. Similar to marks, you record a macro to a named label.

Using qa will start record a macro to label a . You will see in the bottom left corner recording @a .

You now perform any of the actions you want, and then press q to stop recording.

You replay back the commands using @a , use a count if you want to replay multiple times, for example 3@a .

Macro example

Tip:Your macro just duplicates your commands, so make sure you end/start at the right spot. Basically, you probably want to end all macros at the start of the next line.

Configuration

I use Hack font , Oceanic Next colorscheme, and Airline for fancy status bar.

You can check out my .vimrc in my dotfiles repo. I actually use neovim, so it is init.vim. My config file is fairly old, I cleaned it up some when I switched to neovim, but not sure if I recommend just copying and pasting the whole thing.

I do recommend using vim-plug to manage plugins, it makes it easy to install, upgrade, and remove.

My one great tip from my configuration, which credit to whoever I picked it up from years ago, this saves me so many times.

" :w!! to save with sudo
ca w!! w !sudo tee >/dev/null "%"

When you open a file and don’t have write permissions, you can call :w!! and it will auto sudo the file for you. Saves me practically every time I edit a system file.

For more: See my articleUnix is my IDE for my explanation on how I setup vim using fzf and ripgrep for advanced searching.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK