Macro ring

Macros are nice. They have one disadvantage tho - you need to remember to record them.

I had an idea - I can record every key pressed into “ring buffer” and interactively choose last n keys to use as a macro. So I hacked this POC

provide-module qring %£

declare-option str-list qring_keys

define-command qring-enable %{
    hook -group qring global RawKey .* %{
        set-option -add global qring_keys "%val{hook_param}"
    }

    hook -group qring global InsertIdle .* %{
        qring-trim
    }

    hook -group qring global NormalIdle .* %{
        qring-trim
    }
}

define-command qring-disable %{
    remove-hooks global qring
}

define-command qring-show -params 0..1 %{
    qring-disable
    try %{ delete-buffer! *qring* }
    evaluate-commands -save-regs dquote %{
        edit -scratch *qring*
        set-register dquote %opt{qring_keys}
        execute-keys "<a-p>i<ret><esc><space>;ge"
        unmap buffer normal q
        unmap buffer normal Q
        map buffer normal q ': qring-cancel<ret>'
        map buffer normal Q ': qring-accept<ret>'
    }
}

define-command -hidden qring-cancel %{
    evaluate-commands %{
        delete-buffer!
        qring-enable
    }
}

define-command -hidden qring-accept %{
    evaluate-commands %
        set-register '@' %sh{ echo $kak_selections | tr -d ' ' }
        delete-buffer!
        qring-enable
    }
}

define-command -hidden qring-trim %{
    nop %sh{
        (
            eval "set -- $kak_quoted_opt_qring_keys"
            if [ $# -gt 100 ]
            then
                shift $(($# - 100))
            fi
            echo set-option global qring_keys $@ | kak -p "$kak_session"
        ) > /dev/null 2>&1 < /dev/null &
    }
}

£

Usage

Map qring-show to Q in normal mode (or other key, whatever). Enable plugin with qring-enable.

When you do some awesome key combo you want to record as a macro use qring-show mapping. Select all keys you are interested in and press Q. Press q to cancel.

Possible future improvements

  • filter out mouse events and other weird keys
  • disable when entering prompt?
  • trim key combination mapped to qring-show from the bottom of *qring* buffer
  • trim without calling shell? (how?)

WDYT?

7 Likes

That’s pretty awesome. One idea I think would be a great extension to this is to save those n keys into a separate buffer(or even a file), essentially allowing you to generate commands on the fly. It allows you to perform repetitive but simple command chains when necessary, and makes it easy to actually save that if you find yourself doing it often.

an example of this was when I was testing out turning pasted csv contents into an sql database using sql alchemy in python. I wound up doing the same actions repeatedly(across a few files), but never needed it outside of that one use case

Well qring-show opens keys in scratch *qring* buffer, you can actually edit it and save somewhere