0. Vim 基础
模式
模式切换
o
: open a new linei
: inserta
: append
Visual [Character]
视觉模式:用于选择单个字符(v 小写v
)- 视觉
线
模式:用于一次选择整条线(V 大写V
) - 视觉
块
模式:用于选择块状矩形形状的文本ctrl + v
normal 模式进行选择
h/j/k/l
移动它,w/e/b/ge
键跳过单词
b
代表 begine
代表 end
f{c}
find char
t{c}
till char
;
find next
,
find previous
1. 动作 (motion)
2. 操作符 (operator)
3. 操作符 (Operator) + 区间 (Range) +符号 (Motion / TextObject)
- Operator: v / c / d ( visual select / change / delete )
- Range: 2 / i / a / t / f (数字 / inner / around / till / find)
- TextObject: w / ( / { (区间 / f+字符串 / vij动作 )
- e.g.,
d ie
c ie
y ie
c it
v iw y
选中当前单词后复制
4. 其余技巧
- 大小写转换
- 对选中内容进行操作
:'<,'>g/^$/d
5. Plugin
5.1. easymotion
5.2. vim-surround
nnoremap
代表 normal 模式vnoremap
代表 visual 模式:map
和:noremap
是各种映射命令的递归和非递归版本
n
仅正常v
可视化和选择o
操作员待定x
仅可视s
仅选择i
插入c
命令行l
插入、命令行、regexp 搜索(及其他; 统称为 “lang arg
” 伪模式)
vim replace single quote to double quotes
- use
cs'"
to change surrounding quotes.
5.3. vim-easymotion
6 数字递增
g
+ ctrl + a
7. Vim 配置 .vimrc
" 将 <space> 键设为快捷键前缀
let mapleader = "\<Space>"
" -- map leader to <Space>
" vim.keymap.set("n", " ", "<Nop>", { silent = true, remap = false })
" vim.g.mapleader = " "
" nnoremap <Space> <Nop>
map <Space> <Leader>
" 将当前行复制到系统剪贴板
nnoremap <leader>y "+yy
" 将系统剪贴板中的文本粘贴到光标所在位置
nnoremap <leader>p "+p
set mouse=a " 启用鼠标
" 禁用兼容模式,允许使用 vim 的一些高级功能
set nocompatible
if has('syntax')
"这个代码块在语法高亮功能可用的情况下
syntax on
endif
" 显示行号
set nu
" 不显示行尾空格
set noeb
" 设置 tab 键宽度为 4 个空格
set tabstop=4
" 开启自动缩进
set autoindent
" 将 tab 转换为空格
set expandtab
" 设置缩进宽度为 4 个空格
set shiftwidth=4
" 在括号匹配时高亮显示匹配的括号
set showmatch
" 设置文件编码,可以处理多种编码的文件
set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936,iso-8859-1
" 设置当前 vim 编码
set encoding=utf-8
" 设置终端编码
set termencoding=utf-8
" 设置 gui 模式下的字体和大小
set guifont="fira code":h13
" 允许在 vim 和系统剪贴板之间复制粘贴
set clipboard^=unnamed,unnamedplus
" 不自动折行
set nowrap
" enable visual feedback instead of an audible beep when an error or warning occurs
set novisualbell
"" [error bell]
set noerrorbells
" Use a line cursor within insert mode and a block cursor everywhere else.
"
" Reference chart of values:
" Ps = 0 -> blinking block.
" Ps = 1 -> blinking block (default).
" Ps = 2 -> steady block.
" Ps = 3 -> blinking underline.
" Ps = 4 -> steady underline.
" Ps = 5 -> blinking bar (xterm).
" Ps = 6 -> steady bar (xterm).
" SI = INSERT mode
" SR = REPLACE mode
" EI = NORMAL mode (ELSE)
let &t_SI = "\e[6 q"
let &t_EI = "\e[2 q"
" fast for cursor
set ttimeout
set ttimeoutlen=1
set ttyfast
nnoremap <C-A> <C-A>
nnoremap <C-X> <C-X>
8. !
感叹号的作用
来源
:help
! bang (on command of vim)
-
:<cmd>!
means to force the action (e.g.:w!
will overwrite an existing file and:q!
will quit without saving). -
:set <option>!
toggles a boolean option, e.g.:set number!
,set wrap!
-
!
followed by some shell command executes that command directly from the editor, e.g.:! ls /etc
-
:w !cmd
pipes the contents of the current buffer to the commandcmd
, e.g.:w !sudo tee %
(a.k.a. the write with sudo trick).
ps: cheat sheet
example | meaning |
---|---|
:wq! :q! | do it anyway! |
:autocmd! {group} {event} {pat} cmd | override specific autocommands (:help autocmd-remove*) |
:function! | override existing |
:com[mand][!] [{attr}…] {cmd} {repl} | override existing |
:set number! | (override 0 with 1, or 1 → 0) toggle an option |
:!ls | shell command |
9. IdeaVim
settings 选项:
Ctrl + {char}
in Intellij idea
B - F H N O Q P (S) (T) U (W)
- 插件:
IdeaVimExtension
- 配置: Variable groups:
align in columns
" .ideavimrc is a configuration file for IdeaVim plugin. It uses
" the same commands as the original .vimrc configuration.
" You can find a list of commands here: https://jb.gg/h38q75
" Find more examples here: https://jb.gg/share-ideavimrc
" Source your .vimrc
source ~/.vimrc
" -- Suggested options --
" Show a few lines of context around the cursor. Note that this makes the
" text scroll if you mouse-click near the start or end of the window.
set scrolloff=5
" Do incremental searching.
set incsearch
set number relativenumber
set idearefactormode=keep
set ideajoin
" set easymotion
" Don't use Ex mode, use Q for formatting.
map Q gq
" --- Enable IdeaVim plugins https://jb.gg/ideavim-plugins
" Highlight copied text
Plug 'machakann/vim-highlightedyank'
" Commentary plugin
Plug 'tpope/vim-commentary'
" -- Map IDE actions to IdeaVim -- https://jb.gg/abva4t
" Map \r to the Reformat Code action
" map \r <Action>(ReformatCode)
" Map <leader>d to start debug
" map <leader>d <Action>(Debug)
" Map \b to toggle the breakpoint on the current line
" map \b <Action>(ToggleLineBreakpoint)
" cancel Esc
" noremap <Esc> <nop>
" s-enter = shift enter
" nmap <S-Enter> O<Esc>
" nmap <CR> o<Esc>
" cr = enter = lr = cr/lf
" nmap <CR> i<CR><Esc>
let mapleader = " "
" move line
nnoremap <C-j> :m +1<CR>
nnoremap <C-k> :m -2<CR>
inoremap <C-j> <Esc>:m +1<CR>gi
inoremap <C-k> <Esc>:m -2<CR>gi
" system clipboard
nmap <leader>y "+yy
nmap <leader>p "+p
nmap <leader>P "+P
vmap <leader>y "+y
vmap <leader>p "+p
vmap <leader>P "+P
" vmap <leader>d "+d
" scrolling f/b or d/u
nmap <leader>j <C-d>
vmap <leader>j <C-d>
nmap <leader>k <C-u>
vmap <leader>k <C-u>
nmap <leader>h :action PreviousTab<CR>
nmap <leader>l :action NextTab<CR>
nmap <leader>bd :action CloseEditor<CR>
" select mode
nmap <S-Left> <Action>(EditorLeftWithSelection)
nmap <S-Right> <Action>(EditorRightWithSelection)
nmap <S-Up> <Action>(EditorUpWithSelection)
nmap <S-Down> <Action>(EditorDownWithSelection)
nmap <S-Home> <Action>(EditorLineStartWithSelection)
nmap <S-End> <Action>(EditorLineEndWithSelection)
imap <S-Left> <Action>(EditorLeftWithSelection)
imap <S-Right> <Action>(EditorRightWithSelection)
imap <S-Up> <Action>(EditorUpWithSelection)
imap <S-Down> <Action>(EditorDownWithSelection)
imap <S-Home> <Action>(EditorLineStartWithSelection)
imap <S-End> <Action>(EditorLineEndWithSelection)
vmap <S-Left> <Action>(EditorLeftWithSelection)
vmap <S-Right> <Action>(EditorRightWithSelection)
vmap <S-Up> <Action>(EditorUpWithSelection)
vmap <S-Down> <Action>(EditorDownWithSelection)
vmap <S-Home> <Action>(EditorLineStartWithSelection)
vmap <S-End> <Action>(EditorLineEndWithSelection)
" extensions
set surround
vmap S <Plug>VSurround
" set keep-english-in-normal-and-restore-in-insert
set keep-english-in-normal
set NERDTree
let g:NERDTreeMapActivateNode='l'
let g:NERDTreeMapJumpParent='h'
" Use a line cursor within insert mode and a block cursor everywhere else.
" ( SI = INSERT mode SR = REPLACE mode EI = NORMAL mode (ELSE) )
"
" Reference chart of values:
" Ps = 0 -> blinking block.
" Ps = 1 -> blinking block (default).
" Ps = 2 -> steady block.
" Ps = 3 -> blinking underline.
" Ps = 4 -> steady underline.
" Ps = 5 -> blinking bar (xterm).
" Ps = 6 -> steady bar (xterm).
- idea 快捷键
use cmd+shift+delete to unwrap the try-resource statement
opt+j opt+shift+j(deselect) cmd+opt+shift+j(select all occurrences in the file) esc
opt-F7 to see all of its usages and more detailed view of usages; cmd-shift-a -> "find" open again.
cmd-opt-n Inline Variable
cmd-F1 to expand the warning description.
chick the drop-down(下拉菜单) while holding SHIFT.
chick the tab-title while holding CMD -> open in finder
cmd-p to see the method's signature.
# cmd-shift-space smart TYPE completion 在点后面的单词首位, cmd-[opt]-space (basic/second basic completion) 然后 tab 直接替换
# cmd-shift-i to see the definition of the symbol at the caret.
# cmd-shift-F7 to highlight all usages of the symbol at the caret within the file
# cmd-shift-f with opt-w(words) and opt-d(directory)
# opt-7 equals cmd-F12
# cmd-e recent files, and press `Del` can close tab.
# cmd-f and F3 or shift-F3(backwards); with the search panel closed, you can still use these shortcuts to navigate
# cmd-shift-a -> "add to watches"
# F7 and use "->" to choose method call -> press enter.
# cmd-opt-F8 to invoke Quick Evaluate Expression for selected argument. esc to close the popup
# opt-F8 selected + Evaluate Expression...
# shift-F9 debug F10 is run (far than F9)
# opt-F9 Run to Cursor.
# cmd-F9 Hot Swap (build).
# cmd-F2 to Stop
10. NERD Tree
Press o to toggle folder open/close.
Press O to recursively open all folders.
Press t to open in new tab (activate).
Press T to open in new tab (background).
Press i to open file in vertical split.
Press s to open file in horizontal split.
Press p to go to parent directory.
Press r to refresh the current directory.
Press m to launch NERDTree menu inside Vim.
Press za to toggle collapse folders.
Press zc to close folder.
Press zo to open folder.
Press zR to open all folders.
Press zM to close all folders.
NERD Tree use in Intellij idea
能在 idea 中使用的有
im opq st x
o
(open)O
(recursively)t
(open)T
(open)x
(fold)p
(parent)i
(vertical)s
(horizontal)m
(menu)
11. 命令模式
常用命令模式
- 去掉 java 注释
# 去除单行注释 //
:g/\/\/.*$/d
# 去除多行注释 /* 和 */
:g/\/\*/,/\*\//d
# 去除 Javadoc 注释 /** 和 */
:g/\/\*\*/,/\*\//d
- 删除空行
:g/^\s*$/d
- 删除前面的空格
:%s/^\s\+//g
- 将所有连续的空行合并成一个空行
:g/^\s*$/j
自定义命令
如果经常使用这些命令,可以考虑添加到 .vimrc
or init.lua
文件中作为自定义命令
# 在 .vimrc 中添加
command! CleanCode g/^\s*$/d | g/\/\/.*$/d | g/\/\*/,/\*\//d | g/\/\*\*/,/\*\//d
- 在 neovim 中自定义命令 (使用 lazy.vim 举例)
在 Windows 上,LazyVim 的配置文件默认存放路径:
%USERPROFILE%\AppData\Local\nvim\
(C:\Users\<YourUsername>\AppData\Local\nvim\
)
# ~/.config/nvim/init.vim
command! CleanCode execute "g/^\\s*$/d | g/\\/\\/.*$/d | g/\\/\\*/,/\\*\\//d | g/\\/\\*\\*/,/\\*\\//d"
# ~/.config/nvim/init.lua (封装成 Lua 函数)
vim.api.nvim_create_user_command(
"CleanCode",
function()
vim.cmd([[ g/^\s*$/d ]])
vim.cmd([[ g/\/\/.*$/d ]])
vim.cmd([[ g/\/\*/,/\*\//d ]])
vim.cmd([[ g/\/\*\*/,/\*\//d ]])
end,
{ desc = "Remove empty lines, // comments, /* */ and /** */ comments" }
)
# (可选) 绑定快捷键 <Leader>cc
vim.keymap.set("n", "<Leader>cc", ":CleanCode<CR>", { desc = "Clean code (remove comments & empty lines)" })
可单独在
lua/config/
下创建一个新文件(如custom.lua
), 然后在init.lua
或lua/config/lazy.lua
中引用
# custom.lua require("config.custom")
命令模式合并执行 |
在 Vim 中,可以通过使用 | 符号来合并多条命令执行
:echo "hello" | echo "goodbye"
Some commands don’t allow separation via |.
Luckily, you can wrap them up in an execute:
:execute 'echo "hello"' | execute 'echo "goodbye"'
- 去掉 java 注释, 删除空行
:execute 'g/\/\/.*$/d' | execute 'g/\/\*/,/\*\//d' | execute 'g/\/\*\*/,/\*\//d' | execute 'g/^\s*$/d'
注意: 请勿直接使用以下命令
# 不生效
:g/^\s*$/d | g/\/\/.*$/d | g/\/\*/,/\*\//d | g/\/\*\*/,/\*\//d
命令模式详解
:g
命令
用途:全局命令,用于在整个文件中查找匹配的行,并对这些行执行指定的命令。
- 语法:
# pattern:要匹配的正则表达式。command:对匹配的行执行的命令(例如,d 删除行,p 打印行等)。
:g/pattern/command
- command
d:删除匹配的行。
例::g/pattern/d
p:打印匹配的行。
例::g/pattern/p
s/pattern/replacement/:替换匹配的行中的特定内容。
例::g/pattern/s/foo/bar/g
move:移动匹配的行到指定行号。
例::g/pattern/m 10
t:复制匹配的行到指定行。
例::g/pattern/t 10
!command:对匹配的行执行外部命令。
例::g/pattern!sort
normal:对匹配的行执行普通模式命令。
例::g/pattern/normal dd(删除匹配的行)
join:合并匹配的行。
例::g/pattern/join
copy:复制匹配的行到指定行。
例::g/pattern/copy 10
:s
命令
用途:替换命令,用于在指定范围内查找匹配的文本并进行替换。
- 语法:
# pattern:要查找的文本。replacement:用于替换的文本。g:可选参数,表示全局替换(替换行内所有匹配项)
:s/pattern/replacement/g
- 可选参数
g:
作用:在每一行中进行全局替换,即替换行内所有匹配的模式。
示例::s/foo/bar/g(替换当前行中所有的 "foo" 为 "bar")。
c:
作用:在执行替换之前提示用户确认每个替换。
示例::s/foo/bar/c(每次遇到 "foo" 时都会询问确认)。
i:
作用:忽略大小写进行匹配。
示例::s/foo/bar/i(替换 "foo"、"Foo"、"FOO" 等)。
n:
作用:显示匹配的次数,而不进行替换。
示例::s/foo/bar/n(显示 "foo" 的匹配次数)。
&:
作用:用上一个替换模式的结果进行替换。
示例:可以在后续的替换中使用。
范围参数
%:
作用:在整个文件中进行替换。
示例::%s/foo/bar/g(在整个文件中替换所有的 "foo" 为 "bar")。
[range]:
作用:指定替换的行范围。
示例::5,10s/foo/bar/g(在第 5 行到第 10 行中进行替换)。
(END)