Elisp: Text Editing Functions

By Xah Lee. Date: . Last updated: .

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

You should memorize these by heart.

Insert Text

;; insert string at current cursor position
(insert "i ♥ u")

(info "(elisp) Text")

Delete Text

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

;; deleting text btween positions 59 and 896
(delete-region 59 896)

Grab Text from Buffer to String

Functions that grab text in a buffer into a string.

;; return the string between position 99 and 200
(buffer-substring-no-properties 99 200)
;; get thing at point. The “thing” can be
; word, symbol, line, filename, URL and others

;; return string that's the current word
(thing-at-point 'word)

;; return string that's the current word with hyphens or underscore
(thing-at-point 'symbol)

;; return string that's the current line
(thing-at-point 'line)

;; get the start and end positions of a word
(bounds-of-thing-at-point 'word)
;; returs a pair, e.g. (cons 33 38)

For more about thing-at-point, see: Elisp: Using thing-at-point.

(info "(elisp) Buffer Contents")


Functions that take a string argument.

;; length
(length "abc") ; returns 3

;; Extract a substring
(substring myStr myStartPos myEndPos)

;; join strings
(concat "some" "thing")

;; check if a string matches a pattern
(string-match myRegex myStr)

;; get captured match
;; second argument is optional, but required if the last match is done by “string-match”
(match-string 1 myStr)

;; change a given string using regex. Returns changed string.
(replace-regexp-in-string myRegex myReplacement myStr)

;; split a string into parts, returns a list
(split-string "xy_007_cat" "_")

(string-to-number "3") ; change datatype
(number-to-string 3) ; convert to string
(format "%d" 3) ; similar to number-to-string but with fine control

Emacs has only very few functions that takes a string as argument. Any non-trivial string processing is done with a buffer.

If you got a big string already somehow, you can put into a buffer by using with-temp-buffer, then insert your string, process it, then use buffer-string to get the whole buffer content.

;; you got myBigString
;; you want to put into a buffer to work with it

  (insert myBigString)

  (goto-char (point-min))

  ;; do stuff here

  ;; return whole buffer string

(info "(elisp) Strings and Characters")

Elisp Basic Functions

  1. Elisp: Cursor Position Functions
  2. Elisp: Text Editing Functions
  3. Elisp: Buffer and File Functions
  4. Elisp: File and Directory Functions
Like my tutorial? Put $5 at patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

Ask me question on patreon