tags:

views:

95

answers:

2

I need to comment out some blocks of code in Python. How can I do that with emacs? How can I prepend # character at the start of each line of a block?

+9  A: 

You can use the comment-region command using

M-x comment-region

Edit: And as suggested by @Gilles in comment you can use M-; which according to the help is

Call the comment command you want (Do What I Mean).

If the region is active and 'transient-mark-mode' is on, call 'comment-region' (unless it only consists of comments, in which case it calls 'uncomment-region'). Else, if the current line is empty, call 'comment-insert-comment-function' if it is defined, otherwise insert a comment and indent it. Else if a prefix arg is specified, call 'comment-kill'. Else, call 'comment-indent'.

which is probably easier on the long run. :-) Remember that this is "mode-dependant", so you need to set python-mode before you comment using M-x python-mode

Or if you want to prefix every line with any type of character, select the text you want to comment and type

C-x r t

and type the character you want to prefix with. Remember that the caret must be on the first column on the last line that you select, or your text would be replaced.

You select text by pressing C-space and moving your caret around btw.

Patrick
Which is the same as: M-x string-insert-rectangle RET string RET
Zitrax
@Zitrax: Yes, absolutely right
Patrick
There's also `M-;` (`comment-dwim`), which comments the region, (except when the region is already a comment: then it uncomments).
Gilles
A: 

One way would be to define a simple keyboard macro

C-x (
C-a
#
C-n
C-x )

then you can execute it over 100 lines with

M-1 0 0 C-x e

not necessarily the most efficient for this case, but easy to remember

cobbal
or a variant which will apply it to the region: `F3 # F4` then mark the region, then `C-x C-k r`
phils
But you'd be reinventing the wheel: 'comment-region' is one of the most fundamental commands in Emacs. I use it hundreds of times a day.
Joel J. Adamson