0

How to indent a block of text rightward by 2 whitespace characters in Emacs?

How to indent a block of text rightward by 4 whitespace characters in Emacs?

[EDIT] I need a method that doesn't interfere with CUA mode.

3 Answers 3

4

Try the key binding C-x TAB (aka C-x C-i) which is bound to indent-rigidly, which indents a region by a single space.

So, you'd indent by two by pressing that twice setting the region around the code you want to indent and typing:

C-x C-i C-x C-i

Or, you can pass a numeric prefix with

C-u 2 C-x C-i

To get 4 spaces, do a prefix with 4

C-u 4 C-x C-i

And, as a bonus, you can remove spaces with a negative prefix argument. Removing 4 spaces is accomplished by

C-u - 4 C-x C-i
8
  • How to set the starting and ending points of the block to which I want to indent?
    – qazwsx
    Jan 17, 2012 at 7:42
  • @user6076: the same way you mark a region for any other purpose. In one of the positions, press C-space, and navigate to the other.
    – choroba
    Jan 17, 2012 at 8:18
  • There are two ways to mark a region of code: M-x mark-sexp and M-x mark-defun. Jan 17, 2012 at 15:32
  • @choroba Doing what you described deletes the text in the block.
    – qazwsx
    Jan 17, 2012 at 17:45
  • 1
    To select a block of text to indent: 1) move cursor to the beginning of the block by mouse or up arrow key; 2) C-M-@ 3) move cursor to the end of the block 4) C-X C-i
    – Computist
    Jan 17, 2012 at 22:16
2

You can also use Rectangles.

Mark the beginning of the region with C-Space, go to then end of the region and then type C-xrtRET.

Example:

v----------------------- cursor position
blabla bla bla bla
bla bla bla
bla bla bla

C-SpaceC-nC-n

blabla bla bla bla
bla bla bla
bla bla bla
^----------------------- cursor position

C-xrtM-2RET

  blabla bla bla bla
  bla bla bla
  bla bla bla
  ^----------------------- cursor position
2
  • By go to then end of the region, what concrete keyboard and/or mouse movement do you do? If I use down arrow key to do that, the following C-x will delete the text.
    – qazwsx
    Jan 17, 2012 at 17:47
  • As described in the example I've used C-n. C-space pushes a mark at the current position and C-n goes to the next line.
    – Daimrod
    Jan 18, 2012 at 16:48
0

I noticed your edit "I need a method that doesn't interfere with CUA mode." Assuming you have CUA mode enabled, I would also like to recommend you to try C-Enter (cua-set-rectangle-mark). Here is the sequence that works for me.

  1. Move the cursor to the start (top-left) of the block.
  2. Press C-ENTER.
  3. Move the cursor down to the end (bottom-left) of the block.
  4. Press SPACE twice or four times depending on your indentation width.
  5. Press C-ENTER to quit the selection.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .