33.23 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 insert and delete-region would destroy these properties.

However, in order to do that, replace-region-contents needs to compare the contents of the original buffer with that of source, using a costly algorithm which makes the operation much slower than a simple insert and delete-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 as insert and delete-region while 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-nil value 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-region and insert-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-contents returns t if a non-destructive replacement could be performed. Otherwise, i.e., if max-secs was exceeded, it returns nil.

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.