#!/bin/zsh
#set -x
zparseopts h=a_help -help=a_help p=a_ps v=a_vim
if [ -n "$a_help" ]
then
	echo "usage: `basename $0` [options]"
	echo "options:"
	echo "  -h  this help"
	echo "  -p  show process tree"
	echo "  -v  show vim sessions"
	exit
fi
tmux list-panes -a -F '#{session_name}|#{window_index}|#{pane_id}|#{pane_pid}|#{pane_tty}|#{pane_title}' | \
sort -g | \
while read line; do
	l=( ${(s:|:)line} )
	p=( ${l[1,5]} )
	p+=$(tr '\0' ' ' </proc/${l[4]}/cmdline)
	p+=$(readlink /proc/${l[4]}/cwd)
	p+=${l[6]}
	(($#a_ps)) && echo
	echo ${(j:\t:)p}
	(($#a_ps)) && ps --forest --tty ${p[5]} --format cmd --no-headers
	if (($#a_vim)) && [[ $l[6] == *VIM* ]]; then
		session=~/.local/share/tmux_session/vimsession.${l[3]#%}
		[[ -f $session ]] && grep '^badd ' $session | while read _b line file; do
			printf '\t%s  %s\n' $file $line
		done
	fi
done