Subject: [PATCH] Magic number regexp shouldn't match beyond end-of-line.

From: "Andrew L. Moore" <[email-masked]>
Date: Tue, 1 Mar 2022 23:52:50 -0500

Repeat magic number search to work around match-data loss
when `save-window-excursion' is called.
---
  lisp/progmodes/executable.el | 12 +++++++++---
  1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/lisp/progmodes/executable.el b/lisp/progmodes/executable.el
index d7c093444e..9116bdea9d 100644
--- a/lisp/progmodes/executable.el
+++ b/lisp/progmodes/executable.el
@@ -232,7 +232,8 @@ executable-set-magic
        (save-excursion
         (goto-char (point-min))
         (add-hook 'after-save-hook 'executable-chmod nil t)
-       (if (looking-at "#![ \t]*\\(.*\\)$")
+        ;; Regexp shouldn't match beyond end-of-line.
+       (if (looking-at "#![ \t]*\\([^\n]*\\)$")
             (and (goto-char (match-beginning 1))
                  ;; If the line ends in a space,
                  ;; don't offer to change it.
@@ -247,8 +248,13 @@ executable-set-magic
                                       "Replace magic number by `#!%s'? "
                                       argument))))
                      (progn
-                      (replace-match argument t t nil 1)
-                      (message "Magic number changed to `#!%s'" 
argument))))
+                       ;; Repeat search to work around match-data loss
+                       ;; from call to `save-window-excursion' above.
+                       (goto-char (point-min))
+                       (if (looking-at "^#![ \t]*\\([^\n]*\\)$")
+                           (progn
+                            (replace-match argument t t nil 1)
+                            (message "Magic number changed to `#!%s'" 
argument))))))
           (insert "#!" argument ?\n)
           (message "Magic number changed to `#!%s'" argument))))
      interpreter)
--