From 311cd9042e5d22ce52980d02ade6b8c7e6152cd8 Mon Sep 17 00:00:00 2001
From: Daniel Lundin <dln@arity.se>
Date: Thu, 2 Jan 2025 10:55:43 +0100
Subject: [PATCH] nvim: wrapper script for persistent+remote control

---
 home/common/fish.nix         |  2 +-
 home/common/ghostty.nix      |  5 ++++-
 home/common/nvim/default.nix | 12 ++++++++++++
 3 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/home/common/fish.nix b/home/common/fish.nix
index 5fd6a55..253c701 100644
--- a/home/common/fish.nix
+++ b/home/common/fish.nix
@@ -53,7 +53,7 @@
         description = "Open a file in already running nvim";
         argumentNames = [ "file" ];
         body = ''
-          nvim --server "$XDG_RUNTIME_DIR/nvim-persistent.sock" --remote (readlink -f "$file")
+          nvim-remote --remote (readlink -f "$file")
         '';
       };
 
diff --git a/home/common/ghostty.nix b/home/common/ghostty.nix
index 7db5cca..60174c8 100644
--- a/home/common/ghostty.nix
+++ b/home/common/ghostty.nix
@@ -33,6 +33,7 @@
         unfocused-split-opacity = 1.0;
 
         shell-integration = "fish";
+        initial-command = "nvim-remote";
 
         window-decoration = true;
         gtk-single-instance = true;
@@ -112,7 +113,9 @@
           "System"
           "TerminalEmulator"
         ];
-        exec = ''ghostty --class=com.mitchellh.ghostty-nemo --command="ssh -t nemo"'';
+        exec = ''
+        ghostty --class=com.mitchellh.ghostty-nemo --command="ssh -t nemo" --initial-command="ssh -t nemo nvim-remote"
+        '';
         genericName = "Ghostty (nemo)";
         icon = "com.mitchellh.ghostty";
         name = "Ghostty (nemo)";
diff --git a/home/common/nvim/default.nix b/home/common/nvim/default.nix
index 2731261..a67f7e3 100644
--- a/home/common/nvim/default.nix
+++ b/home/common/nvim/default.nix
@@ -4,11 +4,23 @@
   pkgs,
   ...
 }:
+let
+  nvim-remote = pkgs.writeShellApplication {
+    name = "nvim-remote";
+    text = ''
+      _sess=$(echo -n "$USER@''${SSH_CONNECTION:-$HOSTNAME}" | tr -c '[:alnum:]@.' '_')
+      _nvim_sock="''${XDG_RUNTIME_DIR:-/tmp}/nvim.$_sess.sock"
+      exec nvim --listen "$_nvim_sock" --server "$_nvim_sock" "$@"
+    '';
+  };
+in
 {
   imports = [
     ./treesitter.nix
   ];
 
+  home.packages = [ nvim-remote ];
+
   programs.man.generateCaches = false;
 
   programs.neovim = {