Open OrionRandD opened 2 years ago
I think the best is to create custom commands in editors to use a shell command more or less interactively, but editors will have different ways to do that. I was using Kakoune some time ago and did that for some Markdown live preview mode for example. Here is something I came up with for Emacs, which seems to work nicely so far (it should support multiline source text containing quotes and backticks):
;; 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 -no-warn -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)
https://asciinema.org/a/2bGCV9FI0Fisgf1BIFbqmL0YV
It could be shortened but I wanted it to use the current selection as input text, if any, and to support automatic language detection. I wouldn't know how to achieve the same in vim
but I guess that's one task a generative AI like ChatGPT could be useful for if the user don't know how to code it themselves (it helped me here).
Wonderful function! Thx a lot!
Could you also add a shortcut for using translate-shell with vim, neovim, and other Emacs flavours when using chemacs? say:
trans -V - for Vim trans -NV - for neovim trans -Sc - for Scimax trans -ED - for Emacs Doom trans -EnG - Emacs no-GUI
or give us an example on how to set them up in a initiation config file...
https://github.com/plexus/chemacs https://github.com/jkitchin/scimax https://github.com/hlissner/doom-emacs https://github.com/neovim/neovim https://github.com/vim/vim