In Emacs, how to comment a block of text, i.e. how to indent a block of text rightward by n whitespace characters and put a chosen character sequence, say ##, at the beginning of each line?

Original

foo
bar foobar
   foo bar

Desired:

# foo
# bar foobar
#    foo bar
  • I need a method that doesn't interfere with CUA mode.
  • comment-dwin doesn't allow me to choose arbitrary character sequence.
link|improve this question

72% accept rate
feedback

2 Answers

up vote 5 down vote accepted

One way is to use string-rectangle (C-x r t).

Mark the block, then call string-rectangle and give ## as a string to insert.

link|improve this answer
1  
Here are more concrete steps: 1) move cursor to beginning 2) C-M-@ 3) move cursor to end 4) C-x r t 5) type prefix character sequence, such as ## , press ENT – duperuser Jan 18 at 23:25
feedback

Depending on what mode you are running (e.g. CC Mode, Lisp Mode) you can select the region and then use the command comment-region (usually bound to C-c C-c. If everything is set correctly, it should use the appropriate comment characters for the type of file you are editing.

link|improve this answer
How is this different from M-;? – duperuser Jan 19 at 19:30
@duperuser M-; is a more general commenting command. When there is no active region, it inserts a comment (after any statements on the line, and lined up with the comment column). When a region is selected, it behaves like comment-region. When there is no active region, comment-region does not insert a comment. – jwernerny Jan 19 at 19:43
feedback

Your Answer

 
or
required, but never shown

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