aboutsummaryrefslogtreecommitdiff
path: root/emoji/emoji.sh
blob: ae2f3ab36b60675f45519612d55c6b35c48eb642 (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
#!/bin/sh

# Feeds an emoji list into dmenu and allows to select one into clipboard.
# The emoji list file is set as the emojiFile variable of this script.
#
# Usage: emoji.sh [-g]

usageMsg='Usage: emoji.sh [-g]'

[ "$1" != '-g' ] && [ -n "$1" ] && echo "$usageMsg" && exit 1

emojiFile="$XDG_CONFIG_HOME/emoji"
dmenuPath='/usr/local/bin/dmenu'
groupLineRE='^# group: '
sedFilter="/${groupLineRE}/d"

# Check if dmenu has -g option (to show options in a grid)
dmenuGridOptions=''
dmenu -g 4 -v >/dev/null 2>/dev/null && dmenuGridOptions='-g 4'

byGroups=0
[ "$1" = '-g' ] && byGroups=1

if [ "$byGroups" -eq 1 ]; then
	# Select a group name from the file's group lines
	group="$(grep "$groupLineRE" "$emojiFile" |
		sed "s/${groupLineRE}//" |
		dmenu -l 10 -p 'Emoji group:')"
	[ -z "$group" ] && exit 0

	groupLine="$(grep "$group" "$emojiFile")"

	# Prepare the sed filter to delete lines not in the group
	sedFilter="/${groupLine}/,/${groupLineRE}/!d;/${groupLineRE}/d"
fi

# Repeat used emojis at the start of the list sorted by use
emojiList="$(sed "$sedFilter" "$emojiFile")"
usedEmojis="$(echo "$emojiList" | grep '^[0-9]' | sort -nr)"
[ -n "$usedEmojis" ] &&
	emojiList="$(printf -- \
	"---------Used----------\n%s\n----------All----------\n%s" "${usedEmojis}" "${emojiList}" )"

# Choose an emoji with dmenu
lineNoNumber="$(echo "$emojiList" |
	sed 's/^[ 0-9]*//' |
	"$dmenuPath" -i -l 40 $dmenuGridOptions -p "Emoji:")"

if [ -z "$lineNoNumber" ] || echo "$lineNoNumber" | grep -q '^-'; then
	exit 0
fi

# Get the usage number
line="$(grep "$lineNoNumber" "$emojiFile")"
number="$(echo "$line" | grep -o '^[0-9]*')"
if [ -n "$number" ] ; then
	number=$((number + 1))
else
	number=1
fi

# Write the usage number to the emoji file
sed -i "/${line}/s/^[ 0-9]*/${number} /" "$emojiFile"

# Put the emoji in the clipboard
echo "$lineNoNumber" |
	cut -d' ' -f1 |
	tr -d '\n' |
	xsel -bi

# Notify the copied emoji
dunstify -t 2000 "Copied $(xsel -ob)"