Elisp: Text Editing Functions

By Xah Lee. Date: . Last updated: .

Here's the most used functions related to text editing.

Insert Text to Current Buffer at Cursor Position

the following functions insert text to current cursor position. 〔see Cursor Position Functions

insert
(insert &rest ARGS)

Insert string.

;; insert string
(insert "sun and moon")
insert-buffer-substring
(insert-buffer-substring BUFFER &optional START END)

Insert from BUFFER to current buffer.

insert-file-contents
(insert-file-contents FILENAME &optional VISIT BEG END REPLACE)

Insert contents of file FILENAME.

Insert Text to Specific Buffer

insert-into-buffer
(insert-into-buffer BUFFER &optional START END)

Insert text from current buffer into another BUFFER.

append-to-buffer

(append-to-buffer BUFFER START END)

copy current buffer START END region into buffer BUFFER, at that buffer's cursor position.

prepend-to-buffer

Delete Text

delete-char

Delete n characters to the right. Use negative number to delete to the left.

;; delete 9 chars starting at cursor pos
(delete-char 9)
delete-region

(delete-region START END)

  • Delete text between 2 positions. Order of positions does not matter.
  • return nil

the cursor may be moved after the call:

  • If cursor is before the region, no change.
  • If cursor is between the region, it is moved to START.
  • If cursor is after the region, point is updated accordingly. (i.e. Point stay with the text.)

💡 TIP: you may want to always call goto-char after, so the cursor position is explicit.

;; deleting text between positions 59 and 896
(delete-region 59 896)
erase-buffer

Delete all text in buffer, ignores Narrow to Region.

(erase-buffer)
delete-and-extract-region

Delete between 2 positions and return the deleted text.

(delete-and-extract-region 3 20)

Reference

Elisp, text processing functions