Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a region of python code selected in emacs. What are the most efficient ways to indent and unindent every line in it by 4 spaces?

Ideally I'd like something that's not context sensitive (eg. it'll allow me to indent passages within docstrings where the indentation does not relate to python syntax).

My mode line shows (Python). Searching the web I found a lot of discussion of using python-mode instead of python, but I only started using emacs a few days ago so I'm wary of changing defaults before I have had a chance to understand and them. If changing to python-mode is the best option I'm happy to accept that as an answer.

What I've tried (from the manual):

  • <TAB> no effect
  • C-M-\ no effect
  • C-x <TAB> (indent-rigidly) indent every line by one column (and deselects the region)
  • M-i indents one first line by a tab (length of 8 spaces)
  • C-M-q - "C-M-q is undefined"

The only way I've found is using regex-replace, but that's an awful number of keystrokes for such a simple task.

share|improve this question

5 Answers 5

up vote 37 down vote accepted

Assuming that the variable python-indent is 4:

M-x python-shift-right (C-c >)
M-x python-shift-left  (C-c <)
share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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>

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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