0

I'd like to autoformat my python code from the buffer that contains it with a key.

I was looking at this tutorial. One can autoformat the code from the terminal with the command:

autopep8 --in-place --aggressive --aggressive <filename>

I tested it and it works. I'd like to have that bound to a key. The tutorial provides the code:

(defcustom python-autopep8-path (executable-find "autopep8")
  "autopep8 executable path."
  :group 'python
  :type 'string)

(defun python-autopep8 ()
  "Automatically formats Python code to conform to the PEP 8 style guide.
$ autopep8 --in-place --aggressive --aggressive <filename>"
  (interactive)
  (when (eq major-mode 'python-mode)
    (shell-command 
     (format "%s --in-place --aggressive %s" python-autopep8-path
             (shell-quote-argument (buffer-file-name))))
    (revert-buffer t t t)))

(bind-key "C-c C-a" 'python-auto-format)

(eval-after-load 'python
  '(if python-autopep8-path
       (add-hook 'before-save-hook 'python-autopep8)))

that added to my .emacs file, but when I try Ctrl C - Ctrl A I get the error: Wrong type argument: commandp, python-auto-format.

Reading the first answer of this question, they suggest the problem in their case might be that the snippet is for an older version of emacs. I suspect the problem here is the same as the tutorial is from 2015. I have no idea how to modify that code, so that it binds Ctrl C - Ctrl A to the code autoformatting.

3
  • 2
    The error indicates that the there is no command named python-auto-format. You named the command python-autopep8, so try that instead.
    – Dan
    Nov 27 '21 at 21:02
  • Yes, that solved it. Thanks.
    – Schach21
    Nov 27 '21 at 21:45
  • 1
    One of you should add that as an answer to the question.
    – db48x
    Nov 28 '21 at 5:09
1

As pointed out by @Dan in the comments, the problem was that the piece of code invoked python-auto-format, which undefined. Instead, it should be python-autopep8. The functioning code looks like this:

(defcustom python-autopep8-path (executable-find "autopep8")
  "autopep8 executable path."
  :group 'python
  :type 'string)

(defun python-autopep8 ()
  "Automatically formats Python code to conform to the PEP 8 style guide.
$ autopep8 --in-place --aggressive --aggressive <filename>"
  (interactive)
  (when (eq major-mode 'python-mode)
    (shell-command 
     (format "%s --in-place --aggressive %s" python-autopep8-path
             (shell-quote-argument (buffer-file-name))))
    (revert-buffer t t t)))

(bind-key "C-c C-a" 'python-autopep8)  ;;this is the part I changed to make it work

(eval-after-load 'python
  '(if python-autopep8-path
       (add-hook 'before-save-hook 'python-autopep8)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.