You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

复现步骤

  1. 输入已正确缩进的代码:
command --with --many --options \
        --after --backslash
  1. 选中代码执行M-x comment-region(此步骤无异常)
  2. 再执行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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:32:19