master cab6a0d0e33 8/9: Make erc-settings a module

"F. Jason Park" <[email protected]> Tue, 30 Jun 2026 23:37:22 -0400 (EDT)
Newsgroups gmane.emacs.diffs
Message-ID <[email protected]>
branch: master
commit cab6a0d0e332001d75ae252a7148d984a29d724e
Author: F. Jason Park <[email protected]>
Commit: F. Jason Park <[email protected]>

    Make erc-settings a module
    
    * doc/misc/erc.texi: Add Settings node under Modules.
    * etc/ERC-NEWS: Mention new module along with function
    `erc-channel-buffer-p.
    * lisp/erc/erc-networks.el (erc-settings): Move to new module library
    `erc-settings'.
    (erc-get): Neuter completely by effectively aliasing to `ignore'.
    * lisp/erc/erc-settings.el: New file.
    * lisp/erc/erc.el (erc-channel-buffer-p): New function.
    (erc-modules): Add `settings' to custom set.
    * test/lisp/erc/erc-scenarios-settings.el: New file.
    * test/lisp/erc/erc-settings-tests.el: New file.
    * test/lisp/erc/erc-tests.el (erc-tests--modules): Add `settings'.
    * test/lisp/erc/resources/settings/basic-sasl.eld: New file.
    * test/lisp/erc/resources/settings/basic.eld: New file.
    (Bug#76019)
---
 doc/misc/erc.texi                               | 391 +++++++++++++++++++++++-
 etc/ERC-NEWS                                    |  11 +
 lisp/erc/erc-networks.el                        |  50 +--
 lisp/erc/erc-settings.el                        | 296 ++++++++++++++++++
 lisp/erc/erc.el                                 |   5 +
 test/lisp/erc/erc-scenarios-settings.el         | 190 ++++++++++++
 test/lisp/erc/erc-settings-tests.el             | 119 ++++++++
 test/lisp/erc/erc-tests.el                      |   1 +
 test/lisp/erc/resources/settings/basic-sasl.eld |  47 +++
 test/lisp/erc/resources/settings/basic.eld      |  38 +++
 10 files changed, 1105 insertions(+), 43 deletions(-)

diff --git a/doc/misc/erc.texi b/doc/misc/erc.texi
index e8b1724ef5f..3e39f819a52 100644
--- a/doc/misc/erc.texi
+++ b/doc/misc/erc.texi
@@ -83,6 +83,10 @@ Advanced Module Topics
 * Example: Module Example.      An example module.
 * Usage: Module Usage.          How to use specific modules.
 
+Individual Modules
+
+* Settings: Settings Module.    Per-buffer configuration.
+
 Advanced Usage
 
 * Connecting::                  Ways of connecting to an IRC server.
@@ -144,7 +148,6 @@ ERC comes with the following capabilities enabled by default.
 
 @node Getting Started
 @chapter Getting Started
-@cindex settings
 
 The command @kbd{M-x erc} will start ERC and prompt for the server to
 connect to.  If you're unsure of which server or network to connect
@@ -552,6 +555,10 @@ Scroll to the bottom of the buffer
 @item services
 Identify to Nickserv (IRC Services) automatically
 
+@cindex modules, settings
+@item settings
+Apply options locally per-buffer (@pxref{Settings Module})
+
 @cindex modules, smiley
 @item smiley
 Convert smileys to pretty icons
@@ -1011,6 +1018,383 @@ list or the bug tracker.
 
 
 @c PRE5_4: Document every option of every module in its own subnode
+@node Module Usage
+@section Usage
+@cindex individual modules
+@cindex module usage
+
+Detailed documentation on individual built-in modules.
+
+@menu
+* Settings: Settings Module.          Scoped user options.
+@end menu
+
+@node Settings Module
+@subsection Settings
+@cindex settings
+
+This global module lets you apply ERC options on a per-buffer basis as
+local variable bindings (@pxref{Buffer-Local Variables,,, elisp,}).  It
+consists of a single @dfn{meta option}:
+
+@defopt erc-settings
+An alist where each key is a @dfn{match condition} and each value a list
+of bindings that loosely resembles a @code{let}-style @var{varlist}.
+The first element of each binding is the variable of a user option and
+the second an arbitrary sexp assigned to it locally in all matching
+buffers.  You can tell ERC to evaluate a given sexp as a Lisp form
+before assigning it by including a trailing third element: the
+@dfn{modifier flag} @code{:eval}.
+
+A match condition specifies when and whether ERC should apply each group
+of bindings.  These resemble @code{buffer-match-p} conditions, with two
+major differences (@pxref{Buffer List,,, elisp,}).  The first is that
+predicate conditions don't take any arguments.  Instead, ERC runs them
+with the candidate buffer current.  The second difference is that the
+assortment of associative cons-cell conditions is completely new.  Gone
+are @code{major-mode}, @code{category}, etc.  In their place, ERC offers
+the following:
+
+@itemize
+@item @code{(network . @samp{<symbol>})}
+@item @code{(id . @samp{<symbol>})}
+@item @code{(name . @samp{<string>})}
+@item @code{(target . @samp{<string or nil>})}
+@end itemize
+
+The associated @code{cdr} values for the @code{network} and @code{id}
+conditions are symbols identifying the current IRC network and the
+@dfn{network context}, respectively.  When first connecting, a
+@code{network} condition is always @code{nil}, but an @code{id}
+condition can be non-@code{nil} if you supply a matching @var{ID}
+argument to an entry-point command, like @code{erc-tls} (@pxref{Network
+Identifier}).
+
+Additionally, ERC also recognizes @code{buffer-match-p}'s boolean
+operations and constants:
+
+@itemize
+@item @code{(and @samp{<condition...>})}
+@item @code{(or @samp{<condition...>})}
+@item @code{(not @samp{<condition>})}
+@item @code{t}
+@item @code{nil}
+@end itemize
+
+Also valid are regular expressions and nullary predicates:
+
+@itemize
+@item @code{"<some regexp>"}
+@item @code{<predicate symbol>}
+@end itemize
+
+@end defopt
+
+@noindent
+Here's a contrived @code{erc-settings} value containing seven entries,
+the first of which has two assignments:
+
+@lisp
+(((and (network . Libera.Chat)          ; buffers #emacs,
+       "\\`#emacs")                     ; #emacs-foo, etc.,
+  (my-own-variable 42)                  ; on Libera.Chat only
+  (erc-foo ""))
+
+ ((or (target . "#chan")                ; buffers #chan, bob,
+      (target . "bob"))                 ; chan@@Libera.Chat,
+  (erc-foo (erc-current-nick) :eval))   ; bob@@OFTC, etc.
+
+ (erc-open-server-buffer-p (erc-bar 1)) ; connected server buffers
+ (erc-query-buffer-p (erc-bar 2))       ; query buffers only
+ (erc-channel-buffer-p (erc-bar 3))     ; channel buffers only
+ (erc-target (erc-bar 4))               ; query or channel buffers
+ (t (erc-bar 5)))                       ; any `erc-mode' buffer
+@end lisp
+
+@noindent
+Unfortunately, predicate functions too dissimilar from those in the last
+hunk above may not work in all match contexts due to the interaction
+between this module and ERC's rather convoluted major-mode setup.  While
+the only way to know for sure is to try them, selecting them becomes
+much easier if you can gain a sense for when exactly @samp{settings}
+attempts to create bindings:
+
+@itemize
+@item
+In server buffers
+@enumerate
+@item
+before ERC enables any modules or sets any local variables
+@item
+after establishing a logical IRC connection and learning what network
+it's connected to
+@end enumerate
+
+@item
+In target buffers
+@enumerate
+@item
+before enabling any modules, but only if you're overriding
+@code{erc-modules} and, only then, for that option alone
+@item
+after ERC has set most of its default local variables and run
+global-module setup but before running major-mode hooks or local-module
+setup
+@end enumerate
+@end itemize
+
+The main downside of this staggered approach is that @samp{settings}
+skips any bindings for variables that already have a local binding
+rather than do the intuitive thing and simply clobber them.  The reason
+for this is to retain a consistent state between a global module's minor
+mode setup and any local-module setup or major-mode hooks.  They must
+all witness the same value for the same variable.
+
+Revisiting the phony example above with this precedence quirk in mind,
+notice that the made-up variable @code{erc-bar} will be @code{2} in
+query buffers, @code{3} in channel buffers, and @code{5} in server
+buffers.  It's never @code{1} because the first binding opportunity
+occurs before connecting, when @code{erc-open-server-buffer-p} returns
+@code{nil}.  It's likewise never @code{4} because that binding appears
+lower in the list than those for @code{2} and @code{3}.  For more on
+this behavior, see the very last example below.
+
+When it comes to binding the option @code{erc-modules}, @samp{settings}
+must make special accommodations.  Getting it right may take some trial
+and error, and it's only guaranteed to work for local modules because
+most global ones share state among all sessions.  However, it's fine to
+include global modules in an @code{erc-modules} binding as long as they
+also appear in the @code{default-value}.  To set @code{erc-modules} for
+a specific server buffer, specify an entry like
+
+@lisp
+("[.]libera[.]chat:"
+ (erc-modules (seq-union '(sasl keep-place-indicator) erc-modules)
+              :eval)
+ (erc-sasl-user :nick))
+@end lisp
+
+@noindent
+Here, the match condition is a regexp matching a dialed @acronym{TCP}
+address because server buffers typically have these as temporary names
+while connecting.  As mentioned, ERC later renames them to reflect a
+discovered network, after which @samp{settings} binds any matching
+unbound options.
+
+A session's target buffers normally share the @code{erc-modules} value
+bound locally in their server buffer.  To specify a separate, overriding
+set of modules for certain target buffers, use a condition that only
+applies to them:
+
+@lisp
+((and (network . Libera.Chat) erc-channel-buffer-p)
+ (erc-modules (seq-union '(fill-wrap) erc-modules) :eval))
+@end lisp
+
+@noindent
+This is often unnecessary because local modules that only operate in one
+kind of buffer tend to disable themselves elsewhere.  And some, like
+@samp{keep-place-indicator}, offer an option to restrict activation
+based on buffer type.
+
+@anchor{Settings Examples}
+@subsection Settings Examples
+@cindex settings, examples
+
+A typical setup might include configuration for two networks, one that
+uses @acronym{SASL} to authenticate and another that uses a server
+password.
+
+@lisp
+(setopt erc-modules
+        `(settings ,@@erc-modules) ; assuming `erc' is loaded
+
+        erc-settings
+        ;; Pre-connect and server buffer config for @samp{Libera.Chat}.
+        '(("libera\\.chat:"
+           (erc-prompt "Libera>")
+           (erc-autojoin-channels-alist ((Libera.Chat "##jrh")))
+           (erc-header-line-format "%n on %S (%m, %l)")
+           (erc-sasl-user :nick)
+           (erc-modules `(sasl ,@@erc-modules) :eval))
+
+          ;; Channel buffer config for @samp{Libera.Chat}.
+          ((and (network . Libera.Chat) erc-channel-buffer-p)
+           (erc-modules `(keep-place-indicator ,@@erc-modules) :eval)
+           (erc-prompt erc-prompt-format)
+           (erc-prompt-format "%c%b>")
+           (erc-header-line-format "%t: %o"))
+
+          ;; Query buffer configuration for any network.
+          (erc-query-buffer-p
+           (erc-prompt erc-prompt-format)
+           (erc-prompt-format "%S>")
+           (erc-header-line-format nil))
+
+          ;; Pre-connect and server-buffer config for @samp{OFTC}.
+          ("oftc\\.net:"
+           (erc-prompt "OFTC!")
+           (erc-modules `(nicks ,@@erc-modules) :eval))))
+@end lisp
+
+@noindent
+Note that the pre-connection config described in the last entry can't
+use the @dfn{global module} @samp{services} because it's incompatible
+with the @dfn{local module} @samp{sasl}, needed for Libera by the first
+entry.  In this scenario, instead of a server password, the @samp{OFTC}
+connection could alternatively use @dfn{CertFP} via auth-source (see
+next example).
+
+@anchor{ID-based Settings Example}
+@subsubsection ID-based
+@cindex settings, examples, id-based
+
+New users coming from traditional IRC clients often express a desire to
+store connection details alongside other per-network or per-connection
+configuration.  Although ERC was designed to keep these concerns
+separate, the @samp{settings} module can emulate that experience to some
+degree.
+
+@lisp
+(setopt erc-modules
+        `(settings ,@@erc-modules)
+
+        erc-settings
+        ;; Connection details common to both @samp{Libera.Chat} IDs.
+        '(((and (or (id . lib-jrh) (id . lib-jrbot))
+                (not erc-server-process-alive))
+           (erc-server "irc.libera.chat")
+           (erc-port 6697)
+           (erc-modules `(sasl ,@@erc-modules) :eval))
+
+          ;; Connection details for account @samp{jrh}.
+          ((and (id . lib-jrh) (not erc-server-process-alive))
+           (erc-nick "jrh")
+           (erc-user-full-name "J. Random Hacker")
+           (erc-email-userid "jrh")
+           (erc-autojoin-channels-alist ((lib-jrh "##jrh"))))
+
+          ;; Connection details for account @samp{jrbot}.
+          ((and (id . lib-jrbot) (not erc-server-process-alive))
+           (erc-nick "jrbot")
+           (erc-email-userid "jrbot")
+           (erc-user-full-name "J.R. Bot (jrh's bot)")
+           (erc-sasl-auth-source-function erc-auth-source-function)
+           (erc-autojoin-channels-alist ((lib-jrbot "##jrh" "##jrbot"))))
+
+          ;; Non-connection opts for both @samp{Libera.Chat} sessions.
+          ((and (network . Libera.Chat) erc-open-server-buffer-p)
+           (erc-prompt "libera>")
+           (erc-header-line-format "%n on %S (%m, %l)"))
+          ((and (network . Libera.Chat) erc-channel-buffer-p)
+           (erc-modules `(keep-place-indicator ,@@erc-modules) :eval)
+           (erc-prompt erc-prompt-format)
+           (erc-prompt-format "%c%b>")
+           (erc-header-line-format "%t: %o"))
+
+          ;; Server details for @samp{OFTC}.
+          ((and (id . oftc) (target . nil))
+           (erc-server "irc.oftc.net")
+           (erc-port 6697)
+           (erc-nick "jrh")
+           (erc-email-userid "jrh")
+           (erc-user-full-name "J. Random Hacker")
+           (network-stream-use-client-certificates t)
+           (erc-modules `(services-regain ,@@erc-modules) :eval)
+           (erc-prompt "jrh@@OFTC!"))))
+
+(defun my-erc-up (id)
+  "Connect to preconfigured session identified by ID."
+  (interactive "SNet id: ")
+  (erc-tls :server nil
+           :port nil
+           :nick nil
+           :user nil
+           :password nil
+           :full-name nil
+           :id network-id))
+@end lisp
+
+@noindent
+With a setup like the above, you can connect to a predefined session by
+supplying an identifying symbol, like @code{lib-jrh}, along with the
+@var{ID} keyword parameter to the entry-point command @code{erc-tls}.
+The main gotcha when using these identifiers is that a regexp targeting
+a dialed @acronym{TCP} address, like
+@code{"\\`irc[.]libera[.]chat:6697\\'"}, won't work for conditions like
+the first one above because server buffers receive permanent names
+immediately upon creation, long before connecting.  Instead, you'll want
+to specify a chosen identifier via the @samp{(id . <symbol>)} pattern
+and likely qualify it with another subcondition, like @code{(not
+erc-server-process-alive)}, to ensure that the @code{erc-modules}
+binding only matches the server buffer and not any target buffers.
+Equivalent qualifying subconditions would be @code{(not erc-target)} and
+@code{(target . nil)}.
+
+Regarding authentication, notice that the @samp{lib-jrbot} connection
+retrieves its @acronym{SASL} credentials, which might be a client
+certificate, via auth-source, while session @samp{lib-jrh} prompts you
+interactively for a password.  (@xref{SASL, SASL in ERC}.)  The
+@samp{oftc} connection also uses auth-source to supply its credentials,
+this time for non-@acronym{SASL} client-cert (@dfn{CertFP})
+authentication.  Lastly, in the scenario above, a user would need to run
+@kbd{M-x my-erc-up @key{RET}} instead of @kbd{M-x erc @key{RET}} when
+connecting to IRC.  For convenience, ERC provides a similar command:
+
+@defun erc-settings-connect-by-id network-id
+Prompt the user and provide completion for some @samp{(id . <symbol>)}
+appearing in their @code{erc-settings}, and specify it as the argument
+to the @var{ID} keyword parameter when invoking @code{erc-tls}.
+@end defun
+
+With both traditional and ID-based setups, it's often more convenient to
+define less exclusive, more ``overlapping'' match conditions:
+
+@lisp
+(use-package erc-settings
+  :custom
+  (erc-settings
+   '(((not erc-server-process-alive) ; common to all servers
+      (erc-nick "jrh")
+      (erc-port 6697)
+      (erc-email-userid "jrh")
+      (erc-user-full-name "J. Random Hacker"))
+
+     (erc-channel-buffer-p ; all channels
+      (erc-modules `(keep-place-indicator ,@@erc-modules) :eval))
+
+     ((id . id-libera) ; Libera.Chat only, including targets
+      (erc-server "irc.libera.chat")
+      (erc-sasl-password "changeme")
+      (erc-modules `(sasl ,@@erc-modules) :eval)
+      (erc-prompt erc-prompt-format)
+      (erc-autojoin-channels-alist ((id-foonet "#erc"))))
+
+     ((id . id-oftc) ; OFTC only, including targets
+      (erc-server "irc.oftc.net")
+      (erc-modules `(fill-wrap ,@@erc-modules) :eval)
+      (erc-autojoin-channels-alist ((id-barnet "##jrh")))))))
+@end lisp
+
+If you go this route, know that @samp{settings} will often create local
+bindings in buffers where they're not applicable.  In the above example,
+buffer @file{#erc} on @samp{Libera.Chat} will have @code{erc-server} and
+@code{erc-sasl-password} bound locally for no reason.  In most cases,
+this is perfectly harmless.
+
+A final thing to notice about the example above is that the
+@code{erc-modules} binding in the second group, the one with match
+condition @code{erc-channel-buffer-p}, effectively @dfn{shadow}s that
+same variable in all remaining settings affecting channel buffers.  If
+it instead appeared at the end of the list, ERC would skip its
+@code{erc-modules} binding because the variable would already be locally
+bound.  But, as is, both @file{##jrh} on @samp{OFTC} and @file{#erc} on
+@samp{Libera.Chat} activate @samp{keep-place-indicator} but not
+@samp{fll-wrap}.  Server buffer @file{id-oftc} has only @samp{fll-wrap},
+and server buffer @file{id-libera} has neither.  And, if you were to
+receive a query from @samp{alice} on @samp{OFTC}, buffer @file{alice}
+would only have @samp{fill-wrap} but not @samp{keep-place-indicator}
+because it's a non-channel on @samp{OFTC}.
 
 
 @node Advanced Usage
@@ -1519,6 +1903,11 @@ authenticate successfully.
 @item
 Multiple networks
 
+If you use the @samp{settings} module, introduced in ERC 5.7, please
+refer to that section's guide for a more modern, config-based approach
+to specifying buffer-local @acronym{SASL} options (@pxref{Settings
+Examples}).
+
 @example
 # ~/.authinfo.gpg
 
diff --git a/etc/ERC-NEWS b/etc/ERC-NEWS
index 68655ecd4bd..bc9669e7b59 100644
--- a/etc/ERC-NEWS
+++ b/etc/ERC-NEWS
@@ -34,6 +34,13 @@ skip messages from "fools" and those in untracked buffers.
 Option 'erc-desktop-notifications-ignored-when-focused' can spare users
 from being notified when interacting with the initiating buffer.
 
+** Apply options granularly to specific connections or buffers.
+Based on an idea drafted nearly a quarter century ago by ERC's earliest
+contributors, the 'settings' module offers a ready-made method for
+binding arbitrary user options to various "scopes" of interest.  It
+leverages buffer-local variables and match conditions reminiscent of
+'buffer-match-p'.
+
 ** Changes in the library API.
 
 *** Module setup runs in query buffers on reconnect.
@@ -61,6 +68,10 @@ being killed.  For modules still needing to run delayed, session-aware
 code, a new convenience macro called 'erc-with-initialized-session' is
 now available to automate any 'erc-mode-hook' wrangling for you.
 
+*** A predicate to detect if the current buffer is a channel.
+New function 'erc-channel-buffer-p' is a channel-detecting complement to
+'erc-query-buffer-p' and a light wrapper around 'erc-channel-p'.
+
 
 * Changes in ERC 5.6.2
 
diff --git a/lisp/erc/erc-networks.el b/lisp/erc/erc-networks.el
index 3e924d0b0f1..20188b323df 100644
--- a/lisp/erc/erc-networks.el
+++ b/lisp/erc/erc-networks.el
@@ -1609,28 +1609,12 @@ return the host alone sans URL formatting (for compatibility)."
          (scheme (if (cdr pspec) "ircs" "irc")))
     (if ports (format "%s://%s:%d" scheme host (seq-random-elt ports)) host)))
 
-;;; The following experimental
-;; It does not work yet, help me with it if you
-;; think it is worth the effort.
-
-(defvar erc-settings
-  '((pals Libera.Chat ("kensanata" "shapr" "anti\\(fuchs\\|gone\\)"))
-    (format-nick-function (Libera.Chat "#emacs") erc-format-@nick))
-  "Experimental: Alist of configuration options.
-
-WARNING: this variable is a vestige from a long-abandoned
-experiment.  ERC may redefine it using the same name for any
-purpose at any time.
-
-The format is (VARNAME SCOPE VALUE) where
-VARNAME is a symbol identifying the configuration option,
-SCOPE is either a symbol which identifies an entry from
-  `erc-networks-alist' or a list (NET TARGET) where NET is a network symbol and
-  TARGET is a string identifying the channel/query target.
-VALUE is the options value.")
-(make-obsolete-variable 'erc-settings
-                        "temporarily deprecated for later repurposing" "30.1")
+;; Longtime occupant of this file `erc-settings' was repurposed in ERC
+;; 5.7 and moved to erc-settings.el.
 
+;; Attempting to provide a "working" version of this function would be
+;; nonsensical because `erc-settings' now has a completely different
+;; layout than the unfinished version from `erc-networks' (circa 2002).
 (defun erc-get (var &optional net target)
   "Retrieve configuration values from `erc-settings'.
 
@@ -1639,27 +1623,9 @@ long-abandoned experiment.  ERC may redefine it using the same
 name for any purpose at any time.
 
 \(fn &rest UNKNOWN)"
-  (declare (obsolete "temporarily deprecated for later repurposing" "30.1"))
-  (let ((items erc-settings)
-	elt val)
-    (while items
-      (setq elt (car items)
-	    items (cdr items))
-      (when (eq (car elt) var)
-	(cond ((and net target (listp (nth 1 elt))
-		    (eq net (car (nth 1 elt)))
-		    (string-equal target (nth 1 (nth 1 elt))))
-	       (setq val (nth 2 elt)
-		     items nil))
-	      ((and net (eq net (nth 1 elt)))
-	       (setq val (nth 2 elt)
-		     items nil))
-	      ((and (not net) (not target) (not (nth 1 elt)))
-	       (setq val (nth 2 elt)
-		     items nil)))))
-    val))
-
-;; (erc-get 'pals 'Libera.Chat)
+  (declare (obsolete "`erc-settings' schema incompatible with PoC from 2002"
+                     "31.1"))
+  (ignore var net target))
 
 (provide 'erc-networks)
 
diff --git a/lisp/erc/erc-settings.el b/lisp/erc/erc-settings.el
new file mode 100644
index 00000000000..570a86a9039
--- /dev/null
+++ b/lisp/erc/erc-settings.el
@@ -0,0 +1,296 @@
+;;; erc-settings.el -- Buffer-local options  -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2026 Free Software Foundation, Inc.
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published
+;; by the Free Software Foundation, either version 3 of the License,
+;; or (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This module is based on an ancient proof-of-concept by Mario Lang,
+;; with contributions from Diane Murray and possibly others.  It lived
+;; in erc-networks.el for over two decades before becoming its own
+;; module in 2026.
+
+;; Usage: add `settings' to `erc-modules', and customize the option
+;; `erc-settings'.
+
+;;; Code:
+(require 'erc)
+
+(defgroup erc-settings nil
+  "Buffer-local values for arbitrary user options."
+  :group 'erc)
+
+(define-widget 'erc--buffer-match 'lazy
+  "Condition for `erc-settings--buffer-match-p'."
+  :tag "Valid `erc-settings' match condition"
+  :type `(choice (boolean :tag "Always/never")
+                 (regexp :tag "Buffer-name regexp")
+                 (function :tag "Predicate")
+                 (cons :tag "Network" (const network) symbol)
+                 (cons :tag "ID" (const id) symbol)
+                 (cons :tag "Target" (const target) (choice string
+                                                            (const nil)))
+                 (cons :tag "Buffer name" (const name) string)
+                 (list :tag "Negation"
+                       (const not)
+                       (erc--buffer-match :tag "Match condition"))
+                 (cons :tag "All/any"
+                       (choice :tag "Operator" (const or) (const and))
+                       (repeat :tag "Match condition" erc--buffer-match))))
+
+(defcustom erc-settings ()
+  "A match-condition alist for setting ERC's user options locally.
+
+This \"meta option\" provides a means of specifying buffer-local values
+for other user options.  It does this by setting an option's variable
+locally in server and target buffers.  If a local binding already exists
+for a variable, ERC leaves it alone.  Alist members should be of the
+form (MATCHCOND . BINDINGS), where BINDINGS is a list of assignments
+like (VAR VAL . FLAGS).
+
+MATCHCOND works like a `buffer-match-p' condition, only tailored
+slightly to meet ERC's unique requirements.  The boolean operators
+`and', `or', and `not' remain unchanged, as do strings, which ERC treats
+as regexps to be matched against a buffer's name.  For servers, this
+name is usually a dialed TCP address while connecting and a network (ID)
+once connected.  Query and channel buffers normally share their target's
+name, possibly suffixed by a disambiguating \"@\" + identifier.  If
+MATCHCOND is a function, ERC assumes it's a predicate that takes no
+arguments and runs in the candidate ERC buffer.  As for key-value
+cons-cell conditions, ERC ignores all traditional ones defined by
+`buffer-match-p', like `derived-mode' and `major-mode', instead
+preferring to define its own: (network . NETWORK), where NETWORK is a
+symbol returned by the function `erc-network'; (id . ID), where ID is a
+user-provided symbol as described by the Info node `(erc) Network
+Identifier'; (target . TARGET), where TARGET, if non-nil, is the channel
+name or query nick; and (name . NAME), which matches a buffer's NAME, as
+a string.
+
+In BINDINGS, each member's VAR is the symbol of a user option or
+variable to which ERC assigns the sexp VAL locally in the current
+buffer.  When FLAGS contains the keyword :eval, ERC evaluates VAL as a
+Lisp form and assigns the result to VAR.  Each entry in BINDINGS should
+appear in order of decreasing match specificity and increasing
+generality because even though ERC applies all matching entries, it
+skips subsequent ones for which a local binding already exists.
+
+See Info node `(erc) Settings' for a friendlier description of the DSL
+and Info node `(erc) Settings Examples' for example usage."
+  :package-version '(ERC . "5.7")
+  :type (let* ((flags '(set :tag "Flags"
+                            (const :tag "Prefer custom-set (advanced)" :custom)
+                            (const :tag "Evaluate form" :eval)))
+               (setting `(cons :tag "Binding assignment"
+                               (variable :tag "Option/variable")
+                               (cons :tag "Value" sexp ,flags))))
+          `(alist :key-type erc--buffer-match :value-type (repeat ,setting))))
+
+;;;###autoload(autoload 'erc-settings-mode "erc-settings" nil t)
+(define-erc-module settings nil
+  "Global module to set ERC options locally per-buffer.
+Like many modules, this cannot reasonably be toggled via mode command
+mid-session.  To see the result of updates to the option `erc-settings'
+immediately, destroy and reopen all affected sessions."
+  ((when (and erc--updating-modules-p
+              (not (memq #'erc-settings--set-modules
+                         (default-value 'erc--set-modules-functions))))
+     (erc--warn-once-before-connect 'erc-settings-mode
+       "Module `settings' did not load properly. Add it to `erc-modules'"
+       " and run `erc-update-modules' before connecting, or use a"
+       " Custom-aware configuration method, like `setopt'."))
+   ;; Set non-`erc-module' entries in target buffers after all default
+   ;; non-connection related local session variables have been set.
+   (if erc--updating-modules-p
+       (add-hook 'change-major-mode-after-body-hook
+                 #'erc-settings--setup -90 t)
+     (erc-buffer-do #'erc-settings--setup))
+   ;; Set any remaining entries in server buffers once the network is
+   ;; known and all local session variables have been populated.
+   (add-hook 'erc-after-connect #'erc-settings-bind -30)
+   (add-hook 'erc--set-modules-functions #'erc-settings--set-modules 30))
+  ((erc-buffer-do #'erc-settings--setup)
+   (remove-hook 'erc-after-connect #'erc-settings-bind)
+   (remove-hook 'erc--set-modules-functions #'erc-settings--set-modules)))
+
+(defun erc-settings--setup ()
+  (if erc-settings-mode
+      (when erc-server-connected
+        (erc-settings--set (erc-settings--gather-bindings (current-buffer))))
+    (remove-hook 'change-major-mode-after-body-hook #'erc-settings--setup t)
+    (dolist (entry erc-settings)
+      (pcase-dolist (`(,var . ,_) (cdr entry))
+        (when (local-variable-p var)
+          (kill-local-variable var))))))
+
+(defun erc-settings--buffer-match-p (condition)
+  "Return non-nil if CONDITION matches current buffer.
+Act almost like `buffer-match-p', except recognize an alternate set of
+property-based cons-cell conditions.  Additionally, don't pass any
+arguments to predicate-type conditions, and interpret CONDITION in the
+current buffer, where CONDITION should be among the following:
+
+- the symbol t, which always matches,
+- the symbol nil, which never matches,
+- a regular expression matched against current buffer's name,
+- a predicate taking no arguments and run in the candidate buffer
+- a symbol-keyed cons cell described by one the following:
+
+         `id' `eq' to current buffer's network context ID
+    `network' `eq' to current buffer's `erc-network'
+     `target' `equal' to current buffer's `erc-target'
+       `name' `equal' to current buffer's name
+        `and'  a list of matching conditions
+         `or'  a list containing at least one matching condition
+        `not'  a list of a single condition that matches when negated"
+  (pcase condition
+    ('t t)
+    ((pred stringp) (string-match-p condition (buffer-name)))
+    ((pred functionp) (funcall condition))
+    (`(id . ,id) (and erc-networks--id
+                      (eq (erc-networks--id-symbol erc-networks--id) id)))
+    (`(network . ,network) (and erc-network (eq erc-network network)))
+    (`(target . ,target) (equal target (erc-target)))
+    (`(name . ,name) (equal name (buffer-name)))
+    (`(not . ,cond) (not (erc-settings--buffer-match-p cond)))
+    (`(or . ,args) (seq-some #'erc-settings--buffer-match-p args))
+    (`(and . ,args) (seq-every-p #'erc-settings--buffer-match-p args))))
+
+(defun erc-settings-bind (&rest _)
+  "Set all settings in option `erc-settings' from current network's ID."
+  (erc-settings--set (erc-settings--gather-bindings (current-buffer))))
+
+;;;###autoload
+(defun erc-settings--set-modules (id target target-server-buffer)
+  "Set `erc-modules' locally if an entry exists for the current buffer.
+In server buffers, bind all matching entries, not just `erc-modules'.
+Expect TARGET to be a string or nil and ID to be a symbol.  When TARGET
+is non-nil, borrow local values from TARGET-SERVER-BUFFER to temporarily
+bind identifying variables sought by match conditions."
+  (when (and erc-settings (or erc-settings-mode (memq 'settings erc-modules)))
+    ;; Shadow `erc-networks--id' for (id . <id>), `erc--target' for
+    ;; (target . <target>), etc.  Although predicates of interest, like
+    ;; `erc-query-buffer-p', may call on `buffer-local-value', its
+    ;; `buffer' argument will be the current buffer, which doesn't yet
+    ;; have any buffer-local bindings.
+    (cl-assert (not (local-variable-p 'erc-networks--id)))
+    (cl-assert (not (local-variable-p 'erc-network)))
+    (cl-assert (not (local-variable-p 'erc--target)))
+    (let ((erc-networks--id
+           (or (and id (erc-networks--id-create id))
+               (and target (buffer-local-value 'erc-networks--id
+                                               target-server-buffer)))))
+      (if target
+          (if-let*
+              ((erc-network (buffer-local-value 'erc-network
+                                                target-server-buffer))
+               (erc--target (erc--target-from-string target))
+               (bindings (erc-settings--gather-bindings (current-buffer)))
+               (entry (assq 'erc-modules bindings)))
+              (erc-settings--set-value 'erc-modules (nth 1 entry) (cddr entry))
+            (when-let* ((old-value (with-current-buffer target-server-buffer
+                                     (and (local-variable-p 'erc-modules)
+                                          erc-modules))))
+              (setq-local erc-modules old-value)))
+        (erc-settings-bind)))))
+
+(defun erc-settings--gather-bindings (buffer)
+  "Return a list of matching bindings for server BUFFER's session."
+  (with-current-buffer buffer
+    (mapcan (lambda (entry)
+              (and (erc-settings--buffer-match-p (car entry))
+                   (copy-sequence (cdr entry))))
+            erc-settings)))
+
+;; Currently, when a binding contains the experimental flag :custom, ERC
+;; tries to use VAR's `custom-set' function, if defined, for setting its
+;; value. ERC doesn't do so by default because many such functions use
+;; `set-default', which defeats the purpose.
+(defun erc-settings--set-value (var value flags)
+  "Set VAR to VALUE locally and interpret FLAGS.
+Do nothing if VAR already has a local binding.  If VAR has the symbol
+property `erc-settings--wrap', assume it's a function that takes the
+arguments (SETTER VAR VALUE), and defer to it to perform the actual
+setting."
+  (unless (local-variable-p var)
+    (let ((setter #'set)
+          (evalp nil)
+          (customp nil))
+      (dolist (flag flags)
+        (pcase-exhaustive flag
+          (:eval (setq evalp t))
+          (:custom (setq customp t))))
+      (make-local-variable var)
+      (when evalp
+        (setq value (eval value t)))
+      (when customp
+        (custom-load-symbol var)
+        (setq setter (or (get var 'custom-set) #'set)))
+      (if-let* ((xsetter (get var 'erc-settings--wrap)))
+          (funcall xsetter setter var value)
+        (funcall setter var value)))))
+
+(defun erc-settings--set (bindings)
+  "Set all matching bindings locally in current buffer.
+Expect BINDINGS to be a list of (KEY VALUE . FLAGS)."
+  (pcase-dolist (`(,var ,value . ,flags) bindings)
+    (erc-settings--set-value var value flags)))
+
+(defun erc-settings--ensure-prompt-reset (setter var value)
+  (cl-assert (eq var 'erc-prompt))
+  (when (and erc-input-marker (stringp value))
+    (let ((erc-prompt (lambda () value)))
+      (with-silent-modifications
+        (erc--refresh-prompt))))
+  (funcall setter var value))
+
+(put 'erc-prompt 'erc-settings--wrap #'erc-settings--ensure-prompt-reset)
+
+(defun erc-settings--find-condition (predicate settings)
+  "Return all conditions in SETTINGS for which PREDICATE returns non-nil."
+  (letrec ((found ())
+           (find (lambda (condition)
+                   (pcase condition
+                     (`(and . ,rest) (mapc find rest))
+                     (`(or . ,rest) (mapc find rest))
+                     (`(not ,cond) (funcall find cond))
+                     ((pred (funcall predicate)) (push condition found))))))
+    (dolist (setting settings)
+      (funcall find (car setting)))
+    (nreverse found)))
+
+(defun erc-settings--extract-ids ()
+  "Return all arguments to an `id' property condition in `erc-settings'."
+  (mapcar #'cdr (erc-settings--find-condition
+                 (lambda (condition) (eq (car-safe condition) 'id))
+                 erc-settings)))
+
+;;;###autoload
+(defun erc-settings-connect-by-id (network-id)
+  "Connect via some preconfigured network ID specified in `erc-settings'.
+See Info node `(erc) ID-based Settings Example'."
+  (interactive (list (completing-read "Network ID: "
+                                      (erc-settings--extract-ids))))
+  (erc-tls :server nil :port nil :nick nil :user nil
+           :password nil :full-name nil :id network-id))
+
+(provide 'erc-settings)
+
+;;; erc-settings.el ends here
+;;
+;; Local Variables:
+;; generated-autoload-file: "erc-loaddefs.el"
+;; End:
diff --git a/lisp/erc/erc.el b/lisp/erc/erc.el
index b661453fdce..f87d13eb559 100644
--- a/lisp/erc/erc.el
+++ b/lisp/erc/erc.el
@@ -2016,6 +2016,10 @@ buries those."
                     (target (buffer-local-value 'erc--target target))
                     ((erc--target-channel-p target)))))))
 
+(defun erc-channel-buffer-p (&optional buffer)
+  "Call `erc-channel-p' with BUFFER or the current buffer."
+  (erc-channel-p (or buffer (current-buffer))))
+
 ;; For the sake of compatibility, a historical quirk concerning this
 ;; option, when nil, has been preserved: all buffers are suffixed with
 ;; the original dialed host name, which is usually something like
@@ -2410,6 +2414,7 @@ removed modules.  It also gives packages access to the hook
            scrolltobottom)
     (const :tag "services: Identify to Nickserv (IRC Services) automatically"
            services)
+    (const :tag "settings: Set ERC user options buffer locally" settings)
     (const :tag "smiley: Convert smileys to pretty icons" smiley)
     (const :tag "sound: Play sounds when you receive CTCP SOUND requests"
            sound)
diff --git a/test/lisp/erc/erc-scenarios-settings.el b/test/lisp/erc/erc-scenarios-settings.el
new file mode 100644
index 00000000000..97ff547e12b
--- /dev/null
+++ b/test/lisp/erc/erc-scenarios-settings.el
@@ -0,0 +1,190 @@
+;;; erc-scenarios-settings.el --- erc-settings tests -*- lexical-binding: t -*-
+
+;; Copyright (C) 2026 Free Software Foundation, Inc.
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
+
+;;; Code:
+
+(require 'ert-x)
+(eval-and-compile
+  (let ((load-path (cons (ert-resource-directory) load-path)))
+    (require 'erc-scenarios-common)))
+
+(require 'erc-settings)
+
+(ert-deftest erc-scenarios-settings/sasl ()
+  :tags '(:expensive-test)
+  (erc-scenarios-common-with-cleanup
+      ((erc-server-flood-penalty 0.1)
+       (erc-scenarios-common-dialog "settings")
+       (server-foonet (erc-d-run "localhost" t "server-foonet" 'basic-sasl))
+       (server-barnet (erc-d-run "localhost" t "server-barnet" 'basic))
+       (port-foonet (process-contact server-foonet :service))
+       (port-barnet (process-contact server-barnet :service))
+       (erc-modules `(settings ,@erc-modules))
+       (erc-settings
+        `(((and ,(rx-to-string `(: ":" ,(number-to-string port-foonet) eot) t)
+                (not erc-server-process-alive))
+           (erc-modules `(sasl ,@erc-modules) :eval))
+          ((and ,(rx-to-string `(: ":" ,(number-to-string port-barnet) eot) t)
+                (not erc-server-process-alive))
+           (erc-modules `(fill-wrap ,@erc-modules) :eval)
+           (erc-autojoin-channels-alist (("." "#spam"))))
+          ((and (network . foonet) erc-open-server-buffer-p)
+           (erc-prompt "server!!!")
+           (erc-autojoin-channels-alist ((foonet "#chan"))))
+          ((and (network . foonet) erc-channel-buffer-p)
+           (erc-modules `(keep-place-indicator ,@erc-modules) :eval))))
+       (expect (erc-d-t-make-expecter)))
+
+    ;; Simulate `setopt', `custom-set-variables', etc.
+    (erc-update-modules)
+    (with-current-buffer (erc :server "127.0.0.1"
+                              :port port-foonet
+                              :nick "tester"
+                              :user "tester"
+                              :password "changeme"
+                              :full-name "tester")
+      (funcall expect 10 "This server is in debug mode"))
+    (with-current-buffer (erc :server "127.0.0.1"
+                              :port port-barnet
+                              :nick "tester"
+                              :user "tester"
+                              :full-name "tester")
+      (funcall expect 10 "This server is in debug mode"))
+
+    ;; Sentinel variables for modules we're enabling locally.
+    (defvar erc-fill--wrap-last-msg)
+    (defvar erc--keep-place-indicator-overlay)
+
+    (with-current-buffer (erc-d-t-wait-for 10 (get-buffer "#chan"))
+      (funcall expect 10 "<alice> bob: Grows, lives, and dies")
+      (should erc--keep-place-indicator-overlay)
+      (should-not erc-fill--wrap-last-msg)
+      (funcall expect 10 "ERC>"))
+
+    ;; Targets that don't specify their own local modules inherit any
+    ;; from their server buffer (if `erc-modules' is locally bound).
+    (with-current-buffer (erc-d-t-wait-for 10 (get-buffer "#spam"))
+      (funcall expect 10 "<bob> alice: Ay, like a")
+      (should-not erc--keep-place-indicator-overlay)
+      (should erc-fill--wrap-last-msg)
+      (funcall expect 10 "ERC>"))
+
+    ;; Point in fact: `fill-wrap' is enabled in this query buffer.
+    (with-current-buffer (erc-d-t-wait-for 10 (get-buffer "alice"))
+      (funcall expect 10 "<alice> My hand to thee")
+      (should-not erc--keep-place-indicator-overlay)
+      (should erc-fill--wrap-last-msg)
+      (funcall expect 10 "ERC>"))
+
+    (with-current-buffer (erc-d-t-wait-for 10 (get-buffer "foonet"))
+      (should-not erc--keep-place-indicator-overlay)
+      (should-not  erc-fill--wrap-last-msg)
+      (funcall expect 10 "server!!!"))
+
+    (with-current-buffer (erc-d-t-wait-for 10 (get-buffer "barnet"))
+      (should-not erc--keep-place-indicator-overlay)
+      (should erc-fill--wrap-last-msg)
+      (funcall expect 10 "ERC>"))
+
+    (erc-settings-mode -1)))
+
+(ert-deftest erc-scenarios-settings/sasl/id ()
+  :tags '(:expensive-test)
+  (erc-scenarios-common-with-cleanup
+      ((erc-server-flood-penalty 0.1)
+       (erc-scenarios-common-dialog "settings")
+       (server-foonet (erc-d-run "localhost" t "server-foonet" 'basic-sasl))
+       (server-barnet (erc-d-run "localhost" t "server-barnet" 'basic))
+       (port-foonet (process-contact server-foonet :service))
+       (port-barnet (process-contact server-barnet :service))
+       (erc-modules `(settings ,@erc-modules))
+       (erc-settings
+        `(((not erc-server-process-alive) ; common to both servers
+           (erc-server "127.0.0.1")
+           (erc-nick "tester")
+           (erc-email-userid "tester")
+           (erc-user-full-name "tester"))
+          ;; If this were moved to the end of the list (try it), ERC
+          ;; would skip it because (id . x) matches in channels too.
+          (erc-channel-buffer-p ; all channels
+           (erc-modules `(keep-place-indicator ,@erc-modules) :eval))
+          ((id . id-foonet) ; foonet only (channels too)
+           (erc-port ,port-foonet)
+           (erc-sasl-password "changeme")
+           (erc-modules `(sasl ,@erc-modules) :eval)
+           (erc-prompt "wee!!!")
+           (erc-autojoin-channels-alist ((id-foonet "#chan"))))
+          ((id . id-barnet) ; barnet only (channels too)
+           (erc-port ,port-barnet)
+           (erc-modules `(fill-wrap ,@erc-modules) :eval)
+           (erc-autojoin-channels-alist ((id-barnet "#spam"))))))
+       (expect (erc-d-t-make-expecter)))
+
+    ;; Simulate `setopt', `custom-set-variables', etc.
+    (erc-update-modules)
+
+    ;; Mimic `erc-settings-connect-by-id', except don't use TLS.
+    (with-current-buffer (erc :server nil :port nil :nick nil :user nil
+                              :password nil :full-name nil :id 'id-foonet)
+      (should (equal (buffer-name) "id-foonet"))
+      (funcall expect 10 "This server is in debug mode"))
+    (with-current-buffer (erc :server nil :port nil :nick nil :user nil
+                              :password nil :full-name nil :id 'id-barnet)
+      (should (equal (buffer-name) "id-barnet"))
+      (funcall expect 10 "This server is in debug mode"))
+
+    ;; Sentinel variables for modules we're enabling locally.
+    (defvar erc-fill--wrap-last-msg)
+    (defvar erc--keep-place-indicator-overlay)
+
+    (with-current-buffer (erc-d-t-wait-for 10 (get-buffer "#chan"))
+      (funcall expect 10 "<alice> bob: Grows, lives, and dies")
+      (should erc--keep-place-indicator-overlay)
+      (should-not erc-fill--wrap-last-msg)
+      (funcall expect 10 "wee!!!"))
+
+    ;; Channel-only module overrides were applied correctly.
+    (with-current-buffer (erc-d-t-wait-for 10 (get-buffer "#spam"))
+      (funcall expect 10 "<bob> alice: Ay, like a")
+      (should erc--keep-place-indicator-overlay)
+      (should-not erc-fill--wrap-last-msg)
+      (funcall expect 10 "ERC>"))
+
+    ;; Module `fill-wrap' is active in this query buffer because it has
+    ;; no query-specific overrides for `erc-modules'.  It instead
+    ;; inherits the local value from the server buffer.
+    (with-current-buffer (erc-d-t-wait-for 10 (get-buffer "alice"))
+      (funcall expect 10 "<alice> My hand to thee")
+      (should-not erc--keep-place-indicator-overlay)
+      (should erc-fill--wrap-last-msg)
+      (funcall expect 10 "ERC>"))
+
+    (with-current-buffer "id-foonet"
+      (should-not erc--keep-place-indicator-overlay)
+      (should-not  erc-fill--wrap-last-msg)
+      (funcall expect 10 "wee!!!"))
+
+    (with-current-buffer "id-barnet"
+      (should-not erc--keep-place-indicator-overlay)
+      (should erc-fill--wrap-last-msg)
+      (funcall expect 10 "ERC>"))
+
+    (erc-settings-mode -1)))
+
+;;; erc-scenarios-settings.el ends here
diff --git a/test/lisp/erc/erc-settings-tests.el b/test/lisp/erc/erc-settings-tests.el
new file mode 100644
index 00000000000..a9e338992db
--- /dev/null
+++ b/test/lisp/erc/erc-settings-tests.el
@@ -0,0 +1,119 @@
+;;; erc-settings-tests.el --- Tests for erc-settings  -*- lexical-binding:t -*-
+
+;; Copyright (C) 2026 Free Software Foundation, Inc.
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;;; Code:
+
+(require 'erc-settings)
+(require 'ert-x)
+(eval-and-compile
+  (let ((load-path (cons (ert-resource-directory) load-path)))
+    (require 'erc-tests-common)))
+
+;; This test does some Custom type checking via `setopt'.
+(ert-deftest erc-settings ()
+  (when (< emacs-major-version 29) (ert-skip "Needs `setopt'"))
+
+  (cl-letf* ((erc-settings ())
+             ((symbol-function 'set-default) #'set)
+             ((symbol-function 'warn) #'error))
+
+    (setopt erc-settings `(((or (network . foonet)
+                                ,(rx bot "127.0.0.1:"))
+                            (erc-foo 1))
+                           ((and ,(rx bot "#emacs")
+                                 (not ,(rx bot "#emacs-devel")))
+                            (erc-foo 2)
+                            (erc-bar 3))))
+
+    ;; Realistic predicates and bindings.
+    (setopt erc-settings '(((and (id . foonet)
+                                 (not erc-server-process-alive))
+                            (erc-prompt "ERC! ")
+                            (erc-sasl-user :nick))
+                           (erc-open-server-buffer-p
+                            (erc-autojoin-channels-alist (("." "#chan"))))
+                           ((or "#chan" "#spam" erc-query-buffer-p)
+                            (erc-modules `(keep-place-indicator ,@erc-modules)
+                                         :eval))))
+
+    ;; Network can also be a regexp.
+    (setopt erc-settings `(((or ,(rx bot (| "localhost" "127.0.0.1") ":")
+                                (network . foonet))
+                            (erc-foo 1))
+                           ((or ,(rx bot "#emacs") "#erc")
+                            (erc-foo 2)))))
+
+  (should (equal erc-settings ())))
+
+(ert-deftest erc-settings--gather-bindings ()
+
+  ;; Match by network only.
+  (with-current-buffer (get-buffer-create "foonet")
+    (setq erc-network 'foonet)
+    (let ((erc-settings '(((or (network . barnet) ignore nil))
+                          ((and (network . foonet) always t)
+                           (erc-foo 1) (erc-bar 2))
+                          ((network . baznet)))))
+      (should (equal '((erc-foo 1) (erc-bar 2))
+                     (erc-settings--gather-bindings (current-buffer)))))
+    (kill-buffer))
+
+  ;; Multiple regexps.
+  (with-current-buffer (get-buffer-create "localhost:6697")
+    (let ((erc-settings '(((network . barnet))
+                          ("\\`localhost"
+                           (erc-foo 1))
+                          ("."
+                           (erc-bar 2)))))
+      (should (equal '((erc-foo 1) (erc-bar 2))
+                     (erc-settings--gather-bindings (current-buffer))))
+      (kill-buffer)))
+
+  ;; One regexp, one network.
+  (with-current-buffer (get-buffer-create "foonet")
+    (setq erc-network 'foonet)
+    (let ((erc-settings `((,(rx (| "foonet" "barnet"))
+                           (erc-foo 1))
+                          ((and (network . foonet) (name . "foonet"))
+                           (erc-bar 2)))))
+      (should (equal '((erc-foo 1) (erc-bar 2))
+                     (erc-settings--gather-bindings (current-buffer)))))
+    (kill-buffer)))
+
+(ert-deftest erc-settings--extract-ids ()
+  (should-not (erc-settings--extract-ids))
+
+  ;; Does not deduplicate.
+  (let ((erc-settings '(((id . a)
+                         (erc-foo 0))
+                        ("."
+                         (erc-foo 1))
+                        ((and t nil)
+                         (erc-foo 2))
+                        ((and ignore (id . b))
+                         (erc-foo 3))
+                        ((or (not (id . c)) (and (id . d) ignore))
+                         (erc-foo 4))
+                        ((not (id . a))
+                         (erc-foo 5)))))
+    (should (equal (erc-settings--extract-ids) '(a b c d a)))))
+
+;;; erc-settings-tests.el ends here
diff --git a/test/lisp/erc/erc-tests.el b/test/lisp/erc/erc-tests.el
index b3a39c66f5a..74c1a4bfa19 100644
--- a/test/lisp/erc/erc-tests.el
+++ b/test/lisp/erc/erc-tests.el
@@ -3807,6 +3807,7 @@
     sasl
     scrolltobottom
     services
+    settings
     smiley
     sound
     spelling
diff --git a/test/lisp/erc/resources/settings/basic-sasl.eld b/test/lisp/erc/resources/settings/basic-sasl.eld
new file mode 100644
index 00000000000..33d57018bb7
--- /dev/null
+++ b/test/lisp/erc/resources/settings/basic-sasl.eld
@@ -0,0 +1,47 @@
+;; -*- mode: lisp-data; -*-
+((cap 10 "CAP REQ :sasl"))
+((nick 10 "NICK tester"))
+((user 10 "USER tester 0 * :tester"))
+((authenticate 10 "AUTHENTICATE PLAIN")
+ (0.00 ":irc.foonet.org CAP * ACK sasl")
+ (0.04 "AUTHENTICATE +"))
+((authenticate 10 "AUTHENTICATE AHRlc3RlcgBjaGFuZ2VtZQ==")
+ (0.01 ":irc.foonet.org 900 * * tester :You are now logged in as tester")
+ (0.01 ":irc.foonet.org 903 * :Authentication successful"))
+((cap 10 "CAP END")
+ (0.00 ":irc.foonet.org 001 tester :Welcome to the foonet IRC Network tester")
+ (0.01 ":irc.foonet.org 002 tester :Your host is irc.foonet.org, running version ergo-v2.11.1")
+ (0.01 ":irc.foonet.org 003 tester :This server was created Sat, 01 Feb 2025 03:19:43 UTC")
+ (0.00 ":irc.foonet.org 004 tester irc.foonet.org ergo-v2.11.1 BERTZios CEIMRUabefhiklmnoqstuv Iabefhkloqv")
+ (0.00 ":irc.foonet.org 005 tester AWAYLEN=390 BOT=B CASEMAPPING=ascii CHANLIMIT=#:100 CHANMODES=Ibe,k,fl,CEMRUimnstu CHANNELLEN=64 CHANTYPES=# CHATHISTORY=25 ELIST=U EXCEPTS EXTBAN=,m FORWARD=f INVEX :are supported by this server")
+ (0.01 ":irc.foonet.org 005 tester KICKLEN=390 MAXLIST=beI:60 MAXTARGETS=4 MODES MONITOR=100 NETWORK=foonet NICKLEN=32 PREFIX=(qaohv)~&@%+ STATUSMSG=~&@%+ TARGMAX=NAMES:1,LIST:1,KICK:,WHOIS:1,USERHOST:10,PRIVMSG:4,TAGMSG:4,NOTICE:4,MONITOR:100 TOPICLEN=390 UTF8ONLY WHOX :are supported by this server")
+ (0.03 ":irc.foonet.org 005 tester draft/CHATHISTORY=25 :are supported by this server")
+ (0.00 ":irc.foonet.org 251 tester :There are 0 users and 4 invisible on 1 server(s)")
+ (0.00 ":irc.foonet.org 252 tester 0 :IRC Operators online")
+ (0.00 ":irc.foonet.org 253 tester 0 :unregistered connections")
+ (0.00 ":irc.foonet.org 254 tester 2 :channels formed")
+ (0.00 ":irc.foonet.org 255 tester :I have 4 clients and 0 servers")
+ (0.00 ":irc.foonet.org 265 tester 4 4 :Current local users 4, max 4")
+ (0.03 ":irc.foonet.org 266 tester 4 4 :Current global users 4, max 4")
+ (0.00 ":irc.foonet.org 422 tester :MOTD File is missing")
+ (0.00 ":irc.foonet.org 221 tester +i")
+ (0.00 ":irc.foonet.org NOTICE tester :This server is in debug mode and is logging all user I/O. If you do not wish for everything you send to be readable by the server owner(s), please disconnect."))
+
+((mode-user 10 "MODE tester +i")
+ (0.00 ":irc.foonet.org 221 tester +i"))
+
+((join 10 "JOIN #chan")
+ (0.00 ":[email protected] JOIN #chan")
+ (0.03 ":irc.foonet.org 353 tester = #chan :@fsbot bob alice tester")
+ (0.03 ":irc.foonet.org 366 tester #chan :End of NAMES list")
+ (0.00 ":[email protected] PRIVMSG #chan :tester, welcome!")
+ (0.01 ":[email protected] PRIVMSG #chan :tester, welcome!")
+ (0.01 ":[email protected] PRIVMSG #chan :alice: Then the liars and swearers are fools, for there are liars and swearers enow to beat the honest men, and hang up them."))
+
+((mode-chan 10 "MODE #chan")
+ (0.00 ":irc.foonet.org 324 tester #chan +Cnt")
+ (0.01 ":irc.foonet.org 329 tester #chan 1738379988")
+ (0.07 ":[email protected] PRIVMSG #chan :bob: Grows, lives, and dies, in single blessedness.")
+ (0.05 ":[email protected] PRIVMSG #chan :alice: Is't come to this, i' faith ? Hath not the world one man but he will wear his cap with suspicion ? Shall I never see a bachelor of three-score again ? Go to, i' faith; an thou wilt needs thrust thy neck into a yoke, wear the print of it, and sigh away Sundays. Look! Don Pedro is returned to seek you.")
+ (0.05 ":[email protected] PRIVMSG #chan :There's the fool hangs on your back already.")
+ (0.07 ":[email protected] PRIVMSG #chan :bob: Here is a purr of Fortune's, sir, or of Fortune's cat but not a musk-cat that has fallen into the unclean fishpond of her displeasure, and, as he says, is muddied withal. Pray you, sir, use the carp as you may, for he looks like a poor, decayed, ingenious, foolish, rascally knave. I do pity his distress in my similes of comfort, and leave him to your lordship."))
diff --git a/test/lisp/erc/resources/settings/basic.eld b/test/lisp/erc/resources/settings/basic.eld
new file mode 100644
index 00000000000..e6a54f1fd38
--- /dev/null
+++ b/test/lisp/erc/resources/settings/basic.eld
@@ -0,0 +1,38 @@
+;; -*- mode: lisp-data; -*-
+((nick 10 "NICK tester"))
+((user 10 "USER tester 0 * :tester")
+ (0.00 ":irc.barnet.org 001 tester :Welcome to the barnet IRC Network tester")
+ (0.01 ":irc.barnet.org 002 tester :Your host is irc.barnet.org, running version ergo-v2.11.1")
+ (0.01 ":irc.barnet.org 003 tester :This server was created Sat, 01 Feb 2025 03:19:43 UTC")
+ (0.00 ":irc.barnet.org 004 tester irc.barnet.org ergo-v2.11.1 BERTZios CEIMRUabefhiklmnoqstuv Iabefhkloqv")
+ (0.00 ":irc.barnet.org 005 tester AWAYLEN=390 BOT=B CASEMAPPING=ascii CHANLIMIT=#:100 CHANMODES=Ibe,k,fl,CEMRUimnstu CHANNELLEN=64 CHANTYPES=# CHATHISTORY=25 ELIST=U EXCEPTS EXTBAN=,m FORWARD=f INVEX :are supported by this server")
+ (0.01 ":irc.barnet.org 005 tester KICKLEN=390 MAXLIST=beI:60 MAXTARGETS=4 MODES MONITOR=100 NETWORK=barnet NICKLEN=32 PREFIX=(qaohv)~&@%+ STATUSMSG=~&@%+ TARGMAX=NAMES:1,LIST:1,KICK:,WHOIS:1,USERHOST:10,PRIVMSG:4,TAGMSG:4,NOTICE:4,MONITOR:100 TOPICLEN=390 UTF8ONLY WHOX :are supported by this server")
+ (0.03 ":irc.barnet.org 005 tester draft/CHATHISTORY=25 :are supported by this server")
+ (0.00 ":irc.barnet.org 251 tester :There are 0 users and 4 invisible on 1 server(s)")
+ (0.00 ":irc.barnet.org 252 tester 0 :IRC Operators online")
+ (0.00 ":irc.barnet.org 253 tester 0 :unregistered connections")
+ (0.00 ":irc.barnet.org 254 tester 2 :channels formed")
+ (0.00 ":irc.barnet.org 255 tester :I have 4 clients and 0 servers")
+ (0.00 ":irc.barnet.org 265 tester 4 4 :Current local users 4, max 4")
+ (0.03 ":irc.barnet.org 266 tester 4 4 :Current global users 4, max 4")
+ (0.00 ":irc.barnet.org 422 tester :MOTD File is missing")
+ (0.00 ":irc.barnet.org 221 tester +i")
+ (0.00 ":irc.barnet.org NOTICE tester :This server is in debug mode and is logging all user I/O. If you do not wish for everything you send to be readable by the server owner(s), please disconnect."))
+
+((mode-user 10 "MODE tester +i")
+ (0.00 ":irc.barnet.org 221 tester +i"))
+
+((join 10 "JOIN #spam")
+ (0.00 ":[email protected] JOIN #spam")
+ (0.03 ":irc.barnet.org 353 tester = #spam :@fsbot bob alice tester")
+ (0.03 ":irc.barnet.org 366 tester #spam :End of NAMES list")
+ (0.00 ":[email protected] PRIVMSG #spam :tester, welcome!")
+ (0.01 ":[email protected] PRIVMSG #spam :tester, welcome!")
+ (0.07 ":[email protected] PRIVMSG #spam :Prithee, unpin me,have grace and favour in them."))
+
+((mode-chan 10 "MODE #spam")
+ (0.00 ":irc.barnet.org 324 tester #spam +Cnt")
+ (0.01 ":irc.barnet.org 329 tester #spam 1738379988")
+ (0.04 ":[email protected] PRIVMSG #spam :alice: Ay, like a black dog, as the saying is.")
+ (0.07 ":[email protected] PRIVMSG tester :My hand to thee; mine honour on my promise.")
+ (0.02 ":[email protected] PRIVMSG #spam :bob: She is Lavinia, therefore must be lov'd."))