1752873200652260785

· ficd's pastes · raw

expires: 2025-10-16

 1provide-module root %
 2    declare-option str-list root_globs .kakrc kakrc .git 
 3    declare-option str root_path %sh{ echo "$PWD" }
 4    declare-option -hidden str root_prev_pwd %opt{root_path}
 5    # recursively discovers the root dir based on root_globs
 6    define-command root-discover %{
 7        evaluate-commands %sh{
 8            globs="$kak_opt_root_globs"
 9            dir="$PWD"
10            root="$dir"
11
12            while [ "$dir" != "/" ]; do
13            	for glob in $globs; do
14            		match=$(fd -H -td -1 --glob "$glob" "$dir" --max-depth 1 2>/dev/null | head -n1)
15            		if [ -n "$match" ]; then
16            			root="$(dirname "$match")"
17            			break
18            		fi
19            	done
20            	dir="$(dirname "$dir")"
21            done
22            printf 'set-option global root_path "%s"\n' "$root"
23            printf 'echo "Discovered root: %s"\n' "$root"
24        }
25    }
26    # syntax highlighting
27    hook global BufCreate (.*/)?\.kakrc %{
28        set-option buffer filetype kak
29    }
30    # load proj. config
31    define-command root-load-kakrc %{
32        try %{ source %exp{%opt{root_path}/.kakrc} }
33    }
34
35    # convenience, for kak -e root
36    define-command root %{
37        root-discover
38        root-load-kakrc
39    }
40
41    # change the cwd to root
42    define-command -hidden root-cd-root-impl %{
43        set-option global root_prev_pwd %sh{ echo "$PWD" }
44        change-directory %opt{root_path}
45        echo "CWD: %opt{root_path}"
46    }
47    # change cwd back to what it was before
48    define-command -hidden root-cd-return-impl %{
49        change-directory %opt{root_prev_pwd}
50        echo "CWD: %opt{root_prev_pwd}"
51    }
52
53    # toggle between root and previous cwd
54    define-command root-cd %{
55        evaluate-commands %sh{
56            if [ "$PWD" != "$kak_opt_root_path" ]; then
57                echo "root-cd-root-impl"
58            else
59                echo "root-cd-return-impl"
60            fi
61        }
62    }
63
64    # edit a file, relative to root
65    define-command -params 1 root-edit %{
66        edit %exp{%opt{root_path}/%arg{1}}
67    }
68    complete-command root-edit shell-script-candidates %{
69        fd -H -tf --exclude '.git' --base-directory "$kak_opt_root_path" .
70    }
71
72    alias global re root-edit
73    alias global rc root-cd
74
75