Subject: Re: bug#68272: [PATCH] Fix -1 leaking from C to lisp in 'read-event' etc.

From: Stefan Monnier <[email-masked]>
Date: Tue, 05 Mar 2024 15:18:45 -0500

> I'd prefer that we allowed Lisp programs to diagnose the situation
> where the macro ends prematurely,

If we prefer to preserve the current behavior in Calc, the patch below
should do the trick.

        Stefan

diff --git a/lisp/calc/calc-prog.el b/lisp/calc/calc-prog.el
index 03210995eb3..8dff7f1f264 100644
--- a/lisp/calc/calc-prog.el
+++ b/lisp/calc/calc-prog.el
@@ -1225,13 +1225,17 @@ calc-kbd-else-if
   (interactive)
   (calc-kbd-if))
 
+(defun calc--at-end-of-kmacro-p ()
+  (and (arrayp executing-kbd-macro)
+       (>= executing-kbd-macro-index (length executing-kbd-macro))))
+
 (defun calc-kbd-skip-to-else-if (else-okay)
   (let ((count 0)
 	ch)
     (while (>= count 0)
-      (setq ch (read-char))
-      (if (= ch -1)
+      (if (calc--at-end-of-kmacro-p)
 	  (error "Unterminated Z[ in keyboard macro"))
+      (setq ch (read-char))
       (if (= ch ?Z)
 	  (progn
 	    (setq ch (read-char))
@@ -1299,9 +1303,9 @@ calc-kbd-loop
     (or executing-kbd-macro
 	(message "Reading loop body..."))
     (while (>= count 0)
-      (setq ch (read-event))
-      (if (eq ch -1)
+      (if (calc--at-end-of-kmacro-p)
 	  (error "Unterminated Z%c in keyboard macro" open))
+      (setq ch (read-event))
       (if (eq ch ?Z)
 	  (progn
 	    (setq ch (read-event)
@@ -1427,9 +1431,9 @@ calc-kbd-push
 	   (if defining-kbd-macro
 	       (message "Reading body..."))
 	   (while (>= count 0)
-	     (setq ch (read-char))
-	     (if (= ch -1)
+	     (if (calc--at-end-of-kmacro-p)
 		 (error "Unterminated Z` in keyboard macro"))
+	     (setq ch (read-char))
 	     (if (= ch ?Z)
 		 (progn
 		   (setq ch (read-char)