-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathclang_format.vim
287 lines (251 loc) · 9.09 KB
/
clang_format.vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
let s:save_cpo = &cpo
set cpo&vim
" helper functions {{{
function! s:has_vimproc()
if !exists('s:exists_vimproc')
try
silent call vimproc#version()
let s:exists_vimproc = 1
catch
let s:exists_vimproc = 0
endtry
endif
return s:exists_vimproc
endfunction
function! s:system(str, ...)
let command = a:str
let input = a:0 >= 1 ? a:1 : ''
if a:0 == 0
let output = s:has_vimproc() ?
\ vimproc#system(command) : system(command)
elseif a:0 == 1
let output = s:has_vimproc() ?
\ vimproc#system(command, input) : system(command, input)
else
" ignores 3rd argument unless you have vimproc.
let output = s:has_vimproc() ?
\ vimproc#system(command, input, a:2) : system(command, input)
endif
return output
endfunction
function! s:create_keyvals(key, val) abort
if type(a:val) == type({})
return a:key . ': {' . s:stringize_options(a:val) . '}'
else
return a:key . ': ' . a:val
endif
endfunction
function! s:stringize_options(opts) abort
let dict_type = type({})
let keyvals = map(items(a:opts), 's:create_keyvals(v:val[0], v:val[1])')
return join(keyvals, ',')
endfunction
function! s:build_extra_options()
let extra_options = ""
let opts = copy(g:clang_format#style_options)
if has_key(g:clang_format#filetype_style_options, &ft)
call extend(opts, g:clang_format#filetype_style_options[&ft])
endif
let extra_options .= ', ' . s:stringize_options(opts)
return extra_options
endfunction
function! s:make_style_options()
let extra_options = s:build_extra_options()
return printf("'{BasedOnStyle: %s, IndentWidth: %d, UseTab: %s%s}'",
\ g:clang_format#code_style,
\ (exists('*shiftwidth') ? shiftwidth() : &l:shiftwidth),
\ &l:expandtab==1 ? "false" : "true",
\ extra_options)
endfunction
function! s:success(result)
return (s:has_vimproc() ? vimproc#get_last_status() : v:shell_error) == 0
\ && a:result !~# '^YAML:\d\+:\d\+: error: unknown key '
\ && a:result !~# '^\n\?$'
endfunction
function! s:error_message(result)
echoerr "clang-format has failed to format."
if a:result =~# '^YAML:\d\+:\d\+: error: unknown key '
echohl ErrorMsg
for l in split(a:result, "\n")[0:1]
echomsg l
endfor
echohl None
endif
endfunction
function! clang_format#get_version()
if &shell =~# 'csh$' && executable('/bin/bash')
let shell_save = &shell
set shell=/bin/bash
endif
try
let version_output = s:system(g:clang_format#command.' --version 2>&1')
if stridx(version_output, 'NPM') != -1
" Note:
" When clang-format is installed with npm, version string is changed (#39).
return matchlist(version_output, 'NPM version \d\+\.\d\+\.\(\d\)\(\d\+\)')[1:2]
else
return matchlist(version_output, '\(\d\+\)\.\(\d\+\)')[1:2]
endif
finally
if exists('l:shell_save')
let &shell = shell_save
endif
endtry
endfunction
function! clang_format#is_invalid()
if !exists('s:command_available')
" if running on windows and the path has spaces it needs to be quoted,
" but executable() get confused by the quotes, so we remove them
if has("win32") && !executable(split(g:clang_format#command, '"')[0])
return 1
elseif !has("win32") && !executable(g:clang_format#command)
return 1
endif
let s:command_available = 1
endif
if !exists('s:version')
let v = clang_format#get_version()
if v[0] < 3 || (v[0] == 3 && v[1] < 4)
return 2
endif
let s:version = v
endif
return 0
endfunction
function! s:verify_command()
let invalidity = clang_format#is_invalid()
if invalidity == 1
echoerr "clang-format is not found. check g:clang_format#command."
elseif invalidity == 2
echoerr 'clang-format 3.3 or earlier is not supported for the lack of aruguments'
endif
endfunction
" }}}
" variable definitions {{{
function! s:getg(name, default)
" backward compatibility
if exists('g:operator_'.substitute(a:name, '#', '_', ''))
echoerr 'g:operator_'.substitute(a:name, '#', '_', '').' is deprecated. Please use g:'.a:name
return g:operator_{substitute(a:name, '#', '_', '')}
else
return get(g:, a:name, a:default)
endif
endfunction
let g:clang_format#command = s:getg('clang_format#command', 'clang-format')
let g:clang_format#extra_args = s:getg('clang_format#extra_args', "")
if type(g:clang_format#extra_args) == type([])
let g:clang_format#extra_args = join(g:clang_format#extra_args, " ")
endif
let g:clang_format#code_style = s:getg('clang_format#code_style', 'google')
let g:clang_format#style_options = s:getg('clang_format#style_options', {})
let g:clang_format#filetype_style_options = s:getg('clang_format#filetype_style_options', {})
let g:clang_format#detect_style_file = s:getg('clang_format#detect_style_file', 1)
let g:clang_format#auto_format = s:getg('clang_format#auto_format', 0)
let g:clang_format#auto_format_on_insert_leave = s:getg('clang_format#auto_format_on_insert_leave', 0)
let g:clang_format#auto_formatexpr = s:getg('clang_format#auto_formatexpr', 0)
" }}}
" format codes {{{
function! s:detect_style_file()
let dirname = fnameescape(expand('%:p:h'))
return findfile('.clang-format', dirname.';') != '' || findfile('_clang-format', dirname.';') != ''
endfunction
function! clang_format#format(line1, line2)
let args = printf(" -lines=%d:%d", a:line1, a:line2)
if ! (g:clang_format#detect_style_file && s:detect_style_file())
let args .= printf(" -style=%s ", s:make_style_options())
else
let args .= " -style=file "
endif
let args .= printf("-assume-filename=%s ", shellescape(escape(expand('%'), " \t")))
let args .= g:clang_format#extra_args
let clang_format = printf("%s %s --", g:clang_format#command, args)
return s:system(clang_format, join(getline(1, '$'), "\n"))
endfunction
" }}}
" replace buffer {{{
function! clang_format#replace(line1, line2)
call s:verify_command()
let pos_save = getpos('.')
let sel_save = &l:selection
let &l:selection = "inclusive"
let [save_g_reg, save_g_regtype] = [getreg('g'), getregtype('g')]
try
let formatted = clang_format#format(a:line1, a:line2)
if s:success(formatted)
try
" Note:
" Replace current buffer with workaround not to move
" the cursor on undo (issue #8)
"
" The points are:
" - Do not touch the first line.
" - Use :put (p, P and :put! is not available).
"
" To meet above condition:
" - Delete all lines except for the first line.
" - Put formatted text except for the first line.
"
let i = stridx(formatted, "\n")
if i == -1 || getline(1) !=# formatted[:i-1]
throw "fallback"
endif
call setreg('g', formatted[i+1:], 'V')
undojoin | silent normal! 2gg"_dG
silent put g
catch
" Fallback:
" The previous way. It lets the cursor move to the first line
" on undo.
call setreg('g', formatted, 'V')
silent keepjumps normal! ggVG"gp
endtry
else
call s:error_message(formatted)
endif
finally
call setreg('g', save_g_reg, save_g_regtype)
let &l:selection = sel_save
call setpos('.', pos_save)
endtry
endfunction
" }}}
" auto formatting on insert leave {{{
let s:pos_on_insertenter = []
function! s:format_inserted_area()
let pos = getpos('.')
" When in the same buffer
if &modified && ! empty(s:pos_on_insertenter) && s:pos_on_insertenter[0] == pos[0]
call clang_format#replace(s:pos_on_insertenter[1], line('.'))
let s:pos_on_insertenter = []
endif
endfunction
function! clang_format#enable_format_on_insert()
augroup plugin-clang-format-auto-format-insert
autocmd!
autocmd InsertEnter <buffer> let s:pos_on_insertenter = getpos('.')
autocmd InsertLeave <buffer> call s:format_inserted_area()
augroup END
endfunction
" }}}
" toggle auto formatting {{{
function! clang_format#toggle_auto_format()
let g:clang_format#auto_format = !g:clang_format#auto_format
if g:clang_format#auto_format
echo "Auto clang-format: enabled"
else
echo "Auto clang-format: disabled"
endif
endfunction
" }}}
" enable auto formatting {{{
function! clang_format#enable_auto_format()
let g:clang_format#auto_format = 1
endfunction
" }}}
" disable auto formatting {{{
function! clang_format#disable_auto_format()
let g:clang_format#auto_format = 0
endfunction
" }}}
let &cpo = s:save_cpo
unlet s:save_cpo