In emacs Python mode, how do I set a different auto-fill width for docstrings and code?

2.5k views Asked by At

I would like to have auto-fill set to 79 columns for code sections and 72 for docstrings to get automatic PEP8 compliance. There seems to be an option to do this for Lisp mode (emacs-lisp-docstring-fill-column) but not for Python.

Is there an enhanced python-mode.el around somewhere that includes this?

4

There are 4 answers

8
Andreas Röhler On BEST ANSWER

Current python-mode.el provides

(defcustom py-docstring-fill-column 72 [...]

(defcustom py-comment-fill-column 79 [...]

while for code value of fill-column is used.

0
Drew On

I don't know how to do that, but I've never felt the need. It is so easy to use C-x f to change the fill column. And you can just hit M-p to reuse the last value you entered. Just C-x f M-p --- 3 keystrokes.

3
huaiyuan On

Only slightly tested:

(defadvice current-fill-column (around handle-docstring activate)
  (flet ((docp (p) (let ((q (get-text-property p 'face))
                         (r 'font-lock-string-face))
                     (or (eq r q) (memq r q)))))
    (if (or (docp (point)) (docp (point-at-bol)) (docp (point-at-eol)))
        (setq ad-return-value 72)
      ad-do-it)))

This depends on font-lock-mode being enabled to detect the docstrings.

0
mforbes On

With the current python.el mode as dstributed with Emacs 24.3 you can redefine the python-fill-string as follows (in this example, I also set the fill-column to 85 and change the python-fill-docstring-style):

;; Python customizations
(defun my-python-fill-string (&optional justify)
  (let ((old-fill-column fill-column))
    (setq fill-column 72)
    (python-fill-string justify)
    (setq fill-column old-fill-column)
  ))

(add-hook 'python-mode-hook
          (lambda () (interactive)
            (setq python-fill-docstring-style 'pep-257-nn)
            (set-fill-column 85)
            (setq python-fill-string-function my-python-fill-string)
            ))