#!/usr/bin/env fish argparse q/quiet k/kill-on-exit h/help -- $argv if test (count $argv) -eq 0; or set -q _flag_h echo "Helper script for opening Typst files from Helix in Zathura." echo "Usage: (bind the following to a key)" echo ':sh typst-zathura [opts] %{buffer_name}' echo "Options:" echo "-q/--quiet: Don't `echo` on caught errors, return 1 instead." echo "-k/--kill-on-exit: Kill Zathura when parent Helix exits." echo "-h/--help: print this screen" end # 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 if set -q _flag_k set kill_parent echo "kill flag set" set parent_pid (find_parent_process hx) if test -z "$parent_pid" qecho "Couldn't find parent hx process!" return $ret end end # opens zathura, watching for helix closing function zopen --wraps zathura if set -q kill_parent begin zathura "$argv[1]" &>/dev/null & set zathura_pid $last_pid waitpid "$parent_pid" kill $zathura_pid end & else zathura "$argv[1]" &>/dev/null & 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 -n "$candidate" zopen "$candidate" else return 1 end end set -l src (path resolve $argv[1]) 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 at root $root!" end end end