Elisp: Write File
Write Region to File
To write to a file in a batch script, most of the time you want
;; write current buffer's content to ~/temp.el (write-region (point-min) (point-max) "~/temp.el")
Note: in batch script you should not use
“write-file” is like other editor's “Save As”.
It has side-effects such as opening the file, run its major mode and hooks, and is slow.
[see Emacs Lisp Text Processing: find-file vs with-temp-buffer]
Write String to File
(write-region "something something" nil "filepath")
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 1 (point-max) fPath)))))
Create New File
If you want to create new file, use
(with-temp-file path &rest body)
it'll create a new buffer, then run body, then it'll write to file at path. Existing file at path are overwritten.
;; create new buffer, do things, then write to file at fpath (with-temp-file fpath (insert-file-contents fpath) ;; insert text here )
Append to File
(append-to-file START END FILENAME)
;; append whole buffer content to a file (append-to-file (point-min) (point-max) "filePath")
Elisp, Writing Scritpts
If you have a question, put $5 at patreon and message me.