help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: replace-regexp


From: Yuri Khan
Subject: Re: replace-regexp
Date: Sat, 8 May 2021 12:38:35 +0700

On Sat, 8 May 2021 at 07:02, Emanuel Berg via Users list for the GNU
Emacs text editor <help-gnu-emacs@gnu.org> wrote:

> > Maybe it has something to do with the replacement being
> > longer than the original string?
>
> That's it, I think, as this doesn't give me the error:
>
> (defun md-latex-reduce (beg end)
>   (interactive "r")
>   (save-excursion
>     (goto-char beg)
>     (while (re-search-forward "_\\(.*\\)_" end t)
>       (replace-match "\\1") )))

And this is probably one of the reasons why most[citation needed]
tutorials, when implementing a function operating on a region, do a
‘narrow-to-region’ first thing.

    (defun md-latex-reduce (beg end)
      (interactive "r")
      (save-excursion
        (save-restriction
          (narrow-to-region beg end)

          (goto-char (point-min))
          (while (re-search-forward "_\\(.*\\)_" nil t)
            (replace-match "\\\\textit{\\1}"))))

You might probably solve the same issue by carefully tracking the
lengthening of text — e.g. by incrementing ‘end’ by (- (length
"\\\\textit{}") (length "__")) on each iteration — or by putting a
marker at end and then passing that marker in re-search-forward. But
narrowing is easier.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]