Emacs: Format Python Code π
put this in your Emacs Init File:
(defun xah-python-format-buffer () "Format the current buffer file. Calls the external program βblackβ. Buffer is saved first. URL `http://xahlee.info/emacs/emacs/xah_format_python_code.html' Created: 2022-08-25 Version: 2024-12-22" (interactive) (when (not (buffer-file-name)) (user-error "buffer %s is not a file." (buffer-name))) (when (buffer-modified-p) (save-buffer)) (let ((xoutbuf (get-buffer-create "*xah-python-format output*"))) (save-current-buffer (set-buffer xoutbuf) (erase-buffer)) (call-process "black" nil xoutbuf nil buffer-file-name "-q") (if (eq 1 (save-current-buffer (set-buffer xoutbuf) (point-max))) (progn (kill-buffer xoutbuf) (revert-buffer t t t)) (display-buffer xoutbuf))))
requires python black
.
γsee Python: Format Codeγ