Emacs Lisp 编程实例-利用 sdcv 查单词

Emacs 查单词 -- 利用 sdcv

by Jian Lee

这段 lisp 代码基于网上资源,后来我又修改了一些地方,最终成这样:

;; sdcv 翻译单词
;; 原 author: pluskid
;; 修改: jianlee
;; 调用 stardict 的命令行接口来查辞典
;; 如果选中了 region 就查询 region 的内容,
;; 否则就查询当前光标所在的词


(global-set-key (kbd "C-c d") 'kid-sdcv-to-buffer)
(defun kid-sdcv-to-buffer ()
  (interactive)
  (let ((word (if mark-active
                  (buffer-substring-no-properties (region-beginning) (region-end))
                  (current-word nil t))))
    (setq word (read-string (format "查字典 (默认 %s): " word)
                            nil nil word))
    (set-buffer (get-buffer-create "*sdcv*"))
    (buffer-disable-undo)
    (erase-buffer)
    ; 在没有创建 *sdcv* windows 之前检查是否有分屏(是否为一个window)
    ; 缺憾就是不能自动开出一个小屏幕,自己注销
    (if (null (cdr (window-list)))
        (setq onewindow t)
      (setq onewindow nil))
    (let ((process (start-process-shell-command "sdcv" "*sdcv*" "sdcv" "-n" word)))
      (set-process-sentinel
       process
       (lambda (process signal)
         (when (memq (process-status process) '(exit signal))
           (unless (string= (buffer-name) "*sdcv*")
             (setq kid-sdcv-window-configuration (current-window-configuration))
             (switch-to-buffer-other-window "*sdcv*")
             (local-set-key (kbd "d") 'kid-sdcv-to-buffer)
             (local-set-key (kbd "n") 'next-line)
             (local-set-key (kbd "j") 'next-line)
             (local-set-key (kbd "p") 'previous-line)
             (local-set-key (kbd "k") 'previous-line)
             (local-set-key (kbd "SPC") 'scroll-up)
             (local-set-key (kbd "DEL") 'scroll-down)
             (local-set-key (kbd "q") (lambda ()
                                        (interactive)
                                        (if (eq onewindow t)
                                            (delete-window)
                                          (progn (bury-buffer) (other-window 1))))))
           (goto-char (point-min))))))))

使用 "C-c d" 查询单词,默认为光标前一个单词。进入 "*sdcv*" 缓冲区后,下面按键可以用:

d 查单词
q 退出
j 或 n 向下移动一行
p 或 k 向上移动一行
SPC (空格键) 向下移动一页
DEL (退格键) 向上移动一页

你可能感兴趣的:(Emacs Lisp 编程实例-利用 sdcv 查单词)