如何以编程方式确定在 ELisp 中运行 Emacs 的操作系统?
我想根据操作系统在
.emacs
中运行不同的代码。
system-type
变量:
system-type is a variable defined in `C source code'.
Its value is darwin
Documentation:
Value is symbol indicating type of operating system you are using.
Special values:
`gnu' compiled for a GNU Hurd system.
`gnu/linux' compiled for a GNU/Linux system.
`darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...).
`ms-dos' compiled as an MS-DOS application.
`windows-nt' compiled as a native W32 application.
`cygwin' compiled using the Cygwin library.
Anything else indicates some sort of Unix system.
对于刚接触 elisp 的人,示例用法:
(if (eq system-type 'darwin)
; something for OS X if true
; optional something if not
)
或者,如果我们不关心 else-form 并且有多个 then-forms,
(when (eq system-type 'darwin)
; do this
; and this ...
)
我创建了一个简单的宏来根据系统类型轻松运行代码:
(defmacro with-system (type &rest body)
"Evaluate BODY if `system-type' equals TYPE."
(declare (indent defun))
`(when (eq system-type ',type)
,@body))
(with-system gnu/linux
(message "Free as in Beer")
(message "Free as in Freedom!"))
在.emacs中,不仅有
system-type
,还有window-system
变量。
当你想在一些仅限 x 的选项、终端或 macos 设置之间进行选择时,这很有用。
现在还有适用于 Windows 的 Linux 子系统(Windows 10 下的 bash),其中
system-type
是 gnu/linux
。要检测此系统类型,请使用:
(if
(string-match "Microsoft"
(with-temp-buffer (shell-command "uname -r" t)
(goto-char (point-max))
(delete-char -1)
(buffer-string)))
(message "Running under Linux subsystem for Windows")
(message "Not running under Linux subsystem for Windows")
)
这大部分已经回答了,但对于那些感兴趣的人,我刚刚在 FreeBSD 上测试了这个,报告的值为“berkeley-unix”。
还有(至少在版本 24-26 中)
system-configuration
,如果你想调整构建系统的差异。但是,此变量的文档没有像 system-type
变量的文档那样描述它可能包含的可能值。
最简单的方法是对
system-type
变量进行模式匹配,如下所示:
(pcase system-type
;; GNU/Linux or WSL
(gnu/linux
(message "This is GNU/Linux"))
;; macOS
(darwin
(message "This is macOS"))
;; Windows
(windows-nt
(message "This is Windows"))
;; BSDs
(berkeley-unix
(message "This is a BSD"))
;; Other operating system
(_
(message "Unknown operating system")))
有关更多信息和其他类型的操作系统,请参阅
system-type
中的完整文档 https://www.gnu.org/software/emacs/manual/html_node/elisp/System-Environment.html
(测试上述代码的一种简单方法是将其粘贴到 *scratch* 缓冲区中,然后在最外面的括号后按 C-j)