Skip to content

Instantly share code, notes, and snippets.

@unhammer
Last active Nov 9, 2020
Embed
What would you like to do?
Bind "/path/to/apertium-xsel" and "/path/to/apertium-xsel prev" to some global shortcut key, and get apertium translation on whatever you've selected with your mouse (if it's an URL, then it'll download the page, translate it and open that). The one with the "prev" argument will use your most recently used language pair, the other one pops up a …
#!/bin/bash
# This file gives you apertium translation on whatever you've selected
# with your mouse. When called with "prev" as an argument, it will use
# your most recently used language pair, without it will pop up a
# picker. It only uses installed pairs, ie. the ones listed by
# "apertium -l".
# Install dependencies on Debian/Ubuntu:
# $ sudo apt-get install xsel zenity
# Install dependencies on Arch Linux:
# $ sudo pacman -S xsel zenity
# And of course you need some apertium language pairs.
# chmod +x this file, then bind "/path/to/apertium-xsel" and
# "/path/to/apertium-xsel prev" to some global shortcut keys of your
# choice. In xfce, you can do this by opening the Settings Manager and
# selecting Keyboard and the Application Shortcuts tab and Add.
set -e -u
if command -V xdpyinfo &>/dev/null; then
# Half of screen in either direction:
width=$(xdpyinfo | awk -F' +|x' '/dimensions:/{print $3/2}')
height=$(xdpyinfo | awk -F' +|x' '/dimensions:/{print $4/2}')
else
width=600
height=400
fi
recentfile=$HOME/.config/apertium-xsel.recent
mkdir -p $(dirname "${recentfile}")
touch "${recentfile}"
recent=$(tail -20 "${recentfile}")
if [[ $# -ge 1 && $1 = prev ]]; then
pair=$(echo "${recent}"|tail -1)
else
pair=$(
cat <(echo "${recent}") <(apertium -l) |
sort | uniq -c | sort -nr |
sed 's/^ *[0-9][0-9]* *//' |
zenity --list --title "Apertium" --text "Select language pair" --column "pair" --hide-header --height "${height}" |
sed 's/|.*//' # work around zenity 3.8 bug #711251
)
fi
echo ">>${pair}<<"
if [[ -n ${pair} ]]; then
echo "${recent}" > "${recentfile}"
echo "${pair}" >> "${recentfile}"
if [[ $(xsel|head -1) =~ ^(file|https?):// && $(xsel|wc -l) -le 1 ]]; then
tmpfile=$(mktemp -t apertium-xsel.XXXXXXXXXXX)
curl "$(xsel)" >"${tmpfile}" && exo-open "${tmpfile}" || zenity --error --text "Couldn't download $(xsel)"
else
cat <(xsel | apertium "${pair}" 2>&1) <(printf "\n\n%30sOriginal:%30s\n") <(xsel) |
fold -s |
zenity --list --column "${pair}" --text "" --title "Apertium ${pair}" --hide-header --width "${width}" --height "${height}" --cancel-label OK
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment