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

40,284

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

Updating Chen's solution above, currently (tested on Emacs 24.4.1) the commands have been renamed. So, assuming you want to indent according to the variable python-indent, the commands are python-indent-shift-left and python-indent-shift-right. You can:

  1. issue them by typing M-x python-indent-shift-right or M-x python-indent-shift-left

  2. use the default python-mode short cuts C-c > and C-c <

  3. rebind them. E.g., on a keyboard with a windows button I use:

    (global-set-key (kbd "s-s") 'python-indent-shift-left) 
    (global-set-key (kbd "s-d") 'python-indent-shift-right)
    
Share:
40,284

Related videos on Youtube

Aishwarya R
Author by

Aishwarya R

Updated on September 17, 2022

Comments

  • Aishwarya R
    Aishwarya R over 1 year

    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.

  • SCH
    SCH almost 9 years
    I had to do python-indent-shift-left.