DEV Community

Cover image for emacs: how to switch between module.py and test_module.py
Frederic Lepied
Frederic Lepied

Posted on

emacs: how to switch between module.py and test_module.py

Switching between files

emacs has a nice feature to switch between related files using the ff-find-other-file function. By default this is not bound to any keys. I usually bind it to F5 to find the related file in the same window and M-o to open it in a new window like this in my ~/.emacs:

(global-set-key '[f5] 'ff-find-other-file)
(global-set-key '[(meta o)] '(lambda() (interactive) (ff-find-other-file t)))
Enter fullscreen mode Exit fullscreen mode

Switching between module.py and module_test.py

For python files, related files can be a module and its test file. To do so, you need to confiure the ff-other-file-alist variable once you enter into python-mode. You can do it like that in your ~/.emacs:

(add-hook 'python-mode-hook
          (function
           (lambda()
             (setq ff-other-file-alist
                   '(("_test\\.py$" (".py"))
                     ("\\.py$" ("_test.py")) ) ) ) ) )
Enter fullscreen mode Exit fullscreen mode

The order is important in the ff-other-file-alist variable as ff-find-other-file stops at the first match.

Switching between module.py and test_module.py

To switch between module.py and test_module.py is a little bit more complex. By default ff-find-other-file works with suffixes. There is a feature that is not documented (I had to look at the source code to find it): you can pass the name of a function instead of the replacement suffixes.

Here is how to do it:

(defun py-module (fname)
  (list (concat
         (match-string 1 (file-name-nondirectory fname))
         ".py")) )

(defun py-test (fname)
  (list (concat "test_"
                (match-string 1 (file-name-nondirectory fname))
                ".py")) )

(add-hook 'python-mode-hook
          (function
           (lambda()
             (setq ff-other-file-alist
                   '(("test_\\(.*\\)\\.py$" py-module)
                     ("\\(.*\\)\\.py$" py-test))
                   ) ) ))
Enter fullscreen mode Exit fullscreen mode

Looking up in different directories

If your test and module are not in the same directory, you can use the ff-search-directories variable to add some relative paths. For example:

(add-hook 'python-mode-hook
          (function
           (lambda()
             (setq ff-search-directories '("." "../tests" "../src")) ) ) )
Enter fullscreen mode Exit fullscreen mode

Top comments (0)