I'm wondering what is the key to toggle line comment in python, because M-; is not working, although it's the line toggle command mentioned in the docs, despite that it's working with block comments when text is selected.

Any help would be appreciated.

P.S: well I could use C-a and put a # or remove it but I'd like to find out about comment toggle.

  • The word Python ,between parentheses, is in the bottom of the screen, isn't that it? – Bahax Jul 24 '15 at 3:50
  • Yes, that is. Do M-x comment-region or M-x uncomment-region work? – Name Jul 24 '15 at 3:53
  • Yes they both do! – Bahax Jul 24 '15 at 4:20
  • @Name I just tried pressing M-; on an uncommented line and it added a # after a some blank spaces in the end of the line. – Bahax Jul 24 '15 at 4:22
  • M-; is a shortcut for M-x comment-dwim. Do M-x describe-binding and make sure that M-; is binded to comment-dwim. – Name Jul 24 '15 at 4:23

I don't know which version of Emacs you're using, but there is (will be) C-x C-; in Emacs 25, it runs comment-line that seem to have the behavior you want.

  • I'm currently using Emacs 24.4.1, I'll upgarde and try your suggestion, thanks! P.S: C-x C-; now seems to set comment column to 0. – Bahax Jul 24 '15 at 18:07
  • Wait, there is NOTHING similar for emacs24 ?! – Ricky Robinson Sep 14 '16 at 9:22

From misc-cmds.el

(defun comment-region-lines (beg end &optional arg)
  "Like `comment-region' (which see), but comment or uncomment whole lines."
  (interactive "*r\nP")
  (when (> beg end) (setq beg  (prog1 end (setq end  beg))))
  (let ((bol  (save-excursion (goto-char beg) (line-beginning-position)))
        (eol  (save-excursion (goto-char end) (if (bolp) (point) (line-end-position)))))
    (comment-region bol eol arg)))

I bind it to C-x C-;.


;; The following code (select-current-line) is due to Xah Lee, see http://lists.gnu.org/archive/html/help-gnu-emacs/2010-12/msg01183.html

(defun select-current-line ()
  "Select the current line"
 (beginning-of-line) ; move to end of line
  (set-mark (line-end-position)))

Now we can define the following function (which uses the idea from https://stackoverflow.com/a/9697222/ due to Gerstmann but it is not identical to that answer).

(defun comment-or-uncomment-line-or-region ()
(save-excursion (if (region-active-p) (comment-dwim nil)
  (select-current-line) (comment-dwim nil)

Now you can define a shortcut for it:

 (eval-after-load "python"
'(define-key python-mode-map (kbd "M-;") #'comment-or-uncomment-line-or-region))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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