OSDN Git Service

Regular updates
[twpd/master.git] / vimscript-functions.md
1 ---
2 title: Vimscript functions
3 category: Vim
4 ---
5
6 Dictionaries
7 ------------
8
9 ```vim
10 let colors = {
11   \ "apple": "red",
12   \ "banana": "yellow"
13 }
14
15 echo colors["a"]
16 echo get(colors, "apple")   " suppress error
17
18 remove(colors, "apple")
19
20 " :help E715
21 if has_key(dict, 'foo')
22 if empty(dict)
23 keys(dict)
24 len(dict)
25
26 max(dict)
27 min(dict)
28
29 count(dict, 'x')
30 string(dict)
31
32 map(dict, '<>> " . v:val')
33 extend(s:fruits, { ... })
34 ```
35
36 ```vim
37 for key in keys(mydict)
38   echo key . ': ' . mydict(key)
39 endfor
40 ```
41
42 Lists
43 -----
44
45 ```vim
46 let mylist = [1, two, 3, "four"]
47
48 let first = mylist[0]
49 let last  = mylist[-1]
50
51 " Suppresses errors
52 let second = get(mylist, 1)
53 let second = get(mylist, 1, "NONE")
54 ```
55
56 Functions
57 ---------
58
59 ### Buffer
60
61     line('.')             " current line number
62     col('.')
63     col('$')
64
65     getline('.')          " current line as a string
66     getline(1)            " get line 1
67     getline(1, 5)         " get lines 1-5
68     search('^$')          " next blank line, returns line number
69     search('^$','n')      " but don't move cursor
70
71     getcurpos()           " [bufnum, lnum, col, off, curswant]
72     getpos('.')           " [bufnum, lnum, col, off]
73
74     nextnonblank(1)       " next non-blank line after line1
75     prevnonblank()
76
77 ### Marks
78
79     getpos("'a")          " position of a mark
80     setpos("'a",...)
81
82     getpos("'<")          " position of selection start
83
84 ### Cursor
85
86     cursor(line,col)      " moves cursor
87     cursor(line,col,off,curswant)
88
89     getcurpos()           " returns [bufnum,line,col,off,curswant]
90
91 ### Expand
92
93     expand('<cword>')      " word under cursor
94     expand('%')            " current file
95
96     " <cword>  current word on cursor
97     " :p    full path
98     " :h    head
99     " :p:h  dirname   (/Users/rsc/project)
100     " :t    tail      (file.txt)
101     " :r    root      (file)
102     " :e    extension (.txt)
103     " see :h cmdline-special
104
105 ### Files
106
107     fnameescape('string')
108     fnamemodify('main.c', ':p:h')
109     fnamemodify(fname, ':e')   " current file extension - see expand()
110     filereadable(fname)
111     getfsize('file.txt')
112     getcwd()
113
114     globpath(&rtp, "plugin/commentary.vim")
115
116 ### Math
117
118     fmod(9, 2)  " modulus
119     abs(-0.5)
120     sqrt(9)
121
122     trunc(1.84)
123     floor(1.84)
124     ceil(1.84)
125     float2nr(3.14)
126
127 ### Casting
128
129     str2float('0.2')
130     str2nr('240')
131     str2nr('ff', '16')
132
133     string(0.3)
134
135 ### Type checking
136
137     type(var) == type(0)
138     type(var) == type("")
139     type(var) == type(function("tr"))
140     type(var) == type([])
141     type(var) == type({})
142     type(var) == type(0.0)
143
144 ### Date/time
145
146     strftime('%c')
147     strftime('%c',getftime('file.c'))
148
149 ### Strings
150
151     if a =~ '\s*'
152     substitute(str, '.', 'x', 'g')
153     strpart("abcdef", 3, 2)    " == "de" (substring)
154     strpart("abcdef", 3)       " == "def"
155     stridx("abcdef", "e")      " == 4
156     strridx()                  " reverse
157
158     matchstr('testing','test')  " == 'test' (or '')
159     match('testing','test')     " == 0
160     matchend('testing','test')  " == 4
161     match('testing','\ctest')   " ignore case
162
163     split(str, '\zs')           " split into characters
164
165     strlen(str)
166     strchars()                  " accounts for composing chars
167     strwidth()                  " accounts for ambig characters
168     strdisplaywidth()           " accounts for tab stops
169
170     toupper(str)
171     tolower(str)
172     tr('foo', '_-', '  ')
173
174 ### Syntax
175
176     synstack(line('.'),col('.'))   " returns many
177     synID(line('.'),col('.'),1)    " only one
178
179     synIDattr(id,"bg")
180     synIDattr(id,"name")
181     synIDtrans()
182
183     " syntax stack
184     map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')
185
186 ### Shell
187
188     system('ls '.shellescape(expand('%:h')))
189
190 ### Registers
191
192     getreg('*')
193     getregtype('*')     " v(char), V(line) <ctrl-v>(block)
194
195 Comparisons
196 -----------
197
198     if name ==# 'John'     " case-sensitive
199     if name ==? 'John'     " case-insensitive
200     if name == 'John'      " depends on :set ignorecase
201     " also: is#, is?, >=#, >=?, and so on
202
203     if "hello" =~ '.*'
204     if "hello" !~ '.*'
205
206 Executing
207 ---------
208
209 ### Running commands
210
211     normal 'ddahello'
212     exe 'normal ^C'  " with expansions
213     wincmd J