1

almost everytime, I cope e.g. snippets from the web and paste it with M-w in a python buffer the indentation is all wrong. Sometimes slanted to the left, sometimes to the right. Often all of the copied text, sometimes only parts of it. I have this in my config

(global-set-key (kbd "C->") 'indent-rigidly-right-to-tab-stop)
(global-set-key (kbd "C-<") 'indent-rigidly-left-to-tab-stop)

but neither that nor multiple cursors are sufficient in these situations. So I searched for snippets online and included this long piece here

; indent pasted stuff correctly
(dolist (command '(yank yank-pop))
   (eval `(defadvice ,command (after indent-region activate)
            (and (not current-prefix-arg)
                 (member major-mode '(emacs-lisp-mode lisp-mode
                                                      clojure-mode    scheme-mode
                                                      haskell-mode    ruby-mode
                                                      rspec-mode      python-mode
                                                      c-mode          c++-mode
                                                      objc-mode       latex-mode
                                                      plain-tex-mode))
                 (let ((mark-even-if-inactive transient-mark-mode))
                   (indent-region (region-beginning) (region-end) nil))))))

still no luck. My python config reads

(use-package python
 :mode ("\\.py\\'" . python-mode)
 :interpreter ("python" . python-mode)
 :config
 (progn (setq python-shell-interpreter "python")
        (setq python-indent-offset 4)
        (setq python-shell-completion-native-disabled-interpreters '("python"))))

So how can I achieve to just paste in code and it is indented and aligned correctly?

2
  • May you provide some example? Ideally from the web source alongside with the results in Emacs buffer? – Andreas Röhler Nov 22 '19 at 20:18
  • @CD86, please note in menu Emacs | Python you already have two commands - Shift region left (C-c <) and Shift region right (C-c >) - maybe these are more useful? Does these interfere with yours? Also observed some authors do not respect correct indentation (some at 2, found with 3...) – Ian Nov 23 '19 at 15:28

Your Answer

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

Browse other questions tagged or ask your own question.