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는 문자 하나를 삭제하고 삽입하며 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은 문자 하나를 바꾸고 즉시 노멀 모드로 돌아갑니다(모드 전환 없음). 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는 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는 노멀 명령 하나를 실행한 뒤 삽입으로 돌아옵니다(예: 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(문자 삭제)의 단축입니다. 삭제한 텍스트는 unnamed 레지스터(와 1번 레지스터)로 갑니다. 텍스트 객체(ciw, dib)와 d를 쓰면 강력한 편집이 됩니다. J는 다음 줄을 공백 하나로 현재 줄에 합칩니다.

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는 줄을 양크합니다. x라는 단축이 있는 d와 달리 y에는 단일 문자 단축이 없어 모션을 써야 합니다. 양크는 항상 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)

Put(붙여넣기)

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.

대소문자 변경

~는 문자 하나의 대소문자를 토글하고 전진합니다. 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는 줄을 공백 하나로 합치고 gJ는 아무것도 넣지 않고 합칩니다. :join은 범위에 동작합니다. gq는 포맷 연산자로 'textwidth'(보통 80)에 맞게 줄을 감싸며 'formatoptions'를 존중합니다. gqip는 문단을 재배치하고 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에서 가장 유용한 키입니다. u/Ctrl-r은 실행 취소/재실행입니다. 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). 그룹 문법을 단순화하려면 \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은 널 바이트). '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 명령을 실행하는 강력한 '전역' 편집기입니다. :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가 예상대로 동작합니다. =는 자동 들여쓰기(코드 재포맷에 좋음)입니다. >/<는 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의 가장 강력한 기능 중 하나입니다. 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은 최근 두 버퍼를 토글하는 가장 빠른 방법입니다. '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는 현재 창의 버퍼를 바꾸지 않고 분할에서 버퍼를 엽니다. 내장된 '최근 닫은 버퍼' 실행 취소는 없지만 플러그인이 있습니다. :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은 중요한 커서 이동의 점프 목록을 유지합니다. Ctrl-o/Ctrl-i는 뒤/앞으로 이동합니다. '중요한' 것은 점프(G, gg, 검색, 마크 점프, 태그 점프)이며 j/k/w 같은 일반 모션은 아닙니다. :jumps는 목록을 보여줍니다. 점프 목록은 창별이며 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

변경 목록

변경 목록은 (탐색이 아닌) 편집 위치를 추적합니다. g;는 이전 편집, g,는 다음 편집으로 점프합니다. 방금 어디서 작업했는지 되짚을 때 유용합니다. :changes는 목록을 보여줍니다. 점프 목록과 달리 변경 목록은 버퍼별입니다. 현재 버퍼의 마지막 변경에는 `.`을 결합하세요.

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), 특수(unnamed ", yank 0, clipboard + 등). :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

추가와 블랙홀

대문자 레지스터는 추가(append)합니다: "Ayy는 a 레지스터에 추가하므로 텍스트나 다단계 매크로를 쌓는 데 매우 유용합니다. 블랙홀 레지스터 "_는 쓰인 내용을 모두 버려 삭제가 숫자/unnamed/양크 레지스터를 갱신하지 않습니다. 마지막 양크를 덮어쓰지 않고 텍스트를 삭제하고 싶을 때 사용하세요.

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는 매크로를 한 번, @@는 마지막 매크로를 재생하고 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

수동 접기

수동 모드에서 zf는 접기를 만듭니다(예: zf3j는 다음 3줄을 접음). zd는 접기 하나를, zD는 재귀적으로, zE는 창의 모든 접기를 삭제합니다. 비주얼 모드 + zf는 선택을 접습니다. foldmethod=marker에서는 주석에 {{{와 }}}를 넣어 파일에 저장되는 지속 접기를 만들 수 있어 버전 관리에서 접기 구조를 공유할 때 유용합니다.

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은 접기 수준을 전역으로 조정합니다(한 번에 한 수준). 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는 접힌 모든 줄을 하나의 단위(줄 단위)로 조작합니다. 닫힌 접기 안에서 입력하면 열립니다. '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은 새 분할에서 파일을 엽니다. :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는 이전에 사용한 창으로 돌아가므로 두 창을 오갈 때 유용합니다.

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은 버퍼마다 창을 열어 한눈에 모두 보기에 유용합니다. 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)는 창을 닫지만 마지막 창은 닫지 않습니다. :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는 시작 시 각 파일을 자체 탭에서 엽니다. 각 탭 페이지는 하나 이상의 창을 담습니다. 탭은 단일 파일이 아니라 레이아웃입니다. Ctrl-w T는 현재 창을 새 탭 페이지로 옮깁니다. 탭은 관련 없는 작업 맥락(예: 프로젝트 영역당 탭 하나)을 분리하는 데 좋습니다.

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을 매핑하는 것이 흔합니다. 탭은 기본적으로 순환합니다. 각 탭은 자체 창 레이아웃(분할 등)을 유지합니다.

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.

탭 레이아웃과 다중 창

각 탭 페이지는 독립적인 창 레이아웃(분할, 크기, 위치)을 유지합니다. 탭마다 여러 창을 둘 수 있습니다. Ctrl-w T는 창을 자체 새 탭으로 옮깁니다. :set showtabline=2는 항상 탭 바를 보여줍니다. 탭은 작업 공간 구분자(예: 프로젝트 영역당 탭 하나)로 쓰는 것이 가장 좋으며 각각 자체 레이아웃을 가집니다.

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=항상). 포맷 문자열을 반환하는 함수로 tabline을 완전히 사용자 정의할 수 있어 수정 상태, 버퍼 이름, 탭 번호를 표시할 때 유용합니다. 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는 커서 아래 파일을 새 탭에서 엽니다. 탭으로 관련 파일(기능/영역당 탭 하나)을 묶으세요. 탭 간 작업에는 :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는 :command 완성을 메뉴로 강화합니다. 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는 <<, >>, 자동 들여쓰기가 쓰는 들여쓰기 양입니다. 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는 탭, 뒤 공백, 줄바꿈 없는 공백을 보여줍니다. colorcolumn은 열(예: 줄 길이 제한 80)을 표시합니다. termguicolors는 최신 터미널에서 진정한 24비트 색을 켭니다. splitright/splitbelow는 새 분할 위치를 제어합니다.

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>는 이스케이프, <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' 옵션은 지연 로딩(명령/파일타입이 트리거할 때만 로드)을 켜 시작 시간을 개선합니다.

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 같은 좋은 색상 테마.

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

플러그인 로딩과 런타임

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+ 내장 패키지(플러그인 관리자 불필요, pack/<name>/start/에 플러그인 배치)가 있습니다. Neovim 사용자에게는 Packer(Lua 기반)가 인기입니다. 내장 패키지는 미니멀리스트에게 좋습니다.

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는 검색을 현재 비주얼 선택으로 제한합니다. / 후 Up은 검색 기록을 불러오고 :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.

Quickfix와 grep

: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.

문장과 문단 이동

(와 )는 문장 단위, {와 }는 문단(빈 줄 구분) 단위로 이동합니다. 감싸진 줄에서는 j/k/0/$가 논리 줄에서 동작하는 반면 gj/gk/g0/g$는 화면 줄에서 동작하므로 '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는 커서를 움직이지 않고 한 줄 스크롤합니다. 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는 diff 모드로 두 파일을 열고 scrollbind, 문법 강조 차이, [c/]c로 헝크 탐색을 제공합니다. 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는 점프 목록을 탐색합니다. `"는 파일이 마지막으로 닫힌 위치를 복원하며 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)

매핑 명령

개인 매핑에는 *noremap 변형을 사용하세요. 재귀하지 않아 예상 밖 동작을 막습니다. <leader>는 사용자 정의 접두사입니다(기본 백슬래시, 많은 사람이 공백이나 쉼표로 설정). <buffer>는 매핑을 현재 버퍼에 한정합니다. 특수 키는 <CR>, <Esc>, <C-x>(Ctrl-X), <A-x>(Alt-X) 같은 <표기>를 씁니다.

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?