about summary refs log tree commit diff stats
path: root/foil.sh
blob: 52382eb45d00c561895cf283fcce0c60543ba219 (plain)
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
#!/bin/sh
# FOIL: copy and paste shit
# by C. Duckworth <acdw@acdw.net>
# This program is free software;
# you can use it as you see fit,
# but don't hold me responsible.

t="$(mktemp)"
trap 'rm -f "$t"' EXIT INT

_run() {
	c="$1"
	shift
	if command -v "$c" >/dev/null 2>&1; then
		"$c" "$@" && rm "$t"
		return 0
	else
		return 1
	fi
}
_runs() {
	_run "$@" # >/dev/null 2>&1
}

_copy() {
	test -n "${TMUX:-}" && _run tmux load-buffer "${1:--}"
	cat "${1:-/dev/stdin}" |
		case "$OSTYPE" in
		cygwin* | msys*) _run cat >/dev/clipboard ;;
		linux-android*)
			_runs termux-clipboard-set
			;;
		*)
			if test -n "$WAYLAND_DISPLAY"; then
				_runs wl-copy
			elif test -n "$DISPLAY"; then
				_runs pbcopy ||
					_runs xsel --clipboard --input ||
					_runs xclip -selection clipboard -in
			else
				_runs lemonade copy ||
					_runs doitclient wclip ||
					_runs win32yank -i ||
					_runs clip.exe
			fi
			;;
		esac
	! test -f "$t"
}

_paste() {
	test -n "${TMUX:-}" && _run tmux save-buffer -
	case "$OSTYPE" in
	cygwin* | msys*) _run cat /dev/clipboard ;;
	linux-android*) _run termux-clipboard-get ;;
	*)
		if test -n "$WAYLAND_DISPLAY"; then
			_run wl-paste
		elif test -n "$DISPLAY"; then
			_run pbpaste ||
				_run xsel --clipboard --output ||
				_run xclip -out -selection clipboard
		else
			_run lemonade paste ||
				_run doitclient wclip -r ||
				_run win32yank -o ||
				exec powershell.exe -noprofile -command Get-Clipboard
		fi
		;;
	esac
	! test -f "$t"
}

_main() {
	c="$1"
	shift
	case "$c" in
	*yoink* | *copy*) _copy "$@" ;;
	*yeet* | *paste*) _paste "$@" ;;
	*)
		_main "$@"
		;;
	esac
}

test -n "$DEBUG" && set -x
test -z "$SOURCE" && _main "$0" "$@"