Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload a Keybinding in Emacs

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 auto-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.

like image 943
kladd Avatar asked Oct 10 '22 01:10

kladd


1 Answers

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.
like image 183
phils Avatar answered Oct 13 '22 11:10

phils