My Scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bin/clip

142 lines
2.6 KiB

#!/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}"
}
# No-Op till we get the lock, blocking
# Usage: lock [NAME] [Instr to do if lock fails, until succeed]
lock()
{
# What op to do in the loop, allows for setting exit, ie locks failure -> prog term
lock_op="${2:-:}"
while ! mkdir "/tmp/todo.${1:-generic}.lock"
do
$lock_op
done
}
# Release the lock
# Usage: unlock [NAME]
unlock()
{
rm -r "/tmp/todo.${1:-generic}.lock"
}
# 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" < <(tac "$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
touch "$buffer"
case "$com" in
copy|paste|clean)
lock generic exit # Exit is for dwm to not repeatedly try.
$com "$@"
unlock generic
;;
'')
usage
;;
*)
printf 'Unknown Command: %s\n' "$com"
usage 1
;;
esac
}
main "$@"