Jedi.el: jump to definition **and back again**


Jedi.el works surprisingly well for me in Emacs. One of my favourite features is (jedi:goto-definition). Often it spots the right position better than the traditional (find-tag). It lags when I want to go back, there is no counterpart to (pop-tag-mark) in jedi.el.

My solution is to define my own jump-to-definition and jump-back functions, which maintain a stack of the previous positions.

I like C-. key-binding for jumping to definition, but prefer to bind my jump function to it. That's why I don't enable the default keymap of the jedi package:

 ;; don't use default keybindings from jedi.el; keep C-. free
 (setq jedi:setup-keys nil)
 (setq jedi:tooltip-method nil)
 (autoload 'jedi:setup "jedi" nil t)
 (add-hook 'python-mode-hook 'jedi:setup)

Instead I define these functions:

(defvar jedi:goto-stack '())
(defun jedi:jump-to-definition ()
  (add-to-list 'jedi:goto-stack
               (list (buffer-name) (point)))
(defun jedi:jump-back ()
  (let ((p (pop jedi:goto-stack)))
    (if p (progn
            (switch-to-buffer (nth 0 p))
            (goto-char (nth 1 p))))))

Finally I define my jedi keymap, which mostly coincides with jedi.el's defaults:

;; redefine jedi's C-. (jedi:goto-definition)
;; to remember position, and set C-, to jump back
(add-hook 'python-mode-hook
          '(lambda ()
             (local-set-key (kbd "C-.") 'jedi:jump-to-definition)
             (local-set-key (kbd "C-,") 'jedi:jump-back)
             (local-set-key (kbd "C-c d") 'jedi:show-doc)
             (local-set-key (kbd "C-<tab>") 'jedi:complete)))

Then when I open any Python file: Ctrl-. to jump to definition, Ctrl-, to jump back.