Split View: Vim 명령어 완벽 가이드: 텍스트 에디터의 끝판왕을 마스터하는 모든 명령어 총정리
Vim 명령어 완벽 가이드: 텍스트 에디터의 끝판왕을 마스터하는 모든 명령어 총정리
- 1. Vim 소개
- 2. 모드(Mode) 개념
- 3. 이동 명령어
- 4. 편집 명령어
- 5. Visual Mode
- 6. 텍스트 객체 (Text Objects)
- 7. 명령 모드 (Command-line Mode)
- 8. 버퍼, 윈도우, 탭
- 9. 매크로와 레지스터
- 10. .vimrc 필수 설정
- 11. 플러그인 생태계
- 12. 치트시트 종합 테이블
- 13. Reference
1. Vim 소개
1.1 역사: Vi → Vim → Neovim
Vi는 1976년 Bill Joy가 BSD Unix를 위해 작성한 텍스트 에디터다. 당시 터미널 환경에서 키보드만으로 효율적인 편집을 가능하게 한 혁신적인 도구였다. Vi의 핵심 아이디어인 **모달 편집(Modal Editing)**은 오늘날까지 살아 숨 쉰다.
Vim(Vi IMproved)은 1991년 Bram Moolenaar가 공개한 Vi의 대폭 확장 버전이다. 구문 강조, 플러그인 시스템, 다중 창, 매크로, 정규식 치환 등 수백 가지 기능이 추가되었다. Vim은 GNU/Linux 서버에 기본 탑재되어 전 세계 개발자와 시스템 관리자가 일상적으로 사용하는 표준 에디터가 되었다.
Neovim은 2014년에 시작된 Vim의 리팩토링 포크다. Lua 기반 설정, 내장 LSP(Language Server Protocol), 비동기 플러그인 API를 제공하며, VS Code 수준의 IDE 경험을 터미널에서 구현하는 것을 목표로 한다.
| 에디터 | 출시 | 특징 |
|---|---|---|
| Vi | 1976 | 모달 편집의 원조, 경량 |
| Vim | 1991 | 플러그인, 구문 강조, 매크로 |
| Neovim | 2014 | Lua API, 내장 LSP, 비동기 처리 |
1.2 왜 Vim을 배워야 하는가
- 어디서나 사용 가능: SSH 접속한 원격 서버, Docker 컨테이너, 임베디드 장치 — 거의 모든 Unix 환경에 Vi/Vim이 설치되어 있다.
- 손이 키보드를 벗어나지 않는다: 마우스 없이 모든 조작이 가능하므로 편집 속도가 극적으로 향상된다.
- 강력한 조합 언어:
d3w(단어 3개 삭제),ci"(따옴표 안 내용 변경) 처럼 동사+횟수+명사 구조로 복잡한 조작을 간결하게 표현한다. - 매크로와 자동화: 반복 작업을 매크로로 기록하여 수천 줄을 순식간에 변환한다.
- Vim 키바인딩의 범용성: VS Code, IntelliJ, Obsidian, Jupyter, bash readline, tmux copy mode 등 수십 가지 도구가 Vim 키바인딩을 지원한다. Vim을 배우면 모든 도구가 빨라진다.
2. 모드(Mode) 개념
Vim의 가장 중요한 특징은 모달 편집이다. 키를 누를 때의 동작이 현재 모드에 따라 완전히 달라진다.
2.1 주요 모드 및 전환
| 모드 | 설명 | 진입 방법 | 탈출 방법 |
|---|---|---|---|
| Normal | 이동, 명령 실행 | <Esc>, <C-c> | — (기본 모드) |
| Insert | 텍스트 입력 | i, a, o, I, A, O, s, c | <Esc>, <C-c> |
| Visual | 문자 단위 선택 | v | <Esc>, v |
| Visual Line | 줄 단위 선택 | V | <Esc>, V |
| Visual Block | 블록(열) 단위 선택 | <C-v> | <Esc>, <C-v> |
| Command-line | : 명령 입력 | :, /, ?, ! | <Esc>, <CR> |
| Replace | 문자 덮어쓰기 | R | <Esc> |
2.2 모드 전환 다이어그램
┌─────────────────────────────────────────┐
│ Normal Mode │
│ (Vim 시작 시 / <Esc> 로 항상 복귀) │
└────┬───────┬───────┬────────────────────┘
│ │ │
i,a,o│ v,V│ :,/,?│
│ │ │
┌────▼──┐ ┌──▼────┐ ┌▼────────────┐
│Insert │ │Visual │ │Command-line │
│ Mode │ │ Mode │ │ Mode │
└───────┘ └───────┘ └─────────────┘
규칙: 언제든
<Esc>를 누르면 Normal Mode로 돌아간다. 방향을 잃었을 때<Esc>를 2번 누르는 것이 Vim 생존 법칙 #1이다.
3. 이동 명령어
3.1 기본 이동 (hjkl)
| 키 | 동작 |
|---|---|
h | 왼쪽 한 칸 |
j | 아래 한 줄 |
k | 위 한 줄 |
l | 오른쪽 한 칸 |
5j | 아래 5줄 (숫자 접두어 조합 가능) |
10k | 위 10줄 |
3.2 단어 단위 이동
| 키 | 동작 |
|---|---|
w | 다음 단어 시작으로 이동 (구두점 구분) |
W | 다음 WORD 시작으로 이동 (공백 구분) |
b | 이전 단어 시작으로 이동 |
B | 이전 WORD 시작으로 이동 |
e | 현재/다음 단어 끝으로 이동 |
E | 현재/다음 WORD 끝으로 이동 |
ge | 이전 단어 끝으로 이동 |
소문자(
w,b,e)는 구두점을 단어 경계로 인식하고, 대문자(W,B,E)는 공백만 경계로 인식한다.hello_world에서w는 2번,W는 1번에 이동한다.
3.3 줄 단위 이동
| 키 | 동작 |
|---|---|
0 | 줄의 맨 처음(컬럼 0)으로 이동 |
^ | 줄의 첫 번째 비공백 문자로 이동 |
$ | 줄의 맨 끝으로 이동 |
g_ | 줄의 마지막 비공백 문자로 이동 |
gg | 파일의 첫 번째 줄로 이동 |
G | 파일의 마지막 줄로 이동 |
42G | 42번 줄로 이동 |
:42 | 42번 줄로 이동 (명령 모드) |
% | 매칭되는 괄호/중괄호/대괄호로 이동 |
3.4 화면 스크롤
| 키 | 동작 |
|---|---|
<C-u> | 화면 절반 위로 스크롤 |
<C-d> | 화면 절반 아래로 스크롤 |
<C-f> | 화면 전체 아래로 스크롤 (Page Down) |
<C-b> | 화면 전체 위로 스크롤 (Page Up) |
H | 화면 맨 위 줄로 커서 이동 (High) |
M | 화면 중간 줄로 커서 이동 (Middle) |
L | 화면 맨 아래 줄로 커서 이동 (Low) |
zz | 현재 줄을 화면 중앙에 맞춤 |
zt | 현재 줄을 화면 상단에 맞춤 |
zb | 현재 줄을 화면 하단에 맞춤 |
3.5 검색 이동
| 키 | 동작 |
|---|---|
/pattern | 아래 방향으로 pattern 검색 |
?pattern | 위 방향으로 pattern 검색 |
n | 같은 방향으로 다음 검색 결과 |
N | 반대 방향으로 다음 검색 결과 |
* | 커서 아래 단어를 아래 방향으로 검색 |
# | 커서 아래 단어를 위 방향으로 검색 |
f{char} | 현재 줄에서 char를 앞 방향 검색, 그 위치로 이동 |
F{char} | 현재 줄에서 char를 뒤 방향 검색 |
t{char} | char 바로 앞으로 이동 (till) |
T{char} | char 바로 뒤(역방향)로 이동 |
; | f/F/t/T 방향으로 반복 |
, | f/F/t/T 역방향으로 반복 |
3.6 점프 이동
| 키 | 동작 |
|---|---|
<C-o> | 이전 커서 위치로 이동 (jump back) |
<C-i> | 다음 커서 위치로 이동 (jump forward) |
'' | 직전 점프 위치로 복귀 (작은따옴표 2번) |
m{a-z} | 현재 위치를 마크 a~z로 저장 |
'{a-z} | 마크로 이동 |
gd | 로컬 정의(declaration)로 이동 |
gD | 전역 정의로 이동 |
4. 편집 명령어
4.1 삽입 모드 진입
| 키 | 동작 |
|---|---|
i | 커서 앞에서 Insert Mode 진입 |
I | 줄의 첫 비공백 문자 앞에서 Insert Mode 진입 |
a | 커서 뒤에서 Insert Mode 진입 (append) |
A | 줄의 끝에서 Insert Mode 진입 |
o | 현재 줄 아래에 새 줄을 추가하고 Insert Mode 진입 |
O | 현재 줄 위에 새 줄을 추가하고 Insert Mode 진입 |
gi | 마지막으로 편집한 위치에서 Insert Mode 진입 |
4.2 삭제 명령어
| 키 | 동작 |
|---|---|
x | 커서 아래 문자 삭제 |
X | 커서 앞 문자 삭제 (Backspace) |
dd | 현재 줄 삭제 |
3dd | 현재 줄부터 3줄 삭제 |
D | 커서부터 줄 끝까지 삭제 (d$와 동일) |
dw | 커서부터 다음 단어 시작 전까지 삭제 |
de | 커서부터 단어 끝까지 삭제 |
d0 | 커서부터 줄 시작까지 삭제 |
dG | 현재 줄부터 파일 끝까지 삭제 |
dgg | 현재 줄부터 파일 시작까지 삭제 |
삭제된 텍스트는 레지스터에 저장되어
p로 붙여넣기할 수 있다. Vim의 삭제는 "잘라내기(Cut)"와 동일하다.
4.3 변경 명령어
| 키 | 동작 |
|---|---|
r{char} | 커서 아래 문자를 char로 교체 (Normal Mode 유지) |
R | Replace Mode 진입 (연속 덮어쓰기) |
s | 커서 아래 문자 삭제 후 Insert Mode 진입 |
S | 현재 줄 내용 삭제 후 Insert Mode 진입 (cc와 동일) |
cw | 커서부터 단어 끝까지 변경 |
cc | 현재 줄 내용 변경 |
C | 커서부터 줄 끝까지 변경 (c$와 동일) |
c0 | 커서부터 줄 시작까지 변경 |
~ | 커서 아래 문자의 대소문자 토글 |
g~w | 단어의 대소문자 토글 |
guw | 단어를 소문자로 변환 |
gUw | 단어를 대문자로 변환 |
4.4 복사 및 붙여넣기
| 키 | 동작 |
|---|---|
yy | 현재 줄 복사 (yank) |
Y | 현재 줄 복사 (yy와 동일) |
3yy | 현재 줄부터 3줄 복사 |
yw | 커서부터 단어 끝까지 복사 |
y$ | 커서부터 줄 끝까지 복사 |
y0 | 커서부터 줄 시작까지 복사 |
p | 커서 뒤(아래)에 붙여넣기 |
P | 커서 앞(위)에 붙여넣기 |
gp | p와 동일하나 붙여넣기 후 커서를 붙여넣은 텍스트 끝으로 이동 |
"ayy | 레지스터 a에 현재 줄 복사 |
"ap | 레지스터 a의 내용 붙여넣기 |
4.5 Undo / Redo
| 키 | 동작 |
|---|---|
u | 마지막 변경 취소 (Undo) |
3u | 마지막 3개 변경 취소 |
<C-r> | Undo 취소 (Redo) |
U | 현재 줄에 대한 모든 변경 취소 |
4.6 들여쓰기
| 키 | 동작 |
|---|---|
>> | 현재 줄 들여쓰기 |
<< | 현재 줄 내어쓰기 |
3>> | 3줄 들여쓰기 |
= | 자동 들여쓰기 (Visual 선택 후 또는 ==으로 현재 줄) |
== | 현재 줄 자동 들여쓰기 |
gg=G | 파일 전체 자동 들여쓰기 |
5. Visual Mode
5.1 Visual Mode 종류
| 키 | 모드 | 설명 |
|---|---|---|
v | Visual (문자) | 문자 단위 선택 |
V | Visual Line | 줄 단위 선택 |
<C-v> | Visual Block | 열(column) 단위 블록 선택 |
gv | — | 이전 Visual 선택 영역 재선택 |
5.2 Visual Mode에서 사용 가능한 조작
| 키 | 동작 |
|---|---|
d / x | 선택 영역 삭제 |
y | 선택 영역 복사 |
c | 선택 영역 삭제 후 Insert Mode 진입 |
> / < | 선택 영역 들여쓰기 / 내어쓰기 |
= | 선택 영역 자동 들여쓰기 |
~ | 선택 영역 대소문자 토글 |
u | 선택 영역 소문자 변환 |
U | 선택 영역 대문자 변환 |
: | 선택 영역에 명령 적용 (:'<,'>) |
o | 선택 영역의 반대 끝으로 커서 이동 |
5.3 Visual Block 실전 예제
Visual Block(<C-v>)은 여러 줄에 동시에 텍스트를 삽입하거나 삭제할 때 매우 유용하다.
예시: 여러 줄 앞에 // 주석 추가하기
1. <C-v>로 Visual Block 진입
2. j를 눌러 원하는 줄 수만큼 선택
3. I 를 눌러 블록 Insert Mode 진입
4. // 입력
5. <Esc> 를 누르면 모든 선택된 줄에 // 가 삽입됨
예시: 여러 줄의 특정 컬럼 내용 삭제
1. <C-v>로 Visual Block 진입
2. 원하는 범위 선택 (hjkl로 열 범위 조정 가능)
3. d로 삭제
6. 텍스트 객체 (Text Objects)
텍스트 객체는 Vim 편집의 핵심 개념이다. {operator}{a|i}{object} 구조로 "동사 + 전치사 + 명사" 형태의 명령을 구성한다.
a(around): 객체와 주변 공백/구분자 포함i(inner): 객체 내부만 선택
6.1 텍스트 객체 목록
| 객체 | i (inner) | a (around) |
|---|---|---|
w | 단어 내부 | 단어 + 주변 공백 |
W | WORD 내부 | WORD + 주변 공백 |
s | 문장 내부 | 문장 + 뒤 공백 |
p | 단락 내부 | 단락 + 앞뒤 빈 줄 |
" | "..." 안쪽 내용 | "..." 전체 |
' | '...' 안쪽 내용 | '...' 전체 |
` | `...` 안쪽 내용 | `...` 전체 |
( / ) | (...) 안쪽 | (...) 전체 |
[ / ] | [...] 안쪽 | [...] 전체 |
{ / } | {...} 안쪽 | {...} 전체 |
< / > | <...> 안쪽 | <...> 전체 |
t | XML/HTML 태그 내부 | 태그 포함 전체 |
6.2 텍스트 객체 + Operator 조합 예제
| 명령 | 동작 | 예시 상황 |
|---|---|---|
diw | 커서 아래 단어 삭제 | hello 위에서 → 단어 삭제 |
daw | 커서 아래 단어 + 공백 삭제 | 문장 중 단어 완전 제거 |
ci" | "..." 안 내용 변경 | "old" → 따옴표 유지하고 내용 교체 |
ca" | "..." 전체 변경 | "old" → 따옴표까지 교체 |
di( | (...) 안 내용 삭제 | 함수 인자 전체 삭제 |
da( | (...) 전체 삭제 | 괄호 포함 삭제 |
yip | 현재 단락 복사 | 단락 전체 복사 |
dap | 현재 단락 삭제 | 단락 전체 삭제 |
vit | HTML 태그 내부 Visual 선택 | <div>content</div>에서 content 선택 |
cit | HTML 태그 내부 변경 | 태그 내용 교체 |
=i{ | 중괄호 안 자동 들여쓰기 | 함수 바디 전체 정렬 |
>i{ | 중괄호 안 들여쓰기 추가 |
7. 명령 모드 (Command-line Mode)
7.1 파일 조작
| 명령 | 동작 |
|---|---|
:w | 저장 |
:w filename | 다른 이름으로 저장 |
:q | 종료 (변경 없을 때) |
:q! | 변경 사항 무시하고 강제 종료 |
:wq | 저장 후 종료 |
:wq! | 강제 저장 후 종료 |
:x | 변경 사항이 있을 때만 저장 후 종료 (ZZ와 동일) |
ZZ | :x와 동일 |
ZQ | :q!와 동일 |
:e filename | 파일 열기 |
:e! | 현재 파일 변경 사항 버리고 재로드 |
:r filename | 파일 내용을 현재 위치에 삽입 |
:r !command | 명령 실행 결과를 현재 위치에 삽입 |
7.2 검색 및 치환
| 명령 | 동작 |
|---|---|
:%s/old/new/g | 파일 전체에서 old를 new로 모두 치환 |
:%s/old/new/gc | 전체 치환, 각 항목마다 확인 |
:%s/old/new/gi | 대소문자 무시하고 전체 치환 |
:5,20s/old/new/g | 5~20번 줄에서 치환 |
:'<,'>s/old/new/g | Visual 선택 영역에서 치환 |
:%s/\s\+$//e | 줄 끝 공백 제거 |
:%s/^/ / | 모든 줄 앞에 공백 4개 추가 |
7.3 외부 명령 실행
| 명령 | 동작 |
|---|---|
:!command | 외부 명령 실행 (예: :!ls -la) |
:!python % | 현재 파일을 Python으로 실행 |
:%!command | 파일 전체를 command의 입력으로 넘기고 출력으로 교체 |
:.!command | 현재 줄을 command의 입력으로 넘기고 출력으로 교체 |
:shell | 임시로 쉘로 나가기 (exit으로 복귀) |
7.4 범위 지정
| 범위 표현 | 의미 |
|---|---|
:5 | 5번 줄 |
:5,10 | 5번에서 10번 줄 |
:% | 파일 전체 (1,$와 동일) |
:. | 현재 줄 |
:.,$ | 현재 줄부터 파일 끝 |
:'<,'> | Visual 선택 영역 |
:.,+5 | 현재 줄부터 5줄 |
8. 버퍼, 윈도우, 탭
8.1 버퍼 관리
**버퍼(Buffer)**는 메모리에 열려 있는 파일이다. 여러 파일을 동시에 열어 편집할 수 있다.
| 명령 | 동작 |
|---|---|
:ls / :buffers | 열려 있는 버퍼 목록 표시 |
:b2 | 2번 버퍼로 전환 |
:bn | 다음 버퍼로 전환 |
:bp | 이전 버퍼로 전환 |
:bd | 현재 버퍼 닫기 |
:ba | 모든 버퍼를 분할 창으로 열기 |
8.2 창 분할
| 명령 | 동작 |
|---|---|
:sp / :split | 수평 분할 (horizontal split) |
:vsp / :vsplit | 수직 분할 (vertical split) |
:sp filename | 파일을 새 수평 분할 창에서 열기 |
:vsp filename | 파일을 새 수직 분할 창에서 열기 |
<C-w>s | 수평 분할 (Normal Mode) |
<C-w>v | 수직 분할 (Normal Mode) |
<C-w>w | 다음 창으로 포커스 이동 |
<C-w>h/j/k/l | 방향으로 창 이동 |
<C-w>H/J/K/L | 창을 해당 방향으로 이동 |
<C-w>= | 모든 창 크기 균등 분배 |
<C-w>+ / <C-w>- | 수평 크기 조정 |
Ctrl-w > / Ctrl-w < | 수직 크기 조정 |
Ctrl-w _ | 현재 창 수직 최대화 |
Ctrl-w | | 현재 창 수평 최대화 |
<C-w>q | 현재 창 닫기 |
<C-w>o | 다른 모든 창 닫기 (only) |
8.3 탭 관리
| 명령 | 동작 |
|---|---|
:tabnew | 새 탭 열기 |
:tabnew filename | 파일을 새 탭에서 열기 |
gt | 다음 탭으로 이동 |
gT | 이전 탭으로 이동 |
2gt | 2번 탭으로 이동 |
:tabclose | 현재 탭 닫기 |
:tabonly | 다른 모든 탭 닫기 |
:tabs | 탭 목록 표시 |
9. 매크로와 레지스터
9.1 매크로 (Macro)
매크로는 일련의 키 입력을 기록하여 반복 실행하는 기능이다.
| 키 | 동작 |
|---|---|
q{a-z} | 레지스터 a~z에 매크로 기록 시작 |
q | 매크로 기록 종료 |
@{a-z} | 레지스터의 매크로 실행 |
@@ | 마지막 실행한 매크로 재실행 |
10@a | 레지스터 a의 매크로를 10회 반복 실행 |
매크로 실전 예제: CSV 각 줄의 첫 번째 필드에 따옴표 추가
원본: hello,world
목표: "hello",world
1. q a (레지스터 a에 기록 시작)
2. 0 (줄 시작으로 이동)
3. i"<Esc> (줄 앞에 " 삽입)
4. f, (첫 번째 , 앞으로 이동)
5. i"<Esc> (, 앞에 " 삽입)
6. j (다음 줄로 이동)
7. q (기록 종료)
8. 99@a (나머지 줄에 반복 적용)
9.2 레지스터 종류
| 레지스터 | 설명 |
|---|---|
" (unnamed) | 기본 레지스터. 삭제/복사 시 자동 사용 |
0 | 마지막 yank(복사) 내용 |
1~9 | 최근 삭제/변경 내용 (순환) |
a~z | 사용자 지정 레지스터 |
A~Z | 소문자 레지스터에 추가(append) |
+ | 시스템 클립보드 |
* | Primary selection (Linux X11) |
_ | Black hole 레지스터 (삭제해도 레지스터 오염 없음) |
% | 현재 파일명 |
: | 마지막 실행한 명령 |
/ | 마지막 검색 패턴 |
레지스터 사용 예시:
"+yy " 현재 줄을 시스템 클립보드에 복사
"+p " 시스템 클립보드 내용 붙여넣기
"_dd " 줄을 삭제하되 레지스터를 오염시키지 않음
"ayy " 레지스터 a에 현재 줄 복사
"Ayy " 레지스터 a에 현재 줄을 추가(append)
:reg " 모든 레지스터 내용 확인
:reg a " 레지스터 a 내용 확인
10. .vimrc 필수 설정
10.1 기본 설정 코드블록
" ===================================================
" .vimrc 기본 필수 설정
" ===================================================
" 기본 편의 설정
set nocompatible " Vim 모드 (Vi 호환 모드 비활성화)
set encoding=utf-8 " 인코딩
set fileencoding=utf-8
set number " 줄 번호 표시
set relativenumber " 상대 줄 번호 (현재 줄 기준)
set cursorline " 현재 줄 강조
set showmatch " 매칭 괄호 강조
set nowrap " 줄 바꿈 비활성화
set scrolloff=8 " 화면 스크롤 시 여백 유지
set signcolumn=yes " 사인 컬럼 항상 표시
" 검색 설정
set hlsearch " 검색 결과 강조
set incsearch " 실시간 검색
set ignorecase " 대소문자 무시
set smartcase " 대문자 포함 시 case sensitive
" 탭/들여쓰기 설정
set tabstop=4 " 탭 = 4칸
set shiftwidth=4 " 들여쓰기 = 4칸
set softtabstop=4
set expandtab " 탭을 스페이스로 변환
set autoindent " 자동 들여쓰기
set smartindent " 스마트 들여쓰기
" 성능/UX 설정
set lazyredraw " 매크로 실행 중 화면 갱신 최소화
set updatetime=250 " Swap 파일 갱신 간격 (ms)
set timeoutlen=300 " 키 입력 대기 시간 (ms)
set hidden " 버퍼 숨기기 허용 (저장 안 해도 전환 가능)
set history=1000 " 명령 히스토리 1000개
set undolevels=1000 " Undo 최대 횟수
" 파일 타입 및 구문 강조
filetype plugin indent on " 파일 타입별 플러그인/들여쓰기 활성화
syntax on " 구문 강조 활성화
set background=dark " 어두운 배경
" 클립보드
set clipboard=unnamedplus " 시스템 클립보드 사용 (Linux)
" set clipboard=unnamed " macOS
" 백업 파일 비활성화
set nobackup
set nowritebackup
set noswapfile
" 상태바
set laststatus=2 " 상태바 항상 표시
set ruler " 커서 위치 표시
set showcmd " 입력 중인 명령 표시
" 마우스 지원 (선택 사항)
set mouse=a
10.2 유용한 키 매핑
" ===================================================
" Key Mappings
" ===================================================
let mapleader = " " " Leader 키를 스페이스바로 설정
" 일반 편의 매핑
nnoremap <Leader>w :w<CR> " <Space>w 로 저장
nnoremap <Leader>q :q<CR> " <Space>q 로 종료
nnoremap <Leader>wq :wq<CR> " <Space>wq 로 저장+종료
nnoremap <Leader>ev :e ~/.vimrc<CR> " vimrc 빠른 편집
" 검색 결과 강조 해제
nnoremap <Leader>/ :nohlsearch<CR>
" 창 이동 (Ctrl + hjkl)
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
" 줄 이동 (Alt + j/k)
nnoremap <A-j> :m .+1<CR>==
nnoremap <A-k> :m .-2<CR>==
vnoremap <A-j> :m '>+1<CR>gv=gv
vnoremap <A-k> :m '<-2<CR>gv=gv
" 들여쓰기 후 Visual 유지
vnoremap < <gv
vnoremap > >gv
" 터미널 모드 탈출
tnoremap <Esc> <C-\><C-n>
" Y를 D, C처럼 동작하게 (커서부터 줄 끝까지 복사)
nnoremap Y y$
" 중앙 정렬 유지하며 검색
nnoremap n nzzzv
nnoremap N Nzzzv
" 붙여넣기 후 레지스터 유지
xnoremap <Leader>p "_dP
" 버퍼 이동
nnoremap <Leader>bn :bnext<CR>
nnoremap <Leader>bp :bprevious<CR>
nnoremap <Leader>bd :bdelete<CR>
11. 플러그인 생태계
11.1 vim-plug 설치
# Vim
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
# Neovim
curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
11.2 .vimrc 플러그인 설정 예시
call plug#begin('~/.vim/plugged')
Plug 'preservim/nerdtree' " 파일 트리
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim' " 퍼지 파인더
Plug 'neoclide/coc.nvim', {'branch': 'release'} " LSP
Plug 'vim-airline/vim-airline' " 상태바
Plug 'vim-airline/vim-airline-themes'
Plug 'tpope/vim-fugitive' " Git 통합
Plug 'tpope/vim-surround' " 괄호/따옴표 조작
Plug 'tpope/vim-commentary' " 주석 처리
Plug 'airblade/vim-gitgutter' " Git diff 표시
Plug 'morhetz/gruvbox' " 컬러 테마
call plug#end()
11.3 주요 플러그인 소개
| 플러그인 | 기능 | 핵심 명령 |
|---|---|---|
| NERDTree | 파일 트리 탐색기 | :NERDTreeToggle (<C-n>) |
| fzf.vim | 퍼지 파일/내용 검색 | :Files, :Rg, :Buffers |
| coc.nvim | LSP, 자동완성, 진단 | gd (정의 이동), K (문서) |
| vim-surround | 괄호/따옴표 감싸기/변경 | cs"', ds", ysiw" |
| vim-commentary | 주석 토글 | gcc (줄), gc (Visual) |
| vim-fugitive | Git 통합 | :G, :Gblame, :Gdiff |
| vim-gitgutter | 변경 사항 gutter 표시 | ]c / [c (hunk 이동) |
| vim-airline | 강화된 상태바 | 자동 활성화 |
| gruvbox | 레트로 컬러 테마 | colorscheme gruvbox |
11.4 vim-surround 사용법
cs"' → "Hello" 를 'Hello'로 변경 (change surrounding)
cs({ → (Hello) 를 { Hello }로 변경
ds" → "Hello" 의 따옴표 제거 (delete surrounding)
ysiw" → 커서 아래 단어에 "" 추가 (you surround inner word)
yss) → 현재 줄 전체를 ()로 감싸기
S" → Visual 선택 영역을 ""로 감싸기
11.5 Neovim 전환 이유
Neovim은 Vim과 호환되면서도 다음 장점을 제공한다.
| 기능 | Vim | Neovim |
|---|---|---|
| 설정 언어 | Vimscript | Vimscript + Lua |
| 내장 LSP | 없음 (플러그인 필요) | 내장 지원 |
| 비동기 API | 제한적 | 완전한 비동기 |
| Treesitter | 없음 | 내장 지원 |
| 설정 파일 | ~/.vimrc | ~/.config/nvim/init.lua |
| 추천 배포판 | — | LazyVim, AstroNvim, NvChad |
# Neovim 설치
brew install neovim # macOS
sudo apt install neovim # Ubuntu
sudo dnf install neovim # Fedora/RHEL
# LazyVim (권장 배포판) 설치
git clone https://github.com/LazyVim/starter ~/.config/nvim
12. 치트시트 종합 테이블
12.1 최우선 기억 명령어
| 카테고리 | 명령 | 설명 |
|---|---|---|
| 탈출 | <Esc> | Normal Mode로 복귀 |
| 저장/종료 | :wq | 저장 후 종료 |
| 강제 종료 | :q! | 변경 무시 종료 |
| 이동 | gg / G | 파일 시작 / 끝 |
| 이동 | /pattern | 검색 |
| 이동 | n / N | 다음/이전 검색 |
| 편집 | dd | 줄 삭제 |
| 편집 | yy | 줄 복사 |
| 편집 | p | 붙여넣기 |
| 편집 | u | Undo |
| 편집 | <C-r> | Redo |
| 편집 | ciw | 단어 변경 |
| 모드 | v / V / <C-v> | Visual 모드 |
| 창 | <C-w>s / <C-w>v | 분할 |
| 치환 | :%s/old/new/g | 전체 치환 |
12.2 Operator + Motion 조합 공식
{횟수}{operator}{motion 또는 text object}
예시:
3dd → 3줄 삭제
2yy → 2줄 복사
d3w → 단어 3개 삭제
ci" → 따옴표 안 내용 변경
da( → 괄호 포함 삭제
>ip → 단락 들여쓰기
12.3 Insert Mode 단축키
| 키 | 동작 |
|---|---|
<C-w> | 이전 단어 삭제 |
<C-u> | 줄 시작까지 삭제 |
<C-h> | 한 글자 삭제 (Backspace) |
<C-t> | 들여쓰기 추가 |
<C-d> | 들여쓰기 제거 |
<C-r>{reg} | 레지스터 내용 삽입 |
<C-r>= | 수식 결과 삽입 (예: <C-r>=2+2<CR> → 4) |
<C-o>{cmd} | Normal Mode 명령 한 번 실행 후 Insert Mode 복귀 |
12.4 Command Mode 필수 패턴
| 명령 | 설명 |
|---|---|
:%s/\n/,/g | 줄바꿈을 쉼표로 치환 |
:%s/^\s*$\n//g | 빈 줄 제거 |
:%s/\s\+$//e | 줄 끝 공백 제거 |
:%!sort | 파일 전체 정렬 |
:%!sort -u | 파일 전체 정렬 후 중복 제거 |
:g/pattern/d | pattern이 있는 줄 삭제 |
:v/pattern/d | pattern이 없는 줄 삭제 (inverse) |
:g/pattern/y A | pattern이 있는 모든 줄을 레지스터 A에 복사 |
13. Reference
- Vim 공식 문서:
:help(Vim 안에서 직접 실행) - vimtutor: 터미널에서
vimtutor명령으로 대화형 튜토리얼 시작 - Vim Adventures: https://vim-adventures.com — 게임으로 배우는 Vim
- Neovim 공식 사이트: https://neovim.io
- LazyVim 배포판: https://www.lazyvim.org
- vim-plug: https://github.com/junegunn/vim-plug
- fzf.vim: https://github.com/junegunn/fzf.vim
- coc.nvim: https://github.com/neoclide/coc.nvim
- vim-surround: https://github.com/tpope/vim-surround
- vim-fugitive: https://github.com/tpope/vim-fugitive
이 포스트에서 다룬 명령어들은
:help {command}로 Vim 안에서 언제든 상세 문서를 확인할 수 있다. 예::help text-objects,:help registers,:help macros
The Complete Vim Command Guide: Master Every Command of the Ultimate Text Editor
- 1. Introduction to Vim
- 2. Mode Concepts
- 3. Navigation Commands
- 4. Editing Commands
- 5. Visual Mode
- 6. Text Objects
- 7. Command-line Mode
- 8. Buffers, Windows, and Tabs
- 9. Macros and Registers
- 10. Essential .vimrc Settings
- 11. Plugin Ecosystem
- 12. Comprehensive Cheat Sheet
- 13. Reference
- Quiz
1. Introduction to Vim
1.1 History: Vi to Vim to Neovim
Vi is a text editor written by Bill Joy for BSD Unix in 1976. It was a groundbreaking tool that enabled efficient editing using only the keyboard in terminal environments. Vi's core idea of Modal Editing lives on to this day.
Vim (Vi IMproved) is a greatly enhanced version of Vi released by Bram Moolenaar in 1991. Hundreds of features were added including syntax highlighting, a plugin system, multiple windows, macros, and regex substitution. Vim became the standard editor used daily by developers and system administrators worldwide, as it comes pre-installed on GNU/Linux servers.
Neovim is a refactored fork of Vim that began in 2014. It offers Lua-based configuration, a built-in LSP (Language Server Protocol), and an asynchronous plugin API, aiming to deliver a VS Code-level IDE experience within the terminal.
| Editor | Released | Key Features |
|---|---|---|
| Vi | 1976 | Pioneer of modal editing, lightweight |
| Vim | 1991 | Plugins, syntax highlighting, macros |
| Neovim | 2014 | Lua API, built-in LSP, async support |
1.2 Why Learn Vim
- Available everywhere: Remote servers via SSH, Docker containers, embedded devices — Vi/Vim is installed on virtually every Unix environment.
- Your hands never leave the keyboard: All operations are possible without a mouse, dramatically improving editing speed.
- Powerful composable language: Complex operations can be expressed concisely with a verb+count+noun structure, such as
d3w(delete 3 words) orci"(change contents inside quotes). - Macros and automation: Record repetitive tasks as macros and transform thousands of lines in an instant.
- Universal Vim keybindings: Dozens of tools support Vim keybindings including VS Code, IntelliJ, Obsidian, Jupyter, bash readline, and tmux copy mode. Learning Vim makes every tool faster.
2. Mode Concepts
The most important feature of Vim is modal editing. The behavior when you press a key changes completely depending on the current mode.
2.1 Major Modes and Transitions
| Mode | Description | How to Enter | How to Exit |
|---|---|---|---|
| Normal | Navigation, commands | <Esc>, <C-c> | — (default mode) |
| Insert | Text input | i, a, o, I, A, O, s, c | <Esc>, <C-c> |
| Visual | Character-wise selection | v | <Esc>, v |
| Visual Line | Line-wise selection | V | <Esc>, V |
| Visual Block | Block (column) selection | <C-v> | <Esc>, <C-v> |
| Command-line | : command input | :, /, ?, ! | <Esc>, <CR> |
| Replace | Overwrite characters | R | <Esc> |
2.2 Mode Transition Diagram
┌─────────────────────────────────────────┐
│ Normal Mode │
│ (Default at startup / return via <Esc>) │
└────┬───────┬───────┬────────────────────┘
│ │ │
i,a,o│ v,V│ :,/,?│
│ │ │
┌────▼──┐ ┌──▼────┐ ┌▼────────────┐
│Insert │ │Visual │ │Command-line │
│ Mode │ │ Mode │ │ Mode │
└───────┘ └───────┘ └─────────────┘
Rule: Pressing
<Esc>at any time returns you to Normal Mode. Pressing<Esc>twice when you are lost is Vim survival rule number 1.
3. Navigation Commands
3.1 Basic Movement (hjkl)
| Key | Action |
|---|---|
h | Move left one character |
j | Move down one line |
k | Move up one line |
l | Move right one character |
5j | Move down 5 lines (numeric prefix) |
10k | Move up 10 lines |
3.2 Word-Level Movement
| Key | Action |
|---|---|
w | Move to start of next word (punctuation delimited) |
W | Move to start of next WORD (whitespace delimited) |
b | Move to start of previous word |
B | Move to start of previous WORD |
e | Move to end of current/next word |
E | Move to end of current/next WORD |
ge | Move to end of previous word |
Lowercase (
w,b,e) treats punctuation as word boundaries, while uppercase (W,B,E) only treats whitespace as boundaries. Inhello_world,wrequires 2 presses whileWrequires 1.
3.3 Line-Level Movement
| Key | Action |
|---|---|
0 | Move to beginning of line (column 0) |
^ | Move to first non-whitespace character of line |
$ | Move to end of line |
g_ | Move to last non-whitespace character of line |
gg | Move to first line of file |
G | Move to last line of file |
42G | Move to line 42 |
:42 | Move to line 42 (command mode) |
% | Jump to matching parenthesis/brace/bracket |
3.4 Screen Scrolling
| Key | Action |
|---|---|
<C-u> | Scroll half screen up |
<C-d> | Scroll half screen down |
<C-f> | Scroll full screen down (Page Down) |
<C-b> | Scroll full screen up (Page Up) |
H | Move cursor to top of screen (High) |
M | Move cursor to middle of screen (Middle) |
L | Move cursor to bottom of screen (Low) |
zz | Center current line on screen |
zt | Align current line to top of screen |
zb | Align current line to bottom of screen |
3.5 Search Movement
| Key | Action |
|---|---|
/pattern | Search forward for pattern |
?pattern | Search backward for pattern |
n | Next match in same direction |
N | Next match in opposite direction |
* | Search forward for word under cursor |
# | Search backward for word under cursor |
f{char} | Find char forward on current line, move to it |
F{char} | Find char backward on current line |
t{char} | Move to just before char (till) |
T{char} | Move to just after char (reverse direction) |
; | Repeat f/F/t/T in same direction |
, | Repeat f/F/t/T in opposite direction |
3.6 Jump Movement
| Key | Action |
|---|---|
<C-o> | Jump to previous cursor position (jump back) |
<C-i> | Jump to next cursor position (jump forward) |
'' | Return to last jump position (two single quotes) |
m{a-z} | Set mark a-z at current position |
'{a-z} | Jump to mark |
gd | Go to local declaration |
gD | Go to global declaration |
4. Editing Commands
4.1 Entering Insert Mode
| Key | Action |
|---|---|
i | Enter Insert Mode before cursor |
I | Enter Insert Mode before first non-whitespace character |
a | Enter Insert Mode after cursor (append) |
A | Enter Insert Mode at end of line |
o | Open new line below and enter Insert Mode |
O | Open new line above and enter Insert Mode |
gi | Enter Insert Mode at last edit position |
4.2 Delete Commands
| Key | Action |
|---|---|
x | Delete character under cursor |
X | Delete character before cursor (Backspace) |
dd | Delete current line |
3dd | Delete 3 lines starting from current line |
D | Delete from cursor to end of line (same as d$) |
dw | Delete from cursor to start of next word |
de | Delete from cursor to end of word |
d0 | Delete from cursor to start of line |
dG | Delete from current line to end of file |
dgg | Delete from current line to start of file |
Deleted text is stored in a register and can be pasted with
p. Vim's delete is equivalent to "Cut."
4.3 Change Commands
| Key | Action |
|---|---|
r{char} | Replace character under cursor with char (stay in Normal Mode) |
R | Enter Replace Mode (continuous overwrite) |
s | Delete character under cursor and enter Insert Mode |
S | Delete current line contents and enter Insert Mode (same as cc) |
cw | Change from cursor to end of word |
cc | Change current line contents |
C | Change from cursor to end of line (same as c$) |
c0 | Change from cursor to start of line |
~ | Toggle case of character under cursor |
g~w | Toggle case of word |
guw | Convert word to lowercase |
gUw | Convert word to uppercase |
4.4 Copy and Paste
| Key | Action |
|---|---|
yy | Yank (copy) current line |
Y | Yank current line (same as yy) |
3yy | Yank 3 lines starting from current line |
yw | Yank from cursor to end of word |
y$ | Yank from cursor to end of line |
y0 | Yank from cursor to start of line |
p | Paste after (below) cursor |
P | Paste before (above) cursor |
gp | Same as p but moves cursor to end of pasted text |
"ayy | Yank current line to register a |
"ap | Paste contents of register a |
4.5 Undo / Redo
| Key | Action |
|---|---|
u | Undo last change |
3u | Undo last 3 changes |
<C-r> | Redo (undo the undo) |
U | Undo all changes on current line |
4.6 Indentation
| Key | Action |
|---|---|
>> | Indent current line |
<< | Outdent current line |
3>> | Indent 3 lines |
= | Auto-indent (after Visual selection or == for current line) |
== | Auto-indent current line |
gg=G | Auto-indent entire file |
5. Visual Mode
5.1 Visual Mode Types
| Key | Mode | Description |
|---|---|---|
v | Visual (char) | Character-wise selection |
V | Visual Line | Line-wise selection |
<C-v> | Visual Block | Column-wise block selection |
gv | — | Reselect previous Visual region |
5.2 Operations Available in Visual Mode
| Key | Action |
|---|---|
d / x | Delete selection |
y | Yank selection |
c | Delete selection and enter Insert Mode |
> / < | Indent / outdent selection |
= | Auto-indent selection |
~ | Toggle case of selection |
u | Convert selection to lowercase |
U | Convert selection to uppercase |
: | Apply command to selection (:'<,'>) |
o | Move cursor to opposite end of selection |
5.3 Visual Block Practical Examples
Visual Block (<C-v>) is extremely useful for inserting or deleting text across multiple lines simultaneously.
Example: Adding // comments to the beginning of multiple lines
1. Enter Visual Block with <C-v>
2. Press j to select the desired number of lines
3. Press I to enter block Insert Mode
4. Type //
5. Press <Esc> and // will be inserted on all selected lines
Example: Deleting content at a specific column across multiple lines
1. Enter Visual Block with <C-v>
2. Select the desired range (adjust column range with hjkl)
3. Press d to delete
6. Text Objects
Text objects are a core concept of Vim editing. They form commands in a "verb + preposition + noun" structure using {operator}{a|i}{object}.
a(around): Includes the object and surrounding whitespace/delimitersi(inner): Selects only the inside of the object
6.1 Text Object List
| Object | i (inner) | a (around) |
|---|---|---|
w | Inside word | Word + surrounding spaces |
W | Inside WORD | WORD + surrounding spaces |
s | Inside sentence | Sentence + trailing space |
p | Inside paragraph | Paragraph + surrounding blank lines |
" | Contents inside "..." | Entire "..." |
' | Contents inside '...' | Entire '...' |
` | Contents inside `...` | Entire `...` |
( / ) | Inside (...) | Entire (...) |
[ / ] | Inside [...] | Entire [...] |
{ / } | Inside {...} | Entire {...} |
< / > | Inside <...> | Entire <...> |
t | Inside XML/HTML tag | Entire tag including markers |
6.2 Text Object + Operator Combination Examples
| Command | Action | Example Scenario |
|---|---|---|
diw | Delete word under cursor | On hello - deletes the word |
daw | Delete word + surrounding spaces | Completely remove a word from a sentence |
ci" | Change contents inside "..." | "old" - replace content keeping quotes |
ca" | Change entire "..." | "old" - replace including quotes |
di( | Delete contents inside (...) | Delete all function arguments |
da( | Delete entire (...) | Delete including parentheses |
yip | Yank current paragraph | Copy entire paragraph |
dap | Delete current paragraph | Delete entire paragraph |
vit | Visual select inside HTML tag | Select content in <div>content</div> |
cit | Change inside HTML tag | Replace tag content |
=i{ | Auto-indent inside curly braces | Align entire function body |
>i{ | Add indent inside curly braces |
7. Command-line Mode
7.1 File Operations
| Command | Action |
|---|---|
:w | Save |
:w filename | Save as different name |
:q | Quit (when no changes) |
:q! | Force quit ignoring changes |
:wq | Save and quit |
:wq! | Force save and quit |
:x | Save and quit only if changes exist (same as ZZ) |
ZZ | Same as :x |
ZQ | Same as :q! |
:e filename | Open file |
:e! | Discard current file changes and reload |
:r filename | Insert file contents at current position |
:r !command | Insert command output at current position |
7.2 Search and Replace
| Command | Action |
|---|---|
:%s/old/new/g | Replace all old with new in entire file |
:%s/old/new/gc | Replace all with confirmation for each |
:%s/old/new/gi | Replace all ignoring case |
:5,20s/old/new/g | Replace in lines 5-20 |
:'<,'>s/old/new/g | Replace in Visual selection |
:%s/\s\+$//e | Remove trailing whitespace |
:%s/^/ / | Add 4 spaces to beginning of all lines |
7.3 Running External Commands
| Command | Action |
|---|---|
:!command | Run external command (e.g., :!ls -la) |
:!python % | Run current file with Python |
:%!command | Pipe entire file through command and replace with output |
:.!command | Pipe current line through command and replace with output |
:shell | Temporarily exit to shell (return with exit) |
7.4 Range Specification
| Range Expression | Meaning |
|---|---|
:5 | Line 5 |
:5,10 | Lines 5 through 10 |
:% | Entire file (same as 1,$) |
:. | Current line |
:.,$ | From current line to end of file |
:'<,'> | Visual selection |
:.,+5 | 5 lines from current line |
8. Buffers, Windows, and Tabs
8.1 Buffer Management
A buffer is a file loaded into memory. You can open and edit multiple files simultaneously.
| Command | Action |
|---|---|
:ls / :buffers | List open buffers |
:b2 | Switch to buffer 2 |
:bn | Switch to next buffer |
:bp | Switch to previous buffer |
:bd | Close current buffer |
:ba | Open all buffers in split windows |
8.2 Window Splitting
| Command | Action |
|---|---|
:sp / :split | Horizontal split |
:vsp / :vsplit | Vertical split |
:sp filename | Open file in new horizontal split |
:vsp filename | Open file in new vertical split |
<C-w>s | Horizontal split (Normal Mode) |
<C-w>v | Vertical split (Normal Mode) |
<C-w>w | Move focus to next window |
<C-w>h/j/k/l | Move to window in direction |
<C-w>H/J/K/L | Move window to that direction |
<C-w>= | Equalize all window sizes |
<C-w>+ / <C-w>- | Adjust horizontal size |
Ctrl-w > / Ctrl-w < | Adjust vertical size |
Ctrl-w _ | Maximize current window vertically |
Ctrl-w | | Maximize current window horizontally |
<C-w>q | Close current window |
<C-w>o | Close all other windows (only) |
8.3 Tab Management
| Command | Action |
|---|---|
:tabnew | Open new tab |
:tabnew filename | Open file in new tab |
gt | Move to next tab |
gT | Move to previous tab |
2gt | Move to tab 2 |
:tabclose | Close current tab |
:tabonly | Close all other tabs |
:tabs | List tabs |
9. Macros and Registers
9.1 Macros
Macros are a feature that records a sequence of keystrokes for repeated execution.
| Key | Action |
|---|---|
q{a-z} | Start recording macro to register a-z |
q | Stop recording macro |
@{a-z} | Execute macro from register |
@@ | Re-execute last executed macro |
10@a | Execute macro in register a 10 times |
Practical Macro Example: Adding quotes to the first field of each CSV line
Original: hello,world
Target: "hello",world
1. q a (start recording to register a)
2. 0 (move to start of line)
3. i"<Esc> (insert " at start of line)
4. f, (move to first ,)
5. i"<Esc> (insert " before ,)
6. j (move to next line)
7. q (stop recording)
8. 99@a (repeat on remaining lines)
9.2 Register Types
| Register | Description |
|---|---|
" (unnamed) | Default register. Automatically used on delete/yank |
0 | Last yank content |
1-9 | Recent delete/change content (cycled) |
a-z | User-defined registers |
A-Z | Append to lowercase register |
+ | System clipboard |
* | Primary selection (Linux X11) |
_ | Black hole register (delete without polluting registers) |
% | Current filename |
: | Last executed command |
/ | Last search pattern |
Register usage examples:
"+yy " Yank current line to system clipboard
"+p " Paste from system clipboard
"_dd " Delete line without polluting registers
"ayy " Yank current line to register a
"Ayy " Append current line to register a
:reg " View contents of all registers
:reg a " View contents of register a
10. Essential .vimrc Settings
10.1 Basic Configuration Block
" ===================================================
" .vimrc Essential Settings
" ===================================================
" Basic convenience settings
set nocompatible " Vim mode (disable Vi compatibility)
set encoding=utf-8 " Encoding
set fileencoding=utf-8
set number " Show line numbers
set relativenumber " Relative line numbers (based on current line)
set cursorline " Highlight current line
set showmatch " Highlight matching brackets
set nowrap " Disable line wrapping
set scrolloff=8 " Maintain margin when scrolling
set signcolumn=yes " Always show sign column
" Search settings
set hlsearch " Highlight search results
set incsearch " Incremental search
set ignorecase " Case insensitive
set smartcase " Case sensitive when uppercase included
" Tab/indentation settings
set tabstop=4 " Tab = 4 spaces
set shiftwidth=4 " Indent = 4 spaces
set softtabstop=4
set expandtab " Convert tabs to spaces
set autoindent " Auto indent
set smartindent " Smart indent
" Performance/UX settings
set lazyredraw " Minimize screen updates during macro execution
set updatetime=250 " Swap file update interval (ms)
set timeoutlen=300 " Key input timeout (ms)
set hidden " Allow hidden buffers (switch without saving)
set history=1000 " Command history size 1000
set undolevels=1000 " Maximum undo count
" File type and syntax highlighting
filetype plugin indent on " Enable filetype plugins/indentation
syntax on " Enable syntax highlighting
set background=dark " Dark background
" Clipboard
set clipboard=unnamedplus " Use system clipboard (Linux)
" set clipboard=unnamed " macOS
" Disable backup files
set nobackup
set nowritebackup
set noswapfile
" Status bar
set laststatus=2 " Always show status bar
set ruler " Show cursor position
set showcmd " Show command being typed
" Mouse support (optional)
set mouse=a
10.2 Useful Key Mappings
" ===================================================
" Key Mappings
" ===================================================
let mapleader = " " " Set Leader key to spacebar
" General convenience mappings
nnoremap <Leader>w :w<CR> " <Space>w to save
nnoremap <Leader>q :q<CR> " <Space>q to quit
nnoremap <Leader>wq :wq<CR> " <Space>wq to save+quit
nnoremap <Leader>ev :e ~/.vimrc<CR> " Quick edit vimrc
" Clear search highlighting
nnoremap <Leader>/ :nohlsearch<CR>
" Window navigation (Ctrl + hjkl)
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
" Move lines (Alt + j/k)
nnoremap <A-j> :m .+1<CR>==
nnoremap <A-k> :m .-2<CR>==
vnoremap <A-j> :m '>+1<CR>gv=gv
vnoremap <A-k> :m '<-2<CR>gv=gv
" Keep Visual selection after indenting
vnoremap < <gv
vnoremap > >gv
" Exit terminal mode
tnoremap <Esc> <C-\><C-n>
" Make Y behave like D and C (yank from cursor to end of line)
nnoremap Y y$
" Keep centered while searching
nnoremap n nzzzv
nnoremap N Nzzzv
" Preserve register on paste
xnoremap <Leader>p "_dP
" Buffer navigation
nnoremap <Leader>bn :bnext<CR>
nnoremap <Leader>bp :bprevious<CR>
nnoremap <Leader>bd :bdelete<CR>
11. Plugin Ecosystem
11.1 Installing vim-plug
# Vim
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
# Neovim
curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
11.2 .vimrc Plugin Configuration Example
call plug#begin('~/.vim/plugged')
Plug 'preservim/nerdtree' " File tree
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim' " Fuzzy finder
Plug 'neoclide/coc.nvim', {'branch': 'release'} " LSP
Plug 'vim-airline/vim-airline' " Status bar
Plug 'vim-airline/vim-airline-themes'
Plug 'tpope/vim-fugitive' " Git integration
Plug 'tpope/vim-surround' " Surround manipulation
Plug 'tpope/vim-commentary' " Comment toggling
Plug 'airblade/vim-gitgutter' " Git diff display
Plug 'morhetz/gruvbox' " Color theme
call plug#end()
11.3 Key Plugin Overview
| Plugin | Function | Key Commands |
|---|---|---|
| NERDTree | File tree explorer | :NERDTreeToggle (<C-n>) |
| fzf.vim | Fuzzy file/content search | :Files, :Rg, :Buffers |
| coc.nvim | LSP, autocomplete, diagnostics | gd (go to definition), K (docs) |
| vim-surround | Surround with brackets/quotes | cs"', ds", ysiw" |
| vim-commentary | Comment toggle | gcc (line), gc (Visual) |
| vim-fugitive | Git integration | :G, :Gblame, :Gdiff |
| vim-gitgutter | Gutter change indicators | ]c / [c (hunk navigation) |
| vim-airline | Enhanced status bar | Auto-activated |
| gruvbox | Retro color theme | colorscheme gruvbox |
11.4 vim-surround Usage
cs"' → Change "Hello" to 'Hello' (change surrounding)
cs({ → Change (Hello) to { Hello }
ds" → Remove quotes from "Hello" (delete surrounding)
ysiw" → Add "" around word under cursor (you surround inner word)
yss) → Wrap entire line with ()
S" → Wrap Visual selection with ""
11.5 Why Switch to Neovim
Neovim is compatible with Vim while offering the following advantages.
| Feature | Vim | Neovim |
|---|---|---|
| Config Language | Vimscript | Vimscript + Lua |
| Built-in LSP | None (plugin required) | Built-in support |
| Async API | Limited | Full async |
| Treesitter | None | Built-in support |
| Config File | ~/.vimrc | ~/.config/nvim/init.lua |
| Recommended Distros | — | LazyVim, AstroNvim, NvChad |
# Install Neovim
brew install neovim # macOS
sudo apt install neovim # Ubuntu
sudo dnf install neovim # Fedora/RHEL
# Install LazyVim (recommended distro)
git clone https://github.com/LazyVim/starter ~/.config/nvim
12. Comprehensive Cheat Sheet
12.1 Top Priority Commands to Memorize
| Category | Command | Description |
|---|---|---|
| Escape | <Esc> | Return to Normal Mode |
| Save/Quit | :wq | Save and quit |
| Force Quit | :q! | Quit ignoring changes |
| Navigation | gg / G | File start / end |
| Navigation | /pattern | Search |
| Navigation | n / N | Next/previous match |
| Editing | dd | Delete line |
| Editing | yy | Yank line |
| Editing | p | Paste |
| Editing | u | Undo |
| Editing | <C-r> | Redo |
| Editing | ciw | Change word |
| Mode | v / V / <C-v> | Visual modes |
| Window | <C-w>s / <C-w>v | Split |
| Replace | :%s/old/new/g | Global replace |
12.2 Operator + Motion Combination Formula
{count}{operator}{motion or text object}
Examples:
3dd → Delete 3 lines
2yy → Yank 2 lines
d3w → Delete 3 words
ci" → Change contents inside quotes
da( → Delete including parentheses
>ip → Indent paragraph
12.3 Insert Mode Shortcuts
| Key | Action |
|---|---|
<C-w> | Delete previous word |
<C-u> | Delete to start of line |
<C-h> | Delete one character (Backspace) |
<C-t> | Add indent |
<C-d> | Remove indent |
<C-r>{reg} | Insert register contents |
<C-r>= | Insert expression result (e.g., <C-r>=2+2<CR> yields 4) |
<C-o>{cmd} | Execute one Normal Mode command then return to Insert Mode |
12.4 Essential Command Mode Patterns
| Command | Description |
|---|---|
:%s/\n/,/g | Replace newlines with commas |
:%s/^\s*$\n//g | Remove blank lines |
:%s/\s\+$//e | Remove trailing whitespace |
:%!sort | Sort entire file |
:%!sort -u | Sort entire file and remove duplicates |
:g/pattern/d | Delete lines containing pattern |
:v/pattern/d | Delete lines not containing pattern (inverse) |
:g/pattern/y A | Yank all lines containing pattern to register A |
13. Reference
- Vim Official Documentation:
:help(run directly inside Vim) - vimtutor: Start interactive tutorial with
vimtutorcommand in terminal - Vim Adventures: https://vim-adventures.com — Learn Vim through a game
- Neovim Official Site: https://neovim.io
- LazyVim Distribution: https://www.lazyvim.org
- vim-plug: https://github.com/junegunn/vim-plug
- fzf.vim: https://github.com/junegunn/fzf.vim
- coc.nvim: https://github.com/neoclide/coc.nvim
- vim-surround: https://github.com/tpope/vim-surround
- vim-fugitive: https://github.com/tpope/vim-fugitive
All commands covered in this post can be explored in detail within Vim using
:help {command}. For example::help text-objects,:help registers,:help macros
Quiz
Q1: What is the main topic covered in "The Complete Vim Command Guide: Master Every Command of
the Ultimate Text Editor"?
From Vim modal editing philosophy to navigation, editing, Visual Mode, text objects, command mode, macros, .vimrc configuration, and plugins — a comprehensive guide to every Vim command with practical examples.
Q2: What is Mode Concepts?
The most important feature of Vim is modal editing. The behavior when you press a key changes
completely depending on the current mode. 2.1 Major Modes and Transitions 2.2 Mode Transition
Diagram
Q3: Explain the core concept of Navigation Commands.
3.1 Basic Movement (hjkl) 3.2 Word-Level Movement 3.3 Line-Level Movement 3.4 Screen Scrolling 3.5
Search Movement 3.6 Jump Movement
Q4: What are the key aspects of Editing Commands?
4.1 Entering Insert Mode 4.2 Delete Commands 4.3 Change Commands 4.4 Copy and Paste 4.5 Undo /
Redo 4.6 Indentation
Q5: How does Visual Mode work?
5.1 Visual Mode Types 5.2 Operations Available in Visual Mode 5.3 Visual Block Practical Examples
Visual Block (Ctrl+V) is extremely useful for inserting or deleting text across multiple lines
simultaneously.