Is there any way I can advise python-mode to ignore indentation rules within docstrings?
Yes, in Emacs 25.1 or greater (before that python-indent-context
didn't distinguish string from docstring). Indentation works by setting indent-line-function
to a mode-specific value:
indent-line-function is a variable defined in ‘indent.el’.
Its value is ‘python-indent-line-function’
Local in buffer foo.py; global value is indent-relative
This variable may be risky if used as a file-local variable.
Documentation:
Function to indent the current line.
This function will be called with no arguments.
If it is called somewhere where auto-indentation cannot be done
(e.g. inside a string), the function should simply return ‘noindent’.
Setting this function is all you need to make TAB indent appropriately.
Don’t rebind TAB unless you really need to.
You can advise python-indent-line
like this:
(defun my-python-noindent-docstring (&optional _previous)
(if (eq (car (python-indent-context)) :inside-docstring)
'noindent))
(advice-add 'python-indent-line :before-until #'my-python-noindent-docstring)
Actually, you could technically do it without advice as such, by setting indent-line-function
:
(defun my-python-indent-line ()
(if (eq (car (python-indent-context)) :inside-docstring)
'noindent
(python-indent-line)))
(defun my-python-mode-hook ()
(setq indent-line-function #'my-python-indent-line))
(add-hook 'python-mode-hook #'my-python-mode-hook)