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
.
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")))))
You need to create a .emacs rule setting cc-other-file-alist, e.g.:
(setq cc-other-file-alist
`(("\\.py$" ("_test.py"))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With