Is there a way to format a full python buffer in emacs with a keystroke?

I'm looking for any way for Emacs to format a Python buffer by pressing a few keys. By format, I mean:

  • Replace tabs with four spaces
  • Wrap all long lines correctly with 79 characters. This includes wrapping and concatenating a long string, wrapping long comments, wrapping lists, function headers, etc.
  • Unrelated, but when I press enter, it would be nice if the cursor was automatically bookmarked.

In general, I would just like to format everything according to PEP 8.

I was looking for a beautiful printer / code / code formatter for Python to run a buffer, but cannot find open source.

My.emacs is here .

For those who are going to answer "You do not need a formatter for Python, it is beautiful by the nature of the language," I tell you that this is not true. In real software systems, comments should be automatically wrapped for you, lines will be longer than 79 characters, tab levels will work with a depth of 3+. Please just help me solve my problem directly without any philosophical discussion about the virtues of formatting a Python source.

+3
source share
5 answers

To change tabs to spaces and fill in comments at the same time, you can use this command:

(defun my-format-python-text ()
  "untabify and wrap python comments"
  (interactive)
  (untabify (point-min) (point-max))
  (goto-char (point-min))
  (while (re-search-forward comment-start nil t)
    (call-interactively 'fill-paragraph)
    (forward-line 1)))

What you can bind to a key of your choice, presumably like this:

(eval-after-load "python"
  '(progn
     (define-key python-mode-map (kbd "RET") 'newline-and-indent)
     (define-key python-mode-map (kbd "<f4>") 'my-format-python-text)))

RET .

, :

C-x h           ;; mark-whole-buffer
M-x untabify    ;; tabs->spaces

, , .emacs:

(setq fill-column 79)
(setq-default tab-width 4)

, ​​ 8, , (8 ). , 4 'python-mode-hook. .

+4

3:

, enter, , .

emacs Python , -. python-mode...

+1

- . ,

;; Turn off tab insertion in favor of space insertion
(setq-default indent-tabs-mode nil)

, .emacs

0
0

Python Spacemacs :

, = yapfify-buffer, PEP8 .

(setq-default dotspacemacs-configuration-layers '(
  (python :variables python-enable-yapf-format-on-save t)))

.

0

Source: https://habr.com/ru/post/1715338/


All Articles