Kakoune Client Server

Today I deployed a variation on the “1 session per project” implementation from the Kakoune wiki. My version of the script is called kak-cs and looks like this:

#!/bin/sh

dir="${1:-$(pwd)}"
shift 0${1:+1}

test -d "${dir}" || dir="$(dirname "${dir}")"
dir="$(git -C "${dir}" rev-parse --show-toplevel)"

cd "${dir}"

if test "$(pwd)" = "${HOME}"
then
  server_name='HOME'
else
  server_name="$(basename "${dir}" | sed 's#[./]#-#g')"
fi

socket_file="$(kak -l | grep "^${server_name}\$")"

if test "${socket_file}" = ""
then
  setsid kak -d -s "${server_name}" &
fi

while true
do
  kak -l | grep -q "^${server_name}$" && break
done

kak -c "${server_name}" ${1:+-e "$@"}

This takes an optional path as first argument and finds its directory, using the current working directory by default. Then it looks for the topmost git repository that contains the given directory. The basename of this git repo directory is the project name. Start a server for the project if one does not already exist, and then start a new client connecting to the project server.

The unfortunate while true loop ensures that the server is running before the client attempts to connect. There should be a better way.

I use this in tmux context with user-mode key bindings to launch the new client in a horizontal or vertical split of the current pane, or in a new window.

Obviously it assumes that all of my projects reside in git repos, including my home directory, all of which happens to be true.

This will probably require some hooks to handle the close of the last client and make sure that a clientless server isn’t holding unsaved changes. But that’s for another TIL.