2

I use elpy package for Python 3 in Emacs. It uses yapf to format a Python buffer. I have tried about everything, setting tab-width to 2 and setting python-indent-offset to 2 but nothing makes it so that when I run elpy-format-code the code is format using two spaces.

I have this in init file,

(set-default tab-width 4)

But I also set it locally within my use-package declaration for elpy. Here are my elpy configs.

;; elpy
(use-package elpy
  :ensure t 
  :init
  (elpy-enable)
  (setq python-shell-interpreter "python3"
        elpy-rpc-python-command "python3"
        python-shell-completion-native-enable nil
        elpy-shell-starting-directory 'current-directory
        python-remove-cwd-from-path nil
        ;; don't prompt before running compile
        compilation-read-command nil)
  ;; to keep the unhelpful warning from *Flymake log* buffer
  (remove-hook
   'flymake-diagnostic-functions
   'flymake-proc-legacy-flymake)
  :hook
  (elpy-mode . (lambda ()
                 (setq tab-width 2
                       python-indent-offset 2)
                 (highlight-indentation-mode -1))))

1 Answer 1

3

Is python-indent-guess-indent-offset set to t? If so, then it's probably looking at your file and deciding to set the python-indent-offset to some other value. Try setting it to nil in the :init for the package. You could also check to see what the value of python-indent-offset is after you've opened the file using C-h v python-indent-offset.

Edit:

I just noticed that you're using an external tool called yapf to autoformat all your Python code. Are you sure it doesn't just defer all those decisions to yapf? Presumably yapf has a config file you are supposed to edit.

3
  • I tried python-indent-guess-indent-offset to nil and checked the python-indent-offset to be 2! The yapf formatting is still happening with 4 spaces. There is also python-indent-guess-indent-offset-verbose which I did not change and is set to t.
    – scribe
    Sep 3, 2020 at 4:53
  • It's actually not me who is using yapf, it came with the package elpy. Maybe you are right and I thought about that too but then thought elpy should parse the correct settings to yapf.
    – scribe
    Sep 6, 2020 at 3:43
  • 1
    Reading here, I was able to make a file ~/.config/yapf/style and add [style] \n INDENT_WIDTH=2 to it and then the yapf formatted the files with two spaces. If you add that to your answer, I'll accept it.
    – scribe
    Sep 6, 2020 at 4:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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