diff --git a/docs/reference/tmux.md b/docs/reference/tmux.md index 5c3c9e6..b03dd8d 100644 --- a/docs/reference/tmux.md +++ b/docs/reference/tmux.md @@ -1,31 +1,90 @@ -# 🪟 Tmux Reference & Workflow +# 🪟 Terminal Workspaces & Tmux Reference -This document describes the Tmux terminal multiplexer configuration declared in `home/shell.nix` and `home/config/tmux.conf`. +This reference covers the operational controls, keybindings, and workflows for persistent workspaces and terminal multiplexing on the `laptop` workstation. --- -## 1. Core Configuration +## 1. Terminal Workflows -- **Prefix Key**: `Ctrl+Space` (`C-Space`, remapped from standard `Ctrl+B`). +| Shortcut | Action | Semantics | +| :--- | :--- | :--- | +| `Mod+Return` | **Alacritty Shell** | Opens a standard shell immediately. Ephemeral, isolated, non-persistent. | +| `Mod+T` | **Workspace Selector** | Opens Alacritty running the interactive sessionizer (`ts`). Exiting `fzf` with `Esc` closes the window cleanly. | + +--- + +## 2. Sessionizer CLI (`ts`) + +The `ts` utility (`tmux-sessionizer`) connects directly to persistent tmux workspaces: + +```bash +# Interactive fuzzy selector (shows session name and path) +ts + +# Open a workspace by name (exact or normalized) +ts config +ts brain +ts core +ts bitetrack-api + +# Open a workspace by unique substring +ts magnet # Resolves to MagNetFlix + +# Open a workspace by direct filesystem path +ts ~/Config +ts ~/Projects/active/nekoweb +``` + +### Argument Resolution Order +When an argument is provided (`ts `), it resolves in this exact order: +1. **Existing directory**: Canonicalizes path via `realpath`. +2. **Exact session name**: Matches normalized session name. +3. **Exact directory basename**: Matches directory name. +4. **Unique substring**: Matches against names and paths. + +*Ambiguous matches fail safely with an error and candidate list rather than guessing.* + +--- + +## 3. Workspace Discovery + +The sessionizer automatically indexes workspaces from: + +- **Explicit Workspaces**: + - `~/Config` + - `~/Brain` + - `~/Homelab/Core` +- **Git Repositories**: + - Discovered beneath `~/Projects` and `~/Homelab` (depth 4). + +*Any directory passed directly as a path (`ts `) works immediately without needing to be under discovery roots.* + +--- + +## 4. Tmux Behavior & Persistence + +- **Outside Tmux**: Running `ts` creates or attaches to the session. +- **Inside Tmux**: Running `ts` switches the active client (`switch-client`) without nesting sessions. +- **Session State**: New sessions start in the workspace folder. Reconnecting to an existing session preserves your current working directory, open files, and terminal buffers. +- **Persistence**: Closing an Alacritty window leaves background jobs and tmux sessions running. Reconnect at any time by pressing `Mod+T` or running `ts `. + +--- + +## 5. Tmux Controls & Keybindings + +- **Prefix Key**: `Ctrl+Space` (`C-Space`) - **Terminal Capabilities**: TrueColor (`tmux-256color`) with RGB support and extended keys enabled. - **Mouse Support**: Enabled for scrolling, pane selection, and resizing. -- **Base Index**: Windows and panes start at index `1` (matching keyboard row `1..9`). -- **Escape Time**: `0ms` (zero delay for responsive escape-key behavior in Vim/Neovim). -- **Clipboard**: OSC 52 integration enabled (`set -s set-clipboard on`), syncing clipboard locally and over SSH. - ---- - -## 2. Keybindings & Controls ### Smart Neovim / Tmux Navigation (No Prefix Required) -Thanks to `vim-tmux-navigator` integration, you can navigate seamlessly between Vim splits and Tmux panes without pressing the prefix key: +Navigate between Neovim splits and Tmux panes seamlessly using `Ctrl+h/j/k/l`: | Shortcut | Action | | :--- | :--- | -| `Ctrl+h` | Move to left pane / Vim split. | -| `Ctrl+j` | Move to down pane / Vim split. | -| `Ctrl+k` | Move to up pane / Vim split. | -| `Ctrl+l` | Move to right pane / Vim split. | +| `Ctrl+h` | Move to left pane / Neovim split. | +| `Ctrl+j` | Move to down pane / Neovim split. | +| `Ctrl+k` | Move to up pane / Neovim split. | +| `Ctrl+l` | Move to right pane / Neovim split. | *(Fallback navigation using prefix: `Ctrl+Space h/j/k/l`)* @@ -58,15 +117,14 @@ Thanks to `vim-tmux-navigator` integration, you can navigate seamlessly between --- -## 3. Persistent Sessions +## 6. Verification Commands ```bash -# Attach or create session named "dev": -tmux new-session -A -s dev +# Validate flake metadata & checks +nix flake check -# List active sessions: -tmux ls - -# Detach from active session: -Ctrl+Space d +# Build laptop configuration without switching +nix build .#nixosConfigurations.laptop.config.system.build.toplevel --no-link ``` + +*(For architectural background, boundary models, and design principles, see `Brain/records/decisions/terminal-workspace-architecture.md`)*. diff --git a/home/config/niri/custom.kdl b/home/config/niri/custom.kdl index b4bdbd3..5be8462 100644 --- a/home/config/niri/custom.kdl +++ b/home/config/niri/custom.kdl @@ -4,9 +4,10 @@ binds { // === Core Application Launchers === - Mod+Return hotkey-overlay-title="Alacritty Terminal" { spawn "alacritty"; } - Mod+B hotkey-overlay-title="Firefox Browser" { spawn "firefox"; } - Mod+O hotkey-overlay-title="Obsidian Notes" { spawn "flatpak" "run" "md.obsidian.Obsidian"; } + Mod+Return hotkey-overlay-title="Alacritty Terminal (Shell)" { spawn "alacritty"; } + Mod+T hotkey-overlay-title="Workspace Terminal (Sessionizer)" { spawn "alacritty" "-e" "tmux-sessionizer"; } + Mod+B hotkey-overlay-title="Firefox Browser" { spawn "firefox"; } + Mod+O hotkey-overlay-title="Obsidian Notes" { spawn "flatpak" "run" "md.obsidian.Obsidian"; } // === Active Window Management === // Force kill active window process via Niri IPC (JSON parsed) diff --git a/home/scripts/tmux-sessionizer.sh b/home/scripts/tmux-sessionizer.sh new file mode 100644 index 0000000..05c3484 --- /dev/null +++ b/home/scripts/tmux-sessionizer.sh @@ -0,0 +1,187 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Declarative workspace roots +EXPLICIT_WORKSPACES=( + "$HOME/Config" + "$HOME/Brain" + "$HOME/Homelab/Core" +) + +DISCOVERY_ROOTS=( + "$HOME/Projects" + "$HOME/Homelab" +) + +# Normalize folder basename to a valid, deterministic tmux session name +normalize_name() { + local raw="$1" + local name + name=$(basename "$raw" | tr '[:upper:]' '[:lower:]' | sed -E 's/[ .]+/-/g; s/[^a-z0-9_-]//g; s/[-_]+$//') + if [[ -z "$name" ]]; then + echo "ERROR: normalized session name for '$raw' is empty" >&2 + return 1 + fi + echo "$name" +} + +# Discover all registered and git-backed workspaces +# Outputs tab-separated: \t +get_projects() { + local -A seen_paths=() + + # 1. Explicit workspaces + for ws in "${EXPLICIT_WORKSPACES[@]}"; do + if [[ -d "$ws" ]]; then + seen_paths["$ws"]=1 + fi + done + + # 2. Discovered git repos under existing roots + for root in "${DISCOVERY_ROOTS[@]}"; do + [[ -d "$root" ]] || continue + while IFS= read -r gitdir; do + local pdir + pdir=$(dirname "$gitdir") + seen_paths["$pdir"]=1 + done < <(fd -H -d 4 -t d '^\.git$' "$root" 2>/dev/null) + done + + # 3. Format output + for dir in "${!seen_paths[@]}"; do + local sname + if sname=$(normalize_name "$dir" 2>/dev/null); then + printf "%s\t%s\n" "$sname" "$dir" + fi + done | sort -k1,1 +} + +# Ensure the workspace registry has zero session-name collisions +validate_registry() { + local registry="$1" + local collisions + collisions=$(printf "%s\n" "$registry" | awk -F'\t' ' + { + count[$1]++ + paths[$1] = paths[$1] "\n " $2 + } + END { + for (s in count) { + if (count[s] > 1) { + printf "ERROR: workspace name collision: '\''%s'\''%s\n\n", s, paths[s] + } + } + } + ') + + if [[ -n "$collisions" ]]; then + printf "%s" "$collisions" >&2 + return 1 + fi + return 0 +} + +# Resolve target directory and session name from arguments or interactive selection +resolve_workspace() { + local projects + projects=$(get_projects) + validate_registry "$projects" || exit 1 + + if [[ $# -eq 0 ]]; then + local selected + selected=$(printf "%s\n" "$projects" | fzf \ + --delimiter=$'\t' \ + --with-nth=1,2 \ + --prompt="Workspace > " \ + --height=40% \ + --reverse || true) + + if [[ -z "$selected" ]]; then + exit 0 + fi + + echo "$selected" + return 0 + fi + + local query="$1" + + # 1. Existing directory path + if [[ -d "$query" ]]; then + local abs_path sname + abs_path=$(realpath "$query") + sname=$(normalize_name "$abs_path") || exit 1 + printf "%s\t%s\n" "$sname" "$abs_path" + return 0 + fi + + # 2. Exact session name match + local exact exact_cnt + exact=$(printf "%s\n" "$projects" | awk -F'\t' -v q="$query" 'tolower($1) == tolower(q)') + exact_cnt=$(printf "%s\n" "$exact" | grep -c -v "^$" || true) + if [[ "$exact_cnt" -eq 1 ]]; then + echo "$exact" + return 0 + fi + + # 3. Exact basename match + local base_matches base_cnt query_base + query_base=$(basename "$query" | tr '[:upper:]' '[:lower:]') + base_matches=$(printf "%s\n" "$projects" | awk -F'\t' -v q="$query_base" ' + { + n = split($2, parts, "/") + if (tolower(parts[n]) == q) print $0 + } + ') + base_cnt=$(printf "%s\n" "$base_matches" | grep -c -v "^$" || true) + if [[ "$base_cnt" -eq 1 ]]; then + echo "$base_matches" + return 0 + elif [[ "$base_cnt" -gt 1 ]]; then + echo "ERROR: ambiguous project basename '$query':" >&2 + printf "%s\n" "$base_matches" | awk -F'\t' '{print " " $2}' >&2 + exit 1 + fi + + # 4. Unique Substring Match + local sub_matches sub_cnt query_lower + query_lower=$(echo "$query" | tr '[:upper:]' '[:lower:]') + sub_matches=$(printf "%s\n" "$projects" | awk -F'\t' -v q="$query_lower" ' + index(tolower($1), q) || index(tolower($2), q) + ') + sub_cnt=$(printf "%s\n" "$sub_matches" | grep -c -v "^$" || true) + if [[ "$sub_cnt" -eq 1 ]]; then + echo "$sub_matches" + return 0 + elif [[ "$sub_cnt" -gt 1 ]]; then + echo "ERROR: ambiguous match for '$query' (multiple candidates found):" >&2 + printf "%s\n" "$sub_matches" | awk -F'\t' '{printf " %-20s %s\n", $1, $2}' >&2 + exit 1 + fi + + echo "ERROR: no workspace found matching '$query'" >&2 + exit 1 +} + +main() { + local target + target=$(resolve_workspace "$@") + [[ -z "$target" ]] && exit 0 + + local session_name target_dir + IFS=$'\t' read -r session_name target_dir <<< "$target" + + # Ensure session exists (initialize cwd only on creation) + if ! tmux has-session -t "$session_name" 2>/dev/null; then + tmux new-session -ds "$session_name" -c "$target_dir" + fi + + # Attach or switch client based on current context + if [[ -z "${TMUX:-}" ]]; then + exec tmux attach-session -t "$session_name" + else + tmux switch-client -t "$session_name" + fi +} + +main "$@" diff --git a/home/shell.nix b/home/shell.nix index 42f659b..8ca9352 100644 --- a/home/shell.nix +++ b/home/shell.nix @@ -3,7 +3,28 @@ { pkgs, ... }: +let + # Hermetic packaging for project-driven persistent terminal workspaces + tmuxSessionizer = pkgs.writeShellApplication { + name = "tmux-sessionizer"; + runtimeInputs = with pkgs; [ + bash + coreutils + gnused + gawk + gnugrep + fd + fzf + tmux + ]; + text = builtins.readFile ./scripts/tmux-sessionizer.sh; + }; +in { + home.packages = [ + tmuxSessionizer + ]; + programs = { # 🌟 Git Version Control Configuration git = { @@ -171,6 +192,7 @@ shellAliases = { zed = "zeditor"; reload = "exec bash"; + ts = "tmux-sessionizer"; ff = "fastfetch --logo none"; # System Navigation