What is in this article about vim?
Some Basic knowledge and keyword to use VIM
Basic search in document with VIM
Basic select text and block with VIM
Basic copy and paste with VIM
Basic moving in VIM
Copy and paste in vim over ssh with X11 forwarding
Replace content with VIM
Replace content with VIM entire working folder
Replace text between quotes in vim
Repeat the Last Change
Go to line number with VIM
Go to a word in a line with VIM
Go to a previous file stored in buffer
Go to last modification line
undo / redo with VIM
Insert mode with i/I/a/A
Jump to definition
How to delete a several rows with vim
How to use auto completion and suggest with vim
How to split windows with vim
How to view folder tree with vim
Go to a file in a folder
Go to a file in a folder when open another file
Go to the begin / end of a function
Search a text in a file
Search a text whole folder
Format code in vim
Insert newline and move back to previous position
Comment in vim
Leader key in vim
How to install plugin to support more with vim
How to support golang
How to support javascript
How to support swift
How to support java/ kotlin
Another ugly things for fun: read pdf with vim, read epub with vim, read big file with vim

Some Basic knowledge and keyword to use VIM

Normal mode (also known as command mode): is what you see after press Esc
Insert mode: is what you see in vim after press i
Config file: .vimrc
To see vim version: vim –version

Basic search in document with VIM

To perform search, press /
Then type the search pattern
Press Enter to perform serch
Press n to find the next occurence or N to go to the previous occurrence

To search the whole word
press / or ?
Then type \< to mark the begin of word Then type \> to mark the end of word
Then press Enter to perform search
Press n to find the next occurrence or N to find the previous occurrence

Basic select text and block with VIM

In visual mode, type v to begin select text base, V to select the whole lines
Ctrl v or Ctrl q to select a block

Press d to cut , y to yank (copy)
Press p to paste after the cursor, and P to paste before

Basic moving in VIM

Basic moving:
Use
h j k l

Moving faster
} jumps entire paragraphs downwards.
{ similarly but upwards.
CTRL-D lets you move down half a page by scrolling the page.
CTRL-U lets you move up half a page also by scrolling

Basic copy and paste with VIM

yank with this pattern
:400,450y
then p or P to paste (in visual mode)

If you want to duplicate a row, at the current row, press y (yarn), then press p ( to paste)

Try these command
yy : copy current line
:pu : paste in a new line

How to copy text in VIM and use it for the OS clipboard(even after exit VIM) ?
Try to use some guide
+Use * (eg: *y)
“*y
To paste: “*p
+check vim clipboard support
vim –version
or
vim –version | grep “clipboard”
then find
+clipboard : support
-clipboard : not support
+check vim-gnome
+edit .vimrc:
set clipboard=unnamedplus
or
set clipboard=unnamed
use :help ‘clipboard’
to see more help info

 unnamed         When included, Vim will use the clipboard register '*'
                        for all yank, delete, change and put operations which
                        would normally go to the unnamed register.  When a
                        register is explicitly specified, it will always be
                        used regardless of whether "unnamed" is in 'clipboard'
                        or not.  The clipboard register can always be
                        explicitly accessed using the "* notation.  Also see
                        gui-clipboard.

 A variant of the "unnamed" flag which uses the
                        clipboard register '+' (quoteplus) instead of
                        register '*' for all yank, delete, change and put
                        operations which would normally go to the unnamed
                        register.  When "unnamed" is also included to the
                        option, yank operations (but not delete, change or
                        put) will additionally copy the text into register
                        '*'.
                        Only available with the +X11 feature.
                        Availability can be checked with:
                                if has('unnamedplus')

+ install vim-gtk3 for +xterm_clipboard
sudo apt-get install vim-gtk3 (an alternative for vim-gnome which has been removed)
+ install vim-gnome to get xterm_clipboard
sudo apt-get install vim-gnome
+ Use SHIFT , not change to visual mode

Copy and paste in vim over ssh

Keyword: vim clipboard over ssh

When you are using Vim on a remote server via SSH, everything you do in Vim is done on the remote server. The remote server and the remote Vim that you are running on it have zero practical knowledge of your local computer and its system clipboard.

Because of that, y will never put the yanked text in your local clipboard.

In order to copy a chunk of text from the remote Vim to your local machine's clipboard you have three options:

Select the text with your mouse and hit Cmd+C like in any Mac OS X application.

Obviously, it seems to be the easiest but it has at least three limitations:

It is limited to the current screen. If the text you want to yank is not displayed entirely you won't be able to copy all of it.
It doesn't play well with set mouse=a. With this option, any attempt to select something with the mouse will result in a visual mode selection which can't be copied with Cmd+C. As a workaround, you can use Alt+mouse to select the text without entering visual mode or simply remove this setting from your remote ~/.vimrc.
Line numbers are copied as well.
Put the yanked text in a temporary file, scp it to your local machine and use pbcopy to put it in your system clipboard.

This solution seems to be a little convoluted but it works (and the problem itself is also a little bit convoluted). Over the years I've seen a lot of different implementations ranging from simple one liners to client/server setups. Here is one, feel free to google around for others.
Use X-forwarding to connect your local clipboard to the remote clipboard if available.

For more info how to use X-forwarding
You can also use a clipboard on remote machines if you enable X11 forwarding over SSH. This is especially useful with the above tip since you can then use xclip to access your desktop’s clipboard. The Vim on the machine you’re ssh-ing to will still need the +clipboard feature.

This requires the ForwardX11Trusted setting, and should only be done with trusted servers, as this gives the server almost complete control over your X11 session:

$ ssh -XY myhost
To make these settings persistent (so you don’t need to add -XY every time), you could do something like this in your ~/.ssh/config:

# Do **NOT** set this globally; it gives the server complete control over
# your X11 session.
Host myhost
ForwardX11 yes
ForwardX11Trusted yes

More keyword: XQuartz, X11
ssh -X user@host

Replace content with VIM : first occurrence, current line, entire document

To search for the first occurrence of the string ‘foo’ in the current line and replace it with ‘bar’, you would use:

:s/foo/bar/
Copy
To replace all occurrences of the search pattern in the current line, add the g flag:

:s/foo/bar/g
Copy
If you want to search and replace the pattern in the entire file, use the percentage character % as a range. This character indicates a range from the first to the last line of the file:

:%s/foo/bar/g

Replace text between quotes in vim

Use

ci’ – change inside the single quotes
ciw – change inside a word
ci( – change inside parentheses
dit – delete inside an HTML tag, etc.

Replace content with VIM entire working folder

Modern text editors like VSCode makes it very easy to search and replace string across multiple files. If I may confess, in the beginning when I had to search/replace string in multiple files, I used VSCode because doing it in Vim, although possible, takes too long… until now.

I will show you two different tricks to easily do search and replace phrases across multiple files in Vim.

The first method is to replace ALL matching phrases in our project. We will need to use :grep. Let’s say you want to replace all instance of “pizza” with “donut”. Here’s what you do:

:grep “pizza”
:cfdo %s/pizza/donut/g | update
That’s it? Yup! That’s it. Let me break down the steps:

:grep pizza uses ripgrep to succinctly search for all instances of “pizza”. By the way, this would still work even if we didn’t reassign ripgrep to replace default grep. We would have to do :grep “pizza” . -R instead of :grep “pizza”.
We run :cfdo because :grep uses quickfix.:cfdo executes any command we pass (in this case, our command is %s/pizza/donut/g) on all entries in our quickfix list. To run multiple commands, we can chain it with pipe (|). The first command we are executing is pizza-donut substitution: %s/pizza/donut/g. The second command, update, saves each file after the first is finished.
Let’s discuss the second way.

The second method is to search and replace in select multiple files instead of all files using buffers. Here we can choose which files we want to perform select and replace.

Clear our buffers (:Buffers) first. Our buffers list should contain only the needed files. We can clear it with %bd | e# | bd# (or restart Vim).
Run :Files.
Select all files you want to perform search and replace on. To select multiple files, use Tab / Shift+Tab. This is only possible if we have -m in FZF_DEFAULT_OPTS.
Run :bufdo %s/pizza/donut/g | update.
Our command :bufdo %s/pizza/donut/g | update looks similar to :cfdo %s/pizza/donut/g | update. That’s because they are. Instead of performing substitution on all quickfix (cfdo) entries, we perform our substitution on all buffer (bufdo) entries.

Repeat the Last Change

Use
.
to repeat the last change (in edit/insert mode)

Go to line number with VIM

The easiest way
:123
or
123G
or
123gg

Go to the begin of file: gg
Go the the end of file: G
Go to the begin of line: 0
Go to the end of line: $

Go to a word in a line with VIM

While cursor at a line
Press f
Then press any word that you want to move to forward

To move backward, press F instead f

Go to last modification line

Use
‘. : jump to last modification line
`. : jump to exact spot in last modification line
CTRL O : Retrace your movements in file in backwards
CTRL I : Retrace your movements in file in forwards

undo / redo with VIM

How to undo in vim
If you are in insert or any other mode, press the Esc key to go back to the normal mode, which is also known as command mode.
Type u to undo the last change. In Vim, the u command also accepts quantifiers. For example, if you want to undo the four last changes, you would use 4u.
Make sure you’re typing lowercase u, not the uppercase U command, which undoes all latest changes on one line. If you accidentally type U you can undo the change with u.

The redo feature reverses the action of undo.

To redo a change in Vim and Vi use the Ctrl-R or :redo:

Press the Esc key to go back to the normal mode.
Use Ctrl-R (press and hold Ctrl and press r) to redo the last change. In Vim, you can also use quantifiers. For example, if you want to redo the 4 last changes, you would type 4Ctrl-R.
Each undo command can be reversed by a redo command.

Insert mode with i/I/a/A

Use :
i (insert) to insert before cursor
I to insert at the begin of line
a (append) to insert after cursor
A to insert at the end of line

Jump to definition

With neovim (nvim), while your cursor at any variable / function, you can use command: gi
to go to the definition

To support go lang, you need to add language server support for golang (gopls)
:CocInstall coc-go

More info : gopls for coc.nvim
https://github.com/josa42/coc-go
https://github.com/golang/tools/blob/master/gopls/README.md
https://github.com/neoclide/coc.nvim/wiki/Debug-language-server#using-output-channel
https://github.com/neoclide/coc.nvim

How to open files tree with vim

Use this command in vim
:Explore

How to delete a several rows with vim

Delete a Range of Lines
1. Use Esc to switch to normal mode in Vim.
2. Use the following command and replace [from] with the number of the line where you want the range to start and [to] where you want it to end:
:[from],[to]d
For instance, if you wanted to remove lines 4, 5, 6, and 7, you would use the command:
:4,7d

Go to the starting line of your block, and type ma (mark “a”, though you can of course use different letters, and even multiple letters for different marks provided you can keep it straight in your head what each letter is a mark of).

Then go to the last line and enter d’a (delete to mark “a”) or y’a (yank to mark “a”) (a).

That will delete/yank all lines from the current to the marked one (inclusive).

Then you can paste it somewhere else with the normal paste commands, such as p or P.

It’s also compatible with vi as well as vim, on the off chance that your environment is not blessed with the latter.

(a) I also use this to save my place in the file if I have to go looking elsewhere for something like, for example, copy-pasting the definition of a function I want to call.

I simply mark the current line in the same way, ma, then wander off to find whatever you’re looking for.

Then, once I’ve found it and copied it to a register, I just enter ‘a to go back to mark “a”, the line I saved beforehand, where I can then paste it.

https://phoenixnap.com/kb/how-to-delete-line-vim

https://vi.stackexchange.com/questions/1915/how-do-i-delete-a-large-block-of-text-without-counting-the-lines

How to use auto completion and suggest with vim

If you are using VIM version 8+, just type
ctrl+p: previous – suggest based on previous typed words
ctrl+n: next – suggest based on the next coming words
How to remember the shortcuts?

ctrl+p: previous – suggest based on previous typed words
ctrl+n: next – suggest based on the next coming words

Where does this feature work?
This works in the insert mode of Vim i.e. the mode where we do the regular typing ( After pressing i in ESC mode). Type few letters of a word and press CTRL+p. If there are previously typed words starting with those letters. You can see some suggestions. If there is only one suggestion, the word will be auto complete and you can continue editing.

How to make a selection when multiple suggestions are shown?

When pressing you are ctrl+p (ctrl+n), you are shown multiple suggestions and you want to make use of nth suggestion, press ctrl+p (ctrl+n) n-1 times and continue editing. That is if you are shown five suggestions, and you want to use third suggestion, press ctrl+p two times and you can continue editing.

How not to make use of given suggestions?

When pressing you are ctrl+p (ctrl+n), you are shown n suggestions and you couldn’t find what you are looking for. Press ctrl+p (ctrl+n) n times and you can continue editing. Press ctrl+p (ctrl+n) will undo showing any specified suggestion.

Others,
Some recommended plugin:
AutoComplPop
YouCompleteMe
https://github.com/Valloric/YouCompleteMe
completor.vim
https://github.com/maralla/completor.vim

How to split windows with vim

To open a new VIM window next to the existing one, press + then press .

Now you can move to the right window from the left by pressing + and then pressing

You can move to the left window again by pressing + and then pressing . To open a new VIM window on the bottom of the currently selected window, press + then press s. You currently selected window should be split vertically as shown in the screenshot below.

You can go to the window below the selected window by pressing + and then pressing

You can go to the window above the selected window by pressing + and then pressing

How to view folder tree with vim

Method 1: use command
:NERDTree

method 2: run vim command with
vim .

Go to a file in a folder

Method 1: use fzf plugin
Type :Files then type path or filename that you remember

Go to a file in a folder when open another file

Method 1: use fzf plugin
Type :Files then type path or filename that you remember

Go to a previous file stored in buffer

Use
:e#

or:

CTRL-^ Edit the alternate file. Mostly the alternate file is
the previously edited file. This is a quick way to
toggle between two files. It is equivalent to “:e #”,
except that it also works when there is no file name.

Go to the begin / end of a function

Use this key
[{
or
]}

Search a text in a file

Type
/
Then typing the text to search
Or
Go to a word (inside any word)
Then press *
It will search the whole file
Then use n to move to next word
To search case insensitive or case sensitive, use
\c or \C

Search a text whole folder

Use ripgrep
:Rg
Note: you need to install fzf and ripgrep first

Format code in vim

In visual mode, use v and select text area
Press = to format code

Insert newline and move back to previous position

Use this compination key
o
Esc
k

Or use this
” Create Blank Newlines and stay in Normal mode
nnoremap zj ok
nnoremap zk Oj

Comment in vim

Use the guide below
+ Use visual block mode Ctrl+v
+ use arrow to select
+ Then go to insert mode: shift+i
+ Type the comment letter (# or // or anything)
+ Press esc to complete (not enter)

To uncomment
+ Use visual block mode Ctrl+v
+ use arrow to select
+ Press x

Ref
https://stackoverflow.com/questions/1676632/whats-a-quick-way-to-comment-uncomment-lines-in-vim

Leader key in vim

V im’s key is a way of creating a namespace for commands you want to define. Vim already maps most keys and combinations of Ctrl + (some key), so (some key) is where you (or plugins) can add custom behavior.

For example, if you find yourself frequently deleting exactly 3 words and 7 characters, you might find it convenient to map a command via nmap d 3dw7x so that pressing the leader key followed by d will delete 3 words and 7 characters. Because it uses the leader key as a prefix, you can be (relatively) assured that you’re not stomping on any pre-existing behavior.

The default key for is \, but you can use the command :let mapleader = “,” to remap it to another key (, in this case).

Usevim’s page on the leader key has more information.

How to install plugin to support more with vim

You can edit file .vimrc to install more plugins

For example,

" Call
call plug#begin('~/.vim/plugged')

" Shorthand notation;  https://github.com/junegunn/vim-easy-align
Plug 'junegunn/vim-easy-align'

" vim-github-dashboard
Plug 'https://github.com/junegunn/vim-github-dashboard.git'

" ultisnips
Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'

" Loading
Plug 'scrooloose/nerdtree', { 'on':  'NERDTreeToggle' }
Plug 'tpope/vim-fireplace', { 'for': 'clojure' }

" YCM-Generator
Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' }

" tag released
Plug 'fatih/vim-go', { 'tag': '*' }

" 
Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' }

" 
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }

" Huy's Choice 
Plug 'neoclide/coc.nvim', {'branch': 'release'}
"let g:coc_disable_startup_warning = 1
" Plugin cho việc sủ dụng auto close
Plug 'townk/vim-autoclose'

" end
call plug#end()

then run the following in Vim:

:source %
:PlugInstall

Note:
Remember to config if you meet any problem with :PlugInstall command
.vim/autoload/plug.vim

(ls -al /root for more detail)

Plugin to support vim for coding Go

Use plugin here
https://github.com/beastoin/dotfiles

Plugin to support vim for coding Swift / Objc-C

More info here
https://github.com/apple/sourcekit-lsp/blob/main/Editors/README.md
https://github.com/prabirshrestha/vim-lsp

Plugin to support vim for coding java/ kotlin

Plugin to support vim for coding javascript

Another ugly things for fun: read pdf with vim, read epub with vim, read big file with vim

To read pdf with vim: use plugin Plug ‘rhysd/open-pdf.vim’ along with pdftotext installed on the server

More Reference and resource

https://vimawesome.com/plugin/autoclose

https://linuxize.com/post/how-to-compare-strings-in-bash/

https://linuxize.com/post/bash-if-else-statement/

https://vi.stackexchange.com/questions/84/how-can-i-copy-text-to-the-system-clipboard-from-vim

https://unix.stackexchange.com/questions/138417/ssh-forwardx11-vs-forwardx11trusted-beyond-my-grasp/263734

https://www.businessnewsdaily.com/11035-how-to-use-x11-forwarding.html

X Server (android app)
https://play.google.com/store/apps/details?id=au.com.darkside.XServer&hl=en

Vim Tutor
https://github.com/vim/vim/blob/master/runtime/tutor/tutor

Dot file example

https://github.com/ryenguyen7411/dot-files

Split windows with vim

How To Use VIM Split Screen

Vim and Go
https://www.rockyourcode.com/how-i-setup-go-with-vim/

Neoclide/coc.nvim
https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions

FZF Plugin
https://dev.to/iggredible/how-to-search-faster-in-vim-with-fzf-vim-36ko

https://www.cyberciti.biz/faq/unix-linux-vim-go-back-to-last-cursor-position/

Vim bes plugin collection
https://www.makeuseof.com/best-vim-plugins/

About the Author

Trần Huy

View all author's posts

Bài viết khác

Backend xử lý với dữ liệu người dùng tải lên như thế nào?

Khi người dùng tải lên dữ liệu (file, hình ảnh, video, v.v.), backend thường xử lý dữ liệu này qua các bước sau: Nhận dữ liệu  Qua API: Backend nhận dữ liệu từ HTTP request (thường là POST hoặc PUT). Ví dụ: sử dụng multipart/form-data cho file. Xác thực dữ liệu Kiểm tra định dạng: […]

MinIO

MinIO là gì? MinIO là một giải pháp lưu trữ đối tượng (object storage) mã nguồn mở, tương thích với API của Amazon S3. Nó được thiết kế để lưu trữ và quản lý dữ liệu phi cấu trúc như hình ảnh, video, tài liệu, và các tệp tin lớn khác. Dung lượng của 1 object […]

Relational Database Design Principle

1-1 1-n n-n   https://nexwebsites.com/database/database-design/  

Laravel

Laravel là gì? Laravel là một framework PHP mã nguồn mở miễn phí được phát hành lần đầu tiên vào năm 2011. Taylor Otwell đã tạo ra Laravel nhằm giúp các Developer xây dựng các ứng dụng web bằng cách sử dụng mẫu kiến ​​trúc Model-View-Controller (MVC). Mô hình Model-View-Controller (MVC) trong Laravel: 1. Model […]

PHP

PHP là gì? PHP là từ viết tắt của thuật ngữ Personal Home Page và hiện nay đang có tên Hypertext Preprocessor. Đây là một dạng mã lệnh hoặc một chuỗi ngôn ngữ kịch bản. Trong đó, ngôn ngữ PHP chủ yếu được phát triển để dành cho những ứng dụng nằm trên máy chủ. Mỗi […]

Build for global scale: AFK scale cube and basic rule to build an application for global scale

REF https://akfpartners.com/growth-blog/scale-cube