Subject: 'electric-pair-inhibit-if-helps-balance' has side-effects

From: Akib Azmain Turja <[email-masked]>
Date: Fri, 22 Sep 2023 17:51:55 +0600

With the default configuration (which uses
'electric-pair-inhibit-if-helps-balance'), inserting parens at the end
of a Tempel field doesn't extend the field.

I think the modify+undo magic in electric-pair-inhibit-if-helps-balance
moves markers.

The following is the solution that works for me atleast; it uses insert
to insert back the character, and let-bind buffer-undo-list to not
clobber the undo list.

--8<---------------cut here---------------start------------->8---
(defun *electric-pair-inhibit-if-helps-balance (char)
  "Return non-nil if auto-pairing of CHAR would hurt parens' balance.

Works by first removing the character from the buffer, then doing
some list calculations, finally restoring the situation as if nothing
happened."
  (pcase (electric-pair-syntax-info char)
    (`(,syntax ,pair ,_ ,s-or-c)
     (let ((buffer-undo-list t))
       ;; Don't use `delete-char'; that may modify the head of the
       ;; undo list.
       (delete-region (point) (1- (point)))
       (let ((ret
              (cond
               ((eq ?\( syntax)
                (let* ((pair-data
                        (electric-pair--balance-info 1 s-or-c))
                       (outermost (cdr pair-data)))
                  (cond ((car outermost)
                         nil)
                        (t
                         (eq (cdr outermost) pair)))))
               ((eq syntax ?\")
                (electric-pair--unbalanced-strings-p char)))))
         (insert (string char))
         ret)))))
--8<---------------cut here---------------end--------------->8---

-- 
Akib Azmain Turja, GPG key: 70018CE5819F17A3BBA666AFE74F0EFA922AE7F5
Fediverse: [email-masked]
Codeberg: akib
emailselfdefense.fsf.org | "Nothing can be secure without encryption."