有时候想重复一个命令,比如
- 一直向下滚屏,或者说执行 C-n N 次;
- 输入
---------------------------
这样的重复序列。
需要一直按着 C-n 或 -
会比较烦人。我刚写了一个 repeater-mode
自动帮用户重复。比如说你连按 3 次 C-n,它就会帮你一直按着 C-n,直到你按任意一个按键终止。
最初的代码
(defvar repeater-commands (make-ring 2))
(defvar repeater-timeout 1 "决定是否重复的等待时间.")
(defvar repeater-interval 0.1 "重复间隔.")
(defun repeater-post-command ()
(ring-insert repeater-commands (list last-repeatable-command
last-command-event))
(when (= (ring-length repeater-commands) 2)
(let ((last (ring-ref repeater-commands 0))
(penult (ring-ref repeater-commands 1)))
(when (equal last penult)
(let ((this (cons this-command (append (this-command-keys-vector) nil))))
(when (equal this last)
(unwind-protect
(let ((message-log-max nil)
(name (propertize (symbol-name this-command)
'face font-lock-function-name-face)))
(message "About to repeating %s... (Hit any key to quit)" name)
(when (sit-for repeater-timeout)
(let ((count 0))
(while (and (sit-for repeater-interval)
(condition-case err
(prog1 t (call-interactively this-command))
(error
(message "%s" (error-message-string err))
nil)))
(setq count (1+ count))
(message "Repeating %s [%d times] (Hit any key to quit)"
name count)))))
(dotimes (_ (ring-length repeater-commands))
(ring-remove repeater-commands)))))))))
(define-minor-mode repeater-mode
"如果你连着三次用了同一个命令,帮你自动重复它."
:global t
:lighter " Repeater"
(if repeater-mode
(add-hook 'post-command-hook #'repeater-post-command)
(remove-hook 'post-command-hook #'repeater-post-command)))