aboutsummaryrefslogtreecommitdiff
path: root/tmuxrdr/plugin/bin/automatic-rename
blob: f3409a5d20a52c28b27c046d3f13463f4d16e609 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/bin/sh
# tmux.conf: automatic-rename on, automatic-rename-format '#{b:pane_current_path}',
# status-interval 5 -- every window is named after the directory of its
# current pane. Herdr names nothing (an unnamed tab shows its place in the tab
# bar), so this runs as a tab_bar_right command entry every 5 s (config.toml)
# and renames each tab after the basename of its focused pane's foreground
# directory -- tmux's pane_current_path. Like tmux's rename-window, a manual
# rename switches it off for that tab for good: a label this did not set is
# left alone. Prints nothing, so the status entry stays empty.
H="${HERDR_BIN_PATH:-herdr}"
dir="${XDG_STATE_HOME:-$HOME/.local/state}/herdr-tmux-mode/$(basename "$(dirname "${HERDR_SOCKET_PATH:-x/default/x}")")/names"
mkdir -p "$dir"

"$H" api snapshot | jq -r '
    .result.snapshot as $s
    | $s.tabs as $tabs
    | range(0; $tabs | length) as $i
    | $tabs[$i] as $t
    | ([$tabs[0:$i][] | select(.workspace_id == $t.workspace_id)] | length + 1) as $pos
    | ([$s.layouts[] | select(.tab_id == $t.tab_id) | .focused_pane_id][0]) as $fp
    | ([$s.panes[] | select(.pane_id == $fp) | (.foreground_cwd // .cwd // "")][0] // "") as $cwd
    | select($cwd != "")
    | [$t.tab_id, $t.label, ($pos | tostring),
       (if $cwd == "/" then "/" else ($cwd | rtrimstr("/") | split("/") | last) end)]
    | @tsv' \
| while IFS="$(printf '\t')" read -r tab label pos want; do
    f="$dir/$(printf '%s' "$tab" | tr -c 'A-Za-z0-9._-' '_')"
    mine="$(cat "$f" 2>/dev/null || true)"
    [ "$mine" = "@manual" ] && continue
    if [ "$label" != "$mine" ] && [ "$label" != "$pos" ]; then
        printf '@manual\n' >"$f"
        continue
    fi
    [ "$label" = "$want" ] && continue
    "$H" tab rename "$tab" "$want" >/dev/null 2>&1 && printf '%s\n' "$want" >"$f"
done
exit 0