Jump to the positions before and after `M-x imenu`

  |   Source

As a programmer, I use `M-x imenu` to jump to the callee when editing a code file. After a little code tweaking in the callee, I need jump back to caller as quickly as possible.

Solution

Insert below code to ~/.emacs:

(defvar rimenu-position-pair nil "positions before and after imenu jump")
(add-hook 'imenu-after-jump-hook
          (lambda ()
            (let ((start-point (marker-position (car mark-ring)))
                  (end-point (point)))
              (setq rimenu-position-pair (list start-point end-point)))))

(defun rimenu-jump ()
  "jump to the closest before/after position of latest imenu jump"
  (interactive)
  (when rimenu-position-pair
    (let ((p1 (car rimenu-position-pair))
          (p2 (cadr rimenu-position-pair)))

      ;; jump to the far way point of the rimenu-position-pair
      (if (< (abs (- (point) p1))
             (abs (- (point) p2)))
          (goto-char p2)
          (goto-char p1))
      )))

Now you can use `M-x rimenu-jump` to jump.

Technical details

Imenu will push the start point into mark-ring. After reaching the destination, it will call the imenu-after-jump-hook where I can store the end point.

I store the start/end point into rimenu-position-pair and `M-x rimenu-jump` goes to the farthest one from the pair.

Here is the original discussion on G+. Thanks to Jorge A. Alfaro Murillo for enlightening me on the solution.

Comments powered by Disqus