1# Autoformatting Module
2# Provides utilities to make managing filetype-based autoformatters easier
3# Usage example:
4# autofmt-register rust rustfmt
5
6define-command -docstring %{
7 autofmt-register <filetype> <formatcmd>: Register <formatcmd> as the formatter for <filetype>. Will be automatically enabled and disabled.
8} -params 2 \
9autofmt-register %{
10 declare-option str "formatcmd_%arg{1}" "%arg{2}"
11 hook -group "autofmt-%arg{1}" global WinSetOption "filetype=%arg{1}" %{
12 autofmt-enable
13 }
14}
15
16define-command -docstring %{
17 autofmt-unregister <filetype>: don't automatically enable autoformatting for <filetype>
18} -params 1 autofmt-unregister %{
19 remove-hooks global "autofmt-%arg{1}"
20}
21
22define-command -docstring %{
23 autofmt-disable: Disable registered formatter for this filetype, for this window
24} autofmt-disable %{
25 unset-option window formatcmd
26 remove-hooks window "autofmt-%opt{filetype}"
27}
28
29define-command -docstring %{
30 autofmt-enable: Enable registered formatter for this filetype, for this window
31} autofmt-enable %{
32 evaluate-commands "set-option window formatcmd %%opt{formatcmd_%opt{filetype}}"
33 hook -group "autofmt-%opt{filetype}" window BufWritePre .* %{
34 try format-buffer
35 }
36 hook -group "autofmt-%opt{filetype}" -once -always window WinSetOption filetype=.* %{
37 autofmt-disable
38 }
39}
40
41hook global ModuleLoaded kak %{
42 add-highlighter shared/kakrc/code/autofmt regex (?:\s|\A)\Kautofmt-((en|dis)able|(un)?register)(?:(?=\s)|\z) 0:keyword
43}
44