lua.kak: more accurate "end" insertion

- Also insert "end" after "do", "else" and "elseif"
- Do not insert "end" after strings or comments containing keywords
- Only insert "end" if the block is empty

An example of the last item is if we want to add a new line to the start
of an unclosed block that already contains statements. @ is the cursor.

    -- before
    if a then@
        x = 1
        y = 2

    -- after
    if a then
        @
    end
        x = 1
        y = 2

In this case, inserting the "end" before the statements is probably not
what the programmer wants. It might make more sense to insert the "end"
after the statements, but that is potentially confusing due to spooky
action at a distance. I think the least confusing thing to do in this
situation is to not insert the "end".
This commit is contained in:
Hugo Musso Gualandi 2021-09-11 00:51:12 -03:00
parent 8755fc679e
commit aa1a280309

View File

@ -127,10 +127,21 @@ define-command -hidden lua-insert-on-new-line %[
try %[ execute-keys -draft k<a-x>s^\h*\K--\h*<ret> y gh j <a-x><semicolon> P ] try %[ execute-keys -draft k<a-x>s^\h*\K--\h*<ret> y gh j <a-x><semicolon> P ]
# wisely add end structure # wisely add end structure
evaluate-commands -save-regs x %[ evaluate-commands -save-regs x %[
try %[ execute-keys -draft k<a-x>s^\h+<ret>"xy ] catch %[ reg x '' ] # Save previous line indent in register x # save previous line indent in register x
try %[ execute-keys -draft k<a-x> <a-k>^<c-r>x\b[^\n]*(do|for|function|if|while)<ret><a-K>\bend\b<ret> J}iJ<a-x> <a-K>^<c-r>x(else|end|elseif)$<ret> # Validate previous line and that it is not closed yet try %[ execute-keys -draft k<a-x>s^\h+<ret>"xy ] catch %[ reg x '' ]
execute-keys -draft o<c-r>xend<esc> # auto insert end try %[
execute-keys -draft k<a-x><a-k>\(function\b<ret>jjA)<esc> ] # auto insert ) for anonymous function # check that starts with a block keyword that is not closed on the same line
execute-keys -draft \
k<a-x> \
<a-k>^\h*\b(else|elseif|do|for|function|if|while)\b|[^\n]\bfunction\b\h*[(]<ret> \
<a-K>\bend\b<ret>
# check that the block is empty and is not closed on a different line
execute-keys -draft <a-a>i <a-K>^[^\n]*\n[^\n]*\n<ret> j<a-x> <a-K>^<c-r>x\b(else|elseif|end)\b<ret>
# auto insert end
execute-keys -draft o<c-r>xend<esc>
# auto insert ) for anonymous function
execute-keys -draft k<a-x><a-k>\([^)\n]*function\b<ret>jjA)<esc>
]
] ]
] ]
] ]