From 6376aa6206aefb408fef75ecfb21648418656301 Mon Sep 17 00:00:00 2001 From: Frank LENORMAND Date: Fri, 23 Jun 2017 15:09:18 +0300 Subject: [PATCH] rc formatter: Make sure the formatter returned successfully The previous implementation used to replace the contents of the buffer with whatever the `formatcmd` was returning, regardless of the exit code of the command, which led to the buffer being wiped out on error. This commit does the formatting in a temporary file, and only replaces the current buffer with the contents of the -formatted- temporary file if the `formatcmd` returned successfully. Fixes #1357 --- rc/core/formatter.kak | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/rc/core/formatter.kak b/rc/core/formatter.kak index 46bb0661..c776e637 100644 --- a/rc/core/formatter.kak +++ b/rc/core/formatter.kak @@ -1,17 +1,35 @@ decl -docstring "shell command to which the contents of the current buffer is piped" \ str formatcmd -def format -docstring "Format the contents of the current buffer" %{ +def format -docstring "Format the contents of the current buffer" %{ eval -draft %{ %sh{ - if [ ! -z "${kak_opt_formatcmd}" ]; then - readonly kak_opt_formatcmd=$(printf '%s' "${kak_opt_formatcmd}" | sed 's/ //g') + if [ -n "${kak_opt_formatcmd}" ]; then ## Save the current position of the cursor readonly x=$((kak_cursor_column - 1)) readonly y="${kak_cursor_line}" - printf %s\\n "exec -draft %{%|${kak_opt_formatcmd}}" - ## Try to restore the position of the cursor as it was prior to formatting - printf %s\\n "exec gg ${y}g ${x}l" + path_file_tmp=$(mktemp "${TMPDIR:-/tmp}"/kak-formatter-XXXXXX) + printf %s\\n " + write \"${path_file_tmp}\" + + %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' \"exec \\%|cat'\${path_file_out}'\" + printf '%s\\n' \"%sh{ rm -f '\${path_file_out}' }\" + ## Try to restore the position of the cursor as it was prior to formatting + printf '%s\\n' 'exec gg ${y}g ${x}l' + else + printf '%s\\n' \" + eval -client '${kak_client}' echo -color Error formatter returned an error (\$?) + \" + rm -f \"\${path_file_out}\" + fi + + rm -f \"${path_file_tmp}\" + } + " fi } -} +} }