Skip to content

Commit b6699d3

Browse files
committed
Use vim's builtin format mapping
1 parent b5270ae commit b6699d3

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Diff for: autoload/codefmt.vim

+27
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,16 @@ function! codefmt#FormatMap(type) range abort
246246
call codefmt#FormatLines(line("'["), line("']"))
247247
endfunction
248248

249+
""
250+
" @public
251+
" To map the builtin |gq| command to invoke codefmt, set 'formatexpr' to call
252+
" this function. Example: >
253+
" set formatexpr=codefmt#FormatExpr()
254+
" <
255+
function! codefmt#FormatExpr() abort
256+
call codefmt#FormatLines(v:lnum, v:lnum + v:count)
257+
endfunction
258+
249259
""
250260
" Generate the completion for supported formatters. Lists available formatters
251261
" that apply to the current buffer first, then unavailable formatters that
@@ -260,6 +270,23 @@ function! codefmt#GetSupportedFormatters(ArgLead, CmdLine, CursorPos) abort
260270
return join(l:groups[0] + l:groups[1] + l:groups[2], "\n")
261271
endfunction
262272

273+
""
274+
" Returns whether there is a default formatter available for the current
275+
" buffer.
276+
function! codefmt#AvailableInCurrrentBuffer() abort
277+
let l:formatters = s:registry.GetExtensions()
278+
if !empty(get(b:, 'codefmt_formatter'))
279+
let l:Predicate = {f -> f.name ==# b:codefmt_formatter}
280+
else
281+
let l:Predicate = {f -> f.AppliesToBuffer() && s:IsAvailable(f)}
282+
endif
283+
for l:formatter in s:registry.GetExtensions()
284+
if l:Predicate(l:formatter)
285+
return 1
286+
endif
287+
endfor
288+
return 0
289+
endfunction
263290

264291
""
265292
" @private

Diff for: plugin/mappings.vim

+11
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)