Emacs Lisp: Write File

By Xah Lee. Date: . Last updated: .

Write File

write-region
(write-region START END FILENAME &optional APPEND VISIT LOCKNAME MUSTBENEW)
Write region or string to a file. START and END are buffer positions.
If START is nil, write whole buffer.
If START is a string, write that.
FILENAME is a file path or name relative to default-directory.
;; write region to file
(write-region (point-min) (point-max) "~/temp.el")
;; write string to file
(write-region "something something" nil "filepath")
save-buffer
(save-buffer &optional ARG)
Save current buffer.
;; save current buffer (write to the associated file)
(save-buffer)
write-file
(write-file FILENAME &optional CONFIRM)
Write buffer content into a new file, like “save as”, and open that file.
Note: This is not useful in emacs lisp script. It has side-effects such as opening the file, run its major mode and hooks. [see Emacs Lisp Text Processing: find-file vs with-temp-buffer]
(write-file "~/new.txt")
append-to-file
(append-to-file START END FILENAME)
Append text between 2 positions in current buffer to a file.
;; append whole buffer content to a file
(append-to-file (point-min) (point-max) "~/test.txt" )

Create New File

If you want to create new file, use with-temp-file.

with-temp-file
(with-temp-file FILE BODY)
Create a new buffer, make it current, evaluate BODY, and write the buffer to FILE. Existing file at FILE is overwritten. The value returned is the value of the last form in BODY.
;; create a file with text hello

(with-temp-file "test.txt"
  (insert "hello"))

Here's another way to create a file, with more control.

;; name for new buffer. If start with space, undo is disabled
(setq newBufName " xyz")

;; create a new buffer, save it to a var, so later you can switch to it or kill it
(setq newBuf (generate-new-buffer newBufName))

;; make it current (but does not make it visible), so all insert etc operations works on it.
(set-buffer newBuf)

;; like “Save As”. Save current buffer, close it, and open the new saved
(write-file "~/new.txt")

;; close it
(kill-buffer newBuf)

[see Emacs Lisp: Buffer Functions]

(info "(elisp) Files")

Open, Read, Possibly Write

If you want to write to file ONLY when you actually changed the file, you can create flag variable and use write-region, like this:

(defun my-process-file (fPath)
  "Process the file at path FPATH …"
  (let ((fileChanged-p nil))
    (with-temp-buffer
      (insert-file-contents fPath)

      ;; process text
      ;; set fileChanged-p to t or nil

      (when fileChanged-p (write-region (point-min) (point-max) fPath)))))

(info "(elisp) Writing to Files")

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Practical Elisp ⭐

Writing Command

Writing Script