* lisp/subr.el (replace-in-string): New, side-effect-free function.
* doc/lispref/searching.texi (Search and Replace): Document it.
description of @code{replace-match}.
However, replacing matches in a string is more complex, especially
-if you want to do it efficiently. So Emacs provides a function to do
+if you want to do it efficiently. So Emacs provides two functions to do
this.
@defun replace-regexp-in-string regexp rep string &optional fixedcase literal subexp start
value @var{rep} returns and passes that to @code{replace-match} as the
replacement string. The match data at this point are the result
of matching @var{regexp} against a substring of @var{string}.
+@end defun
+
+@defun replace-in-string fromstring tostring instring
+This function copies @var{instring} and replaces any occurrences of
+@var{fromstring} with @var{tostring}.
@end defun
If you want to write a command along the lines of @code{query-replace},
\f
* Lisp Changes in Emacs 28.1
++++
+*** New function 'replace-in-string'.
+This function works along the line of 'replace-regexp-in-string', but
+matching on strings instead of regexps, and does not change the global
+match state.
+
---
*** 'ascii' is now a coding system alias for 'us-ascii'.
(aset newstr i tochar)))
newstr))
+(defun replace-in-string (fromstring tostring instring)
+ "Replace FROMSTRING with TOSTRING in INSTRING each time it occurs.
+This function returns a freshly created string."
+ (declare (side-effect-free t))
+ (let ((i 0)
+ (start 0)
+ (result nil))
+ (while (< i (length instring))
+ (if (eq (aref instring i)
+ (aref fromstring 0))
+ ;; See if we're in a match.
+ (let ((ii i)
+ (if 0))
+ (while (and (< ii (length instring))
+ (< if (length fromstring))
+ (eq (aref instring ii)
+ (aref fromstring if)))
+ (setq ii (1+ ii)
+ if (1+ if)))
+ (when (= if (length fromstring))
+ (when (not (= start i))
+ (push (substring instring start i) result))
+ (push tostring result)
+ (setq i ii
+ start ii)))
+ (setq i (1+ i))))
+ (when (not (= start i))
+ (push (substring instring start i) result))
+ (apply #'concat (nreverse result))))
+
(defun replace-regexp-in-string (regexp rep string &optional
fixedcase literal subexp start)
"Replace all matches for REGEXP with REP in STRING.
(should-error (ignore-error foo
(read ""))))
+(ert-deftest replace-in-string ()
+ (should (equal (replace-in-string "foo" "bar" "zot")
+ "zot"))
+ (should (equal (replace-in-string "foo" "bar" "foozot")
+ "barzot"))
+ (should (equal (replace-in-string "foo" "bar" "barfoozot")
+ "barbarzot"))
+ (should (equal (replace-in-string "zot" "bar" "barfoozot")
+ "barfoobar"))
+ (should (equal (replace-in-string "z" "bar" "barfoozot")
+ "barfoobarot")))
+
(provide 'subr-tests)
;;; subr-tests.el ends here