Have Emacs edit Python docstrings using rst-mode

emacs, python, restructuredtext

Solution

The Emacs package that supports that is `mmm-mode`. Ensure that's installed, and then code like this as part of your Emacs startup should do it:

(require 'mmm-mode)
(setq mmm-global-mode 'maybe)
(mmm-add-classes
 '((python-rst
    :submode rst-mode
    :front "^ *[ru]?\"\"\"[^\"]*$"
    :back "^ *\"\"\""
    :include-front t
    :include-back t
    :end-not-begin t)))
(mmm-add-mode-ext-class 'python-mode nil 'python-rst)

I tested this with some Python programs and it seems to work properly.

Note that this will switch to rst-mode for every triple-quoted string, not just the ones at the start of a function definition. You could probably restrict it to just the ones at the start of a function definition with a more complex front regex, but I'm not completely sure how to handle it since I think mmm-mode definitions by default match a line at a time.

Edit: My original version would put Emacs into rst-mode at the point of a single line docstring and then leave it in that mode up until the start of the next docstring. This version avoids putting Emacs into rst-mode if there is another double quote on the same line as the start of the docstring, which still isn't perfect but should be closer.

Problem

How to I get Emacs to use `rst-mode` inside of docstrings in Python files? I vaguely remember that different modes within certain regions of a file is possible, but I don't remember how it's done.

Original source

Related problems