Skip to content

Instantly share code, notes, and snippets.

@mtmtcode
Last active December 27, 2015 02:39
Show Gist options
  • Save mtmtcode/7253740 to your computer and use it in GitHub Desktop.
Save mtmtcode/7253740 to your computer and use it in GitHub Desktop.
(require 'google-translate)
(defvar helm-multilingual-source-language "ja")
(defvar helm-multilingual-target-language-alist
'(
("Japanese" . "ja")
("Arabic" . "ar")
("Chinese Simplified" . "zh-CN")
("Dutch" . "nl")
("English" . "en")
("French" . "fr")
("German" . "de")
("Greek" . "el")
("Korean" . "ko")
("Latin" . "la")
("Persian" . "fa")
("Russian" . "ru")
("Spanish" . "es")
))
(defun helm-multilingual-do-traslation (source-language target-language text)
"Translate TEXT from SOURCE-LANGUAGE to TARGET-LANGUAGE."
(let ((text-stripped
(replace-regexp-in-string "[[:space:]\n\r]+" " " text)))
(if (or (= (length text-stripped) 0)
(string= text-stripped " "))
(message "Nothing to translate.") ;; TOOD ここで処理抜けなくてよいのか
(let* ((json
(json-read-from-string
(google-translate-insert-nulls
;; Google Translate won't let us make a request unless we
;; send a "User-Agent" header it recognizes.
;; "Mozilla/5.0" seems to work.
(let ((url-request-extra-headers
'(("User-Agent" . "Mozilla/5.0"))))
(google-translate-http-response-body
(google-translate-format-request-url
`(("client" . "t")
("ie" . "UTF-8")
("oe" . "UTF-8")
("sl" . ,source-language)
("tl" . ,target-language)
("text" . ,text-stripped))))))))
(text-phonetic
(mapconcat #'(lambda (item) (aref item 3))
(aref json 0) ""))
(translation
(mapconcat #'(lambda (item) (aref item 0))
(aref json 0) ""))
(translation-phonetic
(mapconcat #'(lambda (item) (aref item 2))
(aref json 0) ""))
(dict (aref json 1)))
translation))))
(defun helm-multilingual-translate-multi (text)
(let ((langs (mapcar 'cdr helm-multilingual-target-language-alist)))
(mapcar (lambda (lang) (helm-multilingual-do-traslation helm-multilingual-source-language lang text)) langs)))
(defun helm-multilingual (text)
(interactive "sString: ")
(helm :sources `(
(name . "Multilingual")
(candidates . ,(helm-multilingual-translate-multi text))
(action . (lambda (c) (kill-new c) (message c)))
)))
(defun helm-multilingual-region (beg end)
(interactive "r")
(let ((text (buffer-substring-no-properties beg end)))
(helm-multilingual text)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment