Replacing Buffer Text
You can use the following function to replace some the text of the current buffer:
- Function: replace-region-contents beg end source &optional max-secs max-costs inherit
-
This function replaces the region between beg and end of the current buffer with the text found in source which is usually a string or a buffer, in which case it will use the accessible portion of that buffer.
This function attempts to keep point, markers, text properties, and overlays in the current buffer intact. One potential case where this behavior is useful is external code formatting programs: they typically write the reformatted text into a temporary buffer or file, and using
insertanddelete-regionwould destroy these properties.However, in order to do that,
replace-region-contentsneeds to compare the contents of the original buffer with that of source, using a costly algorithm which makes the operation much slower than a simpleinsertanddelete-region. In many cases, you may not need that refinement, and you will then want to pass 0 as max-secs argument, so as to short-circuit that costly algorithm: It will then be just as fast asinsertanddelete-regionwhile still preserving point and markers marginally better.Beyond that basic usage, if you need to use as source a subset of the accessible portion of a buffer, source can also be a vector
[sbuf sbeg send]where the region between sbeg and send in buffer sbuf is the text you want to use as source.If you need the inserted text to inherit text-properties from the adjoining text, you can pass a non-
nilvalue as inherit argument.When you do want the costly refined replacement, in order to keep
replace-region-contents’s runtime in bounds, it has two optional arguments.max-secs defines a hard boundary in terms of seconds. If given and exceeded, it will fall back to
delete-regionandinsert-buffer-substring.max-costs defines the quality of the difference computation. If the actual costs exceed this limit, heuristics are used to provide a faster but suboptimal solution. The default value is 1000000.
replace-region-contentsreturnstif a non-destructive replacement could be performed. Otherwise, i.e., if max-secs was exceeded, it returnsnil.Note: When using the refined replacement algorithm, if the replacement is a string, it will be internally copied to a temporary buffer. Therefore, all else being equal, it is preferable to pass a buffer than a string as source argument.
Copyright © 1990-1996, 1998-2026 Free Software Foundation, Inc.
Licensed under the GNU GPL license.
https://www.gnu.org/software/emacs/manual/html_node/elisp/Replacing.html