pax_global_header00006660000000000000000000000064150147604430014516gustar00rootroot0000000000000052 comment=77e639bc6b982be09f355390beef6f200936109a corfu-2.2/000077500000000000000000000000001501476044300124775ustar00rootroot00000000000000corfu-2.2/.elpaignore000066400000000000000000000000331501476044300146210ustar00rootroot00000000000000LICENSE .elpaignore .githubcorfu-2.2/.github/000077500000000000000000000000001501476044300140375ustar00rootroot00000000000000corfu-2.2/.github/ISSUE_TEMPLATE/000077500000000000000000000000001501476044300162225ustar00rootroot00000000000000corfu-2.2/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000011301501476044300207070ustar00rootroot00000000000000--- title: name: 🐞 Bug report about: Report a bug. Do not use this for questions, support or feature requests. --- Thank you for reporting a bug. Please use the latest stable release of Emacs 30.1 and start with `emacs -Q` or `package-isolate` in order to only load a minimal set of packages. This way your Emacs configuration is not loaded. Please provide precise information and the exact steps to reproduce the issue. This is important to ensure that your problem can be reproduced on a different machine. If you are not really sure if your issue is a bug, please open a discussion instead. corfu-2.2/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000024331501476044300202140ustar00rootroot00000000000000blank_issues_enabled: false contact_links: - name: "🙏 Please support my work on Corfu and my other Emacs packages" url: https://github.com/sponsors/minad about: Thanks! Your support helps dedicating time to project maintenance and development. - name: "💡 Suggest a feature ➞ Please create a discussion" url: https://github.com/minad/corfu/discussions/categories/ideas about: Start a new discussion suggesting an improvement or a feature. - name: "🧑‍🤝‍🧑 Ask the community for support" url: https://www.reddit.com/r/emacs about: Please be kind and support others. - name: "🤓 Ask the maintainer for support ➞ Please create a discussion" url: https://github.com/minad/corfu/discussions/categories/q-a about: Please keep in mind that my bandwidth is limited. - name: "🔍 Search through old issues or discussions" url: https://github.com/search?q=repo%3Aminad%2Fcorfu&type=issues about: The same question may have been asked before. - name: "📝 Corfu wiki" url: https://github.com/minad/corfu/wiki about: Additional configuration tips are covered there. Feel free to edit! - name: "📖 Corfu manual" url: https://github.com/minad/corfu/blob/main/README.org about: The manual covers the basic setup and workflow. corfu-2.2/.gitignore000066400000000000000000000001021501476044300144600ustar00rootroot00000000000000*-autoloads.el *-pkg.el *.elc *.info *.texi *~ \#*\# /README-elpa corfu-2.2/CHANGELOG.org000066400000000000000000000142511501476044300145020ustar00rootroot00000000000000#+title: corfu.el - Changelog #+author: Daniel Mendler #+language: en * Version 2.2 (2025-05-26) - Guard Corfu hooks to automatically print stack traces in order to ease debugging. * Version 2.1 (2025-04-22) - =corfu-history-duplicate= and =corfu-history-decay=: New customization options to adjust the rank of duplicate history elements, such that they appear earlier in the completion list. - =corfu-history-mode=: Add =corfu-history= to =savehist-minibuffer-history-variables= in order to save the history if =savehist-mode= is enabled. * Version 2.0 (2025-03-28) - ~corfu-quick~: Ensure that popup does not move. * Version 1.7 (2025-01-28) - Bugfixes only. * Version 1.6 (2024-12-22) - Require Emacs 28.1. - Use fringe to display scroll bar. This change improves performance and makes sure that the scroll bar cannot be pushed outside the child frame by the content. This affects for example ~cape-emoji~. - Improve suffix alignment. - Remember popup width during completion to avoid width fluctuations. Basically the popup is only allowed to grow. - ~corfu-insert-separator~: Jump back to prompt if a candidate is previewed. * Version 1.5 (2024-07-26) - New customization variable =global-corfu-minibuffer= to enable Corfu in the minibuffer. - Unbind =C-a= in =corfu-map=. This binding is only needed in modes which override =C-a= instead of remapping ~move-beginning-of-line~. - Unbind == in ~corfu-map~. This binding is only needed in modes which bind == instead of =TAB=, as was the case in old versions of Org. If you use such a mode, please report this as a bug for this mode. In the meantime you can use =(keymap-set corfu-map "" #'corfu-complete)=. - Add new command ~corfu-send~ as alternative to ~corfu-insert~. - =corfu-popupinfo=: Support both =face= and =font-lock-face= highlighting. - Bump Compat dependency to Compat 30. * Version 1.4 (2024-05-23) - ~corfu-auto-commands~: Add ~delete-backward-char~. * Version 1.3 (2024-04-05) - Preserve currently selected candidate on further input. This matters if candidate preview is disabled (~corfu-preview-current=nil~). - Add new command ~corfu-expand~ bound to ~M-TAB~ by default. The command expands the input via ~completion-try-completion~, for example the ~basic~ completion style expands the common prefix of all candidates. * Version 1.2 (2024-01-23) - Support the EXWM window manager. - Optimization: Reduce auto completion timer overhead. - Use ~internal-border-width~ instead of ~child-frame-border-width~. - Internal refactoring: Do not use buffer-local variables. - Internal refactoring: Store ~completion-extra-properties~ as part of ~completion-in-region--data~. * Version 1.1 (2023-12-27) - Deduplicate candidates with respect to ~equal-including-properties~, such that backends can provide equal candidate strings, which only differ in their text properties and annotations. - Ensure that the string passed to the ~:exit-function~ retains the candidate properties, when possible. The properties are guaranteed to exist when a candidate is selected explicitly, but may be missing when candidates are completed in a stepwise manner. - ~corfu-on-exact-match~: Add value ~show~ to the customization option. With this setting the Corfu popup will be shown even if there is only a single matching candidate. * Version 1.0 (2023-12-01) - Bug fixes. - =corfu-quick=: Use a slightly different scheme to support more candidates. - =corfu-reset=: Quit immediately if input did not change. - Support =completion-lazy-hilit=. * Version 0.38 (2023-08-14) - =corfu-quick=: Bugfix. - =corfu-mode-map=: Add mode map. - Replace =corfu-excluded-modes= with =global-corfu-modes=, the Emacs 28 convention for globalized minor modes. * Version 0.37 (2023-07-02) - Bugfixes. - Improve child frame display code, =corfu--popup-show= takes a =posn= argument. - Ensure that the popup font matches the font of the parent frame. - Close popup when window selection changes. - Remove =corfu-history-length=. Instead set the =history-length= property of =corfu-history= variable. - =corfu-info-documentation=, =corfu-info-location=: Make buffer and window persistent if called with prefix argument. * Version 0.36 (2023-03-27) - Drop obsolete =corfu-preselect-first=. - =corfu-popupinfo-delay= and =corfu-echo-delay=: Remove support for value =t=. Instant updates are not recommended. It is still possible to use a small value for the delay. - Rename =corfu-excluded-modes= to =corfu-exclude-modes= (Naming convention). - Remove call to =undo-boundary=, which caused issues with auto completion. * Version 0.35 (2023-02-17) - =corfu-popupinfo=: Take more text into account when computing popup width. - =corfu-popupinfo=: Change keybindings, remap =corfu-info-documentation/location=. - =corfu-popupinfo=: Add commands =corfu-popupinfo-beginning/end=. - =corfu-popupinfo=: Improve popup placement. - Add =corfu-prompt-beginning= and =corfu-prompt-end= commands. - Add =corfu-preselect= option, deprecate =corfu-preselect-first=. - Use =cl-defgeneric= internally as mechanism to allow extensions to override functionality, e.g., the candidate formatting and display. * Version 0.34 (2022-12-03) - Bugfixes - Popup frame code updated for Emacs 29. Please report any issues. - =corfu-popupinfo-direction=: Variable must be a list of directions. - Support height adjustments of =corfu-default= face * Version 0.33 (2022-11-21) - =corfu-popupinfo=: Bugfixes * Version 0.31 (2022-11-20) - =corfu-echo=, =corfu-quick=: Bugfixes for interaction issue. * Version 0.30 (2022-11-19) - =corfu-popupinfo=: Bugfixes and improvements. * Version 0.29 (2022-11-19) - BREAKING: Extract the =corfu-echo= extension from =corfu.el=. In order to see echo messages, enable =corfu-echo-mode=. You probably want to enable either =corfu-echo-mode= or =corfu-popupinfo-mode=. - BREAKING: Rename =corfu-echo-documentation= to =corfu-echo-delay=. - Add =corfu-popupinfo= extension to display candidate documentation and location in a small child frame next to the candidate menu. This extension has been contributed by Yuwei Tian who assigned copyright to the FSF. The extension supersedes Yuwei's =corfu-doc= package. * Version 0.28 (2022-10-16) - Start of changelog. corfu-2.2/LICENSE000066400000000000000000001045151501476044300135120ustar00rootroot00000000000000 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 . corfu-2.2/README.org000066400000000000000000000733431501476044300141570ustar00rootroot00000000000000#+title: corfu.el - COmpletion in Region FUnction #+author: Daniel Mendler #+language: en #+export_file_name: corfu.texi #+texinfo_dir_category: Emacs misc features #+texinfo_dir_title: Corfu: (corfu). #+texinfo_dir_desc: COmpletion in Region FUnction #+html: GNU Emacs #+html: GNU ELPA #+html: GNU-devel ELPA #+html: MELPA #+html: MELPA Stable Corfu enhances in-buffer completion with a small completion popup. The current candidates are shown in a popup below or above the point, and can be selected by moving up and down. Corfu is the minimalistic in-buffer completion counterpart of the [[https://github.com/minad/vertico][Vertico]] minibuffer UI. Corfu is a small package, which relies on the Emacs completion facilities and concentrates on providing a polished completion UI. In-buffer completion UIs in Emacs can hook into ~completion-in-region~, which implements the interaction with the user. Completions at point are either provided by commands like ~dabbrev-completion~ or by pluggable backends (~completion-at-point-functions~, Capfs) and are then passed to ~completion-in-region~. Many programming, text and shell major modes implement a Capf. Corfu does not include its own completion backends. The Emacs built-in Capfs and the Capfs provided by third-party programming language packages are often sufficient. Additional Capfs and completion utilities are provided by the separate [[https://github.com/minad/cape][Cape]] package. *NOTE*: Corfu relies on child frames to show the popup. Emacs 31 supports child frames also for terminal Emacs. On older Emacs versions, you can use the [[https://codeberg.org/akib/emacs-corfu-terminal][corfu-terminal]] package. #+html: #+html: #+html: #+html: #+toc: headlines 8 * Features - Timer-based auto-completions (/off/ by default). - Popup display with scrollbar indicator and arrow key navigation. - The popup can be summoned explicitly by pressing =TAB= at any time. - The current candidate is inserted with =TAB= and selected with =RET=. - Sorting by prefix, string length and alphabetically, optionally by history. - The selected candidate is previewed (configurable via ~corfu-preview-current~). - The selected candidate is automatically committed on further input by default. (configurable via ~corfu-preview-current~). - Supports the [[https://github.com/oantolin/orderless][Orderless]] completion style. The filter string can contain arbitrary characters, after inserting a space via =M-SPC= (configurable via ~corfu-quit-at-boundary~ and ~corfu-separator~). - Lazy candidate highlighting for performance. - Support for candidate annotations (=annotation-function=, =affixation-function=). - Deprecated candidates are displayed as crossed out. - Icons are provided by external packages via margin formatter functions. - Rich set of extensions: Quick keys, Index keys, Sorting by history, Candidate documentation in echo area, popup or separate buffer. * Installation Corfu is available from [[https://elpa.gnu.org/packages/corfu.html][GNU ELPA]]. You can install it directly via =M-x package-install RET corfu RET=. After installation, activate the global minor mode with =M-x global-corfu-mode RET=. For completion press =M-TAB= (or =TAB=) within a buffer. Auto completion is disabled by default for safety and unobtrusiveness. * Key bindings Corfu uses a transient keymap ~corfu-map~ which is active while the popup is shown. The keymap defines the following remappings of fundamental commands and bindings: | Binding/Remapping | Corfu command | |--------------------------+--------------------------| | ~move-beginning-of-line~ | ~corfu-prompt-beginning~ | | ~move-end-of-line~ | ~corfu-prompt-end~ | | ~beginning-of-buffer~ | ~corfu-first~ | | ~end-of-buffer~ | ~corfu-last~ | | ~scroll-down-command~ | ~corfu-scroll-down~ | | ~scroll-up-command~ | ~corfu-scroll-up~ | | ~next-line~, =down=, =M-n= | ~corfu-next~ | | ~previous-line~, =up=, =M-p= | ~corfu-previous~ | | ~completion-at-point~, =TAB= | ~corfu-complete~ | | =M-TAB= | ~corfu-expand~ | | =RET= | ~corfu-insert~ | | =M-g= | ~corfu-info-location~ | | =M-h= | ~corfu-info-documentation~ | | =M-SPC= | ~corfu-insert-separator~ | | =C-g= | ~corfu-quit~ | | ~keyboard-escape-quit~ | ~corfu-reset~ | * Configuration In order to configure Corfu and other packages in your init.el, you may want to use ~use-package~. Corfu is flexibly customizable via ~corfu-*~ customization variables, such that you can adapt it precisely to your requirements. However in order to quickly try out the Corfu completion package, it should be sufficient to activate ~global-corfu-mode~. You can experiment with manual completion for example in an Elisp buffer or in an Eshell or Shell buffer. Auto completion is disabled by default in Corfu. Note that completion can be vulnerable to arbitrary code execution in untrusted files. In particular the ~elisp-completion-at-point~ completion function performs macro expansion and code evaluation. Auto completion can be enabled by setting ~corfu-auto~ to t locally or globally before enabling the local ~corfu-mode~ or the ~global-corfu-mode~. Here is an example configuration: #+begin_src emacs-lisp (use-package corfu ;; Optional customizations ;; :custom ;; (corfu-cycle t) ;; Enable cycling for `corfu-next/previous' ;; (corfu-quit-at-boundary nil) ;; Never quit at completion boundary ;; (corfu-quit-no-match nil) ;; Never quit, even if there is no match ;; (corfu-preview-current nil) ;; Disable current candidate preview ;; (corfu-preselect 'prompt) ;; Preselect the prompt ;; (corfu-on-exact-match nil) ;; Configure handling of exact matches ;; Enable Corfu only for certain modes. See also `global-corfu-modes'. ;; :hook ((prog-mode . corfu-mode) ;; (shell-mode . corfu-mode) ;; (eshell-mode . corfu-mode)) :init ;; Recommended: Enable Corfu globally. Recommended since many modes provide ;; Capfs and Dabbrev can be used globally (M-/). See also the customization ;; variable `global-corfu-modes' to exclude certain modes. (global-corfu-mode) ;; Enable optional extension modes: ;; (corfu-history-mode) ;; (corfu-popupinfo-mode) ) ;; A few more useful configurations... (use-package emacs :custom ;; TAB cycle if there are only few candidates ;; (completion-cycle-threshold 3) ;; Enable indentation+completion using the TAB key. ;; `completion-at-point' is often bound to M-TAB. (tab-always-indent 'complete) ;; Emacs 30 and newer: Disable Ispell completion function. ;; Try `cape-dict' as an alternative. (text-mode-ispell-word-completion nil) ;; Hide commands in M-x which do not apply to the current mode. Corfu ;; commands are hidden, since they are not used via M-x. This setting is ;; useful beyond Corfu. (read-extended-command-predicate #'command-completion-default-include-p)) #+end_src Dabbrev completion is based on =completion-in-region= and can be used with Corfu. You may want to swap the =dabbrev-completion= with the =dabbrev-expand= key for easier access, if you prefer completion. Also take a look at the =cape-dabbrev= completion at point function provided by my [[https://github.com/minad/cape][Cape]] package. #+begin_src emacs-lisp ;; Use Dabbrev with Corfu! (use-package dabbrev ;; Swap M-/ and C-M-/ :bind (("M-/" . dabbrev-completion) ("C-M-/" . dabbrev-expand)) :config (add-to-list 'dabbrev-ignored-buffer-regexps "\\` ") ;; Available since Emacs 29 (Use `dabbrev-ignored-buffer-regexps' on older Emacs) (add-to-list 'dabbrev-ignored-buffer-modes 'authinfo-mode) (add-to-list 'dabbrev-ignored-buffer-modes 'doc-view-mode) (add-to-list 'dabbrev-ignored-buffer-modes 'pdf-view-mode) (add-to-list 'dabbrev-ignored-buffer-modes 'tags-table-mode)) #+end_src If you start to configure Corfu more thoroughly, I recommend to give the Orderless completion style a try for filtering. Orderless completion offers more flexible filtering than the default completion styles. Note that Orderless is not a necessity; Corfu can be used just as well with the default completion styles. #+begin_src emacs-lisp ;; Optionally use the `orderless' completion style. (use-package orderless :custom ;; (orderless-style-dispatchers '(orderless-affix-dispatch)) ;; (orderless-component-separator #'orderless-escapable-split-on-space) (completion-styles '(orderless basic)) (completion-category-defaults nil) (completion-category-overrides '((file (styles partial-completion))))) #+end_src The =basic= completion style is specified as fallback in addition to =orderless= in order to ensure that completion commands which rely on dynamic completion tables, e.g., ~completion-table-dynamic~ or ~completion-table-in-turn~, work correctly. Additionally enable =partial-completion= for file path expansion. =partial-completion= is important for file wildcard support. Multiple files can be opened at once with =find-file= if you enter a wildcard. You may also give the =initials= completion style a try. See also the [[https://github.com/minad/corfu/wiki][Corfu Wiki]] and the [[https://github.com/minad/cape][Cape manual]] for additional Capf configuration tips. For more general documentation read the chapter about completion in the [[https://www.gnu.org/software/emacs/manual/html_node/emacs/Completion.html][Emacs manual]]. If you want to create your own Capfs, you can find documentation about completion in the [[https://www.gnu.org/software/emacs/manual/html_node/elisp/Completion.html][Elisp manual]]. ** Auto completion Auto completion is disabled by default for safety and unobtrusiveness. Note that completion can be vulnerable to arbitrary code execution. Auto completion can be enabled by setting ~corfu-auto~ to t. Only enable auto completion locally in trusted buffers or globally if you edit trusted files only. You may want to configure Corfu to quit completion eagerly, such that the completion popup stays out of your way when it appeared unexpectedly. #+begin_src emacs-lisp ;; Enable auto completion and configure quitting (setq corfu-auto t corfu-quit-no-match 'separator) ;; or t #+end_src I suggest to experiment with the various settings and key bindings to find a configuration which works for you. There is no one perfect configuration which fits all. Some people like auto completion, some like manual completion, some want to cycle with TAB and some with the arrow keys. In case you like auto completion settings, where the completion popup appears immediately, better use a cheap completion style like =basic=, which performs prefix filtering. See the next section about setting Corfu-only completion styles. In this case Corfu completion should still be fast in buffers with efficient completion backends. You can try the following settings in an Elisp buffer or the Emacs scratch buffer. Note that such settings can slow down Emacs due to the high load on the Lisp runtime and garbage collector. #+begin_src emacs-lisp (setq corfu-auto t corfu-auto-delay 0 ;; TOO SMALL - NOT RECOMMENDED! corfu-auto-prefix 0) ;; TOO SMALL - NOT RECOMMENDED! (add-hook 'corfu-mode-hook (lambda () ;; Settings only for Corfu (setq-local completion-styles '(basic) completion-category-overrides nil completion-category-defaults nil))) #+end_src ** Buffer-local/Corfu-only completion styles Sometimes it makes sense to use separate completion style settings for minibuffer completion and in-buffer Corfu completion. For example inside the minibuffer you may prefer advanced Orderless completion, while for Corfu, faster prefix completion is needed or literal-only completion is sufficient. This matters in particular if you use aggressive auto completion settings, where the completion popup appears immediately. Then a cheap completion style like =basic= should be used, which performs prefix filtering only. Such Corfu-only configurations are possible by setting the ~completion-styles~ variables buffer-locally, as follows: #+begin_src emacs-lisp (orderless-define-completion-style orderless-literal-only (orderless-style-dispatchers nil) (orderless-matching-styles '(orderless-literal))) (add-hook 'corfu-mode-hook (lambda () (setq-local completion-styles '(orderless-literal-only basic) completion-category-overrides nil completion-category-defaults nil))) #+end_src If you want to combine fast prefix filtering and Orderless filtering you can still do that by defining a custom Orderless completion style via =orderless-define-completion-style=. We use a custom style dispatcher, which enables efficient prefix filtering for input shorter than 4 characters. #+begin_src emacs-lisp (defun orderless-fast-dispatch (word index total) (and (= index 0) (= total 1) (length< word 4) (cons 'orderless-literal-prefix word))) (orderless-define-completion-style orderless-fast (orderless-style-dispatchers '(orderless-fast-dispatch)) (orderless-matching-styles '(orderless-literal orderless-regexp))) (setq corfu-auto t corfu-auto-delay 0 ;; TOO SMALL - NOT RECOMMENDED corfu-auto-prefix 0) ;; TOO SMALL - NOT RECOMMENDED (add-hook 'corfu-mode-hook (lambda () (setq-local completion-styles '(orderless-fast basic) completion-category-overrides nil completion-category-defaults nil))) #+end_src ** Completing in the minibuffer Corfu can be used for completion in the minibuffer, since it relies on child frames to display the candidates. The Corfu popup floats on top of the Emacs frame and can be shown even if it doesn't fit inside the minibuffer. ~global-corfu-mode~ activates ~corfu-mode~ in the minibuffer if the variable ~global-corfu-minibuffer~ is non-nil. In order to avoid interference with specialised minibuffer completion UIs like Vertico or Mct, Corfu is only enabled if the minibuffer sets the variable ~completion-at-point-functions~ locally. This way minibuffers with completion can be detected, such that minibuffer commands like ~M-:~ (~eval-expression~) or ~M-!~ (~shell-command~) are enhanced with Corfu completion. If needed, one can also enable Corfu more generally in all minibuffers, as long as no completion UI is active. In the following example we set ~global-corfu-minibuffer~ to a predicate function, which checks for Mct and Vertico. Furthermore we ensure that Corfu is not enabled if a password is read from the minibuffer. #+begin_src emacs-lisp (setq global-corfu-minibuffer (lambda () (not (or (bound-and-true-p mct--active) (bound-and-true-p vertico--input) (eq (current-local-map) read-passwd-map))))) #+end_src ** Completing in the Eshell or Shell When completing in the Eshell I recommend conservative local settings without auto completion, such that the completion behavior is similar to widely used shells like Bash, Zsh or Fish. #+begin_src emacs-lisp (add-hook 'eshell-mode-hook (lambda () (setq-local corfu-auto nil) (corfu-mode))) #+end_src When pressing =RET= while the Corfu popup is visible, the ~corfu-insert~ command will be invoked. This command does inserts the currently selected candidate, but it does not send the prompt input to Eshell or the Comint process. Therefore you often have to press =RET= twice which feels like an unnecessary double confirmation. Fortunately it is easy to improve this by using the command ~corfu-send~ instead. #+begin_src emacs-lisp (keymap-set corfu-map "RET" #'corfu-send) #+end_src Shell completion uses the flexible Pcomplete mechanism internally, which allows you to program the completions per shell command. If you want to know more, look into this [[https://www.masteringemacs.org/article/pcomplete-context-sensitive-completion-emacs][blog post]], which shows how to configure Pcomplete for git commands. Since Emacs 29, Pcomplete offers the =pcomplete-from-help= function which parses the ~--help~ output of a command and produces completions for command line options. Pcomplete has a few bugs on Emacs 28. We can work around the issues with the [[https://github.com/minad/cape][Cape]] library (Completion at point extensions). Cape provides wrappers which sanitize the Pcomplete function. On Emacs 29 the advices should not be necessary anymore, since most relevant bugs have been fixed. In case you discover any remaining Pcomplete issues, please report them upstream. #+begin_src emacs-lisp ;; Sanitize the `pcomplete-completions-at-point' Capf. The Capf has undesired ;; side effects on Emacs 28. These advices are not needed on Emacs 29 and newer. (when (< emacs-major-version 29) (advice-add 'pcomplete-completions-at-point :around #'cape-wrap-silent) (advice-add 'pcomplete-completions-at-point :around #'cape-wrap-purify)) #+end_src ** Orderless completion [[https://github.com/oantolin/orderless][Orderless]] is an advanced completion style that supports multi-component search filters separated by a configurable character (space, by default). Normally, entering characters like space which lie outside the completion region boundaries (words, typically) causes Corfu to quit. This behavior is helpful with auto-completion, which may pop-up when not desired, e.g. on entering a new variable name. Just keep typing and Corfu will get out of the way. But orderless search terms can contain arbitrary characters; they are also interpreted as regular expressions. To use orderless, set ~corfu-separator~ (a space, by default) to the primary character of your orderless component separator. Then, when a new orderless component is desired, use =M-SPC= (~corfu-insert-separator~) to enter the first component separator in the input, and arbitrary orderless search terms and new separators can be entered thereafter. To treat the entire input as Orderless input, you can set the customization option ~corfu-quit-at-boundary~ to nil. This disables the predicate which checks if the current completion boundary has been left. In contrast, if you always want to quit at the boundary, set ~corfu-quit-at-boundary~ to t. By default ~corfu-quit-at-boundary~ is set to ~separator~ which quits at completion boundaries as long as no separator has been inserted with ~corfu-insert-separator~. Finally, there exists the user option ~corfu-quit-no-match~ which is set to =separator= by default. With this setting Corfu stays alive as soon as you start advanced filtering with a ~corfu-separator~ even if there are no matches, for example due to a typo. As long as no separator character has been inserted with ~corfu-insert-separator~, Corfu will still quit if there are no matches. This ensures that the Corfu popup goes away quickly if completion is not possible. In the following we show two configurations, one which works best with auto completion and one which may work better with manual completion if you prefer to always use =SPC= to separate the Orderless components. #+begin_src emacs-lisp ;; Auto completion example (use-package corfu :custom (corfu-auto t) ;; Enable auto completion ;; (corfu-separator ?_) ;; Set to orderless separator, if not using space :bind ;; Another key binding can be used, such as S-SPC. ;; (:map corfu-map ("M-SPC" . corfu-insert-separator)) :init (global-corfu-mode)) ;; Manual completion example (use-package corfu :custom ;; (corfu-separator ?_) ;; Set to orderless separator, if not using space :bind ;; Configure SPC for separator insertion (:map corfu-map ("SPC" . corfu-insert-separator)) :init (global-corfu-mode)) #+end_src ** TAB-only completion By default, Corfu steals both the ~RET~ and ~TAB~ keys, when the Corfu popup is open. This can feel intrusive, in particular in combination with auto completion. ~RET~ may accidentally commit an automatically selected candidate, while you actually wanted to start a new line. As an alternative we can unbind the ~RET~ key completely from ~corfu-map~ or reserve the ~RET~ key only in shell modes using a menu-item filter. #+begin_src emacs-lisp ;; TAB-only configuration (use-package corfu :custom (corfu-auto t) ;; Enable auto completion (corfu-preselect 'directory) ;; Select the first candidate, except for directories :init (global-corfu-mode) :config ;; Free the RET key for less intrusive behavior. ;; Option 1: Unbind RET completely ;; (keymap-unset corfu-map "RET") ;; Option 2: Use RET only in shell modes (keymap-set corfu-map "RET" `( menu-item "" nil :filter ,(lambda (&optional _) (and (derived-mode-p 'eshell-mode 'comint-mode) #'corfu-send))))) #+end_src ** TAB-and-Go completion You may be interested in configuring Corfu in TAB-and-Go style. Pressing TAB moves to the next candidate and further input will then commit the selection. Note that further input will not expand snippets or templates, which may not be desired but which leads overall to a more predictable behavior. In order to force snippet expansion, confirm a candidate explicitly with ~RET~. #+begin_src emacs-lisp (use-package corfu ;; TAB-and-Go customizations :custom (corfu-cycle t) ;; Enable cycling for `corfu-next/previous' (corfu-preselect 'prompt) ;; Always preselect the prompt ;; Use TAB for cycling, default is `corfu-complete'. :bind (:map corfu-map ("TAB" . corfu-next) ([tab] . corfu-next) ("S-TAB" . corfu-previous) ([backtab] . corfu-previous)) :init (global-corfu-mode)) #+end_src ** Transfer completion to the minibuffer Sometimes it is useful to transfer the Corfu completion session to the minibuffer, since the minibuffer offers richer interaction features. In particular, [[https://github.com/oantolin/embark][Embark]] is available in the minibuffer, such that you can act on the candidates or export/collect the candidates to a separate buffer. We could add Corfu support to Embark in the future, such that export or collect is possible directly from Corfu. Nevertheless, the ability to transfer the Corfu completion to the minibuffer is even more powerful, since further completion is possible. The command ~corfu-move-to-minibuffer~ is defined here in terms of ~consult-completion-in-region~, which uses the minibuffer completion UI via ~completing-read~. #+begin_src emacs-lisp (defun corfu-move-to-minibuffer () (interactive) (pcase completion-in-region--data (`(,beg ,end ,table ,pred ,extras) (let ((completion-extra-properties extras) completion-cycle-threshold completion-cycling) (consult-completion-in-region beg end table pred))))) (keymap-set corfu-map "M-m" #'corfu-move-to-minibuffer) (add-to-list 'corfu-continue-commands #'corfu-move-to-minibuffer) #+end_src * Extensions :properties: :custom_id: extensions :end: We maintain small extension packages to Corfu in this repository in the subdirectory [[https://github.com/minad/corfu/tree/main/extensions][extensions/]]. The extensions are installed together with Corfu if you pull the package from ELPA. The extensions are inactive by default and can be enabled manually if desired. Furthermore it is possible to install all of the files separately, both ~corfu.el~ and the ~corfu-*.el~ extensions. Currently the following extensions come with the Corfu ELPA package: - [[https://github.com/minad/corfu/blob/main/extensions/corfu-echo.el][corfu-echo]]: =corfu-echo-mode= displays a brief candidate documentation in the echo area. - [[https://github.com/minad/corfu/blob/main/extensions/corfu-history.el][corfu-history]]: =corfu-history-mode= remembers selected candidates and sorts the candidates by their history position and frequency. - [[https://github.com/minad/corfu/blob/main/extensions/corfu-indexed.el][corfu-indexed]]: =corfu-indexed-mode= allows you to select indexed candidates with prefix arguments. - [[https://github.com/minad/corfu/blob/main/extensions/corfu-info.el][corfu-info]]: Actions to access the candidate location and documentation. - [[https://github.com/minad/corfu/blob/main/extensions/corfu-popupinfo.el][corfu-popupinfo]]: Display candidate documentation or source in a popup next to the candidate menu. - [[https://github.com/minad/corfu/blob/main/extensions/corfu-quick.el][corfu-quick]]: Commands to select using Avy-style quick keys. See the Commentary of those files for configuration details. * Complementary packages Corfu works well together with all packages providing code completion via the ~completion-at-point-functions~. Many modes and packages already provide a Capf out of the box. Nevertheless you may want to look into complementary packages to enhance your setup. - [[https://code.bsdgeek.org/adam/corfu-candidate-overlay][corfu-candidate-overlay]]: Shows as-you-type auto-suggestion candidate overlay with a visual indication of whether there are many or exactly one candidate available (works only with =corfu-auto= disabled). - [[https://codeberg.org/akib/emacs-corfu-terminal][corfu-terminal]]: Child frames are supported by terminal Emacs 31 out of the box. On older Emacs versions, this package provides an overlay-based popup display. - [[https://github.com/oantolin/orderless][Orderless]]: Corfu supports completion styles, including the advanced =orderless= completion style, where the filter expressions are separated by spaces or another character (see ~corfu-separator~). - [[https://github.com/minad/cape][Cape]]: Provides additional Capf backends and =completion-in-region= commands. Among others, the package supplies the file completion backend =cape-file= and the Dabbrev backend =cape-dabbrev=. Cape provides the ~cape-company-to-capf~ adapter to reuse Company backends in Corfu. - [[https://github.com/jdtsmith/kind-icon][kind-icon]], [[https://github.com/LuigiPiucco/nerd-icons-corfu][nerd-icons-corfu]]: Icons are supported by Corfu via external packages. The nerd-icons-corfu package relies on the Nerd icon font, which is supported on terminal, while kind-icon uses SVGs from monochromatic icon sets, or colored-coded text badges for terminal or simpler appearance. - [[https://github.com/minad/tempel][Tempel]]: Tiny template/snippet package with templates in Lisp syntax, which can be used in conjunction with Corfu. - [[https://github.com/minad/vertico][Vertico]]: You may also want to look into my Vertico package. Vertico is the minibuffer completion counterpart of Corfu. * Alternatives - [[https://github.com/company-mode/company-mode][Company]]: Company is a widely used and mature completion package, which implements a similar UI as Corfu. While Corfu relies exclusively on the standard Emacs completion API (Capfs), Company defines its own API for the backends. Company includes its own completion backends, following its own API, which are incompatible with the Emacs completion infrastructure. Company provides an adapter ~company-capf~ to handle Capfs as a Company backend. As a result of this design, Company is a more complex package than Corfu, three times as large, even without backends. Company by default uses overlays for the popup in contrast to the child frames used by Corfu. Overall both packages work well, but Company integrates less tightly with Emacs. The ~completion-styles~ support is more limited and the ~completion-at-point~ command and the ~completion-in-region~ function do not invoke Company. - [[https://github.com/minad/consult][consult-completion-in-region]]: The Consult package provides the function ~consult-completion-in-region~ which can be set as ~completion-in-region-function~ such that it handles ~completion-at-point~. The function works by transferring the in-buffer completion to the minibuffer. In the minibuffer, the minibuffer completion UI, for example [[https://github.com/minad/vertico][Vertico]] takes over. If you prefer to perform all your completions in the minibuffer ~consult-completion-in-region~ is your best option. * Debugging Corfu Corfu will automatically print a stack trace to the =*Messages*= buffer when an error is detected. The stack trace allows you to narrow down the exact code location which caused the error. When Capfs do not yield the expected result, you can wrap a Capf with ~cape-capf-debug~ from the [[https://github.com/minad/cape][Cape]] package, creating a new Capf, which adds completion log messages for debugging. The completion log messages are added to the =*Messages*= buffer. #+begin_src emacs-lisp (setq completion-at-point-functions (list (cape-capf-debug #'cape-dict))) #+end_src Sometimes you will find errors inside Capfs. Such errors are bugs in the Capfs must be fixed there, since they Corfu cannot work around them. * Contributions Since this package is part of [[https://elpa.gnu.org/packages/corfu.html][GNU ELPA]] contributions require a copyright assignment to the FSF. corfu-2.2/corfu.el000066400000000000000000002026711501476044300141470ustar00rootroot00000000000000;;; corfu.el --- COmpletion in Region FUnction -*- lexical-binding: t -*- ;; Copyright (C) 2021-2025 Free Software Foundation, Inc. ;; Author: Daniel Mendler ;; Maintainer: Daniel Mendler ;; Created: 2021 ;; Version: 2.2 ;; Package-Requires: ((emacs "28.1") (compat "30")) ;; URL: https://github.com/minad/corfu ;; Keywords: abbrev, convenience, matching, completion, text ;; This file is part of GNU Emacs. ;; 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: ;; Corfu enhances in-buffer completion with a small completion popup. ;; The current candidates are shown in a popup below or above the ;; point. The candidates can be selected by moving up and down. ;; Corfu is the minimalistic in-buffer completion counterpart of the ;; Vertico minibuffer UI. ;;; Code: (require 'compat) (eval-when-compile (require 'cl-lib) (require 'subr-x)) (defgroup corfu nil "COmpletion in Region FUnction." :link '(info-link :tag "Info Manual" "(corfu)") :link '(url-link :tag "Website" "https://github.com/minad/corfu") :link '(url-link :tag "Wiki" "https://github.com/minad/corfu/wiki") :link '(emacs-library-link :tag "Library Source" "corfu.el") :group 'convenience :group 'tools :group 'matching :prefix "corfu-") (defcustom corfu-count 10 "Maximal number of candidates to show." :type 'natnum) (defcustom corfu-scroll-margin 2 "Number of lines at the top and bottom when scrolling. The value should lie between 0 and corfu-count/2." :type 'natnum) (defcustom corfu-min-width 15 "Popup minimum width in characters." :type 'natnum) (defcustom corfu-max-width 100 "Popup maximum width in characters." :type 'natnum) (defcustom corfu-cycle nil "Enable cycling for `corfu-next' and `corfu-previous'." :type 'boolean) (defcustom corfu-on-exact-match 'insert "Configure how a single exact match should be handled. - nil: No special handling, continue completion. - insert: Insert candidate, quit and call the `:exit-function'. - quit: Quit completion without further action. - show: Initiate completion even for a single match only." :type '(choice (const insert) (const show) (const quit) (const nil))) (defcustom corfu-continue-commands '(ignore universal-argument universal-argument-more digit-argument "\\`corfu-" "\\`scroll-other-window") "Continue Corfu completion after executing these commands. The list can container either command symbols or regular expressions." :type '(repeat (choice regexp symbol))) (defcustom corfu-preview-current 'insert "Preview currently selected candidate. If the variable has the value `insert', the candidate is automatically inserted on further input." :type '(choice boolean (const insert))) (defcustom corfu-preselect 'valid "Configure if the prompt or first candidate is preselected. - prompt: Always select the prompt. - first: Always select the first candidate. - valid: Only select the prompt if valid and not equal to the first candidate. - directory: Like first, but select the prompt if it is a directory." :type '(choice (const prompt) (const valid) (const first) (const directory))) (defcustom corfu-separator ?\s "Component separator character. The character used for separating components in the input. The presence of this separator character will inhibit quitting at completion boundaries, so that any further characters can be entered. To enter the first separator character, call `corfu-insert-separator' (bound to M-SPC by default). Useful for multi-component completion styles such as Orderless." :type 'character) (defcustom corfu-quit-at-boundary 'separator "Automatically quit at completion boundary. nil: Never quit at completion boundary. t: Always quit at completion boundary. separator: Quit at boundary if no `corfu-separator' has been inserted." :type '(choice boolean (const separator))) (defcustom corfu-quit-no-match 'separator "Automatically quit if no matching candidate is found. When staying alive even if there is no match a warning message is shown in the popup. nil: Stay alive even if there is no match. t: Quit if there is no match. separator: Only stay alive if there is no match and `corfu-separator' has been inserted." :type '(choice boolean (const separator))) (defcustom corfu-left-margin-width 0.5 "Width of the left margin in units of the character width." :type 'float) (defcustom corfu-right-margin-width 0.5 "Width of the right margin in units of the character width." :type 'float) (defcustom corfu-bar-width 0.2 "Width of the bar in units of the character width." :type 'float) (defcustom corfu-margin-formatters nil "Registry for margin formatter functions. Each function of the list is called with the completion metadata as argument until an appropriate formatter is found. The function should return a formatter function, which takes the candidate string and must return a string, possibly an icon. In order to preserve correct popup alignment, the length and display width of the returned string must precisely span the same number of characters of the fixed-width popup font. For example the kind-icon package returns a string of length 3 with a display width of 3 characters." :type 'hook) (defcustom corfu-sort-function #'corfu-sort-length-alpha "Default sorting function. This function is used if the completion table does not specify a `display-sort-function'." :type `(choice (const :tag "No sorting" nil) (const :tag "By length and alpha" ,#'corfu-sort-length-alpha) (function :tag "Custom function"))) (defcustom corfu-sort-override-function nil "Override sort function which overrides the `display-sort-function'. This function is used even if a completion table specifies its own sort function." :type '(choice (const nil) function)) (defcustom corfu-auto-prefix 3 "Minimum length of prefix for auto completion. The completion backend can override this with :company-prefix-length. It is *not recommended* to use a small prefix length (below 2), since this will create high load for Emacs. See also `corfu-auto-delay'." :type 'natnum) (defcustom corfu-auto-delay 0.2 "Delay for auto completion. It is *not recommended* to use a short delay or even 0, since this will create high load for Emacs, in particular if executing the completion backend is costly." :type 'float) (defcustom corfu-auto-commands '("self-insert-command\\'" "delete-backward-char\\'" "\\`backward-delete-char" c-electric-colon c-electric-lt-gt c-electric-slash c-scope-operator) "Commands which initiate auto completion. The list can container either command symbols or regular expressions." :type '(repeat (choice regexp symbol))) (defcustom corfu-auto nil "Enable auto completion. Auto completion is disabled by default for safety and unobtrusiveness. Note that auto completion is particularly dangerous in untrusted files since some completion functions may perform arbitrary code execution, notably the Emacs built-in `elisp-completion-at-point' . See also the settings `corfu-auto-delay', `corfu-auto-prefix' and `corfu-auto-commands'." :type 'boolean) (defgroup corfu-faces nil "Faces used by Corfu." :group 'corfu :group 'faces) (defface corfu-default '((((class color) (min-colors 88) (background dark)) :background "#191a1b") (((class color) (min-colors 88) (background light)) :background "#f0f0f0") (t :background "gray")) "Default face, foreground and background colors used for the popup.") (defface corfu-current '((((class color) (min-colors 88) (background dark)) :background "#00415e" :foreground "white" :extend t) (((class color) (min-colors 88) (background light)) :background "#c0efff" :foreground "black" :extend t) (t :background "blue" :foreground "white" :extend t)) "Face used to highlight the currently selected candidate.") (defface corfu-bar '((((class color) (min-colors 88) (background dark)) :background "#a8a8a8") (((class color) (min-colors 88) (background light)) :background "#505050") (t :background "gray")) "The background color is used for the scrollbar indicator.") (defface corfu-border '((((class color) (min-colors 88) (background dark)) :background "#323232") (((class color) (min-colors 88) (background light)) :background "#d7d7d7") (t :background "gray")) "The background color used for the thin border.") (defface corfu-annotations '((t :inherit completions-annotations)) "Face used for annotations.") (defface corfu-deprecated '((t :inherit shadow :strike-through t)) "Face used for deprecated candidates.") (defvar-keymap corfu-mode-map :doc "Keymap used when `corfu-mode' is active.") (defvar-keymap corfu-map :doc "Keymap used when popup is shown." " " #'corfu-prompt-beginning " " #'corfu-prompt-end " " #'corfu-first " " #'corfu-last " " #'corfu-scroll-down " " #'corfu-scroll-up " " #'corfu-next " " #'corfu-previous " " #'corfu-complete " " #'corfu-reset "" #'corfu-next "" #'corfu-previous "M-n" #'corfu-next "M-p" #'corfu-previous "C-g" #'corfu-quit "RET" #'corfu-insert "TAB" #'corfu-complete "M-TAB" #'corfu-expand "M-g" 'corfu-info-location "M-h" 'corfu-info-documentation "M-SPC" #'corfu-insert-separator) (defvar corfu--auto-timer (timer-create) "Auto completion timer.") (defvar corfu--candidates nil "List of candidates.") (defvar corfu--metadata nil "Completion metadata.") (defvar corfu--base "" "Base string, which is concatenated with the candidate.") (defvar corfu--total 0 "Length of the candidate list `corfu--candidates'.") (defvar corfu--hilit #'identity "Lazy candidate highlighting function.") (defvar corfu--index -1 "Index of current candidate or negative for prompt selection.") (defvar corfu--preselect -1 "Index of preselected candidate, negative for prompt selection.") (defvar corfu--scroll 0 "Scroll position.") (defvar corfu--input nil "Cons of last prompt contents and point.") (defvar corfu--preview-ov nil "Current candidate overlay.") (defvar corfu--change-group nil "Undo change group.") (defvar corfu--frame nil "Popup frame.") (defvar corfu--width 0 "Popup width of current completion to reduce width fluctuations.") (defconst corfu--initial-state (mapcar (lambda (k) (cons k (symbol-value k))) '(corfu--base corfu--candidates corfu--hilit corfu--index corfu--preselect corfu--scroll corfu--input corfu--total corfu--preview-ov corfu--change-group corfu--metadata corfu--width)) "Initial Corfu state.") (defvar corfu--frame-parameters '((no-accept-focus . t) (no-focus-on-map . t) (min-width . t) (min-height . t) (border-width . 0) (outer-border-width . 0) (internal-border-width . 1) (child-frame-border-width . 1) (vertical-scroll-bars . nil) (horizontal-scroll-bars . nil) (menu-bar-lines . 0) (tool-bar-lines . 0) (tab-bar-lines . 0) (tab-bar-lines-keep-state . t) (no-other-frame . t) (unsplittable . t) (undecorated . t) (cursor-type . nil) (no-special-glyphs . t) (desktop-dont-save . t)) "Default child frame parameters.") (defvar corfu--buffer-parameters '((mode-line-format . nil) (header-line-format . nil) (tab-line-format . nil) (tab-bar-format . nil) (frame-title-format . "") (truncate-lines . t) (cursor-in-non-selected-windows . nil) (cursor-type . nil) (show-trailing-whitespace . nil) (display-line-numbers . nil) (left-fringe-width . 0) (right-fringe-width . 0) (left-margin-width . 0) (right-margin-width . 0) (fringes-outside-margins . 0) (fringe-indicator-alist (continuation) (truncation)) (indicate-empty-lines . nil) (indicate-buffer-boundaries . nil) (buffer-read-only . t)) "Default child frame buffer parameters.") (defvar corfu--mouse-ignore-map (let ((map (define-keymap "" #'ignore))) (dotimes (i 7) (dolist (k '(mouse down-mouse drag-mouse double-mouse triple-mouse)) (keymap-set map (format "<%s-%s>" k (1+ i)) #'ignore))) map) "Ignore all mouse clicks.") (defun corfu--replace (beg end str) "Replace range between BEG and END with STR." (unless (equal str (buffer-substring-no-properties beg end)) ;; bug#55205: completion--replace removed properties as an unwanted ;; side-effect. We also don't want to leave text properties. (completion--replace beg end (substring-no-properties str)))) (defun corfu--capf-wrapper (fun &optional prefix) "Wrapper for `completion-at-point' FUN. The wrapper determines if the Capf is applicable at the current position and performs sanity checking on the returned result. For non-exclusive Capfs, the wrapper checks if the current input can be completed. PREFIX is a prefix length override, which is t for manual completion." (pcase (funcall fun) ((and res `(,beg ,end ,table . ,plist)) (and (integer-or-marker-p beg) ;; Valid Capf result (<= beg (point) end) ;; Sanity checking ;; When auto completing, check the prefix length! (let ((len (or prefix (plist-get plist :company-prefix-length) (- (point) beg)))) (or (eq len t) (>= len corfu-auto-prefix))) ;; For non-exclusive Capfs, check for valid completion. (or (not (eq 'no (plist-get plist :exclusive))) (let* ((str (buffer-substring-no-properties beg end)) (pt (- (point) beg)) (pred (plist-get plist :predicate)) (md (completion-metadata (substring str 0 pt) table pred))) ;; We use `completion-try-completion' to check if there are ;; completions. The upstream `completion--capf-wrapper' uses ;; `try-completion' which is incorrect since it only checks for ;; prefix completions. (completion-try-completion str table pred pt md))) (cons fun res))))) (defun corfu--make-buffer (name) "Create buffer with NAME." (let ((fr face-remapping-alist) (ls line-spacing) (buffer (get-buffer-create name))) (with-current-buffer buffer ;;; XXX HACK install mouse ignore map (use-local-map corfu--mouse-ignore-map) (dolist (var corfu--buffer-parameters) (set (make-local-variable (car var)) (cdr var))) (setq-local face-remapping-alist (copy-tree fr) line-spacing ls) (cl-pushnew 'corfu-default (alist-get 'default face-remapping-alist)) buffer))) (defvar x-gtk-resize-child-frames) ;; Not present on non-gtk builds (defvar corfu--gtk-resize-child-frames (let ((case-fold-search t)) ;; XXX HACK to fix resizing on gtk3/gnome taken from posframe.el ;; More information: ;; * https://github.com/minad/corfu/issues/17 ;; * https://gitlab.gnome.org/GNOME/mutter/-/issues/840 ;; * https://lists.gnu.org/archive/html/emacs-devel/2020-02/msg00001.html (and (string-match-p "gtk3" system-configuration-features) (string-match-p "gnome\\|cinnamon" (or (getenv "XDG_CURRENT_DESKTOP") (getenv "DESKTOP_SESSION") "")) 'resize-mode))) ;; Function adapted from posframe.el by tumashu (defun corfu--make-frame (frame x y width height) "Show current buffer in child frame at X/Y with WIDTH/HEIGHT. FRAME is the existing frame." (when-let (((frame-live-p frame)) (timer (frame-parameter frame 'corfu--hide-timer))) (cancel-timer timer) (set-frame-parameter frame 'corfu--hide-timer nil)) (let* ((window-min-height 1) (window-min-width 1) (inhibit-redisplay t) (x-gtk-resize-child-frames corfu--gtk-resize-child-frames) (before-make-frame-hook) (after-make-frame-functions) (parent (window-frame))) (unless (and (frame-live-p frame) (eq (frame-parent frame) (and (not (bound-and-true-p exwm--connection)) parent)) ;; If there is more than one window, `frame-root-window' may ;; return nil. Recreate the frame in this case. (window-live-p (frame-root-window frame))) (when frame (delete-frame frame)) (setq frame (make-frame `((parent-frame . ,parent) (minibuffer . ,(minibuffer-window parent)) (width . 0) (height . 0) (visibility . nil) (right-fringe . ,right-fringe-width) (left-fringe . ,left-fringe-width) ,@corfu--frame-parameters)))) ;; XXX HACK Setting the same frame-parameter/face-background is not a nop. ;; Check before applying the setting. Without the check, the frame flickers ;; on Mac. We have to apply the face background before adjusting the frame ;; parameter, otherwise the border is not updated. (let ((new (face-attribute 'corfu-border :background nil 'default))) (unless (equal (face-attribute 'internal-border :background frame 'default) new) (set-face-background 'internal-border new frame)) ;; XXX The Emacs Mac Port does not support `internal-border', we also have ;; to set `child-frame-border'. (unless (or (not (facep 'child-frame-border)) (equal (face-attribute 'child-frame-border :background frame 'default) new)) (set-face-background 'child-frame-border new frame))) ;; Reset frame parameters if they changed. For example `tool-bar-mode' ;; overrides the parameter `tool-bar-lines' for every frame, including child ;; frames. The child frame API is a pleasure to work with. It is full of ;; lovely surprises. (let* ((win (frame-root-window frame)) (is (frame-parameters frame)) (should `((background-color . ,(face-attribute 'corfu-default :background nil 'default)) (font . ,(frame-parameter parent 'font)) (right-fringe . ,right-fringe-width) (left-fringe . ,left-fringe-width) ,@corfu--frame-parameters)) (diff (cl-loop for p in should for (k . v) = p unless (equal (alist-get k is) v) collect p))) (when diff (modify-frame-parameters frame diff)) ;; XXX HACK: `set-window-buffer' must be called to force fringe update. (when (or diff (eq (window-buffer win) (current-buffer))) (set-window-buffer win (current-buffer))) ;; Disallow selection of root window (gh:minad/corfu#63) (set-window-parameter win 'no-delete-other-windows t) (set-window-parameter win 'no-other-window t) ;; Mark window as dedicated to prevent frame reuse (gh:minad/corfu#60) (set-window-dedicated-p win t)) (redirect-frame-focus frame parent) (set-frame-size frame width height t) (pcase-let ((`(,px . ,py) (frame-position frame))) (unless (and (= x px) (= y py)) (set-frame-position frame x y)))) (make-frame-visible frame) ;; Unparent child frame if EXWM is used, otherwise EXWM buffers are drawn on ;; top of the Corfu child frame. (when (and (bound-and-true-p exwm--connection) (frame-parent frame)) (set-frame-parameter frame 'parent-frame nil)) frame) (defun corfu--hide-frame-deferred (frame) "Deferred hiding of child FRAME." (when (and (frame-live-p frame) (frame-visible-p frame)) (set-frame-parameter frame 'corfu--hide-timer nil) (make-frame-invisible frame) (with-current-buffer (window-buffer (frame-root-window frame)) (with-silent-modifications (delete-region (point-min) (point-max)))))) (defun corfu--hide-frame (frame) "Hide child FRAME." (when (and (frame-live-p frame) (frame-visible-p frame) (not (frame-parameter frame 'corfu--hide-timer))) (set-frame-parameter frame 'corfu--hide-timer (run-at-time 0 nil #'corfu--hide-frame-deferred frame)))) (defun corfu--move-to-front (elem list) "Move ELEM to front of LIST." ;; In contrast to Vertico, this function handles duplicates. See also the ;; special deduplication function `corfu--delete-dups' based on ;; `equal-including-properties' (nconc (cl-loop for x in list if (equal x elem) collect x) (delete elem list))) (defun corfu--filter-completions (&rest args) "Compute all completions for ARGS with lazy highlighting." (dlet ((completion-lazy-hilit t) (completion-lazy-hilit-fn nil)) (static-if (>= emacs-major-version 30) (cons (apply #'completion-all-completions args) completion-lazy-hilit-fn) (cl-letf* ((orig-pcm (symbol-function #'completion-pcm--hilit-commonality)) (orig-flex (symbol-function #'completion-flex-all-completions)) ((symbol-function #'completion-flex-all-completions) (lambda (&rest args) ;; Unfortunately for flex we have to undo the lazy highlighting, since flex uses ;; the completion-score for sorting, which is applied during highlighting. (cl-letf (((symbol-function #'completion-pcm--hilit-commonality) orig-pcm)) (apply orig-flex args)))) ((symbol-function #'completion-pcm--hilit-commonality) (lambda (pattern cands) (setq completion-lazy-hilit-fn (lambda (x) ;; `completion-pcm--hilit-commonality' sometimes throws an internal error ;; for example when entering "/sudo:://u". (condition-case nil (car (completion-pcm--hilit-commonality pattern (list x))) (t x)))) cands)) ((symbol-function #'completion-hilit-commonality) (lambda (cands prefix &optional base) (setq completion-lazy-hilit-fn (lambda (x) (car (completion-hilit-commonality (list x) prefix base)))) (and cands (nconc cands base))))) (cons (apply #'completion-all-completions args) completion-lazy-hilit-fn))))) (defsubst corfu--length-string< (x y) "Sorting predicate which compares X and Y first by length then by `string<'." (or (< (length x) (length y)) (and (= (length x) (length y)) (string< x y)))) (defmacro corfu--partition! (list form) "Evaluate FORM for every element and partition LIST." (cl-with-gensyms (head1 head2 tail1 tail2) `(let* ((,head1 (cons nil nil)) (,head2 (cons nil nil)) (,tail1 ,head1) (,tail2 ,head2)) (while ,list (if (let ((it (car ,list))) ,form) (progn (setcdr ,tail1 ,list) (pop ,tail1)) (setcdr ,tail2 ,list) (pop ,tail2)) (pop ,list)) (setcdr ,tail1 (cdr ,head2)) (setcdr ,tail2 nil) (setq ,list (cdr ,head1))))) (defun corfu--move-prefix-candidates-to-front (field cands) "Move CANDS which match prefix of FIELD to the beginning." (let* ((word (substring field 0 (seq-position field corfu-separator))) (len (length word))) (corfu--partition! cands (and (>= (length it) len) (eq t (compare-strings word 0 len it 0 len completion-ignore-case)))))) ;; bug#6581: `equal-including-properties' uses `eq' for properties until 29.1. ;; Approximate by comparing `text-properties-at' position 0. (defalias 'corfu--equal-including-properties (static-if (< emacs-major-version 29) (lambda (x y) (and (equal x y) (equal (text-properties-at 0 x) (text-properties-at 0 y)))) #'equal-including-properties)) (defun corfu--delete-dups (list) "Delete `equal-including-properties' consecutive duplicates from LIST." (let ((beg list)) (while (cdr beg) (let ((end (cdr beg))) (while (equal (car beg) (car end)) (pop end)) ;; The deduplication is quadratic in the number of duplicates. We can ;; avoid the quadratic complexity with a hash table which takes ;; properties into account (available since Emacs 28). (while (not (eq beg end)) (let ((dup beg)) (while (not (eq (cdr dup) end)) (if (corfu--equal-including-properties (car beg) (cadr dup)) (setcdr dup (cddr dup)) (pop dup)))) (pop beg))))) list) (defun corfu--sort-function () "Return the sorting function." (or corfu-sort-override-function (corfu--metadata-get 'display-sort-function) corfu-sort-function)) (defun corfu--recompute (str pt table pred) "Recompute state from STR, PT, TABLE and PRED." (pcase-let* ((before (substring str 0 pt)) (after (substring str pt)) (corfu--metadata (completion-metadata before table pred)) ;; bug#47678: `completion-boundaries' fails for `partial-completion' ;; if the cursor is moved before the slashes of "~//". ;; See also vertico.el which has the same issue. (bounds (condition-case nil (completion-boundaries before table pred after) (t (cons 0 (length after))))) (field (substring str (car bounds) (+ pt (cdr bounds)))) (completing-file (eq (corfu--metadata-get 'category) 'file)) (`(,all . ,hl) (corfu--filter-completions str table pred pt corfu--metadata)) (base (or (when-let ((z (last all))) (prog1 (cdr z) (setcdr z nil))) 0)) (corfu--base (substring str 0 base)) (pre nil)) ;; Filter the ignored file extensions. We cannot use modified predicate for ;; this filtering, since this breaks the special casing in the ;; `completion-file-name-table' for `file-exists-p' and `file-directory-p'. (when completing-file (setq all (completion-pcm--filename-try-filter all))) ;; Sort using the `display-sort-function' or the Corfu sort functions, and ;; delete duplicates with respect to `equal-including-properties'. This is ;; a deviation from the Vertico completion UI with more aggressive ;; deduplication, where candidates are compared with `equal'. Corfu ;; preserves candidates which differ in their text properties. Corfu tries ;; to preserve text properties as much as possible, when calling the ;; `:exit-function' to help Capfs with candidate disambiguation. This ;; matters in particular for Lsp backends, which produce duplicates for ;; overloaded methods. (setq all (corfu--delete-dups (funcall (or (corfu--sort-function) #'identity) all)) all (corfu--move-prefix-candidates-to-front field all)) (when (and completing-file (not (string-suffix-p "/" field))) (setq all (corfu--move-to-front (concat field "/") all))) (setq all (corfu--move-to-front field all) pre (if (or (eq corfu-preselect 'prompt) (not all) (and completing-file (eq corfu-preselect 'directory) (= (length corfu--base) (length str)) (test-completion str table pred)) (and (eq corfu-preselect 'valid) (not (equal field (car all))) (not (and completing-file (equal (concat field "/") (car all)))) (test-completion str table pred))) -1 0)) `((corfu--base . ,corfu--base) (corfu--metadata . ,corfu--metadata) (corfu--candidates . ,all) (corfu--total . ,(length all)) (corfu--hilit . ,(or hl #'identity)) (corfu--preselect . ,pre) (corfu--index . ,(or (and (>= corfu--index 0) (/= corfu--index corfu--preselect) (seq-position all (nth corfu--index corfu--candidates))) pre))))) (defun corfu--update (&optional interruptible) "Update state, optionally INTERRUPTIBLE." (pcase-let* ((`(,beg ,end ,table ,pred . ,_) completion-in-region--data) (pt (- (point) beg)) (str (buffer-substring-no-properties beg end)) (input (cons str pt))) (unless (equal corfu--input input) ;; Redisplay such that the input is immediately shown before the expensive ;; candidate recomputation (gh:minad/corfu#48). See also corresponding ;; issue gh:minad/vertico#89. (when interruptible (redisplay)) ;; Bind non-essential=t to prevent Tramp from opening new connections, ;; without the user explicitly requesting it via M-TAB. (pcase (let ((non-essential t)) (if interruptible (while-no-input (corfu--recompute str pt table pred)) (corfu--recompute str pt table pred))) ('nil (keyboard-quit)) ((and state (pred consp)) (setq corfu--input input) (dolist (s state) (set (car s) (cdr s)))))) input)) (defun corfu--match-symbol-p (pattern sym) "Return non-nil if SYM is matching an element of the PATTERN list." (cl-loop with case-fold-search = nil for x in (and (symbolp sym) pattern) thereis (if (symbolp x) (eq sym x) (string-match-p x (symbol-name sym))))) (defun corfu--metadata-get (prop) "Return PROP from completion metadata." ;; Marginalia and various icon packages advise `completion-metadata-get' to ;; inject their annotations, but are meant only for minibuffer completion. ;; Therefore call `completion-metadata-get' without advices here. (let ((completion-extra-properties (nth 4 completion-in-region--data))) (funcall (advice--cd*r (symbol-function (compat-function completion-metadata-get))) corfu--metadata prop))) (defun corfu--format-candidates (cands) "Format annotated CANDS." (cl-loop for c in cands do (cl-loop for s in-ref c do (setf s (replace-regexp-in-string "[ \t]*\n[ \t]*" " " s)))) (let* ((cw (cl-loop for x in cands maximize (string-width (car x)))) (pw (cl-loop for x in cands maximize (string-width (cadr x)))) (sw (cl-loop for x in cands maximize (string-width (caddr x)))) (width (min (max corfu--width corfu-min-width (+ pw cw sw)) ;; -4 because of margins and some additional safety corfu-max-width (- (frame-width) 4))) (trunc (not (display-graphic-p)))) (setq corfu--width width) (list pw width (cl-loop for (cand prefix suffix) in cands collect (let ((s (concat prefix (make-string (- pw (string-width prefix)) ?\s) cand (when (> sw 0) (make-string (max 0 (- width pw (string-width cand) (string-width suffix))) ?\s)) suffix))) (if trunc (truncate-string-to-width s width) s)))))) (defun corfu--compute-scroll () "Compute new scroll position." (let ((off (max (min corfu-scroll-margin (/ corfu-count 2)) 0)) (corr (if (= corfu-scroll-margin (/ corfu-count 2)) (1- (mod corfu-count 2)) 0))) (setq corfu--scroll (min (max 0 (- corfu--total corfu-count)) (max 0 (+ corfu--index off 1 (- corfu-count)) (min (- corfu--index off corr) corfu--scroll)))))) (defun corfu--candidates-popup (pos) "Show candidates popup at POS." (corfu--compute-scroll) (pcase-let* ((last (min (+ corfu--scroll corfu-count) corfu--total)) (bar (ceiling (* corfu-count corfu-count) corfu--total)) (lo (min (- corfu-count bar 1) (floor (* corfu-count corfu--scroll) corfu--total))) (`(,mf . ,acands) (corfu--affixate (cl-loop repeat corfu-count for c in (nthcdr corfu--scroll corfu--candidates) collect (funcall corfu--hilit ;; bug#77754: Highlight unquoted string. (substring (or (get-text-property 0 'completion--unquoted c) c)))))) (`(,pw ,width ,fcands) (corfu--format-candidates acands)) ;; Disable the left margin if a margin formatter is active. (corfu-left-margin-width (if mf 0 corfu-left-margin-width))) ;; Nonlinearity at the end and the beginning (when (/= corfu--scroll 0) (setq lo (max 1 lo))) (when (/= last corfu--total) (setq lo (min (- corfu-count bar 2) lo))) (corfu--popup-show pos pw width fcands (- corfu--index corfu--scroll) (and (> corfu--total corfu-count) lo) bar))) (defun corfu--range-valid-p () "Check the completion range, return non-nil if valid." (pcase-let ((buf (current-buffer)) (pt (point)) (`(,beg ,end . ,_) completion-in-region--data)) (and beg end (eq buf (marker-buffer beg)) (eq buf (window-buffer)) (<= beg pt end) (save-excursion (goto-char beg) (<= (pos-bol) pt (pos-eol)))))) (defun corfu--continue-p () "Check if completion should continue after a command. Corfu bails out if the current buffer changed unexpectedly or if point moved out of range, see `corfu--range-valid-p'. Also the input must satisfy the `completion-in-region-mode--predicate' and the last command must be listed in `corfu-continue-commands'." (and (corfu--range-valid-p) ;; We keep Corfu alive if a `overriding-terminal-local-map' is ;; installed, e.g., the `universal-argument-map'. It would be good to ;; think about a better criterion instead. Unfortunately relying on ;; `this-command' alone is insufficient, since the value of ;; `this-command' gets clobbered in the case of transient keymaps. (or overriding-terminal-local-map ;; Check if it is an explicitly listed continue command (corfu--match-symbol-p corfu-continue-commands this-command) (pcase-let ((`(,beg ,end . ,_) completion-in-region--data)) (and (or (not corfu--input) (< beg end)) ;; Check for empty input (or (not corfu-quit-at-boundary) ;; Check separator or predicate (and (eq corfu-quit-at-boundary 'separator) (or (eq this-command #'corfu-insert-separator) ;; with separator, any further chars allowed (seq-contains-p (car corfu--input) corfu-separator))) (funcall completion-in-region-mode--predicate))))))) (defun corfu--preview-current-p () "Return t if the selected candidate is previewed." (and corfu-preview-current (>= corfu--index 0) (/= corfu--index corfu--preselect))) (defun corfu--preview-current (beg end) "Show current candidate as overlay given BEG and END." (when (corfu--preview-current-p) (corfu--preview-delete) (setq beg (+ beg (length corfu--base)) corfu--preview-ov (make-overlay beg end nil)) (overlay-put corfu--preview-ov 'priority 1000) (overlay-put corfu--preview-ov 'window (selected-window)) (overlay-put corfu--preview-ov (if (= beg end) 'after-string 'display) (substring-no-properties (nth corfu--index corfu--candidates))))) (defun corfu--preview-delete () "Delete the preview overlay." (when corfu--preview-ov (delete-overlay corfu--preview-ov) (setq corfu--preview-ov nil))) (defun corfu--window-change (_) "Window and buffer change hook which quits Corfu." (unless (corfu--range-valid-p) (corfu-quit))) (defun corfu--debug (&rest _) "Debugger used by `corfu--protect'." (let ((inhibit-message t)) (require 'backtrace) (declare-function backtrace-to-string "backtrace") (message "Corfu detected an error:\n%s" (backtrace-to-string))) (let (message-log-max) (message "%s %s" (propertize "Corfu detected an error:" 'face 'error) (substitute-command-keys "Press \\[view-echo-area-messages] to see the stack trace"))) nil) (defun corfu--protect (fun) "Protect FUN such that errors are caught. If an error occurs, the FUN is retried with `debug-on-error' enabled and the stack trace is shown in the *Messages* buffer." (static-if (>= emacs-major-version 30) (ignore-errors (handler-bind ((error #'corfu--debug)) (funcall fun))) (when (or debug-on-error (condition-case nil (progn (funcall fun) nil) (error t))) (let ((debug-on-error t) (debugger #'corfu--debug)) (condition-case nil (funcall fun) ((debug error) nil)))))) (defun corfu--post-command () "Refresh Corfu after last command." (corfu--protect (lambda () (if (corfu--continue-p) (corfu--exhibit) (corfu-quit)) (when corfu-auto (corfu--auto-post-command))))) (defun corfu--goto (index) "Go to candidate with INDEX." (setq corfu--index (max corfu--preselect (min index (1- corfu--total))))) (defun corfu--exit-function (str status cands) "Call the `:exit-function' with STR and STATUS. Lookup STR in CANDS to restore text properties." (when-let ((exit (plist-get completion-extra-properties :exit-function))) (funcall exit (or (car (member str cands)) str) status))) (defun corfu--done (str status cands) "Exit completion and call the exit function with STR and STATUS. Lookup STR in CANDS to restore text properties." (let ((completion-extra-properties (nth 4 completion-in-region--data))) ;; For successful completions, amalgamate undo operations, ;; such that completion can be undone in a single step. (undo-amalgamate-change-group corfu--change-group) (corfu-quit) (corfu--exit-function str status cands))) (defun corfu--setup (beg end table pred) "Setup Corfu completion state. See `completion-in-region' for the arguments BEG, END, TABLE, PRED." (setq beg (if (markerp beg) beg (copy-marker beg)) end (if (and (markerp end) (marker-insertion-type end)) end (copy-marker end t)) completion-in-region--data (list beg end table pred completion-extra-properties)) (completion-in-region-mode) (activate-change-group (setq corfu--change-group (prepare-change-group))) (setcdr (assq #'completion-in-region-mode minor-mode-overriding-map-alist) corfu-map) (add-hook 'pre-command-hook #'corfu--prepare nil 'local) (add-hook 'window-selection-change-functions #'corfu--window-change nil 'local) (add-hook 'window-buffer-change-functions #'corfu--window-change nil 'local) (add-hook 'post-command-hook #'corfu--post-command) ;; Disable default post-command handling, since we have our own ;; checks in `corfu--post-command'. (remove-hook 'post-command-hook #'completion-in-region--postch) (let ((sym (make-symbol "corfu--teardown")) (buf (current-buffer))) (fset sym (lambda () ;; Ensure that the tear-down runs in the correct buffer, if still alive. (unless completion-in-region-mode (remove-hook 'completion-in-region-mode-hook sym) (corfu--teardown buf)))) (add-hook 'completion-in-region-mode-hook sym))) (defun corfu--in-region (&rest args) "Corfu completion in region function called with ARGS." ;; XXX We can get an endless loop when `completion-in-region-function' is set ;; globally to `corfu--in-region'. This should never happen. (apply (if (corfu--popup-support-p) #'corfu--in-region-1 (default-value 'completion-in-region-function)) args)) (defun corfu--in-region-1 (beg end table &optional pred) "Complete in region, see `completion-in-region' for BEG, END, TABLE, PRED." (barf-if-buffer-read-only) ;; Restart the completion. This can happen for example if C-M-/ ;; (`dabbrev-completion') is pressed while the Corfu popup is already open. (when completion-in-region-mode (corfu-quit)) (let* ((pt (max 0 (- (point) beg))) (str (buffer-substring-no-properties beg end)) (metadata (completion-metadata (substring str 0 pt) table pred)) (threshold (completion--cycle-threshold metadata)) (completion-in-region-mode-predicate (or completion-in-region-mode-predicate #'always))) (pcase (completion-try-completion str table pred pt metadata) ('nil (corfu--message "No match") nil) ('t (goto-char end) (corfu--message "Sole match") (if (eq corfu-on-exact-match 'show) (corfu--setup beg end table pred) (corfu--exit-function str 'finished (alist-get 'corfu--candidates (corfu--recompute str pt table pred)))) t) (`(,newstr . ,newpt) (setq beg (if (markerp beg) beg (copy-marker beg)) end (copy-marker end t)) (corfu--replace beg end newstr) (goto-char (+ beg newpt)) (let* ((state (corfu--recompute newstr newpt table pred)) (base (alist-get 'corfu--base state)) (total (alist-get 'corfu--total state)) (cands (alist-get 'corfu--candidates state))) (cond ((<= total 1) ;; If completion is finished and cannot be extended further and ;; `corfu-on-exact-match' is not 'show, return 'finished. Otherwise ;; setup the popup. (if (and (= total 1) (or (eq corfu-on-exact-match 'show) (consp (completion-try-completion newstr table pred newpt (completion-metadata newstr table pred))))) (corfu--setup beg end table pred) (corfu--exit-function newstr 'finished cands))) ;; Too many candidates for cycling -> Setup popup. ((or (not threshold) (and (not (eq threshold t)) (< threshold total))) (corfu--setup beg end table pred)) (t ;; Cycle through candidates. (corfu--cycle-candidates total cands (+ (length base) beg) end) ;; Do not show Corfu when completion is finished after the candidate. (unless (equal (completion-boundaries (car cands) table pred "") '(0 . 0)) (corfu--setup beg end table pred))))) t)))) (defun corfu--message (&rest msg) "Show completion MSG." (let (message-log-max) (apply #'message msg))) (defun corfu--cycle-candidates (total cands beg end) "Cycle between TOTAL number of CANDS. See `completion-in-region' for the arguments BEG, END, TABLE, PRED." (let* ((idx 0) (map (make-sparse-keymap)) (replace (lambda () (interactive) (corfu--replace beg end (nth idx cands)) (corfu--message "Cycling %d/%d..." (1+ idx) total) (setq idx (mod (1+ idx) total)) (set-transient-map map)))) (define-key map [remap completion-at-point] replace) (define-key map [remap corfu-complete] replace) (define-key map (vector last-command-event) replace) (funcall replace))) (defun corfu--auto-complete-deferred (&optional tick) "Initiate auto completion if TICK did not change." (corfu--protect (lambda () (when (and (not completion-in-region-mode) (or (not tick) (equal tick (corfu--auto-tick)))) (pcase (while-no-input ;; Interruptible Capf query (run-hook-wrapped 'completion-at-point-functions #'corfu--capf-wrapper)) (`(,fun ,beg ,end ,table . ,plist) (let ((completion-in-region-mode-predicate (lambda () (when-let ((newbeg (car-safe (funcall fun)))) (= newbeg beg)))) (completion-extra-properties plist)) (corfu--setup beg end table (plist-get plist :predicate)) (corfu--exhibit 'auto)))))))) (defun corfu--auto-post-command () "Post command hook which initiates auto completion." (corfu--protect (lambda () (cancel-timer corfu--auto-timer) (when (and (not completion-in-region-mode) (not defining-kbd-macro) (not buffer-read-only) (corfu--match-symbol-p corfu-auto-commands this-command) (corfu--popup-support-p)) (if (<= corfu-auto-delay 0) (corfu--auto-complete-deferred) ;; Do not use `timer-set-idle-time' since this leads to ;; unpredictable pauses, in particular with `flyspell-mode'. (timer-set-time corfu--auto-timer (timer-relative-time nil corfu-auto-delay)) (timer-set-function corfu--auto-timer #'corfu--auto-complete-deferred (list (corfu--auto-tick))) (timer-activate corfu--auto-timer)))))) (defun corfu--auto-tick () "Return the current tick/status of the buffer. Auto completion is only performed if the tick did not change." (list (selected-window) (current-buffer) (buffer-chars-modified-tick) (point))) (cl-defgeneric corfu--popup-show (pos off width lines &optional curr lo bar) "Show LINES as popup at POS - OFF. WIDTH is the width of the popup. The current candidate CURR is highlighted. A scroll bar is displayed from LO to LO+BAR." (let ((lh (max (default-line-height) (cdr (posn-object-width-height pos))))) (with-current-buffer (corfu--make-buffer " *corfu*") (let* ((ch (default-line-height)) (cw (default-font-width)) ;; bug#74214, bug#37755, bug#37689: Even for larger fringes, fringe ;; bitmaps can only have a width between 1 and 16. Therefore we ;; restrict the fringe width to 16 pixel. This restriction may ;; cause problem on HDPi systems. Hopefully Emacs will adopt ;; larger fringe bitmaps in the future and lift the restriction. (ml (min 16 (ceiling (* cw corfu-left-margin-width)))) (mr (min 16 (ceiling (* cw corfu-right-margin-width)))) (bw (min mr (ceiling (* cw corfu-bar-width)))) (fringe (display-graphic-p)) (marginl (and (not fringe) (propertize " " 'display `(space :width (,ml))))) (sbar (if fringe #(" " 0 1 (display (right-fringe corfu--bar corfu--bar))) (concat (propertize " " 'display `(space :align-to (- right (,bw)))) (propertize " " 'face 'corfu-bar 'display `(space :width (,bw)))))) (cbar (if fringe #(" " 0 1 (display (left-fringe corfu--nil corfu-current)) 1 2 (display (right-fringe corfu--bar corfu--cbar))) sbar)) (cmargin (and fringe #(" " 0 1 (display (left-fringe corfu--nil corfu-current)) 1 2 (display (right-fringe corfu--nil corfu-current))))) (pos (posn-x-y pos)) (width (+ (* width cw) (if fringe 0 (+ ml mr)))) ;; XXX HACK: Minimum popup height must be at least 1 line of the ;; parent frame (gh:minad/corfu#261). (height (max lh (* (length lines) ch))) (edge (window-inside-pixel-edges)) (border (alist-get 'internal-border-width corfu--frame-parameters)) (x (max 0 (min (+ (car edge) (- (or (car pos) 0) ml (* cw off) border)) (- (frame-pixel-width) width)))) (yb (+ (cadr edge) (or (cdr pos) 0) lh (static-if (< emacs-major-version 31) (window-tab-line-height) 0))) (y (if (> (+ yb (* corfu-count ch) lh lh) (frame-pixel-height)) (- yb height lh border border) yb)) (bmp (logxor (1- (ash 1 mr)) (1- (ash 1 bw))))) (setq left-fringe-width (if fringe ml 0) right-fringe-width (if fringe mr 0)) ;; Define an inverted corfu--bar face (unless (equal (and (facep 'corfu--bar) (face-attribute 'corfu--bar :foreground)) (face-attribute 'corfu-bar :background)) (set-face-attribute (make-face 'corfu--bar) nil :foreground (face-attribute 'corfu-bar :background))) (unless (or (= right-fringe-width 0) (eq (get 'corfu--bar 'corfu--bmp) bmp)) (put 'corfu--bar 'corfu--bmp bmp) (define-fringe-bitmap 'corfu--bar (vector (lognot bmp)) 1 mr '(top periodic)) (define-fringe-bitmap 'corfu--nil [0] 1 1) ;; Fringe bitmaps require symbol face specification, define internal face. (set-face-attribute (make-face 'corfu--cbar) nil :inherit '(corfu--bar corfu-current))) (with-silent-modifications (delete-region (point-min) (point-max)) (apply #'insert (cl-loop for row from 0 for line in lines collect (let ((str (concat marginl line (if (and lo (<= lo row (+ lo bar))) (if (eq row curr) cbar sbar) (and (eq row curr) cmargin)) "\n"))) (when (eq row curr) (add-face-text-property 0 (length str) 'corfu-current 'append str)) str))) (goto-char (point-min))) (setq corfu--frame (corfu--make-frame corfu--frame x y width height)))))) (cl-defgeneric corfu--popup-hide () "Hide Corfu popup." (corfu--hide-frame corfu--frame)) (cl-defgeneric corfu--popup-support-p () "Return non-nil if child frames are supported." (or (display-graphic-p) (featurep 'tty-child-frames))) (cl-defgeneric corfu--insert (status) "Insert current candidate, exit with STATUS if non-nil." ;; XXX There is a small bug here, depending on interpretation. ;; When completing "~/emacs/master/li|/calc" where "|" is the ;; cursor, then the candidate only includes the prefix ;; "~/emacs/master/lisp/", but not the suffix "/calc". Default ;; completion has the same problem when selecting in the ;; *Completions* buffer. See bug#48356. (pcase-let* ((`(,beg ,end . ,_) completion-in-region--data) (str (concat corfu--base (nth corfu--index corfu--candidates)))) (corfu--replace beg end str) (corfu--goto -1) ;; Reset selection, completion may continue. (when status (corfu--done str status nil)) str)) (cl-defgeneric corfu--affixate (cands) "Annotate CANDS with annotation function." (let* ((dep (corfu--metadata-get 'company-deprecated)) (mf (let ((completion-extra-properties (nth 4 completion-in-region--data))) (run-hook-with-args-until-success 'corfu-margin-formatters corfu--metadata)))) (setq cands (if-let ((aff (corfu--metadata-get 'affixation-function))) (funcall aff cands) (if-let ((ann (corfu--metadata-get 'annotation-function))) (cl-loop for cand in cands collect (let ((suff (or (funcall ann cand) ""))) ;; The default completion UI adds the ;; `completions-annotations' face if no other faces are ;; present. We use a custom `corfu-annotations' face to ;; allow further styling which fits better for popups. (unless (text-property-not-all 0 (length suff) 'face nil suff) (setq suff (propertize suff 'face 'corfu-annotations))) (list cand "" suff))) (cl-loop for cand in cands collect (list cand "" ""))))) (cl-loop for x in cands for (c . _) = x do (when mf (setf (cadr x) (funcall mf c))) (when (and dep (funcall dep c)) (setcar x (setq c (substring c))) (add-face-text-property 0 (length c) 'corfu-deprecated 'append c))) (cons mf cands))) (cl-defgeneric corfu--prepare () "Insert selected candidate unless command is marked to continue completion." (corfu--preview-delete) ;; Ensure that state is initialized before next Corfu command (when (and (symbolp this-command) (string-prefix-p "corfu-" (symbol-name this-command))) (corfu--update)) ;; If the next command is not listed in `corfu-continue-commands', insert the ;; currently selected candidate and bail out of completion. This way you can ;; continue typing after selecting a candidate. The candidate will be inserted ;; and your new input will be appended. (and (corfu--preview-current-p) (eq corfu-preview-current 'insert) ;; See the comment about `overriding-local-map' in `corfu--post-command'. (not (or overriding-terminal-local-map (corfu--match-symbol-p corfu-continue-commands this-command))) (corfu--insert 'exact))) (cl-defgeneric corfu--exhibit (&optional auto) "Exhibit Corfu UI. AUTO is non-nil when initializing auto completion." (pcase-let ((`(,beg ,end ,table ,pred . ,_) completion-in-region--data) (`(,str . ,pt) (corfu--update 'interruptible))) (cond ;; 1) Single exactly matching candidate and no further completion is possible. ((and (not (equal str "")) (equal (car corfu--candidates) str) (not (cdr corfu--candidates)) (not (eq corfu-on-exact-match 'show)) (or auto corfu-on-exact-match) (not (consp (completion-try-completion str table pred pt corfu--metadata)))) ;; Quit directly when initializing auto completion. (if (or auto (eq corfu-on-exact-match 'quit)) (corfu-quit) (corfu--done (car corfu--candidates) 'finished nil))) ;; 2) There exist candidates => Show candidates popup. (corfu--candidates (let ((pos (posn-at-point (+ beg (length corfu--base))))) (corfu--preview-current beg end) (corfu--candidates-popup pos))) ;; 3) No candidates & `corfu-quit-no-match' & initialized => Confirmation popup. ((pcase-exhaustive corfu-quit-no-match ('t nil) ('nil corfu--input) ('separator (seq-contains-p (car corfu--input) corfu-separator))) (corfu--popup-show (posn-at-point beg) 0 8 '(#("No match" 0 8 (face italic))))) ;; 4) No candidates & auto completing or initialized => Quit. ((or auto corfu--input) (corfu-quit))))) (cl-defgeneric corfu--teardown (buffer) "Tear-down Corfu in BUFFER, which might be dead at this point." (corfu--popup-hide) (corfu--preview-delete) (remove-hook 'post-command-hook #'corfu--post-command) (when (buffer-live-p buffer) (with-current-buffer buffer (remove-hook 'window-selection-change-functions #'corfu--window-change 'local) (remove-hook 'window-buffer-change-functions #'corfu--window-change 'local) (remove-hook 'pre-command-hook #'corfu--prepare 'local) (accept-change-group corfu--change-group))) (cl-loop for (k . v) in corfu--initial-state do (set k v))) (defun corfu-sort-length-alpha (list) "Sort LIST by length and alphabetically." (sort list #'corfu--length-string<)) (defun corfu-quit () "Quit Corfu completion." (interactive) (completion-in-region-mode -1)) (defun corfu-reset () "Reset Corfu completion. This command can be executed multiple times by hammering the ESC key. If a candidate is selected, unselect the candidate. Otherwise reset the input. If there hasn't been any input, then quit." (interactive) (if (/= corfu--index corfu--preselect) (progn (corfu--goto -1) (setq this-command #'corfu-first)) ;; Cancel all changes and start new change group. (pcase-let* ((`(,beg ,end . ,_) completion-in-region--data) (str (buffer-substring-no-properties beg end))) (cancel-change-group corfu--change-group) (activate-change-group (setq corfu--change-group (prepare-change-group))) ;; Quit when resetting, when input did not change. (when (equal str (buffer-substring-no-properties beg end)) (corfu-quit))))) (defun corfu-insert-separator () "Insert a separator character, inhibiting quit on completion boundary. If the currently selected candidate is previewed, jump to the input prompt instead. See `corfu-separator' for more details." (interactive) (if (not (corfu--preview-current-p)) (insert corfu-separator) (corfu--goto -1) (unless (or (= (car completion-in-region--data) (point)) (= (char-before) corfu-separator)) (insert corfu-separator)))) (defun corfu-next (&optional n) "Go forward N candidates." (interactive "p") (let ((index (+ corfu--index (or n 1)))) (corfu--goto (cond ((not corfu-cycle) index) ((= corfu--total 0) -1) ((< corfu--preselect 0) (1- (mod (1+ index) (1+ corfu--total)))) (t (mod index corfu--total)))))) (defun corfu-previous (&optional n) "Go backward N candidates." (interactive "p") (corfu-next (- (or n 1)))) (defun corfu-scroll-down (&optional n) "Go back by N pages." (interactive "p") (corfu--goto (max 0 (- corfu--index (* (or n 1) corfu-count))))) (defun corfu-scroll-up (&optional n) "Go forward by N pages." (interactive "p") (corfu-scroll-down (- (or n 1)))) (defun corfu-first () "Go to first candidate. If the first candidate is already selected, go to the prompt." (interactive) (corfu--goto (if (> corfu--index 0) 0 -1))) (defun corfu-last () "Go to last candidate." (interactive) (corfu--goto (1- corfu--total))) (defun corfu-prompt-beginning (arg) "Move to beginning of the prompt line. If the point is already the beginning of the prompt move to the beginning of the line. If ARG is not 1 or nil, move backward ARG - 1 lines first." (interactive "^p") (let ((beg (car completion-in-region--data))) (if (or (not (eq arg 1)) (and (= corfu--preselect corfu--index) (= (point) beg))) (move-beginning-of-line arg) (corfu--goto -1) (goto-char beg)))) (defun corfu-prompt-end (arg) "Move to end of the prompt line. If the point is already the end of the prompt move to the end of the line. If ARG is not 1 or nil, move forward ARG - 1 lines first." (interactive "^p") (let ((end (cadr completion-in-region--data))) (if (or (not (eq arg 1)) (and (= corfu--preselect corfu--index) (= (point) end))) (move-end-of-line arg) (corfu--goto -1) (goto-char end)))) (defun corfu-complete () "Complete current input. If a candidate is selected, insert it. Otherwise invoke `corfu-expand'. Return non-nil if the input has been expanded." (interactive) (if (< corfu--index 0) (corfu-expand) ;; Continue completion with selected candidate. Exit with status 'finished ;; if input is a valid match and no further completion is ;; possible. Additionally treat completion as finished if at the end of a ;; boundary, even if other longer candidates would still match, since the ;; user invoked `corfu-complete' with an explicitly selected candidate! (pcase-let ((`(,_beg ,_end ,table ,pred . ,_) completion-in-region--data) (newstr (corfu--insert nil))) (and (test-completion newstr table pred) (or (not (consp (completion-try-completion newstr table pred (length newstr) (completion-metadata newstr table pred)))) (equal (completion-boundaries newstr table pred "") '(0 . 0))) (corfu--done newstr 'finished nil)) t))) (defun corfu-expand () "Expands the common prefix of all candidates. If the currently selected candidate is previewed, invoke `corfu-complete' instead. Expansion relies on the completion styles via `completion-try-completion'. Return non-nil if the input has been expanded." (interactive) (if (corfu--preview-current-p) (corfu-complete) (pcase-let* ((`(,beg ,end ,table ,pred . ,_) completion-in-region--data) (pt (max 0 (- (point) beg))) (str (buffer-substring-no-properties beg end))) (pcase (completion-try-completion str table pred pt corfu--metadata) ('t (goto-char end) (corfu--done str 'finished corfu--candidates) t) ((and `(,newstr . ,newpt) (guard (not (and (= pt newpt) (equal newstr str))))) (corfu--replace beg end newstr) (goto-char (+ beg newpt)) ;; Exit with status 'finished if input is a valid match ;; and no further completion is possible. (and (test-completion newstr table pred) (not (consp (completion-try-completion newstr table pred newpt (completion-metadata (substring newstr 0 newpt) table pred)))) (corfu--done newstr 'finished corfu--candidates)) t))))) (defun corfu-insert () "Insert current candidate. Quit if no candidate is selected." (interactive) (if (>= corfu--index 0) (corfu--insert 'finished) (corfu-quit))) (defun corfu-send () "Insert current candidate and send it when inside comint or eshell." (interactive) (corfu-insert) (cond ((and (derived-mode-p 'eshell-mode) (fboundp 'eshell-send-input)) (eshell-send-input)) ((and (derived-mode-p 'comint-mode) (fboundp 'comint-send-input)) (comint-send-input)))) ;;;###autoload (define-minor-mode corfu-mode "COmpletion in Region FUnction." :group 'corfu :keymap corfu-mode-map (cond (corfu-mode (and corfu-auto (add-hook 'post-command-hook #'corfu--auto-post-command nil 'local)) (setq-local completion-in-region-function #'corfu--in-region)) (t (remove-hook 'post-command-hook #'corfu--auto-post-command 'local) (kill-local-variable 'completion-in-region-function)))) (defcustom global-corfu-modes t "List of modes where Corfu should be enabled by `global-corfu-mode'. The variable can either be t, nil or a list of t, nil, mode symbols or elements of the form (not modes). Examples: - Enable everywhere, except in Org: ((not org-mode) t). - Enable in programming modes except Python: ((not python-mode) prog-mode). - Enable only in text modes: (text-mode)." :type '(choice (const t) (repeat sexp)) :group 'corfu) ;; TODO use `:predicate' on Emacs 29 (defcustom global-corfu-minibuffer t "Corfu should be enabled in the minibuffer by `global-corfu-mode'. The variable can either be t, nil or a custom predicate function. If the variable is set to t, Corfu is only enabled if the minibuffer has local `completion-at-point-functions'." :type '(choice (const t) (const nil) function) :group 'corfu) ;;;###autoload (define-globalized-minor-mode global-corfu-mode corfu-mode corfu--on :group 'corfu (remove-hook 'minibuffer-setup-hook #'corfu--minibuffer-on) (when (and global-corfu-mode global-corfu-minibuffer) (add-hook 'minibuffer-setup-hook #'corfu--minibuffer-on 100))) (defun corfu--on () "Enable `corfu-mode' in the current buffer respecting `global-corfu-modes'." (when (and (not noninteractive) (not (eq (aref (buffer-name) 0) ?\s)) ;; TODO use `:predicate' on Emacs 29 (or (eq t global-corfu-modes) (eq t (cl-loop for p in global-corfu-modes thereis (pcase-exhaustive p ('t t) ('nil 0) ((pred symbolp) (and (derived-mode-p p) t)) (`(not . ,m) (and (seq-some #'derived-mode-p m) 0))))))) (corfu-mode))) (defun corfu--minibuffer-on () "Enable `corfu-mode' in the minibuffer respecting `global-corfu-minibuffer'." (when (and global-corfu-minibuffer (not noninteractive) (if (functionp global-corfu-minibuffer) (funcall global-corfu-minibuffer) (local-variable-p 'completion-at-point-functions))) (corfu-mode))) ;; Do not show Corfu commands with M-X (dolist (sym '( corfu-next corfu-previous corfu-first corfu-last corfu-quit corfu-reset corfu-complete corfu-insert corfu-scroll-up corfu-scroll-down corfu-expand corfu-send corfu-insert-separator corfu-prompt-beginning corfu-prompt-end corfu-info-location corfu-info-documentation ;; autoloads in corfu-info.el corfu-quick-jump corfu-quick-insert corfu-quick-complete)) ;; autoloads in corfu-quick.el (put sym 'completion-predicate #'ignore)) (defun corfu--capf-wrapper-advice (orig fun which) "Around advice for `completion--capf-wrapper'. The ORIG function takes the FUN and WHICH arguments." (if corfu-mode (corfu--capf-wrapper fun t) (funcall orig fun which))) (defun corfu--eldoc-advice () "Return non-nil if Corfu is currently not active." (not (and corfu-mode completion-in-region-mode))) ;; Install advice which fixes `completion--capf-wrapper', such that it respects ;; the completion styles for non-exclusive Capfs. See also the fixme comment in ;; the `completion--capf-wrapper' function in minibuffer.el. (advice-add #'completion--capf-wrapper :around #'corfu--capf-wrapper-advice) ;; Register Corfu with ElDoc (advice-add #'eldoc-display-message-no-interference-p :before-while #'corfu--eldoc-advice) (eldoc-add-command #'corfu-complete #'corfu-insert #'corfu-expand #'corfu-send) (provide 'corfu) ;;; corfu.el ends here corfu-2.2/extensions/000077500000000000000000000000001501476044300146765ustar00rootroot00000000000000corfu-2.2/extensions/corfu-echo.el000066400000000000000000000074031501476044300172560ustar00rootroot00000000000000;;; corfu-echo.el --- Show candidate documentation in echo area -*- lexical-binding: t -*- ;; Copyright (C) 2021-2025 Free Software Foundation, Inc. ;; Author: Daniel Mendler ;; Maintainer: Daniel Mendler ;; Created: 2022 ;; Version: 2.2 ;; Package-Requires: ((emacs "28.1") (compat "30") (corfu "2.2")) ;; URL: https://github.com/minad/corfu ;; This file is part of GNU Emacs. ;; 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: ;; Show candidate documentation in echo area. Enable `corfu-echo-mode'. ;;; Code: (require 'corfu) (eval-when-compile (require 'subr-x)) (defface corfu-echo '((t :inherit completions-annotations)) "Face used for echo area messages." :group 'corfu-faces) (defcustom corfu-echo-delay '(2.0 . 1.0) "Show documentation string in the echo area after that number of seconds. The value can be a pair of two floats to specify initial and subsequent delay." :type '(choice (const :tag "Never" nil) (number :tag "Delay in seconds") (cons :tag "Two Delays" (choice :tag "Initial " number) (choice :tag "Subsequent" number))) :group 'corfu) (defvar corfu-echo--timer nil "Echo area message timer.") (defvar corfu-echo--message nil "Last echo message.") (defun corfu-echo--cancel (&optional msg) "Cancel echo timer and refresh MSG." (when corfu-echo--timer (cancel-timer corfu-echo--timer) (setq corfu-echo--timer nil)) (corfu-echo--show msg) (unless corfu-echo--message (setq corfu-echo--timer nil corfu-echo--message nil))) (defun corfu-echo--show (msg) "Show MSG in echo area." (when (or msg corfu-echo--message) (setq msg (or msg "") corfu-echo--message msg) (corfu--message "%s" (if (text-property-not-all 0 (length msg) 'face nil msg) msg (propertize msg 'face 'corfu-echo))))) ;;;###autoload (define-minor-mode corfu-echo-mode "Show candidate documentation in echo area." :global t :group 'corfu) (cl-defmethod corfu--exhibit :after (&context (corfu-echo-mode (eql t)) &optional _auto) (if-let (((not (minibufferp))) (delay (if (consp corfu-echo-delay) (funcall (if corfu-echo--message #'cdr #'car) corfu-echo-delay) corfu-echo-delay)) (fun (corfu--metadata-get 'company-docsig)) (cand (and (>= corfu--index 0) (nth corfu--index corfu--candidates)))) (if (<= delay 0) (corfu-echo--show (funcall fun cand)) (corfu-echo--cancel) (setq corfu-echo--timer (run-at-time delay nil (lambda () (corfu-echo--show (funcall fun cand)))))) (corfu-echo--cancel))) (cl-defmethod corfu--teardown :before (_buf &context (corfu-echo-mode (eql t))) (corfu-echo--cancel)) (cl-defmethod corfu--prepare :before (&context (corfu-echo-mode (eql t))) ;; The refreshing is needed to prevent flicker if corfu-echo-delay=t. (corfu-echo--cancel corfu-echo--message)) (provide 'corfu-echo) ;;; corfu-echo.el ends here corfu-2.2/extensions/corfu-history.el000066400000000000000000000107221501476044300200370ustar00rootroot00000000000000;;; corfu-history.el --- Sorting by history for Corfu -*- lexical-binding: t -*- ;; Copyright (C) 2022-2025 Free Software Foundation, Inc. ;; Author: Daniel Mendler ;; Maintainer: Daniel Mendler ;; Created: 2022 ;; Version: 2.2 ;; Package-Requires: ((emacs "28.1") (compat "30") (corfu "2.2")) ;; URL: https://github.com/minad/corfu ;; This file is part of GNU Emacs. ;; 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: ;; Enable `corfu-history-mode' to sort candidates by their history position. ;; The recently selected candidates are stored in the `corfu-history' variable. ;; If `history-delete-duplicates' is nil, duplicate elements are ranked higher ;; with exponential decay. In order to save the history across Emacs sessions, ;; enable `savehist-mode'. ;; ;; (corfu-history-mode) ;; (savehist-mode) ;;; Code: (require 'corfu) (eval-when-compile (require 'cl-lib)) (defvar corfu-history nil "History of Corfu candidates. The maximum length is determined by the variable `history-length' or the property `history-length' of `corfu-history'.") (defvar corfu-history--hash nil "Hash table of Corfu candidates.") (defcustom corfu-history-duplicate 10 "History position shift for duplicate history elements. The more often a duplicate element occurs in the history, the earlier it appears in the completion list. The shift decays exponentially with `corfu-history-decay'. Note that duplicates occur only if `history-delete-duplicates' is disabled." :type 'number :group 'corfu) (defcustom corfu-history-decay 10 "Exponential decay for the position shift of duplicate elements. The shift will decay away after `corfu-history-duplicate' times `corfu-history-decay' history elements." :type 'number :group 'corfu) (defun corfu-history--sort-predicate (x y) "Sorting predicate which compares X and Y." (or (< (cdr x) (cdr y)) (and (= (cdr x) (cdr y)) (corfu--length-string< (car x) (car y))))) (defun corfu-history--sort (cands) "Sort CANDS by history." (unless corfu-history--hash (let ((ht (make-hash-table :test #'equal :size (length corfu-history))) (decay (/ -1.0 (* corfu-history-duplicate corfu-history-decay)))) (cl-loop for elem in corfu-history for idx from 0 for r = (if-let ((r (gethash elem ht))) ;; Reduce duplicate rank with exponential decay. (- r (round (* corfu-history-duplicate (exp (* decay idx))))) ;; Never outrank the most recent element. (if (= idx 0) (/ most-negative-fixnum 2) idx)) do (puthash elem r ht)) (setq corfu-history--hash ht))) (cl-loop for ht = corfu-history--hash for max = most-positive-fixnum for cand on cands do (setcar cand (cons (car cand) (gethash (car cand) ht max)))) (setq cands (sort cands #'corfu-history--sort-predicate)) (cl-loop for cand on cands do (setcar cand (caar cand))) cands) ;;;###autoload (define-minor-mode corfu-history-mode "Update Corfu history and sort completions by history." :global t :group 'corfu (if corfu-history-mode (add-function :override corfu-sort-function #'corfu-history--sort) (remove-function corfu-sort-function #'corfu-history--sort))) (cl-defmethod corfu--insert :before (_status &context (corfu-history-mode (eql t))) (when (>= corfu--index 0) (unless (or (not (bound-and-true-p savehist-mode)) (memq 'corfu-history (bound-and-true-p savehist-ignored-variables))) (defvar savehist-minibuffer-history-variables) (add-to-list 'savehist-minibuffer-history-variables 'corfu-history)) (add-to-history 'corfu-history (substring-no-properties (nth corfu--index corfu--candidates))) (setq corfu-history--hash nil))) (provide 'corfu-history) ;;; corfu-history.el ends here corfu-2.2/extensions/corfu-indexed.el000066400000000000000000000067661501476044300177730ustar00rootroot00000000000000;;; corfu-indexed.el --- Select indexed candidates -*- lexical-binding: t -*- ;; Copyright (C) 2022-2025 Free Software Foundation, Inc. ;; Author: Luis Henriquez-Perez , Daniel Mendler ;; Maintainer: Daniel Mendler ;; Created: 2022 ;; Version: 2.2 ;; Package-Requires: ((emacs "28.1") (compat "30") (corfu "2.2")) ;; URL: https://github.com/minad/corfu ;; This file is part of GNU Emacs. ;; 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: ;; This package is a Corfu extension, which prefixes candidates with indices if ;; enabled via `corfu-indexed-mode'. It allows you to select candidates with ;; prefix arguments. This is designed to be a faster alternative to selecting a ;; candidate with `corfu-next' and `corfu-previous'. ;;; Code: (require 'corfu) (eval-when-compile (require 'cl-lib)) (defface corfu-indexed '((default :height 0.75) (((class color) (min-colors 88) (background dark)) :foreground "#f4f4f4" :background "#323232") (((class color) (min-colors 88) (background light)) :foreground "#404148" :background "#d7d7d7") (t :background "black")) "Face used for the candidate index prefix." :group 'corfu-faces) (defcustom corfu-indexed-start 0 "Start of the indexing." :group 'corfu :type 'natnum) (defvar corfu-indexed--commands '(corfu-insert corfu-complete) "Commands that should be indexed.") ;;;###autoload (define-minor-mode corfu-indexed-mode "Prefix candidates with indices." :global t :group 'corfu) (cl-defmethod corfu--prepare :before (&context (corfu-indexed-mode (eql t))) (when (and prefix-arg (memq this-command corfu-indexed--commands)) (let ((index (+ corfu--scroll (- (prefix-numeric-value prefix-arg) corfu-indexed-start)))) (if (and (>= index 0) (< index corfu--total) (< index (+ corfu--scroll corfu-count))) (setq corfu--index index) (message "Out of range") (setq this-command #'ignore))))) (cl-defmethod corfu--affixate :around (cands &context (corfu-indexed-mode (eql t))) (setq cands (cdr (cl-call-next-method cands))) (let* ((space #(" " 0 1 (face (:height 0.5 :inherit corfu-indexed)))) (width (if (length> cands (- 10 corfu-indexed-start)) 2 1)) (fmt (concat space (propertize (format "%%%ds" width) 'face 'corfu-indexed) space)) (align (propertize (make-string width ?\s) 'display `(space :align-to (+ left ,(1+ width)))))) (cl-loop for cand in cands for index from corfu-indexed-start do (setf (cadr cand) (concat (propertize " " 'display (format fmt index)) align (cadr cand)))) (cons t cands))) (provide 'corfu-indexed) ;;; corfu-indexed.el ends here corfu-2.2/extensions/corfu-info.el000066400000000000000000000107611501476044300172740ustar00rootroot00000000000000;;; corfu-info.el --- Show candidate information in separate buffer -*- lexical-binding: t -*- ;; Copyright (C) 2022-2025 Free Software Foundation, Inc. ;; Author: Daniel Mendler ;; Maintainer: Daniel Mendler ;; Created: 2022 ;; Version: 2.2 ;; Package-Requires: ((emacs "28.1") (compat "30") (corfu "2.2")) ;; URL: https://github.com/minad/corfu ;; This file is part of GNU Emacs. ;; 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: ;; This Corfu extension provides commands to show additional information to the ;; candidates in a separate buffer. The commands `corfu-info-location' and ;; `corfu-info-documentation' are bound by default in the `corfu-map' to M-g and ;; M-h respectively. ;;; Code: (require 'corfu) (eval-when-compile (require 'subr-x)) (defun corfu-info--restore-on-next-command () "Restore window configuration before next command." (let ((config (current-window-configuration)) (other other-window-scroll-buffer) (restore (make-symbol "corfu--restore"))) (fset restore (lambda () (setq other-window-scroll-buffer other) (unless (memq this-command '(scroll-other-window scroll-other-window-down)) (when (memq this-command '(corfu-quit corfu-reset)) (setq this-command #'ignore)) (remove-hook 'pre-command-hook restore) (set-window-configuration config)))) (add-hook 'pre-command-hook restore))) (defun corfu-info--display-buffer (buffer name) "Display BUFFER and return window displaying the buffer. Make the buffer persistent with NAME if non-nil." (if name (unless (buffer-local-value 'buffer-file-name buffer) (if-let ((old (get-buffer name))) (setq buffer (prog1 old (kill-buffer buffer))) (with-current-buffer buffer (rename-buffer name)))) (corfu-info--restore-on-next-command)) (setq other-window-scroll-buffer buffer) (display-buffer buffer t)) ;;;###autoload (defun corfu-info-documentation (&optional arg) "Show documentation of current candidate. If called with a prefix ARG, the buffer is persistent." (interactive "P") ;; Company support, taken from `company.el', see `company-show-doc-buffer'. (when (< corfu--index 0) (user-error "No candidate selected")) (let ((cand (nth corfu--index corfu--candidates))) (if-let ((fun (corfu--metadata-get 'company-doc-buffer)) (res (funcall fun cand))) (set-window-start (corfu-info--display-buffer (get-buffer (or (car-safe res) res)) (and arg (format "*corfu doc: %s*" cand))) (or (cdr-safe res) (point-min))) (user-error "No documentation available for `%s'" cand)))) ;;;###autoload (defun corfu-info-location (&optional arg) "Show location of current candidate. If called with a prefix ARG, the buffer is persistent." (interactive "P") ;; Company support, taken from `company.el', see `company-show-location'. (when (< corfu--index 0) (user-error "No candidate selected")) (let ((cand (nth corfu--index corfu--candidates))) (if-let ((fun (corfu--metadata-get 'company-location)) ;; BUG: company-location may throw errors if location is not found (loc (ignore-errors (funcall fun cand)))) (with-selected-window (corfu-info--display-buffer (or (and (bufferp (car loc)) (car loc)) (find-file-noselect (car loc) t)) (and arg (format "*corfu loc: %s*" cand))) (without-restriction (goto-char (point-min)) (when-let ((pos (cdr loc))) (if (bufferp (car loc)) (goto-char pos) (forward-line (1- pos)))) (set-window-start nil (point)))) (user-error "No location available for `%s'" cand)))) (provide 'corfu-info) ;;; corfu-info.el ends here corfu-2.2/extensions/corfu-popupinfo.el000066400000000000000000000534051501476044300203620ustar00rootroot00000000000000;;; corfu-popupinfo.el --- Candidate information popup for Corfu -*- lexical-binding: t -*- ;; Copyright (C) 2021-2025 Free Software Foundation, Inc. ;; Author: Yuwei Tian , Daniel Mendler ;; Maintainer: Daniel Mendler ;; Created: 2022 ;; Version: 2.2 ;; Package-Requires: ((emacs "28.1") (compat "30") (corfu "2.2")) ;; URL: https://github.com/minad/corfu ;; This file is part of GNU Emacs. ;; 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: ;; Display an information popup for completion candidate when using ;; Corfu. The popup displays either the candidate documentation or the ;; candidate location. The `corfu-popupinfo-mode' must be enabled ;; globally. Set `corfu-popupinfo-delay' to nil if the info popup should ;; not update automatically. If the popup should not appear initially, ;; but update automatically afterwards, use `(setq corfu-popupinfo-delay ;; (cons nil 1.0))'. ;; For manual toggling the commands `corfu-popupinfo-toggle', ;; `corfu-popupinfo-location' and `corfu-popupinfo-documentation' are ;; bound in the `corfu-popupinfo-map'. ;;; Code: (require 'corfu) (eval-when-compile (require 'cl-lib) (require 'subr-x)) (defface corfu-popupinfo '((t :inherit corfu-default)) "Face used for the info popup." :group 'corfu-faces) (defcustom corfu-popupinfo-delay '(2.0 . 1.0) "Automatically update info popup after that number of seconds. The value can be a pair of two floats to specify initial and subsequent delay. If the value is non-nil or the car of the pair is non-nil, the popup will automatically appear for the preselected candidate. Otherwise the popup can be requested manually via `corfu-popupinfo-toggle', `corfu-popupinfo-documentation' and `corfu-popupinfo-location'. It is *not recommended* to use a short delay or even 0, since this will create high load for Emacs. Retrieving the documentation from the backend is usually expensive." :type '(choice (const :tag "Never" nil) (number :tag "Delay in seconds") (cons :tag "Two Delays" (choice :tag "Initial " (choice (const nil) number)) (choice :tag "Subsequent" (choice (const nil) number)))) :group 'corfu) (defcustom corfu-popupinfo-hide t "Hide the popup during the transition between candidates." :type 'boolean :group 'corfu) (defcustom corfu-popupinfo-max-width 80 "The maximum width of the info popup in characters." :type 'natnum :group 'corfu) (defcustom corfu-popupinfo-min-width 30 "The minimum width of the info popup in characters." :type 'natnum :group 'corfu) (defcustom corfu-popupinfo-max-height 10 "The maximum height of the info popup in characters." :type 'natnum :group 'corfu) (defcustom corfu-popupinfo-min-height 1 "The minimum height of the info popup in characters." :type 'natnum :group 'corfu) (defcustom corfu-popupinfo-resize t "Resize the info popup automatically if non-nil." :type 'boolean :group 'corfu) (defcustom corfu-popupinfo-direction '(right left vertical) "Preferred directions for the popup in order." :type '(repeat (choice (const left) (const right) (const vertical) (const force-left) (const force-right) (const force-vertical))) :group 'corfu) (defvar-keymap corfu-popupinfo-map :doc "Additional keymap activated in popupinfo mode." "M-t" #'corfu-popupinfo-toggle " " #'corfu-popupinfo-documentation " " #'corfu-popupinfo-location " " #'corfu-popupinfo-scroll-up " " #'corfu-popupinfo-scroll-down " " #'corfu-popupinfo-end " " #'corfu-popupinfo-beginning) (defvar corfu-popupinfo--buffer-parameters '((truncate-partial-width-windows . nil) (truncate-lines . nil) (left-margin-width . 1) (right-margin-width . 1) (word-wrap . t) (char-property-alias-alist (face font-lock-face))) "Buffer parameters.") (defvar corfu-popupinfo--frame nil "Info popup child frame.") (defvar corfu-popupinfo--timer nil "Corfu info popup auto display timer.") (defvar corfu-popupinfo--toggle 'init "Toggle state.") (defvar corfu-popupinfo--function #'corfu-popupinfo--get-documentation "Function called to obtain documentation string.") (defvar corfu-popupinfo--candidate nil "Completion candidate for the info popup.") (defvar corfu-popupinfo--coordinates nil "Coordinates of the candidate popup. The coordinates list has the form (LEFT TOP RIGHT BOTTOM) where all values are in pixels relative to the origin. See `frame-edges' for details.") (defvar corfu-popupinfo--lock-dir nil "Locked position direction of the info popup.") (defconst corfu-popupinfo--buffer " *corfu-popupinfo*" "Buffer used by the popup.") (defconst corfu-popupinfo--initial-state (mapcar (lambda (k) (cons k (symbol-value k))) '(corfu-popupinfo--candidate corfu-popupinfo--coordinates corfu-popupinfo--lock-dir corfu-popupinfo--toggle corfu-popupinfo--function)) "Initial state of `corfu-popupinfo-mode'.") (defun corfu-popupinfo--visible-p (&optional frame) "Return non-nil if FRAME is visible." (setq frame (or frame corfu-popupinfo--frame)) (and (frame-live-p frame) (frame-visible-p frame))) (defun corfu-popupinfo--get-location (candidate) "Get source at location of CANDIDATE." (save-excursion (let ((old-buffers (buffer-list)) (buffer nil)) (unwind-protect (when-let ((fun (corfu--metadata-get 'company-location)) ;; BUG: company-location may throw errors if location is not found (loc (ignore-errors (funcall fun candidate))) ((setq buffer (or (and (bufferp (car loc)) (car loc)) (get-file-buffer (car loc)) (let ((inhibit-message t) (message-log-max nil) (inhibit-redisplay t) (enable-dir-local-variables nil) (enable-local-variables :safe) (non-essential t) (delay-mode-hooks t) (find-file-hook '(global-font-lock-mode-check-buffers))) (find-file-noselect (car loc) t)))))) (with-current-buffer buffer (save-excursion (without-restriction (goto-char (point-min)) (when-let ((pos (cdr loc))) (if (bufferp (car loc)) (goto-char pos) (forward-line (1- pos)))) (let ((beg (point))) ;; Support a little bit of scrolling. (forward-line (* 10 corfu-popupinfo-max-height)) (when jit-lock-mode (jit-lock-fontify-now beg (point))) (let ((res (buffer-substring beg (point)))) (and (not (string-blank-p res)) res))))))) (when (and buffer (not (memq buffer old-buffers))) (kill-buffer buffer)))))) (defun corfu-popupinfo--get-documentation (candidate) "Get the documentation for CANDIDATE." (when-let ((fun (corfu--metadata-get 'company-doc-buffer)) (res (save-excursion (let ((inhibit-message t) (message-log-max nil) (inhibit-redisplay t) ;; Reduce print length for elisp backend (#249) (print-level 3) (print-length (* corfu-popupinfo-max-width corfu-popupinfo-max-height))) (funcall fun candidate))))) (with-current-buffer (or (car-safe res) res) (setq res (string-trim (replace-regexp-in-string "[\n\t ]*\\[back\\][\n\t ]*" "" (buffer-string)))) (and (not (string-blank-p res)) res)))) (defun corfu-popupinfo--size () "Return popup size as pair." (let* ((cw (default-font-width)) (lh (default-line-height)) (margin (* cw (+ (alist-get 'left-margin-width corfu-popupinfo--buffer-parameters) (alist-get 'right-margin-width corfu-popupinfo--buffer-parameters)))) (max-height (* lh corfu-popupinfo-max-height)) (max-width (* cw corfu-popupinfo-max-width))) (or (when corfu-popupinfo-resize (with-current-buffer corfu-popupinfo--buffer (cl-letf* (((window-dedicated-p) nil) ((window-buffer) (current-buffer)) (size (window-text-pixel-size nil (point-min) (point-max) ;; Use 3*max-height as y-limit, to take more text ;; into account. max-width (* 3 max-height)))) ;; Check that width is not exceeded. Otherwise use full height, ;; since lines will get wrapped. (when (<= (car size) max-width) (cons (+ margin (car size)) ;; XXX HACK: Ensure that popup has at least a height of 1, ;; which is the minimum frame height (#261). Maybe we ;; should ask upstream how smaller frames can be created. ;; I only managed to create smaller frames by setting ;; `window-safe-min-height' to 0, which feels problematic. (min (max (cdr size) lh) max-height)))))) (cons (+ margin max-width) max-height)))) (defun corfu-popupinfo--frame-geometry (frame) "Return position and size geometric attributes of FRAME. The geometry represents the position and size in pixels in the form of (X Y WIDTH HEIGHT)." (pcase-let ((`(,x . ,y) (frame-position frame))) (list x y (frame-pixel-width frame) (frame-pixel-height frame)))) (defun corfu-popupinfo--fits-p (size area) "Check if SIZE fits into the AREA. SIZE is in the form (WIDTH . HEIGHT). AREA is in the form (X Y WIDTH HEIGHT DIR)." (and (>= (nth 2 area) (car size)) (>= (nth 3 area) (cdr size)))) (defun corfu-popupinfo--larger-p (area1 area2) "Check if AREA1 is larger than AREA2. AREA1 and AREA2 are both in the form (X Y WIDTH HEIGHT DIR)." (>= (* (nth 2 area1) (nth 3 area1)) (* (nth 2 area2) (nth 3 area2)))) (defun corfu-popupinfo--area (ps) "Calculate the display area for the info popup. PS is the pixel size of the popup. The calculated area is in the form (X Y WIDTH HEIGHT DIR)." (pcase-let* ((cw (default-font-width)) (lh (default-line-height)) (border (alist-get 'internal-border-width corfu--frame-parameters)) (`(,_pfx ,_pfy ,pfw ,pfh) (corfu-popupinfo--frame-geometry (frame-parent corfu--frame))) (`(,cfx ,cfy ,cfw ,cfh) (corfu-popupinfo--frame-geometry corfu--frame)) ;; Candidates popup below input (below (>= cfy (+ lh (cadr (window-inside-pixel-edges)) (window-tab-line-height) (or (cdr (posn-x-y (posn-at-point (point)))) 0)))) ;; Popups aligned at top (top-aligned (or below (< (cdr ps) cfh))) ;; Left display area (ahy (if top-aligned cfy (max 0 (- (+ cfy cfh) border border (cdr ps))))) (ahh (if top-aligned (min (- pfh cfy) (cdr ps)) (min (- (+ cfy cfh) border border) (cdr ps)))) (al (list (max 0 (- cfx (car ps) border)) ahy (min (- cfx border) (car ps)) ahh 'left)) ;; Right display area (arx (+ cfx cfw (- border))) (ar (list arx ahy (min (- pfw arx border border) (car ps)) ahh 'right)) ;; Vertical display area (avw (min (car ps) (- pfw cfx border border))) (av (if below (list cfx (+ cfy cfh (- border)) avw (min (- pfh cfy cfh border) (cdr ps)) 'vertical) (let ((h (min (- cfy border border) (cdr ps)))) (list cfx (max 0 (- cfy h border)) avw h 'vertical))))) (unless (and corfu-popupinfo--lock-dir (corfu-popupinfo--fits-p (cons (* cw corfu-popupinfo-min-width) (* lh corfu-popupinfo-min-height)) (pcase corfu-popupinfo--lock-dir ('left al) ('right ar) ('vertical av)))) (setq corfu-popupinfo--lock-dir nil)) (or (cl-loop for dir in corfu-popupinfo-direction thereis (pcase dir ((or 'force-right (guard (eq corfu-popupinfo--lock-dir 'right))) ar) ((or 'force-left (guard (eq corfu-popupinfo--lock-dir 'left))) al) ((or 'force-vertical (guard (eq corfu-popupinfo--lock-dir 'vertical))) av) ((and 'right (guard (corfu-popupinfo--fits-p ps ar))) ar) ((and 'left (guard (corfu-popupinfo--fits-p ps al))) al) ((and 'vertical (guard (corfu-popupinfo--fits-p ps av))) av))) (let ((ah (if (corfu-popupinfo--larger-p ar al) ar al))) (if (corfu-popupinfo--larger-p av ah) av ah))))) (defun corfu-popupinfo--show (candidate) "Show the info popup for CANDIDATE." (when corfu-popupinfo--timer (cancel-timer corfu-popupinfo--timer) (setq corfu-popupinfo--timer nil)) (when (corfu-popupinfo--visible-p corfu--frame) (let* ((cand-changed (not (and (corfu-popupinfo--visible-p) (corfu--equal-including-properties candidate corfu-popupinfo--candidate)))) (new-coords (frame-edges corfu--frame 'inner-edges)) (coords-changed (not (equal new-coords corfu-popupinfo--coordinates)))) (when cand-changed (if-let ((content (funcall corfu-popupinfo--function candidate))) (with-current-buffer (corfu--make-buffer corfu-popupinfo--buffer) (with-silent-modifications (erase-buffer) (insert content) (goto-char (point-min))) (dolist (var corfu-popupinfo--buffer-parameters) (set (make-local-variable (car var)) (cdr var))) (when-let ((m (memq 'corfu-default (alist-get 'default face-remapping-alist)))) (setcar m 'corfu-popupinfo))) (corfu-popupinfo--hide) (setq cand-changed nil coords-changed nil))) (when (or cand-changed coords-changed) (pcase-let* ((border (alist-get 'internal-border-width corfu--frame-parameters)) (`(,area-x ,area-y ,area-w ,area-h ,area-d) (corfu-popupinfo--area (if cand-changed (corfu-popupinfo--size) (cons (- (frame-pixel-width corfu-popupinfo--frame) border border) (- (frame-pixel-height corfu-popupinfo--frame) border border))))) (margin-quirk (not corfu-popupinfo--frame))) (with-current-buffer corfu-popupinfo--buffer (setq corfu-popupinfo--frame (corfu--make-frame corfu-popupinfo--frame area-x area-y area-w area-h) corfu-popupinfo--toggle t corfu-popupinfo--lock-dir area-d corfu-popupinfo--candidate candidate corfu-popupinfo--coordinates new-coords) ;; XXX HACK: Force margin update. For some reason, the call to ;; `set-window-buffer' in `corfu--make-frame' is not effective the ;; first time. Why does Emacs have all these quirks? (when margin-quirk (set-window-buffer (frame-root-window corfu-popupinfo--frame) corfu-popupinfo--buffer)))))))) (defun corfu-popupinfo--hide () "Clear the info popup buffer content and hide it." (corfu--hide-frame corfu-popupinfo--frame)) (defun corfu-popupinfo-end (&optional n) "Scroll text of info popup window to its end. If arg N is omitted or nil, scroll to end. If a numerical value, put point N/10 of the way from the end. If the info popup is not visible, the other window is moved to beginning or end." (interactive "P") (if (corfu-popupinfo--visible-p) (with-selected-frame corfu-popupinfo--frame (with-current-buffer corfu-popupinfo--buffer (with-no-warnings (end-of-buffer n)))) (end-of-buffer-other-window n))) (defun corfu-popupinfo-beginning (&optional n) "Scroll text of info popup window to beginning of buffer. See `corfu-popupinfo-end' for the argument N." (interactive "P") (corfu-popupinfo-end (- 10 (if (numberp n) n 0)))) (defun corfu-popupinfo-scroll-up (&optional n) "Scroll text of info popup window upward N lines. If ARG is omitted or nil, scroll upward by a near full screen. See `scroll-up' for details. If the info popup is not visible, the other window is scrolled." (interactive "p") (if (corfu-popupinfo--visible-p) (with-selected-frame corfu-popupinfo--frame (with-current-buffer corfu-popupinfo--buffer (scroll-up n))) (scroll-other-window n))) (defun corfu-popupinfo-scroll-down (&optional n) "Scroll text of info popup window down N lines. See `corfu-popupinfo-scroll-up' for more details." (interactive "p") (corfu-popupinfo-scroll-up (- (or n 1)))) (defun corfu-popupinfo--toggle (fun) "Set documentation getter FUN and toggle popup." (when (< corfu--index 0) (corfu-popupinfo--hide) (user-error "No candidate selected")) (setq corfu-popupinfo--toggle (not (and (corfu-popupinfo--visible-p) (eq corfu-popupinfo--function fun)))) (if (not corfu-popupinfo--toggle) (corfu-popupinfo--hide) (setq corfu-popupinfo--function fun corfu-popupinfo--candidate nil) (let ((cand (nth corfu--index corfu--candidates))) (corfu-popupinfo--show cand) (unless (corfu-popupinfo--visible-p) (user-error "No %s available for `%s'" (car (last (split-string (symbol-name fun) "-+"))) cand))))) (defun corfu-popupinfo-documentation () "Show or hide documentation in popup. Behaves like `corfu-popupinfo-toggle'." (interactive) (corfu-popupinfo--toggle #'corfu-popupinfo--get-documentation)) (defun corfu-popupinfo-location () "Show or hide location in popup. Behaves like `corfu-popupinfo-toggle'." (interactive) (corfu-popupinfo--toggle #'corfu-popupinfo--get-location)) (defun corfu-popupinfo-toggle () "Toggle the info popup display or hide. When using this command to manually hide the info popup, it will not be displayed until this command is called again, even if `corfu-popupinfo-delay' is non-nil." (interactive) (corfu-popupinfo--toggle corfu-popupinfo--function)) ;;;###autoload (define-minor-mode corfu-popupinfo-mode "Corfu info popup minor mode." :global t :group 'corfu) (cl-defmethod corfu--exhibit :after (&context (corfu-popupinfo-mode (eql t)) &optional _auto) (when completion-in-region-mode (setf (alist-get #'corfu-popupinfo-mode minor-mode-overriding-map-alist) corfu-popupinfo-map) (when corfu-popupinfo--timer (cancel-timer corfu-popupinfo--timer) (setq corfu-popupinfo--timer nil)) (if (and (>= corfu--index 0) (corfu-popupinfo--visible-p corfu--frame)) (let ((cand (nth corfu--index corfu--candidates))) (if-let ((delay (if (consp corfu-popupinfo-delay) (funcall (if (eq corfu-popupinfo--toggle 'init) #'car #'cdr) corfu-popupinfo-delay) corfu-popupinfo-delay)) (corfu-popupinfo--toggle)) (if (or (<= delay 0) (and (corfu--equal-including-properties cand corfu-popupinfo--candidate) (corfu-popupinfo--visible-p))) (corfu-popupinfo--show cand) (when (corfu-popupinfo--visible-p) (cond (corfu-popupinfo-hide (corfu-popupinfo--hide)) (corfu-popupinfo--candidate (corfu-popupinfo--show corfu-popupinfo--candidate)))) (setq corfu-popupinfo--timer (run-at-time delay nil #'corfu-popupinfo--show cand))) (unless (corfu--equal-including-properties cand corfu-popupinfo--candidate) (corfu-popupinfo--hide)))) (corfu-popupinfo--hide)))) (cl-defmethod corfu--teardown :before (_buf &context (corfu-popupinfo-mode (eql t))) (corfu-popupinfo--hide) (cl-loop for (k . v) in corfu-popupinfo--initial-state do (set k v)) (cl-callf2 assq-delete-all #'corfu-popupinfo-mode minor-mode-overriding-map-alist)) ;; Do not show Corfu commands with M-X (dolist (sym '( corfu-popupinfo-scroll-down corfu-popupinfo-scroll-up corfu-popupinfo-documentation corfu-popupinfo-location corfu-popupinfo-beginning corfu-popupinfo-end corfu-popupinfo-toggle)) (put sym 'completion-predicate #'ignore)) (provide 'corfu-popupinfo) ;;; corfu-popupinfo.el ends here corfu-2.2/extensions/corfu-quick.el000066400000000000000000000120471501476044300174540ustar00rootroot00000000000000;;; corfu-quick.el --- Quick keys for Corfu -*- lexical-binding: t -*- ;; Copyright (C) 2022-2025 Free Software Foundation, Inc. ;; Author: Luis Henriquez-Perez , Daniel Mendler ;; Maintainer: Daniel Mendler ;; Created: 2022 ;; Version: 2.2 ;; Package-Requires: ((emacs "28.1") (compat "30") (corfu "2.2")) ;; URL: https://github.com/minad/corfu ;; This file is part of GNU Emacs. ;; 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: ;; This package is a Corfu extension, which prefixes candidates with ;; quick keys. Typing these quick keys allows you to select the ;; candidate in front of them. This is designed to be a faster ;; alternative to selecting a candidate with `corfu-next' and ;; `corfu-previous'. ;; (keymap-set corfu-map "M-q" #'corfu-quick-complete) ;; (keymap-set corfu-map "C-q" #'corfu-quick-insert) ;;; Code: (require 'corfu) (eval-when-compile (require 'cl-lib)) (defcustom corfu-quick1 "asdfgh" "First level quick keys." :type 'string :group 'corfu) (defcustom corfu-quick2 "jkluionm" "Second level quick keys." :type 'string :group 'corfu) (defface corfu-quick1 '((((class color) (min-colors 88) (background dark)) :background "#0050af" :foreground "white" :inherit bold) (((class color) (min-colors 88) (background light)) :background "#7feaff" :foreground "black" :inherit bold) (t :background "blue" :foreground "white" :inherit bold)) "Face used for the first quick key." :group 'corfu-faces) (defface corfu-quick2 '((((class color) (min-colors 88) (background dark)) :background "#7f1f7f" :foreground "white" :inherit bold) (((class color) (min-colors 88) (background light)) :background "#ffaaff" :foreground "black" :inherit bold) (t :background "magenta" :foreground "white" :inherit bold)) "Face used for the second quick key." :group 'corfu-faces) (defun corfu-quick--keys (two idx) ;; See vertico-quick--keys "Format quick keys prefix. IDX is the current candidate index. TWO is non-nil if two keys should be displayed." (let ((fst (length corfu-quick1)) (snd (length corfu-quick2))) (if (>= idx fst) (let ((first (elt corfu-quick2 (mod (/ (- idx fst) fst) snd))) (second (elt corfu-quick1 (mod (- idx fst) fst)))) (cond ((eq first two) (list (propertize (char-to-string second) 'face 'corfu-quick1) (cons second (+ corfu--scroll idx)))) (two (list "")) (t (list (concat (propertize (char-to-string first) 'face 'corfu-quick1) (propertize (char-to-string second) 'face 'corfu-quick2)) (cons first (list first)))))) (let ((first (elt corfu-quick1 (mod idx fst)))) (if two (list "") (list (propertize (char-to-string first) 'face 'corfu-quick1) (cons first (+ corfu--scroll idx)))))))) (defun corfu-quick--read (&optional first) "Read quick key given FIRST pressed key." (cl-letf* ((list nil) (orig (symbol-function #'corfu--format-candidates)) ((symbol-function #'corfu--format-candidates) (lambda (cands) (setq cands (funcall orig cands)) (cl-loop for cand in-ref (nth 2 cands) for index from 0 do (pcase-let ((`(,keys . ,events) (corfu-quick--keys first index))) (setf list (nconc events list) cand (concat keys (substring cand (min (length cand) (length keys))))))) cands))) (corfu--candidates-popup (posn-at-point (+ (car completion-in-region--data) (length corfu--base)))) (alist-get (read-key) list))) ;;;###autoload (defun corfu-quick-jump () "Jump to candidate using quick keys." (interactive) (when (fboundp 'corfu-echo--cancel) (corfu-echo--cancel)) (if (= corfu--total 0) (and (message "No match") nil) (let ((idx (corfu-quick--read))) (when (consp idx) (setq idx (corfu-quick--read (car idx)))) (when idx (setq corfu--index idx))))) ;;;###autoload (defun corfu-quick-insert () "Insert candidate using quick keys." (interactive) (when (corfu-quick-jump) (corfu-insert))) ;;;###autoload (defun corfu-quick-complete () "Complete candidate using quick keys." (interactive) (when (corfu-quick-jump) (corfu-complete))) (provide 'corfu-quick) ;;; corfu-quick.el ends here