4

Is there a way to define a function that, when called, would move the cursor to the middle (or close to the middle) of the current line, similarly to how we can move it to the beginning and end of the line?

I frequently find myself having to do C-left or C-right multiple times to reach a word that is more to the middle of the line. I guess that if it were possible to have a function, bounded to a shortcut combination, to allow me to quickly jump close to the middle of the line, then navigation would become quite more efficient to me.

  • 1
    You might want to try out avy (github.com/abo-abo/avy) or one of the similar packages that lets you jump to a specific visible location. For example, avy-goto-char-in-line prompts for a character and then provides keys to jump to all the instances of that character in the current line. (It makes more sense when you see a demo or try it out!) – glucas Sep 18 '17 at 15:23
  • 2
    Binary line navigation might be what you're looking for! – Caterpillar Sep 18 '17 at 19:08
5

The following function moves the cursor to the middle of the current line:

(defun my/move-to-middle ()
  (interactive)
  (let* ((begin (line-beginning-position))
         (end (line-end-position))
         (middle (/ (+ end begin) 2)))
    (goto-char middle)))

You can bind this to a key (I used C-c m) using

(global-set-key (kbd "C-c m") 'my/move-to-middle)

Note that this calculates the middle of the line using line-beginning-position and line-end-position, which also count whitespace at the beginning and end of the line. This means that for indented text/code, the calculated middle will be slightly to the left of the middle of the text, and slightly to the right for lines with lots of whitespace at the end of the line.

Edit: Just found out evil-mode has this functionality already. You can move the cursor to the middle of the current line using g m, which calls evil-middle-of-visual-line. This moves the cursor to the middle column in the window, instead of the middle character in the line. See also this answer.

  • Thanks for your defined function and for calling my attention for the evil's keybinding. Although I will be using evil's, your function will allow me to do some further customizations (e.g. jumping to the middle of another line informed by number). – Louis15 Sep 18 '17 at 14:48
3

While this doesn't directly answer your question (I think Amot already covered that part just fine), I'll just point out that many Emacs users solve these kinds of problems by navigating with C-s, i.e. rather than think "move close to middle of line", they think "move to the part of the buffer with this text".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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