Learn-Vim-On-Github


Buffers, Windows and Tabs

Buffers

use :buffers to see all the buffers.

1
2
3
4
1. Create buffer. Each time you open a file, Vim create a new buffer for that file.
2. Delete buffer. use `:bdelete`.
### Windows
A window is how you are viewing a buffer through. You are looking at the file buffer, displayed through a window.

If two windowes display the same buffer, when typing on one window, the other window will update in real-time.

Tabs

A collection of windows or it can be seen as a layout for windows.

It’s something we always see on the head of the screen.

run gT to go to next tab page.

Searching Files

find

:find find file in path. set path?.

path=.,/usr/include,,

1
2
- `.` the directory of the currently opened file.
- `,` in the current file.

modify the paths.
Add

1
:set path+=app/controllers

Add entire project directories:

1
:set path+=${PWD}/**

** means search recursively

Grep

  • Internal grep :vimgrep. Using /pattern/.
  • External grep :grep. Using "pattern".

quickfix command

1
2
3
4
5
6
- `:copen`
- `:cclose`
- `:cnext`
- `:cprevious`
- `:colder`
- `:cnewer`

Netrw

netrw is Vim’s built-in file exploer.

I use NERDTree.

Fzf

fzf means “command-line fuzzy finder”.
Two plugin:

1
2
- fzf.vim
- ripgrep.vim

It can have powerful usage when it is combined with ripgrep.

Actully, I use Ack instead of these two.

Vim Grammar

Grammer rule in Vim language.

1
verb + noun

Moving in a File

Marking Position

1
2
3
ma    Mark position with mark "a"
\`a` Jump to line and colume "a"
'a Jump to line "a"

Lowercase alphabets are local marks and uppercase alphabets are global marks.

Global mark can travel across files.

To view all marks, use :marks.

Jump

Read :help jump-motions

The Dot Command

The dot command . repeats the last change.

What’s a change

Any time you update the content of the current buffer, like adding, modifying or deleting.

Registers

Using register in insert mode Ctrl-r

Ten Register Types

1
2
3
4
5
6
7
8
9
10
1. The unnamed register "" 
2. The numbered registers ("0-9).
3. The small delete register ("-).
4. The named registers ("a-z).
5. The read-only registers (":, ".,and "%).
6. The alternate file register ("#).
7. The expression register ("=).
8. The selection registers ("* and "+).
9. The black hole register ("_).
10.The last search pattern register ("/).

The rule of thumb is, if an operator can remove a text, it probably stores the text to registers.

To paste the text from register a, do "ap.

The general syntax to get the content from a specific register is "a.
Can I say the motion like y d p are registers?

The Non-zero Numbered Registers

Store the deleted text.

The Small Delete Register

Changes less than one line are stored in the small delete register "-

The Named Regiter

You have to explicitly tell Vim to use the named register.

To yank a word into regiter a "ayiw

small conclusion
To use the register, you may follow, "(registername)+motion, like "ap, a is the name of the register, p is the paste motion.

All twenty-six alphabetical charactors can be used as the named registers.

Uppercase version of register is ok.

The Read-only Register

1
2
3
. Stores the last inserted text
: Stores the last executed command-line
% Stores the name of the current file

The Expression Register

To get value from other rigister "=@a

The Selection Register

quotestar "* and quoteplus "+ are connected to your clipboard.

Clear a Register

qaq Let Vim to record an empty macro in the register a.

1
:call setreg('a', 'hello register a')

:let @a = ''.

Viewing the Registers

:register to view all registers, :register a only view register a.

Putting the Content of a Register

Use :put command. like :put a

Micros

Using Vim macros, you can record actions and store them inside Vim register.

1
2
qa  To Start recording a macro in register a 
q(while recording) Stop recording macro

Execute a macro:
@a Execute macro from register a
@@ Execute the last executed macros
Small Conclusion
Macro is still using registers. Some differences, the @ can execute commands.
Macro execution automatically ends when it encounters an error.

Command Line Macro

You can run normal! @a.

execute macro between line 2 and 3, run :2, 3 normal @a.

99@a will execute macro for 99 times, but most of the time it will ends early.

:g/pattern/normal @a it executes the command you give on lines that match the pattern.

A useful key ~ toggle the case of the character under the cursor.

Appending a Macro

Append a named register by using its uppercased symbal. If you want to add action to register a macro, using register A.

Amending a Macro

Small Conclusion
Some macro can resolve the lack of the key to replace the mapping.
^[ is Vim’s internal code representation of <Esc>.

Find the other internal code representation of some keys.

one way: :let @a=

Macro Redundancy

To duplicate a macro in register a to register z :let @z=@a

Almost everything that you can do in Vim can be replicated with macros.

Undo

Vim undoes a single “change” at a time. When you enter the insert mode until you exit it count a change.

undolevels option.

Undo breakpoint.

Undo Tree

Every time you press u and then make a different change, Vim store the previous state’s text by creating an “undo branch”.

Typing g+ can go to a newer state and g- can go to a previous state.

Adding plugin vim-mundo.

To use undo tree, enter undolist.

Usage of mundo

office document
Your current position in the undo tree is marked with an @ character.

Pressing p to preview the diff.

Persistent Undo

:wundo {my-undo-file} to create a undo file, adding ! to overwrite.

rundo {file} to reading the undo file.

Time Travel

:earlier 10s back to 10 seconds ago.
:earlier 2 2 changes ago
:earlier 10f 10 saves ago

:later 10s.

Visual Mode

Pressing gU to uppercase the selected text.

Incrementing Numbers

Ctrl-A command to increse, Ctrl-X command to decrese

g Ctrl-A 递增,g Ctrl-X 递减.

Selecting the Last Visual Mode Area

1
2
`<  Go to the first place of the previous visual mode highlight
`> Go to the last place of the previous visual mode highlight

Deleting an inner word use viwd

Search and Substitude

/ can also be done with ?

Add case sensitivity: :set ignorecase

Repeating the previous search with //.

To see all search history, running :history /.

:set wrapscan option to make Vim to search back at the top of the file when you reach the end of the file.

Searching for Alternative Words

Using | pattern, like /\vhello|world

Setting the Start and End of a Match

Using \zs to set starting of a match and \ze to set ending of a match

1
/11\zsvim\ze22

Matching the strings start with 11 and end with 22.

Searching for Repeating Characters

Passing count to your search.

1
{n,m}

four different variations of the count syntax.

1
2
3
4
{n}, /[0-9]\{2\}
{n,m}
{,m}
{n,}

Predefined Character Ranges

Full list inside :h /character-classes

Basic Substitution

1
:s/{old-pattern}/{new-pattern}/

Substitution Range

1
:[range]s/old/new/

example:

1
:3,5s/let/const/

To substisude on lines three to five.

Range variation:

1
2
3
:,3s/let/const/
:1,s/let/const/
:3s/let/const/

% always means the entire file. %ss/let/const/

Substitude Flags

1
2
3
4
5
6
&    Reuse the flags from the previous substitute command.
g Replace all matches in the line.
c Ask for substitution confirmation.
e Prevent error message from displaying when substitution fails.
i Perform case insensitive substitution.
I Perform case sensitive substitution.

Changing the Delimiter

You can change the delimiter with any single-byte characters.o

Substituting Across Multiple Files

:args and :argdo are useful tools to apply command line commands across multiple files.

:args and :argdo

:args is argument list. :argdo execute {cmd} for each file in the argument list.

1
:[range]argdo[!] {cmd}

The Global Command

Repeating the last change with the dot command ., Replaying actions with macros q, storing texts in the registers ".

Global Command Overview

Both Ex commmands and command-line commands are the same. They are the commands that start with a colon :.

They are called Ex because they originally came from the Ex text editor.

Check out :h ex-cmd-index

Syntax:

1
:g/pattern/command

The global command works by executing command against each line that matches the pattern.

When running the g command, Vim makes two scans across file.

Inverse Match

To run the global command on non-matching lines.

1
:g!/pattern/command

or

1
:v/pattern/command

Pattern

Same pattern system as the substitude command.

Passing a Range

If no range are given, by default it affects the entire file.

Symbles as range:

1
2
3
.   means the current line. .,3
$ means the last line in the file
+n means n lines after the current line. 3,.+1

Executing a Macro

1
:g/const/normal @a

Recursive Global Command

The global command itself is a type of a command-line command.

1
:g/console/g/two/d

Changing the Delimiter

Still, you can use any single byte character except for alphabets, numbers, ", | and \

like :g@console@d

The Default Command

1
:g/console

as

1
:g/console/p

The syntax:

1
:g/re/p

grep got its name there.

Black Hole Delete

Make Vim not store your deleted lines into the registers.

1
:g/console/d_

Reduce Multiple Empty Lines to One Empty Line

1
:g/^$/,/./-1j

j is the join command.
Another form of global command:

1
:g/pattern1/,/pattern2/command

Advanced Sort

You can give a range:

1
:2,3sort

External Commands

The Bang Command

! can do three things. :r is the :read command.

1
2
3
4
5
6
1. Reading the STDOUT of a Command Into Vim. 
:r !cmd
2. Writing the Buffer Content Into an External Command.
:w !cmd
3. Executing an External Command.
:!cmd

The bang ! always stay before the cmd.

Filtering Texts

If you give ! a range, it can be used to filter texts.

1
:.!

executes the filter command on the current line.

:%! executes the filter command on all lines.

Normal Mode Command

Vim has a filter operater ! in the normal mode.

Command-line Mode

To leave the command-line mode, you can use <esc>, Ctrl-C or Ctrl-[.

Repeating the Previous Command

Running @:<mark><mark>.

Command-line Mode Shortcuts

To go to the start of the line, use Ctrl-B

To go to the end of the line, use Ctrl-E

To edit the command like you would a normal textfile use Ctrl-F.

Register and Autocomplete

Everything that you can get from the register in the insert mode, you can do the same from the command-line mode.

Using Ctrl-R to insert the content of register.

History Window and Command-line Window

To open the command-line history, run :his :.

Reusing the command, run q: and choose.

To open the search history, run :his / or his ?.

Edit past history, run q/ or q?.

check out :h ex-cmd or :h index.

Tags

Tag Generator

1
2
ctags = C only
ptags = Perl

There are many Tag Generator, almost for different language.

Install the universal ctags, which is still maintained.

Tags Anatomy

Four components:

1
2
3
4
1. tagname
2. tagfile
3. tagaddress
4. tag options

The content of the tag file depends on which generator you use.

A tag file must have either one of those format:

1
2
1. {tagname} {TAB} {tagfile} {TAB} {tagaddress}
2. {tagname} {TAB} {tagfile} {TAB} {tagaddress} {term} {fild} ..

The Tag File

Run set tags?.

To add a new tag file location:

1
set tags+=path/to/my/tags/file

Generating Tags for a Large Project

1
ctags -R --exclude=.git --exclude=vendor --exclude=node_modules

Tags Navigation

The tag jump key Ctrl-] or run :tag name

Tag Priority

Some tags have higher priorities.

check out :h tag-priority.

Selective Tag Jumps

run :tselect name

Normal mode key for tjump : g Ctrl-].

Automatic Tag Generation

Using autocmd:

1
:autocmd BufWritePost \*.rb silent !ctags -R .

One plugin vim-gutemtags.

Fold

Executing a fold from the command-line mode:

1
:,+1fold

Syntax Fold

It is determined by syntax language highlighting.

Check out :h syntax.txt

Git

Running :vimdiff command to show the differences between multiple files. or vim -d file1.txt file2.txt

Go to the next diff with ]c.

Jump to the previous diff window, use [c

One plugin ‘tpope/vim-fugitive’

Compile

Vim has a :make command to run a makefile.

Views, Sessions, and Viminfo

To store the current change of settings, folds, buffers, layouts, etc.

Configuring View Attributes

Tell View to remember the localoptions, run :set viewoptions+=localoptions

Saving the View

Run :mkview

Loading the View File

Run :loadview

Sessions

View saves the settings of a window, a Session saves the infomation of all windows (including the layout).

Save a Session

Run :mksession.

A Session file is saved in the current directory or you can choose.

Loading a Session

To load a Session, run

1
:source Session.vim

Viminfo

Session stores the “external” attributes and Viminfo the “internal” attributes.

One Viminfo file per computer.

Default location: ~/.viminfo

Multiple File Operations

Vim has eight ways to execute commands across multiple files:

1
2
3
4
5
6
7
8
9
  
arg list (argdo)
buffer list (bufdo)
window list (windo)
tab list (tabdo)
quickfix list (cdo)
quickfix list filewise (cfdo)
location list (ldo)
location list filewise (lfdo)

Same idea: make a list of their respective categories then pass them the command that you want to run.

Vimrc

Organizing Vimrc

Two ways to keep your vimrc to look clean:

1
2
Splite your vimrc into several files
Fold your vimrc file

Using :source to splite.

Vim packages

Vim’s own built-in plugin manager called packages.

the version command
you can get some function of your vim.

Vim Runtime

To see your run time path, run :set runtimepath?

Filetype Detection

Two ways to detecte:

file name
file content

:setfiletype type will work only there is no type is set.

Filetype File

Create a filetype.vim in the root directory ~/.vim/filetype.vim.

To prevent running multiple times:

1
2
3
if exists("did_load_filetypes")
finish
endif

finish is a Vim command to stop running the rest of the script.

File Type Script

Based on the file content.

Adding a scripts.vim file (~/.vim/scripts.vim)

I suppose you can use other name instead of scripts.vim

Vimscript Basic Data Types

Following Along With Ex Mode

The Ex mode is like an extended command-line mode (it’s like typing command-line mode commands non-stop), run Q or gQ to enter.

somethings I’m curious about
Before some command, there is a g like gQ.

g was just an empty slot, it means nothing.

To clear your message history, run:

1
:messages clear

Double vs Single Quotes

Single quotes display characters literally.

Double quotes accept special characters.

List use []

1
2
3
Dictionary use `{}`
### Special Primitives
Vim has special primetives:

v:false
v:true
v:none
v:null

`v:` is Vim's built-in variable.

Learn-Vim-On-Github
http://example.com/2022/07/04/Learn-Vim-On-Github/
作者
Jie
发布于
2022年7月4日
许可协议