Skip to content

Commit 004f72a

Browse files
committed
Use vim's builtin format mapping
1 parent 0de948c commit 004f72a

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

autoload/codefmt.vim

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,16 @@ function! codefmt#FormatMap(type) range abort
238238
call codefmt#FormatLines(line("'["), line("']"))
239239
endfunction
240240

241+
""
242+
" @public
243+
" To map the builtin |gq| command to invoke codefmt, set 'formatexpr' to call
244+
" this function. Example: >
245+
" set formatexpr=codefmt#FormatExpr()
246+
" <
247+
function! codefmt#FormatExpr() abort
248+
call codefmt#FormatLines(v:lnum, v:lnum + v:count)
249+
endfunction
250+
241251
""
242252
" Generate the completion for supported formatters. Lists available formatters
243253
" that apply to the current buffer first, then unavailable formatters that
@@ -252,6 +262,23 @@ function! codefmt#GetSupportedFormatters(ArgLead, CmdLine, CursorPos) abort
252262
return join(l:groups[0] + l:groups[1] + l:groups[2], "\n")
253263
endfunction
254264

265+
""
266+
" Returns whether there is a default formatter available for the current
267+
" buffer.
268+
function! codefmt#AvailableInCurrrentBuffer() abort
269+
let l:formatters = s:registry.GetExtensions()
270+
if !empty(get(b:, 'codefmt_formatter'))
271+
let l:Predicate = {f -> f.name ==# b:codefmt_formatter}
272+
else
273+
let l:Predicate = {f -> f.AppliesToBuffer() && s:IsAvailable(f)}
274+
endif
275+
for l:formatter in s:registry.GetExtensions()
276+
if l:Predicate(l:formatter)
277+
return 1
278+
endif
279+
endfor
280+
return 0
281+
endfunction
255282

256283
""
257284
" @private

plugin/mappings.vim

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,14 @@ execute 'nnoremap <unique> <silent>' s:prefix . '=' ':FormatLines<CR>'
5959
" Format the visually selected region using the formatter associated with the
6060
" current buffer.
6161
execute 'vnoremap <unique> <silent>' s:prefix ':FormatLines<CR>'
62+
63+
function! s:SetFormatExpr() abort
64+
if codefmt#AvailableInCurrrentBuffer()
65+
setlocal formatexpr=codefmt#FormatExpr()
66+
endif
67+
endfunction
68+
69+
augroup codefmt_formatexpr
70+
autocmd!
71+
autocmd BufEnter * call <SID>SetFormatExpr()
72+
augroup END

0 commit comments

Comments
 (0)