emacs实现智能注释


之前使用emacs时遇到这么一个问题

当前行存在代码折叠时,如果想要注释,必须先选中当前行,否则只能注释代码折叠块的第一行

就像这样

基础注释函数来源于 stackoverflow

(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)))

在此函数的位置上进行修改,刚开始使用

(when (hs-already-hidden-p)
    (evil-visual-line))

但是一直没得到想要的效果,后来修改了一下,使用

(when (hs-already-hidden-p)
  (progn
    (end-of-visual-line)
    (evil-visual-state)
    (beginning-of-visual-line)))

意思就是如果当前位置存在代码折叠,先选中当前行,然后注释整个选中区域

因为光标被移动到首位,我对这个不太在意,如果有在意的话,可以使用 save-excursion

(save-excursion
(when (hs-already-hidden-p)
  (progn
    (end-of-visual-line)
    (evil-visual-state)
    (beginning-of-visual-line)))
    ......)

完整代码

(defun comment-or-uncomment-region-or-line ()
  "Comments or uncomments the region or the current line if there's no active region."
  (interactive)
  (save-excursion
    (when (hs-already-hidden-p)
      (progn
        (end-of-visual-line)
        (evil-visual-state)
        (beginning-of-visual-line)))
    (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))))

ok,就这样

作者: honmaple
链接: https://honmaple.me/articles/2017/04/emacs实现智能注释.html
版权: CC BY-NC-SA 4.0 知识共享署名-非商业性使用-相同方式共享4.0国际许可协议
wechat
alipay

加载评论