18.4.2025

Just spent another few hours trying to get neovim server working in kitty with split mode editting. Eventually I set it up via sending text to kitty windows instead of using neovim server. But anyway, I learned some interesting commands worth recording

FILE="$1"
LINE="${2+$2G}"
COLUMN="${3+$3|}"
POSITION="${LINE}${COLUMN}"

KITTY_OS_WINDOW=`kitty @ ls -m state:self | jq '.[0].id'`
KITTY_TAB=`kitty @ ls -t recent:0 | jq '.[0].tabs[0].id'`
KITTY_WINDOW=`kitty @ ls -m state:self | jq '.[0].tabs[0].windows[0].id'`

# # Check if this is the only window and if yes, split it
# COUNT=$(kitty @ ls | jq '.[] | select(.is_active == true).tabs[] | select(.is_active == true).windows | length')
# if [ "$COUNT" -eq 1 ]; then
#   kitty @ launch --keep-focus --cwd=current
# fi

# Check if neovim server socket exists
NVIM_WINDOW="$HOME/.cache/nvim/server.window.${KITTY_TAB}"
NVIM_SOCKET="$HOME/.cache/nvim/server.socket.${KITTY_TAB}"
if [ -S "$NVIM_SOCKET" ]; then
  # Edit in remote neovim
  if [ $# -gt 0 ]; then
    nvim --server "$NVIM_SOCKET" --silent --remote-send "<C-\><C-N>:cd $PWD<CR>:e $FILE<CR>"
  fi
  # Focus on the editor window
  kitty @ focus-window --match id:`cat "$NVIM_WINDOW"`
else
  # Start neovim server
  nvim --listen "$NVIM_SOCKET"
  echo "$KITTY_WINDOW" > "$NVIM_WINDOW"
fi

And how the final script that I ended up using

#!/usr/bin/env zsh
set -x
# vim:fileencoding=utf-8:foldmethod=marker
#------------------------------------------------------------------------------
#
# Script to split screen, change current working directory, and open a file
#
#------------------------------------------------------------------------------
if [ "$TERM" != "xterm-kitty" ]; then
  nvim "$@"
  exit
fi

# Set FILE_NAME LINE and COLUMN variables from "pat/to/file:12345:23"
IFS=":" read -r FILE_NAME LINE COLUMN <<< "$1"
kitty @ focus-window --match title:'Nvim$' 2> /dev/null
if [ "$?" -gt 0 ]; then
  if [ -z "$FILE_NAME" ]; then
    WINDOW=`kitty @ launch --keep-focus --cwd=current --location first zsh -c nvim`
  else
    WINDOW=`kitty @ launch --keep-focus --cwd=current --location first zsh -c "nvim \"$FILE_NAME\""`
    if [ -n "$LINE" ]; then
      kitty @ send-text --match id:$WINDOW ":$LINE
"
    fi
  fi
  kitty @ focus-window --match id:$WINDOW
  exit
fi
if [ -n "$FILE_NAME" ]; then
  kitty @ send-text --match title:'Nvim$' ":enew
:lcd $PWD
:e $FILE_NAME
"
  if [ -n "$LINE" ]; then
    kitty @ send-text --match title:'Nvim$' ":$LINE
"
  fi
fi