본문으로 건너뛰기

VI

VI Cheat Sheet

이동

character : 한글자, 한칸
word : 문자,숫자,_ 로 이루어진 한 묶음
token : 공백으로 구분
line : 줄
screen : 화면
step-by-step - 3 words, 1 token

칸,단어 이동

  • h – ⬅️ 한 칸
  • j – ⬇️ 한 줄
  • k – ⬆️ 한 줄
  • l – ➡️ 한 칸
  • #l - ➡️ # 칸
  • b – ⬅️ word 시작
  • B – ⬅️ token 시작
  • w – ➡️ word 시작
  • W – ➡️ token 시작
  • e – ➡️ word 끝
  • E – ➡️ token 끝

줄 이동

  • 0 (zero) – 줄의 맨앞
  • ^ – 줄의 내용 시작
  • $ – 줄의 끝
  • #G / #gg / :# – #번째 줄

화면 이동

  • Ctrl + b – ⬆️ 한 화면
  • Ctrl + f – ⬇️ 한 화면
  • Ctrl + d – ⬇️ 1/2 화면
  • Ctrl + u – ⬆️ 1/2 화면
  • Ctrl + e – ⬇️ 한 줄(커서 고정)
  • Ctrl + y – ⬆️ 한 줄(커서 고정)
  • Ctrl + o – ⬆️ move backward through the jump history
  • Ctrl + i – ⬇️ move forward through the jump history
  • H – move to the top of the screen (H=high)
  • M – move to the middle of the screen (M=middle)
  • L – move to the bottom of the screen (L=low)

입력 모드

커서앞 : | 커서 위치
커서뒤 : | 커서 다음 위치

  • i – ⬅️ 커서앞에서 입력
  • I – ⬅️ 줄 맨앞에서 입력
  • a – ➡️ 커서뒤에서 입력
  • A – ➡️ 줄 끝에서 입력
  • o – ⬇️ 아래 줄 추가하고 입력
  • O – ⬆️ 윗 줄 추가하고 입력
  • ea – ➡️ 단어(word) 다음에 입력
  • Esc – 명령 모드(command mode)로

편집

  • r – 입력하는 글자로 바꾸기
  • cc – 줄 전체 지우고 입력
  • C / c$ – 줄에서 커서부터(|~) 지우고 입력
  • cw – 단어(word)에서 커서부터(|~) 지우고 입력
  • s – 한 글자 지우고 입력
  • J – 현재 줄 + [공백] + 아랫 줄
  • gJ – 현재 줄 + 아랫 줄
  • u – 취소(undo)
  • Ctrl + r – 취소 되돌리기(redo)
  • . – 마지막 명령 재실행

잘라내기, 복사하기, 붙여넣기

  • yy – 현재 줄 전체 복사하기
  • #yy – #줄 복사하기
  • dd – 현재 줄 전체 잘라내기
  • #dd – #줄 잘라내기
  • p – 커서뒤에 붙여넣기, 줄은 아래에 ⬇️
  • P – 커서앞에 붙여넣기, 줄은 위에 ⬆️

블럭 선택 (Visual Mode)

  • v – 블럭 선택 시작
  • V – 줄블럭 선택 시작
  • Ctrl+v – select text using block mode

  • o – 블럭의 시작,끝 이동
  • aw – 단어(word) 선택
  • ab() 블럭 선택
  • aB{} 블럭 선택
  • at<> 블럭 선택
  • ib() 블럭 안 선택
  • iB{} 블럭 안 선택
  • it<> 블럭 안 선택

블럭 편집 (Visual Mode)

  • y – 블럭 복사하기(yank, copy)
  • d – 블럭 잘라내기(delete, cut)
  • p – 블럭 붙여넣기(커서뒤)
  • P – 블럭 붙여넣기(커서앞)
  • u – 블럭 소문자로 바꾸기
  • U – 블럭 대문자로 바꾸기

찾기

  • * – 현재 단어(word)랑 같은 다음 단어 찾기
  • # – 현재 단어(word)랑 같은 이전 단어 찾기
  • /pattern[pattern] 뒤로 찾기
  • ?pattern[pattern] 앞으로 찾기
  • n – 같은 방향으로 찾기 반복
  • N – 반대 방향으로 찾기 반복

파일

  • :w – 파일 저장
  • :wq / :x / ZZ – 파일 저장하고 닫기
  • :q – 닫기
  • :q!/ ZQ – 파일 저장 안하고 닫기
  • :w new_file_name – 새이름으로 저장하고 기존파일 편집
  • :sav – 새이름으로 저장하고 새파일 편집
  • :w !sudo tee % – write out the file using sudo and tee command

버퍼로 여러 파일 다루기

  • :e file_name – 새 버퍼에 파일 열기
  • :bn – 다음 버퍼로 이동
  • :bp – 이전 버퍼로 이동
  • :bd – 버퍼 닫기
  • :b# – #버퍼로 이동
  • :b file_name – file_name 버퍼로 이동
  • :ls – 열린 버러 리스트

뷰포트 Viewport

  • :sp file_name – 화면 가로로 뷰포트 나누고, 새 버퍼에 파일 열기
  • :vs file_name – 화면 세로로 뷰포트 나누고, 새 버퍼에 파일 열기
  • :vert ba – 화면 세로로 뷰포트 나눠서 모든 버퍼 열기
  • Ctrl+ws – 화면 가로로 뷰포트 나누기
  • Ctrl+wv – 화면 세로로 뷰포트 나누기
  • Ctrl+ww – 뷰포트 이동
  • Ctrl+wq – 뷰포트 닫기
  • Ctrl+wx – 현재 뷰포트와 다음 뷰포트 버퍼 바꾸기
  • Ctrl+= – make all viewports equal in height and width

탭 Tab

  • :tab ba – 탭으로 모든 버퍼 열기
  • gt – 다음 탭으로 이동
  • gT – 이전 탭으로 이동

Marks and Jumps

  • m[a-z] – mark text using character mode (from a to z)
  • M[a-z] – mark lines using line mode (from a to z)
  • `a - jump to position marked a
  • `y`a – yank text to position marked >a>
  • `. – jump to last change in file
  • `0 – jump to position where Vim was last exited
  • `` – jump to last jump
  • :marks – list all marks
  • :jumps – list all jumps
  • :changes – list all changes
  • Ctrl+i – move to next instance in jump list
  • Ctrl+o – move to previous instance in jump list
  • g, – move to next instance in change list
  • g; – move to previous instance in change list

Macros

  • qa – record macro a
  • q – stop recording macro
  • @a – run macro a
  • @@ – run last macro again

Enabling Vim Color Schemes

  • :colorscheme [colorscheme_name] – scheme 바꾸기
  • :colorscheme [space]+Ctrl+d – scheme 목록 보기

[🚀]https://phoenixnap.com/kb/vim-commands-cheat-sheet Download

colorscheme

.vimrc

.vimrc : basic.vim + line number, cursor shape, cursor line + colorscheme jellybeans
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Maintainer:
" Amir Salihefendic — @amix3k
"
" Awesome_version:
" Get this config, nice color schemes and lots of plugins!
"
" Install the awesome version from:
"
" https://github.com/amix/vimrc
"
" Sections:
" -> General
" -> VIM user interface
" -> Colors and Fonts
" -> Files and backups
" -> Text, tab and indent related
" -> Visual mode related
" -> Moving around, tabs and buffers
" -> Status line
" -> Editing mappings
" -> vimgrep searching and cope displaying
" -> Spell checking
" -> Misc
" -> Helper functions
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Sets how many lines of history VIM has to remember
set history=500

" Enable filetype plugins
filetype plugin on
filetype indent on

" Set to auto read when a file is changed from the outside
set autoread
au FocusGained,BufEnter * checktime

" With a map leader it's possible to do extra key combinations
" like <leader>w saves the current file
let mapleader = ","

" Fast saving
nmap <leader>w :w!<cr>

" :W sudo saves the file
" (useful for handling the permission-denied error)
command! W execute 'w !sudo tee % > /dev/null' <bar> edit!


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM user interface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set 7 lines to the cursor - when moving vertically using j/k
set so=7

" Avoid garbled characters in Chinese language windows OS
let $LANG='en'
set langmenu=en
source $VIMRUNTIME/delmenu.vim
source $VIMRUNTIME/menu.vim

" Turn on the Wild menu
set wildmenu

" Ignore compiled files
set wildignore=*.o,*~,*.pyc
if has("win16") || has("win32")
set wildignore+=.git\*,.hg\*,.svn\*
else
set wildignore+=*/.git/*,*/.hg/*,*/.svn/*,*/.DS_Store
endif

" Always show current position
set ruler

" Height of the command bar
set cmdheight=1

" A buffer becomes hidden when it is abandoned
set hid

" Configure backspace so it acts as it should act
set backspace=eol,start,indent
set whichwrap+=<,>,h,l

" Ignore case when searching
set ignorecase

" When searching try to be smart about cases
set smartcase

" Highlight search results
set hlsearch

" Makes search act like search in modern browsers
set incsearch

" Don't redraw while executing macros (good performance config)
set lazyredraw

" For regular expressions turn magic on
set magic

" Show matching brackets when text indicator is over them
set showmatch

" How many tenths of a second to blink when matching brackets
set mat=2

" No annoying sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500

" Properly disable sound on errors on MacVim
if has("gui_macvim")
autocmd GUIEnter * set vb t_vb=
endif

" Add a bit extra margin to the left
set foldcolumn=1

" Show line number
set number

" cursor line
" autocmd InsertEnter * set cul
" autocmd InsertLeave * set nocul
set cul

" cursor shpae
" Ps = 0 -> blinking block.
" Ps = 1 -> blinking block (default).
" Ps = 2 -> steady block.
" Ps = 3 -> blinking underline.
" Ps = 4 -> steady underline.
" Ps = 5 -> blinking bar (xterm).
" Ps = 6 -> steady bar (xterm).
" t_SI: Start Insert mode
" t_EI: End Insert mode
let &t_SI = "\<ESC>[6 q"
let &t_EI = "\<ESC>[1 q"

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Enable syntax highlighting
syntax enable

" Enable 256 colors palette in Gnome Terminal
if $COLORTERM == 'gnome-terminal'
set t_Co=256
endif

try
" colorscheme desert
colorscheme jellybeans
catch
endtry

set background=dark

" Set extra options when running in GUI mode
if has("gui_running")
set guioptions-=T
set guioptions-=e
set t_Co=256
set guitablabel=%M\ %t
endif

" Set utf8 as standard encoding and en_US as the standard language
set encoding=utf8

" Use Unix as the standard file type
set ffs=unix,dos,mac


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files, backups and undo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Turn backup off, since most stuff is in SVN, git etc. anyway...
set nobackup
set nowb
set noswapfile


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text, tab and indent related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Use spaces instead of tabs
set expandtab

" Be smart when using tabs ;)
set smarttab

" 1 tab == 2 spaces
set shiftwidth=2
set tabstop=2

" Linebreak on 500 characters
set lbr
set tw=500

set ai "Auto indent
set si "Smart indent
set wrap "Wrap lines


""""""""""""""""""""""""""""""
" => Visual mode related
""""""""""""""""""""""""""""""
" Visual mode pressing * or # searches for the current selection
" Super useful! From an idea by Michael Naumann
vnoremap <silent> * :<C-u>call VisualSelection('', '')<CR>/<C-R>=@/<CR><CR>
vnoremap <silent> # :<C-u>call VisualSelection('', '')<CR>?<C-R>=@/<CR><CR>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Moving around, tabs, windows and buffers
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Map <Space> to / (search) and Ctrl-<Space> to ? (backwards search)
map <space> /
map <C-space> ?

" Disable highlight when <leader><cr> is pressed
map <silent> <leader><cr> :noh<cr>

" Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l

" Close the current buffer
map <leader>bd :Bclose<cr>:tabclose<cr>gT

" Close all the buffers
map <leader>ba :bufdo bd<cr>

map <leader>l :bnext<cr>
map <leader>h :bprevious<cr>

" Useful mappings for managing tabs
map <leader>tn :tabnew<cr>
map <leader>to :tabonly<cr>
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove
map <leader>t<leader> :tabnext

" Let 'tl' toggle between this and the last accessed tab
let g:lasttab = 1
nmap <Leader>tl :exe "tabn ".g:lasttab<CR>
au TabLeave * let g:lasttab = tabpagenr()


" Opens a new tab with the current buffer's path
" Super useful when editing files in the same directory
map <leader>te :tabedit <C-r>=expand("%:p:h")<cr>/

" Switch CWD to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>:pwd<cr>

" Specify the behavior when switching between buffers
try
set switchbuf=useopen,usetab,newtab
set stal=2
catch
endtry

" Return to last edit position when opening files (You want this!)
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif


""""""""""""""""""""""""""""""
" => Status line
""""""""""""""""""""""""""""""
" Always show the status line
set laststatus=2

" Format the status line
set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ Line:\ %l\ \ Column:\ %c


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Editing mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remap VIM 0 to first non-blank character
map 0 ^

" Move a line of text using ALT+[jk] or Command+[jk] on mac
nmap <M-j> mz:m+<cr>`z
nmap <M-k> mz:m-2<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z

if has("mac") || has("macunix")
nmap <D-j> <M-j>
nmap <D-k> <M-k>
vmap <D-j> <M-j>
vmap <D-k> <M-k>
endif

" Delete trailing white space on save, useful for some filetypes ;)
fun! CleanExtraSpaces()
let save_cursor = getpos(".")
let old_query = getreg('/')
silent! %s/\s\+$//e
call setpos('.', save_cursor)
call setreg('/', old_query)
endfun

if has("autocmd")
autocmd BufWritePre *.txt,*.js,*.py,*.wiki,*.sh,*.coffee :call CleanExtraSpaces()
endif


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Spell checking
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Pressing ,ss will toggle and untoggle spell checking
map <leader>ss :setlocal spell!<cr>

" Shortcuts using <leader>
map <leader>sn ]s
map <leader>sp [s
map <leader>sa zg
map <leader>s? z=


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Misc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remove the Windows ^M - when the encodings gets messed up
noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm

" Quickly open a buffer for scribble
map <leader>q :e ~/buffer<cr>

" Quickly open a markdown buffer for scribble
map <leader>x :e ~/buffer.md<cr>

" Toggle paste mode on and off
map <leader>pp :setlocal paste!<cr>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Helper functions
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Returns true if paste mode is enabled
function! HasPaste()
if &paste
return 'PASTE MODE '
endif
return ''
endfunction

" Don't close window, when deleting a buffer
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
let l:currentBufNum = bufnr("%")
let l:alternateBufNum = bufnr("#")

if buflisted(l:alternateBufNum)
buffer #
else
bnext
endif

if bufnr("%") == l:currentBufNum
new
endif

if buflisted(l:currentBufNum)
execute("bdelete! ".l:currentBufNum)
endif
endfunction

function! CmdLine(str)
call feedkeys(":" . a:str)
endfunction

function! VisualSelection(direction, extra_filter) range
let l:saved_reg = @"
execute "normal! vgvy"

let l:pattern = escape(@", "\\/.*'$^~[]")
let l:pattern = substitute(l:pattern, "\n$", "", "")

if a:direction == 'gv'
call CmdLine("Ack '" . l:pattern . "' " )
elseif a:direction == 'replace'
call CmdLine("%s" . '/'. l:pattern . '/')
endif

let @/ = l:pattern
let @" = l:saved_reg
endfunction