#!/bin/zsh
zparseopts -D \
	h=H  -help=H \
	a=A  -append=A \
	p:=P -prompt:=P

if [[ -n $H ]]; then cat <<END
usage: ${0:t} [options] [<command>]

options:
	-h --help         this help
	-a --append       append url to the command
	-p --prompt TEXT  use TEXT as a prompt

environment:
	MATCH_RE must be set to grep extended regular expression to match

description:
	Checks current tmux buffer for regexp matches and shows them using slmenu.
	When user selects one match it is then passed to a command that was given
	as an argument via stdin. In case -a option was used, it is passed as last
	argument instead.
	If no command was given, the result is saved as new tmux buffer.
END
	exit 0
fi

if [[ -z $MATCH_RE ]]; then
	echo 'please set MATCH_RE environment variable (use --help for details)'
	exit 1
fi
MATCH_TYPE=${MATCH_TYPE:--E}

# check if command was passed
if [[ $# == 0 ]]; then
	cmd=( tmux load-buffer - )
	A=()
else
	cmd=( "$@" )
fi

# check if prompt text was passed
if [[ $#P == 2 ]]; then
	sl_args=( -p ${P[2]} )
else
	sl_args=( -p 'select item' )
fi

# grep for matches in the buffer, read them into list and reverse them
typeset -a -U matches # remove duplicates
matches=( ${(fOa)"$( tmux save-buffer - | grep $MATCH_TYPE -oe $MATCH_RE  )"} )

# print error if none was found
if [[ -z "$matches" ]]; then
	echo "no matches found!"
	read -t 1 -q # wait for any keypress, up to 1 sec
	exit
fi

# display menu and print result
print -rl -- $matches | slmenu $sl_args -l $(($LINES-2)) | read match

# exit on canceled
[[ -z "$match" ]] && exit

# execute command depending on --append flag
if (($#A)); then
	$cmd $match
else
	print -r -- $match | $cmd
fi