簡體   English   中英

在 emacs 中以 sh 模式打開 zsh 腳本

[英]Open zsh scripts in sh-mode in emacs

*.zsh文件以默認模式打開(對我來說是文本模式)。 但是,sh-mode 實際上是多種模式,包括 zsh、bash 等的行為。我如何告訴 emacs 以 sh-mode 的 zsh 風格打開*.zsh文件?

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

您的文件是否有#! 不管是否是shebang,您始終可以使用文件模式行或局部變量部分來設置shell 腳本模式。 即使您沒有更新 auto-mode-alist,在您的腳本中擁有其中之一將允許 Emacs 做正確的事情,因此建議用於任何非標准文件擴展名。

shell 腳本的 Emacs 文件模式行是-*- mode: sh -*- 它應該在注釋中,並且必須出現在第一行(如果第一行是 shebang 行,則出現在第二行)。

如果由於某種原因不能把它放在第一(第二)行,你可以在文件的末尾(文件的最后 3000 個字符,最后一頁, 根據手冊):

# Local Variables:
# mode: sh
# End:

請注意,僅設置 Emacs 模式仍將依賴 shebang 行進行 shell 類型自動檢測,如果未檢測到 shebang 行,將默認為當前的SHELL環境變量或sh-shell-file的值(如果已設置)。

如果您沒有 shebang 行,但希望選擇正確的 shell 類型,那么唯一的方法是在模式行或局部變量部分使用eval 添加此項會在每次將文件加載到 Emacs 時生成確認提示,因此通常不建議這樣做,但在某些情況下可能是可以接受的。 模式行將是-*- mode: sh; eval: (sh-set-shell "zsh") -*- -*- mode: sh; eval: (sh-set-shell "zsh") -*- ,局部變量形式為:

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

如果你使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM