Subject: Re: bug#5805: 23.3 abbrev-insert needs a limited save-excursion
From: Stefan Monnier <[email-masked]>
To: Bob Nnamtrop <[email-masked]>
Cc: [email-masked]
Date: Fri, 08 Jul 2011 10:43:18 -0400
List-Id: <debbugs-submit.debbugs.gnu.org>

> --- 23.3/abbrev.el      2011-07-07 08:16:16.000000000 -0600
> +++ 23.3.fix/abbrev.el  2011-07-07 08:43:24.000000000 -0600
> @@ -713,6 +713,7 @@
>      ;; If this abbrev has an expansion, delete the abbrev
>      ;; and insert the expansion.
>      (when (stringp (symbol-value abbrev))
> +      (save-excursion
>        (goto-char wordstart)
>        ;; Insert at beginning so that markers at the end (e.g. point)
>        ;; are preserved.
> @@ -741,7 +742,7 @@
>                (skip-syntax-forward "^w" (1- end))
>                ;; Change just that.
>                (upcase-initials-region (point) (1+ (point)))
> -              (goto-char end))))))
> +              (goto-char end)))))))
>      ;; Now point is at the end of the expansion and the beginning is
>      ;; in last-abbrev-location.

This can't be right, as can be seen in the comment right here: after
this (goto-char end), the rest of the code expects point to be "at the
end of the expansion".

I installed the ugly patch below instead.

        Stefan

=== modified file 'lisp/ChangeLog'
--- lisp/ChangeLog	2011-07-08 14:25:25 +0000
+++ lisp/ChangeLog	2011-07-08 14:41:48 +0000
@@ -5,6 +5,8 @@
 
 2011-07-08  Stefan Monnier  <[email-masked]>
 
+	* abbrev.el (expand-abbrev): Try to preserve point (bug#5805).
+
 	* vc/vc-bzr.el (vc-bzr-revision-keywords): Remove svn, it's only
 	provided by a particular plugin.

=== modified file 'lisp/abbrev.el'
--- lisp/abbrev.el	2011-07-05 15:31:22 +0000
+++ lisp/abbrev.el	2011-07-08 14:41:16 +0000
@@ -814,6 +814,8 @@
     (destructuring-bind (&optional sym name wordstart wordend)
         (abbrev--before-point)
       (when sym
+        (let ((startpos (copy-marker (point) t))
+              (endmark (copy-marker wordend t)))
         (unless (or ;; executing-kbd-macro
                  noninteractive
                  (window-minibuffer-p (selected-window)))
@@ -826,7 +828,14 @@
         (setq last-abbrev-location wordstart)
         ;; If this abbrev has an expansion, delete the abbrev
         ;; and insert the expansion.
-        (abbrev-insert sym name wordstart wordend)))))
+          (prog1
+              (abbrev-insert sym name wordstart wordend)
+            ;; Yuck!!  If expand-abbrev is called with point slightly
+            ;; further than the end of the abbrev, move point back to
+            ;; where it started.
+            (if (and (> startpos endmark)
+                     (= (point) endmark)) ;Obey skeletons that move point.
+                (goto-char startpos))))))))
 
 (defun unexpand-abbrev ()
   "Undo the expansion of the last abbrev that expanded.