Emacs评论/取消注释当前行

Dav*_*mes 42 emacs elisp

我知道已经有一个关于这个问题的Emacs问题,并且关闭了,但我发现它非常重要且非常重要.

基本上,我想评论/取消注释当前行.我期望用宏可以很容易,但我发现它确实不是.

如果当前行已注释,请取消注释.如果取消注释,请对其进行评论.而且我还要评论整条线,而不仅仅是光标位置.

我试过像这样的宏:

C-a

'comment-dwim
Run Code Online (Sandbox Code Playgroud)

但这只是评论一条线,而不是取消注释它,如果它已经评论过.

我不确定它有多容易,但如果有某种方式,我真的很喜欢它.

另外,我非常喜欢这个想法的原因是,当我使用Geany时,我只是使用C-e它并且它是完美的.

Ger*_*ann 94

Trey的功能完美,但不是很灵活.

试试这个:

(defun comment-or-uncomment-region-or-line ()
    "Comments or uncomments the region or the current line if there's no active region."
    (interactive)
    (let (beg end)
        (if (region-active-p)
            (setq beg (region-beginning) end (region-end))
            (setq beg (line-beginning-position) end (line-end-position)))
        (comment-or-uncomment-region beg end)))
Run Code Online (Sandbox Code Playgroud)

如果一个是活动的,它会注释/取消注释当前行或区域.


如果您愿意,可以修改函数以在(un)注释当前行之后跳转到下一行:

(defun comment-or-uncomment-region-or-line ()
    "Comments or uncomments the region or the current line if there's no active region."
    (interactive)
    (let (beg end)
        (if (region-active-p)
            (setq beg (region-beginning) end (region-end))
            (setq beg (line-beginning-position) end (line-end-position)))
        (comment-or-uncomment-region beg end)
        (next-line)))
Run Code Online (Sandbox Code Playgroud)

请注意,只有更改的内容是next-line函数末尾添加的命令.

  • 使用`next-logical-line`而不是`next-line`可能更有意义,这样如果行很长,用户就不会对它进行评论,然后再将其取消注释. (6认同)
  • 这实际上可能更好,如果在注释一行后,光标移动到下一行,因此重复按键绑定将注释连续的行.这样做的任何提示? (4认同)
  • @justingordon我在原版下编辑了另一个版本.请享用! (3认同)
  • 完美的工作!谢谢! (2认同)
  • 这很棒!它应该是默认行为. (2认同)

Tre*_*son 40

试试这个功能,并绑定到你最喜欢的键:

(defun toggle-comment-on-line ()
  "comment or uncomment current line"
  (interactive)
  (comment-or-uncomment-region (line-beginning-position) (line-end-position)))
Run Code Online (Sandbox Code Playgroud)


Arn*_*rne 10

我接受了Trey的回答并对其进行了改进,以便当一个区域处于活动状态时它也可以工作,但是然后在该区域上工作:

(defun comment-or-uncomment-line-or-region ()
  "Comments or uncomments the current line or region."
  (interactive)
  (if (region-active-p)
      (comment-or-uncomment-region (region-beginning) (region-end))
    (comment-or-uncomment-region (line-beginning-position) (line-end-position))
    )
  )

(define-key c-mode-base-map (kbd "C-/") 'comment-or-uncomment-line-or-region)
Run Code Online (Sandbox Code Playgroud)