Run a command on exit

I would like to run a program/script xyz on exiting a client, i.e. between doing :q and the actual exit. Now I do that by hand ( |xyz<Enter>) before exiting, but of course sometimes I forget.

In particular I would like it to be invoked only when kakoune runs in read-only mode, and the xyz already returns the exact input (so kakoune doesn’t complain when I do |xyz<Enter>.

A bonus would be when running the command at the end could be controlled from the kakoune commandline or by setting some environment variable. ( I realise that can be done with the -e option and some appropriate argument, I already use that to enable autoreload is some cases) But I can also deal with that in the xyz program based on that environment variable as well.

Is there some example of how to do this?

A few pointers.

If you look at :doc hooks, you will see a ClientClose hook that fires when the client closes. Also, in :doc options, there is a boolean readonly option that should tell you whether the current buffer is read-only.

You’ll probably need to write a custom command xyz that fires when this hook fires. In this command, there should be a shell block:

evaluate-commands %sh{

}

that looks for your shell’s environment variable, and executes further commands depending on its value.

Hope this helps.

1 Like

In addition, if your use-case is “generate some data, pipe to Kakoune to do some interactive editing or checking, then pipe to some consumer command”, you might be interested in the vipe command from the moreutils package. It reads stdin, writes it to a temporary file, invokes $EDITOR on the temporary file (with its stdin and stdout set to the controlling terminal, so it doesn’t mess up your pipeline). When the editor exits, it reads the temporary file and writes it to stdout again. So, your workflow would be:

generate-some-data | vipe | xyz

Alternatively, if you just have some edits to do that are easy to express in Kakoune’s editing language but difficult to express in (say) sed or awk, you can use Kakoune as a filter:

generate-some-data | kak -f KEYS | xyz

…where KEYS is some sequence of Kakoune editing commands (as you might pass to execute-keys), which starts with the whole buffer selected. When all the keys have been executed, the remaining buffer contents are written to stdout.

1 Like

That is not exactly my use case, but thanks for pointing out moretools. I have used its parallel program until I switched to Ole Tanges paralell` and had forgotten there were other useful tools in the moretool bag.

I don’t want to change the stream (hence the read-only), and I also don’t want to wait until all of stdin is there (which I don’t have to do as I start the client and make it auto-update), I essentially look at the stream as you would with more/less and then optionally select a part of that stream even if input might not have reached its end.