pax_global_header00006660000000000000000000000064152332545010014512gustar00rootroot0000000000000052 comment=b5970885ad19209da1f53bd3ad5872fae2f511ad emacs-keymap-popup-0.4.1/000077500000000000000000000000001523325450100152315ustar00rootroot00000000000000emacs-keymap-popup-0.4.1/.elpaignore000066400000000000000000000001051523325450100173530ustar00rootroot00000000000000CONTRIBUTING.org LICENSE Makefile flake.lock flake.nix tests decks emacs-keymap-popup-0.4.1/.gitignore000066400000000000000000000001651523325450100172230ustar00rootroot00000000000000research *.elc *-autoloads.el *-pkg.el .* !.gitignore !.elpaignore \#* *.md *.info *.texi refs/* tests/live-test.elemacs-keymap-popup-0.4.1/AGENTS.md000066400000000000000000000060351523325450100165400ustar00rootroot00000000000000# AGENTS.md Public guidance for contributors and coding agents working on `keymap-popup`. ## Project `keymap-popup` adds popup help to ordinary Emacs keymaps. The `keymap-popup-define` macro creates a real `defvar-keymap`, `keymap-popup-annotate` describes an existing keymap, and `keymap-popup` displays either form interactively. The package requires Emacs 29.1+ and has no external runtime dependencies. ## Design and architecture - Keep one definition for direct dispatch and popup help. The resulting value must remain a normal keymap compatible with `where-is`, `describe-bindings`, `keymap-set`, parent maps, and standard keymap composition. - Parsers validate and normalize declarations into plain plist/alist data. The macros build keymap bindings and attach descriptions as metadata on the keymap value through `keymap-popup--attach-meta`. - `keymap-popup--render` is the computation boundary: descriptions and current state in, propertized text out. Buffer and window effects belong elsewhere. - The wrapper map parents the source keymap and overrides only behavior needed while the popup is active. Unhandled keys continue through the source map. - Popup lifecycle uses `set-transient-map` and one buffer-local session. Nested menus stack navigation state; dismissal must unwind every active map and hook. - `:if` controls the underlying binding through a `menu-item` filter. `:inapt-if` is popup-only: it changes presentation and refuses the key while leaving direct dispatch outside the popup unchanged. ## Constraints and conventions - Use lexical binding. Public names use `keymap-popup-`; internal helpers use `keymap-popup--`. - Prefer small pure transformations, explicit arguments, and plain alists or plists. Keep buffer insertion, display, hooks, and command execution at clear boundaries. - Preserve the additive design: the keymap must work without opening a popup. Do not introduce a parallel command registry or hidden ownership of user state. - Keep predicate evaluation in its intentional layers: dispatch reads the live keymap; rendering reads normalized descriptions. Do not merge these paths just to remove apparent duplication. - Complex infix systems and stateful sub-prefix languages are outside this package's scope. - Add focused ERT coverage for parser validation, macro expansion, metadata, predicates, wrapper dispatch, nested menus, persistence, and cleanup. ## Verification The Makefile enters the Nix development environment when available. ```sh make test # Run the ERT suite make lint # Run checkdoc and package-lint make compile # Byte-compile keymap-popup.el make doc # Build the Info manual make dev # Compile, lint, and test ``` Run `make dev` before submission. Run `make doc` when changing user-facing syntax or documentation. ## Contributions Send patches to with a subject like `[PATCH emacs-keymap-popup] Short description`. Send bugs and feature requests to with a subject like `[BUG emacs-keymap-popup] Short description`. emacs-keymap-popup-0.4.1/LICENSE000066400000000000000000001045161523325450100162450ustar00rootroot00000000000000 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.1/Makefile000066400000000000000000000033361523325450100166760ustar00rootroot00000000000000.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.1/README.org000066400000000000000000000051461523325450100167050ustar00rootroot00000000000000#+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.1/docs/000077500000000000000000000000001523325450100161615ustar00rootroot00000000000000emacs-keymap-popup-0.4.1/docs/keymap-popup.org000066400000000000000000000362031523325450100213250ustar00rootroot00000000000000#+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= accepts the display keywords above except =:parent=, 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. Declarations are checked when the macro expands. Invalid keys, malformed entries, missing switch variables or sub-menu targets, duplicate or unknown properties, and unsupported options report the offending entry directly. ** 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. Use =:persistent nil= on a definition or annotation to disable a non-nil global default for that keymap. ** 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. Function symbols may precede their definitions; they must be callable when the popup uses them. 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. Runtime values and options are validated before metadata is attached. 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.1/flake.lock000066400000000000000000000010671523325450100171710ustar00rootroot00000000000000{ "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.1/flake.nix000066400000000000000000000066671523325450100170520ustar00rootroot00000000000000{ 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.1/keymap-popup.el000066400000000000000000002154651523325450100202170ustar00rootroot00000000000000;;; keymap-popup.el --- Described keymaps with popup help -*- lexical-binding: t; -*- ;; Copyright (C) 2026 Free Software Foundation, Inc. ;; Author: Thanos Apollo ;; Version: 0.4.1 ;; Package-Requires: ((emacs "29.1")) ;; Keywords: convenience ;; URL: https://git.thanosapollo.org/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. ;; ;; Rendering is pure: commands mutate state in the user's buffer and the ;; popup re-reads it on refresh. A compact session plist owns only popup ;; navigation, transient-map, and display lifecycle state. ;;; 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-let* ((active (plist-get keymap-popup--session :active)) (exit-key (plist-get active :exit-key))) (propertize (format " %s " exit-key) 'face 'keymap-popup-key))) " " (:eval (or (plist-get (plist-get keymap-popup--session :active) :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 and 'no 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 `yes' or `no' because metadata lives in `define-key' bindings, where t means \"default binding\". Returns KEYMAP." (let ((persistent (and (plist-member opts :persistent) (if (plist-get opts :persistent) 'yes 'no)))) (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) persistent)) keymap) ;;; Parsers (defconst keymap-popup--entry-properties '(:if :inapt-if :stay-open :c-u) "Properties accepted by popup entries.") (defconst keymap-popup--group-properties '(:if :inapt-if) "Properties accepted by popup groups.") (defun keymap-popup--invalid (context format-string &rest args) "Signal an invalid popup declaration in CONTEXT. FORMAT-STRING and ARGS describe the error." (error "keymap-popup: %s: %s" context (apply #'format format-string args))) (defun keymap-popup--parse-properties (properties allowed context) "Parse PROPERTIES accepted by ALLOWED for CONTEXT. The :stay-open property may omit its value." (named-let parse ((rest properties) (seen nil)) (cond ((null rest) nil) ((not (consp rest)) (keymap-popup--invalid context "malformed property list")) (t (let ((property (car rest))) (unless (keywordp property) (keymap-popup--invalid context "expected property, got %S" property)) (unless (memq property allowed) (keymap-popup--invalid context "unknown property %S" property)) (when (memq property seen) (keymap-popup--invalid context "duplicate property %S" property)) (if (and (eq property :stay-open) (or (null (cdr rest)) (keywordp (cadr rest)))) (cons property (cons t (parse (cdr rest) (cons property seen)))) (unless (cdr rest) (keymap-popup--invalid context "property %S needs a value" property)) (cons property (cons (cadr rest) (parse (cddr rest) (cons property seen)))))))))) (defun keymap-popup--function-form-p (value) "Return non-nil when VALUE is a quoted or literal function form." (and (consp value) (memq (car value) '(closure function lambda)))) (defun keymap-popup--function-designator-p (value) "Return non-nil when VALUE is a function object or function symbol." (or (functionp value) (and (symbolp value) (not (memq value '(nil t))) (not (keywordp value))))) (defun keymap-popup--valid-description-p (description runtime) "Return non-nil when DESCRIPTION is valid for RUNTIME input." (or (stringp description) (keymap-popup--function-designator-p description) (and (not runtime) (consp description)))) (defun keymap-popup--validate-description (description context runtime) "Validate DESCRIPTION for CONTEXT and RUNTIME input." (unless (keymap-popup--valid-description-p description runtime) (keymap-popup--invalid context "description must be a string or function, got %S" description))) (defun keymap-popup--valid-function-value-p (value runtime) "Return non-nil when VALUE is a function value for RUNTIME input." (or (null value) (keymap-popup--function-designator-p value) (and (not runtime) (consp value)))) (defun keymap-popup--valid-string-value-p (value runtime) "Return non-nil when VALUE is a string value for RUNTIME input." (or (null value) (stringp value) (and (not runtime) (not (eq value t)) (not (keywordp value)) (or (symbolp value) (consp value))))) (defun keymap-popup--validate-properties (properties context runtime) "Validate parsed PROPERTIES for CONTEXT and RUNTIME input." (named-let validate ((rest properties)) (when rest (pcase-exhaustive (car rest) ((or :if :inapt-if) (unless (keymap-popup--valid-function-value-p (cadr rest) runtime) (keymap-popup--invalid context "%S needs a function" (car rest)))) (:stay-open (when (and runtime (not (memq (cadr rest) '(nil t)))) (keymap-popup--invalid context ":stay-open needs a boolean"))) (:c-u (unless (keymap-popup--valid-string-value-p (cadr rest) runtime) (keymap-popup--invalid context ":c-u needs a string")))) (validate (cddr rest)))) properties) (defun keymap-popup--valid-command-p (command runtime) "Return non-nil when COMMAND is valid for RUNTIME input." (let ((command-symbol (and (symbolp command) (not (memq command '(nil t))) (not (keywordp command))))) (if runtime (or command-symbol (commandp command)) (or command-symbol (functionp command) (consp command))))) (defun keymap-popup--entry (key description type &rest properties) "Return a canonical popup entry plist. KEY, DESCRIPTION, and TYPE identify the entry. PROPERTIES supplies the type-specific payload and optional predicates." (list :key key :description description :type type :command (plist-get properties :command) :variable (plist-get properties :variable) :target (plist-get properties :target) :if (plist-get properties :if) :inapt-if (plist-get properties :inapt-if) :stay-open (plist-get properties :stay-open) :c-u (plist-get properties :c-u))) (defun keymap-popup--group (name entries &rest properties) "Return a canonical popup group with NAME, ENTRIES, and PROPERTIES." (list :name name :entries entries :if (plist-get properties :if) :inapt-if (plist-get properties :inapt-if))) (defun keymap-popup--validate-key (key mode context) "Validate entry KEY for parser MODE and CONTEXT." (cond ((stringp key) (unless (key-valid-p key) (keymap-popup--invalid context "invalid key %S" key))) ((and (symbolp key) (not (memq key '(nil t))) (not (keywordp key))) (when (eq mode 'define) (keymap-popup--invalid context "definitions require a key string"))) (t (keymap-popup--invalid context "invalid key or command %S" key)))) (defun keymap-popup--parse-annotated-entry (key spec context runtime) "Parse annotated SPEC for command KEY in CONTEXT. RUNTIME means values have already been evaluated." (let* ((parts (if (or (not (consp spec)) (functionp spec) (keymap-popup--function-form-p spec)) (list spec) spec)) (description (car parts)) (properties (keymap-popup--validate-properties (keymap-popup--parse-properties (cdr parts) keymap-popup--entry-properties context) context runtime))) (keymap-popup--validate-description description context runtime) (unless (keymap-popup--valid-command-p key runtime) (keymap-popup--invalid context "invalid command %S" key)) (apply #'keymap-popup--entry nil description 'suffix :command key properties))) (defun keymap-popup--parse-keyed-entry (key spec context runtime) "Parse keyed SPEC for KEY in CONTEXT. RUNTIME means values have already been evaluated." (unless (and (proper-list-p spec) (>= (length spec) 2)) (keymap-popup--invalid context "expected (DESCRIPTION COMMAND-OR-TYPE ...)")) (let ((description (car spec)) (kind (cadr spec)) (payload (cddr spec))) (keymap-popup--validate-description description context runtime) (pcase kind (:switch (unless (and (symbolp (car payload)) (not (memq (car payload) '(nil t))) (not (keywordp (car payload)))) (keymap-popup--invalid context "switch needs a variable symbol")) (apply #'keymap-popup--entry key description 'switch :variable (car payload) (keymap-popup--validate-properties (keymap-popup--parse-properties (cdr payload) keymap-popup--entry-properties context) context runtime))) (:keymap (unless (and (car payload) (not (eq (car payload) t)) (not (keywordp (car payload)))) (keymap-popup--invalid context "submenu needs a keymap")) (when (and runtime (not (keymapp (car payload)))) (keymap-popup--invalid context "submenu target is not a keymap")) (apply #'keymap-popup--entry key description 'keymap :target (car payload) (keymap-popup--validate-properties (keymap-popup--parse-properties (cdr payload) keymap-popup--entry-properties context) context runtime))) (_ (unless (keymap-popup--valid-command-p kind runtime) (keymap-popup--invalid context "invalid command %S" kind)) (apply #'keymap-popup--entry key description 'suffix :command kind (keymap-popup--validate-properties (keymap-popup--parse-properties payload keymap-popup--entry-properties context) context runtime)))))) (defun keymap-popup--parse-entry (key spec &optional mode) "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. MODE is `define', `annotate', or `runtime'; omitted means macro syntax." (let* ((mode (or mode 'macro)) (context (format "entry %S" key)) (runtime (eq mode 'runtime))) (keymap-popup--validate-key key mode context) (if (stringp key) (keymap-popup--parse-keyed-entry key spec context runtime) (keymap-popup--parse-annotated-entry key spec context runtime)))) (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) (unless (cdr rest) (keymap-popup--invalid "bindings" ":group needs a name")) (split (cddr rest) (cadr rest) nil flushed rows)) ((keywordp (car rest)) (keymap-popup--invalid "bindings" "unknown directive %S" (car rest))) ((null (cdr rest)) (keymap-popup--invalid "bindings" "entry %S needs a specification" (car rest))) (t (split (cddr rest) name (cons (cons (car rest) (cadr rest)) entries) groups rows)))))) (defun keymap-popup--parse-group-name (raw &optional mode) "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. MODE controls whether values have already been evaluated." (let* ((runtime (eq mode 'runtime)) (context (format "group %S" raw)) (specified (and (consp raw) (not (functionp raw)) (not (keymap-popup--function-form-p raw)))) (name (if specified (car raw) raw)) (properties (and specified (keymap-popup--validate-properties (keymap-popup--parse-properties (cdr raw) keymap-popup--group-properties context) context runtime)))) (when name (keymap-popup--validate-description name context runtime)) (cons name properties))) (defun keymap-popup--parse-chunk (chunk &optional mode) "Parse CHUNK into a group plist according to parser MODE." (let* ((name-props (keymap-popup--parse-group-name (car chunk) mode)) (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 mode)))) (apply #'keymap-popup--group name entries group-props))) (defun keymap-popup--parse-bindings (bindings &optional mode) "Parse BINDINGS into a list of rows. Each row is a list of group plists with :name and :entries. MODE controls whether values have already been evaluated." (mapcar (lambda (row) (mapcar (lambda (chunk) (keymap-popup--parse-chunk chunk mode)) 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. Switch and keymap entries name generated commands; suffix entries retain their declared command." (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 canonical entry form for 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)) (command (pcase-exhaustive type ('suffix (plist-get entry :command)) ((or 'switch 'keymap) (and map-name (keymap-popup--entry-command map-name entry))))) (command-form (and command (if (symbolp command) `#',command command))) (variable-form (and (eq type 'switch) `(quote ,(plist-get entry :variable))))) `(keymap-popup--entry ,(plist-get entry :key) ,(plist-get entry :description) ',type :command ,command-form :variable ,variable-form :target ,(and (eq type 'keymap) (plist-get entry :target)) :if ,(plist-get entry :if) :inapt-if ,(plist-get entry :inapt-if) :stay-open ,(plist-get entry :stay-open) :c-u ,(plist-get entry :c-u)))) (defun keymap-popup--build-group-form (group &optional map-name) "Build a canonical form for one GROUP plist. MAP-NAME is passed to `keymap-popup--build-entry-form'." `(keymap-popup--group ,(plist-get group :name) (list ,@(mapcar (lambda (entry) (keymap-popup--build-entry-form entry map-name)) (plist-get group :entries))) :if ,(plist-get group :if) :inapt-if ,(plist-get group :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 persistent-p) "Build the `keymap-popup--attach-meta' call form for MAP-NAME. ROWS-FORM constructs the descriptions at load time. Each of EXIT-KEY and DESCRIPTION is passed only when non-nil. PERSISTENT is passed when PERSISTENT-P is non-nil." `(keymap-popup--attach-meta ,map-name ,rows-form ,@(and exit-key `(:exit-key ,exit-key)) ,@(and description `(:description ,description)) ,@(and persistent-p `(:persistent ,persistent)))) ;;; Macro (defconst keymap-popup--define-options '(:popup-key :exit-key :parent :description :persistent) "Options accepted by `keymap-popup-define'.") (defconst keymap-popup--annotate-options '(:popup-key :exit-key :description :persistent) "Options accepted by `keymap-popup-annotate'.") (defconst keymap-popup--attach-options '(:exit-key :description :persistent) "Options accepted by `keymap-popup-attach'.") (defun keymap-popup--parse-options (values allowed context) "Parse leading options from VALUES for CONTEXT. ALLOWED lists recognized option names. Return (OPTIONS . REST)." (named-let parse ((rest values) (options nil) (seen nil)) (cond ((null rest) (cons (reverse options) nil)) ((memq (car rest) allowed) (unless (cdr rest) (keymap-popup--invalid context "option %S needs a value" (car rest))) (when (memq (car rest) seen) (keymap-popup--invalid context "duplicate option %S" (car rest))) (parse (cddr rest) (cons (cadr rest) (cons (car rest) options)) (cons (car rest) seen))) ((and (keywordp (car rest)) (not (memq (car rest) '(:group :row)))) (keymap-popup--invalid context "unknown option %S" (car rest))) (t (cons (reverse options) rest))))) (defun keymap-popup--validate-key-option (options property context runtime) "Validate key PROPERTY in OPTIONS for CONTEXT and RUNTIME input." (when-let* ((value (plist-get options property))) (cond ((stringp value) (unless (key-valid-p value) (keymap-popup--invalid context "%S is not a valid key" value))) ((or runtime (memq value '(nil t)) (keywordp value) (not (or (symbolp value) (consp value)))) (keymap-popup--invalid context "%S needs a key string" property))))) (defun keymap-popup--validate-options (options context runtime) "Validate OPTIONS for CONTEXT and RUNTIME input." (keymap-popup--validate-key-option options :popup-key context runtime) (keymap-popup--validate-key-option options :exit-key context runtime) (when-let* ((description (plist-get options :description))) (keymap-popup--validate-description description context runtime)) (when (and runtime (plist-member options :persistent) (not (memq (plist-get options :persistent) '(nil t)))) (keymap-popup--invalid context ":persistent needs a boolean")) options) (defun keymap-popup--extract-macro-opts (body allowed context) "Extract options accepted by ALLOWED from macro BODY for CONTEXT. Return a plist containing :docstring, parsed options, and :bindings." (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--parse-options rest allowed context)) (options (append (list :docstring docstring) (car result) (list :bindings (cdr result))))) (keymap-popup--validate-options options context nil))) ;;;###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)) (let* ((options (keymap-popup--extract-macro-opts body keymap-popup--define-options (format "definition %S" name))) (docstring (plist-get options :docstring)) (popup-key (plist-get options :popup-key)) (exit-key (plist-get options :exit-key)) (parent (plist-get options :parent)) (description (plist-get options :description)) (persistent (plist-get options :persistent)) (persistent-p (plist-member options :persistent)) (bindings (plist-get options :bindings)) (rows (keymap-popup--parse-bindings bindings 'define)) (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 persistent-p)))) ;;;###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)) (let* ((options (keymap-popup--extract-macro-opts body keymap-popup--annotate-options "annotation")) (popup-key (plist-get options :popup-key)) (exit-key (plist-get options :exit-key)) (description (plist-get options :description)) (persistent (plist-get options :persistent)) (persistent-p (plist-member options :persistent)) (bindings (plist-get options :bindings)) (rows (keymap-popup--parse-bindings bindings 'annotate)) (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 persistent-p) ,@(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." (let ((parsed (keymap-popup--parse-options opts keymap-popup--attach-options "attachment"))) (when (cdr parsed) (keymap-popup--invalid "attachment" "expected option, got %S" (car (cdr parsed)))) (let ((options (keymap-popup--validate-options (car parsed) "attachment" t))) (apply #'keymap-popup--attach-meta keymap (keymap-popup--parse-bindings bindings 'runtime) options)))) (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")) (let ((entry (keymap-popup--parse-entry key (list description command) 'runtime))) (keymap-set keymap key 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--session nil "Popup session plist owned by the popup buffer. The :active value is a navigation-state plist; :stack holds parent states. Session-wide source, prefix, persistence, backend, and hook values live beside them.") (defun keymap-popup--plist-with (plist &rest properties) "Return PLIST with PROPERTIES replaced without changing PLIST." (named-let replace ((result (copy-sequence plist)) (rest properties)) (if (null rest) result (replace (plist-put result (car rest) (cadr rest)) (cddr rest))))) (defun keymap-popup--session-state (buf) "Return BUF's popup session plist." (and (buffer-live-p buf) (buffer-local-value 'keymap-popup--session buf))) (defun keymap-popup--session-get (buf property) "Return PROPERTY from BUF's popup session." (plist-get (keymap-popup--session-state buf) property)) (defun keymap-popup--active-get (buf property) "Return PROPERTY from BUF's active popup state." (plist-get (keymap-popup--session-get buf :active) property)) (defun keymap-popup--set-session (buf &rest properties) "Replace PROPERTIES in BUF's popup session." (with-current-buffer buf (setq-local keymap-popup--session (apply #'keymap-popup--plist-with keymap-popup--session properties)))) (defun keymap-popup--set-active (buf &rest properties) "Replace PROPERTIES in BUF's active popup state." (let ((active (keymap-popup--session-get buf :active))) (keymap-popup--set-session buf :active (apply #'keymap-popup--plist-with active properties)))) (defun keymap-popup--make-state (keymap descriptions docstring exit-key) "Return state for KEYMAP, DESCRIPTIONS, DOCSTRING, and EXIT-KEY." (list :keymap keymap :descriptions descriptions :docstring docstring :resolved-docstring nil :exit-key exit-key :wrapper-map nil :exit-function 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 (keymap-popup--active-get buf :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 (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 (keymap-popup--session-get buf :backend) :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* ((session (keymap-popup--session-state buf)) (active (plist-get session :active)) (source (plist-get session :source)) (descriptions (plist-get active :descriptions)) (docstring (plist-get active :docstring)) (prefix (plist-get session :prefix-mode))) (with-current-buffer (if (buffer-live-p source) source buf) (let ((resolved (and docstring (keymap-popup--resolve-description docstring)))) (keymap-popup--set-active buf :resolved-docstring resolved)) (keymap-popup--refresh-buffer buf descriptions 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 (keymap-popup--active-get buf :wrapper-map))) (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 (keymap-popup--active-get buf :wrapper-map))) (internal-push-keymap map 'overriding-terminal-local-map))) (defun keymap-popup--session-exit-functions (session include-active) "Return exit functions owned by SESSION. INCLUDE-ACTIVE includes the active transient map as well as parents." (let* ((active (plist-get session :active)) (states (if include-active (cons active (plist-get session :stack)) (plist-get session :stack)))) (seq-keep (lambda (state) (and-let* ((exit (plist-get state :exit-function)) ((functionp exit))) exit)) states))) (defun keymap-popup--close-session (buf include-active) "Deactivate BUF's session maps. INCLUDE-ACTIVE also deactivates the active transient map." (let* ((session (keymap-popup--session-state buf)) (active (plist-get session :active)) (exits (keymap-popup--session-exit-functions session include-active))) (keymap-popup--set-session buf :active (keymap-popup--plist-with active :exit-function nil) :stack nil :closing t) (mapc #'funcall exits))) (defun keymap-popup--remove-session-hooks (buf) "Remove global hooks owned by BUF's popup session." (remove-hook 'minibuffer-setup-hook #'keymap-popup--suspend) (remove-hook 'minibuffer-exit-hook #'keymap-popup--resume) (when-let* ((hook (keymap-popup--session-get buf :persistent-hook))) (remove-hook 'post-command-hook hook))) (defun keymap-popup--hide-session (buf) "Hide the display owned by BUF's popup session." (when-let* ((backend (keymap-popup--session-get buf :backend)) (hide (plist-get backend :hide))) (funcall hide buf))) (defun keymap-popup--kill-buffer-cleanup () "Release the popup session when its buffer is killed directly." (let ((buf (current-buffer))) (unless (keymap-popup--session-get buf :closing) (keymap-popup--close-session buf t) (keymap-popup--remove-session-hooks buf) (keymap-popup--hide-session buf)))) (defun keymap-popup--teardown (buf) "Remove the popup display for BUF and kill it." (when (buffer-live-p buf) (keymap-popup--close-session buf nil) (keymap-popup--remove-session-hooks buf) (keymap-popup--hide-session 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* ((session (keymap-popup--session-state buf)) (active (plist-get session :active)) (key-str (key-description (this-command-keys-vector)))) (cond ((active-minibuffer-window) t) ((plist-get session :reentering) (keymap-popup--set-session buf :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 (plist-get active :exit-key)) nil) ((eq this-command 'keyboard-quit) nil) ((keymap-popup--inapt-key-p buf key-str) t) ((plist-get session :persistent)) (t (keymap-popup--keep-popup-p (plist-get active :descriptions) 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) (let* ((session (keymap-popup--session-state buf)) (active (plist-get session :active)) (stack (plist-get session :stack)) (key-str (key-description (this-command-keys-vector)))) (unless (plist-get session :closing) (if (and stack (member key-str (list (plist-get active :exit-key) "C-g"))) (progn (keymap-popup--set-session buf :active (car stack) :stack (cdr stack) :reentering t :prefix-mode nil) (keymap-popup--refresh buf)) (keymap-popup--teardown buf))))))) (defun keymap-popup--state-for-keymap (keymap) "Derive navigation state from KEYMAP." (keymap-popup--make-state keymap (keymap-popup--resolve-descriptions (keymap-popup--collect-descriptions keymap) keymap) (keymap-popup--meta keymap 'description) (or (keymap-popup--meta keymap 'exit-key) keymap-popup-default-exit-key))) (defun keymap-popup--push-submenu (buf child-keymap) "Push current popup state in BUF and activate CHILD-KEYMAP's transient map." (let* ((session (keymap-popup--session-state buf)) (parent (plist-get session :active)) (child (keymap-popup--state-for-keymap child-keymap))) (keymap-popup--set-session buf :active child :stack (cons parent (plist-get session :stack)) :prefix-mode nil) (keymap-popup--refresh buf) (keymap-popup--activate-transient-map buf))) (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))) (let ((enabled (not (keymap-popup--session-get buf :prefix-mode)))) (keymap-popup--set-session buf :prefix-mode enabled) (setq prefix-arg (and enabled '(4))) (keymap-popup--refresh buf) (when enabled (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) (keymap-popup--session-get buf :prefix-mode)) (setq prefix-arg '(4)))) (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--consume-prefix (buf) "Consume prefix mode owned by popup BUF." (when (keymap-popup--session-get buf :prefix-mode) (keymap-popup--set-session buf :prefix-mode nil) (setq prefix-arg nil))) (defun keymap-popup--dispatch-entry (keymap entry buf) "Dispatch KEYMAP's popup ENTRY for BUF." (let ((key (plist-get entry :key))) (if (keymap-popup--inapt-key-p buf key) (keymap-popup--refuse-inapt buf) (pcase-exhaustive (plist-get entry :type) ('keymap (keymap-popup--push-submenu buf (plist-get entry :target))) ('switch (when (keymap-popup--call-real-binding keymap key) (keymap-popup--consume-prefix buf)) (keymap-popup--refresh buf)) ('suffix (keymap-popup--call-real-binding keymap key) (when (plist-get entry :stay-open) (keymap-popup--refresh buf))))))) (defun keymap-popup--entry-needs-override-p (entry group) "Return non-nil when ENTRY in GROUP needs popup dispatch." (pcase-exhaustive (plist-get entry :type) ((or 'switch 'keymap) t) ('suffix (or (plist-get entry :stay-open) (plist-get entry :inapt-if) (plist-get group :inapt-if))))) (defun keymap-popup--entry-override (keymap entry group buf) "Return KEYMAP override for ENTRY in GROUP and BUF, or nil." (and-let* ((key (plist-get entry :key)) ((keymap-popup--entry-needs-override-p entry group))) (cons key (lambda () (interactive) (keymap-popup--dispatch-entry keymap entry buf))))) (defun keymap-popup--description-overrides (keymap descriptions buf) "Return popup entry overrides for KEYMAP, DESCRIPTIONS, and BUF." (mapcan (lambda (row) (mapcan (lambda (group) (seq-keep (lambda (entry) (keymap-popup--entry-override keymap entry group buf)) (plist-get group :entries))) row)) descriptions)) (defun keymap-popup--build-wrapper-map (keymap descriptions buf exit-key) "Build wrapper keymap over KEYMAP with DESCRIPTIONS for BUF. EXIT-KEY and entry handlers layer over KEYMAP. `:if' enforcement lives on KEYMAP itself via `menu-item' :filter; `:inapt-if' is enforced here at keypress time." (let* ((map (make-sparse-keymap)) (overrides (append (keymap-popup--description-overrides keymap descriptions buf) (keymap-popup--core-overrides exit-key)))) (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))) (keymap-popup--close-session buf t) (when (buffer-live-p buf) (keymap-popup--remove-session-hooks buf) (keymap-popup--hide-session buf) (kill-buffer buf)))) (defun keymap-popup--make-session (keymap) "Derive a popup session for KEYMAP and the current buffer." (list :source (current-buffer) :active (keymap-popup--state-for-keymap keymap) :stack nil :prefix-mode nil :reentering nil :closing nil :persistent (pcase (keymap-popup--meta keymap 'persistent) ('yes t) ('no nil) (_ keymap-popup-persistent)) :backend (funcall keymap-popup-backend) :persistent-hook nil)) (defun keymap-popup--init-session (buf session) "Install SESSION in BUF and arrange cleanup on buffer death." (with-current-buffer buf (setq-local keymap-popup--session session) (add-hook 'kill-buffer-hook #'keymap-popup--kill-buffer-cleanup nil t))) (defun keymap-popup--activate-transient-map (buf) "Build and activate the transient map for BUF's active state." (let* ((active (keymap-popup--session-get buf :active)) (wrapper (keymap-popup--build-wrapper-map (plist-get active :keymap) (plist-get active :descriptions) buf (plist-get active :exit-key)))) (keymap-popup--set-active buf :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) (keymap-popup--set-active buf :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)))) (keymap-popup--set-session buf :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--make-session keymap)) (buf (keymap-popup--prepare-buffer))) (keymap-popup--init-session buf session) (keymap-popup--refresh buf) (funcall (plist-get (plist-get session :backend) :show) buf) (keymap-popup--activate-transient-map buf) (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.1/tests/000077500000000000000000000000001523325450100163735ustar00rootroot00000000000000emacs-keymap-popup-0.4.1/tests/keymap-popup-tests.el000066400000000000000000002614501523325450100225140ustar00rootroot00000000000000;;; keymap-popup-tests.el --- Tests -*- lexical-binding: t; -*- ;;; Commentary: ;; ERT tests for keymap-popup. Run via `make test'. ;;; Code: (require 'ert) (require 'keymap-popup) (defun keymap-popup-test--session (buf descriptions &rest properties) "Install a popup session in BUF for DESCRIPTIONS. PROPERTIES may supply active-state and session values used by a test." (let* ((backend (or (plist-get properties :backend) (list :show #'ignore :fit #'ignore :hide #'ignore))) (active (keymap-popup--make-state (plist-get properties :keymap) descriptions (plist-get properties :docstring) (or (plist-get properties :exit-key) "q"))) (active (keymap-popup--plist-with active :wrapper-map (plist-get properties :wrapper-map) :exit-function (plist-get properties :exit-function))) (session (list :source (or (plist-get properties :source) buf) :active active :stack (plist-get properties :stack) :prefix-mode (plist-get properties :prefix-mode) :reentering (plist-get properties :reentering) :persistent (plist-get properties :persistent) :backend backend :persistent-hook (plist-get properties :persistent-hook)))) (with-current-buffer buf (setq-local keymap-popup--session session)))) ;;; 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)))) (ert-deftest keymap-popup-test-parser-rejects-malformed-entries () (mapc (lambda (case) (pcase-let ((`(,key ,spec ,message) case)) (let ((error (should-error (keymap-popup--parse-entry key spec)))) (should (string-match-p message (error-message-string error)))))) '(("foobar" ("Bad key" ignore) "invalid key") ("x" (42 ignore) "description must be a string or function") ("x" ("Bad command" 42) "invalid command") ("x" ("Missing switch" :switch) "switch needs a variable symbol") ("x" ("Missing submenu" :keymap) "submenu needs a keymap") ("x" ("Typo" ignore :stay-opn t) "unknown property :stay-opn") ("x" ("Odd" ignore :if) "property :if needs a value") ("x" ("Bad predicate" ignore :if t) ":if needs a function")))) (ert-deftest keymap-popup-test-parser-rejects-malformed-groups () (let ((unknown (should-error (keymap-popup--parse-bindings '(:group ("Bad" :stay-open t) "x" ("X" ignore))))) (directive (should-error (keymap-popup--parse-bindings '(:grop "Bad" "x" ("X" ignore)))))) (should (string-match-p "unknown property :stay-open" (error-message-string unknown))) (should (string-match-p "unknown directive :grop" (error-message-string directive))))) (ert-deftest keymap-popup-test-macros-reject-unsupported-syntax () (should-error (macroexpand-1 '(keymap-popup-define keymap-popup--test-invalid-map ignore "Description"))) (should-error (macroexpand-1 '(keymap-popup-annotate some-map :parent parent-map ignore "Description"))) (should-error (macroexpand-1 '(keymap-popup-define keymap-popup--test-invalid-map :popup-key "not-a-key" "x" ("X" ignore))))) (ert-deftest keymap-popup-test-attach-validates-runtime-input () (let ((map (make-sparse-keymap))) (should-error (keymap-popup-attach map '("x" ("Invalid" 42)))) (should-error (keymap-popup-attach map '("x" ("Ignore" ignore)) :unknown t)) (should-error (keymap-popup-attach map '("x" ("Ignore" ignore :c-u 4)))) (should-error (keymap-popup-attach map '("x" ("Ignore" ignore)) :persistent 'yes)))) (ert-deftest keymap-popup-test-attach-accepts-forward-descriptions () "Runtime descriptions may be function symbols defined after attachment." (let* ((group-description (make-symbol "future-group-description")) (entry-description (make-symbol "future-entry-description")) (popup-description (make-symbol "future-popup-description")) (map (make-sparse-keymap))) (keymap-set map "x" #'ignore) (keymap-popup-attach map (list :group group-description "x" (list entry-description 'ignore)) :description popup-description) (let* ((rows (keymap-popup--meta map 'descriptions)) (group (caar rows)) (entry (car (plist-get group :entries)))) (should (eq (plist-get group :name) group-description)) (should (eq (plist-get entry :description) entry-description)) (should (eq (keymap-popup--meta map 'description) popup-description))))) (ert-deftest keymap-popup-test-attach-accepts-forward-predicates () "Runtime predicates may be function symbols defined after attachment." (let* ((group-if (make-symbol "future-group-if")) (group-inapt (make-symbol "future-group-inapt")) (entry-if (make-symbol "future-entry-if")) (entry-inapt (make-symbol "future-entry-inapt")) (map (make-sparse-keymap))) (keymap-set map "x" #'ignore) (keymap-popup-attach map (list :group (list "Group" :if group-if :inapt-if group-inapt) "x" (list "Ignore" 'ignore :if entry-if :inapt-if entry-inapt))) (let* ((rows (keymap-popup--meta map 'descriptions)) (group (caar rows)) (entry (car (plist-get group :entries)))) (should (eq (plist-get group :if) group-if)) (should (eq (plist-get group :inapt-if) group-inapt)) (should (eq (plist-get entry :if) entry-if)) (should (eq (plist-get entry :inapt-if) entry-inapt))))) ;;; 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 (keymap-popup-test--session buf descs :keymap keymap-popup--test-sw-inapt :prefix-mode t) (let* ((wrapper (keymap-popup--build-wrapper-map keymap-popup--test-sw-inapt descs buf "q")) (override (keymap-lookup wrapper "v")) (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 (keymap-popup--session-get buf :prefix-mode))) ;; 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 (keymap-popup--session-get buf :prefix-mode))))) (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 (keymap-popup-test--session buf descs :keymap map) (let* ((wrapper (keymap-popup--build-wrapper-map map descs buf "q")) (override (keymap-lookup wrapper "g"))) (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 (keymap-popup-test--session buf `(((: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 (keymap-popup-test--session buf `(((: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 (keymap-popup-test--session buf nil :prefix-mode t) (let ((prefix-arg nil)) (keymap-popup--refuse-inapt buf) (should (equal prefix-arg '(4)))) (keymap-popup--set-session buf :prefix-mode nil) (let ((prefix-arg nil)) (keymap-popup--refuse-inapt buf) (should-not prefix-arg))) (kill-buffer buf)))) (ert-deftest keymap-popup-test-wrapper-only-shadows-dispatched-entries () "Plain suffixes inherit the real binding; popup-managed entries shadow it." (let* ((pred (lambda () t)) (map (make-sparse-keymap)) (buf (get-buffer-create keymap-popup--buffer-name)) (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))))))) (mapc (lambda (key) (keymap-set map key #'ignore)) '("a" "b" "c" "g" "v")) (unwind-protect (progn (keymap-popup-test--session buf descs :keymap map) (let ((wrapper (keymap-popup--build-wrapper-map map descs buf "q"))) (mapc (lambda (key) (should-not (eq (keymap-lookup wrapper key) #'ignore))) '("a" "b" "g" "v")) (should (eq (keymap-lookup wrapper "c") #'ignore)))) (kill-buffer buf)))) (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 (let ((descs `(((:name nil :entries ((:key "x" :type suffix :inapt-if ,(lambda () t)))))))) (keymap-popup-test--session buf descs :keymap map) (let* ((wrapper (keymap-popup--build-wrapper-map map descs buf "q")) (override (keymap-lookup wrapper "x"))) (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 (let ((descs `(((:name nil :entries ((:key "x" :type suffix :inapt-if ,(lambda () nil)))))))) (keymap-popup-test--session buf descs :keymap map) (let* ((wrapper (keymap-popup--build-wrapper-map map descs buf "q")) (override (keymap-lookup wrapper "x"))) (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 ((descs `(((:name nil :entries ((:key "x" :type suffix :inapt-if ,(lambda () nil)))))))) (keymap-popup-test--session buf descs :keymap map) (let* ((wrapper (keymap-popup--build-wrapper-map map descs buf "q")) (override (keymap-lookup wrapper "x"))) (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 (keymap-popup-test--session buf `(((: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 (let ((descs `(((:name nil :entries ((:key "s" :type keymap :target sub :inapt-if ,(lambda () flag)))))))) (keymap-popup-test--session buf descs) (cl-letf (((symbol-function 'keymap-popup--push-submenu) (lambda (_buf target) (setq pushed target)))) (let* ((wrapper (keymap-popup--build-wrapper-map (make-sparse-keymap) descs buf "q")) (override (keymap-lookup wrapper "s"))) (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 (let ((descs `(((:name nil :entries ((:key "g" :type suffix :stay-open t :inapt-if ,(lambda () t)))))))) (keymap-popup-test--session buf descs :keymap map) (let* ((wrapper (keymap-popup--build-wrapper-map map descs buf "q")) (override (keymap-lookup wrapper "g"))) (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 (keymap-popup-test--session buf descs :keymap keymap-popup--test-annotate-map) (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-core-overrides-win-on-key-collision () "The popup exit and prefix bindings cannot be shadowed by entries." (let* ((map (make-sparse-keymap)) (buf (get-buffer-create keymap-popup--buffer-name)) (descs '(((:name nil :entries ((:key "q" :type suffix :stay-open t) (:key "C-u" :type suffix :stay-open t))))))) (unwind-protect (progn (keymap-popup-test--session buf descs :keymap map) (let ((wrapper (keymap-popup--build-wrapper-map map descs buf "q"))) (should (eq (keymap-lookup wrapper "q") #'ignore)) (should (eq (keymap-lookup wrapper "C-u") #'keymap-popup--prefix-argument)))) (kill-buffer buf)))) (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 (keymap-popup-test--session buf '(((:name nil :entries nil))) :keymap parent-map :wrapper-map parent-wrapper :exit-function #'ignore) (cl-letf (((symbol-function 'set-transient-map) (lambda (map &rest _) (setq received map)))) (keymap-popup--push-submenu buf keymap-popup--test-push-child)) (let* ((session (keymap-popup--session-state buf)) (active (plist-get session :active)) (parent (car (plist-get session :stack)))) (should (= (length (plist-get session :stack)) 1)) (should (eq (plist-get parent :keymap) parent-map)) (should (eq (plist-get parent :wrapper-map) parent-wrapper)) (should (eq (plist-get parent :exit-function) #'ignore)) (should (eq (plist-get active :keymap) keymap-popup--test-push-child)) (should (plist-get active :wrapper-map)) (should (eq received (plist-get active :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-validates-before-binding () "Invalid runtime entries leave the keymap unchanged." (eval '(keymap-popup-define keymap-popup--test-add-invalid "c" ("Comment" ignore)) t) (should-error (keymap-popup-add-entry keymap-popup--test-add-invalid "z" "Bad" 42)) (should-not (keymap-lookup keymap-popup--test-add-invalid "z"))) (ert-deftest keymap-popup-test-add-entry-accepts-forward-command-symbol () "Runtime map assembly may precede the command's defining module." (eval '(keymap-popup-define keymap-popup--test-add-forward "c" ("Comment" ignore)) t) (keymap-popup-add-entry keymap-popup--test-add-forward "f" "Future" 'keymap-popup--future-command) (should (eq (keymap-lookup keymap-popup--test-add-forward "f") 'keymap-popup--future-command))) (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--flatten-with-groups resolved))) (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-stores-explicit-false () (let ((map (make-sparse-keymap))) (keymap-popup--attach-meta map '(rows) :persistent nil) (should (eq (keymap-popup--meta map 'persistent) 'no)))) (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-persistent-false-overrides-global-default () (eval '(keymap-popup-define keymap-popup--test-nonpersistent-map :persistent nil "x" ("Ignore" ignore)) t) (let ((keymap-popup-persistent t)) (should (eq (keymap-popup--meta keymap-popup--test-nonpersistent-map 'persistent) 'no)) (should-not (plist-get (keymap-popup--make-session keymap-popup--test-nonpersistent-map) :persistent)))) (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) (keymap-popup-test--session buf descriptions :keymap parent) (keymap-popup--activate-transient-map buf) (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 (keymap-popup-test--session buf nil) (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-killing-buffer-releases-session-resources () "Direct buffer death removes maps and every global session hook." (let ((overriding-terminal-local-map nil) (pre-command-hook nil) (post-command-hook nil) (minibuffer-setup-hook nil) (minibuffer-exit-hook nil) (keymap-popup-persistent t) (keymap-popup-backend (lambda () (list :show #'ignore :fit #'ignore :hide #'ignore))) (map (make-sparse-keymap))) (keymap-set map "x" #'ignore) (keymap-popup-attach map '("x" ("Ignore" ignore))) (with-temp-buffer (keymap-popup map) (kill-buffer keymap-popup--buffer-name)) (should-not overriding-terminal-local-map) (should-not pre-command-hook) (should-not post-command-hook) (should-not minibuffer-setup-hook) (should-not minibuffer-exit-hook))) (ert-deftest keymap-popup-test-submenu-suffix-exit-cleans-parent-map () "A suffix from a child popup deactivates suspended parent maps too." (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) (keymap-popup-test--session buf descriptions :keymap parent) (keymap-popup--activate-transient-map buf) (keymap-popup--push-submenu buf child) (let ((exit (keymap-popup--active-get buf :exit-function))) (cl-letf (((symbol-function 'this-command-keys-vector) (lambda () [?x]))) (funcall exit))) (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-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*")) (parent (keymap-popup--make-state nil nil nil "q"))) (unwind-protect (progn (keymap-popup-test--session buf nil :stack (list parent)) (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 (let ((parent (keymap-popup--plist-with (keymap-popup--make-state parent-map descs nil "x") :wrapper-map parent-wrapper :exit-function #'ignore))) (keymap-popup-test--session buf descs :keymap (make-sparse-keymap) :stack (list parent))) (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)) (let* ((session (keymap-popup--session-state buf)) (active (plist-get session :active))) (should (eq (plist-get active :keymap) parent-map)) (should (equal (plist-get active :exit-key) "x")) (should (eq (plist-get active :wrapper-map) parent-wrapper)) (should (eq (plist-get active :exit-function) #'ignore)) (should-not (plist-get session :stack))))) (when (buffer-live-p buf) (kill-buffer buf))))) (provide 'keymap-popup-tests) ;;; keymap-popup-tests.el ends here