ELisp: 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. END is ignored.
  • If START is a string, write that. END is ignored.
  • FILENAME is a file path or name relative to default-directory.

💡 TIP: If you have a string, or a buffer not associated with a file, use write-region to write a file. Else, if you have a buffer already associated with a file, use save-buffer. [see ELisp: Buffer Functions]

;; write region to file
(write-region (point-min) (point-max) "~/temp.txt")
;; write string to file
(write-region "something something" nil "~/temp.txt")
write-file
(write-file FILENAME &optional CONFIRM)

Write buffer content into a new file, like “save as”, and open that file.

💡 TIP: do not use this, unless you want the user to see opened file after the command, with syntax coloring and running all hooks of a major mode (which are super slow.). To simply write buffer to file, use write-region.

(write-file "~/new.txt")
append-to-file
(append-to-file START END FILENAME)

Append text between 2 positions in current buffer to a file.

  • START and END are buffer positions.
  • If START is nil, write whole buffer. END is ignored.
  • If START is a string, write that. END is ignored.
  • FILENAME is a file path or name relative to default-directory.
;; append whole buffer content to a file
(append-to-file (point-min) (point-max) "~/test.txt" )
save-buffer
(save-buffer &optional ARG)

A user-oriented command to save current buffer. If buffer is not associated with a file, it prompts for a path.

💡 TIP: avoid using this, because it also invokes automatic backup and other hooks.

Create New File

with-temp-file
(with-temp-file FILE BODY)

Create a new buffer, make it current, evaluate BODY, and write the buffer to FILE.

Overwrite existing file at FILE.

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"))

Reference

Emacs Lisp, File, Buffer

Emacs Lisp, Print, Output