Verified Commit 284fccf0 authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Add SSH host completion to term-startup script

parent 7d9bf767
Loading
Loading
Loading
Loading
+16 −5
Original line number Diff line number Diff line
#!/usr/bin/env bash
set -eu
set -o vi
shopt -s extglob lastpipe

declare -A TERM_STARTUP_OPTIONS=(
@@ -8,6 +9,7 @@ declare -A TERM_STARTUP_OPTIONS=(
)

. ~/.shell/lib/shared.sh
. ~/.shell/lib/term.bash
. ~/.profile

declare -r CODE_HIGHLIGHT=$(tput setab 15; tput setaf 16)
@@ -47,11 +49,20 @@ interact() {
}

do_ssh() {
	local host
	while read -p 'Connect to SSH host [empty for other options]: ' host args; do
	local host args

	if [[ ! -v SSH_HOSTS ]]; then
		local IFS=$'\n',
		cut -f1 -d ' ' <~/.ssh/known_hosts |
			read -d '' -a SSH_HOSTS || true
	fi

	read_completions \
		"Connect to SSH host [empty for other options]" \
		host args -- "${SSH_HOSTS[@]}"

	[[ -z $host ]] && STATE=options && return
	exec ssh $host $args
	done
}

do_tmux() {
+10 −0
Original line number Diff line number Diff line

common_prefix() {
	local IFS=$'\n'
	sed -e '$!{N;s/^\(.*\).*\n\1.*$/\1\n\1/;D;}' <<<"$*"
}

common_suffix() {
	local IFS=$'\n'
	sed -e '$!{N;s/\(.*\)\n.*\1$/\1\n\1/;D;}' <<<"$*"
}

.shell/lib/term.bash

0 → 100644
+60 −0
Original line number Diff line number Diff line
. ~/.shell/lib/strings.bash

_input_completion() {
	local prefix=${READLINE_LINE:0:$READLINE_POINT}
	local suffix=${READLINE_LINE:$READLINE_POINT}
	local host
	declare -a comp=()

	tput -S <<-END
		sc
		ed
	END

	for host in "$@"; do
		if [[ ! $prefix || $host =~ ^"$prefix" ]] && [[ ! $suffix || $host =~ "$suffix" ]]; then
			echo $host
		fi
	done |
	sort -u |
	read -d '' -a comp || true

	case ${#comp[*]} in
		0) return ;;
		1) READLINE_LINE=${comp[0]} READLINE_POINT=${#READLINE_LINE}; return ;;
	esac

	tput -S <<-END
		cud1
		cud1
		setaf 4
		bold
	END
	printf "%s\n" "${comp[@]}" | column
	tput -S <<-END
		sgr0
		rc
	END

	local new_prefix=$(common_prefix "${comp[@]}")
	local new_suffix=$(common_suffix "${comp[@]}")

	[[ -n $new_prefix ]] && prefix=$new_prefix
	[[ -n $new_suffix ]] && suffix=$new_suffix

	READLINE_LINE="${prefix}${suffix}"
	READLINE_POINT=${#prefix}
}

# Usage: read_completions "Prompt" [OUT_VAR ...] [-- [COMPLETION ...]]
read_completions() {
	local IFS=' '
	local prompt=$1
	declare -a out
	while [[ -v 2 && $2 != -- ]]; do out+=($2); shift; done;
	shift 2
	bind -x '"\t"':"_input_completion $*"
	unset IFS
	trap 'bind -r "\t"' RETURN
	read -e -p "$prompt: " "${out[@]}"
}