As discussed in the comments to my question, I was a bit confused when writing the question, but will keep the original text in case similarly inexperienced people approach it from the same way.
To answer the main question "How to dynamically replace certain text, by evaluating a function on change in current buffer", below is an example of how to do it.
In this example, we want to rename all instances of "01" to "1" when our mode is active. The function clean-single-digits
achieves this. Note how we use save-excursion
to save the current point, i.e. this function replaces all "01" to "1" and returns point to the point it was when the function was called.
The second expression, where we add clean-single-digits
to after-change-functions
(refer here to the official documentation) ensures this function is called every time Emacs modifies a buffer.
Now you can see why we have (when (eq major-mode 'my-mode)...
in our main function - we want our function to only apply in the relevant mode (my-mode in this case) and not for ALL changes in Emacs buffers.
Finally note how our function takes three parameters, which we don't use. Functions that we add to hooks need to have the same number of parameters as per the definition of these hooks - its an important point to read in the documentation of each hook function / variable. You can see references to this detail in the comments to the question.
(defun clean-single-digits (change-beg change-end prev-len)
(when (eq major-mode 'my-mode)
(save-excursion
(goto-char (point-min))
(while (re-search-forward "01" nil t)
(replace-match "1")))))
(add-hook 'after-change-functions 'clean-single-digits)
Finally, the window-change-functions referred in the question relate to a different set of hooks that were not appropriate (at least for my approach) to this question. For example window-buffer-change-functions
runs on when the actual buffer is changed to something else, not to changes within a buffer.
C-h v window-change-functions
, as well as Elisp manual, node Window Hooks, tell you that each function on that hook must accept a frame, not a window, as its arg. Right away, that indicates that your function needs more work.window-change-functions
, so doing theadd-hook
might create such a variable, but nobody is running that hook. There are fourwindow-<mumble>-change-functions
hooks, so you would have to decide which one to use. That's in additifon to fixing the function per @Drew's comment.(add-hook 'after-change-functions 'my-function)
and then my-function is a straight forward function that works directly in the current buffer (I use asave-excursion
to save the position of the point).