@@ -25,31 +25,35 @@ function! codefmt#jsbeautify#GetFormatter() abort
25
25
\ ' setup_instructions' : ' Install js-beautify ' .
26
26
\ ' (https://www.npmjs.com/package/js-beautify).' }
27
27
28
- function l: formatter .IsAvailable () abort
28
+ " Mapping of jsbeautify type to vim filetype name.
29
+ " TODO: Support jsx and other variants?
30
+ let l: formatter ._supported_formats = {
31
+ \ ' js' : [' javascript' , ' json' ],
32
+ \ ' css' : [' css' , ' sass' , ' scss' , ' less' ],
33
+ \ ' html' : [' html' ]}
34
+
35
+ function l: formatter .IsAvailable () dict abort
29
36
return executable (s: plugin .Flag (' js_beautify_executable' ))
30
37
endfunction
31
38
32
- function l: formatter .AppliesToBuffer () abort
33
- return &filetype is # ' css' || &filetype is # ' html' ||
34
- \ &filetype = ~# ' \mhtml\.' || &filetype is # ' json' ||
35
- \ &filetype is # ' javascript'
39
+ function l: formatter .AppliesToBuffer () dict abort
40
+ return self ._GetSupportedFormatName (&filetype ) isnot 0
36
41
endfunction
37
42
38
43
" "
39
44
" Reformat the current buffer with js-beautify or the binary named in
40
45
" @flag(js_beautify_executable), only targeting the range between {startline} and
41
46
" {endline}.
42
47
" @throws ShellError
43
- function l: formatter .FormatRange (startline, endline) abort
48
+ function l: formatter .FormatRange (startline, endline) dict abort
44
49
let l: cmd = [s: plugin .Flag (' js_beautify_executable' ), ' -f' , ' -' ]
45
- if &filetype is # ' javascript' || &filetype is # ' json'
46
- let l: cmd = l: cmd + [' --type' , ' js' ]
47
- elseif &filetype is # ' sass' || &filetype is # ' scss' || &filetype is # ' less'
48
- let l: cmd = l: cmd + [' --type' , ' css' ]
49
- elseif &filetype = ~# ' \mhtml\.'
50
- let l: cmd = l: cmd + [' --type' , ' html' ]
51
- elseif &filetype != " "
52
- let l: cmd = l: cmd + [' --type' , &filetype ]
50
+ " Add --type if known
51
+ if ! empty (&filetype )
52
+ let l: format_name = self ._GetSupportedFormatName (&filetype )
53
+ if l: format_name is 0
54
+ let l: format_name = &filetype
55
+ endif
56
+ let l: cmd += [' --type' , l: format_name ]
53
57
endif
54
58
55
59
call maktaba#ensure#IsNumber (a: startline )
@@ -61,6 +65,18 @@ function! codefmt#jsbeautify#GetFormatter() abort
61
65
\ a: startline , a: endline , l: cmd )
62
66
endfunction
63
67
68
+ function l: formatter ._GetSupportedFormatName (filetype ) dict abort
69
+ " Simplify compound filetypes like "html.mustache" down to just "html".
70
+ " TODO: Support other compound filetypes like "javascript.*" and "css.*"?
71
+ let l: filetype = substitute (a: filetype , ' \m^html\..*' , ' html' , ' ' )
72
+ for [l: format_name , l: filetypes ] in items (self ._supported_formats)
73
+ if index (l: filetypes , l: filetype ) >= 0
74
+ return l: format_name
75
+ endif
76
+ endfor
77
+ return 0
78
+ endfunction
79
+
64
80
return l: formatter
65
81
endfunction
66
82
0 commit comments