|
| 1 | +let s:plugin = maktaba#plugin#Get('codefmt') |
| 2 | + |
| 3 | + |
| 4 | +"" |
| 5 | +" @private |
| 6 | +" |
| 7 | +" Formatter provider for lua files using stylua. |
| 8 | +function! codefmt#stylua#GetFormatter() abort |
| 9 | + let l:formatter = { |
| 10 | + \ 'name': 'stylua', |
| 11 | + \ 'setup_instructions': 'Install stylua (https://github.com/JohnnyMorganz/StyLua).'} |
| 12 | + |
| 13 | + function l:formatter.IsAvailable() abort |
| 14 | + return executable(s:plugin.Flag('stylua_executable')) |
| 15 | + endfunction |
| 16 | + |
| 17 | + function l:formatter.AppliesToBuffer() abort |
| 18 | + return codefmt#formatterhelpers#FiletypeMatches(&filetype, 'lua') |
| 19 | + endfunction |
| 20 | + |
| 21 | + "" |
| 22 | + " Reformat the current buffer with stylua or the binary named in |
| 23 | + " @flag(stylua_executable) |
| 24 | + " @throws ShellError |
| 25 | + function l:formatter.Format() abort |
| 26 | + let l:cmd = [s:plugin.Flag('stylua_executable')] |
| 27 | + " Specify we are sending input through stdin |
| 28 | + let l:cmd += ['--stdin-filepath', expand('%:p'), '-'] |
| 29 | + |
| 30 | + try |
| 31 | + call codefmt#formatterhelpers#Format(l:cmd) |
| 32 | + catch |
| 33 | + " Parse all the errors and stick them in the quickfix list. |
| 34 | + let l:errors = [] |
| 35 | + for line in split(v:exception, "\n") |
| 36 | + let l:fname_pattern = 'stdin' |
| 37 | + let l:tokens = matchlist(line, '\C\v^\[string "isCodeValid"\]:(\d+): (.*)') |
| 38 | + if !empty(l:tokens) |
| 39 | + call add(l:errors, { |
| 40 | + \ "filename": @%, |
| 41 | + \ "lnum": l:tokens[1], |
| 42 | + \ "text": l:tokens[2]}) |
| 43 | + endif |
| 44 | + endfor |
| 45 | + |
| 46 | + if empty(l:errors) |
| 47 | + " Couldn't parse stylua error format; display it all. |
| 48 | + call maktaba#error#Shout('Error formatting file: %s', v:exception) |
| 49 | + else |
| 50 | + call setqflist(l:errors, 'r') |
| 51 | + cc 1 |
| 52 | + endif |
| 53 | + endtry |
| 54 | + endfunction |
| 55 | + |
| 56 | + return l:formatter |
| 57 | +endfunction |
0 commit comments