How to prepend # at the head of multiple lines with emacs?
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 l开发者_JS百科ine of a block?
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.
Here's a link that describes how to do this with arbitrary characters in rectangle mode.
This is handy because it only does this for the selected region of text.
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
For those of you that want to achieve this sort of thing but perhaps for more complicated scenarios you might find the following link helpful:
https://stackoverflow.com/a/21725509/1756598
精彩评论