~skiqqy/bin

ref: 2812c8afd69dbb57043eb971c17c2e1bb5833da0 bin/clip -rwxr-xr-x 2.1 KiB
2812c8afStephen Cochrane Clip only stores uniq copies now 3 months ago
                                                                                
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#!/usr/bin/env bash
# Simple xclip X dmenu script, TL;DR Clipboard manager
# Author: Skiqqy
scriptname="$(basename "$0")"

usage()
{
	cat << EOF

$scriptname ~ Simple clipboard manager

    Options
      -h                  Shows this message.
      -b PATH/TO/FILE     Specify the buffer file to use, current = "$buffer"

    Commands
      copy                Put current x selection into the buffer.
      paste [put]         Select an item from the buffer, if put is supplied, paste automatically.
      clean               Reset the buffer

EOF
	exit "${1:-0}"
}

# Select an item from the buffer to paste
paste()
{
	local len
	touch "$buffer"
	len="$(wc -l "$buffer" | tr -s ' ' | cut -d ' ' -f 1)"

	if [ "$len" -gt 0 ]
	then
		dmenu -l "$len" < "$buffer" | tr "$delim" '\n' | xclip -r -selection clipboard
	else
		printf 'Buffer is empty.\n'
		return 1
	fi

	if [ "$1" = "put" ]
	then
		xdotool key 'ctrl+shift+v' # Paste the output.
	fi
}

# Put current selection into the buffer
copy()
{
	# Only copy if the element is uniq
	grep -F "$(xclip -o | tr '\n' "$delim")" "$buffer" > /dev/null && return

	if [ ! "$(wc -l "$buffer"| tr -s ' ' | cut -d ' ' -f 1)" -le "$max" ]
	then
		# Remove oldest item, ie top item in file
		printf 'Buffer full, removing oldest entry...\n'
		tail "$buffer" -n +2 > "$buffer.tmp"
		mv "$buffer.tmp" "$buffer"
	fi

	if [ -n "$(xclip -o)" ]
	then
		{
			xclip -o | tr '\n' "$delim" # Replace new lines with delim char \x1f
			printf '\n'
		} >> "$buffer"
	else
		printf 'Selection is empty.\n'
		return 1
	fi
}

# Reset the buffer
clean()
{
	printf 'Resetting buffer...\n'
	: > "$buffer"
}

main()
{
	max=10 # Max items to be kept in the buffer.
	buffer='/tmp/copy.buffer'
	delim="$(printf '\x1f')"

	while getopts hb: opt
	do
		case "$opt" in
			b)
				buffer="$OPTARG"
				[ ! -f "$buffer" ] && printf 'WARN: %s DNE!\n' "$buffer" && return 1
				;;
			h)
				usage
				;;
			*)
				usage 1
				;;
		esac
	done
	shift "$((OPTIND-1))"

	local com
	com="$1"
	shift 1

	case "$com" in
		copy|paste|clean) $com "$@"
			;;
		'')
			usage
			;;
		*)
			printf 'Unknown Command: %s\n' "$com"
			usage 1
			;;
	esac
}

main "$@"