global-set-key和define-key global-map有什么区别?

请原谅我又双叒叕提这种问题……

然而我确实不理解为什么会出现两种都用的情况。

(defun global-set-key (key command)
  "Give KEY a global binding as COMMAND.
COMMAND is the command definition to use; usually it is
a symbol naming an interactively-callable function.
KEY is a key sequence; noninteractively, it is a string or vector
of characters or event types, and non-ASCII characters with codes
above 127 (such as ISO Latin-1) can be included if you use a vector.

Note that if KEY has a local binding in the current buffer,
that local binding will continue to shadow any global binding
that you make with this function."
  (interactive
   (let* ((menu-prompting nil)
          (key (read-key-sequence "Set key globally: ")))
     (list key
           (read-command (format "Set key %s to command: "
                                 (key-description key))))))
  (or (vectorp key) (stringp key)
      (signal 'wrong-type-argument (list 'arrayp key)))
  (define-key (current-global-map) key command))

use C-h f and RTFS plz.

  • global-set-key 函数,定义于 subr.el
  • define-key 函数,内置 C 函数
  • global-map 变量,定义于 subr.el

(global-set-key ...) 添加内容到 global-map,作用范围是全局。(define-key-set 'foo-mode-map ...) 添加内容到 foo-mode-map,作用范围是 foo-mode。

如果全局和当前 mode 都设置了快捷键,当前 mode 优先

4 个赞
  • global-set-key 完全等于 (define-key (current-global-map)

  • (current-global-map) 一般等于 global-map(我不知道什么情况是例外)

    (eq global-map (current-global-map))
    ;; => t
    

所以下面三种写法作用相同

  1. (global-set-key ...)
  2. (define-key (current-global-map) ...)
  3. (define-key global-map ...)
4 个赞