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

How to read contents of the file programmatically in Emacs?

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

(require 'json)
(setq config (json-read-from-string (read-file "config.json")))

我得到了这段代码:

(defun read-file (filename)
  (save-excursion
    (let ((new (get-buffer-create filename)) (current (current-buffer)))
      (switch-to-buffer new)
      (insert-file-contents filename)
      (mark-whole-buffer)
      (let ((contents (buffer-substring (mark) (point))))
        (kill-buffer new)
        (switch-to-buffer current)
        contents))))

您可以将代码简化为:

(defun my-file-contents (filename)
  "Return the contents of FILENAME."
  (with-temp-buffer
    (insert-file-contents filename)
    (buffer-string)))

编辑:虽然在这个特定的例子中,我看到 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)))

对于 JSON 只需使用 json-read-file。对于一般文件 f library provides f-read-bytes and f-read-text:

(f-read-text "file.txt" 'utf-8)

对于那些您不喜欢编写太多代码的人,您可以使用 f 库(不是标准库的一部分)中的 f-read。这来自这个问题: