From 82d99aa12b8bea66cd8751368181eaa1a39b160a Mon Sep 17 00:00:00 2001 From: Olivier Perret Date: Thu, 12 Sep 2019 16:05:24 +0200 Subject: [PATCH] Refactor formatter.kak The 'format' command is split into two, 'format-selections' and 'format-buffer' which relies on the former. --- rc/tools/formatter.kak | 55 ++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/rc/tools/formatter.kak b/rc/tools/formatter.kak index 40c384448..8795fb8de 100644 --- a/rc/tools/formatter.kak +++ b/rc/tools/formatter.kak @@ -1,31 +1,34 @@ -declare-option -docstring "shell command to which the contents of the current buffer is piped" \ +declare-option -docstring "shell command used for the 'format-selections' and 'format-buffer' commands" \ str formatcmd -define-command format -docstring "Format the contents of the current buffer" %{ evaluate-commands -draft -no-hooks %{ +define-command format-buffer -docstring "Format the contents of the buffer" %{ + evaluate-commands -draft %{ + execute-keys '%' + format-selections + } +} + +define-command format-selections -docstring "Format the selections individually" %{ evaluate-commands %sh{ - if [ -n "${kak_opt_formatcmd}" ]; then - path_file_tmp=$(mktemp "${TMPDIR:-/tmp}"/kak-formatter-XXXXXX) - printf %s\\n " - write -sync \"${path_file_tmp}\" - - evaluate-commands %sh{ - readonly path_file_out=\$(mktemp \"${TMPDIR:-/tmp}\"/kak-formatter-XXXXXX) - - if cat \"${path_file_tmp}\" | eval \"${kak_opt_formatcmd}\" > \"\${path_file_out}\"; then - printf '%s\\n' \"execute-keys \\%|cat'\${path_file_out}'\" - printf '%s\\n' \"nop %sh{ rm -f '\${path_file_out}' }\" - else - printf '%s\\n' \" - evaluate-commands -client '${kak_client}' echo -markup '{Error}formatter returned an error (\$?)' - \" - rm -f \"\${path_file_out}\" - fi - - rm -f \"${path_file_tmp}\" - } - " - else - printf '%s\n' "evaluate-commands -client '${kak_client}' echo -markup '{Error}formatcmd option not specified'" + if [ -z "${kak_opt_formatcmd}" ]; then + printf "fail 'The option ''formatcmd'' must be set'" fi } -} } + evaluate-commands -draft -no-hooks -save-regs '|' %{ + set-register '|' %{ + format_in="$(mktemp "${TMPDIR:-/tmp}"/kak-formatter-XXXXXX)" + format_out="$(mktemp "${TMPDIR:-/tmp}"/kak-formatter-XXXXXX)" + + cat > "$format_in" + eval "$kak_opt_formatcmd" < "$format_in" > "$format_out" + if [ $? -eq 0 ]; then + cat "$format_out" + else + printf 'eval -client %s %%{ echo -markup %%{{Error}formatter returned an error %s} }' "$kak_client" "$?" | kak -p "$kak_session" + cat "$format_in" + fi + rm -f "$format_in" "$format_out" + } + execute-keys '|' + } +}