Emacs bulk indent for Python

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 indent the whole block at once.

I am not an experienced Emacs user, but just find it is the best tool for working through ssh. I am using Emacs on the command line(Ubuntu), not as a gui, if that makes any difference.


If you are programming Python using Emacs, then you should probably be using python-mode. With python-mode, after marking the block of code,

Cc > or Cc Cl shifts the region 4 spaces to the right

Cc < or Cc Cr shifts the region 4 spaces to the left

If you need to shift code by two levels of indention, or some arbitary amount you can prefix the command with an argument:

Cu 8 Cc > shifts the region 8 spaces to the right

Cu 8 Cc < shifts the region 8 spaces to the left

Another alternative is to use Mx indent-rigidly which is bound to Cx TAB :

Cu 8 Cx TAB shifts the region 8 spaces to the right

Cu -8 Cx TAB shifts the region 8 spaces to the left

Also useful are the rectangle commands that operate on rectangles of text instead of lines of text.

For example, after marking a rectangular region,

Cx ro inserts blank space to fill the rectangular region (effectively shifting code to the right)

Cx rk kills the rectangular region (effectively shifting code to the left)

Cx rt prompts for a string to replace the rectangle with. Entering Cu 8 <space> will then enter 8 spaces.

PS. With Ubuntu, to make python-mode the default mode for all .py files, simply install the python-mode package.


In addition to indent-region , which is mapped to CM- by default, the rectangle edit commands are very useful for Python. Mark a region as normal, then:

  • Cx rt ( string-rectangle ): will prompt you for characters you'd like to insert into each line; great for inserting a certain number of spaces
  • Cx rk ( kill-rectangle ): remove a rectangle region; great for removing indentation
  • You can also Cx ry ( yank-rectangle ), but that's only rarely useful.


    indent-region映射到CM-应该做的伎俩。

    链接地址: http://www.djcxy.com/p/6568.html

    上一篇: 是否有可能在Python中打破多行

    下一篇: Python的Emacs批量缩进