Translate selected text

There are some tools to translate the text you are reading especially web browser based. But sometimes you can read a PDF book and you have to copy the misunderstood phrase, open the browser and past it to Google Translate to see the result.

Repeat this procedure several times could be boring and annoying therefore I have created a script to translate any text on the fly.

The procedure is simple, we will use translate-shell in combining with xsel command to keep the selected text and translate it. After that we can show up the result on an info box through the notify-send command.

First we have to install dependencies

$ sudo apt-get install libnotify-bin wget xsel

Then we have to install translate-shell

$ wget git.io/trans
$ chmod +x ./trans
$ sudo mv trans /usr/bin/

Now we have to put the following snippet into notitranslation

#!/usr/bin/env bash
notify-send --icon=info "$(xsel -o)" "$(xsel -o | trans -b -t it)"

and move it in your $PATH

$ chmod +x notitranslation
$ sudo mv notitranslation /usr/bin/

In this case I’ve set the Italian as my target language but you can choose your own language code by following the documentation.

Finally to use the script on the fly you have to assign it a key shortcut.
On Cinnamon, Unity or GNOME you can do this by going to System Settings > Keyboard > Shortcuts > Custom Shortcuts, where you will need to click “+” to add a new keyboard shortcut. Here, enter any name you want for the new custom shortcut and “/usr/bin/notitranslation” as the command:

And then assign a keyboard shortcut to the newly added command by clicking on it and then holding down the keys you want to assign to it. Make sure the keyboard shortcut is not already in use!

Now you just select any text and press the key shortcut for the our command and the result will be the following