A Smarter Way to Move to BOL

Bozhidar Batsov over at the excellent Emacs Redux has a particularly good tip on improving move-beginning-of-line (mapped to 【Ctrl+a】 by default) so that it moves first to the leading non-blank character of the line and then to the absolute beginning of line on the second consecutive call. As soon as I saw it I knew I would be adding it to my init.el.

Batsov implemented it with a function that calls back-to-indentation and move-beginning-of-line as needed. He remarked that it could also be done by advising move-beginning-of-line. Just for kicks, I implemented it with defadvice. Here, for those of you who are interested, is that implementation:

(defadvice move-beginning-of-line (around smarter-bol activate)
  ;; Move to requested line if needed.
  (let ((arg (or (ad-get-arg 0) 1)))
    (when (/= arg 1)
      (forward-line (1- arg))))
  ;; Move to indentation on first call, then to actual BOL on second.
  (let ((pos (point)))
    (back-to-indentation)
    (when (= pos (point))
      ad-do-it)))

Either way is fine so grab whichever appeals to you most. I can't see how anyone wouldn't want this (unless your Emacs use case is very different from normal). And for goodness sake, subscribe to Emacs Redux if you haven't already. Batsov has a ton of great tips delivered almost daily.

This entry was posted in General and tagged . Bookmark the permalink.
  • John Carter

    > I can’t see how anyone wouldn’t want this (unless your Emacs use case is very different from normal)

    Hmm. I thought for a moment of what I do... My fingers are wired to go ctrl-a tab.

    Why? Well tab does two things for me, move to the first non-space _and_ check / indent the line for me.

    Hmm. Maybe I will still grab your code and mod it to do that tab for me on the first go.

  • Dan

    Um, C-h k M-m?

    It doesn't switch back-and-forth, but one can use C-a or M-m as appropriate.

    Personally, I always start at begin-line (ie, use C-a) because cutting/pasting works significantly more cleanly that way.