OSDN Git Service

Regular updates
[twpd/master.git] / vimscript.md
1 ---
2 title: Vim scripting
3 category: Vim
4 prism_languages: [vim]
5 layout: 2017/sheet
6 updated: 2017-08-30
7 weight: -10
8 tags: [Featurable]
9 ---
10
11 ### Start hacking
12
13 ```vim
14 let name = "John"
15 echo "Hello, " . name
16 ```
17
18 You can either put this in a script (`script.vim`) and run it (`:source script.vim`), or you can type the commands individually in normal mode as `:let` and `:echo`.
19
20 ### Learn by example
21
22 ```vim
23 function! SuperTab()
24   let l:part = strpart(getline('.'),col('.')-2,1)
25   if (l:part=~'^\W\?$')
26       return "\<Tab>"
27   else
28       return "\<C-n>"
29   endif
30 endfunction
31
32 imap <Tab> <C-R>=SuperTab()<CR>
33 ```
34
35 [Here](http://www.vimbits.com/bits/46)'s another example with [functions](#functions), [variables](#variables) and [mapping](#mapping).
36
37 Variables
38 ---------
39
40 ### Defining
41 {: .-prime}
42
43 ```vim
44 let var = "hello"
45 ```
46
47 ### Variable prefixes
48
49 ```vim
50 let g:ack_options = '-s -H'    " g: global
51 let s:ack_program = 'ack'      " s: local (to script)
52 let l:foo = 'bar'              " l: local (to function)
53 ```
54
55 The `s:` prefix is also available in function names. See `:help local-variables`
56
57 ### Other prefixes
58
59 ```vim
60 let w:foo = 'bar'    " w: window
61 let b:state = 'on'   " b: buffer
62 let t:state = 'off'  " t: tab
63 echo v:var           " v: vim special
64 ```
65
66 ```vim
67 let @/ = ''          " @  register (this clears last search pattern)
68 echo $PATH           " $  env
69 ```
70
71 ### Vim options
72
73 ```vim
74 echo 'tabstop is ' . &tabstop
75 if &insertmode
76 echo &g:option
77 echo &l:option
78 ```
79
80 Prefix Vim options with `&`
81
82 ### Operators
83
84 ```vim
85 a + b             " numbers only!
86 'hello ' . name   " concat
87 ```
88
89 ```vim
90 let var -= 2
91 let var += 5
92 let var .= 'string'   " concat
93 ```
94
95 ## Strings
96
97 ### Strings
98
99 ```vim
100 let str = "String"
101 let str = "String with \n newline"
102
103 let literal = 'literal, no \ escaping'
104 let literal = 'that''s enough'  " double '' => '
105
106 echo "result = " . re   " concatenation
107 ```
108
109 Also see `:help literal-string` and `:help expr-quote`.
110 See: [Strings](http://learnvimscriptthehardway.stevelosh.com/chapters/26.html)
111
112 ### String functions
113
114 ```vim
115 strlen(str)    " length
116 len(str)       " same
117 strchars(str)  " character length
118
119 split("one two three")       "=> ['one', 'two', 'three']
120 split("one.two.three", '.')  "=> ['one', 'two', 'three']
121
122 join(['a', 'b'], ',')  "=> 'a,b'
123
124 tolower('Hello')
125 toupper('Hello')
126 ```
127
128 Also see `:help functions`
129 See: [String functions](http://learnvimscriptthehardway.stevelosh.com/chapters/27.html)
130
131 Functions
132 ---------
133
134 ### Functions
135 {: .-prime}
136
137 ```vim
138 " prefix with s: for local script-only functions
139 function! s:Initialize(cmd, args)
140   " a: prefix for arguments
141   echo "Command: " . a:cmd
142
143   return true
144 endfunction
145 ```
146
147 See: [Functions](http://learnvimscriptthehardway.stevelosh.com/chapters/23.html)
148
149 ### Namespacing
150
151 ```vim
152 function! myplugin#hello()
153 ```
154
155 ### Calling functions
156
157 ```vim
158 call s:Initialize()
159 call s:Initialize("hello")
160 ```
161
162 ### Consuming return values
163
164 ```vim
165 echo "Result: " . s:Initialize()
166 ```
167
168 ### Abortable
169
170 ```vim
171 function! myfunction() abort
172 endfunction
173 ```
174
175 Aborts when an error occurs.
176
177 ### Var arguments
178
179 ```vim
180 function! infect(...)
181   echo a:0    "=> 2
182   echo a:1    "=> jake
183   echo a:2    "=> bella
184
185   for s in a:000  " a list
186     echon ' ' . s
187   endfor
188 endfunction
189
190 infect('jake', 'bella')
191 ```
192
193 See `:help function-argument`.  See: [Var arguments](http://learnvimscriptthehardway.stevelosh.com/chapters/24.html)
194
195 Loops
196 -----
197
198 ```vim
199 for s in list
200   echo s
201   continue  " jump to start of loop
202   break     " breaks out of a loop
203 endfor
204 ```
205
206 ```vim
207 while x < 5
208 endwhile
209 ```
210
211 Custom commands
212 ---------------
213
214 ### Custom commands
215 {: .-prime}
216
217 ```vim
218 command! Save :set fo=want tw=80 nowrap
219 ```
220
221 Custom commands start with uppercase letters. The `!` redefines a command if it already exists.
222
223 ### Commands calling functions
224
225 ```vim
226 command! Save call <SID>foo()
227 ```
228 {: .-setup}
229
230 ```vim
231 function! s:foo()
232   ...
233 endfunction
234 ```
235
236 ### Commands with arguments
237
238 ```vim
239 command! -nargs=? Save call script#foo(<args>)
240 ```
241 {: .-setup}
242
243 | What | What |
244 | ---- | ---- |
245 | `-nargs=0` | 0 arguments, default |
246 | `-nargs=1` | 1 argument, includes spaces |
247 | `-nargs=?` | 0 or 1 argument |
248 | `-nargs=*` | 0+ arguments, space separated |
249 | `-nargs=+` | 1+ arguments, space reparated |
250
251 Flow
252 ----
253
254 ### Conditionals
255
256 ```vim
257 let char = getchar()
258 if char == "\<LeftMouse>"
259   " ...
260 elseif char == "\<RightMouse>"
261   " ...
262 else
263   " ...
264 endif
265 ```
266
267 ### Truthiness
268
269 ```vim
270 if 1 | echo "true"  | endif
271 if 0 | echo "false" | endif
272 ```
273
274 ```vim
275 if 1       "=> 1 (true)
276 if 0       "=> 0 (false)
277 if "1"     "=> 1 (true)
278 if "456"   "=> 1 (true)
279 if "xfz"   "=> 0 (false)
280 ```
281
282 No booleans. `0` is false, `1` is true.
283 See: [Truthiness](http://learnvimscriptthehardway.stevelosh.com/chapters/21.html)
284
285 ### Operators
286
287 ```vim
288 if 3 > 2
289 if a && b
290 if (a && b) || (c && d)
291 if !c
292 ```
293
294 See `:help expression-syntax`.
295 See: [Operators](http://learnvimscriptthehardway.stevelosh.com/chapters/22.html)
296
297 ### Strings
298
299 ```vim
300 if name ==# 'John'     " case-sensitive
301 if name ==? 'John'     " case-insensitive
302 if name == 'John'      " depends on :set ignorecase
303
304 " also: is#, is?, >=#, >=?, and so on
305 ```
306
307 ### Identity operators
308
309 ```vim
310 a is b
311 a isnot b
312 ```
313
314 Checks if it's the same instance object.
315
316 ### Regexp matches
317
318 ```vim
319 "hello" =~ '/x/'
320 "hello" !~ '/x/'
321 ```
322
323 ### Single line
324
325 ```vim
326 if empty(a:path) | return [] | endif
327 a ? b : c
328 ```
329
330 Use `|` to join lines together.
331
332 ### Boolean logic
333
334 ```vim
335 if g:use_dispatch && s:has_dispatch
336   ···
337 endif
338 ```
339
340 Lists
341 -----
342
343 ### Lists
344
345 ```vim
346 let mylist = [1, two, 3, "four"]
347
348 let first = mylist[0]
349 let last  = mylist[-1]
350
351 " Suppresses errors
352 let second = get(mylist, 1)
353 let second = get(mylist, 1, "NONE")
354 ```
355
356 ### Functions
357
358 ```vim
359 len(mylist)
360 empty(mylist)
361
362 sort(list)
363 let sortedlist = sort(copy(list))
364
365 split('hello there world', ' ')
366 ```
367
368 ### Concatenation
369
370 ```vim
371 let longlist = mylist + [5, 6]
372 let mylist += [7, 8]
373 ```
374
375 ### Sublists
376
377 ```vim
378 let shortlist = mylist[2:-1]
379 let shortlist = mylist[2:]     " same
380
381 let shortlist = mylist[2:2]    " one item
382 ```
383
384 ### Push
385
386 ```vim
387 let alist = [1, 2, 3]
388 let alist = add(alist, 4)
389 ```
390
391 ### Map
392
393 ```vim
394 call map(files, "bufname(v:val)")  " use v:val for value
395 call filter(files, 'v:val != ""')
396 ```
397
398 Dictionaries
399 ------------
400
401 ### Dictionaries
402
403 ```vim
404 let colors = {
405   \ "apple": "red",
406   \ "banana": "yellow"
407 }
408
409 echo colors["a"]
410 echo get(colors, "apple")   " suppress error
411 ```
412
413 See `:help dict`
414
415 ### Using dictionaries
416
417 ```vim
418 remove(colors, "apple")
419 ```
420
421 ```vim
422 " :help E715
423 if has_key(dict, 'foo')
424 if empty(dict)
425 keys(dict)
426 len(dict)
427 ```
428
429 ```vim
430 max(dict)
431 min(dict)
432 ```
433
434 ```vim
435 count(dict, 'x')
436 string(dict)
437 ```
438
439 ```vim
440 map(dict, '<>> " . v:val')
441 ```
442
443 ### Iteration
444
445 ```vim
446 for key in keys(mydict)
447   echo key . ': ' . mydict(key)
448 endfor
449 ```
450
451 ### Prefixes
452
453 ```vim
454 keys(s:)
455 ```
456
457 Prefixes (`s:`, `g:`, `l:`, etc) are actually dictionaries.
458
459 ### Extending
460
461 ```vim
462 " Extending with more
463 let extend(s:fruits, { ... })
464 ```
465
466 Casting
467 -------
468
469 ```vim
470 str2float("2.3")
471 str2nr("3")
472 float2nr("3.14")
473 ```
474
475 Numbers
476 -------
477
478 ### Numbers
479 {: .-prime}
480
481 ```vim
482 let int = 1000
483 let int = 0xff
484 let int = 0755   " octal
485 ```
486
487 See `:help Number`.
488 See: [Numbers](http://learnvimscriptthehardway.stevelosh.com/chapters/25.html)
489
490 ### Floats
491
492 ```vim
493 let fl = 100.1
494 let fl = 5.4e4
495 ```
496
497 See `:help Float`
498
499 ### Arithmetic
500
501 ```vim
502 3 / 2     "=> 1, integer division
503 3 / 2.0   "=> 1.5
504 3 * 2.0   "=> 6.0
505 ```
506
507 ### Math functions
508
509 ```vim
510 sqrt(100)
511 floor(3.5)
512 ceil(3.3)
513 abs(-3.4)
514
515 sin() cos() tan()
516 sinh() cosh() tanh()
517 asin() acos() atan()
518 ```
519
520 Vim-isms
521 --------
522
523 ### Execute a command
524
525 ```vim
526 execute "vsplit"
527 execute "e " . fnameescape(filename)
528 ```
529
530 Runs an ex command you typically run with `:`. Also see `:help execute`.
531 See: [Execute a command](http://learnvimscriptthehardway.stevelosh.com/chapters/28.html)
532
533 ### Running keystrokes
534
535 ```vim
536 normal G
537 normal! G   " skips key mappings
538
539 execute "normal! gg/foo\<cr>dd"
540 ```
541
542 Use `:normal` to execute keystrokes as if you're typing them in normal mode. Combine with `:execute` for special keystrokes.
543 See: [Running keystrokes](http://learnvimscriptthehardway.stevelosh.com/chapters/29.html)
544
545 ### Getting filenames
546
547 ```vim
548 echo expand("%")      " path/file.txt
549 echo expand("%:t")    " file.txt
550 echo expand("%:p:h")  " /home/you/path/file.txt
551 echo expand("%:r")    " path/file
552 echo expand("%:e")    " txt
553 ```
554
555 See `:help expand`
556
557 ### Silencing
558
559 ```vim
560 silent g/Aap/p
561 ```
562
563 Suppresses output. See `:help silent`
564
565 ### Echo
566
567 ```vim
568 echoerr 'oh it failed'
569 echomsg 'hello there'
570 echo 'hello'
571
572 echohl WarningMsg | echomsg "=> " . a:msg | echohl None
573 ```
574
575
576 ### Settings
577
578 ```vim
579 set number
580 set nonumber
581 set number!     " toggle
582 set numberwidth=5
583 set guioptions+=e
584 ```
585
586 ### Prompts
587
588 ```vim
589 let result = confirm("Sure?")
590 execute "confirm q"
591 ```
592
593 ### Built-ins
594
595 ```vim
596 has("feature")  " :h feature-list
597 executable("python")
598 globpath(&rtp, "syntax/c.vim")
599
600 exists("$ENV")
601 exists(":command")
602 exists("variable")
603 exists("+option")
604 exists("g:...")
605 ```
606
607 Mapping
608 -------
609 {: .-three-column}
610
611 ### Mapping commands
612
613 ```vim
614 nmap
615 vmap
616 imap
617 xmap
618 nnoremap
619 vnoremap
620 inoremap
621 xnoremap
622 ...
623 ```
624
625 ### Explanation
626
627 ```vim
628 [nvixso](nore)map
629 ```
630
631 ```
632  │       └ don't recurse
633  │
634  └ normal, visual, insert,
635    eX mode, select, operator-pending
636 ```
637 {: .-setup}
638
639 ### Arguments
640
641 | `<buffer>` | only in current buffer |
642 | `<silent>` | no echo |
643 | `<nowait>` | |
644
645 Syntax
646 ------
647
648 ### Highlights
649
650 ```vim
651 hi Comment
652   term=bold,underline
653   gui=bold
654   ctermfg=4
655   guifg=#80a0ff
656 ```
657
658 ### Filetype detection
659
660 ```vim
661 augroup filetypedetect
662   au! BufNewFile,BufRead *.json setf javascript
663 augroup END
664
665 au Filetype markdown setlocal spell
666 ```
667
668 ### Conceal
669
670 ```vim
671 set conceallevel=2
672 syn match newLine "<br>" conceal cchar=}
673 hi newLine guifg=green
674 ```
675
676 ### Region conceal
677
678 ```vim
679 syn region inBold concealends matchgroup=bTag start="<b>" end="</b>"
680 hi inBold gui=bold
681 hi bTag guifg=blue
682 ```
683
684 ### Syntax
685
686 ```vim
687 syn match :name ":regex" :flags
688
689 syn region Comment  start="/\*"  end="\*/"
690 syn region String   start=+"+    end=+"+         skip=+\\"+
691
692 syn cluster :name contains=:n1,:n2,:n3...
693
694 flags:
695   keepend
696   oneline
697   nextgroup=
698   contains=
699   contained
700
701 hi def link markdownH1 htmlH1
702 ```
703
704 ### Include guards
705
706 ```vim
707 if exists('g:loaded_myplugin')
708   finish
709 endif
710
711 " ...
712
713 let g:loaded_myplugin = 1
714 ```