Emacs custom function to translate text using github.com/soimort/translate-shell.

by Mala
GNU/Linux ā—† foot ā—† bash 107 views

;; Translate text using github.com/soimort/translate-shell
;; The selected text will be used as source and be replaced
;; by the translation. If no text is selected, the user will
;; be prompted to enter the source text.
(defun trans-text (from-lang to-lang text)
  "Translate TEXT from FROM-LANG to TO-LANG using the 'trans' command (translate-shell)."
  (interactive
   (list (let ((input (read-string "Translate from (default: auto): ")))
           (if (string-empty-p input)
               ""
             input))
         (read-string "Translate to language: ")
         (if (use-region-p)
             (buffer-substring (region-beginning) (region-end))
           (read-string "Text to translate: "))))

  ;; Escape the text for proper shell quoting
  (setq text (shell-quote-argument text))

  (let* ((from-option (if (string-empty-p from-lang) "" (format "-s '%s'" from-lang)))
         (command (format "trans -b %s -t '%s' <<< %s" from-option to-lang text))
         (translated-text (shell-command-to-string command)))
    (if (use-region-p)
        (delete-region (region-beginning) (region-end))
      (delete-region (point) (point)))
    (insert translated-text)))

(global-set-key (kbd "C-c M-t") 'trans-text)