将Emacs的输入事件转换为键码

时间:2012-08-14 22:17:05

标签: emacs elisp

在处理一些Vim仿真功能时,我想到了以下代码:

如果按; 后跟返回,光标将跳到行尾并插入分号。

(global-set-key (kbd ";") 'insert-or-append)

(defun insert-or-append ()
  "If the user enters <return>, then jump to end of line and append a semicolon,
   otherwise insert user input at the position of the cursor"
  (interactive)
  (let ((char-read (read-char-exclusive))
        (trigger ";"))
    (if (eql ?\r char-read)
        (progn
          (end-of-line)
          (insert trigger))
      (insert (this-command-keys)))))

此功能正常,但一切都是硬编码的。我宁愿让它更通用。理想情况下,我想指定一个kbd-macro(例如(kbd "<return>"))作为参数,并将其与(read-char)的结果进行比较。但是,kbd返回一个符号,(read-char)返回一个字符代码。我一直在浏览Emacs文档,但无法找到转换。

有没有办法比较两者?或者有更简单的方法吗?

1 个答案:

答案 0 :(得分:4)

这个怎么样:

(global-set-key (kbd "RET") 'electric-inline-comment)

(defun electric-inline-comment ()
  (interactive "*")
  (if (and (eq last-command 'self-insert-command)
           (looking-back ";"))
      (progn
        (delete-region (match-beginning 0) (match-end 0))
        (end-of-line)
        (insert ";"))
    (newline)))