From 8755fc679e265727ed5cb858c156dfdba51ae718 Mon Sep 17 00:00:00 2001 From: Hugo Musso Gualandi Date: Fri, 10 Sep 2021 01:43:59 -0300 Subject: [PATCH] lua.kak: improve the indentation logic This commit makes several improvements to the Lua indentation logic. - Don't indent if the keyword is inside a string or comment - Indent inside "do end" - Indent inside "repeat until" - Indent after a line ending with "{" or "(" - More accurate un-indentation for the "end" keyword For the last point, previously we tried to match the indentation of the starting keyword of the block. However, sometimes this guessed wrong and produced the wrong indentation, as the following example shows. The new logic is to indent the "end" by one less level than the contents of the block. while true do if false then end end -- This was incorrectly matched with the "if" --- rc/filetype/lua.kak | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/rc/filetype/lua.kak b/rc/filetype/lua.kak index cb0775b5..d0227a7a 100644 --- a/rc/filetype/lua.kak +++ b/rc/filetype/lua.kak @@ -92,9 +92,12 @@ define-command -hidden lua-trim-indent %[ define-command -hidden lua-indent-on-char %[ evaluate-commands -no-hooks -draft -itersel %[ - # align middle and end structures to start and indent when necessary, elseif is already covered by else - try %[ execute-keys -draft ^\h*(else)$^\h*(if)s\A|.\z) ] - try %[ execute-keys -draft ^\h*(end)$^\h*(for|function|if|while)s\A|.\z) ] + # unindent middle and end structures + try %[ execute-keys -draft \ + ^\h*(\b(end|else|elseif|until)\b|[)}])$ \ + :lua-indent-on-new-line \ + + ] ] ] @@ -103,9 +106,18 @@ define-command -hidden lua-indent-on-new-line %[ # remove trailing white spaces from previous line try %[ execute-keys -draft k : lua-trim-indent ] # preserve previous non-empty line indent - try %[ execute-keys -draft ^[^\n]+$s\A|.\z) ] - # indent after start structure - try %[ execute-keys -draft ^[^\n]*\w+[^\n]*$\b(else|elseif|for|function|if|while)\b\bend\b ] + try %[ execute-keys -draft gh^[^\n]+$s\A|.\z) ] + # add one indentation level if the previous line is not a comment and: + # - starts with a block keyword that is not closed on the same line, + # - or contains an unclosed function expression, + # - or ends with an enclosed '(' or '{' + try %[ execute-keys -draft \ + K \ + \A\h*-- \ + \A[^\n]*\b(end|until)\b \ + \A(\h*\b(do|else|elseif|for|function|if|repeat|while)\b|[^\n]*[({]$|[^\n]*\bfunction\b\h*[(]) \ + + ] ] ]