Elisp: Find Replace Text in Buffer

By Xah Lee. Date: . Last updated: .

Search and Find Replace Functions

These search functions are used to search text, do find replace, and also move cursor to where a text occur:

The forward versions place cursor at end of match. The backward versions place cursor at begin of match.

Find Replace Text in Buffer

Typical way to do text replacement in current buffer:

(let ((case-fold-search nil))
  ;; set case-fold-search to t, if you want to ignore case

  (goto-char (point-min))
  (while (search-forward "myStr" nil t)
    (replace-match "myReplaceStr"))

  ;; repeat for other string pairs

  ;; use re-search-forward if you want regex


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))
  ;; set case-fold-search to t, if you want to ignore case
  ;; search text code here

Case Sensitivity in Replacement

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


Use t for FIXEDCASE.

By default, the letter case used in replacement is smart. If the found text is First-cap or ALLCAPS, the replacement is accordingly.

Match Data

the begin/end positions of match, or capture, are storedin match-data.

Find Replace in a Region

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

;; 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

🛑 WARNING: Boundary Change After Insert/Remove text

Whenever you work in a region, remember that the position of the end boundary 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.

A good solution is to use narrow-to-region. Elisp: Save narrow-to-region

Find Replace Multiple Pairs

A package to allow easy code for to find replace multiple pairs.

Elisp, Regex in Lisp Code

Elisp, text processing functions