Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read contents of the file programmatically in Emacs?

Tags:

emacs

elisp

I want to read config.json file inside .emacs, how can I do this?

(require 'json)
(setq config (json-read-from-string (read-file "config.json")))
like image 778
jcubic Avatar asked Dec 23 '15 09:12

jcubic


4 Answers

You can simplify your code to:

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

edit: Although in this particular instance, I see that json-read-file is already defined, which cuts out the middle man.

Emacs 24.5 defines it like so:

(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)))
like image 74
phils Avatar answered Oct 20 '22 10:10

phils


For JSON just use json-read-file. For general files f library provides f-read-bytes and f-read-text:

(f-read-text "file.txt" 'utf-8)
like image 40
Mirzhan Irkegulov Avatar answered Oct 20 '22 10:10

Mirzhan Irkegulov


I ended up with this code:

(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))))
like image 1
jcubic Avatar answered Oct 20 '22 08:10

jcubic


For those you dislike writing quite so much code you can use f-read from the f library (not part of the standard library). This comes from this question: elisp: read file into list of lists

like image 1
Att Righ Avatar answered Oct 20 '22 09:10

Att Righ