我如何在ELisp中编程确定Emacs运行的操作系统?
我希望能够根据操作系统在 .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 ...
)
progn
)时烧伤了自己多次,所以对于不熟悉这些怪癖的每个人的建议是 - 查看此答案。 - metakermit(if ... (progn ...) '())
。 - Electric Coffeecond
:(cond ((eq system-type 'gnu/linux) "notify-send") ((eq system-type 'darwin) "growlnotify -a Emacs.app -m"))
。其中,当system-type
为gnu/linux
时,返回"notify-send"
;当system-type
为darwin
时,返回"growlnotify -a Emacs.app -m"
。 - ealfonso我创建了一个简单的宏,可以根据系统类型轻松运行代码:
(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!"))
system-type
变量,还有 window-system
变量。
当你想在一些只有 X11 或终端或 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"。
最简单的方法是对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")))
如需更多信息和其他类型的操作系统,请参阅https://www.gnu.org/software/emacs/manual/html_node/elisp/System-Environment.html上有关system-type
的完整文档。
(测试上述代码的简单方法是将其粘贴到您的*scratch*缓冲区中,然后在最外层括号后按C-j键)
还有(至少在版本24-26中)system-configuration
,如果您想要调整构建系统的差异。然而,与system-type
变量的文档描述可能包含的值不同,该变量的文档未描述此变量可能包含的可能值。