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

;; idiom for string replacement in current buffer

(let ((case-fold-search t)) ; or 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 regexp, use search-forward-regexp

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.


Use t for FIXEDCASE.

Match Data

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

Get 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 2nd captured string
(setq pos1 (match-beginning 2)
      pos2 (match-end 2))

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:

;; idiom for string replacement within a region
  (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 Multi-Pair Find Replace.

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.

Use save-restriction and narrow-to-region, like this:

  (narrow-to-region pos1 pos2)
  (something1-region (point-min) (point-max))
  (something2-region (point-min) (point-max))

Elisp: Writing Command

  1. Writing Command, Basics
  2. Mark and Region
  3. Get Buffer String
  4. Work with Lines
  5. Copy Cut Paste kill-ring
  6. Get User Input
  7. Interactive Form
  8. Get universal-argument
  9. Find Replace Text
  10. thing-at-point
  11. Get Dired Marked Files

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs


Emacs Lisp