Emacs Lisp: Find Replace Text in Buffer

By Xah Lee. Date: . Last updated: .

Search and Find Replace Functions

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

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

[see Emacs Lisp: Regex Functions]

Find Replace Text in Buffer

Typical way to do string replacement in current buffer:

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

  (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


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

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

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. Example:

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

;; 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 p1 p2) and use (point-min) and (point-max) for boundary, once you narrowed.

Find Replace Multiple Pairs

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

Emacs Regular Expression

Regex in Emacs Lisp