Elisp: Search Text Functions
Functions for Search Text in Buffer
search-forward-
similar to
re-search-forward, but using plain text to search, not regex. search-backward-
similar to
search-forwardbut search backward.
re-search-forward(alias:search-forward-regexp)-
(re-search-forward REGEXP &optional BOUND NOERROR COUNT)- Search a Regular Expression pattern starting from cursor position, towards right.
- If found, move cursor to the end of matched text.
- Return cursor position.
- BOUND → is
nilor a positive integer (cursor position). Positive integer means don't search beyond it. - NOERROR → value is
nil,t, or something else e.g.1. Ifnil, then abort with error if pattern is not found. Ift, don't abort, and leave cursor at original position. If other value, no error, and move cursor to end of search text. - COUNT → default to 1. Else, search that many times. If negative, search backward.
(let ((case-fold-search nil)) (re-search-forward "[0-9]+")) ;; 100 cats re-search-backward(alias:search-backward-regexp)-
similar to
re-search-forwardbut search backward.🛑 WARNING: searching backward may stop at a position that's not maximally matched by pattern.
;; note, this does not search all the way back (re-search-backward "[- a-z]+" ) ;; it only move cursor one char back ;; to fix it, try to put some boundary char in front. ;; then move forward 1 char (re-search-backward "[^- a-z][- a-z]+" ) (forward-char )
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 )
How Search and Find Replace Works
These search functions are used to search text, do find replace, and also move cursor to where a text occur:
search-forwardsearch-backwardre-search-forward(aliassearch-backward-regexp)re-search-backward(aliassearch-forward-regexp)
The forward versions place cursor at end of match. The backward versions place cursor at begin of match.
These functions also update a global match data, to allow you to get the match beginning position
(match-beginning)
,
end position
(match-end)
,
captured matches
(match-string)
, and also replace the matched text
(replace-match)
.
Elisp, text processing functions
- Elisp: Cursor Position Functions
- Elisp: Move Cursor
- Elisp: Text Editing Functions
- Elisp: Search Text
- Elisp: Find Replace Text in Buffer
- Elisp: Mark, Region, Active Region
- Elisp: Cut Copy Paste, kill-ring
- Elisp: Get Buffer String
- Elisp: Functions on Line
- Elisp: Get Text at Cursor (thing-at-point)
- Elisp: Get Text Block 📜
- Elisp: Save narrow-to-region