pax_global_header 0000666 0000000 0000000 00000000064 15225053467 0014523 g ustar 00root root 0000000 0000000 52 comment=d0b50926a186d2de72aa12c6d6b06e384731865a
emacs-keymap-popup-0.4.0/ 0000775 0000000 0000000 00000000000 15225053467 0015241 5 ustar 00root root 0000000 0000000 emacs-keymap-popup-0.4.0/.elpaignore 0000664 0000000 0000000 00000000105 15225053467 0017363 0 ustar 00root root 0000000 0000000 CONTRIBUTING.org
LICENSE
Makefile
flake.lock
flake.nix
tests
decks
emacs-keymap-popup-0.4.0/.gitignore 0000664 0000000 0000000 00000000165 15225053467 0017233 0 ustar 00root root 0000000 0000000 research
*.elc
*-autoloads.el
*-pkg.el
.*
!.gitignore
!.elpaignore
\#*
*.md
*.info
*.texi
refs/*
tests/live-test.el emacs-keymap-popup-0.4.0/LICENSE 0000664 0000000 0000000 00000104516 15225053467 0016255 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program 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.
This program 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 this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
emacs-keymap-popup-0.4.0/Makefile 0000664 0000000 0000000 00000003336 15225053467 0016706 0 ustar 00root root 0000000 0000000 .POSIX:
NIX := $(shell command -v nix 2>/dev/null)
USE_NIX ?= 1
ENV_MAKE = $(MAKE) --no-print-directory
ifeq ($(USE_NIX),1)
ifeq ($(IN_NIX_SHELL),)
ifneq ($(NIX),)
ENV_MAKE = nix develop path:. --command $(MAKE) --no-print-directory USE_NIX=0
endif
endif
endif
EMACS_CMD ?= emacs
EMACS_OPTS ?= -Q --batch
SRCS = keymap-popup.el
TESTS = tests/keymap-popup-tests.el
BATCH = $(EMACS_CMD) $(EMACS_OPTS)
ORG = docs/keymap-popup.org
TEXI = docs/keymap-popup.texi
INFO = docs/keymap-popup.info
.PHONY: all compile do-compile test do-test lint do-lint doc do-doc clean dev do-dev load
all: compile
compile:
@$(ENV_MAKE) do-compile
do-compile:
@echo "Compiling $(SRCS)..."
@$(BATCH) -f batch-byte-compile $(SRCS)
test:
@$(ENV_MAKE) do-test
do-test:
@echo "Testing $(TESTS)..."
@$(BATCH) -l ert -l $(SRCS) -l $(TESTS) -f ert-run-tests-batch-and-exit
lint:
@$(ENV_MAKE) do-lint
do-lint:
@echo "Running checkdoc..."
@$(BATCH) --eval '(checkdoc-file "$(SRCS)")'
@echo "Running package-lint..."
@$(BATCH) --eval '(package-initialize)' \
--eval '(require (quote package-lint))' \
-f package-lint-batch-and-exit $(SRCS)
doc:
@$(ENV_MAKE) do-doc
do-doc: $(INFO)
$(INFO): $(ORG)
@echo "Building $(INFO)..."
@$(BATCH) --load org \
--eval "(with-current-buffer (find-file \"$(ORG)\") (org-texinfo-export-to-info))" \
--kill
dev:
@$(ENV_MAKE) do-dev
do-dev: do-compile do-lint do-test
load:
@emacsclient --eval "(progn \
(add-to-list (quote load-path) \"$(CURDIR)\") \
(when (boundp (quote keymap-popup-display-action)) \
(makunbound (quote keymap-popup-display-action))) \
(load-file \"$(CURDIR)/$(SRCS)\"))" > /dev/null
@printf "\033[32mLoaded keymap-popup into Emacs\033[0m\n"
clean:
rm -f *.elc $(TEXI) $(INFO)
emacs-keymap-popup-0.4.0/README.org 0000664 0000000 0000000 00000005146 15225053467 0016715 0 ustar 00root root 0000000 0000000 #+title: keymap-popup.el
A macro that defines a keymap with embedded descriptions and a popup
to display them.
=One definition, two uses: direct key dispatch and interactive menu.=
Unlike =transient=, the result is a real keymap built on stock Emacs
primitives (=defvar-keymap=, =set-transient-map=, =menu-item=
filters): =where-is=, =describe-bindings=, =keymap-set=, and normal
keymap composition all work without special-casing. Plain data
end-to-end -- no EIEIO, no parallel command registry. Sub-prefix
state and infix arguments are deliberately out of scope; for those,
use transient.
** Installation
Requires Emacs 29.1+. No external dependencies.
#+begin_src emacs-lisp
(add-to-list 'load-path "/path/to/keymap-popup")
(require 'keymap-popup)
#+end_src
Or with =use-package=:
#+begin_src emacs-lisp
(use-package keymap-popup
:ensure t)
#+end_src
** Quick start
#+begin_src emacs-lisp
(keymap-popup-define my-commands-map
"My commands."
:group "Edit"
"c" ("Comment" comment-dwim)
"r" ("Rename" rename-file)
:group "View"
"g" ("Refresh" revert-buffer)
"q" ("Quit" quit-window))
;; Use as a normal keymap:
(keymap-set some-mode-map "C-c m" my-commands-map)
;; Or show the popup directly:
(keymap-popup my-commands-map)
#+end_src
Press =h= in the keymap to open the popup. Press =q= to dismiss.
** Features
- =:switch= -- buffer-local toggle with =[on]/[off]= display
- =:keymap= -- sub-menu with stack navigation (=q= / =C-g= pops back)
- =:stay-open= -- command executes without dismissing the popup
- =:inapt-if= -- grays out and blocks entries based on a predicate
- =:c-u= -- prefix argument mode (=C-u= highlights eligible entries)
- =:if= -- conditionally hide entries
- =:group= / =:row= -- column layout
- Dynamic descriptions via lambdas
- =keymap-popup-annotate= -- add popup descriptions to existing keymaps
- =keymap-popup-attach= -- attach descriptions built from runtime data
** Documentation
Full usage -- special bindings, sub-menus, annotating keymaps like
=dired-mode-map=, display backends, customization -- lives in the
[[file:docs/keymap-popup.org][user manual]], also available as an Info
manual (=make doc=).
** Development
The repository flake pins Nixpkgs and provides Emacs, GNU Make,
Texinfo, and package-lint. Public Make targets enter the development
shell automatically when Nix is available:
#+begin_src sh
make dev
make doc
#+end_src
Enter the same environment manually with =nix develop=. Run the
sandboxed package build, tests, lint checks, and manual build with:
#+begin_src sh
nix flake check
#+end_src
Set =USE_NIX=0= to run a Make target directly in the current
environment.
emacs-keymap-popup-0.4.0/docs/ 0000775 0000000 0000000 00000000000 15225053467 0016171 5 ustar 00root root 0000000 0000000 emacs-keymap-popup-0.4.0/docs/keymap-popup.org 0000664 0000000 0000000 00000035165 15225053467 0021343 0 ustar 00root root 0000000 0000000 #+title: Keymap Popup User Manual
#+author: Thanos Apollo
#+email: public@thanosapollo.org
#+language: en
#+options: ':t toc:t author:t email:t num:t
#+texinfo_filename: keymap-popup.info
#+texinfo_dir_category: Emacs misc features
#+texinfo_dir_title: Keymap Popup: (keymap-popup)
#+texinfo_dir_desc: Define a keymap once, dispatch keys and show a popup menu
* Table of Contents :noexport:
:PROPERTIES:
:TOC: this
:END:
- [[#introduction][Introduction]]
- [[#installation][Installation]]
- [[#quick-start][Quick start]]
- [[#defining-keymaps][Defining keymaps]]
- [[#showing-popup][Showing the popup]]
- [[#special-bindings][Special bindings]]
- [[#prompting][Prompting and re-entry]]
- [[#annotate][Annotating existing keymaps]]
- [[#customization][Customization]]
- [[#vs-transient][When to use this vs transient]]
- [[#contributing][Contributing]]
- [[#gfdl][GNU Free Documentation License]]
* Introduction
:PROPERTIES:
:CUSTOM_ID: introduction
:END:
=keymap-popup= defines a normal Emacs keymap with embedded
descriptions, and renders it as a popup menu on demand. One
definition, two uses: direct key dispatch and an interactive menu.
Requires Emacs 29.1 or later (for =defvar-keymap=).
No external dependencies.
* Installation
:PROPERTIES:
:CUSTOM_ID: installation
:END:
** From source
#+begin_src emacs-lisp
(add-to-list 'load-path "/path/to/keymap-popup")
(require 'keymap-popup)
#+end_src
** With ~use-package~
#+begin_src emacs-lisp
(use-package keymap-popup
:ensure t)
#+end_src
* Quick start
:PROPERTIES:
:CUSTOM_ID: quick-start
:END:
#+begin_src emacs-lisp
(keymap-popup-define my-commands-map
"My commands."
:group "Edit"
"c" ("Comment" comment-dwim)
"r" ("Rename" rename-file)
:group "View"
"g" ("Refresh" revert-buffer)
"b" ("Bury buffer" bury-buffer))
(keymap-set some-mode-map "C-c m" my-commands-map)
#+end_src
The macro auto-binds =h= inside the keymap, so =C-c m h= opens the
popup. =q= or =C-g= dismisses it.
* Defining keymaps
:PROPERTIES:
:CUSTOM_ID: defining-keymaps
:END:
** Macro syntax
#+begin_src emacs-lisp
(keymap-popup-define MAP-NAME
DOCSTRING
:popup-key KEY :exit-key KEY
:parent KEYMAP :description STRING-OR-FN
:persistent BOOL
BINDING...)
#+end_src
Only =MAP-NAME= and the bindings are required; every keyword above
is optional and may appear in any order. =keymap-popup-annotate=
takes the same keywords but does /not/ apply defaults for
=:popup-key= or =:exit-key= -- it never binds keys unless asked.
A binding takes one of three forms:
#+begin_src emacs-lisp
KEY (DESC COMMAND [PROP VALUE...]) ; ordinary command
KEY (DESC :switch VAR [PROP VALUE...]) ; toggle
KEY (DESC :keymap MAP [PROP VALUE...]) ; sub-menu
#+end_src
- =KEY= -- =key-valid-p= string.
- =DESC= -- string or zero-arg function (called at render time in the
user's buffer, so it sees buffer-local state).
- =COMMAND= -- command symbol or a =(lambda () (interactive) ...)=.
- =PROP= -- one of =:if=, =:inapt-if=, =:stay-open=, =:c-u= (see
[[#special-bindings][Special bindings]]).
=:stay-open= is a boolean flag and may omit its =t= value.
** Groups and rows
#+begin_src emacs-lisp
(keymap-popup-define my-feed-map
:group "Navigation"
"n" ("Next" next-line :stay-open t)
"p" ("Previous" previous-line :stay-open t)
:group "Tags"
"r" ("Toggle read" my-feed-toggle-read :stay-open t)
:row
:group "Feeds"
"A" ("Add feed" my-feed-add)
"D" ("Remove feed" my-feed-remove))
#+end_src
=:row= between groups starts a fresh row of columns beneath the
first. Groups may attach their own predicates:
=:group ("Bulk" :if PRED :inapt-if PRED)=.
** Dynamic descriptions
#+begin_src emacs-lisp
(keymap-popup-define my-encryption-map
:description (lambda ()
(format "Encryption: %s" my-chat-encryption))
"o" ("OMEMO" my-chat-encryption-set-omemo)
"g" ("OpenPGP" my-chat-encryption-set-openpgp)
"p" ("Plaintext" my-chat-encryption-set-plaintext))
#+end_src
The header is re-rendered after each command.
** Sharing bindings with =:parent=
Same semantics as =defvar-keymap='s =:parent=. The popup walks the
parent chain, so parent bindings appear in the child's menu under
their original group.
If a key is bound in both parent and child, the child wins for
both dispatch and display. Shadowed parent entries are dropped
from the popup, and a parent group whose entries are all shadowed
disappears entirely.
#+begin_src emacs-lisp
(keymap-popup-define my-items-mode-map
:parent my-dashboard-common-map
:group "Items"
"RET" ("Open" my-items-open)
"q" ("Back" my-items-back))
#+end_src
** Adding and removing entries at runtime
#+begin_src emacs-lisp
(keymap-popup-add-entry my-commands-map
"l" "Log message" #'my-log-message
"Edit")
(keymap-popup-remove-entry my-commands-map "l")
#+end_src
Signatures:
- =(keymap-popup-add-entry KEYMAP KEY DESC COMMAND &optional GROUP)=
- =(keymap-popup-remove-entry KEYMAP KEY)=
Both mutate the keymap and its descriptions in place. Re-adding a
key replaces the prior entry (in whatever group it was in),
matching =keymap-set='s semantics.
* Showing the popup
:PROPERTIES:
:CUSTOM_ID: showing-popup
:END:
#+begin_src emacs-lisp
;;;###autoload
(defun yeetube ()
(interactive)
(keymap-popup yeetube-mode-map))
#+end_src
=C-g= always dismisses, regardless of the configured =:exit-key=.
** Display backends
=keymap-popup-backend= selects =keymap-popup-backend-side-window=
(default) or =keymap-popup-backend-child-frame=. Bind it locally for
a one-off floating popup:
#+begin_src emacs-lisp
(defun my-commands-floating ()
(interactive)
(let ((keymap-popup-backend #'keymap-popup-backend-child-frame))
(keymap-popup my-commands-map)))
#+end_src
** Persistent popups
:PROPERTIES:
:CUSTOM_ID: persistent
:END:
By default the popup dismisses after a suffix command runs.
=:persistent t= keeps it open until the exit key or =C-g=:
#+begin_src emacs-lisp
(keymap-popup-define my-map :persistent t ...)
(keymap-popup-annotate dired-mode-map :popup-key "?" :persistent t ...)
(setopt keymap-popup-persistent t) ; global default
#+end_src
Per-keymap setting wins over the global one.
** Dismissing programmatically
Call =keymap-popup-dismiss= from a command to close the popup before
transitioning elsewhere:
#+begin_src emacs-lisp
(defun my-open-detail ()
(interactive)
(keymap-popup-dismiss)
(pop-to-buffer "*detail*"))
#+end_src
* Special bindings
:PROPERTIES:
:CUSTOM_ID: special-bindings
:END:
Predicate quick reference:
- =:if= -- /hide/ the entry (or group) when the predicate returns nil.
- =:inapt-if= -- /grey out/ the entry and block its key when the predicate returns non-nil.
** Sub-menus with =:keymap=
#+begin_src emacs-lisp
(keymap-popup-define my-dashboard-mode-map
:group "Navigate"
"n" ("Nodes" :keymap my-dashboard-nodes-map)
"t" ("Themata" :keymap my-dashboard-themata-map)
:group "More"
"x" ("Import/Export" :keymap my-dashboard-io-map))
#+end_src
Sub-menu entries use the =keymap-popup-submenu= face. Nesting is
unlimited; the exit key pops one level.
** Toggles with =:switch=
#+begin_src emacs-lisp
(keymap-popup-define yeetube-mode-map
:group "Actions"
"o" ("Settings" :switch yeetube--show-settings)
:group "Settings"
"V" ("No video" :switch yeetube-mpv-no-video
:if (lambda () yeetube--show-settings)))
#+end_src
The variable is auto-declared via =defvar= + =make-variable-buffer-local=;
each buffer gets its own value on first set. Switches always keep
the popup open -- no need to add =:stay-open t=.
** Stay-open commands with =:stay-open=
#+begin_src emacs-lisp
(keymap-popup-define my-mark-map
:group "Mark"
"m" ("Mark" dired-mark :stay-open)
"u" ("Unmark" dired-unmark :stay-open)
"U" ("Unmark all" dired-unmark-all-marks))
#+end_src
For an entire popup, prefer =:persistent t= (see [[#persistent][Persistent popups]]).
** Disabling entries with =:inapt-if=
#+begin_src emacs-lisp
(keymap-popup-define yeetube-mode-map
:group "Settings"
"p" ("Toggle pause" yeetube-mpv-toggle-pause
:inapt-if (lambda () (not (get-process yeetube-mpv--process-name)))))
;; Group-level applies to every entry in the group:
(keymap-popup-define my-bulk-map
:group ("Bulk" :inapt-if (lambda () (not (my-marked-files))))
"c" ("Chmod" my-do-chmod)
"z" ("Compress" my-do-compress))
#+end_src
Inapt entries render in =keymap-popup-inapt= and print "Command
unavailable" when pressed.
** Hiding entries with =:if=
#+begin_src emacs-lisp
(keymap-popup-define yeetube-mode-map
"o" ("Settings" :switch yeetube--show-settings)
:group ("Playback" :if (lambda () yeetube--show-settings))
"p" ("Toggle pause" yeetube-mpv-toggle-pause)
"v" ("Toggle video" yeetube-mpv-toggle-video))
#+end_src
** Prefix-arg variants with =:c-u=
#+begin_src emacs-lisp
(keymap-popup-define my-greet-map
:group "Actions"
"a" ("Greet" my-greet :c-u "SHOUT (C-u)"))
#+end_src
The =:c-u= label renders in =shadow= alongside the description as a
hint. Pressing =C-u= enters prefix-arg mode: =:c-u= entries switch
to =warning=, all other entries dim with =shadow=, and
=universal-argument-map= takes over so further =C-u=, digits, and
=-= compose the prefix as usual. Pressing the key then runs the
command with =current-prefix-arg= set, exactly like any
=interactive "P"= command.
* Prompting and re-entry
:PROPERTIES:
:CUSTOM_ID: prompting
:END:
Suffix commands dismiss the popup when they return. For commands
that prompt (=read-string=, =completing-read=, ...) and should leave
the popup visible, either set =:persistent t= on the keymap or
re-invoke =keymap-popup= at the end of the command:
#+begin_src emacs-lisp
(defun my-edit-set-title ()
(interactive)
(let ((new (read-string "Title: ")))
(my-db-set-title new))
(keymap-popup my-edit-map))
(keymap-popup-define my-edit-map
:group "Edit"
"t" ("Title" my-edit-set-title))
#+end_src
The same pattern works with a lambda in the binding itself:
#+begin_src emacs-lisp
(keymap-popup-define my-settings-map
:group "Settings"
"n" ((lambda () (format "Limit: %d" my--limit))
(lambda ()
(interactive)
(setq-local my--limit (read-number "Limit: "))
(keymap-popup my-settings-map))))
#+end_src
* Annotating existing keymaps
:PROPERTIES:
:CUSTOM_ID: annotate
:END:
=keymap-popup-annotate= attaches descriptions to a keymap you don't
own (like =dired-mode-map=) without rebinding its keys. Keys are
resolved at popup time via =where-is-internal=, so the popup tracks
the user's current bindings.
#+begin_src emacs-lisp
(keymap-popup-annotate dired-mode-map
:popup-key "?"
:persistent t
:description (lambda ()
(format "Dired: %s" (abbreviate-file-name default-directory)))
:group "File"
dired-find-file "Open"
dired-do-copy "Copy"
dired-do-rename "Rename"
dired-do-delete "Delete"
:group "Navigate"
dired-up-directory "Up"
dired-previous-line "Prev"
dired-next-line "Next"
:group "More"
"M" ("Mark operations" :keymap my-dired-mark-map))
#+end_src
Entries are =COMMAND-SYMBOL DESCRIPTION= (the key comes from the
user's binding). String-key entries are allowed too -- that's how
sub-menus attach to an annotated keymap.
** Attaching descriptions built from data
Both macros take bindings written literally in source. When the
menu itself is computed at runtime -- an anonymous keymap, entries
generated from a list -- use the function =keymap-popup-attach=:
#+begin_src emacs-lisp
(defun my-project-popup ()
"Pick a recent project from a popup."
(interactive)
(let* ((projects (seq-take (project-known-project-roots) 9))
(map (make-sparse-keymap))
(bindings
(cl-loop for root in projects
for key from ?1
for cmd = (let ((r root))
(lambda () (interactive)
(project-switch-project r)))
do (keymap-set map (char-to-string key) cmd)
append (list (char-to-string key)
(list (abbreviate-file-name root) cmd)))))
(keymap-popup (keymap-popup-attach
map (append '(:group "Projects") bindings)))))
#+end_src
Signature:
- =(keymap-popup-attach KEYMAP BINDINGS &rest OPTS)=
BINDINGS is an evaluated list in the same shape as
=keymap-popup-annotate='s body; commands and predicates are actual
objects rather than forms. OPTS accepts =:exit-key=,
=:description=, and =:persistent=. Reattaching replaces prior
descriptions and options, so omitted options return to their
defaults. Unlike the macros, no keys are bound and no commands are
defined -- keyed entries should already be bound in KEYMAP. Returns
KEYMAP.
* Customization
:PROPERTIES:
:CUSTOM_ID: customization
:END:
** User options
- =keymap-popup-backend= -- display function; built-ins are
=keymap-popup-backend-side-window= (default) and
=keymap-popup-backend-child-frame=.
- =keymap-popup-display-action= -- =display-buffer= action for the
side-window backend.
- =keymap-popup-buffer-parameters= -- buffer-local parameters applied
to the popup buffer.
- =keymap-popup-child-frame-parameters= -- frame parameters for the
child-frame backend.
- =keymap-popup-persistent= -- global default for =:persistent=.
- =keymap-popup-default-popup-key= -- default =:popup-key= (=h=).
- =keymap-popup-default-exit-key= -- default =:exit-key= (=q=).
** Faces
- =keymap-popup-key= -- key string (inherits =help-key-binding=).
- =keymap-popup-group-header= -- group header.
- =keymap-popup-value= -- =[on]= / =[off]= and inline values.
- =keymap-popup-submenu= -- sub-menu entries.
- =keymap-popup-inapt= -- disabled entries (inherits =shadow=).
* When to use this vs =transient=
:PROPERTIES:
:CUSTOM_ID: vs-transient
:END:
=transient= is its own abstraction: a class hierarchy built on
EIEIO, with prefix/suffix/infix objects and a custom dispatch loop.
The menu is not an Emacs keymap. It fits codebases that already
lean on EIEIO and benefit from typed, extensible class machinery
(magit being the canonical example).
=keymap-popup= is just a =defvar-keymap= plus metadata, displayed via
the built-in =set-transient-map= primitive (which predates the
=transient= package by years and is unrelated to it, despite the
naming collision). Use it when you want a real keymap that also knows
how to draw itself: bindings show up in =where-is= and
=describe-key=, and the popup does not block =M-x=. There is no
class hierarchy to learn, and state lives wherever you choose to
put it.
* Contributing
:PROPERTIES:
:CUSTOM_ID: contributing
:END:
Source is a single file, =keymap-popup.el=, with tests in
=tests/keymap-popup-tests.el=. Run them with:
#+begin_src sh
emacs --batch -l ert -l keymap-popup.el \
-l tests/keymap-popup-tests.el \
-f ert-run-tests-batch-and-exit
#+end_src
emacs-keymap-popup-0.4.0/flake.lock 0000664 0000000 0000000 00000001067 15225053467 0017201 0 ustar 00root root 0000000 0000000 {
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1783776592,
"narHash": "sha256-UgCQzxeWI75XM8G+hPrPh+MKzEPjG3SpAj7dtqSbksA=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "e7a3ca8092b61ff85b6a45bf863ea2b2d6a661b3",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
emacs-keymap-popup-0.4.0/flake.nix 0000664 0000000 0000000 00000006667 15225053467 0017062 0 ustar 00root root 0000000 0000000 {
description = "Described keymaps with popup help";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
outputs = { nixpkgs, ... }:
let
systems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
forAllSystems = nixpkgs.lib.genAttrs systems;
mkProject = system:
let
pkgs = import nixpkgs { inherit system; };
lib = pkgs.lib;
emacs = pkgs.emacs30 or pkgs.emacs29 or pkgs.emacs;
emacsPackages = pkgs.emacsPackagesFor emacs;
versionLine = lib.findFirst
(line: lib.hasPrefix ";; Version: " line)
(throw "keymap-popup.el has no Version header")
(lib.splitString "\n" (builtins.readFile ./keymap-popup.el));
version = lib.removePrefix ";; Version: " versionLine;
source = lib.cleanSourceWith {
src = ./.;
filter = path: type:
let
name = baseNameOf path;
in
lib.cleanSourceFilter path type
&& !(builtins.elem name [ ".direnv" ".test-results" "refs" "result" ]
|| lib.hasSuffix ".elc" name
|| lib.hasSuffix ".info" name
|| lib.hasSuffix ".texi" name
|| lib.hasSuffix "~" name);
};
emacsWithPackages = emacsPackages.emacsWithPackages (epkgs: [
epkgs.package-lint
]);
package = emacsPackages.trivialBuild {
pname = "keymap-popup";
inherit version;
src = source;
packageRequires = [ ];
};
check = pkgs.stdenvNoCC.mkDerivation {
pname = "keymap-popup-checks";
inherit version;
src = source;
nativeBuildInputs = [
emacsWithPackages
pkgs.gnumake
pkgs.texinfo
];
dontConfigure = true;
buildPhase = ''
runHook preBuild
export HOME="$TMPDIR/home"
export XDG_CACHE_HOME="$TMPDIR/cache"
export XDG_CONFIG_HOME="$TMPDIR/config"
export XDG_DATA_HOME="$TMPDIR/share"
export XDG_STATE_HOME="$TMPDIR/state"
mkdir -p "$HOME" "$XDG_CACHE_HOME" "$XDG_CONFIG_HOME" \
"$XDG_DATA_HOME" "$XDG_STATE_HOME"
make USE_NIX=0 EMACS_CMD=emacs do-dev do-doc
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out
touch $out/tests-passed
runHook postInstall
'';
};
in
{
inherit check emacsWithPackages package pkgs;
};
in
{
packages = forAllSystems (system:
let
project = mkProject system;
in
{
default = project.package;
});
checks = forAllSystems (system:
let
project = mkProject system;
in
{
default = project.check;
package = project.package;
});
devShells = forAllSystems (system:
let
project = mkProject system;
in
{
default = project.pkgs.mkShellNoCC {
packages = [
project.emacsWithPackages
project.pkgs.gnumake
project.pkgs.texinfo
];
};
});
};
}
emacs-keymap-popup-0.4.0/keymap-popup.el 0000664 0000000 0000000 00000177136 15225053467 0020231 0 ustar 00root root 0000000 0000000 ;;; keymap-popup.el --- Described keymaps with popup help -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Free Software Foundation, Inc.
;; Author: Thanos Apollo
;; Version: 0.4.0
;; Package-Requires: ((emacs "29.1"))
;; Keywords: convenience
;; URL: https://codeberg.org/thanosapollo/emacs-keymap-popup
;; This program 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.
;; This program 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 this program. If not, see .
;;; Commentary:
;; Two macros: `keymap-popup-define' produces a real `defvar-keymap'
;; with embedded descriptions; `keymap-popup-annotate' adds popup
;; descriptions to an existing keymap. `keymap-popup' displays
;; either as an interactive menu. One definition, two uses:
;; direct key dispatch and popup help.
;;
;; The popup is a pure renderer: it reads state (buffer-locals, dynamic
;; descriptions) but owns none. Commands mutate state in the user's
;; buffer; the popup just re-reads it on the next refresh.
;;; Code:
(require 'cl-lib)
(require 'seq)
(require 'subr-x)
(defgroup keymap-popup nil
"Described keymaps with popup help."
:group 'convenience)
(defcustom keymap-popup-display-action
'(display-buffer-in-side-window (side . bottom))
"Display action for the popup buffer.
Only used by `keymap-popup-backend-side-window'.
Common values:
(display-buffer-in-side-window (side . bottom)) - frame-wide
(display-buffer-below-selected) - current window only"
:type display-buffer--action-custom-type
:group 'keymap-popup)
(defcustom keymap-popup-backend #'keymap-popup-backend-side-window
"Function returning a display backend plist (:show :fit :hide).
Each backend function receives a single buffer argument.
:show displays the buffer, :fit refits after content changes,
:hide removes the display and cleans up."
:type '(choice (function-item :tag "Side window" keymap-popup-backend-side-window)
(function-item :tag "Child frame" keymap-popup-backend-child-frame)
(function :tag "Custom backend"))
:group 'keymap-popup)
(defcustom keymap-popup-child-frame-parameters
'((no-accept-focus . t)
(no-focus-on-map . t)
(min-width . t)
(min-height . t)
(border-width . 0)
(child-frame-border-width . 1)
(left-fringe . 0)
(right-fringe . 0)
(vertical-scroll-bars . nil)
(horizontal-scroll-bars . nil)
(menu-bar-lines . 0)
(tool-bar-lines . 0)
(tab-bar-lines . 0)
(no-other-frame . t)
(no-other-window . t)
(no-delete-other-windows . t)
(unsplittable . t)
(undecorated . t)
(cursor-type . nil)
(no-special-glyphs . t)
(desktop-dont-save . t))
"Frame parameters for the child-frame backend.
These are merged with runtime parameters (parent-frame, minibuffer,
visibility) when creating the child frame."
:type '(alist :key-type symbol :value-type sexp)
:group 'keymap-popup)
(defcustom keymap-popup-buffer-parameters
'((buffer-read-only . t)
(cursor-type . nil)
(mode-line-format
. (" "
(:eval (and keymap-popup--active-exit-key
(propertize (format " %s " keymap-popup--active-exit-key)
'face 'keymap-popup-key)))
" "
(:eval (or keymap-popup--resolved-docstring ""))))
(header-line-format . nil)
(tab-line-format . nil)
(left-margin-width . 1)
(right-margin-width . 1))
"Buffer-local parameters applied to the popup buffer.
Each entry is (VARIABLE . VALUE). Users can remove entries to
keep defaults or change values to customize the popup appearance."
:type '(alist :key-type symbol :value-type sexp)
:group 'keymap-popup)
(defcustom keymap-popup-persistent nil
"When non-nil, the popup stays open after every key press.
All suffix commands execute and refresh the popup in place.
Only the exit key and \\`C-g' dismiss it.
Can also be set per-keymap via the `:persistent' keyword in
`keymap-popup-define' or `keymap-popup-annotate'."
:type 'boolean
:group 'keymap-popup)
(defcustom keymap-popup-default-popup-key "h"
"Default key to open the popup in keymaps defined with `keymap-popup-define'.
Applied by `keymap-popup-define' when :popup-key is not specified.
Read when the definition is loaded, so customize it before loading
packages that define popups. Not applied by `keymap-popup-annotate'
\(must be given explicitly)."
:type 'key
:group 'keymap-popup)
(defcustom keymap-popup-default-exit-key "q"
"Default key to dismiss the popup.
Used as the fallback when the popup is shown and the keymap stores
no explicit :exit-key, for both `keymap-popup-define' and
`keymap-popup-annotate'."
:type 'key
:group 'keymap-popup)
(defconst keymap-popup--buffer-name "*keymap-popup*"
"Name of the singleton buffer used to display the popup.")
;;; Faces
(defface keymap-popup-key
'((t :inherit help-key-binding))
"Face for key bindings in the popup.")
(defface keymap-popup-group-header
'((t :weight bold))
"Face for group headers in the popup.")
(defface keymap-popup-value
'((t :inherit font-lock-string-face :weight bold))
"Face for switch values in the popup.")
(defface keymap-popup-submenu
'((t :inherit font-lock-type-face))
"Face for sub-menu entries in the popup.")
(defface keymap-popup-inapt
'((t :inherit shadow))
"Face for inapt (disabled) entries in the popup.")
;;; Keymap metadata
(defun keymap-popup--meta (keymap prop)
"Get popup metadata PROP from KEYMAP via pseudo-key lookup."
(let ((val (lookup-key keymap (vector 'keymap-popup prop))))
;; lookup-key returns an integer when the vector is a prefix of a
;; longer binding rather than an exact match. Filter that out.
(and (not (numberp val)) val)))
;; Values are stored via define-key, so t cannot be used as a value
;; (it means "default binding"). Use symbols like 'yes instead.
(gv-define-setter keymap-popup--meta (val keymap prop)
`(define-key ,keymap (vector 'keymap-popup ,prop) ,val))
(defun keymap-popup--attach-meta (keymap rows &rest opts)
"Attach popup descriptions ROWS and metadata OPTS to KEYMAP.
OPTS is a plist accepting :exit-key, :description, and
:persistent; other keys are ignored. Reattaching replaces all
previous metadata, so omitted options return to their defaults.
:persistent is stored as the symbol `yes' because metadata lives
in `define-key' bindings, where t means \"default binding\".
Returns KEYMAP."
(setf (keymap-popup--meta keymap 'descriptions) rows
(keymap-popup--meta keymap 'exit-key) (plist-get opts :exit-key)
(keymap-popup--meta keymap 'description) (plist-get opts :description)
(keymap-popup--meta keymap 'persistent)
(and (plist-get opts :persistent) 'yes))
keymap)
;;; Parsers
(defun keymap-popup--extract-props (plist)
"Extract known properties from PLIST.
Recognized keys are :if, :inapt-if, :stay-open, and :c-u.
:stay-open may be written as a bare boolean flag."
(named-let extract ((rest plist))
(cond
((null rest) nil)
((and (eq (car rest) :stay-open)
(or (null (cdr rest)) (keywordp (cadr rest))))
(cons :stay-open (cons t (extract (cdr rest)))))
((memq (car rest) '(:if :inapt-if :stay-open :c-u))
(cons (car rest) (cons (cadr rest) (extract (cddr rest)))))
(t (extract (cddr rest))))))
(defun keymap-popup--parse-entry (key spec)
"Parse binding SPEC for KEY into a plist.
KEY is a key string for normal entries, or a command symbol for
annotated entries. SPEC is (DESCRIPTION COMMAND-OR-TYPE &rest PROPS)
for key-based entries, or (DESCRIPTION &rest PROPS) for annotated ones."
(if (symbolp key)
;; Annotated entry: key is a command symbol, spec is (DESC . PROPS),
;; any atom, or a bare lambda/function form.
(let* ((spec (cond ((not (consp spec)) (list spec))
((memq (car-safe spec) '(lambda function)) (list spec))
(t spec)))
(description (car spec))
(props (cdr spec)))
`(:key nil :description ,description :type suffix
:command ,key
,@(keymap-popup--extract-props props)))
;; Normal entry: key is a string
(let* ((description (car spec))
(second (cadr spec))
(rest (cddr spec)))
(pcase second
(:switch
`(:key ,key :description ,description :type switch
:variable ,(car rest)
,@(keymap-popup--extract-props (cdr rest))))
(:keymap
`(:key ,key :description ,description :type keymap
:target ,(car rest)
,@(keymap-popup--extract-props (cdr rest))))
(_
`(:key ,key :description ,description :type suffix
:command ,second
,@(keymap-popup--extract-props rest)))))))
(defun keymap-popup--split-groups (bindings)
"Split BINDINGS at :group and :row keywords.
Returns a list of rows, each row a list of (NAME . FLAT-ENTRIES) chunks.
`:group' starts a new group within the current row.
`:row' starts a new row."
(named-let split ((rest bindings) (name nil) (entries nil)
(groups nil) (rows nil))
(let ((flushed (if entries
(cons (cons name (reverse entries)) groups)
groups)))
(cond
((null rest)
(reverse (if flushed (cons (reverse flushed) rows) rows)))
((eq (car rest) :row)
(split (cdr rest) nil nil nil
(if flushed (cons (reverse flushed) rows) rows)))
((eq (car rest) :group)
(split (cddr rest) (cadr rest) nil flushed rows))
(t
(split (cddr rest) name
(cons (cons (car rest) (cadr rest)) entries)
groups rows))))))
(defun keymap-popup--parse-group-name (raw)
"Parse RAW group name into (NAME . PROPS).
RAW is a string, a lambda, or a list (NAME :if PRED :inapt-if PRED).
A list whose car is not `lambda' is treated as a name with properties."
(if (and (consp raw) (not (eq (car raw) 'lambda)))
(cons (car raw) (keymap-popup--extract-props (cdr raw)))
(cons raw nil)))
(defun keymap-popup--parse-chunk (chunk)
"Parse CHUNK of (NAME . ((KEY . SPEC) ...)) into a group plist."
(let* ((name-props (keymap-popup--parse-group-name (car chunk)))
(name (car name-props))
(group-props (cdr name-props))
(entries (cl-loop for (k . v) in (cdr chunk)
collect (keymap-popup--parse-entry k v))))
`(:name ,name :entries ,entries ,@group-props)))
(defun keymap-popup--parse-bindings (bindings)
"Parse BINDINGS into a list of rows.
Each row is a list of group plists with :name and :entries."
(mapcar (lambda (row) (mapcar #'keymap-popup--parse-chunk row))
(keymap-popup--split-groups bindings)))
(defun keymap-popup--if-allows-p (plist)
"Return non-nil when PLIST has no :if or its :if predicate is non-nil."
(let ((pred (plist-get plist :if)))
(or (null pred) (funcall pred))))
(defun keymap-popup--inapt-active-p (plist)
"Return non-nil when PLIST's :inapt-if predicate is currently active."
(and-let* ((pred (plist-get plist :inapt-if)))
(funcall pred)))
(defun keymap-popup--combine-preds (a b)
"AND-combine zero-arg predicates A and B. Either may be nil."
(cond ((null a) b)
((null b) a)
(t (lambda () (and (funcall a) (funcall b))))))
(defun keymap-popup--merge-group-preds (entry group)
"Return ENTRY with GROUP's :if and :inapt-if AND-merged into it.
The entry is returned unchanged when GROUP has no predicates."
(let ((g-if (plist-get group :if))
(g-inapt (plist-get group :inapt-if)))
(if (not (or g-if g-inapt))
entry
(let* ((merged-if (keymap-popup--combine-preds
g-if (plist-get entry :if)))
(merged-inapt (keymap-popup--combine-preds
g-inapt (plist-get entry :inapt-if)))
(r (copy-sequence entry))
(r (if merged-if (plist-put r :if merged-if) r))
(r (if merged-inapt (plist-put r :inapt-if merged-inapt) r)))
r))))
(defun keymap-popup--group-entries-merged (group)
"Return GROUP's entries with the group's :if/:inapt-if merged in."
(mapcar (lambda (e) (keymap-popup--merge-group-preds e group))
(plist-get group :entries)))
(defun keymap-popup--flatten-with-groups (rows)
"Flatten ROWS into a list of entries with group :if/:inapt-if merged in."
(mapcan (lambda (row) (mapcan #'keymap-popup--group-entries-merged row))
rows))
;;; Generated symbol names
(defun keymap-popup--toggle-name (map-name var)
"Return the symbol naming the toggle command for VAR in MAP-NAME."
(intern (format "%s--toggle-%s" map-name var)))
(defun keymap-popup--enter-name (map-name target)
"Return the symbol naming the sub-menu enterer for TARGET in MAP-NAME."
(intern (format "%s--enter-%s" map-name target)))
(defun keymap-popup--launcher-name (map-name)
"Return the symbol naming the popup launcher for MAP-NAME."
(intern (concat (symbol-name map-name) "-popup")))
(defun keymap-popup--entry-command (map-name entry)
"Return the command to bind in MAP-NAME's keymap for ENTRY.
Always a symbol; the corresponding `defun' is emitted by
`keymap-popup-define'."
(pcase-exhaustive (plist-get entry :type)
('suffix (plist-get entry :command))
('switch (keymap-popup--toggle-name map-name (plist-get entry :variable)))
('keymap (keymap-popup--enter-name map-name (plist-get entry :target)))))
;;; Macro helpers
(defun keymap-popup--make-if-filter (pred)
"Return a `menu-item' :filter exposing the binding only when PRED is non-nil."
(lambda (b) (and (funcall pred) b)))
(defun keymap-popup--wrap-binding-form (cmd-form if-pred)
"Wrap CMD-FORM with a `menu-item' :filter when IF-PRED is set.
IF-PRED is a form that evaluates to a zero-arg predicate; a nil
filter result makes the key act as unbound. `:inapt-if' is not a
keymap concern -- it is enforced by the popup wrapper at keypress
time. The filter closure is built by a helper in this file so it
remains lexical regardless of the caller."
(if if-pred
`(list 'menu-item "" ,cmd-form :filter
(keymap-popup--make-if-filter ,if-pred))
cmd-form))
(defun keymap-popup--build-keymap-pairs (map-name entries)
"Build flat key/command list for `defvar-keymap' from ENTRIES.
MAP-NAME is used to derive generated command names. Entries with
:if expand to a `menu-item' form with :filter."
(cl-loop for entry in entries
for cmd = (keymap-popup--entry-command map-name entry)
for cmd-form = (if (symbolp cmd) `#',cmd cmd)
append (list (plist-get entry :key)
(keymap-popup--wrap-binding-form
cmd-form (plist-get entry :if)))))
(defun keymap-popup--build-entry-form (entry &optional map-name)
"Build a `list' form for a single ENTRY.
When MAP-NAME is non-nil, switch and keymap entries also store the
generated toggle/enter command as :command, so every entry is
command-addressable (annotate entries have no generated commands,
so their builders pass no MAP-NAME)."
(let* ((type (plist-get entry :type))
(generated (and map-name
`(:command #',(keymap-popup--entry-command
map-name entry))))
(type-props (pcase-exhaustive type
('suffix (let ((cmd (plist-get entry :command)))
`(:command ,(if (symbolp cmd) `#',cmd cmd)
,@(and (plist-get entry :stay-open)
'(:stay-open t)))))
('keymap `(:target ,(plist-get entry :target)
,@generated))
('switch `(:variable ',(plist-get entry :variable)
,@generated))))
(if-pred (plist-get entry :if))
(inapt-if (plist-get entry :inapt-if)))
`(list :key ,(plist-get entry :key)
:description ,(plist-get entry :description)
:type ',type
,@type-props
,@(and if-pred (list :if if-pred))
,@(and inapt-if (list :inapt-if inapt-if))
,@(and-let* ((c-u (plist-get entry :c-u)))
(list :c-u c-u)))))
(defun keymap-popup--build-group-form (group &optional map-name)
"Build a `list' form for one GROUP plist.
MAP-NAME is passed to `keymap-popup--build-entry-form'."
(let ((if-pred (plist-get group :if))
(inapt-if (plist-get group :inapt-if)))
`(list :name ,(plist-get group :name)
:entries (list ,@(mapcar (lambda (entry)
(keymap-popup--build-entry-form
entry map-name))
(plist-get group :entries)))
,@(and if-pred (list :if if-pred))
,@(and inapt-if (list :inapt-if inapt-if)))))
(defun keymap-popup--build-descriptions-form (rows &optional map-name)
"Build a `list' form that constructs descriptions at load time.
ROWS is a list of rows, each row a list of groups. Uses `list'
calls so lambdas in :if/:inapt-if/:description get compiled.
MAP-NAME is passed down to the entry forms."
`(list ,@(mapcar (lambda (row)
`(list ,@(mapcar (lambda (group)
(keymap-popup--build-group-form
group map-name))
row)))
rows)))
(defun keymap-popup--build-switch-forms (map-name entries)
"Build `defvar-local' + toggle `defun' forms for switch ENTRIES in MAP-NAME."
(mapcan (lambda (e)
(let* ((var (plist-get e :variable))
(toggle (keymap-popup--toggle-name map-name var)))
`((defvar-local ,var nil
,(format "Buffer-local switch state.\nToggled by `%s'."
toggle))
(defun ,toggle ()
,(format "Toggle the buffer-local switch.\nSets `%s' in the current buffer." var)
(interactive)
(setq ,var (not ,var))
(message "%s: %s" ',var (if ,var "on" "off"))))))
entries))
(defun keymap-popup--build-enter-forms (map-name entries)
"Build sub-menu enter defun forms for keymap ENTRIES in MAP-NAME."
(mapcar (lambda (e)
(let* ((target (plist-get e :target))
(enter (keymap-popup--enter-name map-name target)))
`(defun ,enter ()
,(format "Show popup for `%s' (sub-menu of `%s')."
target map-name)
(interactive)
(keymap-popup ,target))))
entries))
(defun keymap-popup--build-launcher-form (map-name launcher)
"Build the launcher defun form named LAUNCHER for MAP-NAME."
`(defun ,launcher ()
,(format "Show popup help for `%s'." map-name)
(interactive)
(keymap-popup ,map-name)))
(defun keymap-popup--build-declaration-forms (map-name parent entries)
"Build bare `defvar' forms for MAP-NAME, PARENT, and targets in ENTRIES."
(mapcar (lambda (symbol) `(defvar ,symbol))
(seq-uniq
(append (list map-name)
(and parent (symbolp parent) (list parent))
(cl-loop for entry in entries
for target = (plist-get entry :target)
when (and (eq (plist-get entry :type) 'keymap)
target
(symbolp target))
collect target)))))
(defun keymap-popup--build-attach-form (map-name rows-form exit-key
description persistent)
"Build the `keymap-popup--attach-meta' call form for MAP-NAME.
ROWS-FORM constructs the descriptions at load time. Each of
EXIT-KEY, DESCRIPTION, PERSISTENT is passed only when non-nil."
`(keymap-popup--attach-meta ,map-name ,rows-form
,@(and exit-key `(:exit-key ,exit-key))
,@(and description `(:description ,description))
,@(and persistent '(:persistent t))))
;;; Macro
(defun keymap-popup--consume-keywords (rest keywords)
"Consume KEYWORDS from REST in any order.
Returns (VALUES . REMAINING) where VALUES is a list of extracted
values (nil for absent keywords), ordered as KEYWORDS."
(named-let collect ((rest rest) (alist nil))
(if (and rest (memq (car rest) keywords))
(collect (cddr rest)
(cons (cons (car rest) (cadr rest)) alist))
(cons (mapcar (lambda (kw) (alist-get kw alist)) keywords)
rest))))
(defun keymap-popup--extract-macro-opts (body)
"Extract macro options from BODY.
Returns (DOCSTRING POPUP-KEY EXIT-KEY PARENT DESCRIPTION PERSISTENT BINDINGS).
Unspecified keywords yield nil."
(let* ((docstring (and (stringp (car body))
(or (null (cadr body))
(not (listp (cadr body))))
(car body)))
(rest (if docstring (cdr body) body))
(result (keymap-popup--consume-keywords
rest '(:popup-key :exit-key :parent :description :persistent))))
(append (list docstring) (car result) (list (cdr result)))))
;;;###autoload
(defmacro keymap-popup-define (name &rest body)
"Define NAME as a keymap with embedded descriptions.
BODY is an optional docstring, optional :popup-key KEY (default
per `keymap-popup-default-popup-key'), optional :exit-key KEY
\(default per `keymap-popup-default-exit-key'), optional :parent
KEYMAP, optional :description STRING-OR-FUNCTION, optional
:persistent BOOL, followed by :group keywords and KEY (DESC ...)
pairs."
(declare (indent 1))
(pcase-let* ((`(,docstring ,popup-key ,exit-key ,parent ,description
,persistent ,bindings)
(keymap-popup--extract-macro-opts body))
(rows (keymap-popup--parse-bindings bindings))
(all-entries (keymap-popup--flatten-with-groups rows))
(switch-entries (cl-loop for entry in all-entries
when (eq (plist-get entry :type) 'switch)
collect entry))
(keymap-entries (cl-loop for entry in all-entries
when (eq (plist-get entry :type) 'keymap)
collect entry))
(keymap-pairs (keymap-popup--build-keymap-pairs name all-entries))
(launcher (keymap-popup--launcher-name name)))
`(progn
,@(keymap-popup--build-declaration-forms name parent all-entries)
,@(keymap-popup--build-switch-forms name switch-entries)
,@(keymap-popup--build-enter-forms name keymap-entries)
,(keymap-popup--build-launcher-form name launcher)
(defvar-keymap ,name
,@(and docstring (list :doc docstring))
,@(and parent (list :parent parent))
,@keymap-pairs)
;; Bound outside `defvar-keymap' so the default key is read at
;; load time, not baked in when the macro is byte-compiled.
(keymap-set ,name ,(or popup-key 'keymap-popup-default-popup-key)
#',launcher)
,(keymap-popup--build-attach-form
name (keymap-popup--build-descriptions-form rows name)
exit-key description persistent))))
;;;###autoload
(defmacro keymap-popup-annotate (keymap &rest body)
"Annotate existing KEYMAP with popup descriptions.
BODY is optional :popup-key KEY, optional :exit-key KEY, optional
:description STRING-OR-FUNCTION, optional :persistent BOOL,
followed by :group keywords and COMMAND-SYMBOL DESCRIPTION pairs.
COMMAND-SYMBOL is a function symbol already bound in the keymap.
DESCRIPTION is a string or (STRING &rest PROPS).
Unlike `keymap-popup-define', no defaults are applied for
:popup-key or :exit-key. Only explicitly provided values take
effect. When :exit-key is omitted, the popup falls back to
`keymap-popup-default-exit-key' at display time.
Keys are resolved dynamically via `where-is-internal' at display
time, so the popup always reflects the user's current bindings."
(declare (indent 1))
(pcase-let* ((`(,_docstring ,popup-key ,exit-key ,_parent ,description
,persistent ,bindings)
(keymap-popup--extract-macro-opts body))
(rows (keymap-popup--parse-bindings bindings))
(launcher (and popup-key (symbolp keymap)
(keymap-popup--launcher-name keymap))))
`(progn
,(keymap-popup--build-attach-form
keymap (keymap-popup--build-descriptions-form rows)
exit-key description persistent)
,@(cond
(launcher
`(,(keymap-popup--build-launcher-form keymap launcher)
(keymap-set ,keymap ,popup-key #',launcher)))
(popup-key
`((keymap-set ,keymap ,popup-key
(lambda () (interactive) (keymap-popup ,keymap)))))))))
;;; Public API
;;;###autoload
(defun keymap-popup-attach (keymap bindings &rest opts)
"Attach popup descriptions for BINDINGS to KEYMAP at runtime.
BINDINGS is an evaluated list shaped like `keymap-popup-annotate'
BODY: KEY (DESCRIPTION COMMAND . PROPS) or COMMAND-SYMBOL
DESCRIPTION pairs, optionally grouped with :group. Commands and
predicates are actual objects, not forms. OPTS is a plist
accepting :exit-key, :description, and :persistent. Returns
KEYMAP.
Unlike the macros, this attaches descriptions computed from data,
so it suits anonymous keymaps and menus built from runtime lists.
Reattaching replaces prior descriptions and options; omitted
options return to their defaults. It does not bind keys or define
commands; keyed entries should already be bound in KEYMAP."
(apply #'keymap-popup--attach-meta keymap
(keymap-popup--parse-bindings bindings)
opts))
(defun keymap-popup--map-groups (rows fn)
"Apply FN to each group in ROWS, returning the transformed rows.
FN receives a group plist and returns a new group plist."
(mapcar (lambda (row) (mapcar fn row)) rows))
(defun keymap-popup--add-entry-to-rows (rows entry group-name)
"Return ROWS with ENTRY appended to the group named GROUP-NAME.
Falls back to the first group if GROUP-NAME is not found.
If ENTRY's key already appears in ROWS (in any group), the prior
entry is removed first -- matching the replacement semantics of
`keymap-set'."
(let* ((key (plist-get entry :key))
(scrubbed (if key
(keymap-popup--remove-key-from-rows rows key)
rows))
(target (or (cl-loop for row in scrubbed
thereis (cl-loop for g in row
when (equal (plist-get g :name) group-name)
return group-name))
(plist-get (caar scrubbed) :name))))
(keymap-popup--map-groups
scrubbed
(lambda (group)
(if (equal (plist-get group :name) target)
(plist-put (copy-sequence group) :entries
(append (plist-get group :entries) (list entry)))
group)))))
(defun keymap-popup--remove-key-from-rows (rows key)
"Return ROWS with entries matching KEY filtered out."
(keymap-popup--map-groups
rows
(lambda (group)
(plist-put (copy-sequence group) :entries
(cl-remove-if
(lambda (e) (equal (plist-get e :key) key))
(plist-get group :entries))))))
;;;###autoload
(defun keymap-popup-add-entry (keymap key description command &optional group)
"Add KEY binding with DESCRIPTION and COMMAND to KEYMAP.
GROUP is the group name to add to (nil for the first group).
Updates both the keymap and the popup descriptions."
(let ((descs (keymap-popup--meta keymap 'descriptions)))
(or descs (user-error "No descriptions in keymap"))
(keymap-set keymap key command)
(let ((entry (list :key key :description description
:type 'suffix :command command)))
(setf (keymap-popup--meta keymap 'descriptions)
(keymap-popup--add-entry-to-rows descs entry group)))))
;;;###autoload
(defun keymap-popup-remove-entry (keymap key)
"Remove KEY binding from KEYMAP.
Updates both the keymap and the popup descriptions."
(keymap-set keymap key nil)
(setf (keymap-popup--meta keymap 'descriptions)
(keymap-popup--remove-key-from-rows
(keymap-popup--meta keymap 'descriptions) key)))
;;; Renderer
(defconst keymap-popup--max-description-width 40
"Maximum visible width of a resolved description, in columns.
Resolved descriptions longer than this are truncated with an
ellipsis. Authors should keep descriptions short by convention;
this bound exists so dynamic descriptions can't blow out the
column layout.")
(defun keymap-popup--resolve-description (desc)
"Resolve DESC to a display string.
If DESC is a function, call it; otherwise return as-is. Collapse
runs of whitespace into single spaces and truncate to
`keymap-popup--max-description-width'."
(let* ((raw (if (functionp desc) (funcall desc) desc))
(collapsed (and raw (string-clean-whitespace raw))))
(and collapsed
(truncate-string-to-width
collapsed keymap-popup--max-description-width nil nil t))))
(defun keymap-popup--render-entry (entry &optional prefix-mode key-width)
"Render ENTRY into a formatted line, or nil if :if hides it.
When PREFIX-MODE is non-nil, entries with :c-u are highlighted and
their :c-u description is shown; other entries are dimmed.
KEY-WIDTH pads the key column for alignment."
(and (keymap-popup--if-allows-p entry)
(let* ((inapt (keymap-popup--inapt-active-p entry))
(raw-desc (keymap-popup--resolve-description
(plist-get entry :description)))
(type (plist-get entry :type))
(desc (if (eq type 'keymap)
(propertize raw-desc 'face 'keymap-popup-submenu)
raw-desc))
(c-u-desc (plist-get entry :c-u))
(raw-key (plist-get entry :key))
(padded-key (if key-width
(string-pad raw-key key-width)
raw-key))
(key-str (propertize padded-key 'face 'keymap-popup-key))
(value-str (if (eq type 'switch)
(propertize
(if (symbol-value (plist-get entry :variable))
" [on]" " [off]")
'face 'keymap-popup-value)
""))
(c-u-str (and c-u-desc
(propertize (format " (%s)" c-u-desc)
'face (if prefix-mode 'warning 'shadow))))
(line (format " %s %s%s%s" key-str desc value-str
(or c-u-str ""))))
(cond
(inapt (propertize line 'face 'keymap-popup-inapt))
((and prefix-mode (not c-u-desc))
(propertize line 'face 'shadow))
(t line)))))
(defun keymap-popup--render-group-lines (group &optional prefix-mode)
"Render GROUP into a list of lines (strings).
When PREFIX-MODE is non-nil, pass it to entry rendering.
Returns nil if the group is hidden by :if or has no visible entries.
When the group has :inapt-if that returns non-nil, all entries are
rendered with the inapt face."
(and (keymap-popup--if-allows-p group)
(let* ((group-inapt (keymap-popup--inapt-active-p group))
(entries (plist-get group :entries))
(key-width (cl-loop for entry in entries
maximize (length (plist-get entry :key))))
(header (and-let* ((raw-name (plist-get group :name))
(name (keymap-popup--resolve-description raw-name)))
(propertize name 'face (if group-inapt
'keymap-popup-inapt
'keymap-popup-group-header))))
(lines (cl-loop for entry in entries
when (keymap-popup--render-entry
entry prefix-mode key-width)
collect it)))
(and lines
(let ((result (if header (cons header lines) lines)))
(if group-inapt
(mapcar (lambda (line) (propertize line 'face 'keymap-popup-inapt))
result)
result))))))
(defun keymap-popup--column-width (col)
"Return the max visible width of lines in COL."
(cl-loop for line in col
maximize (string-width line)))
(defun keymap-popup--join-columns (columns separator col-widths)
"Join COLUMNS side by side with SEPARATOR between them.
COL-WIDTHS is a list of minimum widths per column position.
Shorter columns are padded with blank lines."
(let* ((max-height (cl-loop for col in columns maximize (length col)))
(padded-cols (cl-mapcar
(lambda (col width)
(let ((padded (mapcar (lambda (line)
(string-pad line width))
col))
(blanks (make-list (- max-height (length col))
(make-string width ?\s))))
(append padded blanks)))
columns col-widths)))
(cl-loop for row from 0 below max-height
collect (string-trim-right
(mapconcat (lambda (col) (nth row col))
padded-cols
separator)))))
(defun keymap-popup--rows-to-columns (rows &optional prefix-mode)
"Render each row of ROWS into its list of column line-lists.
When PREFIX-MODE is non-nil, pass it to group rendering.
Returns a list of ((col-lines ...) ...) per row, filtering empty groups."
(cl-loop for row in rows
collect (cl-loop for group in row
when (keymap-popup--render-group-lines group prefix-mode)
collect it)))
(defun keymap-popup--global-col-widths (rendered-rows)
"Compute max column width per position across all RENDERED-ROWS."
(let ((max-cols (or (cl-loop for cols in rendered-rows
maximize (length cols))
0)))
(cl-loop for i from 0 below max-cols
collect (cl-loop for cols in rendered-rows
when (nth i cols)
maximize (keymap-popup--column-width (nth i cols))))))
(defun keymap-popup--render (rows &optional prefix-mode)
"Render ROWS into a complete popup string.
ROWS is a list of rows, each row a list of groups.
When PREFIX-MODE is non-nil, highlight :c-u entries and dim others.
Column widths are aligned across all rows."
(let* ((rendered-rows (keymap-popup--rows-to-columns rows prefix-mode))
(col-widths (keymap-popup--global-col-widths rendered-rows))
(sections (cl-loop for cols in rendered-rows
when cols
collect (string-join
(keymap-popup--join-columns
cols " " col-widths)
"\n"))))
(concat (string-join sections "\n") "\n")))
;;; Popup state
(defvar-local keymap-popup--source-buffer nil
"The buffer from which the popup was invoked.
Switch variables are buffer-local there, so rendering must read
`symbol-value' in that buffer's context.")
(defvar-local keymap-popup--active-keymap nil
"The currently displayed keymap in the popup.")
(defvar-local keymap-popup--active-descriptions nil
"Descriptions for the currently active keymap.")
(defvar-local keymap-popup--active-docstring nil
"Docstring for the currently active keymap.")
(defvar-local keymap-popup--stack nil
"Stack of parent state plists for sub-menu navigation.")
(defvar-local keymap-popup--prefix-mode nil
"Non-nil when \\`C-u' prefix mode is active.")
(defvar-local keymap-popup--reentering nil
"Non-nil when a sub-menu just popped, preventing cascading exit.")
(defvar-local keymap-popup--active-exit-key nil
"The exit key for the currently active popup.")
(defvar-local keymap-popup--resolved-docstring nil
"Resolved docstring string for mode-line display.")
(defvar-local keymap-popup--persistent nil
"Non-nil when this popup instance is in persistent mode.")
(defvar-local keymap-popup--wrapper-map nil
"The active wrapper keymap on `overriding-terminal-local-map'.")
(defvar-local keymap-popup--exit-function nil
"Function that deactivates the active transient map.")
(defvar-local keymap-popup--persistent-hook nil
"Self-removing post-command hook owned by this popup session.")
(defvar-local keymap-popup--display-backend nil
"The active display backend plist (:show :fit :hide).")
(defun keymap-popup--snapshot-state ()
"Return the current popup navigation state as a plist."
(list :keymap keymap-popup--active-keymap
:descriptions keymap-popup--active-descriptions
:docstring keymap-popup--active-docstring
:exit-key keymap-popup--active-exit-key
:wrapper-map keymap-popup--wrapper-map
:exit-function keymap-popup--exit-function))
(defun keymap-popup--restore-state (state)
"Restore popup navigation STATE in the current buffer."
(setq-local keymap-popup--active-keymap (plist-get state :keymap)
keymap-popup--active-descriptions (plist-get state :descriptions)
keymap-popup--active-docstring (plist-get state :docstring)
keymap-popup--active-exit-key (plist-get state :exit-key)
keymap-popup--wrapper-map (plist-get state :wrapper-map)
keymap-popup--exit-function (plist-get state :exit-function)
keymap-popup--reentering t
keymap-popup--prefix-mode nil))
;;; Popup display
(defun keymap-popup--dedupe-descriptions (descriptions)
"Return DESCRIPTIONS with duplicate-key entries removed.
The first occurrence of each key wins; later duplicates are dropped.
Entries with nil :key (annotated entries before key resolution)
are preserved as-is. Groups and rows that end up empty are removed."
(let ((seen (make-hash-table :test 'equal)))
(cl-labels ((keep-entry (e)
(let ((k (plist-get e :key)))
(cond ((null k) e)
((gethash k seen) nil)
(t (puthash k t seen) e))))
(keep-group (g)
(and-let* ((es (seq-keep #'keep-entry (plist-get g :entries))))
(plist-put (copy-sequence g) :entries es)))
(keep-row (r)
(seq-keep #'keep-group r)))
(seq-keep #'keep-row descriptions))))
(defun keymap-popup--collect-descriptions (keymap)
"Collect descriptions from KEYMAP and all its parent keymaps.
Walks the native parent chain via `keymap-parent'. When a key is
bound in both child and parent, the child's entry wins and the
parent's is dropped, matching the dispatch behavior of inherited
keymaps."
(keymap-popup--dedupe-descriptions
(cl-loop for map = keymap then (keymap-parent map)
while map
when (keymap-popup--meta map 'descriptions)
append it)))
(defun keymap-popup--find-entry-by-key (descriptions key-str)
"Find the entry matching KEY-STR in DESCRIPTIONS.
DESCRIPTIONS is a list of rows, each row a list of groups.
Returns the entry plist, or nil."
(cl-loop for row in descriptions
thereis (cl-loop for group in row
thereis (cl-loop for entry in (plist-get group :entries)
when (equal (plist-get entry :key) key-str)
return entry))))
(defun keymap-popup--keep-popup-p (descriptions key-str)
"Return non-nil if KEY-STR should keep the popup open in DESCRIPTIONS.
True for switches, stay-open suffixes, and :keymap entries with a
target. Inapt-key handling is folded into the keep-pred via
`keymap-popup--inapt-key-p'."
(and-let* ((entry (keymap-popup--find-entry-by-key descriptions key-str)))
(or (eq (plist-get entry :type) 'switch)
(plist-get entry :stay-open)
(and (eq (plist-get entry :type) 'keymap)
(plist-get entry :target)))))
(defun keymap-popup--inapt-key-p (buf key-str)
"Return non-nil when KEY-STR is currently inapt in BUF's popup.
Checks both the entry's own :inapt-if and its containing group's;
group predicates are not merged into the descriptions tree.
Returns nil when BUF is dead (the popup already closed)."
(and (buffer-live-p buf)
(cl-loop
for row in (buffer-local-value 'keymap-popup--active-descriptions buf)
thereis (cl-loop
for group in row
thereis (cl-loop
for entry in (plist-get group :entries)
when (equal (plist-get entry :key) key-str)
return (or (keymap-popup--inapt-active-p entry)
(keymap-popup--inapt-active-p group)))))))
(defun keymap-popup--refresh-buffer (buf descriptions &optional prefix-mode)
"Re-render popup BUF with DESCRIPTIONS, refit via backend.
PREFIX-MODE toggles prefix argument highlighting."
(let ((content (keymap-popup--render descriptions prefix-mode)))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(insert content)
(goto-char (point-min))))
(when-let* ((fit (plist-get (buffer-local-value 'keymap-popup--display-backend buf)
:fit)))
(funcall fit buf))))
(defun keymap-popup--refresh (buf)
"Re-render popup BUF from its buffer-local state.
Renders in the source buffer's context so `symbol-value' for
switch variables sees the user's buffer-local values.
Resolves the docstring for mode-line display."
(when (buffer-live-p buf)
(let ((source (buffer-local-value 'keymap-popup--source-buffer buf))
(descs (buffer-local-value 'keymap-popup--active-descriptions buf))
(doc (buffer-local-value 'keymap-popup--active-docstring buf))
(prefix (buffer-local-value 'keymap-popup--prefix-mode buf)))
(with-current-buffer (if (buffer-live-p source) source buf)
(let ((resolved (and doc (keymap-popup--resolve-description doc))))
(with-current-buffer buf
(setq-local keymap-popup--resolved-docstring resolved)))
(keymap-popup--refresh-buffer buf descs prefix)))))
(defun keymap-popup--resolve-key (entry keymap)
"Return ENTRY with :key reflecting KEYMAP's current bindings.
An entry keeps its stored :key while that key still dispatches to
the entry's :command. When the command has been rebound,
`where-is-internal' supplies the current key; when it finds no
binding, the stored key is kept (this covers lambda commands and
entries hidden by an `:if' filter). Entries with no stored :key
\(annotated) resolve via `where-is-internal' and are dropped when
unbound. Resolution searches only KEYMAP and its parents, never
the global map."
(let ((cmd (plist-get entry :command))
(stored (plist-get entry :key)))
(cond
((null cmd) entry)
((and stored (eq (keymap-lookup keymap stored) cmd)) entry)
(t (let ((keys (where-is-internal cmd (list keymap) t)))
(cond
(keys (plist-put (copy-sequence entry) :key
(key-description keys)))
(stored entry)))))))
(defun keymap-popup--resolve-descriptions (rows keymap)
"Resolve entry keys in ROWS against KEYMAP's current bindings.
Drops annotated entries whose command has no binding, then removes
duplicates introduced when annotated entries resolve to the same key."
(keymap-popup--dedupe-descriptions
(keymap-popup--map-groups
rows
(lambda (group)
(plist-put (copy-sequence group) :entries
(cl-loop for entry in (plist-get group :entries)
when (keymap-popup--resolve-key entry keymap)
collect it))))))
;;; Display backends
(defun keymap-popup--show-side-window (buf)
"Display BUF in a side window."
(display-buffer buf (append keymap-popup-display-action
'((window-height . fit-window-to-buffer)))))
(defun keymap-popup--fit-side-window (buf)
"Refit the side window displaying BUF."
(when-let* ((win (get-buffer-window buf))
(_ (window-live-p win)))
(fit-window-to-buffer win)))
(defun keymap-popup--hide-side-window (buf)
"Delete the side window displaying BUF."
(when-let* ((win (get-buffer-window buf)))
(delete-window win)))
(defun keymap-popup--show-child-frame (buf)
"Display BUF in a child frame centered on the parent.
Frame parameters are taken from `keymap-popup-child-frame-parameters'."
(let* ((parent (selected-frame))
;; Skip window-system init hooks (DnD, terminal face setup,
;; user hooks); irrelevant for an ephemeral popup frame.
(after-make-frame-functions nil)
(frame (make-frame
`((parent-frame . ,parent)
(minibuffer . ,(minibuffer-window))
(visibility . nil)
,@keymap-popup-child-frame-parameters)))
(win (frame-root-window frame)))
(set-window-buffer win buf)
(set-window-dedicated-p win t)
(fit-frame-to-buffer frame)
(let ((x (/ (- (frame-pixel-width parent) (frame-pixel-width frame)) 2))
(y (/ (- (frame-pixel-height parent) (frame-pixel-height frame)) 2)))
(set-frame-position frame (max 0 x) (max 0 y)))
(make-frame-visible frame)
(redirect-frame-focus frame parent)))
(defun keymap-popup--fit-child-frame (buf)
"Refit the child frame displaying BUF."
(when-let* ((win (get-buffer-window buf t))
(frame (window-frame win))
(_ (frame-parent frame)))
(fit-frame-to-buffer frame)))
(defun keymap-popup--hide-child-frame (buf)
"Delete the child frame displaying BUF."
(when-let* ((win (get-buffer-window buf t))
(frame (window-frame win))
(_ (frame-parent frame)))
(delete-frame frame)))
(defun keymap-popup-backend-side-window ()
"Return a side-window display backend."
(list :show #'keymap-popup--show-side-window
:fit #'keymap-popup--fit-side-window
:hide #'keymap-popup--hide-side-window))
(defun keymap-popup-backend-child-frame ()
"Return a child-frame display backend."
(list :show #'keymap-popup--show-child-frame
:fit #'keymap-popup--fit-child-frame
:hide #'keymap-popup--hide-child-frame))
(defun keymap-popup--prepare-buffer ()
"Create and configure the popup buffer."
(let ((buf (get-buffer-create keymap-popup--buffer-name)))
(with-current-buffer buf
(pcase-dolist (`(,var . ,val) keymap-popup-buffer-parameters)
(set (make-local-variable var) val)))
buf))
;; `internal-{push,pop}-keymap' are the only public path for manipulating
;; `overriding-terminal-local-map'; `set-transient-map' itself uses them.
(defun keymap-popup--suspend ()
"Suspend the popup's transient map for minibuffer input."
(when-let* ((buf (get-buffer keymap-popup--buffer-name))
(map (buffer-local-value 'keymap-popup--wrapper-map buf)))
(internal-pop-keymap map 'overriding-terminal-local-map)))
(defun keymap-popup--resume ()
"Resume the popup's transient map after minibuffer input."
(when-let* ((buf (get-buffer keymap-popup--buffer-name))
(map (buffer-local-value 'keymap-popup--wrapper-map buf)))
(internal-push-keymap map 'overriding-terminal-local-map)))
(defun keymap-popup--teardown (buf)
"Remove the popup display for BUF and kill it."
(when (buffer-live-p buf)
(remove-hook 'minibuffer-setup-hook #'keymap-popup--suspend)
(remove-hook 'minibuffer-exit-hook #'keymap-popup--resume)
(when-let* ((hook (buffer-local-value 'keymap-popup--persistent-hook buf)))
(remove-hook 'post-command-hook hook))
(when-let* ((hide (plist-get (buffer-local-value 'keymap-popup--display-backend buf)
:hide)))
(funcall hide buf))
(kill-buffer buf)))
(defun keymap-popup--make-keep-pred (buf)
"Return a keep-pred for `set-transient-map'.
Reads state from BUF. Consumes the reentering flag on read."
(lambda ()
(and (buffer-live-p buf)
(let ((key-str (key-description (this-command-keys-vector)))
(exit-key (buffer-local-value 'keymap-popup--active-exit-key buf)))
(cond
((active-minibuffer-window) t)
((buffer-local-value 'keymap-popup--reentering buf)
(with-current-buffer buf
(setq-local keymap-popup--reentering nil))
t)
((memq this-command
'(universal-argument universal-argument-more
digit-argument negative-argument
keymap-popup--prefix-argument
describe-key describe-key-briefly)))
((equal key-str exit-key) nil)
((eq this-command 'keyboard-quit) nil)
((keymap-popup--inapt-key-p buf key-str) t)
((buffer-local-value 'keymap-popup--persistent buf))
(t (and-let* ((descs (buffer-local-value
'keymap-popup--active-descriptions buf)))
(keymap-popup--keep-popup-p descs key-str))))))))
(defun keymap-popup--make-on-exit (buf)
"Return an on-exit callback for `set-transient-map' closing BUF.
Pops the sub-menu stack if exit-key or \\`C-g' caused the exit,
otherwise tears down completely."
(lambda ()
(when (buffer-live-p buf)
(with-current-buffer buf
(let ((key-str (key-description (this-command-keys-vector))))
(if (and keymap-popup--stack
(or (equal key-str keymap-popup--active-exit-key)
(equal key-str "C-g")))
(progn
(keymap-popup--restore-state (pop keymap-popup--stack))
(keymap-popup--refresh buf))
(keymap-popup--teardown buf)))))))
(defun keymap-popup--collect-entries (descriptions fn)
"Collect non-nil results of (FN ENTRY GROUP) across DESCRIPTIONS.
Walks rows, groups, and entries. FN receives an entry plist and
its parent group plist; non-nil return values are collected."
(mapcan (lambda (row)
(mapcan (lambda (group)
(mapcan (lambda (entry)
(and-let* ((result (funcall fn entry group)))
(list result)))
(plist-get group :entries)))
row))
descriptions))
(defun keymap-popup--classify-entries (descriptions)
"Walk DESCRIPTIONS once, classify entries by type and properties.
Returns plist (:switches KEYS :submenus PAIRS :stay-open KEYS
:inapt-guards KEYS). :inapt-guards lists plain suffix keys whose
entry or group carries an :inapt-if predicate; presence-based only,
the predicate itself is evaluated at keypress time."
(let ((entries (keymap-popup--collect-entries
descriptions
(lambda (entry group)
(and-let* ((key (plist-get entry :key)))
(list :key key
:type (plist-get entry :type)
:target (plist-get entry :target)
:stay-open (plist-get entry :stay-open)
:inapt (or (plist-get entry :inapt-if)
(plist-get group :inapt-if))))))))
(cl-loop for e in entries
for type = (plist-get e :type)
for key = (plist-get e :key)
when (eq type 'switch) collect key into switches
when (eq type 'keymap) collect (cons key (plist-get e :target)) into submenus
when (and (eq type 'suffix) (plist-get e :stay-open))
collect key into stay-open
when (and (eq type 'suffix) (not (plist-get e :stay-open))
(plist-get e :inapt))
collect key into inapt-guards
finally return (list :switches switches
:submenus submenus
:stay-open stay-open
:inapt-guards inapt-guards))))
(defun keymap-popup--push-submenu (buf child-keymap)
"Push current popup state in BUF and activate CHILD-KEYMAP's transient map."
(with-current-buffer buf
(push (keymap-popup--snapshot-state) keymap-popup--stack)
(let* ((descs (keymap-popup--resolve-descriptions
(keymap-popup--collect-descriptions child-keymap)
child-keymap))
(doc (keymap-popup--meta child-keymap 'description))
(exit-key (or (keymap-popup--meta child-keymap 'exit-key)
keymap-popup-default-exit-key)))
(setq-local keymap-popup--active-keymap child-keymap
keymap-popup--active-descriptions descs
keymap-popup--active-docstring doc
keymap-popup--active-exit-key exit-key
keymap-popup--prefix-mode nil)
(keymap-popup--refresh buf)
(keymap-popup--activate-transient-map buf child-keymap descs exit-key))))
(defun keymap-popup--prefix-argument ()
"Toggle prefix argument mode in the active popup.
When toggling on, activates `universal-argument-map' so that
subsequent digit and `negative-argument' keys refine the prefix."
(interactive)
(when-let* ((buf (get-buffer keymap-popup--buffer-name)))
(with-current-buffer buf
(setq-local keymap-popup--prefix-mode
(not keymap-popup--prefix-mode))
(setq prefix-arg
(and keymap-popup--prefix-mode '(4))))
(keymap-popup--refresh buf)
(when (buffer-local-value 'keymap-popup--prefix-mode buf)
(universal-argument--mode))))
(defun keymap-popup--core-overrides (exit-key)
"Return alist of core overrides for EXIT-KEY and prefix toggle.
The exit key is bound to `ignore'; the keep-pred exits on the key
itself, so the binding only needs to exist and do nothing."
(list (cons exit-key #'ignore)
(cons "C-u" #'keymap-popup--prefix-argument)))
(defun keymap-popup--refuse-inapt (buf)
"Refuse an inapt key press for the popup in BUF.
Preserves BUF's prefix-mode so \\[universal-argument] is not
consumed; the popup only ever stores (4) (see
`keymap-popup--prefix-argument'), so re-setting that value is
preservation, not approximation."
(message "Command unavailable")
(when (and (buffer-live-p buf)
(buffer-local-value 'keymap-popup--prefix-mode buf))
(setq prefix-arg '(4))))
(defun keymap-popup--submenu-overrides (submenu-pairs buf)
"Return alist of submenu key overrides from SUBMENU-PAIRS for BUF.
An inapt submenu key is refused instead of pushed."
(mapcar (lambda (pair)
(cons (car pair)
(let ((key-str (car pair))
(target (cdr pair)))
(lambda () (interactive)
(if (keymap-popup--inapt-key-p buf key-str)
(keymap-popup--refuse-inapt buf)
(keymap-popup--push-submenu buf target))))))
submenu-pairs))
(defun keymap-popup--call-real-binding (keymap key-str)
"Call KEY-STR's live binding in KEYMAP if it is a command.
Sets `this-command' to the binding so `repeat' and `last-command'
see the real command rather than the wrapper closure. Return the
binding, which may be nil."
(let ((cmd (keymap-lookup keymap key-str)))
(when (commandp cmd)
(setq this-command cmd)
(call-interactively cmd))
cmd))
(defun keymap-popup--switch-overrides (keymap switch-keys buf)
"Return alist of switch key overrides for KEYMAP's SWITCH-KEYS in BUF.
Wraps the toggle command with prefix-mode consumption. When the
key is currently inapt the toggle is refused; when the underlying
binding is unbound (because an `:if' predicate is false) the toggle
is skipped. Both cases preserve the prefix-mode."
(mapcar (lambda (key-str)
(cons key-str
(lambda () (interactive)
(if (keymap-popup--inapt-key-p buf key-str)
(keymap-popup--refuse-inapt buf)
(when (keymap-popup--call-real-binding keymap key-str)
(when (buffer-local-value 'keymap-popup--prefix-mode buf)
(with-current-buffer buf
(setq-local keymap-popup--prefix-mode nil))
(setq prefix-arg nil))))
(keymap-popup--refresh buf))))
switch-keys))
(defun keymap-popup--stay-open-overrides (keymap stay-open-keys buf)
"Return alist of stay-open suffix overrides for KEYMAP's STAY-OPEN-KEYS in BUF.
Each command executes and refreshes the popup in place. An inapt
key is refused instead of executed."
(mapcar (lambda (key-str)
(cons key-str
(lambda () (interactive)
(if (keymap-popup--inapt-key-p buf key-str)
(keymap-popup--refuse-inapt buf)
(keymap-popup--call-real-binding keymap key-str))
(keymap-popup--refresh buf))))
stay-open-keys))
(defun keymap-popup--inapt-guard-overrides (keymap guard-keys buf)
"Return alist of overrides for suffix GUARD-KEYS carrying :inapt-if.
Refuse when the key is currently inapt; otherwise dispatch KEYMAP's
real binding. On the apt path the keep-pred has already closed the
popup before this runs, so `keymap-popup--inapt-key-p' returning nil
for the dead BUF falls through to the real binding."
(mapcar (lambda (key-str)
(cons key-str
(lambda () (interactive)
(if (keymap-popup--inapt-key-p buf key-str)
(keymap-popup--refuse-inapt buf)
(keymap-popup--call-real-binding keymap key-str)))))
guard-keys))
(defun keymap-popup--build-wrapper-map (keymap descriptions buf exit-key)
"Build wrapper keymap over KEYMAP with DESCRIPTIONS for BUF.
EXIT-KEY and switch/submenu/stay-open/inapt-guard handlers layer
over KEYMAP. `:if' enforcement lives on KEYMAP itself via
`menu-item' :filter; `:inapt-if' is enforced here at keypress time
by the overrides reading the popup's active descriptions."
(let* ((map (make-sparse-keymap))
(classified (keymap-popup--classify-entries descriptions))
(overrides (append (keymap-popup--core-overrides exit-key)
(keymap-popup--switch-overrides
keymap (plist-get classified :switches) buf)
(keymap-popup--submenu-overrides
(plist-get classified :submenus) buf)
(keymap-popup--stay-open-overrides
keymap (plist-get classified :stay-open) buf)
(keymap-popup--inapt-guard-overrides
keymap (plist-get classified :inapt-guards) buf))))
(set-keymap-parent map keymap)
(pcase-dolist (`(,key . ,cmd) overrides)
(keymap-set map key cmd))
map))
(defun keymap-popup-dismiss ()
"Dismiss the active popup, if any.
Deactivates every transient map in a nested popup session and
removes the popup display."
(interactive)
(when-let* ((buf (get-buffer keymap-popup--buffer-name)))
(let ((exit-functions
(with-current-buffer buf
(prog1
(seq-filter
#'functionp
(cons keymap-popup--exit-function
(mapcar (lambda (state)
(plist-get state :exit-function))
keymap-popup--stack)))
(setq-local keymap-popup--exit-function nil
keymap-popup--stack nil)))))
(mapc #'funcall exit-functions)
(when (buffer-live-p buf)
(keymap-popup--teardown buf)))))
(defun keymap-popup--session-inputs (keymap)
"Derive a plist of session inputs from KEYMAP and the current buffer.
Returns (:source BUF :keymap MAP :descriptions D :docstring S
:exit-key K :persistent P :backend B)."
(list :source (current-buffer)
:keymap keymap
:descriptions (keymap-popup--resolve-descriptions
(keymap-popup--collect-descriptions keymap)
keymap)
:docstring (keymap-popup--meta keymap 'description)
:exit-key (or (keymap-popup--meta keymap 'exit-key)
keymap-popup-default-exit-key)
:persistent (or (keymap-popup--meta keymap 'persistent)
keymap-popup-persistent)
:backend (funcall keymap-popup-backend)))
(defun keymap-popup--init-buffer-state (buf session)
"Initialize BUF's buffer-local state from SESSION plist."
(with-current-buffer buf
(setq-local keymap-popup--source-buffer (plist-get session :source)
keymap-popup--active-keymap (plist-get session :keymap)
keymap-popup--active-descriptions (plist-get session :descriptions)
keymap-popup--active-docstring (plist-get session :docstring)
keymap-popup--active-exit-key (plist-get session :exit-key)
keymap-popup--persistent (plist-get session :persistent)
keymap-popup--display-backend (plist-get session :backend)
keymap-popup--stack nil
keymap-popup--exit-function nil
keymap-popup--persistent-hook nil
keymap-popup--prefix-mode nil
keymap-popup--reentering nil)))
(defun keymap-popup--activate-transient-map (buf keymap descriptions exit-key)
"Build the wrapper for KEYMAP using DESCRIPTIONS, stash on BUF, activate.
EXIT-KEY is bound in the wrapper to dismiss the popup."
(let ((wrapper (keymap-popup--build-wrapper-map keymap descriptions buf exit-key)))
(with-current-buffer buf
(setq-local keymap-popup--wrapper-map wrapper))
(let ((exit-function
(set-transient-map wrapper
(keymap-popup--make-keep-pred buf)
(keymap-popup--make-on-exit buf))))
(when (buffer-live-p buf)
(with-current-buffer buf
(setq-local keymap-popup--exit-function exit-function))))))
(defun keymap-popup--install-persistent-hook (buf)
"Install BUF's self-removing persistent refresh hook."
(let ((hook-fn (make-symbol "keymap-popup--persistent-refresh")))
(fset hook-fn
(lambda ()
(if (buffer-live-p buf)
(keymap-popup--refresh buf)
(remove-hook 'post-command-hook hook-fn))))
(with-current-buffer buf
(setq-local keymap-popup--persistent-hook hook-fn))
(add-hook 'post-command-hook hook-fn)))
;;;###autoload
(defun keymap-popup (keymap)
"Show popup help for described KEYMAP.
Activates KEYMAP as a transient map. Switch keys execute and re-render
without closing. Inapt keys are refused with \"Command unavailable\"
and keep the popup open; outside a popup, `:inapt-if' does not block
dispatch. Sub-menu keys push a navigation stack.
\\[universal-argument] toggles prefix mode."
(or (keymap-popup--meta keymap 'descriptions)
(user-error "No descriptions in keymap"))
(when (get-buffer keymap-popup--buffer-name)
(keymap-popup-dismiss))
(let ((session (keymap-popup--session-inputs keymap))
(buf (keymap-popup--prepare-buffer)))
(keymap-popup--init-buffer-state buf session)
(keymap-popup--refresh buf)
(funcall (plist-get (plist-get session :backend) :show) buf)
(keymap-popup--activate-transient-map
buf keymap
(plist-get session :descriptions)
(plist-get session :exit-key))
(add-hook 'minibuffer-setup-hook #'keymap-popup--suspend)
(add-hook 'minibuffer-exit-hook #'keymap-popup--resume)
(when (plist-get session :persistent)
(keymap-popup--install-persistent-hook buf))))
(provide 'keymap-popup)
;;; keymap-popup.el ends here
emacs-keymap-popup-0.4.0/tests/ 0000775 0000000 0000000 00000000000 15225053467 0016403 5 ustar 00root root 0000000 0000000 emacs-keymap-popup-0.4.0/tests/keymap-popup-tests.el 0000664 0000000 0000000 00000243021 15225053467 0022516 0 ustar 00root root 0000000 0000000 ;;; keymap-popup-tests.el --- Tests -*- lexical-binding: t; -*-
;;; Commentary:
;; ERT tests for keymap-popup. Run via `make test'.
;;; Code:
(require 'ert)
(require 'keymap-popup)
;;; Parser tests
(ert-deftest keymap-popup-test-parse-suffix-entry ()
(let ((result (keymap-popup--parse-entry "c" '("Comment" forgejo-view-comment))))
(should (equal (plist-get result :key) "c"))
(should (equal (plist-get result :description) "Comment"))
(should (equal (plist-get result :command) 'forgejo-view-comment))
(should (equal (plist-get result :type) 'suffix))))
(ert-deftest keymap-popup-test-parse-suffix-with-if ()
(let* ((pred (lambda () t))
(result (keymap-popup--parse-entry "b" `("Browse" forgejo-browse :if ,pred))))
(should (equal (plist-get result :type) 'suffix))
(should (eq (plist-get result :if) pred))))
(ert-deftest keymap-popup-test-parse-switch-entry ()
(let ((result (keymap-popup--parse-entry "v" '("Verbose" :switch my-verbose-var))))
(should (equal (plist-get result :type) 'switch))
(should (equal (plist-get result :variable) 'my-verbose-var))))
(ert-deftest keymap-popup-test-parse-dynamic-description ()
(let* ((desc-fn (lambda () "dynamic"))
(result (keymap-popup--parse-entry "d" `(,desc-fn some-command))))
(should (functionp (plist-get result :description)))))
(ert-deftest keymap-popup-test-parse-bindings-groups ()
(let* ((rows (keymap-popup--parse-bindings
'(:group "Actions"
"c" ("Comment" forgejo-view-comment)
"r" ("Reply" forgejo-issue-reply)
:group "Navigate"
"g" ("Refresh" forgejo-view-refresh)
"q" ("Quit" quit-window))))
(row (car rows)))
(should (= (length rows) 1))
(should (= (length row) 2))
(should (equal (plist-get (car row) :name) "Actions"))
(should (= (length (plist-get (car row) :entries)) 2))
(should (equal (plist-get (cadr row) :name) "Navigate"))
(should (= (length (plist-get (cadr row) :entries)) 2))))
(ert-deftest keymap-popup-test-parse-bindings-no-group ()
(let* ((rows (keymap-popup--parse-bindings
'("c" ("Comment" forgejo-view-comment)
"r" ("Reply" forgejo-issue-reply))))
(row (car rows)))
(should (= (length rows) 1))
(should (= (length row) 1))
(should (null (plist-get (car row) :name)))
(should (= (length (plist-get (car row) :entries)) 2))))
(ert-deftest keymap-popup-test-parse-bindings-rows ()
(let ((rows (keymap-popup--parse-bindings
'(:group "A"
"a" ("Aaa" ignore)
:group "B"
"b" ("Bbb" ignore)
:row
:group "C"
"c" ("Ccc" ignore)))))
(should (= (length rows) 2))
(should (= (length (car rows)) 2))
(should (= (length (cadr rows)) 1))
(should (equal (plist-get (caar (cdr rows)) :name) "C"))))
(ert-deftest keymap-popup-test-split-groups-trailing-row ()
"A trailing :row with nothing after it yields no empty row."
(should (= 1 (length (keymap-popup--split-groups
'("a" ("A" ignore) :row))))))
(ert-deftest keymap-popup-test-parse-keymap-entry ()
(let ((result (keymap-popup--parse-entry "a" '("Metadata" :keymap my-sub-map))))
(should (equal (plist-get result :type) 'keymap))
(should (equal (plist-get result :target) 'my-sub-map))))
;;; Infix generator tests
(ert-deftest keymap-popup-test-entry-command ()
(should (eq (keymap-popup--entry-command 'map '(:type suffix :command my-cmd))
'my-cmd))
(should (eq (keymap-popup--entry-command 'map '(:type switch :variable my-var))
'map--toggle-my-var))
(should (eq (keymap-popup--entry-command 'map '(:type keymap :target my-sub))
'map--enter-my-sub)))
;;; Macro tests
(ert-deftest keymap-popup-test-macro-declarations-filter-keymap-expressions ()
(let* ((forms (cdr (macroexpand-1
'(keymap-popup-define keymap-popup--test-root-map
:parent (make-sparse-keymap)
"a" ("A" :keymap keymap-popup--test-sub-map)
"b" ("B" :keymap keymap-popup--test-sub-map)
"c" ("C" :keymap (make-sparse-keymap))))))
(declarations (seq-filter
(lambda (form) (eq (car-safe form) 'defvar))
forms)))
(should (equal declarations
'((defvar keymap-popup--test-root-map)
(defvar keymap-popup--test-sub-map))))))
(ert-deftest keymap-popup-test-macro-declarations-omit-nil-parent ()
(let* ((forms (cdr (macroexpand-1
'(keymap-popup-define keymap-popup--test-no-parent-map
"r" ("Refresh" ignore)))))
(declarations (seq-filter
(lambda (form) (eq (car-safe form) 'defvar))
forms)))
(should (equal declarations
'((defvar keymap-popup--test-no-parent-map))))))
(ert-deftest keymap-popup-test-macro-declarations-include-parent ()
(let* ((forms (cdr (macroexpand-1
'(keymap-popup-define keymap-popup--test-child-map
:parent keymap-popup--test-parent-map
"s" ("Sub" :keymap keymap-popup--test-parent-map)))))
(declarations (seq-filter
(lambda (form) (eq (car-safe form) 'defvar))
forms)))
(should (equal declarations
'((defvar keymap-popup--test-child-map)
(defvar keymap-popup--test-parent-map))))))
(ert-deftest keymap-popup-test-macro-expands-to-attach-meta ()
"Both macros attach metadata via one attach-meta call, no raw setf."
(dolist (form '((keymap-popup-define keymap-popup--test-attach-form-map
:persistent t
"r" ("Refresh" ignore))
(keymap-popup-annotate keymap-popup--test-attach-form-map
:exit-key "x"
forward-char "Forward")))
(let ((forms (cdr (macroexpand-1 form))))
(should (= 1 (seq-count
(lambda (f) (eq (car-safe f) 'keymap-popup--attach-meta))
forms)))
(should-not (seq-some (lambda (f) (eq (car-safe f) 'setf)) forms)))))
(ert-deftest keymap-popup-test-define-switch-entry-stores-command ()
"Define stores the generated toggle command on switch entries."
(eval '(keymap-popup-define keymap-popup--test-entry-cmd-map
:group "Toggles"
"v" ("Verbose" :switch keymap-popup--test-entry-cmd-verbose))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-entry-cmd-map
'descriptions))
(entry (car (plist-get (caar descs) :entries))))
(should (eq (plist-get entry :command)
(keymap-popup--toggle-name
'keymap-popup--test-entry-cmd-map
'keymap-popup--test-entry-cmd-verbose)))
(should (eq (plist-get entry :variable)
'keymap-popup--test-entry-cmd-verbose))))
(ert-deftest keymap-popup-test-define-keymap-entry-stores-command ()
"Define stores the generated enter command on keymap entries."
(defvar keymap-popup--test-entry-cmd-sub (make-sparse-keymap))
(eval '(keymap-popup-define keymap-popup--test-entry-cmd-root
:group "Menus"
"s" ("Sub" :keymap keymap-popup--test-entry-cmd-sub))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-entry-cmd-root
'descriptions))
(entry (car (plist-get (caar descs) :entries))))
(should (eq (plist-get entry :command)
(keymap-popup--enter-name
'keymap-popup--test-entry-cmd-root
'keymap-popup--test-entry-cmd-sub)))
(should (eq (plist-get entry :target)
keymap-popup--test-entry-cmd-sub))))
(ert-deftest keymap-popup-test-annotate-entries-lack-generated-command ()
"Annotate emits no generated commands, so entries carry none."
(defvar keymap-popup--test-entry-cmd-sub (make-sparse-keymap))
(setq keymap-popup--test-annotate-map (make-sparse-keymap))
(eval '(keymap-popup-annotate keymap-popup--test-annotate-map
:group "Menus"
"s" ("Sub" :keymap keymap-popup--test-entry-cmd-sub))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-annotate-map
'descriptions))
(entry (car (plist-get (caar descs) :entries))))
(should (eq (plist-get entry :type) 'keymap))
(should-not (plist-get entry :command))))
(ert-deftest keymap-popup-test-macro-creates-keymap ()
(eval '(keymap-popup-define keymap-popup--test-map-1
"Test keymap."
:group "Actions"
"c" ("Comment" ignore)
"q" ("Quit" quit-window))
t)
(should (keymapp keymap-popup--test-map-1))
(should (eq (keymap-lookup keymap-popup--test-map-1 "c") #'ignore))
(should (eq (keymap-lookup keymap-popup--test-map-1 "q") #'quit-window)))
(ert-deftest keymap-popup-test-macro-stores-descriptions ()
(eval '(keymap-popup-define keymap-popup--test-map-2
"Test."
:group "A"
"c" ("Comment" ignore)
:group "B"
"g" ("Go" ignore))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-map-2
'descriptions))
(row (car descs)))
(should (= (length descs) 1))
(should (= (length row) 2))
(should (equal (plist-get (car row) :name) "A"))
(should (equal (plist-get (cadr row) :name) "B"))))
(ert-deftest keymap-popup-test-macro-switch-infix ()
(eval '(keymap-popup-define keymap-popup--test-map-3
"Test."
"v" ("Verbose" :switch keymap-popup--test-sw))
t)
(should (boundp 'keymap-popup--test-sw))
(should (fboundp 'keymap-popup--test-map-3--toggle-keymap-popup--test-sw)))
(ert-deftest keymap-popup-test-macro-declares-maps-before-helpers ()
(let* ((forms (cdr (macroexpand-1
'(keymap-popup-define keymap-popup--test-declared-map
"Test."
:parent keymap-popup--test-declared-parent
"s" ("Sub" :keymap keymap-popup--test-declared-sub)))))
(map-pos (cl-position '(defvar keymap-popup--test-declared-map)
forms :test #'equal))
(parent-pos (cl-position '(defvar keymap-popup--test-declared-parent)
forms :test #'equal))
(sub-pos (cl-position '(defvar keymap-popup--test-declared-sub)
forms :test #'equal))
(launcher-pos (cl-position-if
(lambda (form)
(and (eq (car-safe form) 'defun)
(eq (cadr form)
'keymap-popup--test-declared-map-popup)))
forms))
(enter-pos (cl-position-if
(lambda (form)
(and (eq (car-safe form) 'defun)
(eq (cadr form)
'keymap-popup--test-declared-map--enter-keymap-popup--test-declared-sub)))
forms))
(keymap-pos (cl-position-if
(lambda (form) (eq (car-safe form) 'defvar-keymap))
forms)))
(should map-pos)
(should parent-pos)
(should sub-pos)
(should launcher-pos)
(should enter-pos)
(should keymap-pos)
(should (< map-pos launcher-pos))
(should (< sub-pos enter-pos))
(should (< parent-pos keymap-pos))))
(ert-deftest keymap-popup-test-macro-emits-launcher-defun ()
"`keymap-popup-define' emits a named `defun' for the popup launcher."
(eval '(keymap-popup-define keymap-popup--test-launcher
"Test." "c" ("Comment" ignore))
t)
(should (fboundp 'keymap-popup--test-launcher-popup))
(should (commandp 'keymap-popup--test-launcher-popup))
(should (eq (keymap-lookup keymap-popup--test-launcher "h")
#'keymap-popup--test-launcher-popup)))
(ert-deftest keymap-popup-test-macro-emits-enterer-defun ()
"`keymap-popup-define' emits a named `defun' for each `:keymap' sub-menu key."
(defvar keymap-popup--test-sub-map (make-sparse-keymap))
(eval '(keymap-popup-define keymap-popup--test-with-sub
"Test." "s" ("Sub" :keymap keymap-popup--test-sub-map))
t)
(should (fboundp 'keymap-popup--test-with-sub--enter-keymap-popup--test-sub-map))
(should (eq (keymap-lookup keymap-popup--test-with-sub "s")
#'keymap-popup--test-with-sub--enter-keymap-popup--test-sub-map)))
(ert-deftest keymap-popup-test-macro-lambda-command ()
(eval '(keymap-popup-define keymap-popup--test-map-5
"Test."
"x" ("Run" (lambda () (interactive) (message "running"))))
t)
(should (functionp (keymap-lookup keymap-popup--test-map-5 "x"))))
(ert-deftest keymap-popup-test-macro-no-docstring ()
(eval '(keymap-popup-define keymap-popup--test-map-nodoc
:group "Actions"
"c" ("Comment" ignore))
t)
(should (keymapp keymap-popup--test-map-nodoc))
(should (eq (keymap-lookup keymap-popup--test-map-nodoc "c") #'ignore))
(let* ((descs (keymap-popup--meta keymap-popup--test-map-nodoc
'descriptions))
(row (car descs)))
(should (= (length descs) 1))
(should (= (length row) 1))
(should (equal (plist-get (car row) :name) "Actions"))))
(ert-deftest keymap-popup-test-macro-default-popup-key ()
(eval '(keymap-popup-define keymap-popup--test-map-defkey
"c" ("Comment" ignore))
t)
(should (functionp (keymap-lookup keymap-popup--test-map-defkey "h"))))
(ert-deftest keymap-popup-test-macro-popup-key-resolved-at-load ()
"The default popup key is read at load time, not expansion time."
(let ((expansion (macroexpand-1
'(keymap-popup-define keymap-popup--test-map-loadkey
"c" ("Comment" ignore)))))
(let ((keymap-popup-default-popup-key "!"))
(eval expansion t))
(should (functionp (keymap-lookup keymap-popup--test-map-loadkey "!")))
(should (null (keymap-lookup keymap-popup--test-map-loadkey "h")))))
(ert-deftest keymap-popup-test-macro-no-exit-key-stores-no-metadata ()
"Without :exit-key, no exit-key metadata is stored; display falls back."
(eval '(keymap-popup-define keymap-popup--test-map-noexit
"c" ("Comment" ignore))
t)
(should-not (keymap-popup--meta keymap-popup--test-map-noexit 'exit-key)))
(ert-deftest keymap-popup-test-macro-custom-popup-key ()
(eval '(keymap-popup-define keymap-popup--test-map-custkey
:popup-key "?"
"c" ("Comment" ignore))
t)
(should (functionp (keymap-lookup keymap-popup--test-map-custkey "?")))
(should (null (keymap-lookup keymap-popup--test-map-custkey "h"))))
(ert-deftest keymap-popup-test-macro-exit-key ()
(eval '(keymap-popup-define keymap-popup--test-exit-key
:exit-key "x"
"c" ("Comment" ignore))
t)
(should (equal (keymap-popup--meta keymap-popup--test-exit-key
'exit-key)
"x")))
(ert-deftest keymap-popup-test-popup-key-with-docstring ()
(eval '(keymap-popup-define keymap-popup--test-pkdoc
"My commands."
:popup-key "?"
:group "Actions"
"c" ("Comment" ignore))
t)
(should (functionp (keymap-lookup keymap-popup--test-pkdoc "?")))
(should (null (keymap-lookup keymap-popup--test-pkdoc "h")))
(should (string-match-p "My commands"
(documentation-property 'keymap-popup--test-pkdoc
'variable-documentation))))
(ert-deftest keymap-popup-test-macro-keyword-order-independent ()
"Keywords can appear in any order."
(eval '(keymap-popup-define keymap-popup--test-kworder
:description "Dynamic"
:parent special-mode-map
:popup-key "?"
:exit-key "x"
"c" ("Comment" ignore))
t)
(should (functionp (keymap-lookup keymap-popup--test-kworder "?")))
(should (equal (keymap-popup--meta keymap-popup--test-kworder 'exit-key) "x"))
(should (eq (keymap-parent keymap-popup--test-kworder) special-mode-map)))
;;; Renderer tests
(ert-deftest keymap-popup-test-render-suffix ()
(let* ((rows (list (list (list :name "Actions"
:entries (list (list :key "c" :description "Comment"
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows)))
(should (string-match-p "Actions" output))
(should (string-match-p "Comment" output))))
(ert-deftest keymap-popup-test-render-switch-value ()
(defvar keymap-popup--test-render-sw nil)
(let* ((rows (list (list (list :name nil
:entries (list (list :key "v" :description "Verbose"
:type 'switch
:variable 'keymap-popup--test-render-sw))))))
(output-off (keymap-popup--render rows)))
(should (string-match-p "\\[off\\]" output-off))
(setq keymap-popup--test-render-sw t)
(let ((output-on (keymap-popup--render rows)))
(should (string-match-p "\\[on\\]" output-on)))))
(ert-deftest keymap-popup-test-render-if-hidden ()
(let* ((rows (list (list (list :name nil
:entries (list (list :key "b" :description "Browse"
:type 'suffix :command 'ignore
:if (lambda () nil)))))))
(output (keymap-popup--render rows)))
(should-not (string-match-p "Browse" output))))
(ert-deftest keymap-popup-test-render-if-shown ()
(let* ((rows (list (list (list :name nil
:entries (list (list :key "b" :description "Browse"
:type 'suffix :command 'ignore
:if (lambda () t)))))))
(output (keymap-popup--render rows)))
(should (string-match-p "Browse" output))))
(ert-deftest keymap-popup-test-render-dynamic-description ()
(let* ((rows (list (list (list :name nil
:entries (list (list :key "d"
:description (lambda () "Dynamic!")
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows)))
(should (string-match-p "Dynamic!" output))))
;;; Column layout tests
(ert-deftest keymap-popup-test-render-columns-side-by-side ()
(let* ((rows (list (list (list :name "Alpha"
:entries (list (list :key "a" :description "Aaa"
:type 'suffix :command 'ignore)))
(list :name "Beta"
:entries (list (list :key "b" :description "Bbb"
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows))
(lines (split-string output "\n" t)))
(should (string-match-p "Alpha" (car lines)))
(should (string-match-p "Beta" (car lines)))))
(ert-deftest keymap-popup-test-render-rows-separated ()
(let* ((rows (list (list (list :name "Row1"
:entries (list (list :key "a" :description "Aaa"
:type 'suffix :command 'ignore))))
(list (list :name "Row2"
:entries (list (list :key "b" :description "Bbb"
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows)))
(should (string-match-p "Row1" output))
(should (string-match-p "Row2" output))
(let ((lines (split-string output "\n" t)))
(should-not (and (string-match-p "Row1" (car lines))
(string-match-p "Row2" (car lines)))))))
(ert-deftest keymap-popup-test-render-empty-descriptions ()
"An empty resolved menu renders as a blank popup."
(should (equal (keymap-popup--render nil) "\n")))
(ert-deftest keymap-popup-test-columns-aligned-across-rows ()
(let* ((rows (list
(list (list :name "A"
:entries (list (list :key "a" :description "X"
:type 'suffix :command 'ignore)))
(list :name "B"
:entries (list (list :key "b" :description "Y"
:type 'suffix :command 'ignore))))
(list (list :name "Longer Name"
:entries (list (list :key "c" :description "Something longer"
:type 'suffix :command 'ignore)))
(list :name "D"
:entries (list (list :key "d" :description "Z"
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows))
(plain (substring-no-properties output))
(lines (split-string plain "\n" t)))
(let ((b-pos (string-match "B" (cl-find-if (lambda (l) (string-match-p "\\bB\\b" l)) lines)))
(d-pos (string-match "D" (cl-find-if (lambda (l) (string-match-p "\\bD\\b" l)) lines))))
(should b-pos)
(should d-pos)
(should (= b-pos d-pos)))))
(ert-deftest keymap-popup-test-join-columns ()
(let* ((col-a '("Header A" " a Aaa" " b Bbb"))
(col-b '("Header B" " c Ccc"))
(widths (list (keymap-popup--column-width col-a)
(keymap-popup--column-width col-b)))
(result (keymap-popup--join-columns (list col-a col-b) " " widths)))
(should (= (length result) 3))
(should (string-match-p "Header A" (nth 0 result)))
(should (string-match-p "Header B" (nth 0 result)))
(should (string-match-p "Bbb" (nth 2 result)))))
;;; Lookup helper tests
(ert-deftest keymap-popup-test-find-entry-by-key ()
(let ((descs (list (list (list :name "G"
:entries (list (list :key "c" :description "Comment"
:type 'suffix :command 'ignore)
(list :key "v" :description "Verbose"
:type 'switch :variable 'some-var)))))))
(should (equal (plist-get (keymap-popup--find-entry-by-key descs "c") :type) 'suffix))
(should (equal (plist-get (keymap-popup--find-entry-by-key descs "v") :type) 'switch))
(should (null (keymap-popup--find-entry-by-key descs "z")))))
(ert-deftest keymap-popup-test-keep-popup-p ()
(let ((descs (list (list (list :name nil
:entries (list (list :key "c" :type 'suffix :command 'ignore)
(list :key "v" :type 'switch :variable 'x)
(list :key "a" :type 'keymap :target 'sub)
(list :key "g" :type 'suffix :command 'ignore
:stay-open t)))))))
(should-not (keymap-popup--keep-popup-p descs "c"))
(should (keymap-popup--keep-popup-p descs "v"))
(should (keymap-popup--keep-popup-p descs "a"))
;; stay-open suffixes refresh in place, kept open
(should (keymap-popup--keep-popup-p descs "g"))
;; Inapt-key handling lives in the keep-pred via
;; `keymap-popup--inapt-key-p', not in keep-popup-p.
;; C-u is detected via `this-command'.
(should-not (keymap-popup--keep-popup-p descs "C-u"))))
;;; C-u rendering tests
(ert-deftest keymap-popup-test-c-u-desc-in-normal-mode ()
(let* ((rows (list (list (list :name nil
:entries (list (list :key "s" :description "Submit"
:type 'suffix :command 'ignore
:c-u "force push"))))))
(output (keymap-popup--render rows)))
(should (string-match-p "(force push)" output))
(let ((pos (string-match "(force push)" output)))
(should (eq (get-text-property pos 'face output) 'shadow)))))
(ert-deftest keymap-popup-test-c-u-desc-in-prefix-mode ()
(let* ((rows (list (list (list :name nil
:entries (list (list :key "s" :description "Submit"
:type 'suffix :command 'ignore
:c-u "force")
(list :key "g" :description "Refresh"
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows t)))
(let ((pos (string-match "(force)" output)))
(should pos)
(should-not (eq (get-text-property pos 'face output) 'shadow)))
(let ((pos (string-match "Refresh" output)))
(should (eq (get-text-property pos 'face output) 'shadow)))))
;;; Inapt rendering tests
(ert-deftest keymap-popup-test-inapt-rendered-with-face ()
(let* ((rows (list (list (list :name nil
:entries (list (list :key "m" :description "Merge"
:type 'suffix :command 'ignore
:inapt-if (lambda () t)))))))
(output (keymap-popup--render rows)))
(should (string-match-p "Merge" output))
(let ((pos (string-match "Merge" output)))
(should (eq (get-text-property pos 'face output) 'keymap-popup-inapt)))))
(ert-deftest keymap-popup-test-inapt-not-when-predicate-nil ()
(let* ((rows (list (list (list :name nil
:entries (list (list :key "m" :description "Merge"
:type 'suffix :command 'ignore
:inapt-if (lambda () nil)))))))
(output (keymap-popup--render rows)))
(let ((pos (string-match "Merge" output)))
(should-not (eq (get-text-property pos 'face output) 'keymap-popup-inapt)))))
(ert-deftest keymap-popup-test-keymap-entry-gets-submenu-face ()
(let* ((rows (list (list (list :name nil
:entries (list (list :key "a" :description "Sub"
:type 'keymap :target 'x))))))
(output (keymap-popup--render rows)))
(let ((pos (string-match "Sub" output)))
(should (eq (get-text-property pos 'face output) 'keymap-popup-submenu)))))
;;; Group-level predicate tests
(ert-deftest keymap-popup-test-group-if-hidden ()
(let* ((rows (list (list (list :name "Visible"
:entries (list (list :key "a" :description "Alpha"
:type 'suffix :command 'ignore)))
(list :name "Hidden" :if (lambda () nil)
:entries (list (list :key "b" :description "Beta"
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows)))
(should (string-match-p "Alpha" output))
(should-not (string-match-p "Beta" output))))
(ert-deftest keymap-popup-test-group-if-shown ()
(let* ((rows (list (list (list :name "Shown" :if (lambda () t)
:entries (list (list :key "a" :description "Alpha"
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows)))
(should (string-match-p "Alpha" output))
(should (string-match-p "Shown" output))))
(ert-deftest keymap-popup-test-group-inapt-grays-all ()
(let* ((rows (list (list (list :name "Disabled"
:inapt-if (lambda () t)
:entries (list (list :key "a" :description "Alpha"
:type 'suffix :command 'ignore)
(list :key "b" :description "Beta"
:type 'suffix :command 'ignore))))))
(output (keymap-popup--render rows)))
(let ((pos-a (string-match "Alpha" output))
(pos-b (string-match "Beta" output)))
(should (eq (get-text-property pos-a 'face output) 'keymap-popup-inapt))
(should (eq (get-text-property pos-b 'face output) 'keymap-popup-inapt)))))
;;; Integration tests
(ert-deftest keymap-popup-test-full-definition ()
(eval '(keymap-popup-define keymap-popup--test-full
"Full test."
:group "Actions"
"c" ("Comment" ignore)
:group "Switches"
"v" ("Verbose" :switch keymap-popup--test-full-verbose)
:row
:group "Navigate"
"b" ("Browse" ignore :if (lambda () t))
"q" ("Quit" quit-window))
t)
(should (keymapp keymap-popup--test-full))
(should (eq (keymap-lookup keymap-popup--test-full "c") #'ignore))
(let ((descs (keymap-popup--meta keymap-popup--test-full
'descriptions)))
(should (= (length descs) 2))))
(ert-deftest keymap-popup-test-switch-toggle-roundtrip ()
(eval '(keymap-popup-define keymap-popup--test-rt
"Test." "v" ("Verbose" :switch keymap-popup--test-rt-sw))
t)
(with-temp-buffer
(should (null keymap-popup--test-rt-sw))
(funcall-interactively #'keymap-popup--test-rt--toggle-keymap-popup--test-rt-sw)
(should (eq keymap-popup--test-rt-sw t))
(funcall-interactively #'keymap-popup--test-rt--toggle-keymap-popup--test-rt-sw)
(should (null keymap-popup--test-rt-sw))))
(ert-deftest keymap-popup-test-stay-open-in-descriptions ()
(eval '(keymap-popup-define keymap-popup--test-stay
"g" ("Refresh" ignore :stay-open t))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-stay
'descriptions))
(entry (keymap-popup--find-entry-by-key descs "g")))
(should (plist-get entry :stay-open))))
(ert-deftest keymap-popup-test-bare-stay-open-in-descriptions ()
"A bare :stay-open property is a true boolean flag."
(eval '(keymap-popup-define keymap-popup--test-bare-stay
"g" ("Refresh" ignore :stay-open))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-bare-stay
'descriptions))
(entry (keymap-popup--find-entry-by-key descs "g")))
(should (eq (plist-get entry :stay-open) t))))
(ert-deftest keymap-popup-test-dynamic-group-name ()
(eval '(keymap-popup-define keymap-popup--test-dyngrp
:group (lambda () "Dynamic Group")
"c" ("Comment" ignore))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-dyngrp
'descriptions))
(output (keymap-popup--render descs)))
(should (string-match-p "Dynamic Group" output))))
;;; Parent inheritance tests
(ert-deftest keymap-popup-test-parent-keymap-bindings ()
(eval '(keymap-popup-define keymap-popup--test-parent
:group "Common"
"g" ("Refresh" ignore)
"q" ("Quit" quit-window))
t)
(eval '(keymap-popup-define keymap-popup--test-child
:parent keymap-popup--test-parent
:group "Child"
"c" ("Comment" ignore))
t)
(should (eq (keymap-lookup keymap-popup--test-child "c") #'ignore))
(should (eq (keymap-lookup keymap-popup--test-child "g") #'ignore)))
(ert-deftest keymap-popup-test-parent-descriptions-merged ()
(eval '(keymap-popup-define keymap-popup--test-parent2
:group "Common"
"g" ("Refresh" ignore))
t)
(eval '(keymap-popup-define keymap-popup--test-child2
:parent keymap-popup--test-parent2
:group "Child"
"c" ("Comment" ignore))
t)
(let ((all (keymap-popup--collect-descriptions keymap-popup--test-child2)))
(should (>= (length all) 2))))
(ert-deftest keymap-popup-test-collect-descriptions-chain ()
(eval '(keymap-popup-define keymap-popup--test-grandparent
:group "GP"
"g" ("Go" ignore))
t)
(eval '(keymap-popup-define keymap-popup--test-mid
:parent keymap-popup--test-grandparent
:group "Mid"
"m" ("Mid cmd" ignore))
t)
(eval '(keymap-popup-define keymap-popup--test-leaf
:parent keymap-popup--test-mid
:group "Leaf"
"l" ("Leaf cmd" ignore))
t)
(let ((all (keymap-popup--collect-descriptions keymap-popup--test-leaf)))
(should (>= (length all) 3))))
(ert-deftest keymap-popup-test-dedupe-preserves-nil-keys ()
"Multiple entries with nil :key (annotated, pre-resolve) are all kept."
(let* ((descs `(((:name "Move" :entries ((:key nil :command forward-char
:description "Right")
(:key nil :command backward-char
:description "Left"))))))
(deduped (keymap-popup--dedupe-descriptions descs))
(entries (plist-get (caar deduped) :entries)))
(should (= (length entries) 2))
(should (equal (mapcar (lambda (e) (plist-get e :description)) entries)
'("Right" "Left")))))
(ert-deftest keymap-popup-test-collect-descriptions-child-shadows-parent ()
"Parent/child key collision: child wins, fully-shadowed parent groups disappear."
(eval '(keymap-popup-define keymap-popup--test-shadow-parent
:group "P"
"a" ("Parent A" ignore)
:group "Q"
"b" ("Parent B" ignore))
t)
(eval '(keymap-popup-define keymap-popup--test-shadow-child
:parent keymap-popup--test-shadow-parent
:group "C"
"a" ("Child A" ignore))
t)
(let* ((all (keymap-popup--collect-descriptions keymap-popup--test-shadow-child))
(group-names (cl-loop for row in all
append (mapcar (lambda (g) (plist-get g :name)) row)))
(entries (cl-loop for row in all
append (cl-loop for group in row
append (plist-get group :entries))))
(keys (mapcar (lambda (e) (plist-get e :key)) entries))
(descs (mapcar (lambda (e) (plist-get e :description)) entries)))
;; Parent group "P" is fully shadowed and dropped; "Q" survives.
(should (equal group-names '("C" "Q")))
(should (equal keys '("a" "b")))
(should (equal descs '("Child A" "Parent B")))))
;;; Macro via-macro integration tests
(ert-deftest keymap-popup-test-inapt-via-macro ()
(eval '(keymap-popup-define keymap-popup--test-inapt-map
"m" ("Merge" ignore :inapt-if (lambda () t))
"c" ("Comment" ignore))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-inapt-map
'descriptions))
(output (keymap-popup--render descs)))
(let ((pos (string-match "Merge" output)))
(should pos)
(should (eq (get-text-property pos 'face output) 'keymap-popup-inapt)))
(should (string-match-p "Comment" output))))
(ert-deftest keymap-popup-test-group-inapt-via-macro ()
(eval '(keymap-popup-define keymap-popup--test-group-inapt-map
:group ("Disabled" :inapt-if (lambda () t))
"a" ("Alpha" ignore)
"b" ("Beta" ignore))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-group-inapt-map
'descriptions))
(output (keymap-popup--render descs))
(pos (string-match "Alpha" output)))
(should pos)
(should (eq (get-text-property pos 'face output) 'keymap-popup-inapt))))
(ert-deftest keymap-popup-test-group-if-via-macro ()
(eval '(keymap-popup-define keymap-popup--test-group-if-map
:group ("Hidden" :if (lambda () nil))
"a" ("Alpha" ignore)
:group "Shown"
"b" ("Beta" ignore))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-group-if-map
'descriptions))
(output (keymap-popup--render descs)))
(should-not (string-match-p "Alpha" output))
(should (string-match-p "Beta" output))))
(ert-deftest keymap-popup-test-if-on-switch ()
"An :if predicate returning nil makes the switch key act unbound."
(eval '(keymap-popup-define keymap-popup--test-if-sw
"v" ("Verbose" :switch keymap-popup--test-if-sw-var
:if (lambda () nil)))
t)
;; Filter returns nil, so the key resolves to nothing at the keymap level.
(should-not (keymap-lookup keymap-popup--test-if-sw "v"))
(let* ((descs (keymap-popup--meta keymap-popup--test-if-sw
'descriptions))
(output (keymap-popup--render descs)))
(should-not (string-match-p "Verbose" output))))
;;; Keymap-level predicate enforcement
(ert-deftest keymap-popup-test-if-filter-blocks-when-pred-nil ()
"An :if predicate returning nil unbinds the key via menu-item :filter."
(eval '(keymap-popup-define keymap-popup--test-if-block
"x" ("X" ignore :if (lambda () nil)))
t)
(should-not (keymap-lookup keymap-popup--test-if-block "x")))
(ert-deftest keymap-popup-test-if-filter-passes-when-pred-t ()
"An :if predicate returning non-nil exposes the underlying command."
(eval '(keymap-popup-define keymap-popup--test-if-pass
"x" ("X" ignore :if (lambda () t)))
t)
(should (eq (keymap-lookup keymap-popup--test-if-pass "x") #'ignore)))
(ert-deftest keymap-popup-test-inapt-keymap-binding-stays-real ()
"An active :inapt-if leaves the keymap binding untouched.
Enforcement lives in the popup wrapper; the keymap stays honest for
`where-is' and `describe-key'."
(eval '(keymap-popup-define keymap-popup--test-inapt-route
"x" ("X" ignore :inapt-if (lambda () t)))
t)
(should (eq (keymap-lookup keymap-popup--test-inapt-route "x") #'ignore)))
(ert-deftest keymap-popup-test-inapt-filter-passes-when-pred-nil ()
"An inactive :inapt-if predicate exposes the underlying command."
(eval '(keymap-popup-define keymap-popup--test-inapt-pass
"x" ("X" ignore :inapt-if (lambda () nil)))
t)
(should (eq (keymap-lookup keymap-popup--test-inapt-pass "x") #'ignore)))
(ert-deftest keymap-popup-test-dynamic-inapt-toggle ()
"Keymap dispatch is constant regardless of the :inapt-if value.
Enforcement moved to the wrapper; the binding never changes."
(defvar keymap-popup--test-dyn-flag nil)
(eval '(keymap-popup-define keymap-popup--test-dyn-map
"x" ("X" ignore
:inapt-if (lambda () keymap-popup--test-dyn-flag)))
t)
(let ((keymap-popup--test-dyn-flag nil))
(should (eq (keymap-lookup keymap-popup--test-dyn-map "x") #'ignore)))
(let ((keymap-popup--test-dyn-flag t))
(should (eq (keymap-lookup keymap-popup--test-dyn-map "x") #'ignore))))
(ert-deftest keymap-popup-test-direct-dispatch-ignores-inapt ()
"Outside a popup, an inapt key dispatches its real command."
(let ((count 0))
(eval `(keymap-popup-define keymap-popup--test-direct-inapt
"x" ("X" ,(lambda () (interactive) (setq count (1+ count)))
:inapt-if (lambda () t)))
t)
(let ((binding (keymap-lookup keymap-popup--test-direct-inapt "x")))
(should (commandp binding))
(call-interactively binding)
(should (= count 1)))))
(ert-deftest keymap-popup-test-where-is-finds-inapt-command ()
"`where-is-internal' finds a command whose entry is inapt."
(eval '(keymap-popup-define keymap-popup--test-whereis-inapt
"n" ("Next" next-line :inapt-if (lambda () t)))
t)
(should (equal (key-description
(where-is-internal
#'next-line (list keymap-popup--test-whereis-inapt) t))
"n")))
(ert-deftest keymap-popup-test-group-if-blocks-dispatch ()
"Group :if applies to each entry's keymap binding."
(eval '(keymap-popup-define keymap-popup--test-grp-if
:group ("Hidden" :if (lambda () nil))
"a" ("A" ignore))
t)
(should-not (keymap-lookup keymap-popup--test-grp-if "a")))
(ert-deftest keymap-popup-test-group-inapt-keymap-binding-stays-real ()
"Group :inapt-if leaves each entry's keymap binding untouched."
(eval '(keymap-popup-define keymap-popup--test-grp-inapt
:group ("Off" :inapt-if (lambda () t))
"a" ("A" ignore))
t)
(should (eq (keymap-lookup keymap-popup--test-grp-inapt "a") #'ignore)))
(ert-deftest keymap-popup-test-if-and-inapt-combine ()
":if takes precedence over :inapt-if when both are present."
(eval '(keymap-popup-define keymap-popup--test-both
"x" ("X" ignore
:if (lambda () nil)
:inapt-if (lambda () t)))
t)
(should-not (keymap-lookup keymap-popup--test-both "x")))
(ert-deftest keymap-popup-test-no-predicates-binds-bare-command ()
"Entries without predicates are bound directly, not through menu-item."
(eval '(keymap-popup-define keymap-popup--test-bare
"x" ("X" ignore))
t)
(should (eq (keymap-lookup keymap-popup--test-bare "x") #'ignore))
;; Internal: the raw binding is the bare command, not a menu-item form.
(should (eq (lookup-key keymap-popup--test-bare "x") #'ignore)))
;;; Wrapper map tests
(ert-deftest keymap-popup-test-wrapper-map-has-exit-key ()
(eval '(keymap-popup-define keymap-popup--test-wrap
"c" ("Comment" ignore))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-wrap
'descriptions))
(buf (get-buffer-create "*keymap-popup-test*"))
(map (keymap-popup--build-wrapper-map
keymap-popup--test-wrap descs buf "q")))
(unwind-protect
(progn
(should (functionp (keymap-lookup map "q")))
(should (eq (keymap-lookup map "c") #'ignore)))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-wrapper-map-has-c-u ()
(eval '(keymap-popup-define keymap-popup--test-wrap-cu
"c" ("Comment" ignore))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-wrap-cu
'descriptions))
(buf (get-buffer-create "*keymap-popup-test*"))
(map (keymap-popup--build-wrapper-map
keymap-popup--test-wrap-cu descs buf "q")))
(unwind-protect
(should (functionp (keymap-lookup map "C-u")))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-switch-override-refuses-when-inapt ()
"Switch override refuses an inapt press, preserving prefix-mode.
Inaptness is read from the popup's active descriptions at keypress
time; the switch variable must not toggle while inapt."
(defvar keymap-popup--test-sw-flag t)
(eval '(keymap-popup-define keymap-popup--test-sw-inapt
"v" ("Verbose" :switch keymap-popup--test-sw-inapt-var
:inapt-if (lambda () keymap-popup--test-sw-flag)))
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-sw-inapt 'descriptions))
(buf (get-buffer-create keymap-popup--buffer-name)))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--prefix-mode t)
(setq-local keymap-popup--active-descriptions descs))
(let* ((overrides (keymap-popup--switch-overrides
keymap-popup--test-sw-inapt '("v") buf))
(override (cdr (assoc "v" overrides)))
(keymap-popup--test-sw-flag t))
(let ((prefix-arg '(4)))
(call-interactively override)
;; Inapt: refused, var untouched, prefix-mode NOT cleared.
(should-not keymap-popup--test-sw-inapt-var)
(should (buffer-local-value 'keymap-popup--prefix-mode buf)))
;; Flip predicate off: toggle runs, prefix-mode is consumed.
(let ((keymap-popup--test-sw-flag nil)
(prefix-arg '(4)))
(call-interactively override)
(should keymap-popup--test-sw-inapt-var)
(should-not (buffer-local-value 'keymap-popup--prefix-mode buf)))))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-stay-open-override-dispatch ()
"Stay-open override calls the real binding and refreshes in place."
(let ((count 0)
(map (make-sparse-keymap))
(buf (get-buffer-create keymap-popup--buffer-name))
(descs '(((:name nil :entries ((:key "g" :description "Go"
:type suffix :stay-open t)))))))
(keymap-set map "g" (lambda () (interactive) (setq count (1+ count))))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-descriptions descs
keymap-popup--source-buffer buf))
(let* ((overrides (keymap-popup--stay-open-overrides map '("g") buf))
(override (cdr (assoc "g" overrides))))
(call-interactively override)
(should (= count 1))
(should (buffer-live-p buf))))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-inapt-key-p-entry-level ()
(let ((buf (get-buffer-create keymap-popup--buffer-name))
(flag t))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-descriptions
`(((:name nil :entries ((:key "x" :type suffix
:inapt-if ,(lambda () flag))))))))
(should (keymap-popup--inapt-key-p buf "x"))
(setq flag nil)
(should-not (keymap-popup--inapt-key-p buf "x"))
(should-not (keymap-popup--inapt-key-p buf "unknown")))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-inapt-key-p-group-level ()
"A group's :inapt-if applies to its entries; group preds are unmerged."
(let ((buf (get-buffer-create keymap-popup--buffer-name)))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-descriptions
`(((:name "Bulk" :inapt-if ,(lambda () t)
:entries ((:key "x" :type suffix)))))))
(should (keymap-popup--inapt-key-p buf "x")))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-inapt-key-p-dead-buffer ()
"A dead popup buffer reports no inapt keys.
Pins the apt-path ordering: the keep-pred tears the popup down
before the guard override runs, which must fall through to the
real binding."
(let ((buf (get-buffer-create keymap-popup--buffer-name)))
(kill-buffer buf)
(should-not (keymap-popup--inapt-key-p buf "x"))))
(ert-deftest keymap-popup-test-refuse-inapt-preserves-prefix-mode ()
(let ((buf (get-buffer-create keymap-popup--buffer-name)))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--prefix-mode t))
(let ((prefix-arg nil))
(keymap-popup--refuse-inapt buf)
(should (equal prefix-arg '(4))))
(with-current-buffer buf
(setq-local keymap-popup--prefix-mode nil))
(let ((prefix-arg nil))
(keymap-popup--refuse-inapt buf)
(should-not prefix-arg)))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-classify-inapt-guards ()
"Only plain suffixes with an entry or group :inapt-if become guards."
(let* ((pred (lambda () t))
(descs `(((:name nil
:entries ((:key "a" :type suffix :inapt-if ,pred)
(:key "g" :type suffix :stay-open t :inapt-if ,pred)
(:key "v" :type switch :variable x :inapt-if ,pred)
(:key "c" :type suffix)))
(:name "Bulk" :inapt-if ,pred
:entries ((:key "b" :type suffix))))))
(classified (keymap-popup--classify-entries descs)))
(should (equal (plist-get classified :inapt-guards) '("a" "b")))))
(ert-deftest keymap-popup-test-inapt-guard-refuses ()
(let* ((count 0)
(map (make-sparse-keymap))
(buf (get-buffer-create keymap-popup--buffer-name)))
(keymap-set map "x" (lambda () (interactive) (setq count (1+ count))))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-descriptions
`(((:name nil :entries ((:key "x" :type suffix
:inapt-if ,(lambda () t))))))))
(let* ((overrides (keymap-popup--inapt-guard-overrides map '("x") buf))
(override (cdr (assoc "x" overrides))))
(call-interactively override)
(should (= count 0))))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-inapt-guard-apt-calls-real-binding ()
(let* ((count 0)
(map (make-sparse-keymap))
(buf (get-buffer-create keymap-popup--buffer-name)))
(keymap-set map "x" (lambda () (interactive) (setq count (1+ count))))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-descriptions
`(((:name nil :entries ((:key "x" :type suffix
:inapt-if ,(lambda () nil))))))))
(let* ((overrides (keymap-popup--inapt-guard-overrides map '("x") buf))
(override (cdr (assoc "x" overrides))))
(call-interactively override)
(should (= count 1))))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-inapt-guard-runs-after-popup-close ()
"The guard dispatches the real binding when the popup is already dead."
(let* ((count 0)
(map (make-sparse-keymap))
(buf (get-buffer-create keymap-popup--buffer-name)))
(keymap-set map "x" (lambda () (interactive) (setq count (1+ count))))
(let* ((overrides (keymap-popup--inapt-guard-overrides map '("x") buf))
(override (cdr (assoc "x" overrides))))
(kill-buffer buf)
(call-interactively override)
(should (= count 1)))))
(ert-deftest keymap-popup-test-keep-pred-keeps-popup-open-on-inapt-key ()
(let ((buf (get-buffer-create keymap-popup--buffer-name))
(flag t))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-exit-key "q"
keymap-popup--reentering nil
keymap-popup--persistent nil
keymap-popup--active-descriptions
`(((:name nil :entries ((:key "x" :type suffix
:inapt-if ,(lambda () flag))))))))
(let ((keep-pred (keymap-popup--make-keep-pred buf))
(this-command 'keymap-popup--test-dummy-cmd))
(cl-letf (((symbol-function 'this-command-keys-vector)
(lambda () [?x])))
(should (funcall keep-pred))
(setq flag nil)
(should-not (funcall keep-pred)))))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-submenu-override-refuses-when-inapt ()
"An inapt submenu key is refused instead of pushed."
(let ((buf (get-buffer-create keymap-popup--buffer-name))
(pushed nil)
(flag t))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-descriptions
`(((:name nil :entries ((:key "s" :type keymap :target sub
:inapt-if ,(lambda () flag))))))))
(cl-letf (((symbol-function 'keymap-popup--push-submenu)
(lambda (_buf target) (setq pushed target))))
(let* ((overrides (keymap-popup--submenu-overrides '(("s" . sub)) buf))
(override (cdr (assoc "s" overrides))))
(call-interactively override)
(should-not pushed)
(setq flag nil)
(call-interactively override)
(should (eq pushed 'sub)))))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-stay-open-override-refuses-when-inapt ()
(let* ((count 0)
(map (make-sparse-keymap))
(buf (get-buffer-create keymap-popup--buffer-name)))
(keymap-set map "g" (lambda () (interactive) (setq count (1+ count))))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--source-buffer buf
keymap-popup--active-descriptions
`(((:name nil :entries ((:key "g" :type suffix :stay-open t
:inapt-if ,(lambda () t))))))))
(let* ((overrides (keymap-popup--stay-open-overrides map '("g") buf))
(override (cdr (assoc "g" overrides))))
(call-interactively override)
(should (= count 0))
(should (buffer-live-p buf))))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-annotate-inapt-enforced-in-wrapper ()
"Annotate-path popups gain :inapt-if dispatch enforcement.
The annotate macro never wraps bindings, so enforcement can only
come from the wrapper."
(setq keymap-popup--test-annotate-map (make-sparse-keymap))
(keymap-set keymap-popup--test-annotate-map "a" #'forward-char)
(eval '(keymap-popup-annotate keymap-popup--test-annotate-map
:group "Move"
forward-char ("Forward" :inapt-if (lambda () t)))
t)
(let* ((descs (keymap-popup--resolve-descriptions
(keymap-popup--collect-descriptions keymap-popup--test-annotate-map)
keymap-popup--test-annotate-map))
(buf (get-buffer-create keymap-popup--buffer-name)))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-descriptions descs))
(let* ((wrapper (keymap-popup--build-wrapper-map
keymap-popup--test-annotate-map descs buf "q"))
(binding (keymap-lookup wrapper "a")))
(should (functionp binding))
(should-not (eq binding #'forward-char))
(with-temp-buffer
(insert "ab")
(goto-char (point-min))
(call-interactively binding)
(should (= (point) (point-min))))))
(kill-buffer buf))))
(ert-deftest keymap-popup-test-classify-submenus ()
"Keymap entries are classified as submenus."
(let* ((descs (list (list (list :name nil
:entries (list (list :key "a" :type 'keymap :target 'sub)
(list :key "c" :type 'suffix))))))
(classified (keymap-popup--classify-entries descs)))
(should (equal (plist-get classified :submenus) '(("a" . sub))))))
(ert-deftest keymap-popup-test-classify-stay-open ()
"Stay-open suffix entries are classified."
(let* ((descs (list (list (list :name nil
:entries (list (list :key "g" :type 'suffix :stay-open t)
(list :key "v" :type 'switch :variable 'x)
(list :key "c" :type 'suffix))))))
(classified (keymap-popup--classify-entries descs)))
(should (equal (plist-get classified :stay-open) '("g")))))
(ert-deftest keymap-popup-test-push-submenu-state ()
"Pushing a sub-menu stacks parent state and activates the child's wrapper."
(eval '(keymap-popup-define keymap-popup--test-push-child
"Child." "c" ("Child cmd" ignore))
t)
(let ((buf (get-buffer-create keymap-popup--buffer-name))
(parent-map (make-sparse-keymap))
(parent-wrapper (make-sparse-keymap))
(received nil))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--source-buffer buf
keymap-popup--active-keymap parent-map
keymap-popup--active-descriptions '(((:name nil :entries nil)))
keymap-popup--active-docstring nil
keymap-popup--active-exit-key "q"
keymap-popup--wrapper-map parent-wrapper
keymap-popup--exit-function #'ignore
keymap-popup--stack nil))
(cl-letf (((symbol-function 'set-transient-map)
(lambda (map &rest _) (setq received map))))
(keymap-popup--push-submenu buf keymap-popup--test-push-child))
(with-current-buffer buf
(should (= (length keymap-popup--stack) 1))
(should (eq (plist-get (car keymap-popup--stack) :keymap) parent-map))
(should (eq (plist-get (car keymap-popup--stack) :wrapper-map)
parent-wrapper))
(should (eq (plist-get (car keymap-popup--stack) :exit-function)
#'ignore))
(should (eq keymap-popup--active-keymap keymap-popup--test-push-child))
(should keymap-popup--wrapper-map)
(should (eq received keymap-popup--wrapper-map))))
(kill-buffer buf))))
;;; Add/remove entry tests
(ert-deftest keymap-popup-test-add-entry ()
(eval '(keymap-popup-define keymap-popup--test-add
:group "Actions"
"c" ("Comment" ignore))
t)
(keymap-popup-add-entry keymap-popup--test-add "z" "New" #'forward-char "Actions")
(should (eq (keymap-lookup keymap-popup--test-add "z") #'forward-char))
(let* ((descs (keymap-popup--meta keymap-popup--test-add
'descriptions))
(output (keymap-popup--render descs)))
(should (string-match-p "New" output))))
(ert-deftest keymap-popup-test-add-entry-replaces-existing ()
"Adding an entry whose key already exists replaces the prior entry."
(eval '(keymap-popup-define keymap-popup--test-add-replace
:group "Actions"
"c" ("Old comment" ignore))
t)
(keymap-popup-add-entry keymap-popup--test-add-replace
"c" "New comment" #'backward-char "Actions")
(should (eq (keymap-lookup keymap-popup--test-add-replace "c") #'backward-char))
(let* ((descs (keymap-popup--meta keymap-popup--test-add-replace 'descriptions))
(output (keymap-popup--render descs)))
(should (string-match-p "New comment" output))
(should-not (string-match-p "Old comment" output))))
(ert-deftest keymap-popup-test-add-entry-moves-across-groups ()
"Re-adding a key under a different group removes it from the original group."
(eval '(keymap-popup-define keymap-popup--test-add-move
:group "Old"
"x" ("X-old" ignore)
:group "New"
"n" ("Anchor" ignore))
t)
(keymap-popup-add-entry keymap-popup--test-add-move
"x" "X-new" #'forward-char "New")
(let* ((descs (keymap-popup--meta keymap-popup--test-add-move 'descriptions))
(groups (cl-loop for row in descs append row))
(old (cl-find "Old" groups :key (lambda (g) (plist-get g :name))
:test #'equal))
(new (cl-find "New" groups :key (lambda (g) (plist-get g :name))
:test #'equal))
(new-keys (mapcar (lambda (e) (plist-get e :key))
(plist-get new :entries))))
(should (null (plist-get old :entries)))
(should (member "x" new-keys))
(should (member "n" new-keys))))
(ert-deftest keymap-popup-test-remove-entry ()
(eval '(keymap-popup-define keymap-popup--test-rm
:group "Actions"
"c" ("Comment" ignore)
"r" ("Reply" ignore))
t)
(keymap-popup-remove-entry keymap-popup--test-rm "r")
(should (null (keymap-lookup keymap-popup--test-rm "r")))
(let* ((descs (keymap-popup--meta keymap-popup--test-rm
'descriptions))
(output (keymap-popup--render descs)))
(should (string-match-p "Comment" output))
(should-not (string-match-p "Reply" output))))
(ert-deftest keymap-popup-test-add-remove-preserve-group-props ()
"Group :if survives `keymap-popup-add-entry' and `keymap-popup-remove-entry'."
(eval '(keymap-popup-define keymap-popup--test-group-props
:group ("Actions" :if (lambda () t))
"c" ("Comment" ignore)
"r" ("Reply" ignore))
t)
(keymap-popup-add-entry keymap-popup--test-group-props
"z" "New" #'forward-char "Actions")
(keymap-popup-remove-entry keymap-popup--test-group-props "r")
(let* ((descs (keymap-popup--meta keymap-popup--test-group-props
'descriptions))
(group (caar descs)))
(should (functionp (plist-get group :if)))
(should (equal (mapcar (lambda (e) (plist-get e :key))
(plist-get group :entries))
'("c" "z")))))
;;; Annotate tests
(defvar keymap-popup--test-annotate-map
(let ((map (make-sparse-keymap)))
(keymap-set map "a" #'forward-char)
(keymap-set map "b" #'backward-char)
(keymap-set map "c" #'kill-line)
map))
(ert-deftest keymap-popup-test-annotate-parse ()
(let ((entry (keymap-popup--parse-entry 'forward-char '("Forward"))))
(should (eq (plist-get entry :command) 'forward-char))
(should-not (plist-get entry :key))
(should (equal (plist-get entry :description) "Forward"))))
(ert-deftest keymap-popup-test-annotate-parse-with-props ()
(let ((entry (keymap-popup--parse-entry 'forward-char '("Forward" :stay-open t))))
(should (eq (plist-get entry :command) 'forward-char))
(should (plist-get entry :stay-open))))
(ert-deftest keymap-popup-test-annotate-parse-bare-string ()
(let ((entry (keymap-popup--parse-entry 'forward-char "Forward")))
(should (eq (plist-get entry :command) 'forward-char))
(should (equal (plist-get entry :description) "Forward"))))
(ert-deftest keymap-popup-test-annotate-parse-lambda-description ()
"Bare lambda as description is preserved, not destructured."
(let* ((desc '(lambda () (if t "On" "Off")))
(entry (keymap-popup--parse-entry 'forward-char desc)))
(should (equal (plist-get entry :description) desc))
(should (eq (plist-get entry :command) 'forward-char))))
(ert-deftest keymap-popup-test-resolve-key ()
(let* ((entry (list :key nil :description "Forward" :type 'suffix
:command 'forward-char))
(resolved (keymap-popup--resolve-key entry keymap-popup--test-annotate-map)))
(should resolved)
(should (equal (plist-get resolved :key) "a"))))
(ert-deftest keymap-popup-test-resolve-key-unbound ()
(let ((entry (list :key nil :description "Nope" :type 'suffix
:command 'some-nonexistent-command-xyz)))
(should-not (keymap-popup--resolve-key entry keymap-popup--test-annotate-map))))
(ert-deftest keymap-popup-test-resolve-key-keeps-current-stored-key ()
"A stored key that still dispatches to its command is kept as-is."
(let ((map (make-sparse-keymap))
(entry (list :key "n" :description "Next" :type 'suffix
:command 'next-line)))
(keymap-set map "n" #'next-line)
(should (eq (keymap-popup--resolve-key entry map) entry))))
(ert-deftest keymap-popup-test-resolve-key-follows-rebinding ()
"A rebound command resolves to its current key, not the stored one."
(let ((map (make-sparse-keymap))
(entry (list :key "n" :description "Next" :type 'suffix
:command 'next-line)))
(keymap-set map "j" #'next-line)
(should (equal (plist-get (keymap-popup--resolve-key entry map) :key)
"j"))))
(ert-deftest keymap-popup-test-resolve-key-stored-key-fallback ()
"A stored key survives when the command has no binding in the map."
(let ((map (make-sparse-keymap))
(entry (list :key "n" :description "Next" :type 'suffix
:command 'next-line)))
(should (equal (plist-get (keymap-popup--resolve-key entry map) :key)
"n"))))
(ert-deftest keymap-popup-test-resolve-key-ignores-global-map ()
"Resolution never falls back to global bindings (C-n is global next-line)."
(let ((map (make-sparse-keymap))
(entry (list :key nil :description "Next" :type 'suffix
:command 'next-line)))
(should-not (keymap-popup--resolve-key entry map))))
(ert-deftest keymap-popup-test-resolve-key-keeps-stored-key-when-if-hidden ()
"An entry hidden by an :if filter keeps its stored key.
The filter makes the key act unbound, so `where-is-internal' cannot
find the command; the stored key must survive (render hides the
entry independently)."
(let* ((map (make-sparse-keymap))
(wrapped (eval (keymap-popup--wrap-binding-form
'(function next-line) (lambda () nil))
t))
(entry (list :key "n" :description "Next" :type 'suffix
:command 'next-line :if (lambda () nil))))
(keymap-set map "n" wrapped)
(should (equal (plist-get (keymap-popup--resolve-key entry map) :key)
"n"))))
(ert-deftest keymap-popup-test-resolve-key-no-command-entry-kept ()
"Entries without :command (e.g. pre-groundwork metadata) pass through."
(let ((map (make-sparse-keymap))
(entry (list :key "s" :description "Sub" :type 'keymap
:target (make-sparse-keymap))))
(should (eq (keymap-popup--resolve-key entry map) entry))))
(ert-deftest keymap-popup-test-define-rebound-key-updates-popup ()
"Rebinding a command after keymap-popup-define updates the shown key."
(eval '(keymap-popup-define keymap-popup--test-rebind-map
:group "Nav"
"n" ("Next" next-line))
t)
(keymap-unset keymap-popup--test-rebind-map "n" t)
(keymap-set keymap-popup--test-rebind-map "j" #'next-line)
(let* ((resolved (keymap-popup--resolve-descriptions
(keymap-popup--collect-descriptions
keymap-popup--test-rebind-map)
keymap-popup--test-rebind-map))
(entry (car (plist-get (caar resolved) :entries))))
(should (equal (plist-get entry :key) "j"))))
(ert-deftest keymap-popup-test-define-rebound-switch-updates-popup ()
"Rebinding a generated toggle command updates the shown key."
(eval '(keymap-popup-define keymap-popup--test-rebind-sw-map
:group "Toggles"
"v" ("Verbose" :switch keymap-popup--test-rebind-sw-var))
t)
(keymap-unset keymap-popup--test-rebind-sw-map "v" t)
(keymap-set keymap-popup--test-rebind-sw-map "V"
(keymap-popup--toggle-name 'keymap-popup--test-rebind-sw-map
'keymap-popup--test-rebind-sw-var))
(let* ((resolved (keymap-popup--resolve-descriptions
(keymap-popup--collect-descriptions
keymap-popup--test-rebind-sw-map)
keymap-popup--test-rebind-sw-map))
(entry (car (plist-get (caar resolved) :entries))))
(should (equal (plist-get entry :key) "V"))))
(ert-deftest keymap-popup-test-resolve-descriptions ()
(let* ((rows (list (list (list :name "Test"
:entries (list (list :key nil :description "Forward"
:type 'suffix :command 'forward-char)
(list :key nil :description "Nope"
:type 'suffix :command 'nonexistent-xyz))))))
(resolved (keymap-popup--resolve-descriptions rows keymap-popup--test-annotate-map))
(entries (plist-get (car (car resolved)) :entries)))
(should (= (length entries) 1))
(should (equal (plist-get (car entries) :key) "a"))))
(ert-deftest keymap-popup-test-resolve-descriptions-deduplicates-keys ()
"Annotated entries resolving to the same key keep the first description."
(let* ((map (make-sparse-keymap))
(rows '(((:name "Child" :entries
((:key nil :description "Child" :type suffix
:command next-line)))
(:name "Parent" :entries
((:key "n" :description "Parent" :type suffix
:command next-line)))))))
(keymap-set map "n" #'next-line)
(let* ((resolved (keymap-popup--resolve-descriptions rows map))
(entries (keymap-popup--collect-entries
resolved (lambda (entry _group) entry))))
(should (= (length entries) 1))
(should (equal (plist-get (car entries) :description) "Child")))))
(ert-deftest keymap-popup-test-annotate-macro ()
(eval '(keymap-popup-annotate keymap-popup--test-annotate-map
:group "Move"
forward-char "Forward"
backward-char "Backward")
t)
(let* ((descs (keymap-popup--meta keymap-popup--test-annotate-map
'descriptions))
(entries (plist-get (car (car descs)) :entries)))
(should (= (length entries) 2))
(should (eq (plist-get (car entries) :command) 'forward-char))))
(ert-deftest keymap-popup-test-annotate-exit-key ()
"Annotate with :exit-key sets metadata."
(setq keymap-popup--test-annotate-map (make-sparse-keymap))
(keymap-set keymap-popup--test-annotate-map "a" #'forward-char)
(eval '(keymap-popup-annotate keymap-popup--test-annotate-map
:exit-key "x"
:group "Move"
forward-char "Forward")
t)
(should (equal (keymap-popup--meta keymap-popup--test-annotate-map
'exit-key)
"x")))
(ert-deftest keymap-popup-test-annotate-popup-key ()
"Annotate with :popup-key binds the popup command."
(setq keymap-popup--test-annotate-map (make-sparse-keymap))
(keymap-set keymap-popup--test-annotate-map "a" #'forward-char)
(eval '(keymap-popup-annotate keymap-popup--test-annotate-map
:popup-key "?"
:group "Move"
forward-char "Forward")
t)
(should (functionp (keymap-lookup keymap-popup--test-annotate-map "?"))))
(ert-deftest keymap-popup-test-annotate-description ()
"Annotate with :description sets metadata."
(setq keymap-popup--test-annotate-map (make-sparse-keymap))
(keymap-set keymap-popup--test-annotate-map "a" #'forward-char)
(eval '(keymap-popup-annotate keymap-popup--test-annotate-map
:description "My commands"
:group "Move"
forward-char "Forward")
t)
(should (equal (keymap-popup--meta keymap-popup--test-annotate-map
'description)
"My commands")))
(ert-deftest keymap-popup-test-annotate-no-defaults-baked ()
"Annotate without keywords sets no exit-key or description metadata."
(setq keymap-popup--test-annotate-map (make-sparse-keymap))
(keymap-set keymap-popup--test-annotate-map "a" #'forward-char)
(eval '(keymap-popup-annotate keymap-popup--test-annotate-map
:group "Move"
forward-char "Forward")
t)
(should-not (keymap-popup--meta keymap-popup--test-annotate-map
'exit-key))
(should-not (keymap-popup--meta keymap-popup--test-annotate-map
'description)))
;;; Metadata tests
(ert-deftest keymap-popup-test-meta-read-write ()
(let ((map (make-sparse-keymap)))
(setf (keymap-popup--meta map 'descriptions) '(test-data))
(should (equal (keymap-popup--meta map 'descriptions) '(test-data)))))
(ert-deftest keymap-popup-test-meta-nil-for-missing ()
(let ((map (make-sparse-keymap)))
(should (null (keymap-popup--meta map 'descriptions)))))
(ert-deftest keymap-popup-test-attach-meta-stores-all ()
(let* ((map (make-sparse-keymap))
(result (keymap-popup--attach-meta map '(rows)
:exit-key "x"
:description "Doc"
:persistent t)))
(should (eq result map))
(should (equal (keymap-popup--meta map 'descriptions) '(rows)))
(should (equal (keymap-popup--meta map 'exit-key) "x"))
(should (equal (keymap-popup--meta map 'description) "Doc"))
(should (eq (keymap-popup--meta map 'persistent) 'yes))))
(ert-deftest keymap-popup-test-attach-meta-omits-nil-opts ()
(let ((map (make-sparse-keymap)))
(keymap-popup--attach-meta map '(rows))
(should (equal (keymap-popup--meta map 'descriptions) '(rows)))
(should-not (keymap-popup--meta map 'exit-key))
(should-not (keymap-popup--meta map 'description))
(should-not (keymap-popup--meta map 'persistent))))
(ert-deftest keymap-popup-test-attach-meta-clears-stale-opts ()
"Reattaching without options removes values from the previous attachment."
(let ((map (make-sparse-keymap)))
(keymap-popup--attach-meta map '(old)
:exit-key "x"
:description "Old"
:persistent t)
(keymap-popup--attach-meta map '(new))
(should (equal (keymap-popup--meta map 'descriptions) '(new)))
(should-not (keymap-popup--meta map 'exit-key))
(should-not (keymap-popup--meta map 'description))
(should-not (keymap-popup--meta map 'persistent))))
(ert-deftest keymap-popup-test-attach-meta-ignores-unknown-opts ()
(let ((map (make-sparse-keymap)))
(keymap-popup--attach-meta map '(rows) :popup-key "?")
(should (equal (keymap-popup--meta map 'descriptions) '(rows)))
(should-not (keymap-popup--meta map 'popup-key))))
(ert-deftest keymap-popup-test-attach-parses-keyed-bindings ()
"Runtime attach parses annotate-shaped bindings into description rows."
(let ((map (make-sparse-keymap)))
(keymap-set map "a" #'ignore)
(should (eq (keymap-popup-attach map '("a" ("Ignore" ignore))) map))
(let* ((rows (keymap-popup--meta map 'descriptions))
(entry (car (plist-get (caar rows) :entries))))
(should (equal (plist-get entry :key) "a"))
(should (equal (plist-get entry :description) "Ignore"))
(should (eq (plist-get entry :command) 'ignore)))))
(ert-deftest keymap-popup-test-attach-stores-opts ()
(let ((map (make-sparse-keymap)))
(keymap-popup-attach map '("a" ("Ignore" ignore))
:exit-key "x" :description "Doc" :persistent t)
(should (equal (keymap-popup--meta map 'exit-key) "x"))
(should (equal (keymap-popup--meta map 'description) "Doc"))
(should (eq (keymap-popup--meta map 'persistent) 'yes))))
(ert-deftest keymap-popup-test-attach-runtime-built-menu ()
"Entries computed from data render and resolve against the live keymap."
(let* ((map (make-sparse-keymap))
(items '(("1" . next-line) ("2" . previous-line)))
(bindings (cl-loop for (key . cmd) in items
append (list key (list (symbol-name cmd) cmd)))))
(cl-loop for (key . cmd) in items do (keymap-set map key cmd))
(keymap-popup-attach map (append '(:group "Nav") bindings))
(let* ((resolved (keymap-popup--resolve-descriptions
(keymap-popup--collect-descriptions map) map))
(group (caar resolved))
(keys (mapcar (lambda (e) (plist-get e :key))
(plist-get group :entries))))
(should (equal (plist-get group :name) "Nav"))
(should (equal keys '("1" "2"))))))
(ert-deftest keymap-popup-test-attach-annotated-symbols-resolve ()
"Command-symbol bindings get keys from `where-is-internal' at resolve time."
(let ((map (make-sparse-keymap)))
(keymap-set map "n" #'next-line)
(keymap-popup-attach map '(next-line "Next"))
(let* ((resolved (keymap-popup--resolve-descriptions
(keymap-popup--collect-descriptions map) map))
(entry (car (plist-get (caar resolved) :entries))))
(should (equal (plist-get entry :key) "n"))
(should (equal (plist-get entry :description) "Next")))))
(ert-deftest keymap-popup-test-no-descriptions-error ()
(let ((map (make-sparse-keymap)))
(should-error (keymap-popup map) :type 'user-error)))
(ert-deftest keymap-popup-test-dismiss-is-command ()
(should (commandp #'keymap-popup-dismiss)))
(ert-deftest keymap-popup-test-dismiss-cleans-real-transient-maps ()
"Dismiss removes nested transient maps and their pre-command hooks."
(let ((overriding-terminal-local-map nil)
(pre-command-hook nil)
(parent (make-sparse-keymap))
(child (make-sparse-keymap))
(descriptions '(((:name nil :entries nil))))
(buf (get-buffer-create keymap-popup--buffer-name)))
(unwind-protect
(progn
(keymap-popup--attach-meta parent descriptions)
(keymap-popup--attach-meta child descriptions)
(with-current-buffer buf
(setq-local keymap-popup--source-buffer buf
keymap-popup--active-keymap parent
keymap-popup--active-descriptions descriptions
keymap-popup--active-exit-key "q"
keymap-popup--display-backend
(list :show #'ignore :fit #'ignore :hide #'ignore)))
(keymap-popup--activate-transient-map
buf parent descriptions "q")
(keymap-popup--push-submenu buf child)
(should overriding-terminal-local-map)
(should (= (length pre-command-hook) 2))
(keymap-popup-dismiss)
(should-not overriding-terminal-local-map)
(should-not pre-command-hook)
(should-not (buffer-live-p buf)))
(when (buffer-live-p buf)
(kill-buffer buf)))))
(ert-deftest keymap-popup-test-teardown-removes-persistent-hook ()
"Teardown removes the popup's persistent post-command hook immediately."
(let ((post-command-hook nil)
(buf (get-buffer-create "*keymap-popup-test-persistent*")))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--display-backend
(list :show #'ignore :fit #'ignore :hide #'ignore)))
(keymap-popup--install-persistent-hook buf)
(should (= (length post-command-hook) 1))
(keymap-popup--teardown buf)
(should-not post-command-hook)
(should-not (buffer-live-p buf)))
(when (buffer-live-p buf)
(kill-buffer buf)))))
(ert-deftest keymap-popup-test-new-session-replaces-active-session ()
"Opening another popup first removes the prior session's maps and hooks."
(let ((overriding-terminal-local-map nil)
(pre-command-hook nil)
(post-command-hook nil)
(keymap-popup-persistent t)
(keymap-popup-backend
(lambda () (list :show #'ignore :fit #'ignore :hide #'ignore)))
(map (make-sparse-keymap)))
(unwind-protect
(progn
(keymap-set map "x" #'ignore)
(keymap-popup-attach map '("x" ("Ignore" ignore)))
(with-temp-buffer
(keymap-popup map)
(should (= (length pre-command-hook) 1))
(should (= (length post-command-hook) 1))
(keymap-popup map)
(should (= (length pre-command-hook) 1))
(should (= (length post-command-hook) 1))
(keymap-popup-dismiss)
(should-not overriding-terminal-local-map)
(should-not pre-command-hook)
(should-not post-command-hook)))
(when (get-buffer keymap-popup--buffer-name)
(keymap-popup-dismiss)))))
(ert-deftest keymap-popup-test-on-exit-tears-down-for-suffix ()
"On-exit tears down when a suffix (non-exit-key) caused the exit."
(let ((buf (get-buffer-create "*keymap-popup-test-exit*")))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-exit-key "q")
(setq-local keymap-popup--stack '((:keymap nil :descriptions nil
:docstring nil :exit-key "q")))
(setq-local keymap-popup--display-backend
(list :show #'ignore :fit #'ignore :hide #'ignore)))
(let ((on-exit (keymap-popup--make-on-exit buf)))
(cl-letf (((symbol-function 'this-command-keys-vector)
(lambda () [?a])))
(funcall on-exit))
(should-not (buffer-live-p buf))))
(when (buffer-live-p buf)
(kill-buffer buf)))))
(ert-deftest keymap-popup-test-on-exit-pops-for-exit-key ()
"On-exit pops to parent when exit-key caused the exit."
(let ((buf (get-buffer-create "*keymap-popup-test-pop*"))
(parent-map (make-sparse-keymap))
(parent-wrapper (make-sparse-keymap))
(descs '(((:name nil :entries nil)))))
(unwind-protect
(progn
(with-current-buffer buf
(setq-local keymap-popup--active-exit-key "q")
(setq-local keymap-popup--active-keymap (make-sparse-keymap))
(setq-local keymap-popup--wrapper-map (make-sparse-keymap))
(setq-local keymap-popup--active-descriptions descs)
(setq-local keymap-popup--active-docstring nil)
(setq-local keymap-popup--source-buffer buf)
(setq-local keymap-popup--stack
(list (list :keymap parent-map
:descriptions descs
:docstring nil
:exit-key "x"
:wrapper-map parent-wrapper
:exit-function #'ignore)))
(setq-local keymap-popup--display-backend
(list :show #'ignore :fit #'ignore :hide #'ignore)))
(let ((on-exit (keymap-popup--make-on-exit buf)))
(cl-letf (((symbol-function 'this-command-keys-vector)
(lambda () [?q])))
(funcall on-exit))
(should (buffer-live-p buf))
(with-current-buffer buf
(should (eq keymap-popup--active-keymap parent-map))
(should (equal keymap-popup--active-exit-key "x"))
(should (eq keymap-popup--wrapper-map parent-wrapper))
(should (eq keymap-popup--exit-function #'ignore))
(should-not keymap-popup--stack))))
(when (buffer-live-p buf)
(kill-buffer buf)))))
(provide 'keymap-popup-tests)
;;; keymap-popup-tests.el ends here