dotfiles/.config/helix/scripts/typst-zathura.fish

98 lines
2.2 KiB
Fish
Executable file

#!/usr/bin/env fish
argparse q/quiet -- $argv
# only return status 1 if -q not set
if set -q _flag_q
set ret 1
else
set ret 0
end
# only echo if -q not set
function qecho
if not set -q _flag_q
echo $argv[1]
end
end
# traverse up process tree to find caller Helix PID
function find_parent_process -a target
set current_pid $fish_pid
while test $current_pid -ne 1 # Stop when we reach init (PID 1)
set parent (ps -o ppid= -p $current_pid | string trim)
set cmd (ps -o comm= -p $parent | string trim)
if string match -q -- $target $cmd
echo "$parent"
return 0
end
set current_pid $parent
end
return 1
end
set parent_pid (find_parent_process hx)
if test -z "$parent_pid"
qecho "Couldn't find parent hx process!"
return $ret
end
echo $parent_pid
# opens zathura, watching for helix closing
function zopen --wraps zathura
begin
zathura "$argv[1]" &>/dev/null &
set zathura_pid $last_pid
notify-send "$zathura_pid"
inotifywait -qq -e delete_self /proc/$parent_pid
notify-send "Zathura killed"
kill $zathura_pid
end &
end
function find_pdf
set -l root $argv[1]
set -l base $argv[2]
set -l candidate (fd --no-ignore-vcs -F -1 "$base" "$root")
if test "$candidate" != ''
zopen "$candidate"
else
return 1
end
end
set -l src (path resolve $argv[1])
# echo $src
# string replace
if not string match -q '*.typ' $src
qecho "$(path basename $src) is not a Typst file!"
return $ret
end
set -l targ (string replace '.typ' '.pdf' $src)
set -l base (path basename --no-extension $src).pdf
if test -f "$targ" -a '' != ''
# zathura "$targ" &>/dev/null &
zopen "$targ"
else
# no such file in current dir, time to search!
# if we're in a git repo, search from root
# if we're not, search from cwd
if git rev-parse --is-inside-work-tree &>/dev/null
# echo in git
set root (git rev-parse --show-toplevel)
# echo $root
else
echo out git
set root (pwd)
end
if not find_pdf "$root" "$base"
if set -q _flag_q
return 1
else
echo "$base couldn't be found!"
end
end
end