Subject: Re: bug#15453: 24.3.50; Point moved away by Flyspell

From: Stefan Kangas <[email-masked]>
Date: Thu, 26 Sep 2019 16:00:24 +0200

tags 15453 notabug
close 15453
quit

"Sebastien Vauban" <[email-masked]> writes:

> When the following 2 conditions are met, Flyspell moves the pointer to the
> beginning of the buffer during commands which change the buffer, such as a
> string replace... But that completely breaks the operation mode of Emacs (and
> is scary).
>
> Conditions:
>
> - Activate Flyspell in `first-change-hook' (as there is no reason to do
>   anything Flyspell-related when opening files just for reading).
>
> - Have a `LocalWords' line in the opened file.
>
> Minimal `.emacs' file:
>
> ;; default dictionary to use
> (setq ispell-dictionary "american")
>
> ;; enable on-the-fly spell checking when changing a buffer which was
> ;; unmodified
> (add-hook 'first-change-hook
>           (lambda ()
>             (save-excursion
>               ;; skip temporary buffers
>               (unless (eq (aref (buffer-name) 0) ?\s) ;; buffer starts with " "
>                 (cond ((derived-mode-p 'text-mode) ;; org-mode
>                        (flyspell-mode 1))
>                       ((derived-mode-p 'prog-mode)
>                        ;; prevent flyspell from finding mistakes in the code,
>                        ;; which is pretty cool
>                        (flyspell-prog-mode))
>                       )))))
>
>
> Minimal file to reproduce the problem:
>
> #+TITLE:     Convert documents
>
> * Usage
>
> - Type =make doc.html= to regenerate only the file =doc.html=.
>
> #  LocalWords:  PDF pdf HTML html
>
> Recipe:
>
> 1. Open the example file
> 2. Put point somewhere in the middle of the file (for example, after the
>    heading "Usage")
> 3. Type `M-%' to replace `doc' by `file'
> 4. Answer `y' to replace the first occurrence (from current point position) of
>    `doc', that is in `make doc.html'
> 5. That modifies the buffer... hence calls `flyspell-mode'
> 6. The second occurrence to replace becomes `doc' from the title "Convert
>    documents" ... *instead of* `doc' from `doc.html' (if point hadn't been
>    moved away to the beginning of the buffer).
>
> Observations:
>
> 1. Having added a `save-excursion' around the `flyspell-mode' activation (in
>    `first-change-hook') did not solve the problem...

The correct solution here is to use save-match-data.  The following
version of your minimal config works for me:

(progn
  (setq ispell-dictionary "american")
  (add-hook 'first-change-hook
            (lambda ()
              (save-excursion
                (save-match-data
                  (unless (eq (aref (buffer-name) 0) ?\s)
                    (cond ((derived-mode-p 'text-mode)
                           (flyspell-mode 1))
                          ((derived-mode-p 'prog-mode)
                           (flyspell-prog-mode)))))))))

I think this is as expected, and I'm closing this as notabug.

Best regards,
Stefan Kangas