pax_global_header 0000666 0000000 0000000 00000000064 14410372114 0014507 g ustar 00root root 0000000 0000000 52 comment=224f79b5f92d5a13a623a4cd7283a236b40dde81
corfu-0.36/ 0000775 0000000 0000000 00000000000 14410372114 0012555 5 ustar 00root root 0000000 0000000 corfu-0.36/CHANGELOG.org 0000664 0000000 0000000 00000004137 14410372114 0014562 0 ustar 00root root 0000000 0000000 #+title: corfu.el - Changelog
#+author: Daniel Mendler
#+language: en
* 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-0.36/LICENSE 0000664 0000000 0000000 00000104515 14410372114 0013570 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
corfu-0.36/README.org 0000664 0000000 0000000 00000064112 14410372114 0014227 0 ustar 00root root 0000000 0000000 #+title: corfu.el - Completion Overlay 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 Overlay Region FUnction
#+html:
#+html:
#+html:
Corfu enhances completion at point with a small completion popup. The current
candidates are shown in a popup below or above the point. Corfu is the
minimalistic ~completion-in-region~ 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. Completions are either
provided by commands like ~dabbrev-completion~ or by pluggable backends
(~completion-at-point-functions~, Capfs). Most programming language major modes
implement a Capf. Furthermore the language server packages, Eglot and Lsp-mode,
use Capfs which talk to the LSP server to retrieve the completions. Corfu does
not include its own completion backends. The Emacs built-in Capfs and the Capfs
provided by other programming language packages are usually sufficient. A few
additional Capfs and completion utilities are provided by the [[https://github.com/minad/cape][Cape]] package.
*NOTE*: Corfu uses child frames to show the popup and falls back to the default
setting of the ~completion-in-region-function~ on non-graphical displays. If you
want to use Corfu in the terminal, install the package [[https://codeberg.org/akib/emacs-corfu-terminal][corfu-terminal]], which
provides an alternative overlay-based display.
#+html:
#+html:
#+html:
#+html:
#+toc: headlines 8
* Features
- Timer-based auto-completions (/off/ by default, set ~corfu-auto~).
- 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=.
- Candidates sorting by prefix, string length and alphabetically.
- The selected candidate is previewed (configurable via ~corfu-preview-current~).
- The selected candidate automatically committed on further input by default.
(configurable via ~corfu-preview-current~).
- The [[https://github.com/oantolin/orderless][Orderless]] completion style is supported. The filter string can contain
arbitrary characters, after inserting a space via =M-SPC= (configurable via
~corfu-quit-at-boundary~ and ~corfu-separator~).
- Deferred completion style highlighting for performance.
- Support for candidate annotations (=annotation-function=, =affixation-function=).
- Deprecated candidates are crossed out in the display.
- Icons can be provided by an external package 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 and Configuration
Corfu is available from [[https://elpa.gnu.org/packages/corfu.html][GNU ELPA]], such that it can be installed directly via
~package-install~. After installation, the global minor mode can be enabled with
=M-x global-corfu-mode=. In order to configure Corfu and other packages in your
init.el, you may want to use ~use-package~.
Corfu is highly flexible and 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. For auto completion,
set ~corfu-auto=t~ before turning on ~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-auto t) ;; Enable auto completion
;; (corfu-separator ?\s) ;; Orderless field separator
;; (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
;; (corfu-scroll-margin 5) ;; Use scroll margin
;; Enable Corfu only for certain modes.
;; :hook ((prog-mode . corfu-mode)
;; (shell-mode . corfu-mode)
;; (eshell-mode . corfu-mode))
;; Recommended: Enable Corfu globally.
;; This is recommended since Dabbrev can be used globally (M-/).
;; See also `corfu-exclude-modes'.
:init
(global-corfu-mode))
;; A few more useful configurations...
(use-package emacs
:init
;; TAB cycle if there are only few candidates
(setq completion-cycle-threshold 3)
;; Emacs 28: Hide commands in M-x which do not apply to the current mode.
;; Corfu commands are hidden, since they are not supposed to be used via M-x.
;; (setq read-extended-command-predicate
;; #'command-completion-default-include-p)
;; Enable indentation+completion using the TAB key.
;; `completion-at-point' is often bound to M-TAB.
(setq tab-always-indent 'complete))
#+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))
;; Other useful Dabbrev configurations.
:custom
(dabbrev-ignored-buffer-regexps '("\\.\\(?:pdf\\|jpe?g\\|png\\)\\'")))
#+end_src
If you start to configure the package more deeply, I recommend to give the
Orderless completion style a try for filtering. Orderless completion is
different from the familiar prefix TAB completion. Corfu can be used with the
default completion styles. The use of Orderless is not a necessity.
#+begin_src emacs-lisp
;; Optionally use the `orderless' completion style.
(use-package orderless
:init
;; Configure a custom style dispatcher (see the Consult wiki)
;; (setq orderless-style-dispatchers '(+orderless-dispatch)
;; orderless-component-separator #'orderless-escapable-split-on-space)
(setq 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. See =+orderless-dispatch= in the [[https://github.com/minad/consult/wiki][Consult wiki]] for an advanced Orderless
style dispatcher. 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. The Eglot and Lsp-mode configurations are documented in the wiki. 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, but can be enabled by setting
~corfu-auto=t~. Furthermore 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 recommend to experiment a bit with the various settings and key bindings to
find a configuration which works for you. There is no one size fits all
solution. 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 aggressive auto completion settings, where the completion popup
appears immediately, I recommend to use a cheap completion style like =basic=,
which performs prefix filtering. In this case Corfu completion should still be
very fast in buffers with efficient completion backends. You can try the
following settings in an Elisp buffer or the Emacs scratch buffer.
#+begin_src emacs-lisp
;; Aggressive completion, cheap prefix filtering.
(setq-local corfu-auto t
corfu-auto-delay 0
corfu-auto-prefix 0
completion-styles '(basic))
#+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 prefix filtering for input shorter than 4 characters. Note that such a
setup is quite advanced. Please refer to the Orderless documentation and source
code for further details.
#+begin_src emacs-lisp
(defun orderless-fast-dispatch (word index total)
(and (= index 0) (= total 1) (length< word 4)
`(orderless-regexp . ,(concat "^" (regexp-quote word)))))
(orderless-define-completion-style orderless-fast
(orderless-style-dispatchers '(orderless-fast-dispatch))
(orderless-matching-styles '(orderless-literal orderless-regexp)))
(setq-local corfu-auto t
corfu-auto-delay 0
corfu-auto-prefix 0
completion-styles '(orderless-fast))
#+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. By default, ~global-corfu-mode~ does not
activate ~corfu-mode~ in the minibuffer, to avoid interference with specialised
minibuffer completion UIs like Vertico or Mct. However you may still want to
enable Corfu completion for commands like ~M-:~ (~eval-expression~) or ~M-!~
(~shell-command~), which read from the minibuffer. Activate ~corfu-mode~ only if
~completion-at-point~ is bound in the minibuffer-local keymap to achieve this
effect.
#+begin_src emacs-lisp
(defun corfu-enable-in-minibuffer ()
"Enable Corfu in the minibuffer if `completion-at-point' is bound."
(when (where-is-internal #'completion-at-point (list (current-local-map)))
;; (setq-local corfu-auto nil) ;; Enable/disable auto completion
(setq-local corfu-echo-delay nil ;; Disable automatic echo and popup
corfu-popupinfo-delay nil)
(corfu-mode 1)))
(add-hook 'minibuffer-setup-hook #'corfu-enable-in-minibuffer)
#+end_src
You can also enable Corfu more generally for every minibuffer, as long as no
completion UI is active. In the following example we check for Mct and Vertico.
Furthermore we ensure that Corfu is not enabled if a password is read from the
minibuffer.
#+begin_src emacs-lisp
(defun corfu-enable-always-in-minibuffer ()
"Enable Corfu in the minibuffer if Vertico/Mct are not active."
(unless (or (bound-and-true-p mct--active)
(bound-and-true-p vertico--input)
(eq (current-local-map) read-passwd-map))
;; (setq-local corfu-auto nil) ;; Enable/disable auto completion
(setq-local corfu-echo-delay nil ;; Disable automatic echo and popup
corfu-popupinfo-delay nil)
(corfu-mode 1)))
(add-hook 'minibuffer-setup-hook #'corfu-enable-always-in-minibuffer 1)
#+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! In my configuration I
define the advice ~corfu-send-shell~ which sends the candidate after insertion.
#+begin_src emacs-lisp
(defun corfu-send-shell (&rest _)
"Send completion candidate when inside comint/eshell."
(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))))
(advice-add #'corfu-insert :after #'corfu-send-shell)
#+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 the [[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. This functionality is
similar to the Fish shell, which also takes advantage of ~--help~ to dynamically
generate completions.
Unfortunately Pcomplete had a few technical issues on Emacs 28 and older. 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. If you use Emacs
28 or older installing these advices is strongly recommend such that Pcomplete
works properly. On Emacs 29 the advices are not necessary anymore, since almost
all of the related bugs have been fixed. I therefore recommend to remove the
advices on Emacs 29 and eventually report any remaining Pcomplete issues
upstream, such that they can be fixed at the root.
#+begin_src emacs-lisp
;; The advices are only needed on Emacs 28 and older.
(when (< emacs-major-version 29)
;; Silence the pcomplete capf, no errors or messages!
(advice-add 'pcomplete-completions-at-point :around #'cape-wrap-silent)
;; Ensure that pcomplete does not write to the buffer
;; and behaves as a pure `completion-at-point-function'.
(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=t~. 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, simply set ~corfu-quit-at-boundary=nil~. 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-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/collect is possible
directly from Corfu. But in my opinion having the ability to transfer the Corfu
completion to the minibuffer is an even better feature, since further completion
can be performed there.
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)
(let ((completion-extra-properties corfu--extra)
completion-cycle-threshold completion-cycling)
(apply #'consult-completion-in-region completion-in-region--data)))
(keymap-set corfu-map "M-m" #'corfu-move-to-minibuffer)
#+end_src
* Key bindings
Corfu uses a transient keymap ~corfu-map~ which is active while the popup is
shown. The keymap defines the following remappings and bindings:
- ~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~
- =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~
* 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.
- [[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://codeberg.org/akib/emacs-corfu-terminal][corfu-terminal]]: The corfu-terminal package provides an overlay-based display
for Corfu, such that you can use Corfu in terminal Emacs.
- [[https://github.com/oantolin/orderless][Orderless]]: Corfu supports completion styles, including the advanced
[[https://github.com/oantolin/orderless][Orderless]] completion style, where the filtering expressions are separated by
spaces or another character (see ~corfu-separator~).
- [[https://github.com/minad/cape][Cape]]: Additional Capf backends and =completion-in-region= commands
are provided by the [[https://github.com/minad/cape][Cape]] package. Among others, the package supplies a file
path and a Dabbrev completion backend. Cape provides the ~cape-company-to-capf~
adapter to reuse Company backends in Corfu. Furthermore the function
~cape-super-capf~ can merge multiple Capfs, such that the candidates of multiple
Capfs are displayed together at the same time.
- [[https://github.com/jdtsmith/kind-icon][kind-icon]]: Icons are supported by Corfu via an external package. For example
the [[https://github.com/jdtsmith/kind-icon][kind-icon]] package provides beautifully styled SVG icons based on
monochromatic icon sets like material design.
- [[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 [[https://github.com/minad/vertico][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 interaction model and popup 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 completion
backends, which are incompatible with the Emacs completion infrastructure. As
a result of this design, Company is a more complex package than Corfu. 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.
* 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-0.36/corfu.el 0000664 0000000 0000000 00000155702 14410372114 0014227 0 ustar 00root root 0000000 0000000 ;;; corfu.el --- Completion Overlay Region FUnction -*- lexical-binding: t -*-
;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
;; Author: Daniel Mendler
;; Maintainer: Daniel Mendler
;; Created: 2021
;; Version: 0.36
;; Package-Requires: ((emacs "27.1") (compat "29.1.4.0"))
;; Homepage: 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:
;; Corfu enhances the default completion in region function with a
;; completion overlay. The current candidates are shown in a popup
;; below or above the point. Corfu can be considered the minimalistic
;; completion-in-region counterpart of Vertico.
;;; Code:
(require 'compat)
(eval-when-compile
(require 'cl-lib)
(require 'subr-x))
(defgroup corfu nil
"Completion Overlay Region FUnction."
:link '(info-link :tag "Info Manual" "(corfu)")
:link '(url-link :tag "Homepage" "https://github.com/minad/corfu")
: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."
:type '(choice (const insert) (const quit) (const nil)))
(defcustom corfu-continue-commands
;; nil is undefined command
'(nil ignore universal-argument universal-argument-more digit-argument
"\\`corfu-" "\\`scroll-other-window")
"Continue Corfu completion after executing these commands."
: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-exclude-modes nil
"List of modes excluded by `global-corfu-mode'."
:type '(repeat symbol))
(define-obsolete-function-alias 'corfu-excluded-modes 'corfu-exclude-modes "0.35")
(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."
:type 'hook)
(defcustom corfu-sort-function #'corfu-sort-length-alpha
"Default sorting function, used if no `display-sort-function' is specified."
: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'."
: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 very small delay or even 0,
since this will create high load for Emacs in particular if the
completion backend in use is expensive."
:type 'float)
(defcustom corfu-auto-commands
'("self-insert-command\\'"
c-electric-colon c-electric-lt-gt c-electric-slash c-scope-operator)
"Commands which initiate auto completion."
:type '(repeat (choice regexp symbol)))
(defcustom corfu-auto nil
"Enable auto completion."
: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")
(((class color) (min-colors 88) (background light))
:background "#c0efff" :foreground "black")
(t :background "blue" :foreground "white"))
"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-map
:doc "Corfu 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
;; XXX C-a is bound because of eshell.
;; Ideally eshell would remap move-beginning-of-line.
"C-a" #'corfu-prompt-beginning
;; XXX [tab] is bound because of org-mode
;; The binding should be removed from org-mode-map.
"" #'corfu-complete
"M-n" #'corfu-next
"M-p" #'corfu-previous
"C-g" #'corfu-quit
"RET" #'corfu-insert
"TAB" #'corfu-complete
"M-g" 'corfu-info-location
"M-h" 'corfu-info-documentation
"M-SPC" #'corfu-insert-separator)
(defvar corfu--auto-timer nil
"Auto completion timer.")
(defvar-local corfu--candidates nil
"List of candidates.")
(defvar-local corfu--metadata nil
"Completion metadata.")
(defvar-local corfu--base ""
"Base string, which is concatenated with the candidate.")
(defvar-local corfu--total 0
"Length of the candidate list `corfu--candidates'.")
(defvar-local corfu--highlight #'identity
"Deferred candidate highlighting function.")
(defvar-local corfu--index -1
"Index of current candidate or negative for prompt selection.")
(defvar-local corfu--preselect -1
"Index of preselected candidate, negative for prompt selection.")
(defvar-local corfu--scroll 0
"Scroll position.")
(defvar-local corfu--input nil
"Cons of last prompt contents and point.")
(defvar-local corfu--preview-ov nil
"Current candidate overlay.")
(defvar-local corfu--extra nil
"Extra completion properties.")
(defvar-local corfu--change-group nil
"Undo change group.")
(defvar corfu--frame nil
"Popup frame.")
(defconst corfu--state-vars
'(corfu--base
corfu--candidates
corfu--highlight
corfu--index
corfu--preselect
corfu--scroll
corfu--input
corfu--total
corfu--preview-ov
corfu--extra
corfu--change-group
corfu--metadata)
"Buffer-local state variables used by Corfu.")
(defvar corfu--frame-parameters
'((no-accept-focus . t)
(no-focus-on-map . t)
(min-width . t)
(min-height . t)
(border-width . 0)
(child-frame-border-width . 1)
(left-fringe . 0)
(right-fringe . 0)
(vertical-scroll-bars . nil)
(horizontal-scroll-bars . nil)
(menu-bar-lines . 0)
(tool-bar-lines . 0)
(tab-bar-lines . 0)
(no-other-frame . t)
(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) ;; Emacs 28 tab-bar-format
(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 . nil)
(right-fringe-width . nil)
(left-margin-width . 0)
(right-margin-width . 0)
(fringes-outside-margins . 0)
(fringe-indicator-alist . nil)
(indicate-empty-lines . nil)
(indicate-buffer-boundaries . nil)
(buffer-read-only . t))
"Default child frame buffer parameters.")
(defvar corfu--mouse-ignore-map
(let ((map (make-sparse-keymap)))
(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--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))
(and
;; 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
(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 buffer)
"Show BUFFER in child frame at X/Y with WIDTH/HEIGHT.
FRAME is the existing frame."
(when-let (timer (and (frame-live-p frame)
(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)
(after-make-frame-functions)
(parent (window-frame)))
(unless (and (frame-live-p frame)
(eq (frame-parent frame) parent)
;; XXX HACK: It seems the frame can be alive but have a dead window?
;; Is this a Emacs 29 regression?
(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)
;; Set `internal-border-width' for Emacs 27
(internal-border-width
. ,(alist-get 'child-frame-border-width corfu--frame-parameters))
,@corfu--frame-parameters))))
;; 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 suprises.
(when-let ((params (frame-parameters frame))
(reset (seq-remove
(lambda (p) (equal (alist-get (car p) params) (cdr p)))
corfu--frame-parameters)))
(modify-frame-parameters frame reset))
;; 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 (BUG?).
(let* ((face (if (facep 'child-frame-border) 'child-frame-border 'internal-border))
(new (face-attribute 'corfu-border :background nil 'default)))
(unless (equal (face-attribute face :background frame 'default) new)
(set-face-background face new frame)))
(let ((new (face-attribute 'corfu-default :background nil 'default)))
(unless (equal (frame-parameter frame 'background-color) new)
(set-frame-parameter frame 'background-color new)))
(let ((win (frame-root-window frame)))
(set-window-buffer win buffer)
;; Disallow selection of root window (#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 (#60)
(set-window-dedicated-p win t))
;; XXX HACK: Child frame popup behavior improved on Emacs 29.
;; It seems we may not need the Emacs 27/28 hacks anymore.
(if (eval-when-compile (< emacs-major-version 29))
(let (inhibit-redisplay)
(set-frame-size frame width height t)
(if (frame-visible-p frame)
;; XXX HACK Avoid flicker when frame is already visible.
;; Redisplay, wait for resize and then move the frame.
(unless (equal (frame-position frame) (cons x y))
(redisplay 'force)
(sleep-for 0.01)
(set-frame-position frame x y))
;; XXX HACK: Force redisplay, otherwise the popup sometimes does not
;; display content.
(set-frame-position frame x y)
(redisplay 'force)
(make-frame-visible frame)))
(set-frame-size frame width height t)
(unless (equal (frame-position frame) (cons x y))
(set-frame-position frame x y))
(unless (frame-visible-p frame)
(make-frame-visible frame)))
(redirect-frame-focus frame parent)
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
(erase-buffer)))))
(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."
(if-let (found (member elem list))
(nconc (list (car found)) (delq (setcar found nil) list))
list))
;; bug#47711: Deferred highlighting for `completion-all-completions'
;; XXX There is one complication: `completion--twq-all' already adds
;; `completions-common-part'.
(defun corfu--all-completions (&rest args)
"Compute all completions for ARGS with deferred highlighting."
(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 deferred
;; 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))))
;; Defer the following highlighting functions
(hl #'identity)
((symbol-function #'completion-hilit-commonality)
(lambda (cands prefix &optional base)
(setq hl (lambda (x) (nconc (completion-hilit-commonality x prefix base) nil)))
(and cands (nconc cands base))))
((symbol-function #'completion-pcm--hilit-commonality)
(lambda (pattern cands)
(setq hl (lambda (x)
;; `completion-pcm--hilit-commonality' sometimes
;; throws an internal error for example when entering
;; "/sudo:://u".
(condition-case nil
(completion-pcm--hilit-commonality pattern x)
(t x))))
cands)))
;; Only advise orderless after it has been loaded to avoid load order issues
(if (and (fboundp 'orderless-highlight-matches)
(fboundp 'orderless-pattern-compiler))
(cl-letf (((symbol-function 'orderless-highlight-matches)
(lambda (pattern cands)
(let ((regexps (orderless-pattern-compiler pattern)))
(setq hl (lambda (x) (orderless-highlight-matches regexps x))))
cands)))
(cons (apply #'completion-all-completions args) hl))
(cons (apply #'completion-all-completions args) hl))))
(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 candidates)
"Move CANDIDATES which match prefix of FIELD to the beginning."
(let* ((word (substring field 0
(seq-position field corfu-separator)))
(len (length word)))
(corfu--partition!
candidates
(and (>= (length it) len)
(eq t (compare-strings word 0 len it 0 len
completion-ignore-case))))))
(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 between the slashes of "~//".
;; See also vertico.el which has the same issue.
(bounds (or (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--all-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)))
;; 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)))
(setq all (delete-consecutive-dups (funcall (or (corfu--sort-function) #'identity) all)))
(setq 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))
`((corfu--base . ,corfu--base)
(corfu--metadata . ,corfu--metadata)
(corfu--candidates . ,all)
(corfu--total . ,(length all))
(corfu--highlight . ,hl)
(corfu--preselect . ,(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)))))
(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 becomes immediately visible before the
;; expensive candidate recomputation is performed (Issue #48). See also
;; corresponding 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))
;; XXX Guard against errors during candidate generation.
;; bug#61274: `dabbrev-capf' signals errors.
(condition-case err
(if interruptible
(while-no-input (corfu--recompute str pt table pred))
(corfu--recompute str pt table pred))
(error
(message "Corfu completion error: %s" (error-message-string err))
t)))
('nil (keyboard-quit))
((and state (pred consp))
(dolist (s state) (set (car s) (cdr s)))
(setq corfu--input input
corfu--index corfu--preselect))))
input))
(defun corfu--match-symbol-p (pattern sym)
"Return non-nil if SYM is matching an element of the PATTERN list."
(and (symbolp sym)
(cl-loop for x in 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."
;; Note: Do not use `completion-metadata-get' in order to avoid Marginalia.
;; The Marginalia annotators are too heavy for the Corfu popup!
(cdr (assq prop corfu--metadata)))
(defun corfu--format-candidates (cands)
"Format annotated CANDS."
(setq cands
(cl-loop for c in cands collect
(cl-loop for s in c collect
(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 (+ pw cw sw))
;; -4 because of margins and some additional safety
(max-width (min corfu-max-width (- (frame-width) 4))))
(when (> width max-width)
(setq sw (max 0 (- max-width pw cw))
width (+ pw cw sw)))
(when (< width corfu-min-width)
(setq cw (+ cw (- corfu-min-width width))
width corfu-min-width))
(setq width (min width max-width))
(list pw width
(cl-loop for (cand prefix suffix) in cands collect
(truncate-string-to-width
(concat prefix
(make-string (max 0 (- pw (string-width prefix))) ?\s)
cand
(when (/= sw 0)
(make-string
(+ (max 0 (- cw (string-width cand)))
(max 0 (- sw (string-width suffix))))
?\s))
suffix)
width)))))
(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 (funcall corfu--highlight
(seq-subseq corfu--candidates corfu--scroll last))))
(`(,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 (length corfu--base)) pw width fcands (- corfu--index corfu--scroll)
(and (> corfu--total corfu-count) lo) bar)))
(defun corfu--preview-current (beg end)
"Show current candidate as overlay given BEG and END."
(when-let (cand (and corfu-preview-current (>= corfu--index 0)
(/= corfu--index corfu--preselect)
(nth corfu--index corfu--candidates)))
(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) cand)))
(defun corfu--continue-p ()
"Continue completion?"
(pcase-let ((pt (point))
(buf (current-buffer))
(`(,beg ,end . ,_) completion-in-region--data))
(and beg end
(eq buf (marker-buffer beg))
(eq buf (window-buffer))
;; Check ranges
(<= beg pt end)
(save-excursion
(goto-char beg)
(<= (pos-bol) pt (pos-eol)))
(or
;; 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.
overriding-terminal-local-map
;; Check if it is an explicitly listed continue command
(corfu--match-symbol-p corfu-continue-commands this-command)
(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--post-command ()
"Refresh Corfu after last command."
(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--done (str status)
"Call the `:exit-function' with STR and STATUS and exit completion."
(let ((exit (plist-get corfu--extra :exit-function)))
;; For successfull completions, amalgamate undo operations,
;; such that completion can be undone in a single step.
(undo-amalgamate-change-group corfu--change-group)
(corfu-quit)
(when exit (funcall exit str status))))
(defun corfu--setup ()
"Setup Corfu completion state."
(setq corfu--extra completion-extra-properties)
(completion-in-region-mode 1)
(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 '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 teardown runs in the correct buffer, if still alive.
(unless completion-in-region-mode
(remove-hook 'completion-in-region-mode-hook sym)
(with-current-buffer (if (buffer-live-p buf) buf (current-buffer))
(corfu--teardown)))))
(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))
(exit (plist-get completion-extra-properties :exit-function))
(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")
(when exit (funcall exit str 'finished))
t)
(`(,newstr . ,newpt)
(let* ((state (corfu--recompute str pt table pred))
(base (alist-get 'corfu--base state))
(total (alist-get 'corfu--total state))
(candidates (alist-get 'corfu--candidates state)))
(unless (markerp beg) (setq beg (copy-marker beg)))
(setq end (copy-marker end t)
completion-in-region--data (list beg end table pred))
(unless (equal str newstr)
;; bug#55205: completion--replace removes properties!
(completion--replace beg end (concat newstr)))
(goto-char (+ beg newpt))
(if (= total 1)
;; If completion is finished and cannot be further completed,
;; return 'finished. Otherwise setup the Corfu popup.
(cond
((consp (completion-try-completion
newstr table pred newpt
(completion-metadata newstr table pred)))
(corfu--setup))
(exit (funcall exit newstr 'finished)))
(if (or (= total 0) (not threshold)
(and (not (eq threshold t)) (< threshold total)))
(corfu--setup)
(corfu--cycle-candidates total candidates (+ (length base) beg) end)
;; Do not show Corfu when "trivially" cycling, i.e.,
;; when the completion is finished after the candidate.
(unless (equal (completion-boundaries (car candidates) table pred "")
'(0 . 0))
(corfu--setup)))))
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)
;; bug#55205: completion--replace removes properties!
(completion--replace beg end (concat (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."
(setq corfu--auto-timer nil)
(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))
(setq completion-in-region--data
(list (if (markerp beg) beg (copy-marker beg))
(copy-marker end t)
table
(plist-get plist :predicate)))
(corfu--setup)
(corfu--exhibit 'auto))))))
(defun corfu--auto-post-command ()
"Post command hook which initiates auto completion."
(when corfu--auto-timer
(cancel-timer corfu--auto-timer)
(setq corfu--auto-timer nil))
(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)
;; NOTE: Do not use idle timer since this leads to unacceptable slowdowns,
;; in particular if flyspell-mode is enabled.
(setq corfu--auto-timer
(run-at-time corfu-auto-delay nil
#'corfu--auto-complete-deferred (corfu--auto-tick))))))
(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 (default-line-height)))
(with-current-buffer (corfu--make-buffer " *corfu*")
(let* ((ch (default-line-height))
(cw (default-font-width))
(ml (ceiling (* cw corfu-left-margin-width)))
(mr (ceiling (* cw corfu-right-margin-width)))
(bw (ceiling (min mr (* cw corfu-bar-width))))
(marginl (and (> ml 0) (propertize " " 'display `(space :width (,ml)))))
(marginr (and (> mr 0) (propertize " " 'display `(space :align-to right))))
(sbar (when (> bw 0)
(concat (propertize " " 'display `(space :align-to (- right (,mr))))
(propertize " " 'display `(space :width (,(- mr bw))))
(propertize " " 'face 'corfu-bar 'display `(space :width (,bw))))))
(pos (posn-x-y (posn-at-point pos)))
(width (+ (* width cw) ml mr))
;; XXX HACK: Minimum popup height must be at least 1 line of the
;; parent frame (#261).
(height (max lh (* (length lines) ch)))
(edge (window-inside-pixel-edges))
(border (alist-get 'child-frame-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) (window-tab-line-height) (or (cdr pos) 0) lh))
(y (if (> (+ yb (* corfu-count ch) lh lh) (frame-pixel-height))
(- yb height lh border border)
yb))
(row 0))
(with-silent-modifications
(erase-buffer)
(insert (mapconcat (lambda (line)
(let ((str (concat marginl line
(if (and lo (<= lo row (+ lo bar)))
sbar
marginr))))
(when (eq row curr)
(add-face-text-property
0 (length str) 'corfu-current 'append str))
(cl-incf row)
str))
lines "\n"))
(goto-char (point-min)))
(setq corfu--frame (corfu--make-frame corfu--frame x y
width height (current-buffer)))))))
(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."
(display-graphic-p))
(cl-defgeneric corfu--insert (status)
"Insert current candidate, exit with STATUS if non-nil."
(pcase-let* ((`(,beg ,end . ,_) completion-in-region--data)
(str (buffer-substring-no-properties beg end)))
;; 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.
(setq str (concat corfu--base (substring-no-properties
(nth corfu--index corfu--candidates))))
;; bug#55205: completion--replace removes properties!
(completion--replace beg end (concat str))
(corfu--goto -1) ;; Reset selection, but continue completion.
(when status (corfu--done str status)))) ;; Exit with status
(cl-defgeneric corfu--affixate (cands)
"Annotate CANDS with annotation function."
(setq cands
(if-let (aff (or (corfu--metadata-get 'affixation-function)
(plist-get corfu--extra :affixation-function)))
(funcall aff cands)
(if-let (ann (or (corfu--metadata-get 'annotation-function)
(plist-get corfu--extra :annotation-function)))
(cl-loop for cand in cands collect
(let ((suffix (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 suffix) 'face nil suffix)
(setq suffix (propertize suffix 'face 'corfu-annotations)))
(list cand "" suffix)))
(cl-loop for cand in cands collect (list cand "" "")))))
(let* ((dep (plist-get corfu--extra :company-deprecated))
(completion-extra-properties corfu--extra)
(mf (run-hook-with-args-until-success 'corfu-margin-formatters corfu--metadata)))
(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."
(when corfu--preview-ov
(delete-overlay corfu--preview-ov)
(setq corfu--preview-ov nil))
;; Ensure that state is initialized before next Corfu command
(when (and (symbolp this-command) (string-prefix-p "corfu-" (symbol-name this-command)))
(corfu--update))
(when (and (eq corfu-preview-current 'insert)
(/= corfu--index corfu--preselect)
;; 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 (consp (completion-try-completion str table pred pt corfu--metadata)))
(or auto corfu-on-exact-match))
;; Quit directly when initializing auto completion.
(if (or auto (eq corfu-on-exact-match 'quit))
(corfu-quit)
(corfu--done str 'finished)))
;; 2) There exist candidates => Show candidates popup.
(corfu--candidates
(corfu--candidates-popup beg)
(corfu--preview-current beg end)
(redisplay 'force)) ;; XXX HACK Ensure that popup is redisplayed
;; 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 beg 0 8 '(#("No match" 0 8 (face italic))))
(redisplay 'force)) ;; XXX HACK Ensure that popup is redisplayed
;; 4) No candidates & auto completing or initialized => Quit.
((or auto corfu--input) (corfu-quit)))))
(cl-defgeneric corfu--teardown ()
"Teardown Corfu."
(corfu--popup-hide)
(remove-hook 'pre-command-hook #'corfu--prepare 'local)
(remove-hook 'post-command-hook #'corfu--post-command)
(when corfu--preview-ov (delete-overlay corfu--preview-ov))
(accept-change-group corfu--change-group)
(mapc #'kill-local-variable corfu--state-vars))
(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.
(cancel-change-group corfu--change-group)
(activate-change-group (setq corfu--change-group (prepare-change-group)))
(when (eq last-command #'corfu-reset) (corfu-quit))))
(defun corfu-insert-separator ()
"Insert a separator character, inhibiting quit on completion boundary.
See `corfu-separator' for more details."
(interactive)
(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 ()
"Try to complete current input.
If a candidate is selected, insert it."
(interactive)
(pcase-let ((`(,beg ,end ,table ,pred) completion-in-region--data))
(if (>= corfu--index 0)
;; Continue completion with selected candidate
(progn
(corfu--insert nil)
;; Exit with status 'finished if input is a valid match and no further
;; completion is possible. Furthermore treat the completion as
;; finished if we are 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!
(let ((newstr (buffer-substring-no-properties beg end)))
(when (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))))
;; Try to complete the current input string
(let* ((pt (max 0 (- (point) beg)))
(str (buffer-substring-no-properties beg end))
(metadata (completion-metadata (substring str 0 pt) table pred)))
(pcase (completion-try-completion str table pred pt metadata)
('t
(goto-char end)
(corfu--done str 'finished))
(`(,newstr . ,newpt)
(unless (equal str newstr)
;; bug#55205: completion--replace removes properties!
(completion--replace beg end (concat newstr)))
(goto-char (+ beg newpt))
;; Exit with status 'finished if input is a valid match
;; and no further completion is possible.
(when (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))))))))
(defun corfu-insert ()
"Insert current candidate.
Quit if no candidate is selected."
(interactive)
(if (>= corfu--index 0)
(corfu--insert 'finished)
(corfu-quit)))
;;;###autoload
(define-minor-mode corfu-mode
"Completion Overlay Region FUnction."
:global nil :group 'corfu
(cond
(corfu-mode
;; FIXME: Install advice which fixes `completion--capf-wrapper', such that
;; it respects the completion styles for non-exclusive capfs. See FIXME in
;; the `completion--capf-wrapper' function in minibuffer.el, where the
;; issue has been mentioned. We never uninstall this advice since the
;; advice is active *globally*.
(advice-add #'completion--capf-wrapper :around #'corfu--capf-wrapper-advice)
(advice-add #'eldoc-display-message-no-interference-p :before-while #'corfu--eldoc-advice)
(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))))
(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. PREFIX is a prefix
length override, set to 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--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)))
;;;###autoload
(define-globalized-minor-mode global-corfu-mode corfu-mode corfu--on :group 'corfu)
(defun corfu--on ()
"Turn `corfu-mode' on."
(unless (or noninteractive
buffer-read-only
(eq (aref (buffer-name) 0) ?\s)
(memq major-mode corfu-exclude-modes))
(corfu-mode 1)))
(defun corfu--eldoc-advice ()
"Return non-nil if Corfu is currently not active."
(not (and corfu-mode completion-in-region-mode)))
;; Emacs 28: 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-insert-separator))
(put sym 'completion-predicate #'ignore))
(provide 'corfu)
;;; corfu.el ends here
corfu-0.36/extensions/ 0000775 0000000 0000000 00000000000 14410372114 0014754 5 ustar 00root root 0000000 0000000 corfu-0.36/extensions/corfu-echo.el 0000664 0000000 0000000 00000007375 14410372114 0017344 0 ustar 00root root 0000000 0000000 ;;; corfu-echo.el --- Show candidate documentation in echo area -*- lexical-binding: t -*-
;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
;; Author: Daniel Mendler
;; Maintainer: Daniel Mendler
;; Created: 2022
;; Version: 0.1
;; Package-Requires: ((emacs "27.1") (corfu "0.36"))
;; Homepage: 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-local corfu-echo--timer nil
"Echo area message timer.")
(defvar-local 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
(kill-local-variable 'corfu-echo--timer)
(kill-local-variable 'corfu-echo--message)))
(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 ((delay (if (consp corfu-echo-delay)
(funcall (if corfu-echo--message #'cdr #'car)
corfu-echo-delay)
corfu-echo-delay))
(fun (plist-get corfu--extra :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 (&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-0.36/extensions/corfu-history.el 0000664 0000000 0000000 00000007074 14410372114 0020123 0 ustar 00root root 0000000 0000000 ;;; corfu-history.el --- Sorting by history for Corfu -*- lexical-binding: t -*-
;; Copyright (C) 2022-2023 Free Software Foundation, Inc.
;; Author: Daniel Mendler
;; Maintainer: Daniel Mendler
;; Created: 2022
;; Version: 0.1
;; Package-Requires: ((emacs "27.1") (corfu "0.36"))
;; Homepage: 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. Maintain a list of recently selected candidates. In order
;; to save the history across Emacs sessions, enable `savehist-mode' and
;; add `corfu-history' to `savehist-additional-variables'.
;;
;; (corfu-history-mode 1)
;; (savehist-mode 1)
;; (add-to-list 'savehist-additional-variables 'corfu-history)
;;; Code:
(require 'corfu)
(eval-when-compile
(require 'cl-lib))
(defcustom corfu-history-length nil
"Corfu history length."
:type '(choice (const nil) natnum)
:group 'corfu)
(defvar corfu-history--hash nil
"Hash table of Corfu candidates.")
(defvar corfu-history nil
"History of Corfu candidates.")
(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 (candidates)
"Sort CANDIDATES by history."
(unless corfu-history--hash
(setq corfu-history--hash (make-hash-table :test #'equal :size (length corfu-history)))
(cl-loop for elem in corfu-history for index from 0 do
(unless (gethash elem corfu-history--hash)
(puthash elem index corfu-history--hash))))
;; Decorate each candidate with (index<<13) + length. This way we sort first by index and then by
;; length. We assume that the candidates are shorter than 2**13 characters and that the history is
;; shorter than 2**16 entries.
(cl-loop for cand on candidates do
(setcar cand (cons (car cand)
(+ (ash (gethash (car cand) corfu-history--hash #xFFFF) 13)
(length (car cand))))))
(setq candidates (sort candidates #'corfu-history--sort-predicate))
(cl-loop for cand on candidates do (setcar cand (caar cand)))
candidates)
;;;###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)
(add-to-history 'corfu-history
(substring-no-properties
(nth corfu--index corfu--candidates))
corfu-history-length)
(setq corfu-history--hash nil)))
(provide 'corfu-history)
;;; corfu-history.el ends here
corfu-0.36/extensions/corfu-indexed.el 0000664 0000000 0000000 00000006756 14410372114 0020050 0 ustar 00root root 0000000 0000000 ;;; corfu-indexed.el --- Select indexed candidates -*- lexical-binding: t -*-
;; Copyright (C) 2022-2023 Free Software Foundation, Inc.
;; Author: Luis Henriquez-Perez , Daniel Mendler
;; Maintainer: Daniel Mendler
;; Created: 2022
;; Version: 0.1
;; Package-Requires: ((emacs "27.1") (corfu "0.36"))
;; Homepage: 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-0.36/extensions/corfu-info.el 0000664 0000000 0000000 00000010073 14410372114 0017346 0 ustar 00root root 0000000 0000000 ;;; corfu-info.el --- Show candidate information in separate buffer -*- lexical-binding: t -*-
;; Copyright (C) 2022-2023 Free Software Foundation, Inc.
;; Author: Daniel Mendler
;; Maintainer: Daniel Mendler
;; Created: 2022
;; Version: 0.1
;; Package-Requires: ((emacs "27.1") (corfu "0.36"))
;; Homepage: 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)))
;;;###autoload
(defun corfu-info-documentation ()
"Show documentation of current candidate."
(interactive)
;; 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 (plist-get corfu--extra :company-doc-buffer))
(res (funcall fun cand)))
(let ((buf (or (car-safe res) res)))
(corfu-info--restore-on-next-command)
(setq other-window-scroll-buffer (get-buffer buf))
(set-window-start (display-buffer buf t) (or (cdr-safe res) (point-min))))
(user-error "No documentation available for `%s'" cand))))
;;;###autoload
(defun corfu-info-location ()
"Show location of current candidate."
(interactive)
;; 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)))
;; BUG: company-location may throw errors if location is not found
(if-let ((fun (ignore-errors (plist-get corfu--extra :company-location)))
(loc (funcall fun cand)))
(let ((buf (or (and (bufferp (car loc)) (car loc))
(find-file-noselect (car loc) t))))
(corfu-info--restore-on-next-command)
(setq other-window-scroll-buffer buf)
(with-selected-window (display-buffer buf t)
(save-restriction
(widen)
(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))))
;; Emacs 28: Do not show Corfu commands with M-X
(put #'corfu-info-location 'completion-predicate #'ignore)
(put #'corfu-info-documentation 'completion-predicate #'ignore)
(provide 'corfu-info)
;;; corfu-info.el ends here
corfu-0.36/extensions/corfu-popupinfo.el 0000664 0000000 0000000 00000053061 14410372114 0020436 0 ustar 00root root 0000000 0000000 ;;; corfu-popupinfo.el --- Candidate information popup for Corfu -*- lexical-binding: t -*-
;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
;; Author: Yuwei Tian , Daniel Mendler
;; Maintainer: Daniel Mendler
;; Created: 2022
;; Version: 0.1
;; Package-Requires: ((emacs "27.1") (corfu "0.36"))
;; Homepage: 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 very small delay, since this
will create high load for Emacs since retrieving the
documentation 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 directionse for the popup in order."
:type '(repeat
(choice
(const left)
(const right)
(const vertical)
(const force-left)
(const force-right)
(const force-horizontal)
(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)
(fringe-indicator-alist (continuation)))
"Buffer parameters.")
(defvar-local corfu-popupinfo--toggle 'init
"Local toggle state.")
(defvar-local corfu-popupinfo--function
#'corfu-popupinfo--get-documentation
"Function called to obtain documentation string.")
(defvar corfu-popupinfo--frame nil
"Info popup child frame.")
(defvar corfu-popupinfo--timer nil
"Corfu info popup auto display timer.")
(defvar-local corfu-popupinfo--candidate nil
"Completion candidate for the info popup.")
(defvar-local 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-local corfu-popupinfo--lock-dir nil
"Locked position direction of the info popup.")
(defconst corfu-popupinfo--state-vars
'(corfu-popupinfo--candidate
corfu-popupinfo--coordinates
corfu-popupinfo--lock-dir
corfu-popupinfo--toggle
corfu-popupinfo--function)
"Buffer-local state variables used by corfu-popupinfo.")
(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 (plist-get corfu--extra :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)
(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
(save-restriction
(widen)
(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 (plist-get corfu--extra :company-doc-buffer))
(res (save-excursion
(let ((inhibit-message t)
(inhibit-redisplay t)
(message-log-max nil)
;; 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*"
(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 'child-frame-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 (and (corfu-popupinfo--visible-p corfu--frame))
(let* ((cand-changed
(not (and (corfu-popupinfo--visible-p)
(equal 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*")
(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)))
(setf face-remapping-alist (copy-tree face-remapping-alist)
(alist-get 'default face-remapping-alist) 'corfu-popupinfo))
(unless (eq corfu-popupinfo--toggle 'init)
(message "No %s available for `%s'"
(car (last (split-string (symbol-name corfu-popupinfo--function) "-+")))
candidate))
(corfu-popupinfo--hide)
(setq cand-changed nil coords-changed nil)))
(when (or cand-changed coords-changed)
(pcase-let* ((border (alist-get 'child-frame-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)))
(setq corfu-popupinfo--frame
(corfu--make-frame corfu-popupinfo--frame
area-x area-y area-w area-h
" *corfu-popupinfo*")
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*")))))))
(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*"
(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*"
(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)
(corfu-popupinfo--show (nth corfu--index corfu--candidates))))
(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 ((candidate (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 (equal candidate corfu-popupinfo--candidate)
(corfu-popupinfo--visible-p)))
(corfu-popupinfo--show candidate)
(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 candidate)))
(unless (equal candidate corfu-popupinfo--candidate)
(corfu-popupinfo--hide))))
(corfu-popupinfo--hide))))
(cl-defmethod corfu--teardown :before (&context (corfu-popupinfo-mode (eql t)))
(corfu-popupinfo--hide)
(mapc #'kill-local-variable corfu-popupinfo--state-vars)
(setq minor-mode-overriding-map-alist
(assq-delete-all #'corfu-popupinfo-mode
minor-mode-overriding-map-alist)))
;; Emacs 28: 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-0.36/extensions/corfu-quick.el 0000664 0000000 0000000 00000013271 14410372114 0017532 0 ustar 00root root 0000000 0000000 ;;; corfu-quick.el --- Quick keys for Corfu -*- lexical-binding: t -*-
;; Copyright (C) 2022-2023 Free Software Foundation, Inc.
;; Author: Luis Henriquez-Perez , Daniel Mendler
;; Maintainer: Daniel Mendler
;; Created: 2022
;; Version: 0.1
;; Package-Requires: ((emacs "27.1") (corfu "0.36"))
;; Homepage: 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 "jkl"
"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))
(len (+ fst snd)))
(if (>= idx fst)
(let ((first (elt corfu-quick2 (mod (/ (- idx fst) len) snd)))
(second (elt (concat corfu-quick1 corfu-quick2) (mod (- idx fst) len))))
(cond
((eq first two)
(list
(concat " " (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
(concat (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)
(space1 (propertize " " 'display
`(space :width
(+ 0.5 (,(alist-get
'child-frame-border-width
corfu--frame-parameters))))))
(space2 #(" " 0 1 (display (space :width 0.5))))
(orig (symbol-function #'corfu--affixate))
((symbol-function #'corfu--affixate)
(lambda (cands)
(setq cands (cdr (funcall orig cands)))
(cl-loop for cand in cands for index from 0 do
(pcase-let ((`(,keys . ,events) (corfu-quick--keys first index)))
(setq list (nconc events list))
(setf (cadr cand) (concat space1 (propertize " " 'display keys) space2))))
(cons t cands)))
;; Increase minimum width to avoid odd jumping
(corfu-min-width (+ 3 corfu-min-width)))
(corfu--candidates-popup (car completion-in-region--data))
(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)))
;; Emacs 28: Do not show Corfu commands in M-X
(dolist (sym '(corfu-quick-jump corfu-quick-insert corfu-quick-complete))
(put sym 'completion-predicate #'ignore))
(provide 'corfu-quick)
;;; corfu-quick.el ends here