Skip to content

Vim チートシート

効率的なテキスト編集のための、高度にカスタマイズ可能なテキストエディタ。

01

はじめに

モードと基本の移動

Vim はモーダルエディタです — モードごとに役割が異なります。Esc はどのモードからでもノーマルモードへ戻ります。hjkl キーはホームポジションから手を動かさずに済みます。w/b で単語移動、0/$ で行頭/行末、gg/G でファイルの先頭/末尾、:N で N 行目へジャンプします。

vim
# 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! を使いましょう。

vim
: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' で設定可能)。

vim
: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 は前の単語の末尾へ移動します(あまり使わないが便利)。

vim
# 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/$ は論理行に対して働きます。| は特定の桁番号へジャンプします。

vim
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% でファイルの割合の位置へジャンプします。

vim
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
02

テキストの挿入

基本の挿入(i、I)

i/I はカーソルの前/行頭に挿入し、a/A はカーソルの後/行末に挿入します。gi は最後に挿入した位置(マーク '^)へ戻ります — Esc で別のことをしてから、続きを打ちたいときに便利です。gI は先頭の空白を無視して絶対的な 1 桁目へ移動します。

vim
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' で制御)。

vim
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 はテキストオブジェクトを使います(専用のセクションを参照)。

vim
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(仮想置換)を使いましょう — テキストをずらす代わりにタブの位置合わせを保ちます。

vim
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 文字でダイグラフ(特殊文字)を入力します。

vim
: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 の連鎖を区切るので、長い挿入を分割して元に戻せます。

vim
# 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
03

編集コマンド(削除/ヤンク/ペースト)

削除コマンド

d{motion} は汎用の削除オペレータです — 任意のモーションと組み合わせられます。dd は行全体を削除します。x は dl(1 文字削除)のショートカットです。削除したテキストは無名レジスタ(とレジスタ 1)に入ります。テキストオブジェクトとの組み合わせ(ciw、dib)で強力な編集ができます。J は次の行を 1 つのスペースを挟んで現在行に連結します。

vim
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" は引用符の中をヤンクします。

vim
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' を正しく設定すれば、クリップボードレジスタ(+)がシステムクリップボードと共有されます。

vim
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 を使いましょう。大文字小文字だけが変わる非破壊的な操作です。

vim
~      # 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' を設定します。

vim
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 コマンドを、& は最後の置換を繰り返します。

vim
.        # 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
04

検索と置換

基本の検索

/ と ? は前方/後方を検索し、n/N で繰り返します。* はカーソル下の完全な単語(単語境界付き)を検索し、g* は部分文字列のマッチを検索します。:noh は次の検索まで現在のハイライトを消します。すべてのマッチを持続的にハイライトするには 'hlsearch'、タイプ中にインクリメンタルにマッチさせるには 'incsearch' を設定しましょう。

vim
/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)はマッチからの相対位置にカーソルを置きます。

vim
: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 です。

vim
# 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 として参照します。

vim
:[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' フラグは何も変更せずマッチ数を数えるのに優れています。

vim
# 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 はデフォルトで上から下へ処理します。

vim
:[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 |)
05

ビジュアルモード

ビジュアルモードの種類

v/V/Ctrl-v は文字/行/ブロックを選択します。gv は最後のビジュアル選択を再選択します — 操作の再適用に便利です。o は選択範囲のもう一方の端へ移動します(どちらの方向にも延長できます)。ブロック選択では O が同じ行のもう一方の角へ移動します。

vim
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 は選択範囲にだけ適用されます。

vim
# 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 に置き換えます。ブロック編集は行の長さが似ているときにきれいに機能します。

vim
# 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 は最後のビジュアル範囲を再選択します。

vim
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 はカーソルが単語内のどこにあってもその単語を変更します。

vim
# 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、...)を作るのに非常に便利です。

vim
# 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
06

バッファ

バッファの基本

バッファはメモリ上のファイルです。:e はファイルを新しいバッファで開きます。:ls はすべてのバッファをステータスフラグ付きで一覧表示します(% = 現在、# = 代替、+ = 変更あり、h = 非表示)。:b N で番号、:b name で一意なプレフィックスで切り替えます。Ctrl-6(または :b#)は現在と代替のバッファを切り替えます — 非常に頻用です。

vim
:e file.txt     # open file in new buffer (current window)
:enew           # new empty buffer
:ls / :buffers  # list all buffers
:b N            # go to buffer N (by number from :ls)
:b name         # go to buffer by name (unique prefix)
:bn             # next buffer
:bp             # previous buffer
:b# / Ctrl-6    # alternate buffer (last edited)
:ball           # open all buffers in horizontal splits
:vertical ball  # open all buffers in vertical splits

# Buffer list symbols:
#   %   current window's buffer
#   #   alternate buffer
#   a   active (loaded and visible)
#   h   hidden (loaded but not visible)
#   -   not modifiable
#   =   read-only
#   +   modified

バッファの切り替え

:bn/:bp はバッファを順送りします。Ctrl-6 は直近の 2 つのバッファを切り替えます — 行き来する最速の方法です。'hidden' を設定すると、変更済みバッファから切り替えても保存を強制されません — Vim が代わりに隠します。バッファ番号を忘れたら :ls の後に :b N を使いましょう。fzf.vim のようなプラグインはファジーなバッファ切り替えをずっと速くします。

vim
:bn / :bnext      # next buffer (wraps around)
:bp / :bprev      # previous buffer
:bf / :bfirst     # first buffer
:bl / :blast      # last buffer
:b#               # alternate buffer (Ctrl-6)
:N b              # go to buffer number N (e.g. 3b)
:b name<tab>      # tab-complete buffer name
:ls then :b N     # two-step navigation

# Faster navigation (set in vimrc):
:nmap <C-n> :bn<CR>
:nmap <C-p> :bp<CR>

# Jump to a buffer with fuzzy matching (with fzf.vim):
:Buffers          # fuzzy-select from buffer list

# Hide current buffer without saving (if 'hidden' is set):
:hide             # or :bn with 'set hidden'

バッファの操作

:bd はバッファをリストから外します(ファイルは閉じられる)。:bw はさらにマークやバッファローカル変数も消去します。:%bd | e# は現在のバッファ以外をすべて削除します — よくある掃除のパターンです。:bufdo はすべてのバッファで Ex コマンドを実行します — グローバルな置換に強力ですが、エラーに注意しましょう(! で無視するか、:s に 'e' フラグを追加)。

vim
:bd / :bdelete       # delete current buffer
:bd N               # delete buffer N
:bd name            # delete buffer by name
:bw / :bwipeout     # wipe buffer (also clears marks, vars)
:N,N bd             # delete buffers in range
:%bd                # delete all buffers
:%bd | e#           # delete all but current

:bn!                # force switch (don't save current)
:wall               # write all buffers
:bufdo cmd          # run cmd in every buffer
:bufdo! cmd         # same but ignore errors

# Useful patterns:
:bufdo %s/old/new/ge   # substitute in all buffers
:bufdo setlocal nowrap # apply setting to all buffers

# Save and quit current buffer:
:wq                 # write current and quit (closes window)

隠しバッファ

'set hidden'(強く推奨)を設定すると、変更済みバッファから保存せずに切り替えられます — Vim がメモリに保持します。'hidden' がないと、保存するか ! で破棄するまで切り替えがブロックされます。:ls は隠しバッファに 'h' を、変更があれば '+' を表示します。この設定は生産的なマルチファイル編集に不可欠です。

vim
:set hidden         # allow switching from modified buffers
:set nohidden       # force save/abandon when switching

# With 'hidden' set:
#   :bn             # switch even if current is modified (no save)
#   :q              # if buffer is modified, prompts to save
#   :qa!            # quit all without saving
#   :wa             # write all (hidden + visible)

# Buffer with changes still in memory:
:ls                  # shows 'h' flag for hidden, '+' for modified

# Recover list of hidden buffers:
:ls h               # only hidden buffers

# Save a hidden buffer:
:w                  # save current (if visible)
:N w                # save buffer N
:wall               # save all buffers

# Common workflow with hidden:
#   :e file1  -> make changes -> :e file2 -> :e file1 (changes preserved)

引数リスト

arglist はバッファリストとは別のリストです — コマンドラインで渡されたか、:args で設定されたファイルの集合です。:n/:prev で移動し、:argdo は arglist のすべてのファイルで Ex コマンドを実行します — :argdo %s/foo/bar/ge | update のような一括処理に完璧です。arglist はバッファリストより的を絞った管理になりがちです。

vim
# Open files in arglist:
vim file1.txt file2.txt    # initial args
:args file1 file2 file3    # replace arglist
:argadd file4              # add to arglist
:arga *.py                 # add all Python files
:argdelete file2           # remove from arglist

# Navigate arglist:
:n / :next         # next file in arglist
:prev / :Next      # previous file
:first             # first file
:last              # last file
:rewind            # rewind to first file

# Process all files:
:argdo %s/old/new/ge    # substitute in every arg file
:argdo set ff=unix | w  # convert line endings in all

# Show current arglist:
:args              # show files (current marked with [ ])

バッファリストの管理

:ls はバッファを一覧表示し、:ls! は未リストのもの(削除済みだが記憶している)も含めます。:sb は現在のウィンドウのバッファを変えずに、split でバッファを開きます。「最近閉じたバッファ」の undo は組み込みにありませんが、プラグインはあります。:bufdo vimgrepadd の後に :copen を組み合わせれば、quickfix リストで開いている全バッファを横断検索できます。

vim
:ls                 # list all buffers
:ls!                # list including unlisted buffers
:files              # alias for :ls

# Move current buffer to a specific position:
:N b N              # buffer number N

# Quickly inspect related files:
:b <tab>            # tab-complete buffer names
:b #<tab>           # buffers matching '#'

# Find buffer containing a pattern:
:vimgrep /pattern/ %   # current buffer only
:bufdo vimgrepadd /pattern/ %  # all buffers (then :copen)

# Open buffer in a specific window:
:sb N              # open buffer N in horizontal split
:vertical sb N     # open buffer N in vertical split
:tab split +b N    # open buffer N in new tab

# Restore closed buffers:
# (No built-in, but plugins like vim-molten or
# vim-restore-buffers can help)
07

マークとジャンプ

マークの設定

マークはファイル内の名前付き位置です。小文字(a-z)はバッファローカル、大文字(A-Z)は Vim のセッションをまたいで残るファイルマークです。番号付きマーク(0-9)は自動で設定されます — 0 は Vim が最後に閉じた位置、1-9 は最近閉じたファイルです。:marks で一覧、:delm で削除します。

vim
m{a-zA-Z}    # set mark at cursor position
ma           # set mark 'a' (lowercase, buffer-local)
mA           # set mark 'A' (uppercase, file mark)
m'           # set the unnamed mark (jump before/after)

# Lowercase marks (a-z):
#   Local to current buffer
#   Lost when buffer is unloaded

# Uppercase marks (A-Z):
#   File marks — preserved across sessions
#   Work even after the file is closed

# Numbered marks (0-9):
#   Set automatically by Vim
#   0 = position when Vim was last closed
#   1-9 = positions of last 9 closed files

# View marks:
:marks       # list all marks
:marks a b c # specific marks
:delm! a     # delete mark 'a' (force)

マークへのジャンプ

`(バッククォート)は正確な位置(行+桁)へジャンプし、'(アポストロフィ)はマーク行の最初の非空白へジャンプします。`A はマーク A を含むファイルが閉じていても開きます。`. は最後にテキストを変更した位置へ、`[ と `] は最後にヤンク/削除した領域の両端へ、`< と `> は最後のビジュアル選択の両端へジャンプします。

vim
\`{a-zA-Z}    # jump to mark (line AND column)
'{a-zA-Z}     # jump to mark (line only, column 1)

\`a          # jump to mark 'a' (exact position)
'a           # jump to line of mark 'a'
\`A          # jump to file mark 'A' (opens file if closed)
\`.          # jump to position of last change in this buffer
\`"          # jump to position when file was last closed
\`[          # jump to start of last yanked/changed text
\`]          # jump to end of last yanked/changed text
\`<          # jump to start of last visual selection
\`>          # jump to end of last visual selection
\`^          # jump to last insert position (also gi)

# Jump to next/prev mark in alphabetical order:
:[count]next  # (no built-in, requires plugin)

ジャンプリスト

Vim は重要なカーソル移動の jumplist を保持します。Ctrl-o/Ctrl-i で前後に移動します。「重要」なのはジャンプ(G、gg、検索、マークへのジャンプ、タグジャンプ)であって、j/k/w のような通常のモーションは含まれません。:jumps でリストを表示します。jumplist はウィンドウごとに保持され、viminfo/shada でセッションをまたいで残ります。

vim
Ctrl-o    # jump BACK in jumplist (older positions)
Ctrl-i    # jump FORWARD in jumplist (newer positions)
Tab       # same as Ctrl-i
:ju       # show jumplist (:jumps)

# What counts as a jump?
#   - Movement commands: G, gg, H, M, L, %
#   - Search: /, ?, n, N, *, #
#   - Mark jumps: 'x, `x (NOT mm)
#   - Buffer switch: Ctrl-6, :b, :e
#   - Tag jumps: Ctrl-]
#   NOT counted: j, k, w, b, h, l (regular motions)

# Max jumplist size: 100 entries by default
:set jumpoptions=stack   # treat jumplist like a stack

# Clear jumplist:
:clearjumps   # or :clj

変更リスト

changelist は編集位置(ナビゲーションではなく)を追跡します。g; で前の編集へ、g, で次の編集へ移動します。変更をさかのぼって歩くのに有用です: 「さっきどこを編集していたっけ?」。:changes でリストを表示します。jumplist と違い、changelist はバッファごとです。現在バッファの直近の変更には `.` を組み合わせましょう。

vim
g;        # go to OLDER position of last change
g,        # go to NEWER position of last change
:changes  # list changelist

# Each entry shows:
#   change number, line, column, text of change

# What counts as a change?
#   - Any insertion, deletion, or substitution
#   - Records the position BEFORE the change

# Differences from jumplist:
#   - Changelist tracks EDITS, not movements
#   - Per-buffer (not per-window)
#   - Limited to 100 entries

# Combine with marks:
\`.       # last change position in current buffer
g;         # previous change position

# Common pattern: g;g;g; to walk back through edits

ファイルマーク(A-Z)

大文字のマーク(A-Z)はファイルマークです — ファイルと位置を記憶し、Vim のセッションをまたいで残ります(viminfo に保存)。foo.txt で mA を設定すれば、どこからでも、Vim を再起動した後でさえ `A でその位置へ戻れます。プロジェクト内の重要なファイル/位置のブックマークとして使いましょう。

vim
# Setting a file mark:
mA          # set mark 'A' at cursor (in current file)
mB          # set mark 'B' (in current file)

# Jumping to a file mark:
\`A          # if file is open: jump to position
\`A          # if file is closed: open it, then jump
'A          # jump to first non-blank of mark's line

# File marks persist across Vim sessions:
#   Stored in viminfo (or shada in Neovim)
#   Restored on next Vim launch

# Use cases:
#   1. Bookmark a function: mA in function definition
#   2. Quick jump between files: `A, `B
#   3. Project navigation: set marks in important files

# Listing file marks:
:marks A-Z   # show only file marks

# Deleting:
:delm A      # delete file mark A (must be in its file)

組み込みの特殊マーク

Vim は特殊なマークを自動で設定します。`.` は最後の変更、`[ と `] は最後にヤンク/削除した領域の両端、`< と `> は最後のビジュアル選択の両端、`^ は挿入モードが最後に終わった位置(gi でそこへジャンプし再び挿入モードに入る)。`" はファイルが最後に閉じられた位置です — 作業の再開に便利です。

vim
\`.    # position of last change in current buffer
\`"    # position when file was last exited
\`[    # start of last yanked/changed text
\`]    # end of last yanked/changed text
\`<    # start of last visual selection
\`>    # end of last visual selection
\`^    # position where insert mode was last stopped
\`'    # position before latest jump (where you came FROM)

# Common uses:
\`[\`]  # operate on last yanked range: \`[v\`]U  (uppercase it)
\`<\`>  # re-select last visual: \`<v\`> or gv

# Re-select last visual selection:
gv        # easier than \`<v\`>

# Re-select last pasted text:
\`]v\`[   # or use a mapping: nnoremap gp \`]v\`[

# Return to last insert position:
gi        # jump to `^ and enter insert mode
08

テキストオブジェクト

単語と文のオブジェクト

テキストオブジェクトは意味的な単位に対して操作できます。'aw'(around word)は後続の空白を含み — daw は空白ごと詰めます。'iw'(inner word)は空白を残すので — diw は空白を残します。as/ap は文/段落版です。オブジェクトを繰り返すと(dawaw)選択が拡張されます。d/c/y/v オペレータと組み合わせるのが最も有用です。

vim
# Operators (d/c/y/v) + text object:
aw   # 'a word' - word + trailing whitespace
iw   # 'inner word' - word only (no whitespace)
aW   # 'a WORD' - WORD + trailing whitespace
iW   # 'inner WORD' - WORD only
as   # 'a sentence' - sentence + trailing space
is   # 'inner sentence' - sentence only
ap   # 'a paragraph' - paragraph + trailing blank line
ip   # 'inner paragraph' - paragraph only

# Examples:
daw    # delete word + trailing space (closes gap)
diw    # delete word only (leaves whitespace)
cas    # change sentence (with trailing space)
yap    # yank paragraph (with trailing blank line)
gqip   # format (wrap) inner paragraph

# Repeated: dawaw extends to next word

括弧のオブジェクト

括弧のオブジェクトは ()、[]、{}、<> に働きます。a(around)は括弧を含め、i(inner)は括弧を除きます。ci( は括弧を残したまま中身を変更します — 関数の引数の編集に完璧です。ネストしているときは最も内側のペアに作用します。at/it は HTML/XML タグに働きます(例: cit はタグの内側の内容を変更)。

vim
# Brackets (any of ( [ { <):
ab / ib   # around / inside ()
aB / iB   # around / inside {} (also a{ / i{)
a( / i(   # same as ab / ib
a[ / i[   # around / inside []
a{ / i{   # same as aB / iB
a< / i<   # around / inside <>

# Examples:
ci(      # change text inside ( ... )
daB      # delete {...} block including braces
yi[      # yank text inside [...]
vaB      # visually select around {...}

# Special: 'tag' objects (HTML/XML):
at / it  # around / inside <tag>...</tag>

# Tip: works with mismatched brackets too:
#   ci) on (foo bar) changes 'foo bar'

# Nested: ci( in ((a)(b)) changes innermost

引用符のオブジェクト

引用符のオブジェクト(a"/i"、a'/i'、a`/i`)は引用符付き文字列に働きます。カーソルが引用符の中にいる必要はなく — Vim が最も近いペアを見つけます。ci" は引用符を残したまま文字列の内容を変更します — 文字列リテラルの編集に非常に有用です。'a' で引用符を含め、'i' で除外します。

vim
a"   # around double-quoted string (includes quotes)
i"   # inside double-quoted string (no quotes)
a'   # around single-quoted string
i'   # inside single-quoted string
a\`   # around backtick-quoted string
i\`   # inside backtick-quoted string

# Examples:
ci"     # change text inside "..."
da"     # delete "..." (including quotes)
yi'     # yank text inside '...'
va\`    # visually select around \`...\`

# Cursor can be ANYWHERE on the line — Vim finds the
# nearest quote pair containing or following the cursor.

# Special: with counts
3a"     # around 3 consecutive quoted strings

# Tip: ci" when cursor is on the quote itself works too

文と段落のオブジェクト

文は . ! ? の後に空白(または段落の切れ目)が続いて終わります。段落は空行で区切られたブロックです。'a' は後続の空白を含み、'i' は除外します。オペレータとの組み合わせに有用です: gqap は段落を再整形し、>ip はインデントし、das は文を削除します。( と ) のモーションは文の間を移動します。

vim
# Sentence: ends with . ! ? followed by whitespace
as / is    # around / inner sentence

# Paragraph: blocks of text separated by blank lines
ap / ip    # around / inner paragraph

# Examples:
das        # delete a sentence
cip        # change inside paragraph
vap        # select around paragraph (with trailing blank)

# Differences:
#   'a' (around): includes trailing whitespace/blank line
#   'i' (inner): no trailing whitespace

# Use cases:
#   gqap    # reformat (wrap) the paragraph
#   >ap     # indent the paragraph
#   vip     # select inside paragraph
#   :'<,'>s/old/new/g   # substitute in selected paragraph

# Sentence motion commands (not objects):
(   # previous sentence start
)   # next sentence start

タグと URL のオブジェクト(プラグイン)

組み込みの at/it は HTML/XML タグに働きます。cit はタグの内側の内容を変更し、dat は開き/閉じを含むタグ全体を削除します。ネストしたタグでは、it が最も内側を選び、vat が外側へ拡張します。プラグインはさらにオブジェクトを追加します: vim-textobj-url(au/iu)、vim-indent-object(ai/ii で同じインデントのブロック — コードに最適)。

vim
# Built-in tag object (HTML/XML):
at / it    # around / inside <tag>...</tag>

# Examples:
cit        # change inner tag text: <p>text</p> -> <p>|</p>
dat        # delete entire tag: <p>text</p> -> (gone)
vit        # visually select inner tag text
yat        # yank entire tag including <tag>...</tag>

# For nested tags, 'it' selects the innermost:
#   <div><p>text</p></div>
#   cit on 'text' changes 'text' only
#   vat extends selection outward

# URL objects (require a plugin like vim-textobj-url):
#   au / iu  # around / inside URL

# Indent objects (require vim-indent-object):
#   ai / ii  # around / inside same-indent block
#   aI / iI  # entire indentation level

# Common plugin combos:
#   vai      # select around indent block (great for code)

テキストオブジェクトの活用(レシピ)

テキストオブジェクトは任意のオペレータ(d/c/y/v/>/</=)と組み合わさって強力な編集を実現します。ciw はカーソルを正確に合わせなくても単語を変更できます。ci"/ci(/ci[ は引用符/括弧の中を変更します。gqip は段落を再整形します。これらを習得することが、Vim で思考の速さで編集する鍵です。

vim
# Common editing recipes using text objects:

# Word:
ciw      # change word (regardless of cursor position in it)
daw      # delete word + space (closes gap)
yiw      # yank inner word (no whitespace)

# Quotes:
ci"      # change inside "..."
ci'\`    # change inside '...' or \`...\`
da"      # delete the entire string (with quotes)

# Brackets:
ci(      # change inside (...) -- great for args
daB      # delete {...} block (function body)
ci[      # change inside [...]

# Sentences & paragraphs:
cas      # change a sentence
dap      # delete a paragraph
gqip     # reformat paragraph

# HTML tags:
cit      # change tag content
vat      # select tag, then vat again to extend

# Combos with counts:
2daw     # delete two words
c2aw     # change two words
09

レジスタ

レジスタの基本

レジスタは Vim のクリップボードです。"ayy で行をレジスタ a にヤンクし、"ap で a からペーストします。レジスタはたくさんあります: 名前付き(a-z)、追記(A-Z)、番号付き(1-9)、特殊(無名 "、ヤンク 0、クリップボード + など)。:reg で一覧表示します。挿入モードでは Ctrl-r {reg} でレジスタを挿入します。大文字のレジスタ名は追記(APPEND)です。

vim
# Registers store text. 10 named (a-z), 10 append (A-Z),
# 9 numbered (1-9), and several special ones.

"ay   # yank into register 'a' (then motion: "ayy, "ayw)
"ap   # paste from register 'a'
"ad   # delete into register 'a' (e.g. "add)
"Ay   # APPEND to register 'a' (uppercase = append)

# View all registers:
:reg           # list all registers
:reg a b c     # list specific registers
:reg +         # show clipboard register

# Use a register with operators:
"aD            # delete to end of line into 'a'
"byy           # yank line into 'b'
"cp            # paste register 'c'

# Insert mode: Ctrl-r + register
Ctrl-r a       # insert contents of register 'a'
Ctrl-r =       # expression register (compute, insert)

# Search from a register:
/ then Ctrl-r a   # search register 'a' contents

名前付き・番号付きレジスタ

名前付きレジスタ(a-z)はユーザーが管理し、A-Z は a-z に追記します。番号付きレジスタ(1-9)は最近の削除を自動で追跡します — 1 が最も新しく、新しい削除のたびに後ろへずれます。レジスタ 0 は最後のヤンクだけを保持します(削除は上書きしない)— ヤンクしてから削除するワークフローに有用です。"- は小さな(行未満の)削除を保持します。

vim
# Named registers (a-z, A-Z):
"ayy      # yank line into 'a'
"byiw     # yank inner word into 'b'
"Ayy      # append yanked line to 'a' (uppercase)

# Numbered registers (1-9) — auto-filled by deletes:
"1        # last delete (largest)
"2        # second-to-last delete
...       # shift older with each new delete
"9        # oldest tracked delete

# Small delete register:
"-        # stores deletes < 1 line (e.g. dw)

# Yank register (separate from deletes):
"0        # last YANK only (not affected by deletes)

# Examples:
"0p       # paste last yank (won't paste a delete)
"1p       # paste last delete
".        # last inserted text (read-only)
"%        # current file name (read-only)

特殊レジスタ

特殊レジスタ: ". = 最後に挿入したテキスト、"% = 現在のファイル、"/ = 最後の検索、": = 最後のコマンド。"_ はブラックホールです — 書き込んだテキストを破棄します(他のレジスタを汚したくない削除に便利)。"+ はシステムクリップボード、"* は X11 のプライマリ選択です。"= は Vimscript の式を評価して結果を挿入します。

vim
# Read-only registers:
".        # last inserted text
"%        # current file name
"#        # alternate file name
":        # last Ex command
"/        # last search pattern

# Read/write registers:
"0        # last yank (not overwritten by deletes)
"-        # last small delete (less than one line)
"_        # black hole register (discard, like /dev/null)
"=        # expression register (evaluate Vimscript)

# Clipboard / selection:
"+        # system clipboard (Ctrl-C / Ctrl-V)
"*        # primary selection (X11 middle-click)

# Examples:
"_dd      # delete line without saving to register
"+y       # yank to system clipboard (then Ctrl-V elsewhere)
"*p       # paste from X11 primary selection

# Expression register (in insert mode):
Ctrl-r =strftime('%Y-%m-%d')<CR>
# inserts today's date

# Black hole: "_ prevents updating other registers.

レジスタ内のマクロ

マクロはレジスタに住んでいます — qa での記録はキーストロークをレジスタ a に書き込み、@a で再生します。レジスタなので、内容を確認し(:reg a)、貼り付け・編集・再ヤンクで修正したり、:let @a = '...' で vimrc に保存したりできます。特殊キーは文字列リテラル内で \<Esc> のようにエスケープします。

vim
# Macros are stored in registers, just like yanked text.
# Record a macro into register 'a':
qa        # start recording into 'a'
...       # perform actions
q         # stop recording

# Play back the macro:
@a        # play macro 'a' once
@@        # play last macro again (the one just played)
5@a       # play macro 'a' 5 times
:reg a    # view the recorded keystrokes

# Edit a macro:
:let @a = "..."     # set register 'a' directly
# Or: paste the register, edit, yank back:
"ap       # paste macro keystrokes
# ... edit the text ...
"ayy      # yank edited version back into 'a'

# Save a macro to vimrc:
:let @a = "0iHello \<Esc>"   # escaped special keys

# Apply macro to a range:
:%normal @a   # run macro 'a' on every line

追記とブラックホール

大文字のレジスタ名は追記します: "Ayy はレジスタ a に追記します(テキストを積み上げたり、複数段階のマクロを作ったりするのに非常に有用)。ブラックホールレジスタ "_ は書き込まれたものをすべて破棄します — 削除は番号付き/無名/ヤンクレジスタを更新しません。最後のヤンクを汚さずにテキストを削除したいときに使いましょう。

vim
# Append to a register (use UPPERCASE letter):
"ayy      # yank line into 'a'
"Ayy      # APPEND another line to 'a'
"Ayiw     # APPEND a word to 'a'

# After: register 'a' contains both.

# Black hole register "_:
"_d       # delete without affecting other registers
"_dd      # delete line, doesn't update "1, "0, "-
"_c       # change without saving deleted text
"_x       # delete char, nothing saved

# Why use black hole?
#   - Keep your yank register ("0) intact while deleting
#   - Avoid polluting numbered registers

# Example: yank a line, then delete another (without
# losing the yank):
"ayy      # yank into 'a'
"_dd      # delete line WITHOUT touching 'a' or '0
"ap       # paste the original yank

# When clipboard=unnamed, "_d still bypasses clipboard.

クリップボードと選択

"+ はシステムクリップボード(GUI アプリの Ctrl-C/Ctrl-V)、"* は X11 のプライマリ選択(中クリックのペースト)です。:set clipboard=unnamedplus を設定すると、ヤンクとペーストが直接システムクリップボードに行きます — "+ のプレフィックスが不要になります。Linux では xclip/xsel(X11)か wl-clipboard(Wayland)のインストールが必要なことがあります。

vim
# System clipboard register:
"+y       # yank to system clipboard
"+p       # paste from system clipboard
"+dd      # delete line to clipboard
"+P       # paste before cursor from clipboard

# X11 primary selection (Linux, middle-click):
"*y       # yank to primary selection
"*p       # paste from primary selection

# Make the system clipboard the default:
:set clipboard=unnamedplus   # use '+ for unnamed register
:set clipboard=unnamed       # use '* for unnamed register

# Then yank/paste go to clipboard automatically:
yy        # yanks to system clipboard (with above setting)
p         # pastes from system clipboard

# Check what's in the clipboard:
:reg +    # show clipboard contents

# On Linux, install a clipboard tool if missing:
#   xclip or xsel for X11
#   wl-clipboard for Wayland
10

マクロ

マクロの記録

q{letter} でレジスタへの記録を開始し、もう一度 q で停止します。記録されたキーストロークは @{letter} で再生できます。記録時には一貫して機能するモーションを使いましょう — 列位置に依存する j/k より 0、^、$、w、e を優先します。一括適用の前に、数行で試しましょう。

vim
q{a-z}    # start recording into register {a-z}
...       # perform actions (keystrokes recorded)
q         # stop recording

# Example: wrap each word in quotes on a line:
qa        # start recording into 'a'
0         # go to first column
i"        # insert opening quote
Esc
e         # go to end of word
a"        # append closing quote
Esc
w         # move to next word
q         # stop recording

# Now @a will wrap one more word.

# Recording tips:
#   - Use 0/^-positioned motions (not j/k)
#   - Use commands that work regardless of line length
#   - Test on a few lines before applying broadly

# View the recorded macro:
:reg a    # see keystrokes in register 'a'

マクロの再生

@a はマクロを 1 回再生し、@@ は最後のマクロを再生し、N@a は N 回再生します。多くの行にマクロを適用するには、ビジュアルで選択して :normal @a を実行するか、ファイル全体なら :%normal @a を使います。マクロはエラーで停止するので(検索の失敗など)、999@a はファイル末尾まで安全に処理します。:g/pattern/normal @a はマッチ行だけに実行します。

vim
@a        # play macro 'a' once (in current buffer)
@@        # replay the LAST macro played
5@a       # play macro 'a' 5 times
100@a     # play 'a' up to 100 times (stops on error)

# Play across multiple lines:
# 1. Visually select lines (V)
# 2. :normal @a    # play 'a' on each selected line

# Or:
:%normal @a        # play on every line in file
:5,20normal @a     # play on lines 5-20
:g/pattern/normal @a  # play on lines matching pattern

# Recursive macros:
#   If macro 'a' contains @a, it'll recurse.
#   Add a 'j' at the end to move to next line.

# Common pattern: process all matching lines:
#   qa0f:x...jq        # record macro moving down 1 line
#   :%s/pattern//gn    # count matches
#   100@a               # play up to 100 times

マクロの編集

マクロはレジスタに保存されているので編集できます。レジスタを貼り付け("ap)、テキストを修正し、ヤンクし戻します("ay$ か "ayy)。またはキーのエスケープ(\<Esc>、\<CR>)付きで :let @a = '...' を使います。小さなミスを直すのに、複雑なマクロを一から録り直すよりずっと簡単です。

vim
# Macros are just text in registers — you can edit them.

# Method 1: paste, edit, yank back:
"ap       # paste register 'a' into buffer
# ... edit the pasted text (modify keystrokes) ...
0"ay$    # yank the line back into 'a'

# Method 2: set the register directly with :let
:let @a = "0iHello \<Esc>"
# Note: special keys need \<Esc> notation in strings

# Method 3: edit in a scratch buffer:
:edit
"ap       # paste macro
# edit
"ayy      # yank back to 'a'
:bdelete

# Common edits:
#   - Add 'j' at the end to advance to next line
#   - Remove a step that you don't need
#   - Replace a hard-coded search with a generic one

# Show the macro as keystrokes:
:reg a    # view current 'a' contents

再帰マクロ

再帰マクロはエラーで止まるまで自分自身を呼びます — たいてい検索の失敗がきっかけです。重要: 記録の前にレジスタをクリアすること(let @a = '')。そうしないとマクロ内の最初の @a 呼び出しが古い内容を再生してしまいます。失敗した検索が再帰を止めるとき、マクロは自己終了します。グローバルな置換パターンに最適です。

vim
# A macro can call itself, enabling recursion.

# Example: change every 'foo' to 'bar' in a column:
#   (search-based macro)

# Steps to set up recursive macro 'a':
#   1. Clear register 'a':
:let @a = ''
#   2. Start recording:
qa
#   3. Search for 'foo':
/foo<CR>
#   4. Replace with 'bar' (ciwbar<Esc>):
ciwbar<Esc>
#   5. Call itself:
@a
#   6. Stop recording:
q

# Now @a runs until search fails (no more 'foo').
# The recursion stops automatically on the first error
# (when /foo finds nothing).

# Tip: clear the register first, otherwise the FIRST
# call also replays the old contents of 'a'.

# Run:
@a    # processes all 'foo' in file

回数付きのマクロ

N@a はマクロを N 回再生します — ただしエラーが起きたら早く止まるので、999@a はファイル末尾まで安全に処理します。:bufdo normal @a はすべてのバッファで、:argdo は arglist のすべてのファイルでマクロを実行します。:g/pattern/normal @a はマッチ行だけに実行します。マクロ内部のカウント(例: 5j)は再生ごとに繰り返され、マクロ単位ではありません。

vim
# Apply a count to a macro:
5@a       # play macro 'a' 5 times
N@a       # play up to N times (stops on error)

# Useful: large count to process until end-of-file
999@a     # play 'a' up to 999 times (errors stop it)

# Macros with counts INSIDE:
#   If your macro starts with '5j', each play jumps 5 lines

# Combine with visual selection (block):
#   Ctrl-v to select, then :normal @a
#   plays 'a' on each line in the block

# Process every Nth line:
:let i = 0
:g/^/if i % 3 == 0 | normal @a | endif
# (plays 'a' on every 3rd line)

# Apply with a delay (avoid blocking):
#   No built-in, but plugins can defer

# Repeat across buffers:
:bufdo normal @a   # play 'a' in every buffer
:argdo normal @a   # play 'a' in every arg file

複数ファイル・複数行のマクロ

:[range]normal @a は範囲内の各行でマクロを実行します — 多くの行にマクロを適用する最も一般的な方法です。各反復が次の行へ進むよう、マクロの最後を 'j' で終えましょう。:bufdo/:argdo はバッファ/ファイルを横断して実行します。変更した各ファイルを保存するには | update を追加し、エラーを越えて続けるには ! を使います(例: :bufdo!)。

vim
# Apply a macro to every line in a range:
:[range]normal @a
:%normal @a           # whole file
:5,20normal @a        # lines 5-20
:'<,'>normal @a       # visual selection
:g/pattern/normal @a  # only matching lines

# Apply across buffers:
:bufdo normal @a      # every buffer
:argdo normal @a      # every arglist file

# Save modified buffers after macro run:
:argdo normal @a | update   # save each that changed

# Best practice: include 'j' (move down) at end of macro
# so it advances to the next line for :normal usage.

# Example macro for processing CSV rows:
#   qa 0f,dt,j q    # cut field at comma, move down
#   :%normal @a     # apply to every line

# Abort on error vs. continue:
:bufdo! normal @a     # continue even if a buffer errors

# Debug: play macro step-by-step (no built-in, but
# :set lazyredraw off + slow key timing helps).
11

折りたたみ(フォールド)

フォールドの方式

foldmethod がフォールドの作り方を制御します。'manual' は zf で手動作成、'indent' はインデントで自動フォールド(コード向き)、'syntax' は構文ルールを使い(言語対応)、'marker' はファイル内の {{{ }}} を使い、'expr' はカスタムロジック用です。手動フォールドは、:mkview で保存しない限りファイルを閉じると失われます。

vim
:set foldmethod=manual    # fold by hand (zf)
:set foldmethod=indent    # fold by indent level
:set foldmethod=expr      # fold by 'foldexpr'
:set foldmethod=syntax    # fold by syntax rules
:set foldmethod=marker    # fold by {{{ }}} markers
:set foldmethod=diff      # fold unchanged text in diff

# Recommended defaults:
:set foldmethod=indent    # great for code
:set foldlevel=2          # show first 2 levels

# Per-method notes:
#   manual  - zf to create, zd to delete
#   indent  - automatic, based on shiftwidth
#   syntax  - automatic, requires syntax file support
#   marker  - persistent (saved in file as {{{ }}})
#   expr    - custom logic via 'foldexpr'

# Persistent manual folds across sessions:
:mkview    # save folds (and other view state)
:loadview  # restore them
# Or set:
:set viewoptions=folds   # what :mkview saves

手動フォールド

manual モードでは zf がフォールドを作ります(例: zf3j は次の 3 行を折りたたむ)。zd は 1 つのフォールドを削除し、zD は再帰的に削除し、zE はウィンドウ内の全フォールドを消去します。ビジュアルモード+ zf で選択範囲を折りたたみます。foldmethod=marker なら、コメント中に fold marker(開始と終了を示す中括弧 3 つ重ねの記号)を書くことで、ファイルに保存される永続的なフォールドを作れます — バージョン管理で折りたたみ構造を共有するのに便利です。

vim
# Manual fold commands (foldmethod=manual):
zf{motion}    # create fold over motion (e.g. zf3j)
zF            # create fold over current line(s)
zd            # delete fold at cursor
zD            # delete fold recursively (nested)
zE            # eliminate ALL folds in window
zj / zk       # move to next/prev fold start
[z / ]z       # move to fold start/end

# Select then fold (visual):
V  zf         # visually select lines, then fold

# Create fold for a range:
:5,20fold     # fold lines 5-20

# Fold using a marker (manual mode):
# Place markers in the file (with foldmethod=marker):
function Foo() " {{{
  echo "hi"
endfunction " }}}

# When foldmethod=marker, the {{{ }}} create persistent
# folds stored in the file text itself.

フォールドの開閉コマンド

zo/zc はフォールドを開閉し、za はトグルします。zO/zC/zA はネストしたフォールドに再帰的に作用します。zr/zm はフォールドレベルを全体的に調整し(1 レベルずつ)、zR はすべて開き、zM はすべて閉じます — リセットの素早い方法です。zj/zk はフォールド間を移動し、[z/]z は現在のフォールドの先頭/末尾へジャンプします。

vim
zo    # open fold (one level)
zc    # close fold (one level)
za    # toggle fold (open <-> closed)
zO    # open fold recursively (all levels)
zC    # close fold recursively (all levels)
zA    # toggle fold recursively
zr    # reduce fold level by 1 (open one level everywhere)
zm    # increase fold level by 1 (close one level everywhere)
zR    # open ALL folds (reduce to level 0)
zM    # close ALL folds (fold everything)

# Navigation in/around folds:
zj    # next fold start (down)
zk    # previous fold end (up)
[z    # start of current open fold
]z    # end of current open fold

# Move with folds intact (don't open):
#   Use j/k normally — they may skip closed folds
#   Set 'foldopen' to control what opens folds

フォールドの移動と編集

j/k は 'foldopen' の設定によっては閉じたフォールドを飛び越えます。zj/zk はフォールドの境界間を移動します。折りたたまれた行での yy/dd は、折りたたまれたすべての行を 1 単位として(行単位で)働きます。閉じたフォールド内で入力すると開きます。どのモーションがフォールドを開くかは 'foldopen' で設定しましょう(例: 'search' を外すと検索中も閉じたまま)。

vim
# Fold-related motions:
zj    # next fold start (move down)
zk    # previous fold end (move up)
[z    # start of current open fold
]z    # end of current open fold

# What opens a fold when triggered?
:set foldopen=block,hor,mark,percent,quickfix,
             search,tag,undo
# Defaults open folds on most motions.
# To make j/k NOT open folds:
:set foldopen-=block

# Editing a closed fold:
#   Typing inside a closed fold opens it.
#   'o' or 'O' on a fold line opens a new line.

# Search inside closed folds:
#   Default behavior depends on 'foldopen'.
#   :set foldopen-=search  # don't open on search

# Yank/paste on folded lines:
#   yy yanks ALL lines in the fold (linewise)
#   dd deletes ALL lines in the fold

# Paste over a fold:
#   p with a linewise register replaces the folded region

フォールドのオプション

foldlevel はどの深さまで開いたままかを制御します(高いほど開く)。foldlevelstart=99 で最初から全部開きます。foldcolumn はフォールド状態のサイドバーを表示します。foldminlines は小さすぎるフォールドを防ぎます。セッションをまたいでフォールドを残すには、BufWinLeave で :mkview、BufWinEnter で :loadview — 定番の autocmd パターンです。

vim
:set foldmethod=indent     # folding method
:set foldlevel=2           # show folds deeper than this
:set foldlevelstart=99     # start with all folds open
:set foldminlines=3        # min lines to form a fold
:set foldcolumn=4          # 4-char column showing fold state
:set foldenable            # enable folding (default on)
:set foldclose=all         # auto-close folds when cursor leaves
:set foldopen=block,hor,mark,percent,quickfix,search,tag,undo
:set foldtext=foldtext()   # text to show on a closed fold
:set fillchars=fold:\ ,   # chars for fold display

# Common combo for code:
:set foldmethod=indent
:set foldlevelstart=10
:set foldnestmax=10        # max nesting depth

# Custom fold text:
:set foldtext=MyFoldText()
function MyFoldText()
  return '+++ ' . (v:foldend - v:foldstart + 1) . ' lines +++'
endfunction

# Persistent folds across sessions:
:set viewoptions=folds,cursor
:autocmd BufWinLeave * mkview
:autocmd BufWinEnter * silent loadview

ネストしたフォールドとレベル

フォールドは階層的にネストします。'foldlevel' が開いたままの最深レベルを決めます — foldlevel=0 ですべて閉じ、99 ですべて開きます。zr/zm は 1 ずつ調整し、zR/zM が極端な値です。'foldnestmax' はネストの深さに上限を設け、深くネストしたコードでフォールドが暴走するのを防ぎます。カスタムの foldtext 関数で、閉じたフォールドの表示内容を制御できます。

vim
# Folds can nest. 'foldlevel' controls which are open:
:set foldlevel=0   # all folds closed
:set foldlevel=1   # only top-level open
:set foldlevel=99  # all open

# Display current fold level:
:echo &foldlevel

# Increase/decrease by 1:
zr    # reduce (open one level everywhere)
zm    # more (close one level everywhere)
zR    # open ALL folds (set foldlevel to 99)
zM    # close ALL folds (set foldlevel to 0)

# Limit nesting:
:set foldnestmax=10

# Each indent level adds a fold level.
# Useful for deeply-nested code:
#   function outer() {
#     function inner() {       <- foldlevel 2
#       function deep() {      <- foldlevel 3
#       }
#     }
#   }

# Custom foldtext for nested folds:
:set foldtext=NeatFoldText()
function! NeatFoldText()
  let line = getline(v:foldstart)
  let n = v:foldend - v:foldstart + 1
  return line . ' (' . n . ' lines)'
endfunction
12

分割ウィンドウ

ウィンドウの分割

:split/:vsplit は現在のウィンドウを分割します — どちらもデフォルトで同じバッファを表示し(変更は同期します)。:split file は新しい split でファイルを開きます。:new/:vnew は空のバッファを作ります。Ctrl-w s/v がキーボードショートカットです。数値のプレフィックスで新しいウィンドウのサイズを設定できます(:10split は 10 行のウィンドウ)。

vim
:split / :sp        # horizontal split (current file)
:vsplit / :vs       # vertical split (current file)
:split file.txt     # split + open file
:vsplit file.txt    # vsplit + open file
:new                # horizontal split with empty buffer
:vnew               # vertical split with empty buffer
:5split / :5vsplit  # split with 5 rows/cols

# Quick splits (Normal mode):
Ctrl-w s    # split horizontally (same as :split)
Ctrl-w v    # split vertically (same as :vsplit)
Ctrl-w n    # new horizontal split (empty)
Ctrl-w q    # close window (same as :q)

# Split with size hints:
:10split file.txt    # split with height 10
:vert 30split file   # vertical split with width 30

# Reopen current file in a new split:
Ctrl-w s    # same buffer, two views (sync scroll optional)

ウィンドウ間の移動

Ctrl-w の後に h/j/k/l でウィンドウ間を移動します(hjkl と同じ記憶法)。Ctrl-w w は次のウィンドウへ巡回します。速度のため、多くのユーザーは Ctrl-h/j/k/l をウィンドウ移動に直接マップします。Ctrl-w p は直前に使ったウィンドウへ戻ります — 2 つのウィンドウを行き来するときに便利です。

vim
Ctrl-w h    # left window
Ctrl-w j    # below window
Ctrl-w k    # above window
Ctrl-w l    # right window
Ctrl-w w    # cycle to next window (wraps)
Ctrl-w W    # cycle to previous window
Ctrl-w t    # top-left window
Ctrl-w b    # bottom-right window
Ctrl-w p    # previous (last accessed) window

# Faster (with mapping):
:nmap <C-h> <C-w>h
:nmap <C-j> <C-w>j
:nmap <C-k> <C-w>k
:nmap <C-l> <C-w>l

# In terminal mode:
Ctrl-w N    # exit terminal mode (to Normal)
Ctrl-w h/j/k/l  # navigate (after exiting terminal mode)

# List windows in current tab:
:ls        # also shows windows' buffers

ウィンドウのサイズ変更

Ctrl-w +-/</> はサイズを 1 ずつ変え、カウントを前置すると大きく動きます(10 Ctrl-w +)。Ctrl-w _ は高さを最大化し、Ctrl-w | は幅を最大化し、Ctrl-w = は全ウィンドウを均等化します。正確には :resize N(高さ)と :vertical resize N(幅)を使いましょう。'mouse=a' ならステータス行や区切りを直接ドラッグできます。

vim
Ctrl-w =    # equalize all window sizes
Ctrl-w +    # increase height by 1
Ctrl-w -    # decrease height by 1
Ctrl-w >    # increase width by 1
Ctrl-w <    # decrease width by 1
Ctrl-w _    # maximize height (current window)
Ctrl-w |    # maximize width (current window)
10 Ctrl-w + # increase height by 10

# Ex commands for precise resize:
:resize 20        # set height to 20 (horizontal split)
:resize +5        # increase height by 5
:resize -5        # decrease height by 5
:vertical resize 80   # set width to 80 (vertical split)
:vertical resize +10  # increase width by 10

# Mouse: drag the status line / vertical separator
# (with :set mouse=a)

# Auto-resize on split:
:set equalalways    # default: auto-equalize on split/close
:set noequalalways  # don't auto-resize

ウィンドウの移動(レイアウト)

Ctrl-w H/J/K/L は現在のウィンドウを画面の端へ移動します(大文字=その側で全画面)。Ctrl-w r/R はレイアウト内でウィンドウを回転させ、Ctrl-w x は次のウィンドウと入れ替え、Ctrl-w T はウィンドウを新しいタブへ移します。小技: Ctrl-w K/H は水平と垂直の向きを変換することもできます。

vim
Ctrl-w H    # move current window to far LEFT (full height)
Ctrl-w J    # move current window to BOTTOM (full width)
Ctrl-w K    # move current window to TOP (full width)
Ctrl-w L    # move current window to far RIGHT (full height)
Ctrl-w r    # rotate windows DOWN/RIGHT
Ctrl-w R    # rotate windows UP/LEFT
Ctrl-w x    # exchange current window with next
Ctrl-w T    # move current window to a NEW tab page

# Move split orientation:
Ctrl-w K    # if vertical, become horizontal (and move to top)
Ctrl-w H    # if horizontal, become vertical (and move to left)

# Example: convert a vertical split to horizontal:
:vsplit        # creates vertical split
Ctrl-w H       # moves it to the left, becoming horizontal

# Reopen current buffer in a new tab:
Ctrl-w T       # current window moves to a new tab

ウィンドウの配置

Ctrl-w = はウィンドウサイズを均等化します。:ball はバッファごとに 1 ウィンドウを開きます — すべてを一度に見るのに便利です。Ctrl-w r/R はレイアウト内でウィンドウを回転させます。完全なウィンドウレイアウト(バッファ、フォールドなどを含む)の保存と復元には、:mksession と :source を使いましょう。タブページごとに独立したウィンドウレイアウトを保持します。

vim
# Equalize window sizes:
Ctrl-w =      # equalize height and width

# Stack layouts:
# Vertical splits side by side, horizontal splits stacked
# Example setup:
#   :vsplit        -> | win1 | win2 |
#   :split         -> | win1 | win3 |
#                       |     | win2 |

# Cycle through layouts (with plugins like golden-ratio,
# or use built-in rotation):
Ctrl-w r      # rotate down/right
Ctrl-w R      # rotate up/left

# Distribute buffers across windows:
:ball         # one window per buffer (horizontal)
:vertical ball  # one window per buffer (vertical)

# Layouts persist within a tab page.
# Save current layout to a session:
:mksession mylayout.vim
# Restore:
:source mylayout.vim

# Tab page = a collection of windows
:tabnew       # new tab with one window

ウィンドウを閉じる

:q はウィンドウを閉じます(最後のウィンドウなら Vim を終了)。:close(Ctrl-w c)はウィンドウを閉じますが、最後の 1 つは閉じません。:only(Ctrl-w o)は他のすべてのウィンドウを閉じます。'hidden' を設定していれば、変更済みバッファを持つウィンドウを閉じるとき、保存の決定を迫る代わりに隠されます。:only! は変更があっても他を強制的に閉じます。

vim
:q / :quit       # close current window (errors if last)
:q!              # close without saving
:wq              # save and close
:close / Ctrl-w c   # close window (won't close last)
:only / Ctrl-w o    # close all OTHER windows
:hide            # hide current buffer in window (close window)

# Save and close splits:
:xa              # save all and exit (close all windows)
:wqa             # same as :xa

# Closing a window with modified buffer:
#   - :q  prompts: "Save changes?"
#   - :q! discards
#   - :wq saves and closes
#   - :hide (with 'hidden' set) keeps buffer in memory

# Close every window except the current:
:only            # or Ctrl-w o
# Errors if other windows have unsaved changes:
:only!           # force-close other windows

# When you close the last window, Vim exits.
# To prevent accidental exit:
:q! on last window still exits Vim.
13

タブ

タブの作成

:tabnew/:tabedit は新しいタブページを作ります。vim -p file1 file2 は起動時に各ファイルを専用のタブで開きます。各タブページは 1 つ以上のウィンドウを含みます — タブはレイアウトであって単一のファイルではありません。Ctrl-w T は現在のウィンドウを新しいタブへ移します。タブは無関係な作業コンテキストの分離に最適です(プロジェクト領域ごとに 1 タブなど)。

vim
:tabnew             # new tab with empty buffer
:tabedit file.txt   # new tab opening file
:tab split          # new tab with current buffer in a split
:tabfind file.txt   # new tab, find file in 'path'

# Open multiple files in tabs at startup:
vim -p file1.txt file2.txt file3.txt

# From inside Vim, open files in tabs:
:args *.py | argdo tabe %

# Or one-by-one:
:tabe file1.txt
:tabe file2.txt

# Keyboard shortcut (common mapping):
:nmap <C-t> :tabnew<CR>

# Open current buffer in a new tab (move window):
#   Ctrl-w T    (move current window to a new tab page)

# Each tab page has its own window layout
# (multiple splits/windows per tab allowed)

タブ間の移動

gt/gT でタブを切り替えます(ノーマルモード)。Ngt でタブ N(1 起点)へ直接ジャンプします。:tabs はすべてのタブページとウィンドウを一覧表示します。素早い切り替えのために Ctrl-Tab/Ctrl-S-Tab や <leader>1/2/3 をマップするのが定番です。タブはデフォルトで巡回します。各タブは独自のウィンドウレイアウト(split など)を保持します。

vim
:tabnext / :tabn   # next tab
:tabprevious / :tabp  # previous tab
:tabfirst / :tabr     # first tab
:tablast / :tabl      # last tab
gt                   # next tab (Normal mode)
gT                   # previous tab
3gt                  # go to tab 3
:tabn 3              # go to tab 3 (Ex command)

# Common mappings (Vim default):
:nmap <C-Tab> :tabnext<CR>
:nmap <C-S-Tab> :tabprevious<CR>

# Or use leader keys:
:nmap <leader>1 1gt
:nmap <leader>2 2gt
:nmap <leader>3 3gt

# Cycle behavior:
#   gt at last tab wraps to first
#   gT at first tab wraps to last
# To disable wrap:
:set tabpagemax=50  # max tabs (not wrap-related)

# Show all tabs:
:tabs   # list tabs with their windows

タブの操作

:tabc は現在のタブを閉じ、:tabo は他のすべてを閉じます。:tabm N は現在のタブを位置 N へ移動します(0 = 先頭)。:tabdo はすべてのタブで Ex コマンドを実行します — タブで分けたワークスペースをまたぐグローバル操作に有用です。タブを閉じるとそのウィンドウはすべて閉じますが、'hidden' を設定していれば変更済みバッファは保持されます。

vim
:tabclose / :tabc   # close current tab
:tabclose! / :tabc!  # force close (discard changes)
:tabonly / :tabo     # close all OTHER tabs
:tabonly! / :tabo!   # force close others

# Reorder tabs:
:tabmove / :tabm 0   # move current tab to position 0 (first)
:tabm              # move to last position
:tabm 2            # move to position 2
:tabm +1           # move right by 1
:tabm -1           # move left by 1

# Quick keyboard reordering (no default, common mapping):
:nmap <leader>tm :tabmove<Space>

# Run a command in every tab:
:tabdo cmd         # run cmd in every tab page
# Example:
:tabdo %s/old/new/ge   # substitute in every tab's first window

# Each tab can hold multiple windows/splits.
# 'Tabclose' closes all windows in the tab.

タブのレイアウトとマルチウィンドウ

各タブページは独立したウィンドウレイアウト(split、サイズ、位置)を保持します。タブごとに複数のウィンドウを持てます。Ctrl-w T はウィンドウを専用の新しいタブへ移します。:set showtabline=2 でタブバーを常に表示します。タブはワークスペースの区切りとして使うのが最善です(プロジェクト領域ごとに 1 タブなど)、それぞれが独自のレイアウトを持ちます。

vim
# Each tab page has its own window layout.

# Create a tab with a 3-window layout:
:tabnew            # new tab
:vsplit            # split vertically (2 windows)
:split             # split horizontally (3 windows)
# Now tab has: [win1] [win2]
#                      [win3]

# Add a buffer to current tab:
:e file.txt        # replaces current window's buffer

# Move a window to its own tab:
Ctrl-w T           # window becomes a new tab page

# Show tab line (always):
:set showtabline=2  # 0=never, 1=multi-tab, 2=always

# Tab page-local options:
:setlocal ...       # option applies only to current tab's windows
:tabdo setlocal ... # apply across all tabs

# Tab label customization (status line):
:set guitablabel=%t  # show filename in GUI tab label

# Common use case: one tab per project area:
#   Tab 1: source files
#   Tab 2: tests
#   Tab 3: docs
# Each with its own split layout.

タブのオプションとラベル

showtabline はタブバーを制御します(0 = 表示しない、1 = 複数タブのときだけ、2 = 常に)。書式文字列を返す関数でタブラインを完全にカスタマイズできます — 変更状態、バッファ名、タブ番号の表示に便利です。guitablabel/guitabtooltip は GUI 版 Vim をカスタマイズします。タブは 1 から番号が付きます。

vim
:set showtabline=2    # always show tab bar (0=never, 1=auto)
:set tabpagemax=50    # max tabs creatable
:set hidden           # allow switching tabs with unsaved changes

# Custom tab labels (terminal Vim):
:set tabline=%!MyTabLine()
function! MyTabLine()
  let s = ''
  for i in range(tabpagenr('$'))
    let n = i + 1
    let s .= '%' . n . 'T'
    let s .= (n == tabpagenr() ? '%#TabLineSel#' : '%#TabLine#')
    let s .= ' [' . n . '] '
    let buflist = tabpagebuflist(n)
    let bufname = bufname(buflist[0])
    let s .= empty(bufname) ? '[No Name]' : fnamemodify(bufname, ':t')
    let s .= ' '
  endfor
  let s .= '%T%#TabLineFill#'
  return s
endfunction

# GUI tab labels:
:set guitablabel=%t   # show filename
:set guitabtooltip=%f # show full path on hover

# Quickly switch with number:
:nmap <leader>t :tabs<CR>

タブページのコマンド

:tabs はタブとウィンドウを一覧表示します。:tabdo はすべてのタブで Ex コマンドを実行し、:tab ball は各バッファを専用のタブで開きます。<C-w>gf はカーソル下のファイルを新しいタブで開きます。関連ファイルのグループ化にタブを使いましょう(機能/領域ごとに 1 タブ)。タブをまたぐ操作には :tabdo が主力です — 複数ウィンドウのタブには windo と組み合わせます。

vim
:tabs                # list all tabs and their windows
:tabdo cmd           # run cmd in every tab
:tab ball            # open each buffer in its own tab
:tab help subject    # open help in a new tab
:tab split           # split current window into new tab

# Quickly duplicate a tab's layout:
# (no built-in, but possible with sessions)
# Or manually: create a new tab, re-open buffers

# Open file under cursor in a new tab:
:nmap gf :tabe <cfile><CR>
# (or use the built-in <C-w>gf)

# Common workflow:
# 1. Group related files in tabs
# 2. Use gt/gT to switch
# 3. Use :tabdo for cross-tab operations

# Save all tabs' buffers:
:tabdo windo w   # write every window in every tab
# (or simpler)
:wall            # write all buffers (across all tabs)

# Close all tabs but keep buffers:
# (no single command — use :tabo + :b then :bd)
14

設定(.vimrc)

vimrc の基本

$MYVIMRC は vimrc ファイルのパスです — :edit $MYVIMRC で開き、:source $MYVIMRC で編集後に再読み込みします。runtimepath は Vim が構文ファイルやプラグインを探す場所を制御します。:verbose set option? はそのオプションがどこで最後に設定されたかを示します — 競合するプラグインのデバッグに非常に役立ちます。

vim
# vimrc location:
#   Unix:    ~/.vimrc       (or ~/.vim/vimrc)
#   Windows: ~/_vimrc       (or ~/vimfiles/vimrc)
#   Neovim:  ~/.config/nvim/init.vim

# Reload vimrc after editing:
:source $MYVIMRC    # or :so %
# Edit vimrc quickly:
:edit $MYVIMRC      # $MYVIMRC = path to your vimrc

# Runtime path (where Vim looks for scripts):
:set runtimepath?
# Add a custom path:
:set runtimepath+=~/.vim/custom

# Conditional config (only in terminal Vim):
if !has('gui_running')
  set mouse=a
endif

# Per-filetype settings (in vimrc or ftplugin/):
:autocmd FileType python setlocal expandtab shiftwidth=4

# Check where an option was set:
:verbose set tabstop?

基本的な設定

これらはよく使う利便性の設定です。relativenumber + number はハイブリッド番号を表示します — 簡単にジャンプできるようカーソルからの相対番号で、現在行は絶対番号です。showmatch は対応する括弧をフラッシュします。wildmenu は :コマンドの補完にメニューを追加します。scrolloff はカーソルの周囲の文脈を表示し続けます — 画面の端で編集しないように。

vim
set nocompatible      # Vim mode (not Vi)
set number            # show line numbers
set relativenumber    # relative line numbers (great for jumps)
set cursorline        # highlight current line
set cursorcolumn      # highlight current column
set showcmd           # show partial commands in status
set showmode          # show current mode (insert, visual...)
set showmatch         # highlight matching brackets
set wildmenu          # better command-line completion
set wildmode=longest:full,full  # completion style
set laststatus=2      # always show status line
set ruler             # show cursor position
set backspace=indent,eol,start  # backspace through everything
set encoding=utf-8    # default encoding
set scrolloff=5       # keep 5 lines above/below cursor
set sidescrolloff=5   # keep 5 cols left/right of cursor
set mouse=a           # enable mouse (all modes)

インデント

tabstop はタブ文字の表示幅です。shiftwidth は <<、>>、autoindent が使うインデント量です。softtabstop は expandtab がオフでも Backspace が正しい桁数を消すようにします。expandtab はタブをスペースに変換します — 一貫性のため推奨です。設定変更後の既存のタブ/スペースの変換には :retab を使いましょう。

vim
set autoindent       # copy indent from previous line
set smartindent      # smart auto-indent for code (basic)
set cindent          # C-style indenting (more language-aware)
set expandtab        # use spaces instead of tabs
set tabstop=4        # tab key inserts 4-column tabs visually
set shiftwidth=4     # indent/outdent amount (<<, >>, autoindent)
set softtabstop=4    # backspace removes 4 cols even with tabs
set shiftround       # round indent to multiple of shiftwidth
set smarttab         # tab key respects shiftwidth at line start

# Toggle tabs vs spaces:
:set expandtab!     # toggle
:retab              # convert existing tabs<->spaces

# Filetype-specific indent:
:filetype plugin indent on
# Then in ~/.vim/ftplugin/python.vim:
#   setlocal expandtab shiftwidth=4

# Quick indent/dedent in Normal mode:
>>     # indent current line
<<     # dedent current line
5>>    # indent 5 lines

検索の設定

ignorecase + smartcase が推奨の組み合わせです: パターンに大文字が含まれない限り大小を無視します。hlsearch はすべてのマッチをハイライトし、incsearch はタイプ中にインクリメンタルに表示します。定番のマッピング: <leader>h で hlsearch をトグル、または :noh で現在のハイライトを消す。Vim 8.2+ は shortmess で検索件数を表示できます。

vim
set ignorecase       # case-insensitive search
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 search around end of file (ws)

# Toggle search highlight:
:nmap <leader>h :set hlsearch!<CR>
# Or clear current highlight:
:nmap <leader>nh :nohlsearch<CR>

# Show search count (Vim 8.2+):
:set shortmess-=S
:set shortmess+=S    # search stats in command line

# Search in visual selection:
:vmap * y/\V<C-R>"<CR>

# Use very-magic mode by default (advanced):
# No built-in, but a search mapping can prepend \v

# Improved '*' (don't jump on first press):
:nmap * *N

# Disable highlighting until next search:
:nohlsearch

表示の設定

wrap + linebreak は長い行を(単語の途中ではなく)単語の境界で折り返し、読みやすくします。list + listchars はタブ、行末の空白、nbsp を可視化します。colorcolumn は列に目印を付けます(例: 行長制限の 80)。termguicolors はモダンなターミナルで 24 ビットカラーを有効にします。splitright/splitbelow は新しい split の出現位置を制御します。

vim
set wrap             # wrap long lines
set linebreak        # wrap at word boundaries (not mid-word)
set textwidth=80     # auto-wrap at 80 chars when typing
set showbreak=+++    # marker for wrapped lines
set list             # show invisible chars
set listchars=tab:>-,trail:.,extends:>,precedes:<
set fillchars=fold:-,vert:\|   # chars for folds/vsplits
set colorcolumn=80   # highlight column 80
set signcolumn=yes   # always show sign column (LSP)
set conceallevel=0   # don't conceal chars
set splitright       # new vsplit on the right
set splitbelow       # new split below
set termguicolors    # 24-bit color (if terminal supports)
set background=dark  # or 'light' — adjusts color scheme

# Color scheme:
:colorscheme desert
# Or with a plugin (e.g. vim-colors-solarized):
:colorscheme solarized

キーマッピング

個人のマッピングには常に *noremap 系(nnoremap、vnoremap など)を使いましょう — 再帰しないので予想外の挙動を避けられます。<leader> はカスタマイズ可能なプレフィックスキーです(デフォルトはバックスラッシュ。カンマやスペースにする人も多い)。<CR> は Enter、<Esc> は escape、<C-x> は Ctrl-X です。保存/終了のようなよく使うコマンドには leader ショートカットをマップしましょう。

vim
# Map families:
:map      # normal, visual, select, operator-pending
:nmap     # normal mode only
:imap     # insert mode only
:vmap     # visual + select mode
:xmap     # visual mode only
:smap     # select mode only
:omap     # operator-pending mode only
:cmap     # command-line mode only
:tmap     # terminal mode only

# Non-recursive (RECOMMENDED):
:nnoremap    # normal mode, non-recursive
:vnoremap    # visual mode, non-recursive
:inoremap    # insert mode, non-recursive
:cnoremap    # command-line mode, non-recursive

# Examples:
nnoremap <leader>w :w<CR>         # save with leader-w
nnoremap <leader>q :q<CR>         # quit
inoremap jk <Esc>                 # Esc with jk
nnoremap <C-h> <C-w>h              # window nav

# Leader key (default is \):
:let mapleader = ','
:let maplocalleader = '\\'

# Special keys:
# <CR> <Esc> <Tab> <Space> <C-x> <A-x> <M-x> <F1>-<F12>
# <Up> <Down> <Left> <Right> <leader> <localleader>
15

プラグイン(vim-plug)

vim-plug の基本

vim-plug は最も人気のあるモダンなプラグインマネージャです。call plug#begin と plug#end の間にプラグインを宣言します。各 Plug 行は GitHub リポジトリ(user/repo)を指定します。プラグインを追加したら、:source $MYVIMRC の後に :PlugInstall でダウンロードします。安定性のためタグ、ブランチ、コミットに固定できます。プラグインは 'plugged' ディレクトリにインストールされます。

vim
# Installation (Unix):
# curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
#     https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

# In vimrc:
call plug#begin('~/.vim/plugged')
  Plug 'junegunn/fzf.vim'           " GitHub repo: user/repo
  Plug 'tpope/vim-surround'         " another plugin
  Plug 'morhetz/gruvbox'            " colorscheme
  Plug 'preservim/nerdtree'         " file explorer
call plug#end()

# After editing vimrc:
:source $MYVIMRC    # or restart Vim
:PlugInstall        # install all declared plugins

# Plugin directory structure:
#   ~/.vim/plugged/<plugin-name>/

# Pin to a specific commit/tag/branch:
Plug 'tpope/vim-fugitive', { 'tag': 'v3.0' }
Plug 'user/repo', { 'branch': 'dev' }
Plug 'user/repo', { 'commit': 'abc123' }

プラグイン管理コマンド

:PlugInstall は新しいプラグインをインストールし、:PlugUpdate はすべてを更新し、:PlugClean はリスト外のものを削除し、:PlugStatus は状態を表示します。'do' フックはインストール後にコマンドを実行します — ビルドやバイナリのインストールが必要なプラグインに便利です。'on'/'for' オプションは遅延読み込みを可能にします(コマンドや filetype がトリガーしたときだけ読み込む)— 起動時間が改善します。

vim
:PlugInstall        # install newly added plugins
:PlugUpdate         # update all plugins
:PlugClean          # remove plugins no longer in vimrc
:PlugStatus         # show plugin status (loaded, errored)
:PlugUpgrade        # update vim-plug itself
:PlugDiff           # review changes from last update
:PlugSnapshot       # generate a snapshot of plugin versions

# Post-install hooks:
Plug 'user/repo', { 'do': ':GoInstallBinaries' }
Plug 'user/repo', { 'do': './install.sh' }
Plug 'user/repo', { 'do': 'npm install' }

# Lazy loading (load only when needed):
Plug 'user/repo', { 'on': 'CommandName' }    " on command
Plug 'user/repo', { 'for': 'python' }        " for filetype
Plug 'user/repo', { 'on': ['Cmd1', 'Cmd2'] }

# Frozen plugin (don't update):
Plug 'user/repo', { 'frozen': 1 }

# Disable a plugin temporarily:
# (no built-in, but comment out the Plug line and :PlugClean)

定番の必須プラグイン

定番の必須プラグイン: fzf はファイル/バッファ/テキストのファジー検索(:find よりはるかに速い)、vim-surround はテキストを囲む引用符/括弧/タグの編集、vim-fugitive は Git 統合、vim-commentary は高速なコメント化(gc オペレータ)、NERDTree はファイルエクスプローラのサイドバー、vim-airline は見栄えのよいステータスライン、そして gruvbox のような良い colorscheme。

vim
" Fuzzy finder (requires fzf binary):
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
"   :Files     :GFiles     :Buffers    :Rg

" Surround (cs/ds/ys for surroundings):
Plug 'tpope/vim-surround'
"   cs"'    change " to '
"   ds"     delete surrounding "
"   ysiw)   surround word with ()

" Fugitive (Git integration):
Plug 'tpope/vim-fugitive'
"   :G       :Gstatus   :Gcommit   :Gpush

" Commentary (gc to toggle comments):
Plug 'tpope/vim-commentary'
"   gcc      comment line
"   gc{motion}  comment motion

" NERDTree (file explorer sidebar):
Plug 'preservim/nerdtree'
"   :NERDTree  :NERDTreeToggle

" Airline (status line):
Plug 'vim-airline/vim-airline'

" Gruvbox (colorscheme):
Plug 'morhetz/gruvbox'

プラグインの設定

'on'/'for' でプラグインを遅延読み込みしましょう — トリガーされたときだけ読み込まれ、起動時間が改善します。プラグイン固有の設定は通常、vimrc で g:pluginname_var 変数を設定するか、~/.vim/after/plugin/ のファイルを使います。'do' フックはビルド手順のためにインストール/更新の後に実行されます。vimrc で g:loaded_pluginname=1 を設定すると、そのプラグインの読み込み自体を防げます。

vim
" Lazy load on command:
Plug 'tpope/vim-fugitive', { 'on': 'Git' }

" Lazy load on filetype:
Plug 'fatih/vim-go', { 'for': 'go' }

" Multiple triggers:
Plug 'junegunn/fzf.vim', { 'on': ['Files', 'Buffers', 'Rg'] }

" Post-install hook:
Plug 'dense-analysis/ale', { 'do': 'npm install' }

" Configuration AFTER plugin loads:
Plug 'preservim/nerdtree'
let g:NERDTreeShowHidden = 1
let g:NERDTreeWinSize = 30
nmap <leader>n :NERDTreeToggle<CR>

" Configuration in AFTER/plugin-name.vim:
" (alternative to setting g: vars in vimrc)
" ~/.vim/after/plugin/nerdtree.vim:
"   let g:NERDTreeShowHidden = 1

" Disable plugin entirely:
let g:loaded_nerdtree = 1   " prevent loading

プラグインの読み込みと runtime

Vim は起動時に plugin/*.vim をディレクトリ順で読み込み、最後に after/plugin/*.vim を読みます(上書き用)。:scriptnames は読み込まれたすべてを列挙します — デバッグに非常に役立ちます。:verbose map <key> はマッピングがどこで定義されたかを示し、:verbose set option? はオプションについて同様です。autoload/ のファイルは関数が最初に呼ばれたときに遅延読み込みされます。

vim
" Plugin loading sequence:
" 1. Vim starts, reads vimrc
" 2. plug#begin / plug#end registers plugins
" 3. Runtime path is updated to include plugin dirs
" 4. plugin/*.vim files are sourced (in directory order)
" 5. after/plugin/*.vim files are sourced last

" Check if a plugin is loaded:
:echo exists('g:loaded_fugitive')
:scriptnames        # list all sourced scripts in order

" Manually source a plugin:
:source ~/.vim/plugged/foo/plugin/foo.vim

" Find where a mapping was defined:
:verbose map <leader>w

" Find where an option was set:
:verbose set formatprg?

" Plugin runtime files:
"   plugin/      - loaded at startup
"   ftplugin/    - loaded for specific filetypes
"   syntax/      - syntax highlighting
"   indent/      - indentation rules
"   autoload/    - lazily-loaded functions
"   after/       - sourced last (overrides)

" Helptags for plugin docs:
:Helptags   (vim-plug generates these on install)

他のプラグインマネージャ

vim-plug 以外の選択肢: Vundle(似た API、機能は少なめ)、Pathogen(最もシンプル — bundle ディレクトリを runtimepath に追加するだけ)、Dein.vim(高速、遅延読み込み重視)、Vim 8+ の組み込み packages(プラグインマネージャ不要 — pack/<name>/start/ に置くだけ)。Neovim ユーザーには(Lua ベースの)Packer が人気です。組み込み packages はミニマリストに最適です。

vim
" 1. Vundle (older, similar to vim-plug):
" set rtp+=~/.vim/bundle/Vundle.vim
" call vundle#begin()
"   Plugin 'tpope/vim-surround'
" call vundle#end()

" 2. Pathogen (just adds dirs to runtimepath):
" Execute: 
"   git clone https://github.com/tpope/vim-pathogen ~/.vim/bundle
" In vimrc:
"   execute pathogen#infect()
" Then clone plugins into ~/.vim/bundle/

" 3. Dein.vim (modern, lazy-loading focused):
" set runtimepath+=~/.cache/dein/repos/github.com/Shougo/dein.vim
" if dein#load_state('~/.cache/dein')
"   call dein#begin('~/.cache/dein')
"     call dein#add('tpope/vim-surround')
"   call dein#end()
"   call dein#save_state()
" endif

" 4. Vim 8+ built-in packages (NO plugin manager needed):
" Place plugins in:
"   ~/.vim/pack/<name>/start/<plugin>/    " loaded at startup
"   ~/.vim/pack/<name>/opt/<plugin>/      " loaded on demand
" Load an opt plugin: :packadd <plugin>

" 5. Packer (Neovim Lua):
"   require('packer').startup(function()
"     use 'tpope/vim-surround'
"   end)
16

検索とナビゲーション

組み込みの検索

組み込みの検索は / と ? で、Vim の正規表現を使います(very-magic には \v)。検索オフセット(/foo/e はマッチの末尾にカーソルを置く)は n/N をまたいで保持されます — 各マッチの後にカーソルを適切な位置へ置くのに便利です。\%V は検索を現在のビジュアル選択内に限定します。/ の後に上キーで検索履歴を呼び出し、:history / で一覧表示します。

vim
/pattern      # search forward
?pattern      # search backward
n / N         # next / previous match
* / #         # search word under cursor (forward / backward)
g* / g#       # search word under cursor (substring match)

# Search with offsets:
/foo/e        # cursor on last char of match
/foo/e+1      # cursor 1 char past match
/foo/b-1      # cursor 1 char before match
/foo/s+2      # cursor 2 chars after start of match

# Search in current visual selection:
# 1. Visually select (v/V/Ctrl-v)
# 2. Press /  ->  search forward
# 3. Pattern auto-confines to selection? NO.
#    Workaround: /\%Vpattern  (\%V = inside visual selection)

# Repeat last search:
/ then Up arrow    # recall from history
:history /         # list search history

# Search offset persists with n/N.

grep と quickfix

:grep は外部の grep を実行し('grepprg' で設定可能)、結果を quickfix リストに入れます。:copen でリストを表示し、:cn/:cp で移動します。grepprg=rg --vimgrep を設定すると ripgrep を使います — grep よりはるかに速く、良いデフォルトを持ちます。:cdo は quickfix の各エントリで Ex コマンドを実行します — マッチをまたぐ一括置換に完璧です。

vim
# Built-in :grep (uses external grep):
:grep pattern *.py        # search Python files
:grep -r pattern .        # recursive search
:grepadd pattern *.c      # append to existing quickfix list

# After :grep, results appear in the quickfix window:
:copen / :cw   # open quickfix window (cw only if non-empty)
:cnext / :cn   # next match
:cprev / :cp   # previous match
:cfirst / :clast  # first / last match
:cc N          # jump to match N
:cclose        # close quickfix window
:clist         # list all matches (no window)

# Customize the grep program:
:set grepprg=rg\ --vimgrep   " use ripgrep instead
:set grepformat=%f:%l:%c:%m,%f:%l:%m

# With ripgrep, super fast:
:grep pattern   # uses grepprg

# Multi-file edit from quickfix:
:cdo s/old/new/ge | update

vimgrep

:vimgrep は Vim 内部の検索エンジンを使います — 外部 grep より遅いですが移植性があり(外部ツールなしでどの OS でも動く)、Vim の正規表現構文を使います。パターンは // のデリミタの間に書き、**/*.py は Python ファイルを再帰的にマッチします。結果は quickfix リストに入ります — :copen で表示、:cn/:cp で移動。既存のリストに追加するには :vimgrepadd を使いましょう。

vim
# :vimgrep uses Vim's internal search (slower than
# external grep, but uses Vim regex and works everywhere).

:vimgrep /pattern/ **/*.py     # search recursively
:vimgrep /pattern/ *.txt       # current directory
:vimgrep /pattern/ file.txt    # single file
:vimgrep /\cFoo/ **/*          # case-insensitive

# Append to existing list:
:vimgrepadd /pattern/ *.c

# Open results in quickfix:
:copen

# Notes:
#   - ** means recursive
#   - Pattern uses Vim regex (same as /search)
#   - Slower than external grep (loads each file into Vim)
#   - Works without external tools (portable)

# Limit search to current buffer only:
:vimgrep /pattern/ %

# Search in visual selection across files: not directly,
# use :grep or external tool instead.

# Jump directly to first match (skip quickfix):
#   :vimgrep /pattern/ **/* | cfirst

ctags 連携

ctags は識別子(関数、クラスなど)のインデックスを生成し、Vim がコードナビゲーションに使います。Ctrl-] でカーソル下の定義へジャンプし、Ctrl-T で戻ります。曖昧なとき :ts がマッチするタグを一覧します。タグの生成にはプロジェクトルートで ctags -R . を実行しましょう。プロジェクト対応のナビゲーションのため、`set autochdir` か 'tags' パスを設定します。

vim
# Generate tags file (run in shell):
#   ctags -R .
# (or with Universal Ctags for more languages)

# In Vim, the tags file is auto-read from 'tags' option:
:set tags?        # default: ./tags,./TAGS,tags,TAGS

# Jump to definition (uses tags):
Ctrl-]            # jump to tag under cursor
:tag funcname     # jump to specific tag
:ts funcname      # list matching tags, pick one
:tn / :tp         # next / previous matching tag
:tl               # last tag
Ctrl-T            # pop back from tag jump
:tags             # show tag stack
:pop              # same as Ctrl-T

# Split window before jumping:
Ctrl-W ]          # split, then jump to tag
:stag funcname    # split, then jump

# Preview tag (open in preview window):
Ctrl-W }          # preview tag under cursor
:ptag funcname    # preview specific tag

# Regenerate tags from inside Vim:
:!ctags -R .

cscope 連携

cscope は ctags より多くのコードナビゲーションを提供します — 定義だけでなく呼び出し元、呼び出し先、include 関係も見つけられます。構築には `cscope -Rb` を使います。Vim では :cscope add でデータベースをリンクし、:cs find X symbol で照会します。cscopequickfix と組み合わせると、結果が quickfix リストに入り移動が容易になります。

vim
# Build cscope database (shell):
#   cscope -Rb       # creates cscope.out
# Or:
#   find . -name '*.c' > cscope.files
#   cscope -b

# In Vim, add the database:
:cscope add cscope.out
:cscope add /path/to/cscope.out /path/to/project

# Query types (use :cs find X symbol):
#   0 or s: symbol (this token)
#   1 or g: definition (same as Ctrl-])
#   2 or d: functions called by this function
#   3 or c: functions calling this function
#   4 or t: string (text)
#   6 or e: egrep pattern
#   7 or f: file
#   8 or i: includes (files #including this file)

:cs find 0 main         # find symbol 'main'
:cs find 3 myfunc       # find callers of myfunc
:cs find e pattern      # egrep search

# Auto-jump on result:
:set cscopequickfix=s-,c-,d-,i-,t-,e-,g-,f-

# Reset connection:
:cscope reset
:cscope kill <connection>

Netrw ファイルブラウザ

Netrw は Vim の組み込みファイルエクスプローラです — プラグイン不要。:Explore は現在のウィンドウで開き、:Lexplore は左のサイドバーをトグルします。中では Enter で開く、'-' で上へ、'D' で削除、'R' でリネーム、'd' で mkdir、'%' でファイル作成です。g:netrw_* 変数でカスタマイズできます(ツリービュー、バナーを隠す、ウィンドウサイズ)。

vim
# Netrw is Vim's built-in file explorer.

:Explore / :E       # open explorer in current window
:Sexplore / :Sex    # explorer in horizontal split
:Vexplore / :Vex    # explorer in vertical split
:Lexplore / :Lex    # explorer in left-side toggle

# Inside Netrw:
<CR>      # open file/directory
-         # go up one directory
D         # delete file
R         # rename file
d         # create directory
%         # create new file
i         # cycle view (thin/long/wide/tree)
r         # reverse sort
s         # select sort key
x         # open with system viewer
gh        # toggle hidden files
q         # close explorer

# Useful settings:
:let g:netrw_liststyle = 3      # tree view by default
:let g:netrw_winsize = 25       # window size 25%
:let g:netrw_banner = 0         # hide banner

# Toggle explorer:
:nmap <leader>e :Lexplore<CR>
17

高度な移動

文字検索(f/F/t/T)

f/F は現在行で次/前の文字を見つけ(カーソルはその上に載る)、t/T はその手前/直後まで移動します。; は同じ方向で最後の f/F/t/T を繰り返し、, は逆方向です。オペレータとの組み合わせ: dt, は次のカンマの手前まで(含めず)削除し、df. は次のピリオドを含めて削除します。行内ナビゲーションに速く正確です。

vim
f{x}    # find next char 'x' on line (cursor ON x)
F{x}    # find previous char 'x' (cursor ON x)
t{x}    # till next char 'x' (cursor BEFORE x)
T{x}    # till previous char 'x' (cursor AFTER x)
;       # repeat last f/F/t/T (same direction)
,       # repeat last f/F/t/T (opposite direction)

# Examples (cursor on 'a' in "hello world abc"):
#   fw  ->  cursor on 'w' (world)
#   tw  ->  cursor on space before 'w'
#   Fo  ->  cursor on 'o' (hello) - backwards
#   ;   ->  next 'w'... or next match of last

# Combined with operators:
dt,    # delete up to (not including) next ','
df.    # delete up to AND including next '.'
ct;    # change up to next ';'
yt:    # yank up to next ':'

# Find on a long line (no built-in multi-line f):
#   Use :s or search for multi-line patterns.

# Set 'hlsearch' to highlight f/F/t/T targets:
:set hlsearch   " doesn't highlight f, but / does.

文・段落の移動

( と ) は文単位で移動し(文は . ! ? に空白が続いて終わる)、開きと閉じの中括弧は段落単位(空行区切り)で移動します。折り返し行では gj/gk/g0/g$ が画面行に対して、j/k/0/$ が論理行に対して働きます — 'wrap' 有効時には必須です。( ) { } をオペレータと組み合わせましょう: das は文を削除し、yap は段落をヤンクします。

vim
(     # previous sentence start
)     # next sentence start
{     # previous paragraph start (blank-line delimited)
}     # next paragraph start

# Sentence boundaries: ends with . ! ? followed by
# whitespace or end of paragraph.

# Paragraph: block of lines separated by blank lines.

# Examples:
#   Hello world.  This is a sentence.
#   ^         ^  ^
#   (         )  ( moves to sentence starts

# Combine with operators:
das   # delete a sentence
cis   # change inside sentence
yap   # yank a paragraph
dip   # delete inside paragraph

# Move by visual line (with 'wrap' on):
gj    # down one screen line (wrap-aware)
gk    # up one screen line
g0    # start of screen line
g$    # end of screen line
g_    # last non-blank of screen line

# These respect wrapping where j/k don't.

対応する括弧(%)

% は対応する括弧の間をジャンプします(デフォルト: ()、[]、{})。'matchpairs' を適切に設定すれば #if/#endif や /* */ にも機能します。オペレータとの組み合わせ: d% はカーソルから対応箇所まで削除し、v% は選択します。[( [{ ]) ]} は対応が取れていない括弧へジャンプします — 囲んでいる関数/クラスのブロックを見つけるのに便利です。

vim
%    # jump to matching bracket: ( ) [ ] { }
     # also works on #if/#endif, /* */ with matching pairs

# In Normal mode:
%    # if cursor on (, jumps to matching )
%    # if cursor on ), jumps to matching (

# Combine with operators:
d%    # delete from cursor to matching bracket
c%    # change from cursor to matching bracket
y%    # yank from cursor to matching bracket
v%    # visually select from cursor to matching bracket

# Extend matching to other pairs:
:set matchpairs+=<:>
:set matchpairs+=«:»
# Default: (:),[:],{:}

# Move to enclosing bracket:
#   [(    # back to unmatched (
#   ])    # forward to unmatched )
#   [{    # back to unmatched {
#   ]}    # forward to unmatched }
#   [} / ]{  similar for braces

# Example: jump to outer function's opening brace:
[{   " previous unmatched {

画面内の移動

H/M/L は表示範囲の上端/中央/下端へジャンプします。Ctrl-f/b は全ページ、Ctrl-d/u は半ページスクロール(方向感覚を保てます)、Ctrl-e/y はカーソルを動かさず 1 行スクロールします。zz/zt/zb はカーソル行を画面の中央/上端/下端へ再配置します — 文脈を保つのに必須です。'scrolloff' はカーソルが画面の端に達しないようにします。

vim
H    # top of screen (High) — first non-blank
M    # middle of screen
L    # bottom of screen (Low) — first non-blank
N H  # Nth line from top (e.g. 5H = 5 lines from top)
N L  # Nth line from bottom

# Scrolling:
Ctrl-f   # forward (down) full screen
Ctrl-b   # backward (up) full screen
Ctrl-d   # down half screen
Ctrl-u   # up half screen
Ctrl-e   # scroll down 1 line (cursor stays)
Ctrl-y   # scroll up 1 line (cursor stays)

# Reposition cursor on screen:
zz   # cursor line to middle of screen
zt   # cursor line to top of screen
zb   # cursor line to bottom of screen
z.   # cursor to middle, first non-blank
z+   # cursor to bottom, scroll up (like zb but accepts count)

# Keep cursor off edges:
:set scrolloff=5   # always 5 lines above/below cursor
:set sidescrolloff=5  # 5 cols left/right of cursor

スクロールの同期

:set scrollbind はウィンドウ間でスクロールを同期します — 同期したい各ウィンドウで設定しましょう。:vimdiff は 2 つのファイルを diff モードで開き、scrollbind が有効で、差分が構文ハイライトされ、[c/]c で hunk を移動します。do(diff obtain)は他のウィンドウから変更を引き寄せ、dp(diff put)は押し込みます。ファイルのバージョン比較に最適です。

vim
# Bind windows to scroll together:
:set scrollbind      # current window syncs scroll
:set syncbind        # force immediate sync
:scrollbind          # same as :set scrollbind

# In each window you want synced:
#   :set scrollbind

# Unbind:
:set noscrollbind

# Common use: diff two files side by side
:vimdiff file1 file2    # opens both, scrollbound, diff highlighted
:diffthis               # mark current window as a diff
:diffoff                # turn off diff mode for current window
:diffupdate             # refresh diff highlighting

# Vertical diff split:
:vert diffsplit file2.txt

# In diff mode:
[c    # previous diff hunk
]c    # next diff hunk
do    # diff obtain (pull from other window)
dp    # diff put (push to other window)

# Bind but at different starting positions:
#   Set scrollbind AFTER scrolling to desired positions.

位置への移動

カーソル位置を指定する方法は多数あります: 行 N には :N、割合には N%、特殊マークには `.`/`"`/[`]/`</`>(最後の変更、最後の終了、最後のヤンク、最後のビジュアル)。Ctrl-o/Ctrl-i で jumplist を移動します。`" はファイルが最後に閉じられた位置を復元します — viminfo の設定と組み合わせればセッションをまたいで保持されます。

vim
:N          # go to line N (e.g. :42)
Ng / N G    # go to line N (e.g. 42G or 42gg)
gg          # first line
G           # last line
N%          # go to N% of file (e.g. 50% = middle)
:-N         # N lines before current (e.g. :-5)
:+N         # N lines after current (e.g. :+10)

# Marks and jumps:
\`.            # position of last change in this buffer
\`"            # position when file was last closed
\`[            # start of last yanked/changed region
\`]            # end of last yanked/changed region
\`<            # start of last visual selection
\`>            # end of last visual selection
\`^            # last insert position (gi goes here + insert)

# Recent jumps:
Ctrl-o      # back in jumplist
Ctrl-i      # forward in jumplist
\`'            # position before last jump (where you came from)

# File position on save:
:set viminfo^=%   # remember buffer positions across sessions

# Cursor hold (no movement for 'updatetime' ms):
# CursorHold event triggers (advanced)
18

コマンドラインモード

範囲コマンド

範囲はコマンドがどの行に作用するかを指定します。:% はファイル全体(1,$)、. は現在行、$ は最終行です。'<,'> は最後のビジュアル選択です(ビジュアルモードで : を押すと自動入力)。'a,'b はマーク a からマーク b までです。検索パターンも範囲の境界に使えます: :/foo/,/bar/d は foo にマッチする行から bar にマッチする行まで削除します。

vim
# Range syntax: :{start},{end}command

# Range forms:
:%          # whole file (1,$)
:1,10       # lines 1-10
:.,$        # current line to end of file
:1,.        # first line to current
:'a,'b      # from mark a to mark b
:'<,'>      # last visual selection
:.          # current line only
:N          # line N only
:.,+5       # current line + 5 below
:.,-2       # current line - 2 above

# Examples:
:1,10d          # delete lines 1-10
:%s/old/new/g   # substitute whole file
:'<,'>s/old/new/g  # substitute visual selection
:.,$j           # join from current to end into one line
:5,10y a        # yank lines 5-10 into register a
:g/pattern/m$   # move matching lines to end of file

# Search-based range:
:/start/,/end/d    # delete from 'start' to 'end' patterns

ファイルコマンド

:w で保存、:e で新しいファイルを開く、:r で別ファイルの内容を挿入(シェル出力は :r !cmd)。:saveas は保存して新しいファイルへ切り替えます。:e! は変更を破棄してファイルを再読み込みします。++enc/++ff でエンコーディング/改行コードを明示的に指定できます — ファイルの変換に便利です。:browse e は GUI のファイルダイアログを開きます(GUI 版 Vim)。

vim
:w / :write          # save current file
:w file.txt          # save as new file
:w! file.txt         # overwrite existing file
:w >> file.txt       # append to file
:saveas / :sav file  # save as new file and switch to it
:e / :edit file      # open file (replace current buffer)
:e!                  # reload current file (discard changes)
:e #                 # edit alternate file
:r / :read file      # insert file below cursor
:r !command          # insert command output below cursor
:0r !date            # insert date at top of file

# Multiple files:
:wa / :wall          # write all buffers
:xa / :xall          # write all and quit
:qa!                 # quit all without saving

# Browse file system:
:browse e            # GUI file open dialog
:Explore             # Netrw file browser

# File encoding:
:w ++enc=utf-8       # save as UTF-8
:e ++enc=latin1 file # open with specific encoding

# File format (line endings):
:w ++ff=unix         # save as Unix line endings

バッファとウィンドウのコマンド

マルチバッファ/ウィンドウ/タブの操作はすべて Ex コマンドの形があります。:b はバッファを切り替え、:sp/:vs はウィンドウを分割し、:tabnew はタブを作ります。:*do ファミリー(bufdo、argdo、tabdo、windo、cdo)は多くのターゲットにコマンドを実行します — 一括操作に非常に強力です。:ls はバッファ、:tabs はタブ、:args は arglist を表示します。

vim
# Buffer commands:
:b N / :buffer N     # switch to buffer N
:b name              # switch by name (tab-completes)
:bd / :bdelete       # delete buffer
:bw / :bwipeout      # wipe buffer (clears marks)
:ls / :buffers       # list buffers
:bn / :bp            # next / previous buffer
:b#                  # alternate buffer

# Window commands:
:sp / :split         # horizontal split
:vs / :vsplit        # vertical split
:new                 # split with empty buffer
:close               # close window
:only                # close all other windows
:qa / :qa!           # quit all windows

# Tab page commands:
:tabnew              # new tab
:tabe file           # new tab with file
:tabc                # close tab
:tabo                # close other tabs
:tabs                # list tabs
:tabn / :tabp        # next / previous tab

# Argument list commands:
:args                # show arg list
:n / :next           # next arg file
:prev                # previous arg file
:argdo cmd           # run cmd on each arg file

オプションの設定

:set はブールオプションを ! でトグルし、値は = で設定し、+=/-= で追加/削除し、& でデフォルトに戻します。:set option? は現在値を表示します。:setlocal はバッファ/ウィンドウローカルの値を設定します(他のバッファには影響しません)。引数なしの :set は変更済みのオプションを一覧し、:set all はすべて表示します。オプション名は Tab で補完できます。

vim
:set option           # turn boolean option on
:set nooption        # turn boolean option off
:set option!         # toggle boolean
:set option?         # show current value
:set option=value    # set value
:set option+=value   # append to value
:set option-=value   # remove from value
:set option&         # reset to default
:set all             # show all options
:set                 # show changed options

# Local vs global:
:setlocal option     # buffer/window-local only
:setglobal option    # global value

# Examples:
:set number          # show line numbers
:set nonumber        # hide line numbers
:set number!         # toggle
:set tabstop=4       # set tabstop to 4
:set formatoptions+=r  # add 'r' to formatoptions
:set ignorecase&     # reset ignorecase to default

# View all set options:
:set                 # shows only non-default values

# Find option with substring:
:set ic<tab>         # tab-complete (ignorecase)

map コマンド

個人のマッピングには *noremap 系を使いましょう — 再帰しないので予想外の挙動を防げます。<leader> はカスタマイズ可能なプレフィックスです(デフォルトはバックスラッシュ。スペースやカンマにする人も多い)。<buffer> はマッピングを現在のバッファに限定します。特殊キーは <CR>、<Esc>、<C-x>(Ctrl-X)、<A-x>(Alt-X)のような <notation> を使います。

vim
:map <key> <action>        # generic map (most modes)
:nmap <key> <action>       # normal mode
:imap <key> <action>       # insert mode
:vmap <key> <action>       # visual mode
:xmap <key> <action>       # visual mode only
:smap <key> <action>       # select mode
:omap <key> <action>       # operator-pending mode
:cmap <key> <action>       # command-line mode
:tmap <key> <action>       # terminal mode

# Non-recursive (RECOMMENDED for personal mappings):
:nnoremap <key> <action>   # normal mode
:vnoremap <key> <action>   # visual mode
:inoremap <key> <action>   # insert mode
:onoremap <key> <action>   # operator-pending
:cnoremap <key> <action>   # command-line
:tnoremap <key> <action>   # terminal

# Buffer-local mappings:
:nnoremap <buffer> <key> <action>

# Clear a mapping:
:nunmap <key>   # or :nmapclear (clears all normal maps)

# Special keys in mappings:
# <CR> <Esc> <Tab> <Space> <BS> <C-x> <A-x> <M-x>
# <F1>-<F12> <Up> <Down> <Left> <Right>
# <leader> <localleader> <C-r> <C-w>
:let mapleader = ' '
:let maplocalleader = '\\'

便利な Ex コマンド

:!cmd はシェルコマンドを実行し、:r !cmd はその出力をバッファに挿入します。:sort は行をソートします(u = ユニーク、n = 数値、! = 逆順)。:retab はタブとスペースを相互変換します。:normal はノーマルモードのキーストロークを Ex として実行します — カスタムマッピングを無視するには ! を付けます。:%!cmd はファイル全体を外部コマンドに渡し、出力で置き換えます。

vim
:!command        # run shell command
:r !command     # insert command output below cursor
:!!              # repeat last :! command
:sh              # open a shell (exit to return)
:terminal / :term  # open terminal in a window
:read file       # insert file contents below cursor
:sort            # sort selected lines (visual mode)
:sort u          # sort and remove duplicates
:sort n          # numeric sort
:sort!           # reverse sort
:retab           # convert tabs to spaces (and vice versa)
:retab!          # also convert in strings
:normal {cmds}   # run normal-mode commands
:normal! {cmds}  # ignore mappings (use raw keys)

# Execute Ex commands from a register:
:@a              # run Ex commands in register 'a'
:@@              # repeat last :@

# Range + command examples:
:5,20s/old/new/g  # substitute in lines 5-20
:%!sort           # pipe whole file through sort
:'<,'>!column -t  # format visual selection as columns

# Help:
:help :command   # help on a specific command
19

Vimscript の基本

変数

Vimscript は代入に let、削除に unlet を使います。変数はプレフィックスでスコープを示します: g:(グローバル)、b:(バッファ)、w:(ウィンドウ)、t:(タブ)、s:(スクリプト)、l:(関数ローカル)、v:(組み込み)。const は不変の値を作ります(Vim 8+)。exists() は変数が定義されているか調べます。Vim 8.2+ は $"...{expr}..." の文字列補完をサポートします。

vim
let var = value          # assignment
let var = "hello"        # string
let var = 42             # number
let var = 3.14           # float
let var = [1, 2, 3]      # list
let var = {"key": "val"} # dictionary
unlet var                # delete a variable

# Variable scopes (prefix with letter + colon):
let g:global_var = 1     # global (everywhere)
let b:buffer_var = 1     # buffer-local
let w:window_var = 1     # window-local
let t:tab_var = 1        # tab-local
let s:script_var = 1     # script-local (this file only)
let l:local_var = 1      # function-local
let v:count              # built-in Vim variable

# Constants (Vim 8+):
const PI = 3.14159
let g:CONFIG = #{name: "vim"}  # locked dictionary

# Check if a variable exists:
if exists('var')
if exists('g:plugin_var')

# String interpolation (Vim 8.2+):
let name = "World"
echo $"Hello, {name}!"

関数

function! Name(args) ... endfunction が関数を定義します — ! で再定義を許可します。引数は a: でアクセスし、a:000 は可変引数のリストです。デフォルト引数(Vim 8+)は =value を使います。ラムダ(Vim 8+)は {args -> expr} です。function('Name') は渡せる funcref を返します。副作用のために関数を呼ぶには :call を使いましょう。

vim
# Define a function:
function! MyFunc(arg1, arg2)
  echo a:arg1 . ' ' . a:arg2
  return a:arg1 + a:arg2
endfunction

# The ! in function! overrides an existing function
# (without ! Vim errors if function already exists).

# Call a function:
call MyFunc("hello", "world")
let result = MyFunc(1, 2)

# Variadic arguments (...):
function! Sum(...)
  let total = 0
  for i in a:000
    let total += i
  endfor
  return total
endfunction

# Default arguments (Vim 8+):
function! Greet(name, greeting="Hello")
  echo a:greeting . ', ' . a:name
endfunction

# Lambda / anonymous functions (Vim 8+):
let Square = {x -> x * x}
echo Square(5)   " 25

# Function as a value:
let Fn = function('MyFunc')
echo Fn(1, 2)

条件分岐とループ

条件には if/elseif/else/endif。for はリストを反復し(range(N) が 0..N-1 を生成)、items() から [key, val] のペアを展開できます。条件ループには while/endwhile。break/continue は期待どおりに機能します。よく使う条件チェック: 機能には has()、変数/コマンドには exists()、ファイルには filereadable()、空値には empty()、型比較には type()。

vim
# Conditionals:
if x > 10
  echo "big"
elseif x > 5
  echo "medium"
else
  echo "small"
endif

# Ternary:
let result = (x > 0) ? "positive" : "non-positive"

# Loops:
for i in range(5)       # 0,1,2,3,4
  echo i
endfor

for [key, val] in items({'a': 1, 'b': 2})
  echo key . '=' . val
endfor

while x > 0
  let x -= 1
endwhile

# Loop control:
break       # exit loop
continue    # skip to next iteration

# Match-related conditionals:
if has('python3')          # feature check
if exists(':Command')      # command exists
if filereadable('file')    # file is readable
if empty(var)              # variable is empty
if type(var) == type([])   # type check

文字列

. は文字列を連結します。Vim 8.2+ は $"...{expr}..." の補完を追加しました。len/strlen はバイト長を、strcharlen は文字数を返します(マルチバイトで重要)。split/join は文字列とリストを相互変換します。substitute() はプログラム版の :s コマンドです。matchstr() は正規表現のマッチを取り出し、=~ は正規表現マッチの演算子です。

vim
# String concatenation:
let s = "Hello" . " " . "World"

# String interpolation (Vim 8.2+):
let name = "Vim"
echo $"Welcome to {name}!"

# Common functions:
len("hello")              # 5
strlen("hello")           # 5 (byte length)
strcharlen("hello")       # 5 (char length)
tolower("HELLO")          # "hello"
toupper("hello")          # "HELLO"
strpart("hello", 1, 3)    # "ell" (substring)
matchstr("foo123bar", '\d\+')  # "123"
substitute("foo", 'o', '0', 'g')  # "f00"
split("a,b,c", ',')       # ['a', 'b', 'c']
join(['a', 'b', 'c'], '-')  # "a-b-c"
trim("  hello  ")         # "hello"

# printf-style formatting:
printf("%d + %d = %d", 1, 2, 3)  # "1 + 2 = 3"
printf("%05.2f", 3.14159)        # "03.14"

# Regex matching:
if "hello" =~ '^h'
  echo "starts with h"
endif

リストと辞書

リストは順序付き(配列のようなもの)で、辞書はキー=値のマップです。リストのスライスは [start:end] を使います。add/insert/remove はリストをその場で変更し、sort/reverse も破壊的です。辞書は .key と ["key"] のどちらのアクセスも可能で、keys()/values()/items() はリストを返します。所属判定には has_key() を使います。#{...}(Vim 8+)はキーの引用が不要な、よりきれいな辞書リテラルです。

vim
# Lists (like arrays):
let nums = [1, 2, 3, 4, 5]
echo nums[0]              # 1 (first)
echo nums[-1]             # 5 (last)
echo nums[1:3]            # [2, 3, 4] (slice)

# List operations:
call add(nums, 6)         # append 6
call insert(nums, 0, 0)   # insert 0 at index 0
call remove(nums, 0)      # remove index 0
echo len(nums)            # length
call sort(nums)           # sort in place
call reverse(nums)        # reverse in place
call extend(nums, [7, 8]) # concatenate

# Iterate:
for n in nums
  echo n
endfor

# Dictionaries (like hash maps / objects):
let d = {"name": "Vim", "version": 9}
echo d.name               # "Vim"
echo d["version"]         # 9
let d.lang = "Vimscript"  # add a key
call remove(d, "version") # remove a key
echo keys(d)              # ['name', 'lang']
echo values(d)            # ['Vim', 'Vimscript']
echo items(d)             # [['name', 'Vim'], ['lang', 'Vimscript']]
echo has_key(d, "name")   # 1 (true)

# Dictionary literal (Vim 8+, cleaner):
let d2 = #{key: "value", count: 42}

autocmd とカスタムコマンド

autocmd は Vim のイベント(BufRead、BufWritePre、FileType、VimEnter、CursorMoved など)でコードを実行します。autocmd は必ず augroup で包み、autocmd! で古い定義を消しましょう — 再読み込み時の重複を防ぎます。カスタムコマンドは :command! -nargs=N -range -bang Name action の形です。<args>、<line1>、<line2>、<bang> がコマンド定義内でユーザーの入力へアクセスします。

vim
# Autocmds: run code on events
:autocmd BufWritePre *.md :%s/\s\+$//e   " trim trailing whitespace

# Group autocmds (recommended - prevents duplicates on reload):
augroup markdown_settings
  autocmd!
  autocmd BufRead,BufNewFile *.md setlocal spell
  autocmd FileType markdown setlocal textwidth=80
  autocmd BufWritePre *.md :%s/\s\+$//e
augroup END

# Common events:
# BufReadPost   - after loading a file
# BufWritePre   - before saving
# BufWritePost  - after saving
# FileType      - when filetype is set
# VimEnter      - after Vim startup
# CursorMoved   - cursor moved in normal mode
# InsertEnter   - entering insert mode

# Custom Ex commands:
command! -nargs=1 Grep !grep <args> %
command! -range Sum echo <line1> + <line2>
command! -bang Q quit<bang>

# Use them:
:Grep pattern
:Sum

# Show all autocmds:
:autocmd
# Show autocmds for a specific event:
:autocmd BufWritePre

Was this helpful?