1

Like in all modern editors, including the SE Q&A fields, I'd like my cursor to move to the beginning of the first line, when I press the Up arrow on the first line of a buffer. Currently, it stays in the middle of the line and messages "Beginning of buffer".

How can I get that behavior ?

(Bonus points for the same thing with Down arrow at end of buffer.)

1 Answer 1

2

You can do such thing by adding advice around previous-line and next-line, motion commands that are bound to these keys by default.

Here's the code:

(advice-add #'previous-line :around
            (lambda (func &rest args)
              (condition-case nil
                  (apply func args)
                (beginning-of-buffer (beginning-of-line)))))

(advice-add #'next-line :around
            (lambda (func &rest args)
              (condition-case nil
                  (apply func args)
                (end-of-buffer (end-of-line)))))

Add it to your init file to make it persistent.

There might be some variable to tweak these functions to work the way you'd want them to, but I couldn't find it with a couple of searches.

4
  • That seems to work just fine, thanks :) Jul 30, 2018 at 3:00
  • After a bit of usage, there's a really debilitating limitation to that : when in the minibuffer, "Up" goes backwards in history / contexts / suggestions / whatnot, but this code overrules those behaviors. So this solution should be limited not to apply to the minibuffer. Aug 2, 2018 at 20:00
  • Maybe this is really another question "how to apply advice to functions but only when not in minibuffer", I dunno ? I wouldn't know how to phrase that question well. Aug 2, 2018 at 20:11
  • M-n and M-p can be used to move through minibuffer history as well, and I assume they should work with advice I've written. It should be possible to adjust this advice to work the way you want it to in minibuffers by just checking whether you're in one with (minibufferp).
    – user12563
    Aug 2, 2018 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.