Emacs bulk indent for Python

前端 未结 8 1243
星月不相逢
星月不相逢 2021-01-29 17:37

Working with Python in Emacs if I want to add a try/except to a block of code, I often find that I am having to indent the whole block, line by line. In Emacs, how do you inden

8条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-29 18:16

    I've been using this function to handle my indenting and unindenting:

    (defun unindent-dwim (&optional count-arg)
      "Keeps relative spacing in the region.  Unindents to the next multiple of the current tab-width"
      (interactive)
      (let ((deactivate-mark nil)
            (beg (or (and mark-active (region-beginning)) (line-beginning-position)))
            (end (or (and mark-active (region-end)) (line-end-position)))
            (min-indentation)
            (count (or count-arg 1)))
        (save-excursion
          (goto-char beg)
          (while (< (point) end)
            (add-to-list 'min-indentation (current-indentation))
            (forward-line)))
        (if (< 0 count)
            (if (not (< 0 (apply 'min min-indentation)))
                (error "Can't indent any more.  Try `indent-rigidly` with a negative arg.")))
        (if (> 0 count)
            (indent-rigidly beg end (* (- 0 tab-width) count))
          (let (
                (indent-amount
                 (apply 'min (mapcar (lambda (x) (- 0 (mod x tab-width))) min-indentation))))
            (indent-rigidly beg end (or
                                     (and (< indent-amount 0) indent-amount)
                                     (* (or count 1) (- 0 tab-width))))))))
    

    And then I assign it to a keyboard shortcut:

    (global-set-key (kbd "s-[") 'unindent-dwim)
    (global-set-key (kbd "s-]") (lambda () (interactive) (unindent-dwim -1)))
    

提交回复
热议问题