LoginSignup
11
7

More than 5 years have passed since last update.

ファイルを読み込む

Last updated at Posted at 2014-03-04

Emacs Lispでファイルを文字列として読み込んで加工ー、なんてことがしたいとする。

「Emacs ファイル 読み込み」でぐぐると GNU Emacs Lispリファレンスマニュアル: ファイル - 24.3 ファイルの読み込み が出てきて、試してみると「これ、ファイルの中身が直接バッファに出てきちゃうじゃーん」と絶望することになる。

愚直

だが待ってほしい、ここはEmacsの世界だ。郷に入っては郷を従へといふ名セリフを知らないのかよ。

(with-temp-buffer
  (insert-file-contents "./input.txt")
  (buffer-substring-no-properties (point-min) (point-max)))

with-temp-bufferは実にべんりなマクロで、見えないところに一時的なバッファを作ってくれる。
Current Buffer - GNU Emacs Lisp Reference Manualを参照のこと。

(buffer-substring-no-properties (point-min) (point-max)はバッファの中身を全部文字列として得られるいかしたイディオムだぞ!

fの時代

f.elはいかしたファイル操作ライブラリだよ。

(f-read-text "./input.txt")

この一行で済むのでした。ちゃんちゃん♪

El-Getを使ってるなら
(el-get 'sync 'f) とかでインストールできるよ。タブンネ。(Pull Request #1595 · dimitri/el-getがマージされてれば…!)

11
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7