aboutsummaryrefslogtreecommitdiff
path: root/vis-complete
blob: 50895b1aac857c2b341bcadbc0eb9e5689a32a3f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/bin/sh
set -e

fatal() {
	echo "$@" >&2
	exit 1
}

usage() {
	fatal "Usage: $(basename "$0") [--file|--word] [--] pattern

Interactively complete file or word

--file this passes pattern to obtain a list of matching
       file names (this is the default).
--word this reads standard input to obtain a list of lines
       matching pattern.
pattern pattern to be completed"
}

basic_regex_quote() { printf "%s" "$1" | sed 's|[\\.*^$[]|\\&|g'; }
glob_quote () { printf "%s" "$1" | sed 's|[\\?*[]]|\\&|g'; }

COMPLETE_WORD=0
FIND_FILE_LIMIT="${FIND_FILE_LIMIT:-1000}"

while [ $# -gt 0 ]; do
	case "$1" in
	--file)
		COMPLETE_WORD=0
		shift
		;;
	--word)
		COMPLETE_WORD=1
		shift
		;;
	--)
		shift
		break
		;;
	-*|'')
		usage
		;;
	*)
		break
		;;
	esac
done

[ "$#" -lt 1 ] && usage

PATTERN="$1"

if [ $COMPLETE_WORD = 1 ]; then
	# shellcheck disable=SC1003
	tr -s '\t {}()[],<>%^&.\\' '\n' |
		grep "^$(basic_regex_quote "$PATTERN")." |
		sort -u
else
	# Expand to absolute path because of the -path option below.
	# shellcheck disable=SC2088
	case $PATTERN in
		/*)
			XPATTERN="$PATTERN"
			;;
		'~'|'~/'*)
			XPATTERN="$HOME$(echo "$PATTERN" | tail -c +2)"
			;;
		*)
			XPATTERN="$PWD/$PATTERN"
			;;
	esac

	# The first path condition rules out paths that start with "." unless
	# they start with "..". That way, hidden paths should stay hidden, but
	# non-normalised paths should still show up.
	find "$(dirname "$XPATTERN")" \
		-name '.*' -prune \
		-o \( \
			! -name '.*' \
			-a -path "$(glob_quote "$XPATTERN")*" \
			-print \
		\) 2>/dev/null |
		head -n "$FIND_FILE_LIMIT" |
		sort |
		sed "s|^$(dirname "$XPATTERN")/||"
fi |
	vis-menu -b |
	sed "s|^$(basename "$PATTERN")$(echo "$PATTERN" | tail -c 2 | grep -F /)||" |
	tr -d '\n'