はじめに
モードと基本の移動
Vim はモーダルエディタです — モードごとに役割が異なります。Esc はどのモードからでもノーマルモードへ戻ります。hjkl キーはホームポジションから手を動かさずに済みます。w/b で単語移動、0/$ で行頭/行末、gg/G でファイルの先頭/末尾、:N で N 行目へジャンプします。
# Vim Modes
# Normal mode (Esc) - default, for navigation
# Insert mode (i) - for typing text
# Visual mode (v) - for selecting text
# Command mode (:) - for Ex commands
# Basic movement (Normal mode)
h # left
j # down
k # up
l # right
w # next word start
b # previous word start
0 # beginning of line
$ # end of line
gg # first line
G # last line
:42 # go to line 42終了と保存
ZZ と ZQ は最速の終了方法です — コロンまで手を伸ばす必要がありません。:x はファイルが変更されたときだけ書き込みます(mtime を保持)。一方 :wq は常に書き込みます。:w! はファイルシステムの権限が許す限り読み取り専用フラグを上書きします。複数の変更済みバッファから抜けるときは :qa! を使いましょう。
:w # write (save) file
:w! # force write (override read-only)
:q # quit
:q! # force quit (discard changes)
:wq # write and quit
:x # write only if changed, then quit
ZZ # same as :x (write if changed, quit)
ZQ # quit without saving (like :q!)
:w newfile.txt # save as new file
:sav newfile.txt # save as new file and switch to it
:wa # write all buffers
:xa # write all changed buffers and exit
:qa! # force quit all (discard everything)ヘルプシステム
Vim のヘルプは包括的でハイパーリンク付きです。Ctrl-] でタグ(リンク)を辿り、Ctrl-T で戻ります。ヘルプの記法: i_CTRL-N は挿入モードでの Ctrl-N、'number'(引用符付き)はオプションを意味します。:helpgrep は全ヘルプファイルを一度に検索します — マッチの移動には :cn/:cp を使います。K はカーソル下のキーワードで man を呼び出します('keywordprg' で設定可能)。
:help # main help
:help subject # help on subject (e.g. :help insert)
:help i_CTRL-N # help on Ctrl-N in insert mode
:help 'number' # help on the 'number' option (quotes)
:helpgrep pattern # search all help files for pattern
:cn / :cp # next/prev helpgrep match
K # man page for word under cursor (Normal mode)
Ctrl-] # jump to tag under cursor (follow link)
Ctrl-T # jump back from tag (pop tag stack)
:helptags ~/.vim/doc # regenerate help tags for a doc directory単語・文字の移動
小文字のモーション(w/b/e)は句読点を単語の区切りとして扱います — コード向きです。大文字のモーション(W/B/E)は空白だけを区切りとして扱います — 文章向きです。e/E は次の単語の末尾へ、ge/gE は前の単語の末尾へ移動します(あまり使わないが便利)。
# Word motions (punctuation-aware)
w # next word start
b # previous word start
e # end of next word
ge # end of previous word
# WORD motions (whitespace-only delimiters, uppercase)
W # next WORD start
B # previous WORD start
E # end of next WORD
gE # end of previous WORD
# Word boundaries:
# word: sequence of word-characters OR sequence of punctuation
# WORD: anything separated by whitespace
# Examples (cursor on 'a' in "foo.bar baz"):
# w -> 'bar' (punctuation splits words)
# W -> 'baz' (only whitespace splits WORDS)行内の移動
0 と $ は行の絶対的な先頭/末尾へ(空白を含む)移動します。^ と g_ は先頭/末尾の空白をスキップします — たいていはこちらが意図に合い ます。'wrap' が有効なとき、g0/g$ は画面行に対して、0/$ は論理行に対して働きます。| は特定の桁番号へジャンプします。
0 # first column (absolute start)
^ # first non-blank character
$ # end of line (last character)
g_ # last non-blank character
g0 # start of screen line (with wrap)
g$ # end of screen line (with wrap)
gm # middle of screen line
gM # middle of text line
| # column N (e.g. 10| = column 10)
+ # first non-blank of next line
- # first non-blank of previous line
_ # first non-blank of current line [count down]ファイル・画面の移動
H/M/L は表示範囲内でジャンプします。Ctrl-d/u は半ページスクロールです(全ページの Ctrl-f/b より方向感覚を保てます)。zz/zt/zb はカーソルを動かさずに現在行を画面の中央/上端/下端へスクロールします — 編集しながら文脈を保つのに非常に有用です。N% でファイルの割合の位置へジャンプします。
gg # go to first line
G # go to last line
Ngg / NG # go to line N (e.g. 50gg or 50G)
:N # go to line N (Ex command)
H # top of screen (High)
M # middle of screen
L # bottom of screen (Low)
N% # jump to N% of the file
Ctrl-f # scroll forward (full page)
Ctrl-b # scroll backward (full page)
Ctrl-d # scroll down (half page)
Ctrl-u # scroll up (half page)
zz # scroll current line to middle
zt # scroll current line to top
zb # scroll current line to bottomテキストの挿入
基本の挿入(i、I)
i/I はカーソルの前/行頭に挿入し、a/A はカーソルの後/行末に挿入します。gi は最後に挿入した位置(マーク '^)へ戻ります — Esc で別のことをしてから、続きを打ちたいときに便利です。gI は先頭の空白を無視して絶対的な 1 桁目へ移動します。
i # insert before cursor
I # insert at first non-blank (same as ^i)
gi # insert at last insert position (also sets mark)
gI # insert at column 1 (same as 0i)
a # insert after cursor
A # insert at end of line (same as $a)
# Examples:
# foo|bar + i -> foo|bar (cursor stays, type before)
# foo|bar + I -> |foobar (cursor at first non-blank)
# foo|bar + A -> foobar| (cursor at end)
# gi returns to where you last left insert mode —
# very useful after escaping to run a Normal-mode command.新しい行を開く(o、O)
o と O はカーソルの下/上に新しい行を開いて挿入モードに入ります。行を追加する最速の方法です — カーソルを行末に合わせる必要がありません。インデントは周囲の行から自動的にコピーされます('autoindent' で制御)。
o # open new line BELOW cursor, enter insert
O # open new line ABOVE cursor, enter insert
# Before (cursor on middle line):
# line one
# li|ne two
# line three
# After 'o':
# line one
# line two
# | <- new blank line, insert mode
# line three
# After 'O':
# line one
# | <- new blank line, insert mode
# line two
# line three変更コマンド(c、C、s、S)
c{motion} はモーションの対象を削除して挿入モードに入ります — 最も柔軟な編集コマンドです。C は c$(行末まで変更)、S は cc(行全体を変更)です。s は 1 文字を削除して挿入モードに入り、3s のように回数と組み合わせます。ciw/caw はテキストオブジェクトを使います(専用のセクションを参照)。
cw / ce # change to end of word
cb # change backward to word start
c$ / C # change to end of line
cc / S # change entire line
c0 # change to beginning of line
c^ # change to first non-blank
ct, # change up to (but not including) next ','
cfx # change up to and including next 'x'
ciw # change inner word (no surrounding whitespace)
caw # change a word (with surrounding whitespace)
cap # change around paragraph
s # substitute: delete char under cursor, insert
S # substitute: delete entire line, insert (like cc)置換モード(r、R、gr)
r は 1 文字を置き換えて即座にノーマルモードへ戻ります(モードの切り替えなし)。R は置換モードに入り、入力した文字が上書きされます — Backspace で元に戻せる点が、単に削除するだけの挿入モードと異なります。タブを含む作業では gr/gR(仮想置換)を使いましょう — テキストをずらす代わりにタブの位置合わせを保ちます。
r{x} # replace single char under cursor with x
gr{x} # virtual replace (doesn't shift tabs)
R # enter Replace mode (overwrite until Esc)
gR # virtual Replace mode (tabs stay aligned)
3r{x} # replace 3 chars with x (single char only)
# In Replace mode, typing overwrites existing text
# but Backspace restores the original characters.
# Tabs are preserved with virtual replace (gr/gR).
# Examples:
# abc|def + rx -> abc|xef (cursor advances)
# abc|def + R -> enter Replace mode
# type 'XYZ' -> abcXYZ|f
# Backspace -> abcXY|def (original restored)特殊な挿入
:r !cmd はシェルコマンドの出力をバッファに挿入します — コマンドの出力、日付、ファイル一覧の貼り付けに便利です。挿入モードでは、Ctrl-r に続けてレジスタ名でそのレジスタを挿入し、Ctrl-r = は Vimscript の式を評価して結果を挿入します。Ctrl-k は 2 つの ASCII 文字でダイグラフ(特殊文字)を入力します。
:r file.txt # insert contents of file below cursor
:r !command # insert output of shell command
:0r !date # insert date at top of file
:r !ls -la # insert directory listing
# Insert with special registers
Ctrl-r = # expression register: evaluate, insert result
Ctrl-r " # insert unnamed register
Ctrl-r % # insert current filename
# Insert from current file path
:i! !pwd # insert pwd output (no autoindent)
# Non-ASCII / digraphs (in insert mode)
Ctrl-k {ch1}{ch2} # digraph: e.g. Ctrl-k e' produces é
:digraphs # list available digraphs挿入モードのショートカット
Ctrl-h/w/u は挿入モード内で Backspace/単語削除/行まで削除として働きます。Ctrl-t/Ctrl-d は挿入モードを出ずにインデントを調整します — コード編集に非常に便利です。Ctrl-n/Ctrl-p はバッファとタグからキーワード補完を行います。Ctrl-o は 1 つだけノーマルコマンドを実行して挿入モードへ戻ります(例: Ctrl-o zz で再センタリング)。Ctrl-g u は undo の連鎖を区切るので、長い挿入を分割して元に戻せます。
# In insert mode:
Ctrl-h # delete char before cursor (Backspace)
Ctrl-w # delete word before cursor
Ctrl-u # delete to start of line
Ctrl-t # indent current line (one shiftwidth)
Ctrl-d # dedent current line (one shiftwidth)
Ctrl-n # keyword completion (forward)
Ctrl-p # keyword completion (backward)
Ctrl-o # execute one Normal command, return to insert
Ctrl-r {reg} # insert register contents
Ctrl-a # insert text typed in last insert mode
Ctrl-@ # insert last text + Esc (like Ctrl-a then Esc)
Ctrl-g u # break undo sequence (start new undo block)
Ctrl-] # trigger abbreviation without inserting編集コマンド(削除/ヤンク/ペースト)
削除コマンド
d{motion} は汎用の削除オペレータです — 任意のモーションと組み合わせられます。dd は行全体を削除します。x は dl(1 文字削除)のショートカットです。削除したテキストは無名レジスタ(とレジスタ 1)に入ります。テキストオブジェクトとの組み合わせ(ciw、dib)で強力な編集ができます。J は次の行を 1 つのスペースを挟んで現在行に連結します。
x # delete char under cursor (also 'dl')
X # delete char before cursor (also 'dh')
dd # delete current line
dw # delete to next word start
de # delete to end of word
d$ / D # delete to end of line
d0 # delete to beginning of line
d^ # delete to first non-blank
dgg # delete from cursor to first line
dG # delete from cursor to last line
J # join next line (removes leading whitespace, inserts space)
gJ # join next line without inserting space
3dd # delete 3 lines
dW # delete WORD (whitespace-separated)ヤンク(コピー)
y{motion} は削除せずにテキストをコピーします。yy は行をヤンクします。d には x のショートカットがありますが、y には 1 文字のショートカットがなくモーションが必要です。ヤンクは常にレジスタ 0 を更新します — 削除と区別するのに有用です。テキストオブジェクトを使いましょう: ya( は括弧の周りを、yi" は引用符の中をヤンクします。
y # yank {motion} (no character shortcut)
yy / Y # yank current line
yw # yank to next word start
ye # yank to end of word
y$ # yank to end of line
y0 # yank to beginning of line
yG # yank to end of file
ygg # yank to beginning of file
5yy # yank 5 lines
ya( # yank around parentheses
yi" # yank inside double quotes
yt, # yank up to (not including) next comma
# Yanked text goes to:
# " (unnamed register)
# 0 (yank register, only updated by y)ペースト
p はカーソルの後(行単位のデータなら下の行)にペーストし、P は前にペーストします。gp/gP はカーソルをペーストしたテキストの末尾へ移動します — 操作を連続させるときに便利です。]p/[p はペーストした行を周囲に合わせて再インデントします。'clipboard' を正しく設定すれば、クリップボードレジスタ(+)がシステムクリップボードと共有されます。
p # paste after cursor (linewise: line below)
P # paste before cursor (linewise: line above)
gp # paste after, leave cursor on last pasted char
gP # paste before, leave cursor on last pasted char
]p # paste after, reindent to match
[p # paste before, reindent to match
"+p # paste from system clipboard
"*p # paste from primary selection (X11)
# Linewise vs charwise:
# yy + p -> pasted as a new line below
# y$ + p -> pasted after cursor on same line
# Counts: 3p pastes the register 3 times.大文字小文字の切り替え
~ は 1 文字の大小を切り替えて進みます。g~/gu/gU はモーションやテキストオブジェクトと組み合わせられるオペレータです。ビジュアルモードでは U/u/~ が選択範囲に作用します。現在の単語を大文字にするには gUiw、行全体には gUU を使いましょう。大文字小文字だけが変わる非破壊的な操作です。
~ # toggle case of char under cursor (advances)
3~ # toggle case of next 3 chars
g~{motion} # toggle case of motion
gu{motion} # lowercase motion
gU{motion} # uppercase motion
g~~ # toggle case of current line
guu # lowercase current line
gUU # uppercase current line
g~~gg # toggle case to first line
# Visual mode:
# U # uppercase selection
# u # lowercase selection
# ~ # toggle case of selection
# Examples:
# hello + gUw -> HELLO
# HELLO + guw -> hello
# hello + g~w -> HELLO行の連結と分割
J は行を 1 つのスペースで連結し、gJ は何も挿入せずに連結します。:join は範囲に対して働きます。gq はフォーマットオペレータです — 'textwidth'(一般的には 80)に合わせて行 を折り返し、'formatoptions' を尊重します。段落を再整形するには gqip、1 行なら gqq です。自動折り返しを有効にするには 'textwidth=80' を設定します。
J # join next line with current (inserts space)
gJ # join next line without inserting space
3J # join next 3 lines into one
:[range]join # join lines in range (also :j)
:[range]join! # join without inserting space
# Splitting a line:
# In insert mode, press Enter (autoindent applies)
# In normal mode: r<Enter> replaces char with newline
# Break a long line at column 80 (with 'textwidth'):
gq{motion} # format motion text to 'textwidth'
gqq # format current line
gqip # format paragraph
gvgq # format visual selection
# Set text width:
:set textwidth=80繰り返しと元に戻す
. は最後の変更を繰り返します — Vim で最も有用な 1 キーです。u/Ctrl-r は undo/redo です。U は現在行へのすべての変更を取り消します。:earlier/:later は時間や回数で時間遡行でき、分岐をまたいでさえ可能です(Vim は undo ツリーを保持します)。分岐の確認には :undolist を使いましょう。@: は最後の Ex コマンドを、& は最後の置換を繰り返します。
. # repeat last change (most powerful key in Vim)
u # undo
Ctrl-r # redo
U # undo all changes on current line
:Nu # undo N changes
:earlier 10m # revert to state 10 minutes ago
:later 5 # redo 5 changes
:undolist # show undo tree branches
# Repeat with counts:
5. # repeat last change 5 times
# Repeat Ex commands:
@: # repeat last :command
& # repeat last :s (substitute)
# Repeat macros/marks across files:
:& # repeat last substitute on current line検索と置換
基本の検索
/ と ? は前方/後方を検索し、n/N で繰り返します。* はカーソル下の完全な単語(単語境界付き)を検索し、g* は部分文字列のマッチを検索します。:noh は次の検索まで現在のハイライトを消します。すべてのマッチを持続的にハイライトするには 'hlsearch'、タイプ中にインクリメンタルにマッチさせるには 'incsearch' を設定しましょう。
/pattern # search forward for pattern
?pattern # search backward
n # repeat search (same direction)
N # repeat search (opposite direction)
* # search forward for word under cursor
# # search backward for word under cursor
g* # search forward (loose, matches substring)
g# # search backward (loose)
# Search history:
# Press / then Up/Down to recall previous searches
# Clear search highlighting:
:nohlsearch # or :noh
# Toggle 'hlsearch' permanently:
:set hlsearch!検索オプション
'ignorecase' + 'smartcase' が推奨の組み合わせです: パターンに大文字が含まれない限り大小を無視します。\c/\C は検索ごとに大小の扱いを上書きします。\v は「very magic」モードを有効にし、多くの文字をエスケープなしで特殊扱いにします — よりきれいな正規表現の構文です。検索オフセット(e、b)はマッチからの相対位置にカーソルを置きます。
:set ignorecase # case-insensitive search (ic)
:set smartcase # case-sensitive if pattern has uppercase
:set hlsearch # highlight all matches (hls)
:set incsearch # show match as you type (is)
:set wrapscan # wrap around end of file (ws)
:set gdefault # add 'g' flag to all :s by default
# Per-search case override:
/foo\c # case-insensitive search for foo
/foo\C # case-sensitive search for foo
# Use very-magic mode (less escaping):
/foo\v(.+)@<=(bar) # very magic regex
# Search offsets:
/foo/e # cursor on last char of match
/foo/e+2 # cursor 2 chars past match
/foo/b-1 # cursor 1 char before match検索パターン(正規表現)
Vim の正規表現は PCRE と異なり、+、=、{、(、| にはバックスラッシュが必要です。\v プレフィックスの「very magic」モードではこれらがエスケープなしで特殊扱いになり(PCRE に近づく)、\< \> が単語境界を、\d/\w/\s が文字クラスを示します。キャプチャグループは \(...\)、後方参照は \1/\2 です。
# Standard Vim regex (default magic mode)
. # any char
* # zero or more (preceding atom)
\+ # one or more
\= # zero or one (optional)
\{n,m} # between n and m
^ $ # start/end of line
\< \> # word boundaries
[abc] # char class (a, b, or c)
[^abc] # negated char class
\( \) # group
\1 \2 # backreference
\| # or
# Predefined classes:
\d \D # digit / non-digit
\w \W # word char / non-word
\s \S # whitespace / non-whitespace
# Very magic (\v prefix) — less escaping:
/\v\w+\s+\w+ # word, spaces, word (no backslashes needed)
/\v(%d+) # capture one-or-more digits置換コマンド
:[range]s/pattern/replacement/flags が置換コマンドです。:% はファイル全体を意味します。'g' フラグなしでは行ごとに最初のマッチだけが置換され、'g' で全部置換されます。'c' は確認を求めます(y/n/a/q/l)。グループ構文を簡略化するには very-magic の \v を使いましょう。キャプチャグループは置換側で \1、\2 として参照します。
:[range]s/old/new/[flags]
# Basic:
:s/old/new/ # replace first 'old' on current line
:s/old/new/g # replace all 'old' on current line
:%s/old/new/g # replace all in whole file
:%s/old/new/gc # confirm each replacement
:%s/old/new/gi # case-insensitive
# Range examples:
:5,10s/old/new/g # lines 5-10
:.,$s/old/new/g # current line to end
:'a,'bs/old/new/g # from mark a to mark b
:'<,'>s/old/new/g # visual selection
:1,$s/old/new/g # whole file (same as %)
# Replace with capture groups:
:%s/\(\w\+\),\(\w\+)/\2,\1/ # swap two comma-separated words
:%s/\v(\w+),(\w+)/\2,\1/ # same with very-magic置換フラグと特殊な置換
よく使うフラグ: g(全部)、c(確認)、i(大小を無視)、n(件数だけ数える)。置換側の & はマッチしたテキストを挿入します。\u/\U/\l/\L は置換の大文字小文字を変えます。改行の挿入には \r を使いましょう(置換内の \n は null バイトです)。'n' フラグは何も変更せずマッチ数を数えるのに優れています。
# Flags:
g # all occurrences on each line (not just first)
c # confirm each substitution
i # ignore case
I # don't ignore case
e # don't error if no match
p # print last substituted line
n # count matches, don't substitute
# Special chars in replacement:
& # the matched text
\0 # the matched text (same as &)
\1..\9 # capture groups
\u # next char uppercase
\U # rest of string uppercase (until \e or \E)
\l \L # lowercase (single / until \e)
\r # split into new line
\n # null byte (use \r for newline)
# Examples:
:%s/foo/&bar/g # foo -> foobar
:%s/\v(\w+)/\U\1/g # uppercase every word
:%s/, /,\r/g # split lines on ', '
:%s/old/new/gn # count matches onlyグローバルコマンド(:g)
:g はパターンにマッチしたすべての行に対して Ex コマンドを実行します — 強力な「global」エディタです。:v(または :g!)は非マッチ行に対して実行します。任意の Ex コマンドと組み合わせられます: d(削除)、m(移動)、t(コピー)、s(置換)、normal(ノーマルモードコマンドの実行)。マーク付き行への一括処理に有用です。順序が重要です: :g はデフォルトで上から下へ処理します。
:[range]g/pattern/cmd # run cmd on each matching line
:[range]g!/pattern/cmd # run cmd on NON-matching lines
:v/pattern/cmd # same as :g! (inverse)
# Common uses:
:g/^$/d # delete all blank lines
:g/TODO/d # delete all lines with TODO
:g/pattern/p # print all matching lines
:g/pattern/normal @a # run macro a on each matching line
:g/pattern/m0 # move matching lines to top (reverse order)
:g/pattern/t$ # copy matching lines to end
:g/pattern/s/old/new/g # substitute on matching lines only
# Combined with Ex range:
:g/^#/s/foo/bar/g # in lines starting with #, replace foo with bar
# Multiple commands per match:
:g/pattern/d|t0 # delete then copy (chained with |)ビジュアルモード
ビジュアルモードの種類
v/V/Ctrl-v は文字/行/ブロックを選択します。gv は最後のビジュアル選択を再選択します — 操作の再適用に便利です。o は選択範囲のもう一方の端へ移動します(どちらの方向にも延長できます)。ブロック選択では O が同じ行のもう一方の角へ移動します。
v # charwise visual (select characters)
V # linewise visual (select whole lines)
Ctrl-v # blockwise visual (select rectangle)
gv # reselect last visual selection
# In visual mode:
o / O # move cursor to other end of selection (corner for block)
Esc / v # exit visual mode (toggle)
# Quick selections from normal mode:
vap # select around paragraph
vip # select inside paragraph
i" # then press v... actually ciw etc. work directly
# Switching between types:
# v then V -> linewise (extends to whole lines)
# V then v -> charwise
# Ctrl-v -> blockwiseビジュアルでの操作
選択範囲を得た後は、d/c/y/x が期待どおりに働きます。= は自動インデントです(コードの再フォーマットに便利)。>/< は 1 shiftwidth 分のインデント/解除です。! は選択範囲をシェルコマンドに渡し、出力で置き換えます。ビジュアルモードで : を押すと範囲に '<,'> が自動入力されるため、:s/old/new/g は選択範囲にだけ適用されます。
# In visual mode, press:
d / x # delete selection
c / s # change selection (delete, enter insert)
y # yank (copy) selection
~ # toggle case of selection
u / U # lowercase / uppercase selection
> # indent selection
< # dedent selection
= # auto-indent selection (reformat)
!cmd # filter through external command
:r !cmd # (after yank) paste command output
# Replace entire selection with a char:
r{x} # replace every char with x
# Print line numbers of selection:
g Ctrl-g # count words/chars/lines in selection
# Search within selection (after selecting, type :):
# '<,'>s/old/new/g -- range auto-filledビジュアルブロックのテクニック
ビジュアルブロック(Ctrl-v)は Vim で最も強力な機能の 1 つです。I と A はブロックの前/後に挿入し — Esc の後、各行に同じテキストが複製されます。複数行にコメントのプレフィックスを付けたり接尾辞を追加したりする最も簡単な方法です。c はブロック全体を変更し、r{x} はすべての文字を x に置き換えます。ブロック編集は行の長さが似ているときにきれいに機能します。
# Enter block visual: Ctrl-v
# Select a column rectangle, then:
I # insert BEFORE block (text typed appears in front)
# Type text, then Esc -> inserted on every line of block
A # insert AFTER block (text appears at end of each line)
# Esc propagates the insert to all lines
c # change block (delete, enter insert; Esc propagates)
r{x} # replace every char in block with x
# Common use cases:
# 1. Add a comment to a column of lines:
# Ctrl-v select first column, I, type '# ', Esc
# 2. Add semicolons at end of selected lines:
# Ctrl-v select end column, $A;, Esc
# 3. Delete a column:
# Ctrl-v select, d
# 4. Replace a column with same char:
# Ctrl-v select, r;ビジュアル行モード
V は行全体を選択します。V の後の定番操作は d/y/>/</= です。:m は選択範囲を移動します(例: :'<,'>m0 で先頭へ)。:t は複製します。'< と '> は最後のビジュアル選択の始端/終端のマークで — スクリプトで有用です。gv は最後のビジュアル範囲を再選択します。
V # enter linewise visual
5V # select 5 lines (current + 4 below)
ggVG # select entire file
:'<,'> # range referring to last visual selection
# After selecting lines (V), useful commands:
d # delete lines
y # yank lines (linewise)
> # indent lines
< # dedent lines
= # auto-indent lines
:m +2 # move selection down 2 lines
:m -3 # move selection up 3 lines
:t . # duplicate lines (copy below selection)
:g/^/m0 # reverse line order (whole file)
# Reselect last visual:
gv # reselect last visual selection
'< # mark: start of last visual
'> # mark: end of last visualテキストオブジェクトとの併用
テキストオブジェクトはビジュアルモードでも機能し — 現在の選択を拡張します。vi( は括弧の内側を、va( は括弧を含めて選択します。オブジェクトを繰り返すと(vawaw)さらに拡張されます。カーソルを手動で合わせるより多くの場合速いです。オペレータとの組み合わせでは: ciw はカーソルが単語内のどこにあってもその単語を変更します。
# In visual mode, text objects EXTEND the selection:
# After pressing v (charwise), type:
aw # extend selection to include next 'a word'
iw # extend selection to inner word
ab # around brackets ()
ib # inside brackets ()
aB # around braces {}
iB # inside braces {}
a" # around double-quoted string
i" # inside double-quoted string
ap # around paragraph
ip # inside paragraph
# Repeated text objects extend selection:
# vaw -> select word + trailing space
# vawaw -> extend to next word + space
# Switch between inner and around:
# vi( -> select inside parens
# va( -> extend to include the parensビジュアル検索と連番
ビジュアルモードで : を押すと範囲に '<,'> が事前入力され — 置換は選択範囲にだけ適用されます。ビジュアル選択を検索するには y/ の後で Ctrl-r " Enter(レジスタを検索に貼り付け)。ビジュアルブロックでの g Ctrl-a は連番を生成します — 同じ数字の列から番号付きリスト(1、2、3、...)を作るのに非常に便利です。
# Search within visual selection:
# 1. Visually select (v/V/Ctrl-v)
# 2. Press : -> :'<,'> appears
# 3. Type s/old/new/g -> substitute only in selection
# Search for current visual selection (forward):
# In visual mode, type:
# \V then / (very-nomagic, escapes regex chars)
# Or use a plugin (e.g. vim-visual-star-search)
# Manual method:
# y/ then Ctrl-r " Enter -> search for selection
# Increment/decrement numbers (visual block):
# Select a column of numbers (Ctrl-v)
Ctrl-a # increment every number in selection by 1
Ctrl-x # decrement every number in selection by 1
g Ctrl-a # increment with running counter (1,2,3,...)
g Ctrl-x # decrement with running counter
# Example: turn 0,0,0,0 into 1,2,3,4:
# Ctrl-v select column, g Ctrl-aバッファ
バッファの基本
バッファはメモリ上のファイルです。:e はファイルを新しいバッファで開きます。:ls はすべてのバッファをステータスフラグ付きで一覧表示します(% = 現在、# = 代替、+ = 変更あり、h = 非表示)。:b N で番号、:b name で一意なプレフィックスで切り替えます。Ctrl-6(または :b#)は現在と代替のバッファを切り替えます — 非常に頻用です。