结合 Company 和 Google 翻译输入英文

目标是输入英文,首先输入中文,然后选择 Google 翻译的结果:

06

代码(需要开启 lexical-binding):

(require 'google-translate)
(require 'company)
(require 'seq)
(require 'subr-x)

(defun company-google-translate (command &optional arg &rest _ignored)
  (interactive (list 'interactive))
  (pcase command
    ('interactive (company-begin-backend 'company-google-translate))
    ('prefix (let ((word (company-grab-word)))
               ;; 只考虑中文
               (when (string-match-p (rx bos (1+ (category chinese)) eos) word)
                 word)))
    ('candidates (company-google-translate--candidates arg))
    ('annotation (when (get-text-property 0 'translate arg)
                   (format "%s [%s]"
                           (get-text-property 0 'translate arg)
                           (substring (get-text-property 0 'type arg) 0 1))))
    ;; Google 返回的结果按 Frequency 排序,保留它
    ('sorted t)
    ('no-cache t)))

(defun company-google-translate--candidates (chinese)
  (let ((json (let ((url-show-status nil))
                (google-translate-request "zh-CN" "en" chinese))))
    (cons
     (google-translate-json-translation json)
     (seq-mapcat
      (lambda (item)
        (mapcar
         (lambda (trans)
           (propertize
            ;; 英文单词
            (aref trans 0)
            'translate
            ;; 中文翻译
            (string-join (aref trans 1) ", ")
            'type
            ;; 词性,名词、动词、副词、形容词
            (aref item 0)))
         (aref item 2)))
      (google-translate-json-detailed-translation json)))))
6 个赞

这个好累啊,看看我的方案 我是怎么用Emacs学习英文的?

英文直接补全输入,或者直接输入一串长中文,长句翻译更好点