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: 2020-07-05
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 1
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" =~ 'xx*'
320 "hello" !~ 'xx*'
321 "hello" =~ '\v<\d+>'
322 ```
323
324 `\v` enables "extended" regex mode which allows word boundary (`<>`), `+`, and more.
325
326 ### Single line
327
328 ```vim
329 if empty(a:path) | return [] | endif
330 a ? b : c
331 ```
332
333 Use `|` to join lines together.
334
335 ### Boolean logic
336
337 ```vim
338 if g:use_dispatch && s:has_dispatch
339   ···
340 endif
341 ```
342
343 Lists
344 -----
345
346 ### Lists
347
348 ```vim
349 let mylist = [1, two, 3, "four"]
350
351 let first = mylist[0]
352 let last  = mylist[-1]
353
354 " Suppresses errors
355 let second = get(mylist, 1)
356 let second = get(mylist, 1, "NONE")
357 ```
358
359 ### Functions
360
361 ```vim
362 len(mylist)
363 empty(mylist)
364
365 sort(list)
366 let sortedlist = sort(copy(list))
367
368 split('hello there world', ' ')
369 ```
370
371 ### Concatenation
372
373 ```vim
374 let longlist = mylist + [5, 6]
375 let mylist += [7, 8]
376 ```
377
378 ### Sublists
379
380 ```vim
381 let shortlist = mylist[2:-1]
382 let shortlist = mylist[2:]     " same
383
384 let shortlist = mylist[2:2]    " one item
385 ```
386
387 ### Push
388
389 ```vim
390 let alist = [1, 2, 3]
391 let alist = add(alist, 4)
392 ```
393
394 ### Map
395
396 ```vim
397 call map(files, "bufname(v:val)")  " use v:val for value
398 call filter(files, 'v:val != ""')
399 ```
400
401 Dictionaries
402 ------------
403
404 ### Dictionaries
405
406 ```vim
407 let colors = {
408   \ "apple": "red",
409   \ "banana": "yellow"
410 }
411
412 echo colors["a"]
413 echo get(colors, "apple")   " suppress error
414 ```
415
416 See `:help dict`
417
418 ### Using dictionaries
419
420 ```vim
421 remove(colors, "apple")
422 ```
423
424 ```vim
425 " :help E715
426 if has_key(dict, 'foo')
427 if empty(dict)
428 keys(dict)
429 len(dict)
430 ```
431
432 ```vim
433 max(dict)
434 min(dict)
435 ```
436
437 ```vim
438 count(dict, 'x')
439 string(dict)
440 ```
441
442 ```vim
443 map(dict, '<>> " . v:val')
444 ```
445
446 ### Iteration
447
448 ```vim
449 for key in keys(mydict)
450   echo key . ': ' . mydict(key)
451 endfor
452 ```
453
454 ### Prefixes
455
456 ```vim
457 keys(s:)
458 ```
459
460 Prefixes (`s:`, `g:`, `l:`, etc) are actually dictionaries.
461
462 ### Extending
463
464 ```vim
465 " Extending with more
466 let extend(s:fruits, { ... })
467 ```
468
469 Casting
470 -------
471
472 ```vim
473 str2float("2.3")
474 str2nr("3")
475 float2nr("3.14")
476 ```
477
478 Numbers
479 -------
480
481 ### Numbers
482 {: .-prime}
483
484 ```vim
485 let int = 1000
486 let int = 0xff
487 let int = 0755   " octal
488 ```
489
490 See `:help Number`.
491 See: [Numbers](http://learnvimscriptthehardway.stevelosh.com/chapters/25.html)
492
493 ### Floats
494
495 ```vim
496 let fl = 100.1
497 let fl = 5.4e4
498 ```
499
500 See `:help Float`
501
502 ### Arithmetic
503
504 ```vim
505 3 / 2     "=> 1, integer division
506 3 / 2.0   "=> 1.5
507 3 * 2.0   "=> 6.0
508 ```
509
510 ### Math functions
511
512 ```vim
513 sqrt(100)
514 floor(3.5)
515 ceil(3.3)
516 abs(-3.4)
517
518 sin() cos() tan()
519 sinh() cosh() tanh()
520 asin() acos() atan()
521 ```
522
523 Vim-isms
524 --------
525
526 ### Execute a command
527
528 ```vim
529 execute "vsplit"
530 execute "e " . fnameescape(filename)
531 ```
532
533 Runs an ex command you typically run with `:`. Also see `:help execute`.
534 See: [Execute a command](http://learnvimscriptthehardway.stevelosh.com/chapters/28.html)
535
536 ### Running keystrokes
537
538 ```vim
539 normal G
540 normal! G   " skips key mappings
541
542 execute "normal! gg/foo\<cr>dd"
543 ```
544
545 Use `:normal` to execute keystrokes as if you're typing them in normal mode. Combine with `:execute` for special keystrokes.
546 See: [Running keystrokes](http://learnvimscriptthehardway.stevelosh.com/chapters/29.html)
547
548 ### Getting filenames
549
550 ```vim
551 echo expand("%")      " path/file.txt
552 echo expand("%:t")    " file.txt
553 echo expand("%:p:h")  " /home/you/path/file.txt
554 echo expand("%:r")    " path/file
555 echo expand("%:e")    " txt
556 ```
557
558 See `:help expand`
559
560 ### Silencing
561
562 ```vim
563 silent g/Aap/p
564 ```
565
566 Suppresses output. See `:help silent`
567
568 ### Echo
569
570 ```vim
571 echoerr 'oh it failed'
572 echomsg 'hello there'
573 echo 'hello'
574
575 echohl WarningMsg | echomsg "=> " . a:msg | echohl None
576 ```
577
578
579 ### Settings
580
581 ```vim
582 set number
583 set nonumber
584 set number!     " toggle
585 set numberwidth=5
586 set guioptions+=e
587 ```
588
589 ### Prompts
590
591 ```vim
592 let result = confirm("Sure?")
593 execute "confirm q"
594 ```
595
596 ### Built-ins
597
598 ```vim
599 has("feature")  " :h feature-list
600 executable("python")
601 globpath(&rtp, "syntax/c.vim")
602
603 exists("$ENV")
604 exists(":command")
605 exists("variable")
606 exists("+option")
607 exists("g:...")
608 ```
609
610 Mapping
611 -------
612 {: .-three-column}
613
614 ### Mapping commands
615
616 ```vim
617 nmap
618 vmap
619 imap
620 xmap
621 nnoremap
622 vnoremap
623 inoremap
624 xnoremap
625 ...
626 ```
627
628 ### Explanation
629
630 ```vim
631 [nvixso](nore)map
632 ```
633
634 ```
635  │       └ don't recurse
636  │
637  └ normal, visual, insert,
638    eX mode, select, operator-pending
639 ```
640 {: .-setup}
641
642 ### Arguments
643
644 | `<buffer>` | only in current buffer |
645 | `<silent>` | no echo |
646 | `<nowait>` | |
647
648 Syntax
649 ------
650
651 ### Highlights
652
653 ```vim
654 hi Comment
655   term=bold,underline
656   gui=bold
657   ctermfg=4
658   guifg=#80a0ff
659 ```
660
661 ### Filetype detection
662
663 ```vim
664 augroup filetypedetect
665   au! BufNewFile,BufRead *.json setf javascript
666 augroup END
667
668 au Filetype markdown setlocal spell
669 ```
670
671 ### Conceal
672
673 ```vim
674 set conceallevel=2
675 syn match newLine "<br>" conceal cchar=}
676 hi newLine guifg=green
677 ```
678
679 ### Region conceal
680
681 ```vim
682 syn region inBold concealends matchgroup=bTag start="<b>" end="</b>"
683 hi inBold gui=bold
684 hi bTag guifg=blue
685 ```
686
687 ### Syntax
688
689 ```vim
690 syn match :name ":regex" :flags
691
692 syn region Comment  start="/\*"  end="\*/"
693 syn region String   start=+"+    end=+"+         skip=+\\"+
694
695 syn cluster :name contains=:n1,:n2,:n3...
696
697 flags:
698   keepend
699   oneline
700   nextgroup=
701   contains=
702   contained
703
704 hi def link markdownH1 htmlH1
705 ```
706
707 ### Include guards
708
709 ```vim
710 if exists('g:loaded_myplugin')
711   finish
712 endif
713
714 " ...
715
716 let g:loaded_myplugin = 1
717 ```