빠른 참조

Vimscript 치트시트

Vimscript 종합 레퍼런스 가이드: 변수, 함수, 사용자 정의 명령, 제어문, 데이터 구조, 키 매핑 및 구문 강조.

· 게시일

Vimscript는 Vim 텍스트 에디터를 맞춤 설정하고 확장하기 위한 내장 스크립팅 언어입니다.

시작하기

let name = "John"
echo "Hello, " . name

스크립트 파일(script.vim)에 작성 후 (:source script.vim)으로 로드하거나, 노멀 모드에서 직접 :let 및 :echo로 실행할 수 있습니다.

예제로 배우기

function! SuperTab()
  let l:part = strpart(getline('.'), col('.') - 2, 1)
  if (l:part =~ '^\W\?$')
    return "\<Tab>"
  else
    return "\<C-n>"
  endif
endfunction

imap <Tab> <C-R>=SuperTab()<CR>

변수

정의

let var = "hello"

변수 스코프 접두어

let g:ack_options = '-s -H'    " g: global
let s:ack_program = 'ack'      " s: local (to script)
let l:foo = 'bar'              " l: local (to function)
let a:arg = 'baz'              " a: function argument

s: 접두어는 스크립트 로컬 함수 이름에도 사용할 수 있습니다. :help local-variables를 참조하세요.

기타 스코프

let w:foo = 'bar'    " w: window local
let b:state = 'on'   " b: buffer local
let t:state = 'off'  " t: tab page local
echo v:version       " v: vim internal variable
let @/ = ''          " @  register
echo $PATH           " $  environment variable

Vim 옵션

echo 'tabstop is ' . &tabstop
if &insertmode
echo &g:option
echo &l:option

표현식에서 옵션 값을 읽거나 수정하려면 옵션 이름 앞에 &를 붙입니다.

산술 및 문자열 연산자

a + b             " Numbers only!
'hello ' . name   " String concatenation
let var -= 2
let var += 5
let var .= 'string'

문자열 (Strings)

문자열 구문

let str = "String"
let str = "String with \n newline"

let literal = 'literal, no \ escaping'
let literal = 'that''s enough'

echo "result = " . res

문자열 함수

strlen(str)
len(str)
strchars(str)

split("one two three")       "=> ['one', 'two', 'three']
split("one.two.three", '.')  "=> ['one', 'two', 'three']

join(['a', 'b'], ',')        "=> 'a,b'

tolower('Hello')
toupper('Hello')

함수

함수 정의

function! s:Initialize(cmd, args)
  echo "Command: " . a:cmd
  return 1
endfunction

함수 덮어쓰기

function! MyFunc()
  echo "Function defined or replaced"
endfunction

function!(! 포함)을 사용하면 오류 없이 동일한 이름의 기존 함수를 덮어씁니다.

네임스페이스 및 자동 로드 (Autoload)

function! myplugin#hello()
  " autoload/myplugin.vim
endfunction

함수 호출

call s:Initialize()
call s:Initialize("hello", 123)

반환값 받기

let result = s:Initialize()

오류 발생 시 즉시 중단 (abort)

function! MyFunction() abort
endfunction

가변 인수 (Variadic Arguments)

function! Infect(...)
  echo a:0
  echo a:1
  echo a:2

  for item in a:000
    echon ' ' . item
  endfor
endfunction

call Infect('jake', 'bella')

반복문 및 흐름 제어

반복문 (Loops)

for s in list
  echo s
  continue
  break
endfor
while x < 5
  let x += 1
endwhile

사용자 정의 명령 (Custom Commands)

명령 정의

command! Save :set fo=want tw=80 nowrap

사용자 정의 명령은 대문자로 시작해야 합니다. ! 플래그로 기존 명령을 재정의할 수 있습니다.

명령에서 함수 호출

command! Save call <SID>Foo()

function! s:Foo()
endfunction

명령 인수

command! -nargs=? Save call script#foo(<args>)
인수 지정자 설명
-nargs=0 인수 0개 (기본값)
-nargs=1 정확히 1개의 인수 (공백 포함 가능)
-nargs=? 0개 또는 1개의 인수
-nargs=* 공백으로 구분된 0개 이상의 인수
-nargs=+ 공백으로 구분된 1개 이상의 인수

조건문 (Conditionals)

If / Elseif / Else

let char = getchar()
if char == "\<LeftMouse>"
elseif char == "\<RightMouse>"
else
endif

참/거짓 평가 (Truthiness)

if 1       "=> True
if 0       "=> False
if "1"     "=> True
if "456"   "=> True
if "xfz"   "=> False

Vimscript에는 별도의 불리언 타입이 없습니다. 0은 거짓이며 0이 아닌 정수는 참입니다.

비교 연산자

if 3 > 2
if a && b
if (a && b) || (c && d)
if !c

문자열 대소문자 구분

if name ==# 'John'     " case-sensitive
if name ==? 'John'     " case-insensitive
if name == 'John'      " &ignorecase

동일성 비교

if a is b
if a isnot b

a와 b가 메모리상에서 동일한 인스턴스를 참조하는지 확인합니다.

정규식 일치 (Regex Matches)

"hello" =~ 'xx*'
"hello" !~ 'xx*'
"hello" =~ '\v<\d+>'

\v는 'very magic' 정규식 구문을 활성화하여 이스케이프 부담을 줄여줍니다.

단일 행 문장

if empty(a:path) | return [] | endif
let status = a ? b : c

|를 사용하여 한 줄에 여러 문장을 연결할 수 있습니다.

데이터 구조

리스트 (Lists)

let mylist = [1, "two", 3, "four"]

let first = mylist[0]
let last  = mylist[-1]

let second = get(mylist, 1)
let fallback = get(mylist, 10, "NONE")

리스트 연산

len(mylist)
empty(mylist)

let sortedlist = sort(copy(mylist))

let shortlist = mylist[2:-1]
let shortlist = mylist[2:]
let single = mylist[2:2]

let longlist = mylist + [5, 6]
let mylist += [7, 8]
call add(mylist, 9)

함수형 리스트 메서드

call map(files, "bufname(v:val)")
call filter(files, 'v:val != ""')

딕셔너리 (Dictionaries)

let colors = {
  \ "apple": "red",
  \ "banana": "yellow"
}

echo colors["apple"]
echo get(colors, "apple")

딕셔너리 연산

call remove(colors, "apple")

if has_key(dict, 'foo')
if empty(dict)
let k = keys(dict)
let v = values(dict)
let n = len(dict)

echo max(dict)
echo min(dict)

call extend(s:fruits, { "cherry": "red" })
for key in keys(mydict)
  echo key . ': ' . mydict[key]
endfor

스코프 접두어(s:, g:, l:, b:) 자체도 딕셔너리 객체로 접근할 수 있습니다:

let script_keys = keys(s:)

숫자 및 산술

let int = 1000
let hex = 0xff
let oct = 0755
let fl = 100.1
let sci = 5.4e4
3 / 2     "=> 1
3 / 2.0   "=> 1.5
sqrt(100)
floor(3.5)
ceil(3.3)
abs(-3.4)

Vim 고유 기능

동적 명령 실행 (execute)

execute "vsplit"
execute "edit " . fnameescape(filename)

노멀 모드 키 입력 실행 (normal)

normal G
normal! G

execute "normal! gg/foo\<cr>dd"

파일명 확장 (expand)

echo expand("%")      " path/file.txt
echo expand("%:t")    " file.txt
echo expand("%:p:h")  " /home/user/path
echo expand("%:r")    " path/file
echo expand("%:e")    " txt

출력 제어 및 메시지

silent g/pattern/p

echo 'Simple text'
echomsg 'Persistent text recorded in :messages'
echoerr 'Error message'

echohl WarningMsg | echomsg "=> Warning!" | echohl None

설정 옵션

set number
set nonumber
set number!
set numberwidth=5
set guioptions+=e

내부 검사 및 기능 감지

has("clipboard")
executable("python3")
globpath(&rtp, "syntax/c.vim")

exists("$ENV")
exists(":command")
exists("variable")
exists("+option")

키 매핑 (Key Mappings)

모드

[nvixso](nore)map

주요 매핑 플래그

플래그 의미
<buffer> 현재 버퍼에만 적용
<silent> 상태 표시줄에 명령 출력 억제
<nowait> 더 긴 매핑 입력을 기다리지 않고 즉시 실행

구문 강조 및 Conceal

하이라이트 그룹

hi Comment term=bold gui=bold ctermfg=4 guifg=#80a0ff
hi def link markdownH1 htmlH1

파일 타입 감지 (Filetype Detection)

augroup filetypedetect
  au! BufNewFile,BufRead *.json setf javascript
augroup END

au Filetype markdown setlocal spell

텍스트 숨김 표시 (Conceal)

set conceallevel=2
syn match newLine "<br>" conceal cchar=}
hi newLine guifg=green

다중 로딩 방지 (Include Guards)

if exists('g:loaded_myplugin')
  finish
endif
let g:loaded_myplugin = 1

관련 주제