Emacs sh-mode下注释缩进问题:如何实现指定格式?
Emacs sh-mode 多行注释缩进调整
问题描述
在sh-mode中执行M-x indent-region后,带反斜杠换行的注释会出现多余缩进:
默认缩进效果:
# command --with --many --options \ # --after --backslah
期望达到的效果:
# command --with --many --options \ # --after --backslah
注:带管道符的多行注释缩进是符合预期的:
# command --with -options | # command2 --after --pipe
复现步骤
- 输入已正确缩进的代码:
command --with --many --options \ --after --backslash
- 选中代码执行
M-x comment-region(此步骤无异常) - 再执行
M-x indent-region后出现注释缩进异常
解决方法
在Emacs配置文件(如~/.emacs或~/.emacs.d/init.el)中添加以下自定义函数及配置,让sh-mode识别带反斜杠结尾的注释行,强制后续注释行的#保持在第0列:
(defun my-sh-indent-comment (indent) "调整sh-mode的注释缩进:若上一行注释以反斜杠结尾,当前注释的#保持在第0列" (if (and (save-excursion (beginning-of-line) (looking-at "\\s-*#")) (save-excursion (forward-line -1) (and (not (bobp)) (string-match "\\\\$" (buffer-substring (line-beginning-position) (line-end-position)))))) 0 indent)) (setq sh-indent-comment-function 'my-sh-indent-comment)
添加后重启Emacs或执行M-x eval-buffer加载配置,即可实现预期的注释缩进效果。
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

