sh-block-fmt.kak

· ficd's pastes · raw

expires: 2025-10-30

 1define-command -docstring %{
 2    Format selection with shfmt -p, keeping whitespace prefix.
 3} \
 4shfmt %{
 5    evaluate-commands -save-regs | %{
 6        set-register | %{
 7            input=$(cat)
 8            prefix=$(printf '%s\n' "$input" | head -n1 | grep -o '^[[:space:]]*')
 9            printf '%s\n' "$input" | \
10            	perl -pe "s/^\Q$prefix\E//" | \
11            	shfmt -p | \
12            	sed "s/^/$prefix/"
13	}
14        execute-keys '|<ret>'
15    }
16}
17
18define-command -hidden sh-object-outer %~
19    execute-keys '<a-/>%sh[{([<lt>]<ret>M'
20~
21
22define-command -hidden sh-object-inner %{
23    execute-keys ':sh-object-outer<ret><a-:>K<a-;>Jx<a-:>'
24}
25
26define-command -docstring 'format %sh blocks in kakscript' sh-kak-shfmt %{
27    execute-keys -itersel -draft '<a-i><a-;>sh-object-wrap<ret>:shfmt<ret>'
28}
29
30map global object <a-s> '<a-;>sh-object-wrap<ret>' -docstring 'shell block'
31try %{ declare-user-mode kak }
32map global kak = ':sh-kak-shfmt<ret>' -docstring 'format current sh block'