在Emacs中如何重载一个按键绑定

5

我查看了许多其他问题和el文件,寻找可以修改以适应我的需求的内容,但我遇到了麻烦,所以来请教专家。

是否有任何方法使按键的行为根据光标所在行的位置而异?

更具体地说,如果我在一行的中间,我想将Tab键映射到该行的末尾,但如果光标位于该行的开头,则正常工作。

到目前为止,我已经自动配对大括号和引号,并在C ++ / Java等语言中重新定位光标。例如,如果函数没有任何参数,我想使用Tab键到达行末。

2个回答

3

根据点在行中的位置而表现不同是容易的部分(请参见代码中的(if (looking-back "^") ...))。"[像制表符一样工作]通常是"较难的部分,因为这是上下文相关的。

这里有一种方法,但我后来想到一个更健壮的方法是定义一个自己绑定TAB的小模式,并让该函数动态查找备用绑定。我不确定如何做到最后一点,但这里有一个解决方案:

Emacs key binding fallback

(defvar my-major-mode-tab-function-alist nil)

(defmacro make-my-tab-function ()
  "Return a major mode-specific function suitable for binding to TAB.
Performs the original TAB behaviour when point is at the beginning of
a line, and moves point to the end of the line otherwise."
  ;; If we have already defined a custom function for this mode,
  ;; return that (otherwise that would be our fall-back function).
  (or (cdr (assq major-mode my-major-mode-tab-function-alist))
      ;; Otherwise find the current binding for this mode, and
      ;; specify it as the fall-back for our custom function.
      (let ((original-tab-function (key-binding (kbd "TAB") t)))
        `(let ((new-tab-function
                (lambda ()
                  (interactive)
                  (if (looking-back "^") ;; point is at bol
                      (,original-tab-function)
                    (move-end-of-line nil)))))
           (add-to-list 'my-major-mode-tab-function-alist
                        (cons ',major-mode new-tab-function))
           new-tab-function))))

(add-hook
 'java-mode-hook
 (lambda () (local-set-key (kbd "TAB") (make-my-tab-function)))
 t) ;; Append, so that we run after the other hooks.

非常感谢您的帮助,我真的很感激您详尽的回答。我会测试两种方法。 - kladd
我还建议您查看http://www.masteringemacs.org/articles/2011/02/08/mastering-key-bindings-emacs/,这将揭示Emacs中适用于键绑定的许多层和优先规则。 - phils
太好了!只需要做一个小修改:如果你把宏的第二行和第三行的注释放在引号 " 中而不是分号 ; 后面,你的注释就会变成文档字符串。这样当你请求帮助时,你就可以看到你的描述 - C-h f make-my-tab-function - Tyler
当然。那些注释并不是作为文档字符串而存在的,但你说得对,它应该有一个。已经修复了(以及我好奇的打错了add-to-list而不是add-hook)。 - phils

1

Emacs Wiki的这个页面列出了几个包(如smarttab等),它们可以根据上下文使TAB键执行不同的操作。你可能可以修改其中一个来实现你想要的功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接