Subject: bug#46374: Regression: erronous calls to PRED switch major-mode of unrelated modified buffers

From: Hauke Rehfeld <[email-masked]>
Date: Sat, 28 Aug 2021 18:25:23 +0200

Hmmm, I'm pretty sure the changes to `save-some-buffers` here
regarding the predicate indirection caused a regression and/or
very unexpected behavior that causes bugs in previously working
code.

Consider

`(save-some-buffers t (lambda () (derived-mode-p 'org-mode)))'

called from an org-mode buffer. It runs through the part of
`save-some-buffers' that is trying to resolve the PRED
indirection:

https://github.com/emacs-mirror/emacs/blob/692da8c6a82f8de376a2eec9304773b3e85205f3/lisp/files.el#L5792

``` emacs-lisp
  ;; Allow `pred' to be a function that returns a predicate
  ;; with lexical bindings in its original environment
  (bug#46374).
  (let ((pred-fun (and (functionp pred) (funcall pred))))
    (when (functionp pred-fun)
      (setq pred pred-fun)))
```
which evaluates the predicate to check if it returns a function --
which `(derived-mode-p)' does, as it simply returns the major-mode
symbol on success! In this case, it would be `#'org-mode'. So then
`org-mode' is called on any unsaved buffers as a PREDICATE,
switching those buffers to org-mode.

Compare this usage in org-mode, org.el:15357:

``` emacs-lisp
(defun org-save-all-org-buffers ()
  "Save all Org buffers without user confirmation."
  (interactive)
  (message "Saving all Org buffers...")
  (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  (when (featurep 'org-id) (org-id-locations-save))
  (message "Saving all Org buffers... done"))
```