Elisp: Buffer and File Functions

By Xah Lee. Date: . Last updated: .

Here's the most useful functions for file and buffer.

You should memorize these by heart.

Buffers

Functions that act on the buffer. Most buffer functions assume the current buffer if no argument is given. Some requires a argument. The argument can usually be a buffer's name, or a buffer object.

buffer-name → return the name of current buffer.

;; return the name of current buffer
(buffer-name)

buffer-file-name → return the full path of the file, or nil if not a file.

;; return the full path of the file
(buffer-file-name)

kill-buffer → close a given buffer.

;; close a given buffer
(kill-buffer myBuffer)

with-temp-buffer → Use temp buffer.

;; use a temp buffer to manipulate string
(with-temp-buffer
  (insert myStr)
  ;; manipulate the string here
  (buffer-string) ; get result
)

(info "(elisp) Buffers")

Switch Buffer

set-buffer → switch to a given buffer temporarily. (does not make the buffer visible.)

;; switch to a given buffer
(set-buffer myBuffer)

switch-to-buffer → switch to a given buffer. Avoid using this in lisp code.

(switch-to-buffer myBuffer)

Files

{Open, Append, Write} Files

;; open a file (returns a buffer)
(find-file "~/test.txt")

;; save current buffer (write to the associated file)
(save-buffer)

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

;; append text between positions 100 to 200 to file
(append-to-file 100 200 "~/test.txt")

;; close a buffer
(kill-buffer myBuffName)

(info "(elisp) Files")

Elisp Basic Functions

  1. Elisp: Cursor Position Functions
  2. Elisp: Text Editing Functions
  3. Elisp: String Functions
  4. Elisp: Buffer and File Functions
  5. Elisp: File and Directory Functions
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.