banner

For a list of BASHing data 2 blog posts see the index page.    RSS


New code for my translation box

Back in 2017 I blogged about a script for quick-and-easy translation. I highlighted a block of non-English text in an application window (for example, on a webpage in my browser) and launched the script with a keyboard shortcut. A YAD dialog popped up next to the application, and a second or two later an English translation appeared in the YAD window. The YAD dialog had automatically gained focus and I could dismiss it by pressing Esc.

I've used the script a lot over the past 8 years, but YAD has changed a little and I wanted to have both the original and the translated text together in the YAD window for copying. The latest version of the script, called "trans-paste", is:

#!/bin/bash
 
while true; do
 
(xclip -o; echo -e "\n----------"; xclip -o | trans -b) | yad --posx="1525" --posy="100" --width="300" --height="600" --text-info --wrap --button=gtk-close:1 --button="Translate":0
 
case $? in
1) exit 0;;
0) continue;;
252) exit 0;;
esac
 
done
exit 0

As before, I highlight some non-English text and launch the script with a keyboard shortcut. If I then highlight another block of text and click the "Translate" button, the newer translation appears in a new instance of the YAD window, the earlier one having been closed. Note that the YAD window position and size suit my desktop; if you use the script you may need to change posx, posy, width and height to fit your own display and window arrangement.

trans-paste

The script's actions are in a while loop that only exits when the YAD dialog is closed with the Close button (exit value 1) or Esc or the window-closing "X" is pressed (exit value 252).
 
The YAD dialog gets 3 things to display: the contents of the primary clipboard (with xclip -o), a separator line of hyphens (echo -e "\n----------") and a translation of the highlighted text (xclip -o | trans -b) from Google Translate through the command-line utility translate-shell.


Next post:
2025-03-28   Text processing with xargs and jot


Last update: 2025-03-21
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License