Subject: Re: bug#65451: 30.0.50; `after-change-functions' are not triggered in the same order the changes are made

From: Ihor Radchenko <[email-masked]>
Date: Tue, 29 Aug 2023 07:39:27 +0000

Eli Zaretskii <[email-masked]> writes:

>> Then, what about compacting the "edit list" more frequently, so that we
>> do not need to worry about its size? But I am not sure what frequency
>> will be safe.
>
> Something like that, yes.  But we need to invent a protocol which
> would allow several clients to consume the list safely and without the
> risk of missing edits.

I can think of two approaches:

1. There will be a new buffer-local variable - `buffer-edit-history'
   that will hold recent `buffer-edit-history-limit' edits. This way,
   Elisp functions will be able to examine it any time they need to.

   In addition, there will be `after-edit-functions' hook that will be
   called after `buffer-edit-history-limit' is exceeded. Before the hook
   is called, `buffer-edit-history' is truncated. The hook functions
   will be called with a single argument - list of edits that have been
   removed from the `buffer-undo-history'. That way, Elisp will be able
   to process edits that will disappear from the `buffer-edit-history'.

   Each entry in `buffer-edit-history' will be a list of
   (beg end_before end_after counter), describing region boundaries
   before and after the edit + a counter that can be used to keep track
   of processed positions. The counter will be useful for the code that
   processes `buffer-edit-history' independently, outside
   `after-edit-functions', and may need to skip already processed
   elements. (I initially though that we can simply hold
   `buffer-chars-modified-tick' here, but it is not necessary to hold
   `buffer-chars-modified-tick' specifically - just something to
   indicate "epoch" in the edit history).

   The downside of exposing `buffer-edit-history' is that some
   bad-written Elisp may be tempted to hold a pointer to a cons cell in
   `buffer-edit-history', thus preventing GC.

2. We can have `after-edit-functions' being called once for each edit
   event with (beg end_before end_after) arguments.

   To avoid skipping edits, in addition to Emacs sometimes calling the
   hook, we should allow Elisp to trigger the hook early, by calling
   `process-buffer-edits'. This way, synchronization can be ensured.

   The downside here is when multiple consumers are using
   `after-edit-functions' - synchronization (`process-buffer-edits')
   requested by one consumer will also trigger all other consumers,
   potentially creating extra overheads.

-- 
Ihor Radchenko // yantar92,
Org mode contributor,
Learn more about Org mode at <https://orgmode.org/>.
Support Org development at <https://liberapay.com/org-mode>,
or support my work at <https://liberapay.com/yantar92>