Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I customize ff-find-other-file to switch between tests and implementations?

Tags:

python

emacs

Whenever I have to edit C++ code, I use ff-find-other-file to switch back and forth between header and implementation files. Can I use it for Python files to switch back and forth between implementations and tests? For example, if I'm in foo.py, I'd like to be able to switch to foo_test.py.

like image 806
Jason Baker Avatar asked May 03 '12 18:05

Jason Baker


2 Answers

You actually want to set ff-other-file-alist (and possibly also ff-search-directories). These variables are automatically buffer-local, so you can safely set them in a mode hook.

cc-other-file-alist is a pre-configured mapping for C/C++ files which is just the default value for ff-other-file-alist.

To handle the reverse mapping from the test back to the implementation, you would add a second entry, so the alist would look like this:

'(("_test\\.py$" (".py"))
  ("\\.py$" ("_test.py")))

The reverse mapping needs to go first in this case, as the rules are processed in order and .py matches both filenames. If they were the other way around you would still go from foo_test.py to foo_test_test.py, and so on...

See this related question for some more information and an example:

If I open doc.foo file, I want emacs to look for and open doc.bar file in the same folder

For your case, you could use:

(add-hook 'python-mode-hook 'my-python-mode-hook)

(defun my-python-mode-hook ()
  "My python customisations."
  (setq ff-search-directories '(".")
        ff-other-file-alist '(("_test\\.py$" (".py"))
                              ("\\.py$" ("_test.py")))))
like image 121
phils Avatar answered Nov 20 '22 00:11

phils


You need to create a .emacs rule setting cc-other-file-alist, e.g.:

(setq cc-other-file-alist
  `(("\\.py$" ("_test.py"))))
like image 37
thebjorn Avatar answered Nov 20 '22 02:11

thebjorn