RSS | Source | License

Jump Back in Emacs

It is annoying when you jumped to somewhere, did some operations and couldn’t find the way back and have to scroll back or jump back by searching. There are many position history packages that record your location and let you jump back in time. But in reality they either set too much anchors or didn’t set the anchor you need. Also jumping between anchors are more or less visually confusing because you have to observe where are you after each jump. In a word, the experience is not very good.

After some observation I found that the annoying situation I described above only takes place after a very limited set of commands: beginning-of-buffer, end-of-buffer, helm-swoop, query-replace, replace-string, isearch. (x-ref has its own jump back command.)

I wrote my jump back command that only records position before these commands, so when I invoke the jump I always know where am I going. Also, if I jump back after jumped back, I jump back to where I was before I jump back the first time ;-)

(defvar luna-jump-back-marker nil
  "Marker set for `luna-jump-back'.")

(defvar luna-jump-back-monitored-command-list
  '(isearch-forward helm-swoop isearch-backward end-of-buffer beginning-of-buffer query-replace replace-string)
  "Commands in this list sets mark before execution for jumping back later.")

(defun luna-jump-back ()
  "Jump back to previous position."
  (if (not luna-jump-back-marker)
      (message "No marker set")
    ;; set `luna-jump-back-marker' to point and jump back
    ;; so we can keep jumping back and forth
    (let ((here (point-marker))
          (there luna-jump-back-marker))
      (setq luna-jump-back-marker here)
      (goto-char there))))

(defun luna-maybe-set-marker-to-jump-back ()
  "Set marker to jump back if this command is search or jump."
  (when (member this-command luna-jump-back-monitored-command-list)
    (setq luna-jump-back-marker (point-marker))))

(add-hook 'pre-command-hook #'luna-maybe-set-marker-to-jump-back)

Written by Yuan Fu

First Published on 2019-08-03 Sat 12:52

Last modified on 2020-09-12 Sat 16:10

Send your comment to archive.casouri.cat@gmail.com