如何在Emacs中以编程方式读取文件的内容?

jcu*_*bic 4 emacs elisp

我想在.emacs中读取config.json文件,我该怎么做?

(require 'json)
(setq config (json-read-from-string (read-file "config.json")))
Run Code Online (Sandbox Code Playgroud)

phi*_*ils 9

您可以将代码简化为:

(defun my-file-contents (filename)
  "Return the contents of FILENAME."
  (with-temp-buffer
    (insert-file-contents filename)
    (buffer-string)))
Run Code Online (Sandbox Code Playgroud)

编辑:虽然在这个特定的例子中,我看到json-read-file已经定义了,这削减了中间人.

Emacs 24.5定义如下:

(defun json-read-file (file)
  "Read the first JSON object contained in FILE and return it."
  (with-temp-buffer
    (insert-file-contents file)
    (goto-char (point-min))
    (json-read)))
Run Code Online (Sandbox Code Playgroud)