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?


bar foobar
   foo bar


# 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.

3 Answers 3


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.

  • 3
    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
    – qazwsx
    Jan 18, 2012 at 23:25
  • is it also possible to do the inverse? May 13, 2016 at 11:07
  • You can select a rectangle and delete it with C-x R K
    – Juancho
    May 13, 2016 at 11:09

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.

  • 10
    How is this different from M-;?
    – qazwsx
    Jan 19, 2012 at 19:30
  • 4
    @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, 2012 at 19:43
  • Not only that, but comment-region, unlike comment-dwim (which is M-; by default) lets you flexibly nest and unnest block comments. Use plain C-u to unnest one level of nesting. (I bind C-x C-; to comment-region. Actually, I bind it to comment-region-lines from misc-cmds.el.)
    – Drew
    Mar 2, 2017 at 18:24

You want to select the code region and then M-;

  • 3
    The best and simple emacs way answer. Mar 8, 2018 at 15:51

You must log in to answer this question.

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