feat: add plugins for zsh

This commit is contained in:
doryan 2024-09-22 20:14:22 +04:00
parent f4c1c54e72
commit 6c85cc3b71
515 changed files with 30838 additions and 0 deletions

View File

@ -0,0 +1,77 @@
version: 2
test: &test
steps:
- checkout
- run:
name: Install Dependencies
command: apt-get update && apt-get install -y curl git ncurses-bin libnotify-bin
- run:
name: Download requirements
command: |
mkdir -p ~/bin
curl -L https://raw.githubusercontent.com/molovo/revolver/master/revolver > ~/bin/revolver
curl -L https://github.com/molovo/zunit/releases/download/v0.8.2/zunit > ~/bin/zunit
chmod u+x ~/bin/{revolver,zunit}
- run:
name: Run Zunit
command: |
export TERM="xterm-256color"
export PATH="$HOME/bin:$PATH"
zunit --verbose
jobs:
lint:
docker:
- image: "python:3.11"
steps:
- checkout
- run:
name: run restructuredtext linter
command: |
pip install restructuredtext_lint
rst-lint *.rst
test-zsh-5.1:
docker:
- image: "zshusers/zsh:5.1.1"
<<: *test
test-zsh-5.2:
docker:
- image: "zshusers/zsh:5.2"
<<: *test
test-zsh-5.3:
docker:
- image: "zshusers/zsh:5.3.1"
<<: *test
test-zsh-5.4:
docker:
- image: "zshusers/zsh:5.4.2"
<<: *test
test-zsh-5.5:
docker:
- image: "zshusers/zsh:5.5.1"
<<: *test
test-zsh-5.6:
docker:
- image: "zshusers/zsh:5.6.2"
<<: *test
workflows:
version: 2
test:
jobs:
- lint
- test-zsh-5.1
- test-zsh-5.2
- test-zsh-5.3
- test-zsh-5.4
- test-zsh-5.5
- test-zsh-5.6

View File

@ -0,0 +1,49 @@
Changelog for zsh-auto-notify
=============================
0.10.2
------
* Use preferable array argument expansion for flexible parameters
0.10.1
------
* Fix regression where not setting icon on Linux would cause issues (#59 #58)
0.10.0
-----
* Allow specifying an icon with notify-send backends
0.8.0
-----
* Change notify-send application title to `zsh`
0.7.0
-----
* Allow alternate `AUTO_NOTIFY_WHITELIST` for specifying commands to allow
0.6.0
-----
* Display warning and disable auto-notify if notify-send is not installed (Linux only)
0.5.1
-----
* Improved handling of MacOS notifications via #16 (Thanks @dmitmel!)
0.5.0
-----
* Support changing notification title and body using AUTO_NOTIFY_TITLE and AUTO_NOTIFY_BODY
0.4.0
-----
* Add `AUTO_NOTIFY_EXPIRE_TIME` configuration option
* Improvements to notification formatting
* Exit code is now displayed in notifications
* Notifications on linux now show as critical if long command exits with non-zero exit code
0.3.0
-----
* Add support for environments where standard history is disabled. Fixed in #10
0.2.0
-----
* Initial stable release

View File

@ -0,0 +1,20 @@
# Issue Details
Please provide the following details when opening an issue:
## Operating System (uname -a)
## zsh version (zsh --version)
## auto-notify version (echo "$AUTO_NOTIFY_VERSION")
## How is auto-notify installed?
- [ ] zplug
- [ ] oh-my-zsh
- [ ] Antigen
- [ ] Other (please specify)
## Steps to reproduce the issue
## gist link to your zshrc

View File

@ -0,0 +1,241 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -0,0 +1,235 @@
ZSH Auto-Notify
===============
|CircleCI| |Version| |GPLv3|
Simple zsh plugin that automatically sends out a notification when a long running task
has completed.
Useful for those commands you don't predict will take long to run or just plain forgot
to keep track of. Leave the task running and go do something else - ``auto-notify`` will
let you know when the task is done! :tada:
* Usage_
* Requirements_
* Installation_
* Configuration_
* `Temporarily Disabling Notifications`_
* Contributing_
* `Running Tests`_
Usage
-----
You don't need to do anything. Once it's installed,
``zsh-auto-notify`` will let you know if a long running task has completed its work via a
notification in your desktop environment.
.. image:: img/notification-example.png
Requirements
------------
``auto-notify`` officially supports zsh versions 5.1 onwards.
It is possible the plugin might work on even older versions.
However they would not have been tested as part of the CI test process.
Supported desktop environments:
* Linux X/Wayland (Requires ``notify-send`` to be installed)
* MacOSX
Installation
------------
Add one of the following to your ``.zshrc`` file depending on your
package manager:
ZPlug_
::
zplug "MichaelAquilina/zsh-auto-notify"
Antigen_
::
antigen bundle "MichaelAquilina/zsh-auto-notify"
Zgen_
::
zgen load "MichaelAquilina/zsh-auto-notify"
Fig_
Install ``zsh-auto-notify`` with Fig in just one click.
.. image:: https://fig.io/badges/install-with-fig.svg
:target: https://fig.io/plugins/other/zsh-auto-notify_MichaelAquilina
:alt: Install with Fig
oh-my-zsh_
Copy this repository to ``$ZSH_CUSTOM/custom/plugins``, where ``$ZSH_CUSTOM``
is the directory with custom plugins of oh-my-zsh `(read more) <https://github.com/robbyrussell/oh-my-zsh/wiki/Customization/>`_:
::
git clone https://github.com/MichaelAquilina/zsh-auto-notify.git $ZSH_CUSTOM/plugins/auto-notify
Then add this line to your ``.zshrc``. Make sure it is **before** the line ``source $ZSH/oh-my-zsh.sh``.
::
plugins=(auto-notify $plugins)
Configuration
-------------
**Notification Threshold**
By default, ``auto-notify`` will send notifications for tasks that take longer than 10 seconds. You
can configure this value by setting the environment variable ``AUTO_NOTIFY_THRESHOLD``:
::
# Set threshold to 20seconds
export AUTO_NOTIFY_THRESHOLD=20
**Notification Formatting**
You can change the formatting of notifications by setting the values for ``AUTO_NOTIFY_TITLE`` and
``AUTO_NOTIFY_BODY``. When writing these values, the following variables will be replaced according to
the data that ``auto-notify`` has detected:
* ``%command`` - the command that the user executed
* ``%elapsed`` - number of seconds that elapsed
* ``%exit_code`` - the exit code of the command that was executed
An example of how these values can be set is shown below:
::
export AUTO_NOTIFY_TITLE="Hey! %command has just finished"
export AUTO_NOTIFY_BODY="It completed in %elapsed seconds with exit code %exit_code"
**Notification Expiration Time**
You can set how long a notification sent by ``auto-notify`` will remain showing by setting the environment
variable ``AUTO_NOTIFY_EXPIRE_TIME`` to a custom value in milliseconds. The default value is set to 8 seconds.
NOTE: This configuration option currently only works for Linux.
::
# Set notification expiry to 10 seconds
export AUTO_NOTIFY_EXPIRE_TIME=10000
**Ignored Commands**
A number of commands do not get notifications for long running times due to their nature (e.g. ``watch`` or ``man``).
The list of ignored commands is specified in the ``AUTO_NOTIFY_IGNORE`` environment variable. This can be modified
or completely overwritten based on your use case.
::
# Add docker to list of ignored commands
AUTO_NOTIFY_IGNORE+=("docker")
Make sure that you append to the array above *after* your plugin manager has been loaded in your ``zshrc``.
If you wish to completely redefine what is ignored and not ignored, then just set ``AUTO_NOTIFY_IGNORE`` to
a new array.
::
# redefine what is ignored by auto-notify
export AUTO_NOTIFY_IGNORE=("docker" "man" "sleep")
**Using a Whitelist to ignore commands**
If you wish to use a whitelist approach instead of the default blacklist approach used by ``AUTO_NOTIFY_IGNORE``,
you can do so by defining the environment variable ``AUTO_NOTIFY_WHITELIST`` with the elements you wish to
allow ``auto-notify`` to track and send notifications for. NOTE: If ``AUTO_NOTIFY_WHITELIST`` is defined,
then all the values in ``AUTO_NOTIFY_IGNORE`` are not used.
::
export AUTO_NOTIFY_WHITELIST=("apt-get" "docker")
**Adding an icon - Linux**
If you wish to have an icon displayed on command success and/or failure, you can do so by defining the environmental variables ``AUTO_NOTIFY_ICON_SUCCESS`` and ``AUTO_NOTIFY_ICON_FAILURE`` respectively.
::
export AUTO_NOTIFY_ICON_SUCCESS=/path/to/success/icon.png
export AUTO_NOTIFY_ICON_FAILURE=/path/to/failure/icon.png
Temporarily Disabling Notifications
-----------------------------------
You can temporarily disable auto notify by running the command ``disable_auto_notify``.
When you want to re-enable notifications, run the command ``enable_auto_notify``.
Contributing
------------
Pull requests and Feedback are welcome! :tada:
I have tried to cater for as many use cases that I can think of.
However, they are naturally tailored to to my own workflow and I could
be missing many others.
Because of this if there is a specific use case that does not work as
you would expect or if you have any suggestions to how the plugin should
behave, feel free to `open an
issue <https://github.com/MichaelAquilina/zsh-auto-notify/issues/new>`__
Running Tests
-------------
Install `zunit <https://zunit.xyz/>`__. Run ``zunit`` in the root
directory of the repo.
::
$ zunit
Launching ZUnit
ZUnit: 0.8.2
ZSH: zsh 5.3.1 (x86_64-suse-linux-gnu)
✔ version exported
✔ hook functions are loaded by default
✔ enable/disable auto-notify
✔ auto-notify-send does not send notification for short task
✔ auto-notify-send does not send notification for ignored commands
NOTE: It is required that you use a minimum zunit version of 0.8.2
.. _Zplug: https://github.com/zplug/zplug
.. _Antigen: https://github.com/zsh-users/antigen
.. _ZGen: https://github.com/tarjoilija/zgen
.. _Fig: https://fig.io
.. _oh-my-zsh: https://github.com/robbyrussell/oh-my-zsh
.. |GPLv3| image:: https://img.shields.io/badge/License-GPL%20v3-blue.svg
:target: https://www.gnu.org/licenses/gpl-3.0
.. |CircleCI| image:: https://circleci.com/gh/MichaelAquilina/zsh-auto-notify.svg?style=svg
:target: https://circleci.com/gh/MichaelAquilina/zsh-auto-notify
.. |Version| image:: https://badge.fury.io/gh/MichaelAquilina%2Fzsh-auto-notify.svg
:target: https://badge.fury.io/gh/MichaelAquilina%2Fzsh-auto-notify

View File

@ -0,0 +1,188 @@
export AUTO_NOTIFY_VERSION="0.10.2"
# Time it takes for a notification to expire
[[ -z "$AUTO_NOTIFY_EXPIRE_TIME" ]] &&
export AUTO_NOTIFY_EXPIRE_TIME=8000
# Threshold in seconds for when to automatically show a notification
[[ -z "$AUTO_NOTIFY_THRESHOLD" ]] &&
export AUTO_NOTIFY_THRESHOLD=10
# List of commands/programs to ignore sending notifications for
[[ -z "$AUTO_NOTIFY_IGNORE" ]] &&
export AUTO_NOTIFY_IGNORE=(
'vim'
'nvim'
'less'
'more'
'man'
'tig'
'watch'
'git commit'
'top'
'htop'
'ssh'
'nano'
)
function _auto_notify_format() {
local MESSAGE="$1"
local command="$2"
local elapsed="$3"
local exit_code="$4"
MESSAGE="${MESSAGE//\%command/$command}"
MESSAGE="${MESSAGE//\%elapsed/$elapsed}"
MESSAGE="${MESSAGE//\%exit_code/$exit_code}"
printf "%s" "$MESSAGE"
}
function _auto_notify_message() {
local command="$1"
local elapsed="$2"
local exit_code="$3"
local platform="$(uname)"
# Run using echo -e in order to make sure notify-send picks up new line
local DEFAULT_TITLE="\"%command\" Completed"
local DEFAULT_BODY="$(echo -e "Total time: %elapsed seconds\nExit code: %exit_code")"
local title="${AUTO_NOTIFY_TITLE:-$DEFAULT_TITLE}"
local text="${AUTO_NOTIFY_BODY:-$DEFAULT_BODY}"
title="$(_auto_notify_format "$title" "$command" "$elapsed" "$exit_code")"
body="$(_auto_notify_format "$text" "$command" "$elapsed" "$exit_code")"
if [[ "$platform" == "Linux" ]]; then
local urgency="normal"
local transient="--hint=int:transient:1"
local icon=${AUTO_NOTIFY_ICON_SUCCESS:-""}
# Exit code 130 is returned when a process is terminated with SIGINT.
# Since the user is already interacting with the program, there is no
# need to make the notification persistent.
if [[ "$exit_code" != "0" ]] && [[ "$exit_code" != "130" ]]; then
urgency="critical"
transient=""
icon=${AUTO_NOTIFY_ICON_FAILURE:-""}
fi
local arguments=("$title" "$body" "--app-name=zsh" "$transient" "--urgency=$urgency" "--expire-time=$AUTO_NOTIFY_EXPIRE_TIME")
if [[ -n "$icon" ]]; then
arguments+=("--icon=$icon")
fi
notify-send ${arguments[@]}
elif [[ "$platform" == "Darwin" ]]; then
osascript \
-e 'on run argv' \
-e 'display notification (item 1 of argv) with title (item 2 of argv)' \
-e 'end run' \
"$body" "$title"
else
printf "Unknown platform for sending notifications: $platform\n"
printf "Please post an issue on gitub.com/MichaelAquilina/zsh-auto-notify/issues/\n"
fi
}
function _is_auto_notify_ignored() {
local command="$1"
# split the command if its been piped one or more times
local command_list=("${(@s/|/)command}")
local target_command="${command_list[-1]}"
# Remove leading whitespace
target_command="$(echo "$target_command" | sed -e 's/^ *//')"
# If the command is being run over SSH, then ignore it
if [[ -n ${SSH_CLIENT-} || -n ${SSH_TTY-} || -n ${SSH_CONNECTION-} ]]; then
print "yes"
return
fi
# Remove sudo prefix from command if detected
if [[ "$target_command" == "sudo "* ]]; then
target_command="${target_command/sudo /}"
fi
# If AUTO_NOTIFY_WHITELIST is defined, then auto-notify will ignore
# any item not defined in the white list
# Otherwise - the alternative (default) approach is used where the
# AUTO_NOTIFY_IGNORE blacklist is used to ignore commands
if [[ -n "$AUTO_NOTIFY_WHITELIST" ]]; then
for allowed in $AUTO_NOTIFY_WHITELIST; do
if [[ "$target_command" == "$allowed"* ]]; then
print "no"
return
fi
done
print "yes"
else
for ignore in $AUTO_NOTIFY_IGNORE; do
if [[ "$target_command" == "$ignore"* ]]; then
print "yes"
return
fi
done
print "no"
fi
}
function _auto_notify_send() {
# Immediately store the exit code before it goes away
local exit_code="$?"
if [[ -z "$AUTO_COMMAND" && -z "$AUTO_COMMAND_START" ]]; then
return
fi
if [[ "$(_is_auto_notify_ignored "$AUTO_COMMAND_FULL")" == "no" ]]; then
local current="$(date +"%s")"
let "elapsed = current - AUTO_COMMAND_START"
if [[ $elapsed -gt $AUTO_NOTIFY_THRESHOLD ]]; then
_auto_notify_message "$AUTO_COMMAND" "$elapsed" "$exit_code"
fi
fi
# Empty tracking so that notifications are not
# triggered for any commands not run (e.g ctrl+C when typing)
_auto_notify_reset_tracking
}
function _auto_notify_track() {
# $1 is the string the user typed, but only when history is enabled
# $2 is a single-line, size-limited version of the command that is always available
# To still do something useful when history is disabled, although with reduced functionality, fall back to $2 when $1 is empty
AUTO_COMMAND="${1:-$2}"
AUTO_COMMAND_FULL="$3"
AUTO_COMMAND_START="$(date +"%s")"
}
function _auto_notify_reset_tracking() {
# Command start time in seconds since epoch
unset AUTO_COMMAND_START
# Full command that the user has executed after alias expansion
unset AUTO_COMMAND_FULL
# Command that the user has executed
unset AUTO_COMMAND
}
function disable_auto_notify() {
add-zsh-hook -D preexec _auto_notify_track
add-zsh-hook -D precmd _auto_notify_send
}
function enable_auto_notify() {
autoload -Uz add-zsh-hook
add-zsh-hook preexec _auto_notify_track
add-zsh-hook precmd _auto_notify_send
}
_auto_notify_reset_tracking
platform="$(uname)"
if [[ "$platform" == "Linux" ]] && ! type notify-send > /dev/null; then
printf "'notify-send' must be installed for zsh-auto-notify to work\n"
printf "Please install it with your relevant package manager\n"
else
enable_auto_notify
fi

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,26 @@
#!/usr/bin/env zunit
@setup {
load "../auto-notify.plugin.zsh"
}
@test 'auto-notify-format no parameters' {
run _auto_notify_format "Hello World" "foo" "bar" "baz"
assert $state equals 0
assert "$output" same_as "Hello World"
}
@test 'auto-notify-format correct formatting 1' {
run _auto_notify_format "Command run is - %command (%elapsed seconds)" "zypper up" "10" "0"
assert $state equals 0
assert "$output" same_as "Command run is - zypper up (10 seconds)"
}
@test 'auto-notify-format correct formatting 2' {
run _auto_notify_format "Exit code is %exit_code!" "zypper up" "10" "-101"
assert $state equals 0
assert "$output" same_as "Exit code is -101!"
}

View File

@ -0,0 +1,157 @@
#!/usr/bin/env zunit
@setup {
load "../auto-notify.plugin.zsh"
function notify-send {
echo - "Notification Title: $1"
echo - "Notification Body: $2"
echo - "${@:3}"
}
function uname {
echo - "Linux"
}
# Mock date function to return a frozen timestamp
function date {
if [[ "$1" == +"%s" ]]; then
echo - "11100"
else
date - "$@"
fi
}
}
@test 'auto-notify-send does not send notification if tracking not set' {
unset AUTO_COMMAND
unset AUTO_COMMAND_FULL
unset AUTO_COMMAND_START
run _auto_notify_send
assert $state equals 0
assert "$output" is_empty
}
@test 'auto-notify-send does not send notification for short task' {
AUTO_COMMAND="foo bar -r"
AUTO_COMMAND_FULL="foo bar -r"
AUTO_COMMAND_START=11099
run _auto_notify_send
assert $state equals 0
assert "$output" is_empty
}
@test 'auto-notify-send does not send notification for ignored commands' {
for command in $AUTO_NOTIFY_IGNORE; do
AUTO_COMMAND="somealias"
AUTO_COMMAND_FULL="$command"
AUTO_COMMAND_START=11000
run _auto_notify_send
assert $state equals 0
assert "$output" is_empty
done
}
@test 'auto-notify-send does not send notification for ignored piped commands' {
AUTO_COMMAND="echo hello world | less -r"
AUTO_COMMAND_FULL="echo hello world | less -r"
AUTO_COMMAND_START=11000
run _auto_notify_send
assert $state equals 0
assert "$output" is_empty
}
@test 'auto-notify-send does not send notification for ignored commands with arguments' {
for command in $AUTO_NOTIFY_IGNORE; do
AUTO_COMMAND="somealias bar -r"
AUTO_COMMAND_FULL="$command bar -r"
AUTO_COMMAND_START=11000
run _auto_notify_send
assert $state equals 0
assert "$output" is_empty
done
}
@test 'auto-notify-send sends notification on Linux' {
AUTO_COMMAND="f bar -r"
AUTO_COMMAND_FULL="foo bar -r"
AUTO_COMMAND_START=11080
AUTO_NOTIFY_EXPIRE_TIME=15000
run _auto_notify_send
assert $state equals 0
assert "$lines[1]" same_as 'Notification Title: "f bar -r" Completed'
assert "$lines[2]" same_as "Notification Body: Total time: 20 seconds"
assert "$lines[3]" same_as "Exit code: 0"
assert "$lines[4]" same_as "--app-name=zsh --hint=int:transient:1 --urgency=normal --expire-time=15000"
}
@test 'auto-notify-send sends notification and icon on Linux on success' {
AUTO_COMMAND="f bar -r"
AUTO_COMMAND_FULL="foo bar -r"
AUTO_COMMAND_START=11080
AUTO_NOTIFY_EXPIRE_TIME=15000
AUTO_NOTIFY_ICON_SUCCESS=/path/to/success/icon.png
run _auto_notify_send
assert $state equals 0
assert "$lines[1]" same_as 'Notification Title: "f bar -r" Completed'
assert "$lines[2]" same_as "Notification Body: Total time: 20 seconds"
assert "$lines[3]" same_as "Exit code: 0"
assert "$lines[4]" same_as "--app-name=zsh --hint=int:transient:1 --urgency=normal --expire-time=15000 --icon=/path/to/success/icon.png"
}
@test 'auto-notify-send sends notification on macOS' {
AUTO_COMMAND="f bar -r"
AUTO_COMMAND_FULL="foo bar -r"
AUTO_COMMAND_START=11080
function uname {
echo - "Darwin"
}
function osascript {
echo - "${@}"
}
run _auto_notify_send
assert $state equals 0
assert "$lines[1]" same_as '-e on run argv -e display notification (item 1 of argv) with title (item 2 of argv) -e end run Total time: 20 seconds'
assert "$lines[2]" same_as 'Exit code: 0 "f bar -r" Completed'
}
@test 'auto-notify-send sends warning on unsupported platform' {
AUTO_COMMAND="f bar -r"
AUTO_COMMAND_FULL="foo bar -r"
AUTO_COMMAND_START=11080
function uname {
echo - "Hal9000"
}
run _auto_notify_send
assert $state equals 0
assert "$lines[1]" same_as "Unknown platform for sending notifications: Hal9000"
assert "$lines[2]" same_as "Please post an issue on gitub.com/MichaelAquilina/zsh-auto-notify/issues/"
}
@test 'auto-notify-send sends custom message' {
AUTO_COMMAND="doom -i"
AUTO_COMMAND_FULL="doom -i"
AUTO_COMMAND_START=11055
AUTO_NOTIFY_TITLE="%command has completed in %elapseds yo"
AUTO_NOTIFY_BODY="%command exited with code %exit_code"
run _auto_notify_send
assert $state equals 0
assert "$lines[1]" same_as 'Notification Title: doom -i has completed in 45s yo'
assert "$lines[2]" same_as "Notification Body: doom -i exited with code 0"
}

View File

@ -0,0 +1,62 @@
#!/usr/bin/env zunit
@setup {
load "../auto-notify.plugin.zsh"
}
@test 'is_auto_notify_ignored - commands outside AUTO_NOTIFY_IGNORE' {
run _is_auto_notify_ignored "echo hello world"
assert $state equals 0
assert "$output" same_as "no"
}
@test 'is_auto_notify_ignored - all commands in AUTO_NOTIFY_IGNORE' {
for command in $AUTO_NOTIFY_IGNORE; do
run _is_auto_notify_ignored $command
assert $state equals 0
assert "$output" same_as "yes"
done
}
@test 'is_auto_notify_ignored - piped commands which are not ignored' {
run _is_auto_notify_ignored "echo hello world | base64 -e"
assert $state equals 0
assert "$output" same_as "no"
}
@test 'is_auto_notify_ignored - piped commands which are ignored' {
run _is_auto_notify_ignored "echo hello world | hexdump | less -R"
assert $state equals 0
assert "$output" same_as "yes"
}
@test 'is_auto_notify_ignored - AUTO_NOTIFY_WHITELIST disallowed' {
AUTO_NOTIFY_WHITELIST="foobar"
run _is_auto_notify_ignored "boom baz"
assert $state equals 0
assert "$output" same_as "yes"
}
@test 'is_auto_notify_ignored - AUTO_NOTIFY_WHITELIST allowed' {
AUTO_NOTIFY_WHITELIST="foobar"
run _is_auto_notify_ignored "foobar baz"
assert $state equals 0
assert "$output" same_as "no"
}
@test 'is_auto_notify_ignored - AUTO_NOTIFY_WHITELIST allowed with sudo' {
AUTO_NOTIFY_WHITELIST="foobar"
run _is_auto_notify_ignored "sudo foobar baz"
assert $state equals 0
assert "$output" same_as "no"
}

View File

@ -0,0 +1,52 @@
#!/usr/bin/env zunit
@setup {
function uname {
printf "Linux"
}
# Mock function for passing builds where we don't
# really need notify-send to be installed (e.g. Mac OSX)
function notify-send {
}
}
@test 'print warning if notify-send is not installed' {
function type {
return 1
}
run load "../auto-notify.plugin.zsh"
assert "$lines[1]" same_as "'notify-send' must be installed for zsh-auto-notify to work"
assert "$lines[2]" same_as "Please install it with your relevant package manager"
@test 'dont load auto-notify if notify-send is not installed' {
function type {
return 1
}
load "../auto-notify.plugin.zsh"
assert "_auto_notify_track" not_in $preexec_functions
assert "_auto_notify_send" not_in $precmd_functions
}
@test 'hook functions are loaded by default' {
load "../auto-notify.plugin.zsh"
assert '_auto_notify_track' in $preexec_functions
assert '_auto_notify_send' in $precmd_functions
}
@test 'enable/disable auto-notify' {
load "../auto-notify.plugin.zsh"
disable_auto_notify
assert '_auto_notify_track' not_in $preexec_functions
assert '_auto_notify_send' not_in $precmd_functions
enable_auto_notify
assert '_auto_notify_track' in $preexec_functions
assert '_auto_notify_send' in $precmd_functions
}

View File

@ -0,0 +1,15 @@
version: 2
jobs:
build:
parallelism: 4
shell: /bin/bash --login
docker:
- image: ericfreese/zsh-autosuggestions-test:latest
steps:
- checkout
- run:
name: Running tests
command: |
for v in $(grep "^[^#]" ZSH_VERSIONS | awk "(NR + $CIRCLE_NODE_INDEX) % $CIRCLE_NODE_TOTAL == 0"); do
TEST_ZSH_BIN=zsh-$v make test || exit 1
done

View File

@ -0,0 +1,18 @@
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = tab
indent_size = 4
[*.md]
indent_style = space
[*.rb]
indent_style = space
indent_size = 2
[*.yml]
indent_style = space
indent_size = 2

View File

@ -0,0 +1,36 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
### Describe the bug
<!-- A clear and concise description of what the bug is. -->
### To Reproduce
Steps to reproduce the behavior:
<!-- If you are not able to reproduce it by running `zsh -df` and sourcing the plugin manually, it means there that the issue is caused by something in your local config file(s). Temporarily comment out or remove sections of your config and restart `zsh` until you narrow down exactly what is causing the issue. -->
```sh
% zsh -df
% source path/to/zsh-autosuggestions.zsh
% ... # what do you do to reproduce?
```
### Expected behavior
<!-- A clear and concise description of what you expected to happen. -->
### Screenshots
<!-- If applicable, add screenshots to help explain your problem. -->
### Desktop
- OS + distribution: <!-- e.g. Arch Linux 2019.07.01 -->
- Zsh version: <!-- `echo $ZSH_VERSION` -->
- Plugin version: <!-- or git commit hash if installed via git -->
### Additional context
<!-- Add any other context about the problem here. -->

View File

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
### Is your feature request related to a problem? Please describe.
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
### Describe the solution you'd like
<!-- A clear and concise description of what you want to happen. -->
### Describe alternatives you've considered
<!-- A clear and concise description of any alternative solutions or features you've considered. -->
### Additional context
<!-- Add any other context or screenshots about the feature request here. -->

2
.zsh/zsh-autosuggestions/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
# zsh word code files
*.zwc

View File

@ -0,0 +1,3 @@
--color
--require spec_helper
--format documentation

View File

@ -0,0 +1,30 @@
# Rails:
# Enabled: true
AllCops:
TargetRubyVersion: 2.3
Include:
- '**/Rakefile'
- '**/config.ru'
- '**/Gemfile'
Metrics/LineLength:
Max: 120
Style/Documentation:
Enabled: false
Style/DotPosition:
EnforcedStyle: trailing
Style/FrozenStringLiteralComment:
Enabled: false
Style/Lambda:
Enabled: false
Style/MultilineMethodCallIndentation:
EnforcedStyle: indented
Style/TrailingUnderscoreVariable:
Enabled: false

View File

@ -0,0 +1 @@
2.5.3

View File

@ -0,0 +1,117 @@
# Changelog
## v0.7.0
- Enable asynchronous mode by default (#498)
- No longer wrap user widgets starting with `autosuggest-` prefix (#496)
- Fix a bug wrapping widgets that modify the buffer (#541)
## v0.6.4
- Fix `vi-forward-char` triggering a bell when using it to accept a suggestion (#488)
- New configuration option to skip completion suggestions when buffer matches a pattern (#487)
- New configuration option to ignore history entries matching a pattern (#456)
## v0.6.3
- Fixed bug moving cursor to end of buffer after accepting suggestion (#453)
## v0.6.2
- Fixed bug deleting the last character in the buffer in vi mode (#450)
- Degrade gracefully when user doesn't have `zsh/system` module installed (#447)
## v0.6.1
- Fixed bug occurring when `_complete` had been aliased (#443)
## v0.6.0
- Added `completion` suggestion strategy powered by completion system (#111)
- Allow setting `ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE` to an empty string (#422)
- Don't fetch suggestions after copy-earlier-word (#439)
- Allow users to unignore zle-\* widgets (e.g. zle-line-init) (#432)
## v0.5.2
- Allow disabling automatic widget re-binding for better performance (#418)
- Fix async suggestions when `SH_WORD_SPLIT` is set
- Refactor async mode to use process substitution instead of zpty (#417)
## v0.5.1
- Speed up widget rebinding (#413)
- Clean up global variable creations (#403)
- Respect user's set options when running original widget (#402)
## v0.5.0
- Don't overwrite config with default values (#335)
- Support fallback strategies by supplying array to suggestion config var
- Rename "default" suggestion strategy to "history" to name it based on what it actually does
- Reset opts in some functions affected by `GLOB_SUBST` (#334)
- Support widgets starting with dashes (ex: `-a-widget`) (#337)
- Skip async tests in zsh versions less than 5.0.8 because of reliability issues
- Fix handling of newline + carriage return in async pty (#333)
## v0.4.3
- Avoid bell when accepting suggestions with `autosuggest-accept` (#228)
- Don't fetch suggestions after [up,down]-line-or-beginning-search (#227, #241)
- We are now running CI against new 5.5.1 version
- Fix partial-accept in vi mode (#188)
- Fix suggestion disappearing on fast movement after switching to `vicmd` mode (#290)
- Fix issue rotating through kill ring with `yank-pop` (#301)
- Fix issue creating new pty for async mode when previous pty is not properly cleaned up (#249)
## v0.4.2
- Fix bug in zsh versions older than 5.0.8 (#296)
- Officially support back to zsh v4.3.11
## v0.4.1
- Switch to [[ and (( conditionals instead of [ (#257)
- Avoid warnnestedvar warnings with `typeset -g` (#275)
- Replace tabs with spaces in yaml (#268)
- Clean up and fix escaping of special characters (#267)
- Add `emacs-forward-word` to default list of partial accept widgets (#246)
## v0.4.0
- High-level integration tests using RSpec and tmux
- Add continuous integration with Circle CI
- Experimental support for asynchronous suggestions (#170)
- Fix problems with multi-line suggestions (#225)
- Optimize case where manually typing in suggestion
- Avoid wrapping any zle-\* widgets (#206)
- Remove support for deprecated options from v0.0.x
- Handle history entries that begin with dashes
- Gracefully handle being sourced multiple times (#126)
- Add enable/disable/toggle widgets to disable/enable suggestions (#219)
## v0.3.3
- Switch from $history array to fc builtin for better performance with large HISTFILEs (#164)
- Fix tilde handling when extended_glob is set (#168)
- Add config option for maximum buffer length to fetch suggestions for (#178)
- Add config option for list of widgets to ignore (#184)
- Don't fetch a new suggestion unless a modification widget actually modifies the buffer (#183)
## v0.3.2
- Test runner now supports running specific tests and choosing zsh binary
- Return code from original widget is now correctly passed through (#135)
- Add `vi-add-eol` to list of accept widgets (#143)
- Escapes widget names within evals to fix problems with irregular widget names (#152)
- Plugin now clears suggestion while within a completion menu (#149)
- .plugin file no longer relies on symbolic link support, fixing issues on Windows (#156)
## v0.3.1
- Fixes issue with `vi-next-char` not accepting suggestion (#137).
- Fixes global variable warning when WARN_CREATE_GLOBAL option enabled (#133).
- Split out a separate test file for each widget.
## v0.3.0
- Adds `autosuggest-execute` widget (PR #124).
- Adds concept of suggestion "strategies" for different ways of fetching suggestions.
- Adds "match_prev_cmd" strategy (PR #131).
- Uses git submodules for testing dependencies.
- Lots of test cleanup.
- Various bug fixes for zsh 5.0.x and `sh_word_split` option.
## v0.2.17
Start of changelog.

View File

@ -0,0 +1 @@
Fish-like fast/unobtrusive autosuggestions for zsh.

View File

@ -0,0 +1,20 @@
FROM ruby:2.5.3-alpine
RUN apk add --no-cache autoconf
RUN apk add --no-cache libtool
RUN apk add --no-cache libcap-dev
RUN apk add --no-cache pcre-dev
RUN apk add --no-cache curl
RUN apk add --no-cache build-base
RUN apk add --no-cache ncurses-dev
RUN apk add --no-cache tmux
WORKDIR /zsh-autosuggestions
ADD ZSH_VERSIONS /zsh-autosuggestions/ZSH_VERSIONS
ADD install_test_zsh.sh /zsh-autosuggestions/install_test_zsh.sh
RUN ./install_test_zsh.sh
ADD Gemfile /zsh-autosuggestions/Gemfile
ADD Gemfile.lock /zsh-autosuggestions/Gemfile.lock
RUN bundle install

View File

@ -0,0 +1,5 @@
source 'https://rubygems.org'
gem 'rspec'
gem 'rspec-wait'
gem 'pry-byebug'

View File

@ -0,0 +1,41 @@
GEM
remote: https://rubygems.org/
specs:
byebug (9.0.5)
coderay (1.1.1)
diff-lcs (1.3)
method_source (0.8.2)
pry (0.10.4)
coderay (~> 1.1.0)
method_source (~> 0.8.1)
slop (~> 3.4)
pry-byebug (3.4.0)
byebug (~> 9.0)
pry (~> 0.10)
rspec (3.5.0)
rspec-core (~> 3.5.0)
rspec-expectations (~> 3.5.0)
rspec-mocks (~> 3.5.0)
rspec-core (3.5.4)
rspec-support (~> 3.5.0)
rspec-expectations (3.5.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.5.0)
rspec-mocks (3.5.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.5.0)
rspec-support (3.5.0)
rspec-wait (0.0.9)
rspec (>= 3, < 4)
slop (3.6.0)
PLATFORMS
ruby
DEPENDENCIES
pry-byebug
rspec
rspec-wait
BUNDLED WITH
1.13.6

View File

@ -0,0 +1,81 @@
# Installation
* [Packages](#packages)
* [Antigen](#antigen)
* [Oh My Zsh](#oh-my-zsh)
* [HomeBrew](#homebrew)
* [Manual](#manual-git-clone)
## Packages
| System | Package |
| ------------- | ------------- |
| Alpine Linux | [zsh-autosuggestions](https://pkgs.alpinelinux.org/packages?name=zsh-autosuggestions) |
| Debian / Ubuntu | [zsh-autosuggestions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-autosuggestions&package=zsh-autosuggestions) |
| Fedora / CentOS / RHEL / Scientific Linux | [zsh-autosuggestions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-autosuggestions&package=zsh-autosuggestions) |
| OpenSUSE / SLE | [zsh-autosuggestions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-autosuggestions&package=zsh-autosuggestions) |
| Arch Linux / Manjaro / Antergos / Hyperbola | [zsh-autosuggestions](https://www.archlinux.org/packages/zsh-autosuggestions), [zsh-autosuggestions-git](https://aur.archlinux.org/packages/zsh-autosuggestions-git) |
| NixOS | [zsh-autosuggestions](https://github.com/NixOS/nixpkgs/blob/master/pkgs/shells/zsh/zsh-autosuggestions/default.nix) |
| Void Linux | [zsh-autosuggestions](https://github.com/void-linux/void-packages/blob/master/srcpkgs/zsh-autosuggestions/template) |
| Mac OS | [homebrew](https://github.com/Homebrew/homebrew-core/blob/master/Formula/z/zsh-autosuggestions.rb) |
| NetBSD | [pkgsrc](http://ftp.netbsd.org/pub/pkgsrc/current/pkgsrc/shells/zsh-autosuggestions/README.html) |
## Antigen
1. Add the following to your `.zshrc`:
```sh
antigen bundle zsh-users/zsh-autosuggestions
```
2. Start a new terminal session.
## Oh My Zsh
1. Clone this repository into `$ZSH_CUSTOM/plugins` (by default `~/.oh-my-zsh/custom/plugins`)
```sh
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
```
2. Add the plugin to the list of plugins for Oh My Zsh to load (inside `~/.zshrc`):
```sh
plugins=(
# other plugins...
zsh-autosuggestions
)
```
3. Start a new terminal session.
## Homebrew
1. Install command:
```sh
brew install zsh-autosuggestions
```
2. To activate the autosuggestions, add the following at the end of your .zshrc:
```sh
source $(brew --prefix)/share/zsh-autosuggestions/zsh-autosuggestions.zsh
```
3. Start a new terminal session.
## Manual (Git Clone)
1. Clone this repository somewhere on your machine. This guide will assume `~/.zsh/zsh-autosuggestions`.
```sh
git clone https://github.com/zsh-users/zsh-autosuggestions ~/.zsh/zsh-autosuggestions
```
2. Add the following to your `.zshrc`:
```sh
source ~/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh
```
3. Start a new terminal session.

View File

@ -0,0 +1,23 @@
Copyright (c) 2013 Thiago de Arruda
Copyright (c) 2016-2021 Eric Freese
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,35 @@
SRC_DIR := ./src
SRC_FILES := \
$(SRC_DIR)/config.zsh \
$(SRC_DIR)/util.zsh \
$(SRC_DIR)/bind.zsh \
$(SRC_DIR)/highlight.zsh \
$(SRC_DIR)/widgets.zsh \
$(SRC_DIR)/strategies/*.zsh \
$(SRC_DIR)/fetch.zsh \
$(SRC_DIR)/async.zsh \
$(SRC_DIR)/start.zsh
HEADER_FILES := \
DESCRIPTION \
URL \
VERSION \
LICENSE
PLUGIN_TARGET := zsh-autosuggestions.zsh
all: $(PLUGIN_TARGET)
$(PLUGIN_TARGET): $(HEADER_FILES) $(SRC_FILES)
cat $(HEADER_FILES) | sed -e 's/^/# /g' > $@
cat $(SRC_FILES) >> $@
.PHONY: clean
clean:
rm $(PLUGIN_TARGET)
.PHONY: test
test: all
@test -n "$$TEST_ZSH_BIN" && echo "Testing zsh binary: $(TEST_ZSH_BIN)" || true
bundle exec rspec $(TESTS)

View File

@ -0,0 +1,191 @@
# zsh-autosuggestions
_[Fish](http://fishshell.com/)-like fast/unobtrusive autosuggestions for zsh._
It suggests commands as you type based on history and completions.
Requirements: Zsh v4.3.11 or later
[![CircleCI](https://img.shields.io/circleci/build/github/zsh-users/zsh-autosuggestions.svg)](https://circleci.com/gh/zsh-users/zsh-autosuggestions)
[![Chat on Gitter](https://img.shields.io/gitter/room/zsh-users/zsh-autosuggestions.svg)](https://gitter.im/zsh-users/zsh-autosuggestions)
<a href="https://asciinema.org/a/37390" target="_blank"><img src="https://asciinema.org/a/37390.png" width="400" /></a>
## Installation
See [INSTALL.md](INSTALL.md).
## Usage
As you type commands, you will see a completion offered after the cursor in a muted gray color. This color can be changed by setting the `ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE` variable. See [configuration](#configuration).
If you press the <kbd></kbd> key (`forward-char` widget) or <kbd>End</kbd> (`end-of-line` widget) with the cursor at the end of the buffer, it will accept the suggestion, replacing the contents of the command line buffer with the suggestion.
If you invoke the `forward-word` widget, it will partially accept the suggestion up to the point that the cursor moves to.
## Configuration
You may want to override the default global config variables. Default values of these variables can be found [here](src/config.zsh).
**Note:** If you are using Oh My Zsh, you can put this configuration in a file in the `$ZSH_CUSTOM` directory. See their comments on [overriding internals](https://github.com/robbyrussell/oh-my-zsh/wiki/Customization#overriding-internals).
### Suggestion Highlight Style
Set `ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE` to configure the style that the suggestion is shown with. The default is `fg=8`, which will set the foreground color to color 8 from the [256-color palette](https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg). If your terminal only supports 8 colors, you will need to use a number between 0 and 7.
Background color can also be set, and the suggestion can be styled bold, underlined, or standout. For example, this would show suggestions with bold, underlined, pink text on a cyan background:
```sh
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE="fg=#ff00ff,bg=cyan,bold,underline"
```
For more info, read the Character Highlighting section of the zsh manual: `man zshzle` or [online](http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting).
**Note:** Some iTerm2 users have reported [not being able to see the suggestions](https://github.com/zsh-users/zsh-autosuggestions/issues/416#issuecomment-486516333). If this affects you, the problem is likely caused by incorrect color settings. In order to correct this, go into iTerm2's setting, navigate to profile > colors and make sure that the colors for Basic Colors > Background and ANSI Colors > Bright Black are **different**.
### Suggestion Strategy
`ZSH_AUTOSUGGEST_STRATEGY` is an array that specifies how suggestions should be generated. The strategies in the array are tried successively until a suggestion is found. There are currently three built-in strategies to choose from:
- `history`: Chooses the most recent match from history.
- `completion`: Chooses a suggestion based on what tab-completion would suggest. (requires `zpty` module, which is included with zsh since 4.0.1)
- `match_prev_cmd`: Like `history`, but chooses the most recent match whose preceding history item matches the most recently executed command ([more info](src/strategies/match_prev_cmd.zsh)). Note that this strategy won't work as expected with ZSH options that don't preserve the history order such as `HIST_IGNORE_ALL_DUPS` or `HIST_EXPIRE_DUPS_FIRST`.
For example, setting `ZSH_AUTOSUGGEST_STRATEGY=(history completion)` will first try to find a suggestion from your history, but, if it can't find a match, will find a suggestion from the completion engine.
### Widget Mapping
This plugin works by triggering custom behavior when certain [zle widgets](http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Zle-Widgets) are invoked. You can add and remove widgets from these arrays to change the behavior of this plugin:
- `ZSH_AUTOSUGGEST_CLEAR_WIDGETS`: Widgets in this array will clear the suggestion when invoked.
- `ZSH_AUTOSUGGEST_ACCEPT_WIDGETS`: Widgets in this array will accept the suggestion when invoked.
- `ZSH_AUTOSUGGEST_EXECUTE_WIDGETS`: Widgets in this array will execute the suggestion when invoked.
- `ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS`: Widgets in this array will partially accept the suggestion when invoked.
- `ZSH_AUTOSUGGEST_IGNORE_WIDGETS`: Widgets in this array will not trigger any custom behavior.
Widgets that modify the buffer and are not found in any of these arrays will fetch a new suggestion after they are invoked.
**Note:** A widget shouldn't belong to more than one of the above arrays.
### Disabling suggestion for large buffers
Set `ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE` to an integer value to disable autosuggestion for large buffers. The default is unset, which means that autosuggestion will be tried for any buffer size. Recommended value is 20.
This can be useful when pasting large amount of text in the terminal, to avoid triggering autosuggestion for strings that are too long.
### Asynchronous Mode
Suggestions are fetched asynchronously by default in zsh versions 5.0.8 and greater. To disable asynchronous suggestions and fetch them synchronously instead, `unset ZSH_AUTOSUGGEST_USE_ASYNC` after sourcing the plugin.
Alternatively, if you are using a version of zsh older than 5.0.8 and want to enable asynchronous mode, set the `ZSH_AUTOSUGGEST_USE_ASYNC` variable after sourcing the plugin (it can be set to anything). Note that there is [a bug](https://github.com/zsh-users/zsh-autosuggestions/issues/364#issuecomment-481423232) in versions of zsh older than 5.0.8 where <kbd>ctrl</kbd> + <kbd>c</kbd> will fail to reset the prompt immediately after fetching a suggestion asynchronously.
### Disabling automatic widget re-binding
Set `ZSH_AUTOSUGGEST_MANUAL_REBIND` (it can be set to anything) to disable automatic widget re-binding on each precmd. This can be a big boost to performance, but you'll need to handle re-binding yourself if any of the widget lists change or if you or another plugin wrap any of the autosuggest widgets. To re-bind widgets, run `_zsh_autosuggest_bind_widgets`.
### Ignoring history suggestions that match a pattern
Set `ZSH_AUTOSUGGEST_HISTORY_IGNORE` to a [glob pattern](http://zsh.sourceforge.net/Doc/Release/Expansion.html#Glob-Operators) to prevent offering suggestions for history entries that match the pattern. For example, set it to `"cd *"` to never suggest any `cd` commands from history. Or set to `"?(#c50,)"` to never suggest anything 50 characters or longer.
**Note:** This only affects the `history` and `match_prev_cmd` suggestion strategies.
### Skipping completion suggestions for certain cases
Set `ZSH_AUTOSUGGEST_COMPLETION_IGNORE` to a [glob pattern](http://zsh.sourceforge.net/Doc/Release/Expansion.html#Glob-Operators) to prevent offering completion suggestions when the buffer matches that pattern. For example, set it to `"git *"` to disable completion suggestions for git subcommands.
**Note:** This only affects the `completion` suggestion strategy.
### Key Bindings
This plugin provides a few widgets that you can use with `bindkey`:
1. `autosuggest-accept`: Accepts the current suggestion.
2. `autosuggest-execute`: Accepts and executes the current suggestion.
3. `autosuggest-clear`: Clears the current suggestion.
4. `autosuggest-fetch`: Fetches a suggestion (works even when suggestions are disabled).
5. `autosuggest-disable`: Disables suggestions.
6. `autosuggest-enable`: Re-enables suggestions.
7. `autosuggest-toggle`: Toggles between enabled/disabled suggestions.
For example, this would bind <kbd>ctrl</kbd> + <kbd>space</kbd> to accept the current suggestion.
```sh
bindkey '^ ' autosuggest-accept
```
## Troubleshooting
If you have a problem, please search through [the list of issues on GitHub](https://github.com/zsh-users/zsh-autosuggestions/issues?q=) to see if someone else has already reported it.
### Reporting an Issue
Before reporting an issue, please try temporarily disabling sections of your configuration and other plugins that may be conflicting with this plugin to isolate the problem.
When reporting an issue, please include:
- The smallest, simplest `.zshrc` configuration that will reproduce the problem. See [this comment](https://github.com/zsh-users/zsh-autosuggestions/issues/102#issuecomment-180944764) for a good example of what this means.
- The version of zsh you're using (`zsh --version`)
- Which operating system you're running
## Uninstallation
1. Remove the code referencing this plugin from `~/.zshrc`.
2. Remove the git repository from your hard drive
```sh
rm -rf ~/.zsh/zsh-autosuggestions # Or wherever you installed
```
## Development
### Build Process
Edit the source files in `src/`. Run `make` to build `zsh-autosuggestions.zsh` from those source files.
### Pull Requests
Pull requests are welcome! If you send a pull request, please:
- Request to merge into the `develop` branch (*NOT* `master`)
- Match the existing coding conventions.
- Include helpful comments to keep the barrier-to-entry low for people new to the project.
- Write tests that cover your code as much as possible.
### Testing
Tests are written in ruby using the [`rspec`](http://rspec.info/) framework. They use [`tmux`](https://tmux.github.io/) to drive a pseudoterminal, sending simulated keystrokes and making assertions on the terminal content.
Test files live in `spec/`. To run the tests, run `make test`. To run a specific test, run `TESTS=spec/some_spec.rb make test`. You can also specify a `zsh` binary to use by setting the `TEST_ZSH_BIN` environment variable (ex: `TEST_ZSH_BIN=/bin/zsh make test`).
A docker image for testing is available [on docker hub](https://hub.docker.com/r/ericfreese/zsh-autosuggestions-test). It comes with ruby, the bundler dependencies, and all supported versions of zsh installed.
Pull the docker image with:
```sh
docker pull ericfreese/zsh-autosuggestions-test
```
To run the tests for a specific version of zsh (where `<version>` below is substituted with the contents of a line from the [`ZSH_VERSIONS`](ZSH_VERSIONS) file):
```sh
docker run -it -e TEST_ZSH_BIN=zsh-<version> -v $PWD:/zsh-autosuggestions zsh-autosuggestions-test make test
```
## License
This project is licensed under [MIT license](http://opensource.org/licenses/MIT).
For the full text of the license, see the [LICENSE](LICENSE) file.

View File

@ -0,0 +1 @@
https://github.com/zsh-users/zsh-autosuggestions

View File

@ -0,0 +1 @@
v0.7.0

View File

@ -0,0 +1,17 @@
# Zsh releases to run tests against
# See https://github.com/zsh-users/zsh/releases
#
# When modifying this file, rebuild and push docker image:
# $ docker build -t ericfreese/zsh-autosuggestions-test .
# $ docker push ericfreese/zsh-autosuggestions-test
4.3.11
5.0.2
5.0.8
5.1.1
5.2
5.3.1
5.4.2
5.5.1
5.6.2
5.7.1
5.8

View File

@ -0,0 +1,26 @@
#!/bin/sh
set -ex
for v in $(grep "^[^#]" ZSH_VERSIONS); do
mkdir zsh-$v
cd zsh-$v
curl -L https://api.github.com/repos/zsh-users/zsh/tarball/zsh-$v | tar xz --strip=1
./Util/preconfig
./configure --enable-pcre \
--enable-cap \
--enable-multibyte \
--with-term-lib='ncursesw tinfo' \
--with-tcsetpgrp \
--program-suffix="-$v"
make install.bin
make install.modules
make install.fns
cd ..
rm -rf zsh-$v
done

View File

@ -0,0 +1,70 @@
context 'with asynchronous suggestions enabled' do
let(:options) { ["ZSH_AUTOSUGGEST_USE_ASYNC="] }
describe '`up-line-or-beginning-search`' do
let(:before_sourcing) do
-> do
session.
run_command('autoload -U up-line-or-beginning-search').
run_command('zle -N up-line-or-beginning-search').
send_string('bindkey "').
send_keys('C-v').send_keys('up').
send_string('" up-line-or-beginning-search').
send_keys('enter')
end
end
it 'should show previous history entries' do
with_history(
'echo foo',
'echo bar',
'echo baz'
) do
session.clear_screen
3.times { session.send_keys('up') }
wait_for { session.content }.to eq("echo foo")
end
end
end
describe '`copy-earlier-word`' do
let(:before_sourcing) do
-> do
session.
run_command('autoload -Uz copy-earlier-word').
run_command('zle -N copy-earlier-word').
run_command('bindkey "^N" copy-earlier-word')
end
end
it 'should cycle through previous words in the buffer' do
session.clear_screen
session.send_string('foo bar baz')
sleep 0.5
session.send_keys('C-n')
wait_for { session.content }.to eq('foo bar bazbaz')
session.send_keys('C-n')
wait_for { session.content }.to eq('foo bar bazbar')
session.send_keys('C-n')
wait_for { session.content }.to eq('foo bar bazfoo')
end
end
describe 'pressing ^C after fetching a suggestion' do
before do
skip 'Workaround does not work below v5.0.8' if session.zsh_version < Gem::Version.new('5.0.8')
end
it 'terminates the prompt and begins a new one' do
session.send_keys('e')
sleep 0.5
session.send_keys('C-c')
sleep 0.5
session.send_keys('echo')
wait_for { session.content }.to eq("e\necho")
end
end
end

View File

@ -0,0 +1,14 @@
describe 'with `AUTO_CD` option set' do
let(:after_sourcing) do
-> {
session.run_command('setopt AUTO_CD')
session.run_command('autoload compinit && compinit')
}
end
it 'directory names are still completed' do
session.send_string('sr')
session.send_keys('C-i')
wait_for { session.content }.to eq('src/')
end
end

View File

@ -0,0 +1,43 @@
describe 'pasting using bracketed-paste-magic' do
let(:before_sourcing) do
-> do
session.
run_command('autoload -Uz bracketed-paste-magic').
run_command('zle -N bracketed-paste bracketed-paste-magic')
end
end
context 'with suggestions disabled while pasting' do
before do
session.
run_command('bpm_init() { zle autosuggest-disable }').
run_command('bpm_finish() { zle autosuggest-enable }').
run_command('zstyle :bracketed-paste-magic paste-init bpm_init').
run_command('zstyle :bracketed-paste-magic paste-finish bpm_finish')
end
it 'does not show an incorrect suggestion' do
with_history('echo hello') do
session.paste_string("echo #{'a' * 60}")
sleep 1
expect(session.content).to eq("echo #{'a' * 60}")
end
end
end
context 'with `bracketed-paste` added to the list of widgets that clear the suggestion' do
let(:options) { ['ZSH_AUTOSUGGEST_CLEAR_WIDGETS+=(bracketed-paste)'] }
it 'does not retain an old suggestion' do
with_history ('echo foo') do
session.send_string('echo ')
wait_for { session.content }.to eq('echo foo')
session.paste_string('bar')
wait_for { session.content }.to eq('echo bar')
session.send_keys('C-a') # Any cursor movement works
sleep 1
expect(session.content).to eq('echo bar')
end
end
end
end

View File

@ -0,0 +1,14 @@
describe 'a running zpty command' do
let(:before_sourcing) { -> { session.run_command('zmodload zsh/zpty && zpty -b kitty cat') } }
context 'when using `completion` strategy' do
let(:options) { ["ZSH_AUTOSUGGEST_STRATEGY=completion"] }
it 'is not affected' do
session.send_keys('a').send_keys('C-h')
session.run_command('zpty -t kitty; echo $?')
wait_for { session.content }.to end_with("\n0")
end
end
end

View File

@ -0,0 +1,12 @@
describe 'with `GLOB_SUBST` option set' do
let(:after_sourcing) do
-> {
session.run_command('setopt GLOB_SUBST')
}
end
it 'error messages are not printed' do
session.send_string('[[')
wait_for { session.content }.to eq('[[')
end
end

View File

@ -0,0 +1,13 @@
describe 'rebinding [' do
context 'initialized before sourcing the plugin' do
before do
session.run_command("function [ { $commands[\\[] \"$@\" }")
session.clear_screen
end
it 'executes the custom behavior and the built-in behavior' do
session.send_string('asdf')
wait_for { session.content }.to eq('asdf')
end
end
end

View File

@ -0,0 +1,80 @@
describe 'when using vi mode' do
let(:before_sourcing) do
-> do
session.run_command('bindkey -v')
end
end
describe 'moving the cursor after exiting insert mode' do
it 'should not clear the current suggestion' do
with_history('foobar foo') do
session.
send_string('foo').
send_keys('escape').
send_keys('h')
wait_for { session.content }.to eq('foobar foo')
end
end
end
describe '`vi-forward-word-end`' do
it 'should accept through the end of the current word' do
with_history('foobar foo') do
session.
send_string('foo').
send_keys('escape').
send_keys('e'). # vi-forward-word-end
send_keys('a'). # vi-add-next
send_string('baz')
wait_for { session.content }.to eq('foobarbaz')
end
end
end
describe '`vi-forward-word`' do
it 'should accept through the first character of the next word' do
with_history('foobar foo') do
session.
send_string('foo').
send_keys('escape').
send_keys('w'). # vi-forward-word
send_keys('a'). # vi-add-next
send_string('az')
wait_for { session.content }.to eq('foobar faz')
end
end
end
describe '`vi-find-next-char`' do
it 'should accept through the next occurrence of the character' do
with_history('foobar foo') do
session.
send_string('foo').
send_keys('escape').
send_keys('f'). # vi-find-next-char
send_keys('o').
send_keys('a'). # vi-add-next
send_string('b')
wait_for { session.content }.to eq('foobar fob')
end
end
end
describe '`vi-delete`' do
it 'should be able to remove the last character in the buffer' do
skip 'deleting last char did not work below zsh version 5.0.8' if session.zsh_version < Gem::Version.new('5.0.8')
session.
send_string('echo foo').
send_keys('escape').
send_keys('d').
send_keys('l')
wait_for { session.content }.to eq('echo fo')
end
end
end

View File

@ -0,0 +1,39 @@
describe 'a wrapped widget' do
let(:widget) { 'backward-delete-char' }
context 'initialized before sourcing the plugin' do
let(:before_sourcing) do
-> do
session.
run_command("_orig_#{widget}() { zle .#{widget} }").
run_command("zle -N orig-#{widget} _orig_#{widget}").
run_command("#{widget}-magic() { zle orig-#{widget}; BUFFER+=b }").
run_command("zle -N #{widget} #{widget}-magic")
end
end
it 'executes the custom behavior and the built-in behavior' do
with_history('foobar', 'foodar') do
session.send_string('food').send_keys('C-h')
wait_for { session.content }.to eq('foobar')
end
end
end
context 'initialized after sourcing the plugin' do
before do
session.
run_command("zle -N orig-#{widget} ${widgets[#{widget}]#*:}").
run_command("#{widget}-magic() { zle orig-#{widget}; BUFFER+=b }").
run_command("zle -N #{widget} #{widget}-magic").
clear_screen
end
it 'executes the custom behavior and the built-in behavior' do
with_history('foobar', 'foodar') do
session.send_string('food').send_keys('C-h')
wait_for { session.content }.to eq('foobar')
end
end
end
end

View File

@ -0,0 +1,24 @@
describe 'using `zle -U`' do
let(:before_sourcing) do
-> do
session.
run_command('_zsh_autosuggest_strategy_test() { sleep 1; _zsh_autosuggest_strategy_history "$1" }').
run_command('foo() { zle -U - "echo hello" }; zle -N foo; bindkey ^B foo')
end
end
let(:options) { ['unset ZSH_AUTOSUGGEST_USE_ASYNC', 'ZSH_AUTOSUGGEST_STRATEGY=test'] }
# TODO: This is only possible with the $KEYS_QUEUED_COUNT widget parameter, coming soon...
xit 'does not fetch a suggestion for every inserted character' do
session.send_keys('C-b')
wait_for { session.content }.to eq('echo hello')
end
it 'shows a suggestion when the widget completes' do
with_history('echo hello world') do
session.send_keys('C-b')
wait_for { session.content(esc_seqs: true) }.to match(/\Aecho hello\e\[[0-9]+m world/)
end
end
end

View File

@ -0,0 +1,23 @@
context 'with some items in the kill ring' do
before do
session.
send_string('echo foo').
send_keys('C-u').
send_string('echo bar').
send_keys('C-u')
end
describe '`yank-pop`' do
it 'should cycle through all items in the kill ring' do
session.send_keys('C-y')
wait_for { session.content }.to eq('echo bar')
session.send_keys('escape').send_keys('y')
wait_for { session.content }.to eq('echo foo')
session.send_keys('escape').send_keys('y')
wait_for { session.content }.to eq('echo bar')
end
end
end

View File

@ -0,0 +1,17 @@
context 'with zle-line-init unignored' do
let(:after_sourcing) do
-> do
session.
run_command('setopt extendedglob').
run_command('ZSH_AUTOSUGGEST_IGNORE_WIDGETS=(${(@)ZSH_AUTOSUGGEST_IGNORE_WIDGETS:#zle-\*} zle-\^line-init)').
run_command('zle-line-init() { BUFFER="echo" }')
end
end
it 'should fetch a suggestion on each line initialization' do
with_history('echo foo') do
session.run_command('zle -N zle-line-init')
wait_for { session.content }.to end_with('echo foo')
end
end
end

View File

@ -0,0 +1,8 @@
describe 'a multi-line suggestion' do
it 'should be displayed on multiple lines' do
with_history("echo \"\n\"") do
session.send_keys('e')
wait_for { session.content }.to eq("echo \"\n\"")
end
end
end

View File

@ -0,0 +1,30 @@
describe 'a suggestion' do
let(:term_opts) { { width: 200 } }
let(:long_command) { "echo #{'a' * 100}" }
around do |example|
with_history(long_command) { example.run }
end
it 'is provided for any buffer length' do
session.send_string(long_command[0...-1])
wait_for { session.content }.to eq(long_command)
end
context 'when ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE is specified' do
let(:buffer_max_size) { 10 }
let(:options) { ["ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE=#{buffer_max_size}"] }
it 'is provided when the buffer is shorter than the specified length' do
session.send_string(long_command[0...(buffer_max_size - 1)])
wait_for { session.content }.to eq(long_command)
end
it 'is provided when the buffer is equal to the specified length' do
session.send_string(long_command[0...(buffer_max_size)])
wait_for { session.content }.to eq(long_command)
end
it 'is not provided when the buffer is longer than the specified length'
end
end

View File

@ -0,0 +1,7 @@
describe 'a displayed suggestion' do
it 'is shown in the default style'
describe 'when ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE is set to a zle_highlight string' do
it 'is shown in the specified style'
end
end

View File

@ -0,0 +1,7 @@
describe 'an original zle widget' do
context 'is accessible with the default prefix'
context 'when ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX is set' do
it 'is accessible with the specified prefix'
end
end

View File

@ -0,0 +1,55 @@
describe 'a suggestion for a given prefix' do
let(:history_strategy) { '_zsh_autosuggest_strategy_history() { suggestion="history" }' }
let(:foobar_strategy) { '_zsh_autosuggest_strategy_foobar() { [[ "foobar baz" = $1* ]] && suggestion="foobar baz" }' }
let(:foobaz_strategy) { '_zsh_autosuggest_strategy_foobaz() { [[ "foobaz bar" = $1* ]] && suggestion="foobaz bar" }' }
let(:after_sourcing) do
-> do
session.run_command(history_strategy)
end
end
it 'by default is determined by calling the `history` strategy function' do
session.send_string('h')
wait_for { session.content }.to eq('history')
end
context 'when ZSH_AUTOSUGGEST_STRATEGY is set to an array' do
let(:after_sourcing) do
-> do
session.
run_command(foobar_strategy).
run_command(foobaz_strategy).
run_command('ZSH_AUTOSUGGEST_STRATEGY=(foobar foobaz)')
end
end
it 'is determined by the first strategy function to return a suggestion' do
session.send_string('foo')
wait_for { session.content }.to eq('foobar baz')
session.send_string('baz')
wait_for { session.content }.to eq('foobaz bar')
end
end
context 'when ZSH_AUTOSUGGEST_STRATEGY is set to a string' do
let(:after_sourcing) do
-> do
session.
run_command(foobar_strategy).
run_command(foobaz_strategy).
run_command('ZSH_AUTOSUGGEST_STRATEGY="foobar foobaz"')
end
end
it 'is determined by the first strategy function to return a suggestion' do
session.send_string('foo')
wait_for { session.content }.to eq('foobar baz')
session.send_string('baz')
wait_for { session.content }.to eq('foobaz bar')
end
end
end

View File

@ -0,0 +1,121 @@
describe 'a zle widget' do
let(:widget) { 'my-widget' }
let(:before_sourcing) { -> { session.run_command("#{widget}() {}; zle -N #{widget}; bindkey ^B #{widget}") } }
context 'when added to ZSH_AUTOSUGGEST_ACCEPT_WIDGETS' do
let(:options) { ["ZSH_AUTOSUGGEST_ACCEPT_WIDGETS+=(#{widget})"] }
it 'accepts the suggestion and moves the cursor to the end of the buffer when invoked' do
with_history('echo hello') do
session.send_string('e')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-b')
wait_for { session.content(esc_seqs: true) }.to eq('echo hello')
wait_for { session.cursor }.to eq([10, 0])
end
end
end
context 'when added to ZSH_AUTOSUGGEST_CLEAR_WIDGETS' do
let(:options) { ["ZSH_AUTOSUGGEST_CLEAR_WIDGETS+=(#{widget})"] }
it 'clears the suggestion when invoked' do
with_history('echo hello') do
session.send_string('e')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-b')
wait_for { session.content }.to eq('e')
end
end
end
context 'when added to ZSH_AUTOSUGGEST_EXECUTE_WIDGETS' do
let(:options) { ["ZSH_AUTOSUGGEST_EXECUTE_WIDGETS+=(#{widget})"] }
it 'executes the suggestion when invoked' do
with_history('echo hello') do
session.send_string('e')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-b')
wait_for { session.content }.to end_with("\nhello")
end
end
end
context 'when added to ZSH_AUTOSUGGEST_IGNORE_WIDGETS' do
let(:options) { ["ZSH_AUTOSUGGEST_IGNORE_WIDGETS=(#{widget})"] }
it 'should not be wrapped with an autosuggest widget' do
session.run_command("echo $widgets[#{widget}]")
wait_for { session.content }.to end_with("\nuser:#{widget}")
end
end
context 'that moves the cursor forward' do
before { session.run_command("#{widget}() { zle forward-char }") }
context 'when added to ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS' do
let(:options) { ["ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS=(#{widget})"] }
it 'accepts the suggestion as far as the cursor is moved when invoked' do
with_history('echo hello') do
session.send_string('e')
wait_for { session.content }.to start_with('echo hello')
session.send_keys('C-b')
wait_for { session.content(esc_seqs: true) }.to match(/\Aec\e\[[0-9]+mho hello/)
end
end
end
end
context 'that modifies the buffer' do
before { session.run_command("#{widget}() { BUFFER=\"foo\" }") }
context 'when not added to any of the widget lists' do
it 'modifies the buffer and fetches a new suggestion' do
with_history('foobar') do
session.send_keys('C-b')
wait_for { session.content }.to eq('foobar')
end
end
end
end
end
describe 'a modification to the widget lists' do
let(:widget) { 'my-widget' }
let(:before_sourcing) { -> { session.run_command("#{widget}() {}; zle -N #{widget}; bindkey ^B #{widget}") } }
before { session.run_command("ZSH_AUTOSUGGEST_ACCEPT_WIDGETS+=(#{widget})") }
it 'takes effect on the next cmd line' do
with_history('echo hello') do
session.send_string('e')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-b')
wait_for { session.content(esc_seqs: true) }.to eq('echo hello')
end
end
context 'when manual rebind is enabled' do
let(:options) { ["ZSH_AUTOSUGGEST_MANUAL_REBIND=true"] }
it 'does not take effect until bind command is re-run' do
with_history('echo hello') do
session.send_string('e')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-b')
sleep 1
expect(session.content(esc_seqs: true)).not_to eq('echo hello')
session.send_keys('C-c')
session.run_command('_zsh_autosuggest_bind_widgets').clear_screen
wait_for { session.content }.to eq('')
session.send_string('e')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-b')
wait_for { session.content(esc_seqs: true) }.to eq('echo hello')
end
end
end
end

View File

@ -0,0 +1,54 @@
require 'pry'
require 'rspec/wait'
require 'terminal_session'
require 'tempfile'
RSpec.shared_context 'terminal session' do
let(:term_opts) { {} }
let(:session) { TerminalSession.new(term_opts) }
let(:before_sourcing) { -> {} }
let(:after_sourcing) { -> {} }
let(:options) { [] }
around do |example|
before_sourcing.call
session.run_command(['source zsh-autosuggestions.zsh', *options].join('; '))
after_sourcing.call
session.clear_screen
example.run
session.destroy
end
def with_history(*commands, &block)
Tempfile.create do |f|
f.write(commands.map{|c| c.gsub("\n", "\\\n")}.join("\n"))
f.flush
session.run_command('fc -p')
session.run_command("fc -R #{f.path}")
session.clear_screen
yield block
session.send_keys('C-c')
session.run_command('fc -P')
end
end
end
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.wait_timeout = 2
config.include_context 'terminal session'
end

View File

@ -0,0 +1,72 @@
describe 'the `completion` suggestion strategy' do
let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=completion'] }
let(:before_sourcing) do
-> do
session.
run_command('autoload compinit && compinit').
run_command('_foo() { compadd bar; compadd bat }').
run_command('_num() { compadd two; compadd three }').
run_command('compdef _foo baz').
run_command('compdef _num one')
end
end
it 'suggests the first completion result' do
session.send_string('baz ')
wait_for { session.content }.to eq('baz bar')
end
it 'does not add extra carriage returns when prefix has a line feed' do
skip '`stty` does not work inside zpty below zsh version 5.0.3' if session.zsh_version < Gem::Version.new('5.0.3')
session.send_string('baz \\').send_keys('C-v', 'C-j')
wait_for { session.content }.to eq("baz \\\nbar")
end
context 'when `_complete` is aliased' do
let(:before_sourcing) do
-> do
session.
run_command('autoload compinit && compinit').
run_command('_foo() { compadd bar; compadd bat }').
run_command('compdef _foo baz').
run_command('alias _complete=_complete')
end
end
it 'suggests the first completion result' do
session.send_string('baz ')
wait_for { session.content }.to eq('baz bar')
end
end
context 'when ZSH_AUTOSUGGEST_COMPLETION_IGNORE is set to a pattern' do
let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=completion', 'ZSH_AUTOSUGGEST_COMPLETION_IGNORE="one *"'] }
it 'makes suggestions when the buffer does not match the pattern' do
session.send_string('baz ')
wait_for { session.content }.to eq('baz bar')
end
it 'does not make suggestions when the buffer matches the pattern' do
session.send_string('one t')
sleep 1
expect(session.content).to eq('one t')
end
end
context 'when async mode is enabled' do
let(:options) { ['ZSH_AUTOSUGGEST_USE_ASYNC=true', 'ZSH_AUTOSUGGEST_STRATEGY=completion'] }
it 'suggests the first completion result' do
session.send_string('baz ')
wait_for { session.content }.to eq('baz bar')
end
it 'does not add extra carriage returns when prefix has a line feed' do
skip '`stty` does not work inside zpty below zsh version 5.0.3' if session.zsh_version < Gem::Version.new('5.0.3')
session.send_string('baz \\').send_keys('C-v', 'C-j')
wait_for { session.content }.to eq("baz \\\nbar")
end
end
end

View File

@ -0,0 +1,23 @@
require 'strategies/special_characters_helper'
describe 'the `history` suggestion strategy' do
it 'suggests the last matching history entry' do
with_history('ls foo', 'ls bar', 'echo baz') do
session.send_string('ls')
wait_for { session.content }.to eq('ls bar')
end
end
context 'when ZSH_AUTOSUGGEST_HISTORY_IGNORE is set to a pattern' do
let(:options) { ['ZSH_AUTOSUGGEST_HISTORY_IGNORE="* bar"'] }
it 'does not make suggestions that match the pattern' do
with_history('ls foo', 'ls bar', 'echo baz') do
session.send_string('ls')
wait_for { session.content }.to eq('ls foo')
end
end
end
include_examples 'special characters'
end

View File

@ -0,0 +1,34 @@
require 'strategies/special_characters_helper'
describe 'the `match_prev_cmd` strategy' do
let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=match_prev_cmd'] }
let(:history) { [
'echo what',
'ls foo',
'echo what',
'ls bar',
'ls baz',
'echo what'
] }
it 'suggests the last matching history entry after the previous command' do
with_history(*history) do
session.send_string('ls')
wait_for { session.content }.to eq('ls bar')
end
end
context 'when ZSH_AUTOSUGGEST_HISTORY_IGNORE is set to a pattern' do
let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=match_prev_cmd', 'ZSH_AUTOSUGGEST_HISTORY_IGNORE="* bar"'] }
it 'does not make suggestions that match the pattern' do
with_history(*history) do
session.send_string('ls')
wait_for { session.content }.to eq('ls foo')
end
end
end
include_examples 'special characters'
end

View File

@ -0,0 +1,75 @@
shared_examples 'special characters' do
describe 'a special character in the buffer should be treated like any other character' do
it 'asterisk' do
with_history('echo "hello*"', 'echo "hello."') do
session.send_string('echo "hello*')
wait_for { session.content }.to eq('echo "hello*"')
end
end
it 'question mark' do
with_history('echo "hello?"', 'echo "hello."') do
session.send_string('echo "hello?')
wait_for { session.content }.to eq('echo "hello?"')
end
end
it 'backslash' do
with_history('echo "hello\nworld"') do
session.send_string('echo "hello\\')
wait_for { session.content }.to eq('echo "hello\nworld"')
end
end
it 'double backslash' do
with_history('echo "\\\\"') do
session.send_string('echo "\\\\')
wait_for { session.content }.to eq('echo "\\\\"')
end
end
it 'tilde' do
with_history('echo ~/foo') do
session.send_string('echo ~')
wait_for { session.content }.to eq('echo ~/foo')
end
end
it 'parentheses' do
with_history('echo "$(ls foo)"') do
session.send_string('echo "$(')
wait_for { session.content }.to eq('echo "$(ls foo)"')
end
end
it 'square bracket' do
with_history('echo "$history[123]"') do
session.send_string('echo "$history[')
wait_for { session.content }.to eq('echo "$history[123]"')
session.send_string('123]')
wait_for { session.content }.to eq('echo "$history[123]"')
end
end
it 'octothorpe' do
with_history('echo "#yolo"') do
session.send_string('echo "#')
wait_for { session.content }.to eq('echo "#yolo"')
end
end
it 'caret' do
with_history('echo "^A"', 'echo "^B"') do
session.send_string('echo "^A')
wait_for { session.content }.to eq('echo "^A"')
end
end
it 'dash' do
with_history('-foo() {}') do
session.send_string('-')
wait_for { session.content }.to eq('-foo() {}')
end
end
end
end

View File

@ -0,0 +1,99 @@
require 'securerandom'
class TerminalSession
ZSH_BIN = ENV['TEST_ZSH_BIN'] || 'zsh'
def initialize(opts = {})
opts = {
width: 80,
height: 24,
prompt: '',
term: 'xterm-256color',
zsh_bin: ZSH_BIN
}.merge(opts)
@opts = opts
cmd="PS1=\"#{opts[:prompt]}\" TERM=#{opts[:term]} #{ZSH_BIN} -f"
tmux_command("new-session -d -x #{opts[:width]} -y #{opts[:height]} '#{cmd}'")
end
def zsh_version
@zsh_version ||= Gem::Version.new(`#{ZSH_BIN} -c 'echo -n $ZSH_VERSION'`)
end
def tmux_socket_name
@tmux_socket_name ||= SecureRandom.hex(6)
end
def run_command(command)
send_string(command)
send_keys('enter')
self
end
def send_string(str)
tmux_command("send-keys -t 0 -l -- '#{str.gsub("'", "\\'")}'")
self
end
def send_keys(*keys)
tmux_command("send-keys -t 0 #{keys.join(' ')}")
self
end
def paste_string(str)
tmux_command("set-buffer -- '#{str}'")
tmux_command("paste-buffer -dpr -t 0")
self
end
def content(esc_seqs: false)
cmd = 'capture-pane -p -t 0'
cmd += ' -e' if esc_seqs
tmux_command(cmd).strip
end
def clear_screen
send_keys('C-l')
i = 0
until content == opts[:prompt] || i > 20 do
sleep(0.1)
i = i + 1
end
self
end
def destroy
tmux_command('kill-session')
end
def cursor
tmux_command("display-message -t 0 -p '\#{cursor_x},\#{cursor_y}'").
strip.
split(',').
map(&:to_i)
end
def attach!
tmux_command('attach-session')
end
private
attr_reader :opts
def tmux_command(cmd)
out = `tmux -u -L #{tmux_socket_name} #{cmd}`
raise("tmux error running: '#{cmd}'") unless $?.success?
out
end
end

View File

@ -0,0 +1,19 @@
describe 'the `autosuggest-disable` widget' do
before do
session.run_command('bindkey ^B autosuggest-disable')
end
it 'disables suggestions and clears the suggestion' do
with_history('echo hello') do
session.send_string('echo')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-b')
wait_for { session.content }.to eq('echo')
session.send_string(' h')
sleep 1
expect(session.content).to eq('echo h')
end
end
end

View File

@ -0,0 +1,42 @@
describe 'the `autosuggest-enable` widget' do
before do
session.
run_command('typeset -g _ZSH_AUTOSUGGEST_DISABLED').
run_command('bindkey ^B autosuggest-enable')
end
it 'enables suggestions and fetches a suggestion' do
with_history('echo hello') do
session.send_string('e')
sleep 1
expect(session.content).to eq('e')
session.send_keys('C-b')
session.send_string('c')
wait_for { session.content }.to eq('echo hello')
end
end
context 'invoked on an empty buffer' do
it 'does not fetch a suggestion' do
with_history('echo hello') do
session.send_keys('C-b')
sleep 1
expect(session.content).to eq('')
end
end
end
context 'invoked on a non-empty buffer' do
it 'fetches a suggestion' do
with_history('echo hello') do
session.send_string('e')
sleep 1
expect(session.content).to eq('e')
session.send_keys('C-b')
wait_for { session.content }.to eq('echo hello')
end
end
end
end

View File

@ -0,0 +1,24 @@
describe 'the `autosuggest-fetch` widget' do
context 'when suggestions are disabled' do
before do
session.
run_command('bindkey ^B autosuggest-disable').
run_command('bindkey ^F autosuggest-fetch').
send_keys('C-b')
end
it 'will fetch and display a suggestion' do
with_history('echo hello') do
session.send_string('echo h')
sleep 1
expect(session.content).to eq('echo h')
session.send_keys('C-f')
wait_for { session.content }.to eq('echo hello')
session.send_string('e')
wait_for { session.content }.to eq('echo hello')
end
end
end
end

View File

@ -0,0 +1,26 @@
describe 'the `autosuggest-toggle` widget' do
before do
session.run_command('bindkey ^B autosuggest-toggle')
end
it 'toggles suggestions' do
with_history('echo world', 'echo hello') do
session.send_string('echo')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-b')
wait_for { session.content }.to eq('echo')
session.send_string(' h')
sleep 1
expect(session.content).to eq('echo h')
session.send_keys('C-b')
wait_for { session.content }.to eq('echo hello')
session.send_keys('C-h')
session.send_string('w')
wait_for { session.content }.to eq('echo world')
end
end
end

View File

@ -0,0 +1,76 @@
#--------------------------------------------------------------------#
# Async #
#--------------------------------------------------------------------#
_zsh_autosuggest_async_request() {
zmodload zsh/system 2>/dev/null # For `$sysparams`
typeset -g _ZSH_AUTOSUGGEST_ASYNC_FD _ZSH_AUTOSUGGEST_CHILD_PID
# If we've got a pending request, cancel it
if [[ -n "$_ZSH_AUTOSUGGEST_ASYNC_FD" ]] && { true <&$_ZSH_AUTOSUGGEST_ASYNC_FD } 2>/dev/null; then
# Close the file descriptor and remove the handler
exec {_ZSH_AUTOSUGGEST_ASYNC_FD}<&-
zle -F $_ZSH_AUTOSUGGEST_ASYNC_FD
# We won't know the pid unless the user has zsh/system module installed
if [[ -n "$_ZSH_AUTOSUGGEST_CHILD_PID" ]]; then
# Zsh will make a new process group for the child process only if job
# control is enabled (MONITOR option)
if [[ -o MONITOR ]]; then
# Send the signal to the process group to kill any processes that may
# have been forked by the suggestion strategy
kill -TERM -$_ZSH_AUTOSUGGEST_CHILD_PID 2>/dev/null
else
# Kill just the child process since it wasn't placed in a new process
# group. If the suggestion strategy forked any child processes they may
# be orphaned and left behind.
kill -TERM $_ZSH_AUTOSUGGEST_CHILD_PID 2>/dev/null
fi
fi
fi
# Fork a process to fetch a suggestion and open a pipe to read from it
exec {_ZSH_AUTOSUGGEST_ASYNC_FD}< <(
# Tell parent process our pid
echo $sysparams[pid]
# Fetch and print the suggestion
local suggestion
_zsh_autosuggest_fetch_suggestion "$1"
echo -nE "$suggestion"
)
# There's a weird bug here where ^C stops working unless we force a fork
# See https://github.com/zsh-users/zsh-autosuggestions/issues/364
autoload -Uz is-at-least
is-at-least 5.8 || command true
# Read the pid from the child process
read _ZSH_AUTOSUGGEST_CHILD_PID <&$_ZSH_AUTOSUGGEST_ASYNC_FD
# When the fd is readable, call the response handler
zle -F "$_ZSH_AUTOSUGGEST_ASYNC_FD" _zsh_autosuggest_async_response
}
# Called when new data is ready to be read from the pipe
# First arg will be fd ready for reading
# Second arg will be passed in case of error
_zsh_autosuggest_async_response() {
emulate -L zsh
local suggestion
if [[ -z "$2" || "$2" == "hup" ]]; then
# Read everything from the fd and give it as a suggestion
IFS='' read -rd '' -u $1 suggestion
zle autosuggest-suggest -- "$suggestion"
# Close the fd
exec {1}<&-
fi
# Always remove the handler
zle -F "$1"
}

View File

@ -0,0 +1,106 @@
#--------------------------------------------------------------------#
# Widget Helpers #
#--------------------------------------------------------------------#
_zsh_autosuggest_incr_bind_count() {
typeset -gi bind_count=$((_ZSH_AUTOSUGGEST_BIND_COUNTS[$1]+1))
_ZSH_AUTOSUGGEST_BIND_COUNTS[$1]=$bind_count
}
# Bind a single widget to an autosuggest widget, saving a reference to the original widget
_zsh_autosuggest_bind_widget() {
typeset -gA _ZSH_AUTOSUGGEST_BIND_COUNTS
local widget=$1
local autosuggest_action=$2
local prefix=$ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX
local -i bind_count
# Save a reference to the original widget
case $widgets[$widget] in
# Already bound
user:_zsh_autosuggest_(bound|orig)_*)
bind_count=$((_ZSH_AUTOSUGGEST_BIND_COUNTS[$widget]))
;;
# User-defined widget
user:*)
_zsh_autosuggest_incr_bind_count $widget
zle -N $prefix$bind_count-$widget ${widgets[$widget]#*:}
;;
# Built-in widget
builtin)
_zsh_autosuggest_incr_bind_count $widget
eval "_zsh_autosuggest_orig_${(q)widget}() { zle .${(q)widget} }"
zle -N $prefix$bind_count-$widget _zsh_autosuggest_orig_$widget
;;
# Completion widget
completion:*)
_zsh_autosuggest_incr_bind_count $widget
eval "zle -C $prefix$bind_count-${(q)widget} ${${(s.:.)widgets[$widget]}[2,3]}"
;;
esac
# Pass the original widget's name explicitly into the autosuggest
# function. Use this passed in widget name to call the original
# widget instead of relying on the $WIDGET variable being set
# correctly. $WIDGET cannot be trusted because other plugins call
# zle without the `-w` flag (e.g. `zle self-insert` instead of
# `zle self-insert -w`).
eval "_zsh_autosuggest_bound_${bind_count}_${(q)widget}() {
_zsh_autosuggest_widget_$autosuggest_action $prefix$bind_count-${(q)widget} \$@
}"
# Create the bound widget
zle -N -- $widget _zsh_autosuggest_bound_${bind_count}_$widget
}
# Map all configured widgets to the right autosuggest widgets
_zsh_autosuggest_bind_widgets() {
emulate -L zsh
local widget
local ignore_widgets
ignore_widgets=(
.\*
_\*
${_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS/#/autosuggest-}
$ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX\*
$ZSH_AUTOSUGGEST_IGNORE_WIDGETS
)
# Find every widget we might want to bind and bind it appropriately
for widget in ${${(f)"$(builtin zle -la)"}:#${(j:|:)~ignore_widgets}}; do
if [[ -n ${ZSH_AUTOSUGGEST_CLEAR_WIDGETS[(r)$widget]} ]]; then
_zsh_autosuggest_bind_widget $widget clear
elif [[ -n ${ZSH_AUTOSUGGEST_ACCEPT_WIDGETS[(r)$widget]} ]]; then
_zsh_autosuggest_bind_widget $widget accept
elif [[ -n ${ZSH_AUTOSUGGEST_EXECUTE_WIDGETS[(r)$widget]} ]]; then
_zsh_autosuggest_bind_widget $widget execute
elif [[ -n ${ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS[(r)$widget]} ]]; then
_zsh_autosuggest_bind_widget $widget partial_accept
else
# Assume any unspecified widget might modify the buffer
_zsh_autosuggest_bind_widget $widget modify
fi
done
}
# Given the name of an original widget and args, invoke it, if it exists
_zsh_autosuggest_invoke_original_widget() {
# Do nothing unless called with at least one arg
(( $# )) || return 0
local original_widget_name="$1"
shift
if (( ${+widgets[$original_widget_name]} )); then
zle $original_widget_name -- $@
fi
}

View File

@ -0,0 +1,93 @@
#--------------------------------------------------------------------#
# Global Configuration Variables #
#--------------------------------------------------------------------#
# Color to use when highlighting suggestion
# Uses format of `region_highlight`
# More info: http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Zle-Widgets
(( ! ${+ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE} )) &&
typeset -g ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=8'
# Prefix to use when saving original versions of bound widgets
(( ! ${+ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX} )) &&
typeset -g ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX=autosuggest-orig-
# Strategies to use to fetch a suggestion
# Will try each strategy in order until a suggestion is returned
(( ! ${+ZSH_AUTOSUGGEST_STRATEGY} )) && {
typeset -ga ZSH_AUTOSUGGEST_STRATEGY
ZSH_AUTOSUGGEST_STRATEGY=(history)
}
# Widgets that clear the suggestion
(( ! ${+ZSH_AUTOSUGGEST_CLEAR_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_CLEAR_WIDGETS
ZSH_AUTOSUGGEST_CLEAR_WIDGETS=(
history-search-forward
history-search-backward
history-beginning-search-forward
history-beginning-search-backward
history-substring-search-up
history-substring-search-down
up-line-or-beginning-search
down-line-or-beginning-search
up-line-or-history
down-line-or-history
accept-line
copy-earlier-word
)
}
# Widgets that accept the entire suggestion
(( ! ${+ZSH_AUTOSUGGEST_ACCEPT_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_ACCEPT_WIDGETS
ZSH_AUTOSUGGEST_ACCEPT_WIDGETS=(
forward-char
end-of-line
vi-forward-char
vi-end-of-line
vi-add-eol
)
}
# Widgets that accept the entire suggestion and execute it
(( ! ${+ZSH_AUTOSUGGEST_EXECUTE_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_EXECUTE_WIDGETS
ZSH_AUTOSUGGEST_EXECUTE_WIDGETS=(
)
}
# Widgets that accept the suggestion as far as the cursor moves
(( ! ${+ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS
ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS=(
forward-word
emacs-forward-word
vi-forward-word
vi-forward-word-end
vi-forward-blank-word
vi-forward-blank-word-end
vi-find-next-char
vi-find-next-char-skip
)
}
# Widgets that should be ignored (globbing supported but must be escaped)
(( ! ${+ZSH_AUTOSUGGEST_IGNORE_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_IGNORE_WIDGETS
ZSH_AUTOSUGGEST_IGNORE_WIDGETS=(
orig-\*
beep
run-help
set-local-history
which-command
yank
yank-pop
zle-\*
)
}
# Pty name for capturing completions for completion suggestion strategy
(( ! ${+ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME} )) &&
typeset -g ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME=zsh_autosuggest_completion_pty

View File

@ -0,0 +1,27 @@
#--------------------------------------------------------------------#
# Fetch Suggestion #
#--------------------------------------------------------------------#
# Loops through all specified strategies and returns a suggestion
# from the first strategy to provide one.
#
_zsh_autosuggest_fetch_suggestion() {
typeset -g suggestion
local -a strategies
local strategy
# Ensure we are working with an array
strategies=(${=ZSH_AUTOSUGGEST_STRATEGY})
for strategy in $strategies; do
# Try to get a suggestion from this strategy
_zsh_autosuggest_strategy_$strategy "$1"
# Ensure the suggestion matches the prefix
[[ "$suggestion" != "$1"* ]] && unset suggestion
# Break once we've found a valid suggestion
[[ -n "$suggestion" ]] && break
done
}

View File

@ -0,0 +1,26 @@
#--------------------------------------------------------------------#
# Highlighting #
#--------------------------------------------------------------------#
# If there was a highlight, remove it
_zsh_autosuggest_highlight_reset() {
typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT
if [[ -n "$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT" ]]; then
region_highlight=("${(@)region_highlight:#$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT}")
unset _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT
fi
}
# If there's a suggestion, highlight it
_zsh_autosuggest_highlight_apply() {
typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT
if (( $#POSTDISPLAY )); then
typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT="$#BUFFER $(($#BUFFER + $#POSTDISPLAY)) $ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE"
region_highlight+=("$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT")
else
unset _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT
fi
}

View File

@ -0,0 +1,33 @@
#--------------------------------------------------------------------#
# Start #
#--------------------------------------------------------------------#
# Start the autosuggestion widgets
_zsh_autosuggest_start() {
# By default we re-bind widgets on every precmd to ensure we wrap other
# wrappers. Specifically, highlighting breaks if our widgets are wrapped by
# zsh-syntax-highlighting widgets. This also allows modifications to the
# widget list variables to take effect on the next precmd. However this has
# a decent performance hit, so users can set ZSH_AUTOSUGGEST_MANUAL_REBIND
# to disable the automatic re-binding.
if (( ${+ZSH_AUTOSUGGEST_MANUAL_REBIND} )); then
add-zsh-hook -d precmd _zsh_autosuggest_start
fi
_zsh_autosuggest_bind_widgets
}
# Mark for auto-loading the functions that we use
autoload -Uz add-zsh-hook is-at-least
# Automatically enable asynchronous mode in newer versions of zsh. Disable for
# older versions because there is a bug when using async mode where ^C does not
# work immediately after fetching a suggestion.
# See https://github.com/zsh-users/zsh-autosuggestions/issues/364
if is-at-least 5.0.8; then
typeset -g ZSH_AUTOSUGGEST_USE_ASYNC=
fi
# Start the autosuggestion widgets on the next precmd
add-zsh-hook precmd _zsh_autosuggest_start

View File

@ -0,0 +1,137 @@
#--------------------------------------------------------------------#
# Completion Suggestion Strategy #
#--------------------------------------------------------------------#
# Fetches a suggestion from the completion engine
#
_zsh_autosuggest_capture_postcompletion() {
# Always insert the first completion into the buffer
compstate[insert]=1
# Don't list completions
unset 'compstate[list]'
}
_zsh_autosuggest_capture_completion_widget() {
# Add a post-completion hook to be called after all completions have been
# gathered. The hook can modify compstate to affect what is done with the
# gathered completions.
local -a +h comppostfuncs
comppostfuncs=(_zsh_autosuggest_capture_postcompletion)
# Only capture completions at the end of the buffer
CURSOR=$#BUFFER
# Run the original widget wrapping `.complete-word` so we don't
# recursively try to fetch suggestions, since our pty is forked
# after autosuggestions is initialized.
zle -- ${(k)widgets[(r)completion:.complete-word:_main_complete]}
if is-at-least 5.0.3; then
# Don't do any cr/lf transformations. We need to do this immediately before
# output because if we do it in setup, onlcr will be re-enabled when we enter
# vared in the async code path. There is a bug in zpty module in older versions
# where the tty is not properly attached to the pty slave, resulting in stty
# getting stopped with a SIGTTOU. See zsh-workers thread 31660 and upstream
# commit f75904a38
stty -onlcr -ocrnl -F /dev/tty
fi
# The completion has been added, print the buffer as the suggestion
echo -nE - $'\0'$BUFFER$'\0'
}
zle -N autosuggest-capture-completion _zsh_autosuggest_capture_completion_widget
_zsh_autosuggest_capture_setup() {
# There is a bug in zpty module in older zsh versions by which a
# zpty that exits will kill all zpty processes that were forked
# before it. Here we set up a zsh exit hook to SIGKILL the zpty
# process immediately, before it has a chance to kill any other
# zpty processes.
if ! is-at-least 5.4; then
zshexit() {
# The zsh builtin `kill` fails sometimes in older versions
# https://unix.stackexchange.com/a/477647/156673
kill -KILL $$ 2>&- || command kill -KILL $$
# Block for long enough for the signal to come through
sleep 1
}
fi
# Try to avoid any suggestions that wouldn't match the prefix
zstyle ':completion:*' matcher-list ''
zstyle ':completion:*' path-completion false
zstyle ':completion:*' max-errors 0 not-numeric
bindkey '^I' autosuggest-capture-completion
}
_zsh_autosuggest_capture_completion_sync() {
_zsh_autosuggest_capture_setup
zle autosuggest-capture-completion
}
_zsh_autosuggest_capture_completion_async() {
_zsh_autosuggest_capture_setup
zmodload zsh/parameter 2>/dev/null || return # For `$functions`
# Make vared completion work as if for a normal command line
# https://stackoverflow.com/a/7057118/154703
autoload +X _complete
functions[_original_complete]=$functions[_complete]
function _complete() {
unset 'compstate[vared]'
_original_complete "$@"
}
# Open zle with buffer set so we can capture completions for it
vared 1
}
_zsh_autosuggest_strategy_completion() {
# Reset options to defaults and enable LOCAL_OPTIONS
emulate -L zsh
# Enable extended glob for completion ignore pattern
setopt EXTENDED_GLOB
typeset -g suggestion
local line REPLY
# Exit if we don't have completions
whence compdef >/dev/null || return
# Exit if we don't have zpty
zmodload zsh/zpty 2>/dev/null || return
# Exit if our search string matches the ignore pattern
[[ -n "$ZSH_AUTOSUGGEST_COMPLETION_IGNORE" ]] && [[ "$1" == $~ZSH_AUTOSUGGEST_COMPLETION_IGNORE ]] && return
# Zle will be inactive if we are in async mode
if zle; then
zpty $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME _zsh_autosuggest_capture_completion_sync
else
zpty $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME _zsh_autosuggest_capture_completion_async "\$1"
zpty -w $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME $'\t'
fi
{
# The completion result is surrounded by null bytes, so read the
# content between the first two null bytes.
zpty -r $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME line '*'$'\0''*'$'\0'
# Extract the suggestion from between the null bytes. On older
# versions of zsh (older than 5.3), we sometimes get extra bytes after
# the second null byte, so trim those off the end.
# See http://www.zsh.org/mla/workers/2015/msg03290.html
suggestion="${${(@0)line}[2]}"
} always {
# Destroy the pty
zpty -d $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME
}
}

View File

@ -0,0 +1,32 @@
#--------------------------------------------------------------------#
# History Suggestion Strategy #
#--------------------------------------------------------------------#
# Suggests the most recent history item that matches the given
# prefix.
#
_zsh_autosuggest_strategy_history() {
# Reset options to defaults and enable LOCAL_OPTIONS
emulate -L zsh
# Enable globbing flags so that we can use (#m) and (x~y) glob operator
setopt EXTENDED_GLOB
# Escape backslashes and all of the glob operators so we can use
# this string as a pattern to search the $history associative array.
# - (#m) globbing flag enables setting references for match data
# TODO: Use (b) flag when we can drop support for zsh older than v5.0.8
local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}"
# Get the history items that match the prefix, excluding those that match
# the ignore pattern
local pattern="$prefix*"
if [[ -n $ZSH_AUTOSUGGEST_HISTORY_IGNORE ]]; then
pattern="($pattern)~($ZSH_AUTOSUGGEST_HISTORY_IGNORE)"
fi
# Give the first history item matching the pattern as the suggestion
# - (r) subscript flag makes the pattern match on values
typeset -g suggestion="${history[(r)$pattern]}"
}

View File

@ -0,0 +1,66 @@
#--------------------------------------------------------------------#
# Match Previous Command Suggestion Strategy #
#--------------------------------------------------------------------#
# Suggests the most recent history item that matches the given
# prefix and whose preceding history item also matches the most
# recently executed command.
#
# For example, suppose your history has the following entries:
# - pwd
# - ls foo
# - ls bar
# - pwd
#
# Given the history list above, when you type 'ls', the suggestion
# will be 'ls foo' rather than 'ls bar' because your most recently
# executed command (pwd) was previously followed by 'ls foo'.
#
# Note that this strategy won't work as expected with ZSH options that don't
# preserve the history order such as `HIST_IGNORE_ALL_DUPS` or
# `HIST_EXPIRE_DUPS_FIRST`.
_zsh_autosuggest_strategy_match_prev_cmd() {
# Reset options to defaults and enable LOCAL_OPTIONS
emulate -L zsh
# Enable globbing flags so that we can use (#m) and (x~y) glob operator
setopt EXTENDED_GLOB
# TODO: Use (b) flag when we can drop support for zsh older than v5.0.8
local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}"
# Get the history items that match the prefix, excluding those that match
# the ignore pattern
local pattern="$prefix*"
if [[ -n $ZSH_AUTOSUGGEST_HISTORY_IGNORE ]]; then
pattern="($pattern)~($ZSH_AUTOSUGGEST_HISTORY_IGNORE)"
fi
# Get all history event numbers that correspond to history
# entries that match the pattern
local history_match_keys
history_match_keys=(${(k)history[(R)$~pattern]})
# By default we use the first history number (most recent history entry)
local histkey="${history_match_keys[1]}"
# Get the previously executed command
local prev_cmd="$(_zsh_autosuggest_escape_command "${history[$((HISTCMD-1))]}")"
# Iterate up to the first 200 history event numbers that match $prefix
for key in "${(@)history_match_keys[1,200]}"; do
# Stop if we ran out of history
[[ $key -gt 1 ]] || break
# See if the history entry preceding the suggestion matches the
# previous command, and use it if it does
if [[ "${history[$((key - 1))]}" == "$prev_cmd" ]]; then
histkey="$key"
break
fi
done
# Give back the matched history entry
typeset -g suggestion="$history[$histkey]"
}

View File

@ -0,0 +1,11 @@
#--------------------------------------------------------------------#
# Utility Functions #
#--------------------------------------------------------------------#
_zsh_autosuggest_escape_command() {
setopt localoptions EXTENDED_GLOB
# Escape special chars in the string (requires EXTENDED_GLOB)
echo -E "${1//(#m)[\"\'\\()\[\]|*?~]/\\$MATCH}"
}

View File

@ -0,0 +1,231 @@
#--------------------------------------------------------------------#
# Autosuggest Widget Implementations #
#--------------------------------------------------------------------#
# Disable suggestions
_zsh_autosuggest_disable() {
typeset -g _ZSH_AUTOSUGGEST_DISABLED
_zsh_autosuggest_clear
}
# Enable suggestions
_zsh_autosuggest_enable() {
unset _ZSH_AUTOSUGGEST_DISABLED
if (( $#BUFFER )); then
_zsh_autosuggest_fetch
fi
}
# Toggle suggestions (enable/disable)
_zsh_autosuggest_toggle() {
if (( ${+_ZSH_AUTOSUGGEST_DISABLED} )); then
_zsh_autosuggest_enable
else
_zsh_autosuggest_disable
fi
}
# Clear the suggestion
_zsh_autosuggest_clear() {
# Remove the suggestion
unset POSTDISPLAY
_zsh_autosuggest_invoke_original_widget $@
}
# Modify the buffer and get a new suggestion
_zsh_autosuggest_modify() {
local -i retval
# Only available in zsh >= 5.4
local -i KEYS_QUEUED_COUNT
# Save the contents of the buffer/postdisplay
local orig_buffer="$BUFFER"
local orig_postdisplay="$POSTDISPLAY"
# Clear suggestion while waiting for next one
unset POSTDISPLAY
# Original widget may modify the buffer
_zsh_autosuggest_invoke_original_widget $@
retval=$?
emulate -L zsh
# Don't fetch a new suggestion if there's more input to be read immediately
if (( $PENDING > 0 || $KEYS_QUEUED_COUNT > 0 )); then
POSTDISPLAY="$orig_postdisplay"
return $retval
fi
# Optimize if manually typing in the suggestion or if buffer hasn't changed
if [[ "$BUFFER" = "$orig_buffer"* && "$orig_postdisplay" = "${BUFFER:$#orig_buffer}"* ]]; then
POSTDISPLAY="${orig_postdisplay:$(($#BUFFER - $#orig_buffer))}"
return $retval
fi
# Bail out if suggestions are disabled
if (( ${+_ZSH_AUTOSUGGEST_DISABLED} )); then
return $?
fi
# Get a new suggestion if the buffer is not empty after modification
if (( $#BUFFER > 0 )); then
if [[ -z "$ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE" ]] || (( $#BUFFER <= $ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE )); then
_zsh_autosuggest_fetch
fi
fi
return $retval
}
# Fetch a new suggestion based on what's currently in the buffer
_zsh_autosuggest_fetch() {
if (( ${+ZSH_AUTOSUGGEST_USE_ASYNC} )); then
_zsh_autosuggest_async_request "$BUFFER"
else
local suggestion
_zsh_autosuggest_fetch_suggestion "$BUFFER"
_zsh_autosuggest_suggest "$suggestion"
fi
}
# Offer a suggestion
_zsh_autosuggest_suggest() {
emulate -L zsh
local suggestion="$1"
if [[ -n "$suggestion" ]] && (( $#BUFFER )); then
POSTDISPLAY="${suggestion#$BUFFER}"
else
unset POSTDISPLAY
fi
}
# Accept the entire suggestion
_zsh_autosuggest_accept() {
local -i retval max_cursor_pos=$#BUFFER
# When vicmd keymap is active, the cursor can't move all the way
# to the end of the buffer
if [[ "$KEYMAP" = "vicmd" ]]; then
max_cursor_pos=$((max_cursor_pos - 1))
fi
# If we're not in a valid state to accept a suggestion, just run the
# original widget and bail out
if (( $CURSOR != $max_cursor_pos || !$#POSTDISPLAY )); then
_zsh_autosuggest_invoke_original_widget $@
return
fi
# Only accept if the cursor is at the end of the buffer
# Add the suggestion to the buffer
BUFFER="$BUFFER$POSTDISPLAY"
# Remove the suggestion
unset POSTDISPLAY
# Run the original widget before manually moving the cursor so that the
# cursor movement doesn't make the widget do something unexpected
_zsh_autosuggest_invoke_original_widget $@
retval=$?
# Move the cursor to the end of the buffer
if [[ "$KEYMAP" = "vicmd" ]]; then
CURSOR=$(($#BUFFER - 1))
else
CURSOR=$#BUFFER
fi
return $retval
}
# Accept the entire suggestion and execute it
_zsh_autosuggest_execute() {
# Add the suggestion to the buffer
BUFFER="$BUFFER$POSTDISPLAY"
# Remove the suggestion
unset POSTDISPLAY
# Call the original `accept-line` to handle syntax highlighting or
# other potential custom behavior
_zsh_autosuggest_invoke_original_widget "accept-line"
}
# Partially accept the suggestion
_zsh_autosuggest_partial_accept() {
local -i retval cursor_loc
# Save the contents of the buffer so we can restore later if needed
local original_buffer="$BUFFER"
# Temporarily accept the suggestion.
BUFFER="$BUFFER$POSTDISPLAY"
# Original widget moves the cursor
_zsh_autosuggest_invoke_original_widget $@
retval=$?
# Normalize cursor location across vi/emacs modes
cursor_loc=$CURSOR
if [[ "$KEYMAP" = "vicmd" ]]; then
cursor_loc=$((cursor_loc + 1))
fi
# If we've moved past the end of the original buffer
if (( $cursor_loc > $#original_buffer )); then
# Set POSTDISPLAY to text right of the cursor
POSTDISPLAY="${BUFFER[$(($cursor_loc + 1)),$#BUFFER]}"
# Clip the buffer at the cursor
BUFFER="${BUFFER[1,$cursor_loc]}"
else
# Restore the original buffer
BUFFER="$original_buffer"
fi
return $retval
}
() {
typeset -ga _ZSH_AUTOSUGGEST_BUILTIN_ACTIONS
_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS=(
clear
fetch
suggest
accept
execute
enable
disable
toggle
)
local action
for action in $_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS modify partial_accept; do
eval "_zsh_autosuggest_widget_$action() {
local -i retval
_zsh_autosuggest_highlight_reset
_zsh_autosuggest_$action \$@
retval=\$?
_zsh_autosuggest_highlight_apply
zle -R
return \$retval
}"
done
for action in $_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS; do
zle -N autosuggest-$action _zsh_autosuggest_widget_$action
done
}

View File

@ -0,0 +1 @@
source ${0:A:h}/zsh-autosuggestions.zsh

View File

@ -0,0 +1,864 @@
# Fish-like fast/unobtrusive autosuggestions for zsh.
# https://github.com/zsh-users/zsh-autosuggestions
# v0.7.0
# Copyright (c) 2013 Thiago de Arruda
# Copyright (c) 2016-2021 Eric Freese
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#--------------------------------------------------------------------#
# Global Configuration Variables #
#--------------------------------------------------------------------#
# Color to use when highlighting suggestion
# Uses format of `region_highlight`
# More info: http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Zle-Widgets
(( ! ${+ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE} )) &&
typeset -g ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE="fg=8"
# Prefix to use when saving original versions of bound widgets
(( ! ${+ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX} )) &&
typeset -g ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX=autosuggest-orig-
# Strategies to use to fetch a suggestion
# Will try each strategy in order until a suggestion is returned
(( ! ${+ZSH_AUTOSUGGEST_STRATEGY} )) && {
typeset -ga ZSH_AUTOSUGGEST_STRATEGY
ZSH_AUTOSUGGEST_STRATEGY=(history)
}
# Widgets that clear the suggestion
(( ! ${+ZSH_AUTOSUGGEST_CLEAR_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_CLEAR_WIDGETS
ZSH_AUTOSUGGEST_CLEAR_WIDGETS=(
history-search-forward
history-search-backward
history-beginning-search-forward
history-beginning-search-backward
history-substring-search-up
history-substring-search-down
up-line-or-beginning-search
down-line-or-beginning-search
up-line-or-history
down-line-or-history
accept-line
copy-earlier-word
)
}
# Widgets that accept the entire suggestion
(( ! ${+ZSH_AUTOSUGGEST_ACCEPT_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_ACCEPT_WIDGETS
ZSH_AUTOSUGGEST_ACCEPT_WIDGETS=(
forward-char
end-of-line
vi-forward-char
vi-end-of-line
vi-add-eol
)
}
# Widgets that accept the entire suggestion and execute it
(( ! ${+ZSH_AUTOSUGGEST_EXECUTE_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_EXECUTE_WIDGETS
ZSH_AUTOSUGGEST_EXECUTE_WIDGETS=(
)
}
# Widgets that accept the suggestion as far as the cursor moves
(( ! ${+ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS
ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS=(
forward-word
emacs-forward-word
vi-forward-word
vi-forward-word-end
vi-forward-blank-word
vi-forward-blank-word-end
vi-find-next-char
vi-find-next-char-skip
)
}
# Widgets that should be ignored (globbing supported but must be escaped)
(( ! ${+ZSH_AUTOSUGGEST_IGNORE_WIDGETS} )) && {
typeset -ga ZSH_AUTOSUGGEST_IGNORE_WIDGETS
ZSH_AUTOSUGGEST_IGNORE_WIDGETS=(
orig-\*
beep
run-help
set-local-history
which-command
yank
yank-pop
zle-\*
)
}
# Pty name for capturing completions for completion suggestion strategy
(( ! ${+ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME} )) &&
typeset -g ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME=zsh_autosuggest_completion_pty
#--------------------------------------------------------------------#
# Utility Functions #
#--------------------------------------------------------------------#
_zsh_autosuggest_escape_command() {
setopt localoptions EXTENDED_GLOB
# Escape special chars in the string (requires EXTENDED_GLOB)
echo -E "${1//(#m)[\"\'\\()\[\]|*?~]/\\$MATCH}"
}
#--------------------------------------------------------------------#
# Widget Helpers #
#--------------------------------------------------------------------#
_zsh_autosuggest_incr_bind_count() {
typeset -gi bind_count=$((_ZSH_AUTOSUGGEST_BIND_COUNTS[$1]+1))
_ZSH_AUTOSUGGEST_BIND_COUNTS[$1]=$bind_count
}
# Bind a single widget to an autosuggest widget, saving a reference to the original widget
_zsh_autosuggest_bind_widget() {
typeset -gA _ZSH_AUTOSUGGEST_BIND_COUNTS
local widget=$1
local autosuggest_action=$2
local prefix=$ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX
local -i bind_count
# Save a reference to the original widget
case $widgets[$widget] in
# Already bound
user:_zsh_autosuggest_(bound|orig)_*)
bind_count=$((_ZSH_AUTOSUGGEST_BIND_COUNTS[$widget]))
;;
# User-defined widget
user:*)
_zsh_autosuggest_incr_bind_count $widget
zle -N $prefix$bind_count-$widget ${widgets[$widget]#*:}
;;
# Built-in widget
builtin)
_zsh_autosuggest_incr_bind_count $widget
eval "_zsh_autosuggest_orig_${(q)widget}() { zle .${(q)widget} }"
zle -N $prefix$bind_count-$widget _zsh_autosuggest_orig_$widget
;;
# Completion widget
completion:*)
_zsh_autosuggest_incr_bind_count $widget
eval "zle -C $prefix$bind_count-${(q)widget} ${${(s.:.)widgets[$widget]}[2,3]}"
;;
esac
# Pass the original widget's name explicitly into the autosuggest
# function. Use this passed in widget name to call the original
# widget instead of relying on the $WIDGET variable being set
# correctly. $WIDGET cannot be trusted because other plugins call
# zle without the `-w` flag (e.g. `zle self-insert` instead of
# `zle self-insert -w`).
eval "_zsh_autosuggest_bound_${bind_count}_${(q)widget}() {
_zsh_autosuggest_widget_$autosuggest_action $prefix$bind_count-${(q)widget} \$@
}"
# Create the bound widget
zle -N -- $widget _zsh_autosuggest_bound_${bind_count}_$widget
}
# Map all configured widgets to the right autosuggest widgets
_zsh_autosuggest_bind_widgets() {
emulate -L zsh
local widget
local ignore_widgets
ignore_widgets=(
.\*
_\*
${_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS/#/autosuggest-}
$ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX\*
$ZSH_AUTOSUGGEST_IGNORE_WIDGETS
)
# Find every widget we might want to bind and bind it appropriately
for widget in ${${(f)"$(builtin zle -la)"}:#${(j:|:)~ignore_widgets}}; do
if [[ -n ${ZSH_AUTOSUGGEST_CLEAR_WIDGETS[(r)$widget]} ]]; then
_zsh_autosuggest_bind_widget $widget clear
elif [[ -n ${ZSH_AUTOSUGGEST_ACCEPT_WIDGETS[(r)$widget]} ]]; then
_zsh_autosuggest_bind_widget $widget accept
elif [[ -n ${ZSH_AUTOSUGGEST_EXECUTE_WIDGETS[(r)$widget]} ]]; then
_zsh_autosuggest_bind_widget $widget execute
elif [[ -n ${ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS[(r)$widget]} ]]; then
_zsh_autosuggest_bind_widget $widget partial_accept
else
# Assume any unspecified widget might modify the buffer
_zsh_autosuggest_bind_widget $widget modify
fi
done
}
# Given the name of an original widget and args, invoke it, if it exists
_zsh_autosuggest_invoke_original_widget() {
# Do nothing unless called with at least one arg
(( $# )) || return 0
local original_widget_name="$1"
shift
if (( ${+widgets[$original_widget_name]} )); then
zle $original_widget_name -- $@
fi
}
#--------------------------------------------------------------------#
# Highlighting #
#--------------------------------------------------------------------#
# If there was a highlight, remove it
_zsh_autosuggest_highlight_reset() {
typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT
if [[ -n "$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT" ]]; then
region_highlight=("${(@)region_highlight:#$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT}")
unset _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT
fi
}
# If there's a suggestion, highlight it
_zsh_autosuggest_highlight_apply() {
typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT
if (( $#POSTDISPLAY )); then
typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT="$#BUFFER $(($#BUFFER + $#POSTDISPLAY)) $ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE"
region_highlight+=("$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT")
else
unset _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT
fi
}
#--------------------------------------------------------------------#
# Autosuggest Widget Implementations #
#--------------------------------------------------------------------#
# Disable suggestions
_zsh_autosuggest_disable() {
typeset -g _ZSH_AUTOSUGGEST_DISABLED
_zsh_autosuggest_clear
}
# Enable suggestions
_zsh_autosuggest_enable() {
unset _ZSH_AUTOSUGGEST_DISABLED
if (( $#BUFFER )); then
_zsh_autosuggest_fetch
fi
}
# Toggle suggestions (enable/disable)
_zsh_autosuggest_toggle() {
if (( ${+_ZSH_AUTOSUGGEST_DISABLED} )); then
_zsh_autosuggest_enable
else
_zsh_autosuggest_disable
fi
}
# Clear the suggestion
_zsh_autosuggest_clear() {
# Remove the suggestion
unset POSTDISPLAY
_zsh_autosuggest_invoke_original_widget $@
}
# Modify the buffer and get a new suggestion
_zsh_autosuggest_modify() {
local -i retval
# Only available in zsh >= 5.4
local -i KEYS_QUEUED_COUNT
# Save the contents of the buffer/postdisplay
local orig_buffer="$BUFFER"
local orig_postdisplay="$POSTDISPLAY"
# Clear suggestion while waiting for next one
unset POSTDISPLAY
# Original widget may modify the buffer
_zsh_autosuggest_invoke_original_widget $@
retval=$?
emulate -L zsh
# Don't fetch a new suggestion if there's more input to be read immediately
if (( $PENDING > 0 || $KEYS_QUEUED_COUNT > 0 )); then
POSTDISPLAY="$orig_postdisplay"
return $retval
fi
# Optimize if manually typing in the suggestion or if buffer hasn't changed
if [[ "$BUFFER" = "$orig_buffer"* && "$orig_postdisplay" = "${BUFFER:$#orig_buffer}"* ]]; then
POSTDISPLAY="${orig_postdisplay:$(($#BUFFER - $#orig_buffer))}"
return $retval
fi
# Bail out if suggestions are disabled
if (( ${+_ZSH_AUTOSUGGEST_DISABLED} )); then
return $?
fi
# Get a new suggestion if the buffer is not empty after modification
if (( $#BUFFER > 0 )); then
if [[ -z "$ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE" ]] || (( $#BUFFER <= $ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE )); then
_zsh_autosuggest_fetch
fi
fi
return $retval
}
# Fetch a new suggestion based on what's currently in the buffer
_zsh_autosuggest_fetch() {
if (( ${+ZSH_AUTOSUGGEST_USE_ASYNC} )); then
_zsh_autosuggest_async_request "$BUFFER"
else
local suggestion
_zsh_autosuggest_fetch_suggestion "$BUFFER"
_zsh_autosuggest_suggest "$suggestion"
fi
}
# Offer a suggestion
_zsh_autosuggest_suggest() {
emulate -L zsh
local suggestion="$1"
if [[ -n "$suggestion" ]] && (( $#BUFFER )); then
POSTDISPLAY="${suggestion#$BUFFER}"
else
unset POSTDISPLAY
fi
}
# Accept the entire suggestion
_zsh_autosuggest_accept() {
local -i retval max_cursor_pos=$#BUFFER
# When vicmd keymap is active, the cursor can't move all the way
# to the end of the buffer
if [[ "$KEYMAP" = "vicmd" ]]; then
max_cursor_pos=$((max_cursor_pos - 1))
fi
# If we're not in a valid state to accept a suggestion, just run the
# original widget and bail out
if (( $CURSOR != $max_cursor_pos || !$#POSTDISPLAY )); then
_zsh_autosuggest_invoke_original_widget $@
return
fi
# Only accept if the cursor is at the end of the buffer
# Add the suggestion to the buffer
BUFFER="$BUFFER$POSTDISPLAY"
# Remove the suggestion
unset POSTDISPLAY
# Run the original widget before manually moving the cursor so that the
# cursor movement doesn't make the widget do something unexpected
_zsh_autosuggest_invoke_original_widget $@
retval=$?
# Move the cursor to the end of the buffer
if [[ "$KEYMAP" = "vicmd" ]]; then
CURSOR=$(($#BUFFER - 1))
else
CURSOR=$#BUFFER
fi
return $retval
}
# Accept the entire suggestion and execute it
_zsh_autosuggest_execute() {
# Add the suggestion to the buffer
BUFFER="$BUFFER$POSTDISPLAY"
# Remove the suggestion
unset POSTDISPLAY
# Call the original `accept-line` to handle syntax highlighting or
# other potential custom behavior
_zsh_autosuggest_invoke_original_widget "accept-line"
}
# Partially accept the suggestion
_zsh_autosuggest_partial_accept() {
local -i retval cursor_loc
# Save the contents of the buffer so we can restore later if needed
local original_buffer="$BUFFER"
# Temporarily accept the suggestion.
BUFFER="$BUFFER$POSTDISPLAY"
# Original widget moves the cursor
_zsh_autosuggest_invoke_original_widget $@
retval=$?
# Normalize cursor location across vi/emacs modes
cursor_loc=$CURSOR
if [[ "$KEYMAP" = "vicmd" ]]; then
cursor_loc=$((cursor_loc + 1))
fi
# If we've moved past the end of the original buffer
if (( $cursor_loc > $#original_buffer )); then
# Set POSTDISPLAY to text right of the cursor
POSTDISPLAY="${BUFFER[$(($cursor_loc + 1)),$#BUFFER]}"
# Clip the buffer at the cursor
BUFFER="${BUFFER[1,$cursor_loc]}"
else
# Restore the original buffer
BUFFER="$original_buffer"
fi
return $retval
}
() {
typeset -ga _ZSH_AUTOSUGGEST_BUILTIN_ACTIONS
_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS=(
clear
fetch
suggest
accept
execute
enable
disable
toggle
)
local action
for action in $_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS modify partial_accept; do
eval "_zsh_autosuggest_widget_$action() {
local -i retval
_zsh_autosuggest_highlight_reset
_zsh_autosuggest_$action \$@
retval=\$?
_zsh_autosuggest_highlight_apply
zle -R
return \$retval
}"
done
for action in $_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS; do
zle -N autosuggest-$action _zsh_autosuggest_widget_$action
done
}
#--------------------------------------------------------------------#
# Completion Suggestion Strategy #
#--------------------------------------------------------------------#
# Fetches a suggestion from the completion engine
#
_zsh_autosuggest_capture_postcompletion() {
# Always insert the first completion into the buffer
compstate[insert]=1
# Don't list completions
unset 'compstate[list]'
}
_zsh_autosuggest_capture_completion_widget() {
# Add a post-completion hook to be called after all completions have been
# gathered. The hook can modify compstate to affect what is done with the
# gathered completions.
local -a +h comppostfuncs
comppostfuncs=(_zsh_autosuggest_capture_postcompletion)
# Only capture completions at the end of the buffer
CURSOR=$#BUFFER
# Run the original widget wrapping `.complete-word` so we don't
# recursively try to fetch suggestions, since our pty is forked
# after autosuggestions is initialized.
zle -- ${(k)widgets[(r)completion:.complete-word:_main_complete]}
if is-at-least 5.0.3; then
# Don't do any cr/lf transformations. We need to do this immediately before
# output because if we do it in setup, onlcr will be re-enabled when we enter
# vared in the async code path. There is a bug in zpty module in older versions
# where the tty is not properly attached to the pty slave, resulting in stty
# getting stopped with a SIGTTOU. See zsh-workers thread 31660 and upstream
# commit f75904a38
stty -onlcr -ocrnl -F /dev/tty
fi
# The completion has been added, print the buffer as the suggestion
echo -nE - $'\0'$BUFFER$'\0'
}
zle -N autosuggest-capture-completion _zsh_autosuggest_capture_completion_widget
_zsh_autosuggest_capture_setup() {
# There is a bug in zpty module in older zsh versions by which a
# zpty that exits will kill all zpty processes that were forked
# before it. Here we set up a zsh exit hook to SIGKILL the zpty
# process immediately, before it has a chance to kill any other
# zpty processes.
if ! is-at-least 5.4; then
zshexit() {
# The zsh builtin `kill` fails sometimes in older versions
# https://unix.stackexchange.com/a/477647/156673
kill -KILL $$ 2>&- || command kill -KILL $$
# Block for long enough for the signal to come through
sleep 1
}
fi
# Try to avoid any suggestions that wouldn't match the prefix
zstyle ':completion:*' matcher-list ''
zstyle ':completion:*' path-completion false
zstyle ':completion:*' max-errors 0 not-numeric
bindkey '^I' autosuggest-capture-completion
}
_zsh_autosuggest_capture_completion_sync() {
_zsh_autosuggest_capture_setup
zle autosuggest-capture-completion
}
_zsh_autosuggest_capture_completion_async() {
_zsh_autosuggest_capture_setup
zmodload zsh/parameter 2>/dev/null || return # For `$functions`
# Make vared completion work as if for a normal command line
# https://stackoverflow.com/a/7057118/154703
autoload +X _complete
functions[_original_complete]=$functions[_complete]
function _complete() {
unset 'compstate[vared]'
_original_complete "$@"
}
# Open zle with buffer set so we can capture completions for it
vared 1
}
_zsh_autosuggest_strategy_completion() {
# Reset options to defaults and enable LOCAL_OPTIONS
emulate -L zsh
# Enable extended glob for completion ignore pattern
setopt EXTENDED_GLOB
typeset -g suggestion
local line REPLY
# Exit if we don't have completions
whence compdef >/dev/null || return
# Exit if we don't have zpty
zmodload zsh/zpty 2>/dev/null || return
# Exit if our search string matches the ignore pattern
[[ -n "$ZSH_AUTOSUGGEST_COMPLETION_IGNORE" ]] && [[ "$1" == $~ZSH_AUTOSUGGEST_COMPLETION_IGNORE ]] && return
# Zle will be inactive if we are in async mode
if zle; then
zpty $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME _zsh_autosuggest_capture_completion_sync
else
zpty $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME _zsh_autosuggest_capture_completion_async "\$1"
zpty -w $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME $'\t'
fi
{
# The completion result is surrounded by null bytes, so read the
# content between the first two null bytes.
zpty -r $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME line '*'$'\0''*'$'\0'
# Extract the suggestion from between the null bytes. On older
# versions of zsh (older than 5.3), we sometimes get extra bytes after
# the second null byte, so trim those off the end.
# See http://www.zsh.org/mla/workers/2015/msg03290.html
suggestion="${${(@0)line}[2]}"
} always {
# Destroy the pty
zpty -d $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME
}
}
#--------------------------------------------------------------------#
# History Suggestion Strategy #
#--------------------------------------------------------------------#
# Suggests the most recent history item that matches the given
# prefix.
#
_zsh_autosuggest_strategy_history() {
# Reset options to defaults and enable LOCAL_OPTIONS
emulate -L zsh
# Enable globbing flags so that we can use (#m) and (x~y) glob operator
setopt EXTENDED_GLOB
# Escape backslashes and all of the glob operators so we can use
# this string as a pattern to search the $history associative array.
# - (#m) globbing flag enables setting references for match data
# TODO: Use (b) flag when we can drop support for zsh older than v5.0.8
local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}"
# Get the history items that match the prefix, excluding those that match
# the ignore pattern
local pattern="$prefix*"
if [[ -n $ZSH_AUTOSUGGEST_HISTORY_IGNORE ]]; then
pattern="($pattern)~($ZSH_AUTOSUGGEST_HISTORY_IGNORE)"
fi
# Give the first history item matching the pattern as the suggestion
# - (r) subscript flag makes the pattern match on values
typeset -g suggestion="${history[(r)$pattern]}"
}
#--------------------------------------------------------------------#
# Match Previous Command Suggestion Strategy #
#--------------------------------------------------------------------#
# Suggests the most recent history item that matches the given
# prefix and whose preceding history item also matches the most
# recently executed command.
#
# For example, suppose your history has the following entries:
# - pwd
# - ls foo
# - ls bar
# - pwd
#
# Given the history list above, when you type 'ls', the suggestion
# will be 'ls foo' rather than 'ls bar' because your most recently
# executed command (pwd) was previously followed by 'ls foo'.
#
# Note that this strategy won't work as expected with ZSH options that don't
# preserve the history order such as `HIST_IGNORE_ALL_DUPS` or
# `HIST_EXPIRE_DUPS_FIRST`.
_zsh_autosuggest_strategy_match_prev_cmd() {
# Reset options to defaults and enable LOCAL_OPTIONS
emulate -L zsh
# Enable globbing flags so that we can use (#m) and (x~y) glob operator
setopt EXTENDED_GLOB
# TODO: Use (b) flag when we can drop support for zsh older than v5.0.8
local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}"
# Get the history items that match the prefix, excluding those that match
# the ignore pattern
local pattern="$prefix*"
if [[ -n $ZSH_AUTOSUGGEST_HISTORY_IGNORE ]]; then
pattern="($pattern)~($ZSH_AUTOSUGGEST_HISTORY_IGNORE)"
fi
# Get all history event numbers that correspond to history
# entries that match the pattern
local history_match_keys
history_match_keys=(${(k)history[(R)$~pattern]})
# By default we use the first history number (most recent history entry)
local histkey="${history_match_keys[1]}"
# Get the previously executed command
local prev_cmd="$(_zsh_autosuggest_escape_command "${history[$((HISTCMD-1))]}")"
# Iterate up to the first 200 history event numbers that match $prefix
for key in "${(@)history_match_keys[1,200]}"; do
# Stop if we ran out of history
[[ $key -gt 1 ]] || break
# See if the history entry preceding the suggestion matches the
# previous command, and use it if it does
if [[ "${history[$((key - 1))]}" == "$prev_cmd" ]]; then
histkey="$key"
break
fi
done
# Give back the matched history entry
typeset -g suggestion="$history[$histkey]"
}
#--------------------------------------------------------------------#
# Fetch Suggestion #
#--------------------------------------------------------------------#
# Loops through all specified strategies and returns a suggestion
# from the first strategy to provide one.
#
_zsh_autosuggest_fetch_suggestion() {
typeset -g suggestion
local -a strategies
local strategy
# Ensure we are working with an array
strategies=(${=ZSH_AUTOSUGGEST_STRATEGY})
for strategy in $strategies; do
# Try to get a suggestion from this strategy
_zsh_autosuggest_strategy_$strategy "$1"
# Ensure the suggestion matches the prefix
[[ "$suggestion" != "$1"* ]] && unset suggestion
# Break once we've found a valid suggestion
[[ -n "$suggestion" ]] && break
done
}
#--------------------------------------------------------------------#
# Async #
#--------------------------------------------------------------------#
_zsh_autosuggest_async_request() {
zmodload zsh/system 2>/dev/null # For `$sysparams`
typeset -g _ZSH_AUTOSUGGEST_ASYNC_FD _ZSH_AUTOSUGGEST_CHILD_PID
# If we've got a pending request, cancel it
if [[ -n "$_ZSH_AUTOSUGGEST_ASYNC_FD" ]] && { true <&$_ZSH_AUTOSUGGEST_ASYNC_FD } 2>/dev/null; then
# Close the file descriptor and remove the handler
exec {_ZSH_AUTOSUGGEST_ASYNC_FD}<&-
zle -F $_ZSH_AUTOSUGGEST_ASYNC_FD
# We won't know the pid unless the user has zsh/system module installed
if [[ -n "$_ZSH_AUTOSUGGEST_CHILD_PID" ]]; then
# Zsh will make a new process group for the child process only if job
# control is enabled (MONITOR option)
if [[ -o MONITOR ]]; then
# Send the signal to the process group to kill any processes that may
# have been forked by the suggestion strategy
kill -TERM -$_ZSH_AUTOSUGGEST_CHILD_PID 2>/dev/null
else
# Kill just the child process since it wasn't placed in a new process
# group. If the suggestion strategy forked any child processes they may
# be orphaned and left behind.
kill -TERM $_ZSH_AUTOSUGGEST_CHILD_PID 2>/dev/null
fi
fi
fi
# Fork a process to fetch a suggestion and open a pipe to read from it
exec {_ZSH_AUTOSUGGEST_ASYNC_FD}< <(
# Tell parent process our pid
echo $sysparams[pid]
# Fetch and print the suggestion
local suggestion
_zsh_autosuggest_fetch_suggestion "$1"
echo -nE "$suggestion"
)
# There's a weird bug here where ^C stops working unless we force a fork
# See https://github.com/zsh-users/zsh-autosuggestions/issues/364
autoload -Uz is-at-least
is-at-least 5.8 || command true
# Read the pid from the child process
read _ZSH_AUTOSUGGEST_CHILD_PID <&$_ZSH_AUTOSUGGEST_ASYNC_FD
# When the fd is readable, call the response handler
zle -F "$_ZSH_AUTOSUGGEST_ASYNC_FD" _zsh_autosuggest_async_response
}
# Called when new data is ready to be read from the pipe
# First arg will be fd ready for reading
# Second arg will be passed in case of error
_zsh_autosuggest_async_response() {
emulate -L zsh
local suggestion
if [[ -z "$2" || "$2" == "hup" ]]; then
# Read everything from the fd and give it as a suggestion
IFS='' read -rd '' -u $1 suggestion
zle autosuggest-suggest -- "$suggestion"
# Close the fd
exec {1}<&-
fi
# Always remove the handler
zle -F "$1"
}
#--------------------------------------------------------------------#
# Start #
#--------------------------------------------------------------------#
# Start the autosuggestion widgets
_zsh_autosuggest_start() {
# By default we re-bind widgets on every precmd to ensure we wrap other
# wrappers. Specifically, highlighting breaks if our widgets are wrapped by
# zsh-syntax-highlighting widgets. This also allows modifications to the
# widget list variables to take effect on the next precmd. However this has
# a decent performance hit, so users can set ZSH_AUTOSUGGEST_MANUAL_REBIND
# to disable the automatic re-binding.
if (( ${+ZSH_AUTOSUGGEST_MANUAL_REBIND} )); then
add-zsh-hook -d precmd _zsh_autosuggest_start
fi
_zsh_autosuggest_bind_widgets
}
# Mark for auto-loading the functions that we use
autoload -Uz add-zsh-hook is-at-least
# Automatically enable asynchronous mode in newer versions of zsh. Disable for
# older versions because there is a bug when using async mode where ^C does not
# work immediately after fetching a suggestion.
# See https://github.com/zsh-users/zsh-autosuggestions/issues/364
if is-at-least 5.0.8; then
typeset -g ZSH_AUTOSUGGEST_USE_ASYNC=
fi
# Start the autosuggestion widgets on the next precmd
add-zsh-hook precmd _zsh_autosuggest_start

View File

@ -0,0 +1,42 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: bug
assignees: ''
---
#### Describe the bug
A clear and concise description of what the bug is.
I can make sure:
- [ ] I am using the latest version of fzf-tab
- [ ] this is the minimal zshrc which can reproduce this bug
- [ ] fzf-tab is loaded after `compinit`
- [ ] fzf-tab is loaded after plugins which will wrap <kbd>Tab</kbd>, like [junegunn/fzf/completion.zsh](https://github.com/junegunn/fzf/blob/master/shell/completion.zsh)
- [ ] fzf-tab is loaded before zsh-autosuggestions, zsh-syntax-highlighting and fast-syntax-highlighting.
#### To Reproduce
Steps to reproduce the behavior:
1. Type '...'
2. Press <kbd>Tab</kbd>
4. See error
#### Expected behavior
A clear and concise description of what you expected to happen.
#### Screenshots
If applicable, add screenshots to help explain your problem.
#### Environment:
- OS: [e.g. Arch Linux]
- zsh version: [e.g. 5.8.1]
#### Minimal zshrc
If applicable, add a minimal zshrc to help us analyze.
#### Log
If applicable, use `C-x .` to trigger completion and provide the log.
If there are only three lines in your log, please make sure your fzf-tab is loaded with the correct order (see the checklist above).

View File

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[FR]"
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -0,0 +1,11 @@
---
name: Question
about: Ask a question about fzf-tab
title: "[Q]"
labels: question
assignees: ''
---
**Describe your question**
A clear and concise description of your question.

View File

@ -0,0 +1,34 @@
name: test on linux
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest]
steps:
- name: checkout
uses: actions/checkout@v1
with:
fetch-depth: 1
- name: install zsh
run: sudo apt-get install -y zsh
- name: test completion
run: cd test && zsh -f runtests.zsh fzftab.ztst
- name: build binary module
run: zsh -fc 'source ./fzf-tab.zsh && build-fzf-tab-module'
- name: test binary module
run: cd test && zsh -f runtests.zsh fzftab.ztst

View File

@ -0,0 +1,30 @@
name: test on macOS
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
test:
runs-on: macos-latest
steps:
- name: checkout
uses: actions/checkout@v1
with:
fetch-depth: 1
- run: brew install autoconf automake libtool
# FIXME: test on macOS
#- name: test completion
# run: cd test && zsh -f runtests.zsh fzftab.ztst
- name: build binary module
run: zsh -fc 'source ./fzf-tab.zsh && build-fzf-tab-module'
#- name: test binary module
# run: cd test && zsh -f runtests.zsh fzftab.ztst

View File

@ -0,0 +1,45 @@
name: test on different zsh versions
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# TODO: test fzf version?
zsh_version:
- 5.3.1
- 5.4.2
- 5.5.1
- 5.6.2
- 5.7.1
- 5.8
- 5.9
container:
image: zshusers/zsh:${{ matrix.zsh_version }}
steps:
- name: checkout
uses: actions/checkout@v1
with:
fetch-depth: 1
- name: install dependencies
run: apt update && apt-get install -y git build-essential autoconf libncurses-dev
- name: test completion
run: cd test && zsh -f runtests.zsh fzftab.ztst
- name: build binary module
run: zsh -fc 'source ./fzf-tab.zsh && build-fzf-tab-module'
- name: test binary module
run: cd test && zsh -f runtests.zsh fzftab.ztst

1
.zsh/zsh-fzf-tab/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.zwc

21
.zsh/zsh-fzf-tab/LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019-2024 Aloxaf
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

163
.zsh/zsh-fzf-tab/README.md Normal file
View File

@ -0,0 +1,163 @@
# fzf-tab
[![CI](https://github.com/Aloxaf/fzf-tab/workflows/ci/badge.svg)](https://github.com/Aloxaf/fzf-tab/actions?query=workflow%3Aci)
[![GitHub license](https://img.shields.io/github/license/Aloxaf/fzf-tab)](https://github.com/Aloxaf/fzf-tab/blob/master/LICENSE)
Replace zsh's default completion selection menu with fzf!
[![asciicast](https://asciinema.org/a/293849.svg)](https://asciinema.org/a/293849)
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc -->
**Table of Contents**
- [fzf-tab](#fzf-tab)
- [Install](#install)
- [Manual](#manual)
- [Antigen](#antigen)
- [Zinit](#zinit)
- [Oh-My-Zsh](#oh-my-zsh)
- [Prezto](#prezto)
- [Usage](#usage)
- [Configure](#configure)
- [Tmux](#tmux)
- [Binary module](#binary-module)
- [Difference from other plugins](#difference-from-other-plugins)
- [Compatibility with other plugins](#compatibility-with-other-plugins)
- [Related projects](#related-projects)
<!-- markdown-toc end -->
# Install
> [!IMPORTANT]
>
> 1. make sure [fzf](https://github.com/junegunn/fzf) is installed
> 2. fzf-tab needs to be loaded after `compinit`, but before plugins which will wrap widgets, such as [zsh-autosuggestions](https://github.com/zsh-users/zsh-autosuggestions) or [fast-syntax-highlighting](https://github.com/zdharma-continuum/fast-syntax-highlighting)
> 3. Completions should be configured before `compinit`, as stated in the [zsh-completions manual installation guide](https://github.com/zsh-users/zsh-completions#manual-installation).
### Manual
First, clone this repository.
```zsh
git clone https://github.com/Aloxaf/fzf-tab ~/somewhere
```
Then add the following line to your `~/.zshrc`.
```zsh
autoload -U compinit; compinit
source ~/somewhere/fzf-tab.plugin.zsh
```
### Antigen
```zsh
antigen bundle Aloxaf/fzf-tab
```
### Zinit
```zsh
zinit light Aloxaf/fzf-tab
```
### Oh-My-Zsh
Clone this repository to your custom directory and then add `fzf-tab` to your plugin list.
```zsh
git clone https://github.com/Aloxaf/fzf-tab ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/fzf-tab
```
### Prezto
Clone this repository to your contrib directory and then add `fzf-tab` to your module list in `.zpreztorc`.
```zsh
git clone https://github.com/Aloxaf/fzf-tab $ZPREZTODIR/contrib/fzf-tab
```
# Usage
Just press <kbd>Tab</kbd> as usual~
Available keybindings:
- <kbd>Ctrl</kdb>+<kdb>Space</kbd>: select multiple results, can be configured by `fzf-bindings` tag
- <kbd>F1</kbd>/<kbd>F2</kbd>: switch between groups, can be configured by `switch-group` tag
- <kbd>/</kbd>: trigger continuous completion (useful when completing a deep path), can be configured by `continuous-trigger` tag
Available commands:
- `disable-fzf-tab`: disable fzf-tab and fallback to compsys
- `enable-fzf-tab`: enable fzf-tab
- `toggle-fzf-tab`: toggle the state of fzf-tab. This is also a zle widget.
## Configure
A common configuration is:
```zsh
# disable sort when completing `git checkout`
zstyle ':completion:*:git-checkout:*' sort false
# set descriptions format to enable group support
# NOTE: don't use escape sequences here, fzf-tab will ignore them
zstyle ':completion:*:descriptions' format '[%d]'
# set list-colors to enable filename colorizing
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
# force zsh not to show completion menu, which allows fzf-tab to capture the unambiguous prefix
zstyle ':completion:*' menu no
# preview directory's content with eza when completing cd
zstyle ':fzf-tab:complete:cd:*' fzf-preview 'eza -1 --color=always $realpath'
# switch group using `<` and `>`
zstyle ':fzf-tab:*' switch-group '<' '>'
```
## Tmux
If you're using tmux >= 3.2, we provide a script `ftb-tmux-popup` to make full use of it's "popup" feature.
```zsh
zstyle ':fzf-tab:*' fzf-command ftb-tmux-popup
```
BTW, you can also use this script outside the fzf-tab.
```zsh
ls | ftb-tmux-popup
```
[![asciicast](https://asciinema.org/a/367471.svg)](https://asciinema.org/a/367471)
For more information, please see [Wiki#Configuration](https://github.com/Aloxaf/fzf-tab/wiki/Configuration).
## Binary module
By default, fzf-tab uses [zsh-ls-colors](https://github.com/xPMo/zsh-ls-colors) to parse and apply ZLS_COLORS if you have set the `list-colors` tag.
However, it is a pure zsh script and is slow if you have too many files to colorize.
fzf-tab is shipped with a binary module to speed up this process. You can build it with `build-fzf-tab-module`, then it will be enabled automatically.
# Difference from other plugins
fzf-tab doesn't do "complete", it just shows you the results of the default completion system.
So it works EVERYWHERE (variables, function names, directory stack, in-word completion, etc.).
And most of your configuration for default completion system is still valid.
# Compatibility with other plugins
Some plugins may also bind "^I" to their custom widget, like [fzf/shell/completion.zsh](https://github.com/junegunn/fzf/blob/master/shell/completion.zsh) or [ohmyzsh/lib/completion.zsh](https://github.com/ohmyzsh/ohmyzsh/blob/master/lib/completion.zsh#L61-L73).
By default, fzf-tab will call the widget previously bound to "^I" to get the completion list. So there is no problem in most cases, unless fzf-tab is initialized before a plugin which doesn't handle the previous binding properly.
So if you find your fzf-tab doesn't work properly, **please make sure it is the last plugin to bind "^I"** (If you don't know what I mean, just put it to the end of your plugin list).
# Related projects
- https://github.com/lincheney/fzf-tab-completion (fzf tab completion for zsh, bash and GNU readline apps)

View File

@ -0,0 +1,3 @@
0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}"
0="${${(M)0:#/*}:-$PWD/$0}"
source "${0:A:h}/fzf-tab.zsh"

View File

@ -0,0 +1,440 @@
# temporarily change options
'builtin' 'local' '-a' '_ftb_opts'
[[ ! -o 'aliases' ]] || _ftb_opts+=('aliases')
[[ ! -o 'sh_glob' ]] || _ftb_opts+=('sh_glob')
[[ ! -o 'no_brace_expand' ]] || _ftb_opts+=('no_brace_expand')
'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand'
# disable aliases
typeset _ftb_aliases="$(builtin alias -Lm '[^+]*')"
builtin unalias -m '[^+]*'
# thanks Valodim/zsh-capture-completion
-ftb-compadd() {
# parse all options
local -A apre hpre dscrs _oad _mesg
local -a isfile _opts __ expl
zparseopts -a _opts P:=apre p:=hpre d:=dscrs X+:=expl O:=_oad A:=_oad D:=_oad f=isfile \
i: S: s: I: x:=_mesg r: R: W: F: M+: E: q e Q n U C \
J:=__ V:=__ a=__ l=__ k=__ o::=__ 1=__ 2=__
# store $curcontext for further usage
_ftb_curcontext=${curcontext#:}
# just delegate and leave if any of -O, -A or -D are given or fzf-tab is not enabled
# or fzf-tab is disabled in the current context
if (( $#_oad != 0 || ! IN_FZF_TAB )) \
|| { -ftb-zstyle -m disabled-on "any" } \
|| ({ -ftb-zstyle -m disabled-on "files" } && [[ -n $isfile ]]); then
builtin compadd "$@"
return
fi
# store matches in $__hits and descriptions in $__dscr
local -a __hits __dscr
if (( $#dscrs == 1 )); then
__dscr=( "${(@P)${(v)dscrs}}" )
fi
builtin compadd -A __hits -D __dscr "$@"
local ret=$?
if (( $#__hits == 0 )); then
if is-at-least 5.9 && (( $#_mesg != 0 )); then
builtin compadd -x $_mesg
fi
return $ret
fi
# only store the fist `-X`
expl=$expl[2]
# keep order of group description
[[ -n $expl ]] && _ftb_groups+=$expl
# store these values in _ftb_compcap
local -a keys=(apre hpre PREFIX SUFFIX IPREFIX ISUFFIX)
local key expanded __tmp_value=$'<\0>' # placeholder
for key in $keys; do
expanded=${(P)key}
if [[ -n $expanded ]]; then
__tmp_value+=$'\0'$key$'\0'$expanded
fi
done
if [[ -n $expl ]]; then
# store group index
__tmp_value+=$'\0group\0'$_ftb_groups[(ie)$expl]
fi
if [[ -n $isfile ]]; then
# NOTE: need a extra ${} here or ~ expansion won't work
__tmp_value+=$'\0realdir\0'${${(Qe)~${:-$IPREFIX$hpre}}}
fi
_opts+=("${(@kv)apre}" "${(@kv)hpre}" $isfile)
__tmp_value+=$'\0args\0'${(pj:\1:)_opts}
if (( $+builtins[fzf-tab-compcap-generate] )); then
fzf-tab-compcap-generate __hits __dscr __tmp_value
else
# dscr - the string to show to users
# word - the string to be inserted
local dscr word i
for i in {1..$#__hits}; do
word=$__hits[i] dscr=$__dscr[i]
if [[ -n $dscr ]]; then
dscr=${dscr//$'\n'}
elif [[ -n $word ]]; then
dscr=$word
fi
_ftb_compcap+=$dscr$'\2'$__tmp_value$'\0word\0'$word
done
fi
# tell zsh that the match is successful
builtin compadd "$@"
}
-ftb-zstyle() {
zstyle $1 ":fzf-tab:$_ftb_curcontext" ${@:2}
}
-ftb-complete() {
local -Ua _ftb_groups
local choice choices _ftb_curcontext continuous_trigger print_query accept_line bs=$'\2' nul=$'\0'
local ret=0
# must run with user options; don't move `emulate -L zsh` above this line
(( $+builtins[fzf-tab-compcap-generate] )) && fzf-tab-compcap-generate -i
COLUMNS=500 _ftb__main_complete "$@" || ret=$?
(( $+builtins[fzf-tab-compcap-generate] )) && fzf-tab-compcap-generate -o
emulate -L zsh -o extended_glob
local _ftb_query _ftb_complist=() _ftb_headers=() command opts
-ftb-generate-complist # sets `_ftb_complist`
-ftb-zstyle -s continuous-trigger continuous_trigger || {
[[ $OSTYPE == msys ]] && continuous_trigger=// || continuous_trigger=/
}
case $#_ftb_complist in
0) return 1;;
1)
choices=("EXPECT_KEY" "${_ftb_compcap[1]%$bs*}")
if (( _ftb_continue_last )); then
choices[1]=$continuous_trigger
fi
;;
*)
if (( ! _ftb_continue_last )) \
&& [[ $compstate[insert] == *"unambiguous" ]] \
&& [[ -n $compstate[unambiguous] ]] \
&& [[ "$compstate[unambiguous]" != "$compstate[quote]$IPREFIX$PREFIX$compstate[quote]" ]]; then
compstate[list]=
compstate[insert]=unambiguous
_ftb_finish=1
return 0
fi
-ftb-generate-query # sets `_ftb_query`
-ftb-generate-header # sets `_ftb_headers`
-ftb-zstyle -s print-query print_query || print_query=alt-enter
-ftb-zstyle -s accept-line accept_line
choices=("${(@f)"$(builtin print -rl -- $_ftb_headers $_ftb_complist | -ftb-fzf)"}")
ret=$?
# choices=(query_string expect_key returned_word)
# insert query string directly
if [[ $choices[2] == $print_query ]] || [[ -n $choices[1] && $#choices == 1 ]] ; then
local -A v=("${(@0)${_ftb_compcap[1]}}")
local -a args=("${(@ps:\1:)v[args]}")
[[ -z $args[1] ]] && args=() # don't pass an empty string
IPREFIX=$v[IPREFIX] PREFIX=$v[PREFIX] SUFFIX=$v[SUFFIX] ISUFFIX=$v[ISUFFIX]
# NOTE: should I use `-U` here?, ../f\tabcd -> ../abcd
builtin compadd "${args[@]:--Q}" -Q -- $choices[1]
compstate[list]=
compstate[insert]=
if (( $#choices[1] > 0 )); then
compstate[insert]='1'
[[ $RBUFFER == ' '* ]] || compstate[insert]+=' '
fi
_ftb_finish=1
return $ret
fi
choices[1]=()
choices=("${(@)${(@)choices%$nul*}#*$nul}")
unset CTXT
;;
esac
if [[ -n $choices[1] && $choices[1] == $continuous_trigger ]]; then
typeset -gi _ftb_continue=1
typeset -gi _ftb_continue_last=1
fi
if [[ -n $choices[1] && $choices[1] == $accept_line ]]; then
typeset -gi _ftb_accept=1
fi
choices[1]=()
_ftb_choices=("${(@)choices}")
compstate[list]=
compstate[insert]=
return $ret
}
_fzf-tab-apply() {
local choice bs=$'\2'
for choice in "$_ftb_choices[@]"; do
local -A v=("${(@0)${_ftb_compcap[(r)${(b)choice}$bs*]#*$bs}}")
local -a args=("${(@ps:\1:)v[args]}")
[[ -z $args[1] ]] && args=() # don't pass an empty string
IPREFIX=$v[IPREFIX] PREFIX=$v[PREFIX] SUFFIX=$v[SUFFIX] ISUFFIX=$v[ISUFFIX]
builtin compadd "${args[@]:--Q}" -Q -- "$v[word]"
done
compstate[list]=
if (( $#_ftb_choices == 1 )); then
compstate[insert]='1'
[[ $RBUFFER == ' '* ]] || compstate[insert]+=' '
elif (( $#_ftb_choices > 1 )); then
compstate[insert]='all'
fi
}
fzf-tab-debug() {
(( $+_ftb_debug_cnt )) || typeset -gi _ftb_debug_cnt
local tmp=${TMPPREFIX:-/tmp/zsh}-$$-fzf-tab-$(( ++_ftb_debug_cnt )).log
local -i debug_fd=-1 IN_FZF_TAB=1
{
exec {debug_fd}>&2 2>| $tmp
local -a debug_indent; debug_indent=( '%'{3..20}'(e. .)' )
local PROMPT4 PS4="${(j::)debug_indent}+%N:%i> "
functions -t -- -ftb-complete _fzf-tab-apply fzf-tab-complete
{
echo $ZSH_NAME $ZSH_VERSION
echo fzf-tab: $(-ftb-version)
typeset -p FZF_DEFAULT_OPTS
echo $commands[fzf] $(fzf --version)
} >&2
zle fzf-tab-complete
if (( debug_fd != -1 )); then
zle -M "fzf-tab-debug: Trace output left in $tmp"
fi
} always {
functions +t -- -ftb-complete _fzf-tab-apply fzf-tab-complete
(( debug_fd != -1 )) && exec 2>&$debug_fd {debug_fd}>&-
}
}
fzf-tab-complete() {
# this name must be ugly to avoid clashes
local -i _ftb_continue=1 _ftb_continue_last=0 _ftb_accept=0 ret=0
# hide the cursor until finishing completion, so that users won't see cursor up and down
# NOTE: MacOS Terminal doesn't support civis & cnorm
echoti civis >/dev/tty 2>/dev/null
while (( _ftb_continue )); do
local _ftb_choices=() _ftb_compcap=() _ftb_finish=0
_ftb_continue=0
local IN_FZF_TAB=1
{
zle .fzf-tab-orig-$_ftb_orig_widget || ret=$?
if (( ! ret && ! _ftb_finish )); then
zle _fzf-tab-apply || ret=$?
fi
} always {
IN_FZF_TAB=0
}
if (( _ftb_continue )); then
zle .split-undo
zle .reset-prompt
zle -R
zle fzf-tab-dummy
fi
done
echoti cnorm >/dev/tty 2>/dev/null
zle .redisplay
(( _ftb_accept )) && zle .accept-line
return $ret
}
# this function does nothing, it is used to be wrapped by other plugins like f-sy-h.
# this make it possible to call the wrapper function without causing any other side effects.
fzf-tab-dummy() { }
zle -N fzf-tab-debug
zle -N fzf-tab-complete
zle -N fzf-tab-dummy
# this is registered as a completion widget
# so that we can have a clean completion list to only insert the results user selected
zle -C _fzf-tab-apply complete-word _fzf-tab-apply
disable-fzf-tab() {
emulate -L zsh -o extended_glob
(( $+_ftb_orig_widget )) || return 0
bindkey '^I' $_ftb_orig_widget
case $_ftb_orig_list_grouped in
0) zstyle ':completion:*' list-grouped false ;;
1) zstyle ':completion:*' list-grouped true ;;
2) zstyle -d ':completion:*' list-grouped ;;
esac
unset _ftb_orig_widget _ftb_orig_list_groupded
# unhook compadd so that _approximate can work properply
unfunction compadd 2>/dev/null
functions[_main_complete]=$functions[_ftb__main_complete]
functions[_approximate]=$functions[_ftb__approximate]
# Don't remove .fzf-tab-orig-$_ftb_orig_widget as we won't be able to reliably
# create it if enable-fzf-tab is called again.
}
enable-fzf-tab() {
emulate -L zsh -o extended_glob
(( ! $+_ftb_orig_widget )) || disable-fzf-tab
typeset -g _ftb_orig_widget="${${$(builtin bindkey '^I')##* }:-expand-or-complete}"
if (( ! $+widgets[.fzf-tab-orig-$_ftb_orig_widget] )); then
# Widgets that get replaced by compinit.
local compinit_widgets=(
complete-word
delete-char-or-list
expand-or-complete
expand-or-complete-prefix
list-choices
menu-complete
menu-expand-or-complete
reverse-menu-complete
)
# Note: We prefix the name of the widget with '.' so that it doesn't get wrapped.
if [[ $widgets[$_ftb_orig_widget] == builtin &&
$compinit_widgets[(Ie)$_ftb_orig_widget] != 0 ]]; then
# We are initializing before compinit and being asked to fall back to a completion
# widget that isn't defined yet. Create our own copy of the widget ahead of time.
zle -C .fzf-tab-orig-$_ftb_orig_widget .$_ftb_orig_widget _main_complete
else
# Copy the widget before it's wrapped by zsh-autosuggestions and zsh-syntax-highlighting.
zle -A $_ftb_orig_widget .fzf-tab-orig-$_ftb_orig_widget
fi
fi
zstyle -t ':completion:*' list-grouped false
typeset -g _ftb_orig_list_grouped=$?
zstyle ':completion:*' list-grouped false
bindkey -M emacs '^I' fzf-tab-complete
bindkey -M viins '^I' fzf-tab-complete
bindkey -M emacs '^X.' fzf-tab-debug
bindkey -M viins '^X.' fzf-tab-debug
# make sure we can copy them
autoload +X -Uz _main_complete _approximate
# hook compadd
functions[compadd]=$functions[-ftb-compadd]
# hook _main_complete to trigger fzf-tab
functions[_ftb__main_complete]=$functions[_main_complete]
function _main_complete() { -ftb-complete "$@" }
# TODO: This is not a full support, see #47
# _approximate will also hook compadd
# let it call -ftb-compadd instead of builtin compadd so that fzf-tab can capture result
# make sure _approximate has been loaded.
functions[_ftb__approximate]=$functions[_approximate]
function _approximate() {
# if not called by fzf-tab, don't do anything with compadd
(( ! IN_FZF_TAB )) || unfunction compadd
_ftb__approximate
(( ! IN_FZF_TAB )) || functions[compadd]=$functions[-ftb-compadd]
}
}
toggle-fzf-tab() {
emulate -L zsh -o extended_glob
if (( $+_ftb_orig_widget )); then
disable-fzf-tab
else
enable-fzf-tab
fi
}
build-fzf-tab-module() {
{
pushd -q $FZF_TAB_HOME/modules
if -ftb-build-module $@; then
print -P "%F{green}%BThe module has been built successfully. Please restart zsh to apply it.%f%b"
else
print -P -u2 "%F{red}%BThe module building has failed. See the output above for details.%f%b"
return 1
fi
} always {
popd -q
}
}
zmodload zsh/zutil
zmodload zsh/mapfile
zmodload -F zsh/stat b:zstat
0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}"
0="${${(M)0:#/*}:-$PWD/$0}"
FZF_TAB_HOME="${0:A:h}"
source "$FZF_TAB_HOME"/lib/zsh-ls-colors/ls-colors.zsh fzf-tab-lscolors
typeset -ga _ftb_group_colors=(
$'\x1b[94m' $'\x1b[32m' $'\x1b[33m' $'\x1b[35m' $'\x1b[31m' $'\x1b[38;5;27m' $'\x1b[36m'
$'\x1b[38;5;100m' $'\x1b[38;5;98m' $'\x1b[91m' $'\x1b[38;5;80m' $'\x1b[92m'
$'\x1b[38;5;214m' $'\x1b[38;5;165m' $'\x1b[38;5;124m' $'\x1b[38;5;120m'
)
# init
() {
emulate -L zsh -o extended_glob
if (( ! $fpath[(I)$FZF_TAB_HOME/lib] )); then
fpath+=($FZF_TAB_HOME/lib)
fi
autoload -Uz is-at-least -- $FZF_TAB_HOME/lib/-#ftb*(:t)
if (( $+FZF_TAB_COMMAND || $+FZF_TAB_OPTS || $+FZF_TAB_QUERY || $+FZF_TAB_SINGLE_GROUP || $+fzf_tab_preview_init )) \
|| zstyle -m ":fzf-tab:*" command '*' \
|| zstyle -m ":fzf-tab:*" extra-opts '*'; then
print -P "%F{red}%B[fzf-tab] Sorry, your configuration is not supported anymore\n" \
"See https://github.com/Aloxaf/fzf-tab/pull/132 for more information%f%b"
fi
if [[ -n $FZF_TAB_HOME/modules/Src/aloxaf/fzftab.(so|bundle)(#qN) ]]; then
module_path+=("$FZF_TAB_HOME/modules/Src")
zmodload aloxaf/fzftab
if [[ $FZF_TAB_MODULE_VERSION != "0.2.2" ]]; then
zmodload -u aloxaf/fzftab
local rebuild
print -Pn "%F{yellow}fzftab module needs to be rebuild, rebuild now?[Y/n]:%f"
read -q rebuild
if [[ $rebuild == y ]]; then
build-fzf-tab-module
zmodload aloxaf/fzftab
fi
fi
fi
}
enable-fzf-tab
zle -N toggle-fzf-tab
# restore aliases
eval "$_ftb_aliases"
builtin unset _ftb_aliases
# restore options
(( ${#_ftb_opts} )) && setopt ${_ftb_opts[@]}
'builtin' 'unset' '_ftb_opts'

View File

@ -0,0 +1,30 @@
#!/hint/zsh
emulate -LR zsh -o extended_glob -o err_return
local zsh_version=${1:-${FZF_TAB_ZSH_SRC_VERSION:-$ZSH_VERSION}}
# macos check
local ret bundle nproc
[[ $OSTYPE == darwin* ]] && {
[[ -n ${module_path[1]}/**/*.bundle(#qN) ]] && bundle=true
nproc=$(sysctl -n hw.logicalcpu)
} || {
nproc=$(nproc)
}
# clone zsh source code if not exists
[[ -d ./zsh/$zsh_version ]] || {
git clone --depth=1 --branch zsh-$zsh_version https://github.com/zsh-users/zsh ./zsh/$zsh_version
}
ln -sf $PWD/Src/fzftab.c ./zsh/$zsh_version/Src/Modules/
ln -sf $PWD/Src/fzftab.mdd ./zsh/$zsh_version/Src/Modules/
# build zsh
cd -q ./zsh/$zsh_version
[[ -f ./configure ]] || ./Util/preconfig
[[ -f ./Makefile ]] || ./configure --disable-gdbm --disable-pcre --without-tcsetpgrp --prefix=/tmp/zsh-fzf-tab-module ${bundle:+DL_EXT=bundle}
make -j$nproc
# we only need aloxaf/fzftab.so
mv ./Src/Modules/fzftab.(so|bundle) $FZF_TAB_HOME/modules/Src/aloxaf/

View File

@ -0,0 +1,34 @@
#!/hint/zsh
emulate -L zsh -o cbases -o octalzeroes
local REPLY
local -a reply stat lstat
# fzf-tab-lscolors::match-by $1 lstat follow
zstat -A lstat -L -- $1
# follow symlink
(( lstat[3] & 0170000 )) && zstat -A stat -- $1 2>/dev/null
fzf-tab-lscolors::from-mode "$1" "$lstat[3]" $stat[3]
# fall back to name
[[ -z $REPLY ]] && fzf-tab-lscolors::from-name $1
# If this is a symlink
if [[ -n $lstat[14] ]]; then
local sym_color=$REPLY
local rsv_color=$REPLY
local rsv=$lstat[14]
# If this is not a broken symlink
if [[ -e $rsv ]]; then
# fzf-tab-lscolors::match-by $rsv stat
zstat -A stat -- $rsv
fzf-tab-lscolors::from-mode $rsv $stat[3]
# fall back to name
[[ -z $REPLY ]] && fzf-tab-lscolors::from-name $rsv
rsv_color=$REPLY
fi
dpre=$'\033[0m\033['$sym_color'm'
dsuf+=$'\033[0m -> \033['$rsv_color'm'$rsv
else
dpre=$'\033[0m\033['$REPLY'm'
fi

109
.zsh/zsh-fzf-tab/lib/-ftb-fzf Executable file
View File

@ -0,0 +1,109 @@
#!/hint/zsh
# import math functions
autoload -Uz zmathfunc
zmathfunc
local tmp_dir=${TMPPREFIX:-/tmp/zsh}-fzf-tab-$USER
[[ -d $tmp_dir ]] || command mkdir $tmp_dir
local ftb_preview_init="
zmodload zsh/mapfile
local -a _ftb_compcap=(\"\${(@f)mapfile[$tmp_dir/compcap.$$]}\")
local -a _ftb_groups=(\"\${(@f)mapfile[$tmp_dir/groups.$$]}\")
local bs=\$'\2'
# get description
export desc=\${\${\"\$(<{f})\"%\$'\0'*}#*\$'\0'}
# get ctxt for current completion
local -A ctxt=(\"\${(@0)\${_ftb_compcap[(r)\${(b)desc}\$bs*]#*\$bs}}\")
# get group
if (( \$+ctxt[group] )); then
export group=\$_ftb_groups[\$ctxt[group]]
fi
# get original word
export word=\${(Q)ctxt[word]}
# get real path if it is file
if (( \$+ctxt[realdir] )); then
export realpath=\${ctxt[realdir]}\$word
fi
$(typeset -p words)
"
local default_binds=tab:down,btab:up,change:top,ctrl-space:toggle,bspace:backward-delete-char/eof,ctrl-h:backward-delete-char/eof
local fzf_command fzf_flags fzf_preview debug_command tmp switch_group fzf_pad fzf_min_height binds
local ret=0
-ftb-zstyle -s fzf-command fzf_command || fzf_command=fzf
-ftb-zstyle -a fzf-bindings-default tmp && binds=${(j:,:)tmp} || binds=$default_binds
-ftb-zstyle -a fzf-bindings tmp && binds+=,${(j:,:)tmp}
-ftb-zstyle -a fzf-flags fzf_flags
-ftb-zstyle -s fzf-preview fzf_preview
-ftb-zstyle -a switch-group switch_group || switch_group=(F1 F2)
-ftb-zstyle -s fzf-pad fzf_pad || fzf_pad=2
-ftb-zstyle -s fzf-min-height fzf_min_height || fzf_min_height=0
-ftb-zstyle -a debug-command debug_command && {
${(eX)debug_command} $fzf_flags
return
}
print -rl -- $_ftb_compcap > $tmp_dir/compcap.$$
print -rl -- $_ftb_groups > $tmp_dir/groups.$$
print -r -- ${ftb_preview_init/{f}/\$1} > $tmp_dir/ftb_preview_init.$$
binds=${binds//{_FTB_INIT_}/. $tmp_dir/ftb_preview_init.$$ {f} $'\n'}
local -i header_lines=$#_ftb_headers
local -i lines=$(( $#_ftb_compcap + fzf_pad + header_lines ))
local reload_command="$commands[zsh] -f $FZF_TAB_HOME/lib/ftb-switch-group $$ $header_lines $tmp_dir"
# detect if we will use tmux popup
local use_tmux_popup=0
if [[ $fzf_command == "ftb-tmux-popup" ]]; then
use_tmux_popup=1
fi
if (( ! use_tmux_popup )); then
# fzf will cause the current line to refresh, so move the cursor down.
echoti cud1 >/dev/tty
# reset cursor before call fzf
echoti cnorm >/dev/tty 2>/dev/null
fi
cat > $tmp_dir/completions.$$
local dd='gdd'
if (( ${+commands[$dd]} == 0 )) ; then
dd='dd'
fi
if (( ${+commands[$dd]} == 0 )) ; then
dd='true' # nop if dd is not installed
fi
_ftb_query="${_ftb_query}$(command "$dd" bs=1G count=1 status=none iflag=nonblock < /dev/tty 2>/dev/null)" || true
SHELL=$ZSH_NAME $fzf_command \
--ansi \
--bind=$binds \
--bind="${switch_group[1]}:reload($reload_command -1),${switch_group[2]}:reload($reload_command 1)" \
--color=hl:$(( header_lines == 0 ? 188 : 255 )) \
--cycle \
--delimiter='\x00' \
--expect=$continuous_trigger,$print_query,$accept_line \
--header-lines=$header_lines \
--height=${FZF_TMUX_HEIGHT:=$(( min(max(lines, fzf_min_height), LINES / 3 * 2) ))} \
--layout=reverse \
--multi \
--nth=2,3 \
--print-query \
--query=$_ftb_query \
--tiebreak=begin \
${fzf_preview:+--preview=${ftb_preview_init/{f}/'{f}'}$fzf_preview} \
$fzf_flags < $tmp_dir/completions.$$ || ret=$?
if (( ! use_tmux_popup )); then
echoti civis >/dev/tty 2>/dev/null
echoti cuu1 >/dev/tty
fi
command rm $tmp_dir/*.$$ 2>/dev/null
return $ret

View File

@ -0,0 +1,113 @@
#!/hint/zsh
local dsuf dpre k _v filepath first_word show_group default_color prefix bs=$'\b'
local -a list_colors group_colors tcandidates reply match mbegin mend
local -i same_word=1 colorful=0
local -Ua duplicate_groups=()
local -A word_map=()
(( $#_ftb_compcap == 0 )) && return
-ftb-zstyle -s show-group show_group || show_group=full
-ftb-zstyle -s default-color default_color || default_color=$'\x1b[37m'
-ftb-zstyle -s prefix prefix || {
zstyle -m ':completion:*:descriptions' format '*' && prefix='·'
}
-ftb-zstyle -a group-colors group_colors || group_colors=($_ftb_group_colors)
zstyle -a ":completion:$_ftb_curcontext" list-colors list_colors
# init colorize
if (( $+builtins[fzf-tab-candidates-generate] )); then
fzf-tab-candidates-generate -i list_colors
else
local -A namecolors=(${(@s:=:)${(@s.:.)list_colors}:#[[:alpha:]][[:alpha:]]=*})
local -A modecolors=(${(@Ms:=:)${(@s.:.)list_colors}:#[[:alpha:]][[:alpha:]]=*})
(( $#namecolors == 0 && $#modecolors == 0 )) && list_colors=()
fi
if (( $#_ftb_groups == 1 )); then
-ftb-zstyle -m single-group prefix || prefix=''
-ftb-zstyle -m single-group color || group_colors=("$default_color")
fi
if (( $+builtins[fzf-tab-candidates-generate] )); then
fzf-tab-candidates-generate
else
for k _v in "${(@ps:\2:)_ftb_compcap}"; do
local -A v=("${(@0)_v}")
[[ $v[word] == ${first_word:=$v[word]} ]] || same_word=0
# add character and color to describe the type of the files
dsuf='' dpre=''
if (( $+v[realdir] )); then
filepath=$v[realdir]${(Q)v[word]}
if [[ -d $filepath ]]; then
dsuf=/
fi
# add color and resolve symlink if have list-colors
# detail: http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fcomplist-Module
if (( $#list_colors )) && [[ -a $filepath || -L $filepath ]]; then
-ftb-colorize $filepath
colorful=1
elif [[ -L $filepath ]]; then
dsuf=@
fi
if [[ $options[list_types] == off ]]; then
dsuf=''
fi
fi
# add color to description if they have group index
if (( $+v[group] )); then
local color=$group_colors[$v[group]]
# add a hidden group index at start of string to keep group order when sorting
# first group index is for builtin sort, sencond is for GNU sort
tcandidates+=$v[group]$'\b'$color$prefix$dpre$'\0'$v[group]$'\b'$k$'\0'$dsuf
else
tcandidates+=$default_color$dpre$'\0'$k$'\0'$dsuf
fi
# check group with duplicate member
if [[ $show_group == brief ]]; then
if (( $+word_map[$v[word]] && $+v[group] )); then
duplicate_groups+=$v[group] # add this group
duplicate_groups+=$word_map[$v[word]] # add previous group
fi
word_map[$v[word]]=$v[group]
fi
done
fi
(( same_word )) && tcandidates[2,-1]=()
# sort and remove sort group or other index
zstyle -T ":completion:$_ftb_curcontext" sort
if (( $? != 1 )); then
if (( colorful )); then
# if enable list_colors, we should skip the first field
if [[ ${commands[sort]:A:t} != (|busybox*) ]]; then
# this is faster but doesn't work if `find` is from busybox
tcandidates=(${(f)"$(command sort -u -t '\0' -k 2 <<< ${(pj:\n:)tcandidates})"})
else
# slower but portable
tcandidates=(${(@o)${(@)tcandidates:/(#b)([^$'\0']#)$'\0'(*)/$match[2]$'\0'$match[1]}})
tcandidates=(${(@)tcandidates/(#b)(*)$'\0'([^$'\0']#)/$match[2]$'\0'$match[1]})
fi
else
tcandidates=("${(@o)tcandidates}")
fi
fi
typeset -gUa _ftb_complist=("${(@)tcandidates//[0-9]#$bs}")
# hide needless group
if (( $#_ftb_groups )); then
local i to_hide indexs=({1..$#_ftb_groups})
case $show_group in
brief) to_hide=(${indexs:|duplicate_groups}) ;;
none) to_hide=($indexs) ;;
esac
for i in $to_hide; do
# NOTE: _ftb_groups is unique array
_ftb_groups[i]="__hide__$i"
done
fi

View File

@ -0,0 +1,35 @@
#!/hint/zsh
typeset -ga _ftb_headers=()
local i tmp group_colors
local -i mlen=0 len=0
if (( $#_ftb_groups == 1 )) && { ! -ftb-zstyle -m single-group "header" }; then
return
fi
# calculate the max column width
for i in $_ftb_groups; do
(( $#i > mlen )) && mlen=$#i
done
mlen+=1
-ftb-zstyle -a group-colors group_colors || group_colors=($_ftb_group_colors)
for (( i=1; i<=$#_ftb_groups; i++ )); do
[[ $_ftb_groups[i] == "__hide__"* ]] && continue
if (( len + $#_ftb_groups[i] > COLUMNS - 5 )); then
_ftb_headers+=$tmp
tmp='' && len=0
fi
if (( len + mlen > COLUMNS - 5 )); then
# the last column doesn't need padding
_ftb_headers+=$tmp$group_colors[i]$_ftb_groups[i]$'\033[00m'
tmp='' && len=0
else
tmp+=$group_colors[i]${(r:$mlen:)_ftb_groups[i]}$'\033[00m'
len+=$mlen
fi
done
(( $#tmp )) && _ftb_headers+=$tmp

View File

@ -0,0 +1,40 @@
#!/hint/zsh
if zmodload -s zsh/pcre; then
setopt localoptions rematch_pcre
fi
local key qtype tmp query_string
typeset -g _ftb_query=
-ftb-zstyle -a query-string query_string || query_string=(prefix input first)
for qtype in $query_string; do
if [[ $qtype == prefix ]]; then
# find the longest common prefix among descriptions
local -a keys=(${_ftb_compcap%$'\2'*})
tmp=$keys[1]
local MATCH match mbegin mend prefix=(${(s::)tmp})
for key in ${keys:1}; do
(( $#tmp )) || break
[[ $key == $tmp* ]] && continue
# interpose characters from the current common prefix and $key and see how
# many pairs of equal characters we get at the start of the resulting string
[[ ${(j::)${${(s::)key[1,$#tmp]}:^prefix}} =~ '^(((.)\3)*)' ]]
# truncate common prefix and maintain loop invariant: ${(s::)tmp} == $prefix
tmp[$#MATCH/2+1,-1]=""
prefix[$#MATCH/2+1,-1]=()
done
elif [[ $qtype == input ]]; then
local fv=${_ftb_compcap[1]#*$'\2'}
local -A v=("${(@0)fv}")
tmp=$v[PREFIX]
if (( $RBUFFER[(i)$v[SUFFIX]] != 1 )); then
tmp=${tmp/%$v[SUFFIX]}
fi
tmp=${${tmp#$v[hpre]}#$v[apre]}
fi
if (( $query_string[(I)longest] )); then
(( $#tmp > $#_ftb_query )) && _ftb_query=$tmp
elif [[ -n $tmp ]]; then
_ftb_query=$tmp && break
fi
done

View File

@ -0,0 +1,10 @@
#!/hint/zsh
emulate -L zsh -o pipe_fail
pushd -q $FZF_TAB_HOME
if [[ -d .git ]]; then
git describe --long --tags --abbrev=7 2>/dev/null | sed 's/\([^-]*-g\)/r\1/;s/-/./g' \
|| printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short=7 HEAD)"
else
echo unknown
fi
popd -q

View File

@ -0,0 +1,38 @@
#!/hint/zsh
emulate -L zsh -o extended_glob
zmodload zsh/mapfile
# receive arguments
local pid=$1 header_lines=$2 tmp_dir=$3 offset=$@[-1]
# read completion list
local -a list=(${(f)mapfile[$tmp_dir/completions.$pid]})
# get total group count
if (( $#list > 10000 )); then
local -Ua total=(${(f)"$(print -l ${list:$header_lines} | grep -a -oP '^\x1b\[[0-9;]*m')"})
else
local -Ua total=(${(M)${list:$header_lines}#$'\x1b['[0-9;]#*m})
fi
# get current group index, start from 2
local current=2
if [[ -f $tmp_dir/current-group.$pid ]]; then
current=$(( $(<$tmp_dir/current-group.$pid) + offset ))
fi
(( current > $#total )) && current=1
(( current == 0 )) && current=$#total
echo $current > $tmp_dir/current-group.$pid
# print headers
if (( header_lines != 0 )); then
print -l ${list[1,header_lines]/${total[current]}/$'\x1b[1m'}
fi
# print current group
if (( $#list > 10000 )); then
print -l ${list:$header_lines} | grep -a -F "${total[current]}"
else
print -l ${(M)${list:$header_lines}:#${total[current]}*}
fi

View File

@ -0,0 +1,100 @@
#!/hint/zsh
# Show results with tmux popup
# Example usage:
# zstyle ':fzf-tab:*' fzf-command ftb-tmux-popup
# zstyle ':fzf-tab:*' popup-pad 0 0
# It can also be used as a standalone tool, like:
# ls | ftb-tmux-popup
emulate -L zsh -o extended_glob
# import math functions (only if they're not already defined)
if (( ! $+functions[zsh_math_func_min] )); then
autoload -Uz zmathfunc
zmathfunc
fi
: ${tmp_dir:=${TMPPREFIX:-/tmp/zsh}-fzf-tab-$USER}
# fallback to fzf if it is not running in tmux
if (( ! $+TMUX_PANE )); then
fzf $@
return
fi
local ret=0
local -a fzf_opts=($@)
fzf_opts=(${${fzf_opts/--height*}/--layout*})
# get position of cursor and size of window
local -a tmp=($(command tmux display-message -p "#{pane_top} #{cursor_y} #{pane_left} #{cursor_x} #{window_height} #{window_width} #{status} #{status-position}"))
local cursor_y=$((tmp[1] + tmp[2])) cursor_x=$((tmp[3] + tmp[4])) window_height=$tmp[5] window_width=$tmp[6] window_top=0
if [[ $tmp[8] == 'top' ]]; then
window_top=$tmp[7]
cursor_y=$((cursor_y + window_top))
fi
# if not called by fzf-tab
if (( ! $+IN_FZF_TAB )); then
[[ -d $tmp_dir ]] || mkdir -p $tmp_dir
cat > $tmp_dir/completions.$$
fi
local text REPLY comp_lines comp_length length popup_pad popup_min_size
zstyle -a ":fzf-tab:$_ftb_curcontext" popup-pad popup_pad || popup_pad=(0 0)
zstyle -a ":fzf-tab:$_ftb_curcontext" popup-min-size popup_min_size || popup_min_size=(0 0)
# get the size of content, note we should remove all ANSI color code
comp_lines=$(( ${#${(f)mapfile[$tmp_dir/completions.$$]}} + $popup_pad[2] ))
if (( comp_lines <= 500 )); then
comp_length=0
for line in ${(f)mapfile[$tmp_dir/completions.$$]}; do
length=${(m)#${(S)line//$'\x1b['[0-9]#*m}}
(( length >= comp_length )) && comp_length=$length
done
else
# FIXME: can't get the correct width of CJK characters.
comp_length=$( command perl -ne 's/\x1b\[[0-9;]*m//g;s/\x00//g; $m= length() if $m < length(); END { print $m }' < $tmp_dir/completions.$$ )
fi
comp_length=$(( comp_length + $popup_pad[1] ))
local popup_height popup_y popup_width popup_x adjust_height
# adjust the popup height if the fzf finder info style is not default
if (( $fzf_opts[(I)--info=*(hidden|inline)*] > 0 )); then
adjust_height=-1
fi
# calculate the popup height and y position
if (( cursor_y * 2 > window_height )); then
# show above the cursor
popup_height=$(( min(max(comp_lines + 4, popup_min_size[2]), cursor_y - window_top) + adjust_height ))
popup_y=$cursor_y
if zstyle -T ":fzf-tab:$_ftb_curcontext" popup-smart-tab; then
fzf_opts+=(--bind=tab:up,btab:down)
fi
fzf_opts+=(--layout=default)
else
# show below the cursor
popup_height=$(( min(max(comp_lines + 4, popup_min_size[2]), window_height - cursor_y + window_top - 1) + adjust_height ))
popup_y=$(( cursor_y + popup_height + 1 ))
fzf_opts+=(--layout=reverse)
fi
# calculate the popup width and x position
popup_width=$(( min(max(comp_length + 5, popup_min_size[1]), window_width) ))
popup_x=$(( cursor_x + popup_width > window_width ? window_width - popup_width : cursor_x ))
echo -E "env SHELL=$ZSH_NAME $commands[fzf] ${(qq)fzf_opts[@]} < $tmp_dir/completions.$$ > $tmp_dir/result-$$" > $tmp_dir/fzf-$$
{
tmux popup -x $popup_x -y $popup_y \
-w $popup_width -h $popup_height \
-d $PWD -E ". $tmp_dir/fzf-$$" || ret=$?
echo -E "$(<$tmp_dir/result-$$)"
} always {
command rm $tmp_dir/*-$$
(( $+IN_FZF_TAB )) || command rm $tmp_dir/completions.$$
}
return $ret

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Gamma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,114 @@
# zsh-ls-colors
![Demo screenshot](https://raw.githubusercontent.com/xPMo/zsh-ls-colors/image/demo.png)
A zsh library to use `LS_COLORS` in scripts or other plugins.
For a simple demo, see the `demo` script in this repo.
For more advanced usage,
instructions are located at top of the source files for `from-mode` and `from-name`.
If a use case isn't adequately covered,
please open an issue!
## Using zsh-ls-colors in a plugin
You can use this as a submodule or a subtree.
### submodule:
```sh
# Add (only once)
git submodule add git://github.com/xPMo/zsh-ls-colors.git ls-colors
git commit -m 'Add ls-colors as submodule'
# Update
cd ls-colors
git fetch
git checkout origin/master
cd ..
git commit ls-colors -m 'Update ls-colors to latest'
```
### Subtree:
```sh
# Initial add
git subtree add --prefix=ls-colors/ --squash -m 'Add ls-colors as a subtree' \
git://github.com/xPMo/zsh-ls-colors.git master
# Update
git subtree pull --prefix=ls-colors/ --squash -m 'Update ls-colors to latest' \
git://github.com/xPMo/zsh-ls-colors.git master
# Or, after adding a remote:
git remote add ls-colors git://github.com/xPMo/zsh-ls-colors.git
# Initial add
git subtree add --prefix=ls-colors/ --squash -m 'Add ls-colors as a subtree' ls-colors master
# Update
git subtree pull --prefix=ls-colors/ --squash -m 'Update ls-colors to latest' ls-colors master
```
### Function namespacing
Since functions are a public namespace,
this plugin allows you to customize the preifix for your plugin:
```zsh
# load functions as my-lscolors::{init,match-by,from-name,from-mode}
source ${0:h}/ls-colors/ls-colors.zsh my-lscolors
```
### Parameter namespacing
While indirect parameter expansion exists with `${(P)var}`,
it doesn't play nicely with array parameters.
There are multiple strategies to prevent unnecessary re-parsing:
```zsh
# Call once when loading.
# Pollutes global namespace but prevents re-parsing
ls-color::init
```
```zsh
# Don't call init at all and only use ::match-by.
# Doesn't pollute global namespace but reparses LS_COLORS on every call
ls-color::match-by $file lstat
```
```zsh
# Initialize within a scope with local parameters.
# Best for not polluting global namespace when multiple filenames need to be parsed.
(){
local -A namecolors modecolors
ls-color::init
for arg; do
...
done
}
```
```zsh
# Serialize:
typeset -g LS_COLORS_CACHE_FILE=$(mktemp)
(){
local -A namecolors modecolors
ls-color::init
typeset -p modecolors namecolors >| $LS_COLORS_CACHE_FILE
zcompile $LS_COLORS_CACHE_FILE
}
my-function(){
local -A namecolors modecolors
source $LS_COLORS_CACHE_FILE
...
}
```

View File

@ -0,0 +1,65 @@
#!/usr/bin/env zsh
# set $0 (ref: zdharma.org/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html#zero-handling)
0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}"
0="${${(M)0:#/*}:-$PWD/$0}"
# load library functions
source ls-colors.zsh ''
# to name the functions with a different namespace
# call source with a different argument
#source my-plugin::ls
# init (sets modecolors and namecolors)
# You have options. Either you can pollute global namespace:
ls-color::init
# Or you can have ::match-by re-parse colors on every call
: # (do nothing)
# Or if you have multiple calls, you can parse colors once for a scope:
(){
local -A modecolors namecolors
ls-color::init
for arg; do
ls-color::match-by $arg lstat
: do something else
done
}
# colors can also be added for other globs after init as well:
namecolors[*.md]='01' # bold markdown files
# EXTENDED_GLOB is enabled when matching, so things like this are possible:
namecolors[(#i)(*/|)license(|.*)]='04' # underline LICENSE, or license.txt, or similar
local file reply
# color each file in the argument list
for file; do
ls-color::match-by $file all
# point to symlink resolution if it exists
print '\e['$reply[1]'m'$file'\e[0m'${reply[2]:+' → \e['$reply[3]'m'$reply[2]'\e[0m'}
done
# =======================
# Alternate manual method:
for file; do
ls-color::match-by $file lstat follow
if [[ $reply[2] ]]; then
# This is a symlink
symlink_color=$reply[1]
# If broken, use link color for destination
resolved_color=$reply[1]
resolved=$reply[2]
if [[ -e $file ]]; then
# Not broken, update destination color
ls-color::match-by $file stat
resolved_color=$reply[1]
fi
print '\e['$symlink_color'm'$file'\e[0m → \e['$resolved_color'm'$resolved'\e[0m'
else
# This is not a symlink
print '\e['$reply[1]'m'$file'\e[0m'
fi
done

View File

@ -0,0 +1,186 @@
#!/usr/bin/env zsh
# set the prefix for all functions
local pfx=${1:-'ls-color'}
# {{{ From mode
# Usage:
# $1: filename
# $2: The value of struct stat st_mode
# If empty, modecolors lookup will be skipped
# $3: (If symlink) The value of struct stat st_mode
# for the target of $1's symlink. If unset,
# interpret as a broken link.
# Sets REPLY to the console code
${pfx}::from-mode () {
emulate -L zsh
setopt cbases octalzeroes extendedglob
[[ -z $2 ]] && return 1
local -i reg=0
local -a codes
local -i st_mode=$(($2))
# See man 7 inode for more info
# file type
case $(( st_mode & 0170000 )) in
$(( 0140000 )) ) codes=( $modecolors[so] ) ;;
$(( 0120000 )) ) # symlink, special handling
if ! (($+3)); then
REPLY=$modecolors[or]
elif [[ $modecolors[ln] = target ]]; then
"$0" "$1" "${@:3}"
else
REPLY=$modecolors[ln]
fi
return
;;
$(( 0100000 )) ) codes=( ); reg=1 ;; # regular file
$(( 0060000 )) ) codes=( $modecolors[bd] ) ;;
$(( 0040000 )) ) codes=( $modecolors[di] ) ;;
$(( 0020000 )) ) codes=( $modecolors[cd] ) ;;
$(( 0010000 )) ) codes=( $modecolors[pi] ) ;;
esac
# setuid/setgid/sticky/other-writable
(( st_mode & 04000 )) && codes+=( $modecolors[su] )
(( st_mode & 02000 )) && codes+=( $modecolors[sg] )
(( ! reg )) && case $(( st_mode & 01002 )) in
# sticky
$(( 01000 )) ) codes+=( $modecolors[st] ) ;;
# other-writable
$(( 00002 )) ) codes+=( $modecolors[ow] ) ;;
# other-writable and sticky
$(( 01002 )) ) codes+=( $modecolors[tw] ) ;;
esac
# executable
if (( ! $#codes )); then
(( st_mode & 0111 )) && codes+=( $modecolors[ex] )
fi
# return nonzero if no matching code
[[ ${REPLY::=${(j:;:)codes}} ]]
} # }}}
# {{{ From name
# Usage:
# $1: filename
#
# Sets REPLY to the console code
${pfx}::from-name () {
emulate -L zsh
setopt extendedglob
# Return non-zero if no keys match
[[ ${REPLY::=$namecolors[(k)$1]} ]]
} # }}}
# {{{ Init
# WARNING: initializes namecolors and modecolors in global scope
${pfx}::init () {
emulate -L zsh
# Use $1 if provided, otherwise use LS_COLORS
# Use LSCOLORS on BSD
local LS_COLORS=${1:-${LS_COLORS:-$LSCOLORS}}
# read in LS_COLORS
typeset -gA namecolors=(${(@s:=:)${(@s.:.)LS_COLORS}:#[[:alpha:]][[:alpha:]]=*})
typeset -gA modecolors=(${(@Ms:=:)${(@s.:.)LS_COLORS}:#[[:alpha:]][[:alpha:]]=*})
}
# }}}
# {{{ Match by
# Usage:
# $1: filename
# Optional (must be $2): g[lobal]: Use existing stat | lstat in parent scope
# ${@:2}: Append to reply:
# - l[stat] : Look up using lstat (don't follow symlink), if empty match name
# - s[tat] : Look up using stat (do follow symlink), if empty match name
# - n[ame] : Only match name
# - f[ollow]: Get resolution path of symlink
# - L[stat] : Same as above but don't match name
# - S[tat] : Same as above but don't match name
# - a[ll] : If a broken symlink: lstat follow lstat
# : If a symlink : lstat follow stat
# : Otherwise : lstat
# - A[ll] : If a broken symlink: Lstat follow Lstat
# : If a symlink : Lstat follow Stat
# : Otherwise : Lstat
#
# or returns non-zero
${pfx}::match-by () {
emulate -L zsh
setopt extendedglob cbases octalzeroes
local arg REPLY name=$1 pfx=${0%::match-by}
shift
# init in local scope if not using global params
if ! [[ -v namecolors && -v modecolors ]]; then
local -A namecolors modecolors
${pfx}::init
fi
if [[ ${1:l} = (g|global) ]]; then
shift
else
local -a stat lstat
declare -ga reply=()
fi
zmodload -F zsh/stat b:zstat
for arg; do
case ${arg[1]:l} in
n|name)
${pfx}::from-name $name
reply+=("$REPLY")
;;
l|lstat)
(($#lstat)) || zstat -A lstat -L $name || return 1
if ((lstat[3] & 0170000 )); then
# follow symlink
(($#stat)) || zstat -A stat $name 2>/dev/null
fi
${pfx}::from-mode "$name" "$lstat[3]" $stat[3]
if [[ $REPLY || ${2[1]} = L ]]; then
reply+=("$REPLY")
else # fall back to name
"$0" "$name" g n
fi
;;
s|stat)
(($#stat)) || zstat -A stat $name || return 1
${pfx}::from-mode $name $stat[3]
reply+=("$REPLY")
if [[ $REPLY || ${arg[1]} = S ]]; then
reply+=("$REPLY")
else # fall back to name
"$0" "$name" g n
fi
;;
f|follow)
(($#lstat)) || zstat -A lstat -L $name || return 1
reply+=("$lstat[14]")
;;
a|all)
# Match case
"$0" "$name" g ${${${arg[1]%a}:+L}:-l}
# won't append if empty
reply+=($lstat[14])
# $stat[14] will be empty if not a symlink
if [[ $lstat[14] ]]; then
if [[ -e $name ]]; then
"$0" "$name" g ${${${arg[1]%a}:+S}:-s}
else
reply+=($reply[-2])
fi
fi
;;
*) return 2 ;;
esac
done
}
# }}}
# vim: set foldmethod=marker:

View File

@ -0,0 +1,16 @@
Makefile
META-FAQ
config.cache
config.h
config.h.in
config.log
config.modules
config.modules.sh
config.status
configure
cscope.out
stamp-h
stamp-h.in
autom4te.cache
*.swp
.git

View File

@ -0,0 +1,4 @@
DISTFILES_SRC='
META-FAQ
configure config.h.in stamp-h.in
'

View File

@ -0,0 +1,15 @@
# Top-most editorconfig file
root = true
[*]
end_of_line = lf
tab_width = 8
indent_size = 2
indent_style = tab
[ChangeLog]
indent_size = 8
[*.[ch]]
indent_size = 4

1
.zsh/zsh-fzf-tab/modules/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
zsh/

Some files were not shown because too many files have changed in this diff Show More