Emacs shell脚本 - 如何将初始选项放入脚本?

Tho*_*ten 18 emacs shell command-line elisp options

受Stack Overflow问题的启发问题Emacs中的文本Idomatic批处理?我尝试了一个带有以下标题的Emacs shell脚本:

#!/usr/bin/emacs --script 
Run Code Online (Sandbox Code Playgroud)

我在其中放入了一些Emacs Lisp代码,并将其保存为textfile rcat.

由于--script选项不会阻止加载site-start文件,因此我有很多

Loading /etc/emacs/site-start.d/20apel.el (source)...
Loading /etc/emacs23/site-start.d/35elib-startup.el (source)...
Loading /etc/emacs23/site-start.d/50auctex.el (source)...
Run Code Online (Sandbox Code Playgroud)

Bash shell中的消息(stdout).我可以通过打电话来阻止

rcat --no-site-file
Run Code Online (Sandbox Code Playgroud)

要么

rcat -Q
Run Code Online (Sandbox Code Playgroud)

但不是通过更改脚本中的标题:

 #!/usr/bin/emacs --script --no-site-file
Run Code Online (Sandbox Code Playgroud)

有没有办法在这样的脚本文件中将其他选项传递给Emacs,而不是稍后在命令行上执行?

Gil*_*il' 34

许多unix变体只允许在shebang行上的程序有一个参数.悲伤,但是真的.如果您使用的#!/usr/bin/env emacs是不依赖于emacs可执行文件的位置,则根本不能传递参数.

链接脚本在某些系统上是可能的,但是在任何地方都不支持.

您可以使用历史悠久的编写多语言脚本的途径:一个既是shell脚本又是Emacs Lisp脚本的脚本(例如Perl's if $running_under_some_shell).它确实看起来很乱,但它确实有效.

Elisp注释开头;,在shell中分隔两个命令.因此我们可以使用a ;后跟shell指令切换到Emacs,实际的Lisp代码从下一行开始.虽然大多数shell都不喜欢空命令,所以我们需要找到shell和Emacs视为无操作的东西,放在之前;.shell no-op命令是:; 就":"shell而言,你可以编写它,而Emacs将它解析为顶层的常量,也是一个无操作.

#! /bin/sh
":"; exec emacs --no-site-file --script "$0" -- "$@" # -*-emacs-lisp-*-
(print (+ 2 2))
Run Code Online (Sandbox Code Playgroud)

  • 交叉引用以下答案+注释,其中显示了如何将`--`参数合并到此方法中以防止Emacs尝试处理传递给脚本的命令行参数http://stackoverflow.com/questions/6759606 /传递论点到的elisp脚本,再次/ 6807133#6807133 (4认同)
  • 伟大的!为什么每个人都对黑客行为如此批评?软件工程师可能找不到像这个这样富有创意的解决方案。 (2认同)
  • 看起来在脚本退出之前仍然需要`(setq argv nil)`的一般解决方案(根据Jurijs Oniscuks的回答),因为Emacs将处理任何剩余的参数作为要访问的文件名.请参阅http://stackoverflow.com/a/24352935/324105 (2认同)

phi*_*ils 11

您可以随时更改#!/usr/bin/emacs为类似的内容#!/home/thorsten/bin/emacs-no-site-file,并将其设置为:

#!/bin/sh
exec /usr/bin/emacs --no-site-file "$@"
Run Code Online (Sandbox Code Playgroud)

如果这对您不起作用,或者您希望您的脚本可以移植,那么请参阅下面的Gilles答案,以获得更强大(并且有点时髦:)的方法.


小智 7

如果您在脚本模式下运行emacs,我建议在脚本结束时将"argv"变量重置为nil,否则emacs将在脚本完成后尝试解释"argv".

假设您有一个名为"test-emacs-script.el"的文件,其中包含以下内容:

#!/usr/bin/emacs --script
(print argv)
(setq argv nil)
Run Code Online (Sandbox Code Playgroud)

尝试将此脚本作为"./test-emacs-script.el -a"运行.如果您运行此脚本而不重置"argv"(脚本中的最后一行),则输出将为:

("-a")
Unknown option `-a'
Run Code Online (Sandbox Code Playgroud)

重置"argv"摆脱"未知选项"错误消息