开发者

Overload a Keybinding in Emacs

开发者 https://www.devze.com 2023-04-04 09:58 出处:网络
I\'ve looked through a number of other questions and el files looking for something i could modify to suit my needs but I\'m having trouble so I came to the experts.

I've looked through a number of other questions and el files looking for something i could modify to suit my needs but I'm having trouble so I came to the experts.

Is there anyway to have a key behave differently depending on where in the line the cursor is?

To be more specific I'd like to map the tab key to go to the end of the line if I'm in the middle of the line but work as a tab normally would if my cursor is positioned at the beginning of the line.

So far I have braces and quotes 开发者_如何学Cauto-pairing and re-positioning the cursor within them for C++/Java etc. I'd like to use the tab key to end-of-line if for example a function doesn't have any arguments.


Behaving differently depending on where point is in the line is the easy bit (see (if (looking-back "^") ...) in the code). "[Working] as a tab normally would" is the harder bit, as that's contextual.

Here's one approach, but I was thinking afterwards that a more robust method would be to define a minor mode with its own binding for TAB and let that function look up the fallback binding dynamically. I wasn't sure how to do that last bit, but there's a solution right here:

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.


This page of Emacs Wiki lists several packages (smarttab, etc.) which make TAB do different things depending on the context. You can probably modify one of them to do what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消