从文档中我可以看到我可以访问命令行参数 (command-line-args)。我想添加自己的参数,但是Emacs在启动时会抱怨它无法识别它们。
例如:
emacs -my_argument
我遇到了以下问题:
command-line-1: 未知选项 `-my_argument'
有什么正确的方法可以定义我的自定义参数并向Emacs会话提供信息吗? 是否有一种从命令行中弹出参数的方法?
将以下内容添加到您的~/.emacs
,~/.emacs.el
或~/.emacs.d/init.el
文件中:
(defun my-argument-fn (switch)
(message "i was passed -my_argument"))
(add-to-list 'command-switch-alist '("-my_argument" . my-argument-fn))
然后你可以执行emacs -my_argument
,它应该会在minibuffer中打印i was passed -my_argument
。你可以在GNU elisp reference中找到更多信息。
command-switch-alist
中,当通过命令行传递匹配的开关时,emacs 将调用处理程序函数。然而,在您的 .emacs
文件被评估后才执行此操作。对于大多数情况而言,这是可以接受的,但您可能希望使用命令行参数来更改 .emacs
评估的执行路径或行为;我经常这样做来启用/禁用配置块(主要用于调试)。command-line-args
并手动检查您的开关,然后从列表中删除它,这将防止 emacs
抱怨未知的参数。(setq my-switch-found (member "-myswitch" command-line-args))
(setq command-line-args (delete "-myswitch" command-line-args))
您可以像这样更改.emacs
的评估:
(unless my-switch-found
(message "Didn't find inhibit switch, loading some config.")
...)
你可以将这个步骤合并为一个:
;; This was written in SO text-box, not been tested.
(defun found-custom-arg (switch)
(let ((found-switch (member switch command-line-args)))
(setq command-line-args (delete switch command-line-args))
found-switch))
(unless (found-custom-arg "-myswitch")
(message "Loading config...")
...)
对于那些感兴趣的人,这里有一个代码片段展示如何在Emacs lisp中处理自定义参数。在本例中,我正在处理变量_suffix
的参数--suffix
/ -S
。
我从一个BSD-Lite Script的Emacs脚本中得到了灵感。
(setq _suffix nil)
;; Process cli args
(while command-line-args-left
(setq k (car command-line-args-left))
(setq command-line-args-left (cdr command-line-args-left))
(setq command-line-args (delete k command-line-args))
(cond
(or (string-equal k "--cs-suffix")
(string-equal k "-S"))
(setq _suffix (intern (car command-line-args-left)))
(setq command-line-args-left (cdr command-line-args-left))
(setq command-line-args (delete _suffix command-line-args))
)))
这将遍历 command-line-args-left
并将它们全部从 command-line-args
中移除,这将防止 Emacs
抱怨。