Emacs实现智能注释


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

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

就像这样

基础注释函数来源于 stackoverflow

1(defun comment-or-uncomment-region-or-line ()
2  "Comments or uncomments the region or the current line if there's no active region."
3  (interactive)
4  (let (beg end)
5    (if (region-active-p)
6        (setq beg (region-beginning) end (region-end))
7      (setq beg (line-beginning-position) end (line-end-position)))
8    (comment-or-uncomment-region beg end)))

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

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

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

1(when (hs-already-hidden-p)
2  (progn
3    (end-of-visual-line)
4    (evil-visual-state)
5    (beginning-of-visual-line)))

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

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

1(save-excursion
2(when (hs-already-hidden-p)
3  (progn
4    (end-of-visual-line)
5    (evil-visual-state)
6    (beginning-of-visual-line)))
7    ......)

完整代码

 1(defun comment-or-uncomment-region-or-line ()
 2  "Comments or uncomments the region or the current line if there's no active region."
 3  (interactive)
 4  (save-excursion
 5    (when (hs-already-hidden-p)
 6      (progn
 7        (end-of-visual-line)
 8        (evil-visual-state)
 9        (beginning-of-visual-line)))
10    (let (beg end)
11      (if (region-active-p)
12          (setq beg (region-beginning) end (region-end))
13        (setq beg (line-beginning-position) end (line-end-position)))
14      (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

加载评论