emacs: how to indent/unindent region of python code by 4 spaces?

Solution 1:

Assuming that the variable python-indent is 4:

M-x python-shift-right (C-c >)
M-x python-shift-left  (C-c <)

Solution 2:

indent-rigidly takes a prefix argument indicating how much to indent by, so C-u 42 C-x TAB indents by 42 columns, and since the default prefix argument is 4, C-u C-x TAB indents by 4 columns.

If you want to select the region again, do C-x C-x afterwards.

Solution 3:

Use the indent-rigidly command with a numeric prefix.

C-u 4 M-x indent-rigidly to indent the region by four spaces, C-u -4 M-x indent-rigidly to remove four spaces.

Solution 4:

C-x C-x mark the code and then M-x indent-for-tab-mode

That's the save if you have pressed tab for every line.

Solution 5:

You could also use column mode.

Select the lines in column mode, then add four spaces to all of them at once:

  1. Jump to column 1 of the first line you want to indent.
  2. C-<space> to set mark
  3. move the point down to the last lines (stay in column one)
  4. C-x r t to enter column mode (or C-<RET> if you've got CUA mode)
  5. <space><space><space><space><RET>

You can do a similar maneuver to delete four spaces -- just include 4 columns in your marked region (steps 2-3) and hit <DEL>