Elisp: Find Replace String in Buffer

By Xah Lee. Date: . Last updated: .

This page shows you how to do Find Replace in emacs lisp.

Find Replace Text in Buffer

Typical way to do string replacement in current buffer:

(let ((case-fold-search nil))

  (goto-char (point-min))
  (while (search-forward "myStr1" nil t)
    (replace-match "myReplaceStr1"))

  (goto-char (point-min))
  (while (search-forward "myStr2" nil t)
    (replace-match "myReplaceStr2"))

  ;; repeat for other string pairs

  )

If you need regex, re-search-forward.

Letter Case Sensitivity in Search

To control the letter case of search, locally set case-fold-search to t or nil. By default, it's t.

(let (
      (case-fold-search nil) ; case sensitive search
      )
  ;; find replace code here
  )

Letter Case Sensitivity in Replacement

To control letter case of the replacement, use the optional arguments in replace-match function.

(replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING SUBEXP)

Use t for FIXEDCASE.

Match Data

Whenever you use regex in emacs lisp, the captured text is stored in match-string.

Get Match String

match-string

;; the second captured string
(match-string 2)

Get Boundary Positions of Match String

match-beginning and match-end returns the beginning and end positions of the matched string.

;; get the positions of the first captured string
(setq pos1 (match-beginning 1))
(setq pos2 (match-end 1))

Complete match data can be accessed by the function match-data.

Find Replace in a Region Boundary

If you need to do find replace on a region only, wrap the code with save-restriction and narrow-to-region. Example:

(save-restriction (narrow-to-region pos1 pos2) )

;; idiom for string replacement within a region
(save-restriction
  (narrow-to-region pos1 pos2)

  (goto-char (point-min))
  (while (search-forward "myStr1" nil t)
    (replace-match "myReplaceStr1"))

  ;; repeat for other string pairs
  )

If you need to find replace multiple pairs frequently, see: Emacs: xah-replace-pairs.el.

WARNING: Boundary Change After Find Replace

Whenever you work in a region, remember that the boundaries of the text that you are interested is changed when you add or remove text in that region. For example, suppose {p1, p2} is the boundary of some text you are interested. After doing some change there, suppose you want to do some more change. Don't just call (something-region p1 p2) again, because p2 is no longer the correct boundary.

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


ELisp

Basics

Basic Functions

Writing Command

Writing Script

Lisp Data Structure

Lisp Symbol

Elisp Misc