【问题标题】:Open zsh scripts in sh-mode in emacs在 emacs 中以 sh 模式打开 zsh 脚本
【发布时间】:2013-12-31 17:50:58
【问题描述】:

*.zsh 文件以默认模式打开(对我来说是文本模式)。但是,sh-mode 实际上是多种模式,包括 zsh、bash 等的行为。如何告诉 emacs 以 sh-mode 的 zsh 风格打开 *.zsh 文件?

【问题讨论】:

  • auto-mode-alist 添加一个条目,将.zsh 后缀映射到您想要的模式。

标签: emacs zsh


【解决方案1】:

sh-mode 的风格是从 shebang 行(脚本的第一行)自动检测到的。如果您有“#!/bin/zsh”,则将假定 zsh 并且(例如)autoload 将被识别为关键字。如果第一行是“#!/bin/bash”,autoload 将不会被识别

要让 emacs 将 *.zsh 文件识别为 shell 脚本,只需将其添加到您的 init 文件中:

(add-to-list 'auto-mode-alist '("\\.zsh\\'" . sh-mode))

当您不想使用 shebang 时,一种以编程方式选择风味的方法是在 sh 模式缓冲区中执行此操作:

(sh-set-shell "zsh")

所以在你的情况下,你需要(除非你使用 shebang)是更新上面的自动模式列表和

(add-hook 'sh-mode-hook
          (lambda ()
            (if (string-match "\\.zsh$" buffer-file-name)
                (sh-set-shell "zsh"))))

【讨论】:

  • 啊,谢谢,我知道调用 sh-mode,但不知道它会自动检测类型。如果我没有 sebang 线,我还能让它自动工作吗?
  • 您知道为什么(add-to-list 'auto-mode-alist '("\\.zsh\\'" . sh-mode)) 在我的emacs 中完全没有影响吗? sh-mode 已安装,我可以手动启动它。
【解决方案2】:

无论您的文件是否有#! shebang,您始终可以使用文件模式行或局部变量部分来设置 shell 脚本模式。即使您没有更新 auto-mode-alist,在您的脚本中包含其中之一将允许 Emacs 做正确的事情,因此建议用于任何非标准文件扩展名。

shell 脚本的 Emacs 文件模式行是 -*- mode: sh -*-。它应该在注释中,并且必须出现在第一行(如果第一行是 shebang 行,则必须出现在第二行)。

如果由于某种原因无法将其放在第一(第二)行,您可以在文件末尾(在文件的最后 3000 个字符中,在最后一页)创建一个局部变量部分, according to the manual):

# Local Variables:
# mode: sh
# End:

请注意,仅设置 Emacs 模式仍将依赖 shebang 行进行 shell 类型自动检测,如果未检测到 shebang 行将默认为当前的 SHELL 环境变量或 sh-shell-file 的值(如果已设置)。

如果您没有 shebang 行,但希望选择正确的 shell 类型,唯一的方法是在模式行或局部变量部分使用 eval。添加它会在每次将文件加载到 Emacs 时生成确认提示,因此通常不建议这样做,但在某些情况下可能可以接受。 模式行为-*- mode: sh; eval: (sh-set-shell "zsh") -*-,局部变量形式为:

# Local Variables:
# mode: sh
# eval: (sh-set-shell "zsh")
# End:

【讨论】:

  • 谢谢!这很酷!我现在正在计划使用此功能的绝妙方法。
【解决方案3】:

如果使用shebang方法,更健壮的形式是

#!/usr/bin/env zsh
# env will search the path for zsh.  Some distros may put it a different place.
# env is pretty much guaranteed to be in /usr/bin

【讨论】:

  • 这与问题无关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2017-07-26
  • 2012-01-09
  • 2014-02-26
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
相关资源
最近更新 更多