#!/bin/zsh
tmux capture-pane -S -9999
had_prompt=0
back=()
lines=()
tmux save-buffer - | cat | while read line; do
	case $line in
		($~1) had_prompt=1;;
		('')
			if (($had_prompt)); then
				continue
			else
				lines+=$line
			fi
			;;
		(*)
			if (($had_prompt)); then
				if ((${#lines})); then
					back+=${(F)lines}
				fi
				lines=( $line )
				had_prompt=0
			else
				lines+=$line
			fi
			;;
esac
done

if [[ -n "$2" ]]; then
	print -r - $back[$2]
else
	print -rl - $lines
fi