[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Request for Mentor] subst-char-in-region
From: |
Stefan Monnier |
Subject: |
Re: [Request for Mentor] subst-char-in-region |
Date: |
Mon, 15 Dec 2014 09:29:07 -0500 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/25.0.50 (gnu/linux) |
> Initially, because I wasn't sure that the a-c-f gave me all the
> information that I needed. I thought it might do, but I was confused by
> the third argument which is "length in bytes of the pre-change text". Is
> "length in bytes" the same as "char position". I presumed note.
Ha, nicely spotted, that's a bug in the docstring. It passes (or
should anyway) the length in characters.
> The difficulty is that in some cases the conversion function uses the
> contents of this buffer to work out the equivalent location in that
> buffer. When the b-c-f is called the two buffers are in sync, so this
> conversion works. But when the a-c-f is called, the two buffers are not
> in sync because we haven't percolated the change yet.
So, rather than the length of the previous text, you'd need to actually
know the previous text? Of course, you can use b-c-f to stash the
"previous text", but indeed it won't necessarily always be exactly
right, in the sense that the previous text stashed in b-c-f may not have
the exact same boundaries, so you'll need to massage it a bit.
The way I see it, you'll need to do something like
(defvar-local my-before-change-text nil)
(defun my-bcf (beg end)
(setq my-before-change-text
(if (null my-before-change-text)
(cons beg (buffer-substring beg end))
(let* ((oldbeg (car my-before-change-text))
(oldtext (cdr my-before-change-text))
(oldend (+ oldbeg (length oldtext)))
(newbeg (min beg oldbeg))
(newend (max end oldend)))
(cl-assert (equal oldtext (buffer-substring oldbeg oldend)))
(if (or (< newbeg oldbeg) (> newend oldend))
(cons newbeg (buffer-substring newbeg newend))
my-before-change-text)))))
(add-hook 'before-change-functions #'my-bcf)
And then in after-change-functions, you'll need something like
(defun my-acf (beg end oldlen)
(let ((oldtext (substring (cdr my-before-change-text)
(- beg (car my-before-change-text))
(+ oldlen (- beg (car my-before-change-text))))))
(setq my-before-change-text nil)
...))
-- Stefan
- [Request for Mentor] subst-char-in-region, Phillip Lord, 2014/12/12
- Re: [Request for Mentor] subst-char-in-region, Stefan Monnier, 2014/12/12
- Re: [Request for Mentor] subst-char-in-region, Phillip Lord, 2014/12/12
- Re: [Request for Mentor] subst-char-in-region, Stefan Monnier, 2014/12/12
- Re: [Request for Mentor] subst-char-in-region, Phillip Lord, 2014/12/15
- Re: [Request for Mentor] subst-char-in-region,
Stefan Monnier <=
- Re: [Request for Mentor] subst-char-in-region, Phillip Lord, 2014/12/16
- Re: [Request for Mentor] subst-char-in-region, Stefan Monnier, 2014/12/16
- Re: [Request for Mentor] subst-char-in-region, Phillip Lord, 2014/12/16