Repository: riscy/shx-for-emacs Branch: main Commit: 5a7b5f0f48f0 Files: 7 Total size: 108.6 KB Directory structure: gitextract_azwfizqi/ ├── .github/ │ └── workflows/ │ └── test.yml ├── .gitignore ├── COPYING ├── README.org ├── shx.el └── test/ ├── script.el └── shx-test.el ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/test.yml ================================================ name: test on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - name: Set up Python uses: actions/setup-python@v6 with: { python-version: '3.10' } - name: Install run: | sudo apt-get install emacs && emacs --version git clone https://github.com/riscy/melpazoid.git ~/melpazoid - name: Run env: LOCAL_REPO: ${{ github.workspace }} RECIPE: (shx :fetcher github :repo "riscy/shx-for-emacs") # set this to false (or remove it) if the package isn't on MELPA: EXIST_OK: true run: | make -C ~/melpazoid emacs --batch --script ./test/script.el ================================================ FILE: .gitignore ================================================ # Compiled *.elc # Packaging .cask # Backup files *~ # Undo-tree save-files *.~undo-tree ================================================ FILE: COPYING ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.org ================================================ #+TITLE: shx for Emacs #+OPTIONS: toc:3 author:t creator:nil num:nil #+AUTHOR: Chris Rayner #+EMAIL: dchrisrayner@gmail.com [[https://melpa.org/#/shx][https://melpa.org/packages/shx-badge.svg]] [[https://stable.melpa.org/#/shx][https://stable.melpa.org/packages/shx-badge.svg]] [[https://github.com/riscy/shx-for-emacs/actions][https://github.com/riscy/shx-for-emacs/workflows/test/badge.svg]] [[file:img/screenshot.png]] * Table of Contents :TOC_3_gh:noexport: - [[#description][Description]] - [[#install][Install]] - [[#from-melpa][From MELPA]] - [[#from-gnu-guix][From GNU Guix]] - [[#manually][Manually]] - [[#setup][Setup]] - [[#quick-start][Quick-start]] - [[#enable-automatically][Enable automatically]] - [[#customize][Customize]] - [[#key-bindings][Key bindings]] - [[#markup-in-the-shell][Markup in the shell]] - [[#extra-shell-commands][Extra shell commands]] - [[#general-commands][General commands]] - [[#graphical-commands][Graphical commands]] - [[#asynchronous-commands][Asynchronous commands]] - [[#adding-new-commands][Adding new commands]] - [[#related][Related]] * Description /shx/ or "shell-extras" extends comint-mode in Emacs (e.g. =M-x shell=). It's compatible with any underlying REPL (zsh, bash, psql, ipython, etc.). It parses the output stream in a few useful ways: - *Display graphics and plots* in the shell with a simple markup language (e.g. ==) - *Add event-driven and timed behaviors* to any shell session - *Open any filename or URL* by arrowing up to it and pressing =RET= (shx will even try to guess the correct directory) - *Yank any line to the prompt* by arrowing up to it and pressing =C-RET= - *Check the time a command was run* by mousing over its prompt shx makes it easy to add new shell commands written in elisp. Some are already built in: - =:clear= clears the buffer (like =clear= or =Command-K= on macOS) - =:e filename.txt= opens a file for editing - =:ssh user@host:port= starts a remote shell session using tramp - =:view image_file.png= embeds an image in the shell - =:plotline data_file.txt= embeds a line plot - etc. It also extends =shell-mode='s syntax highlighting, recenters and highlights content for better viewing when you run commands like ~comint-previous-prompt~ and ~comint-kill-input~, and improves compatibility with evil-mode by anticipating when to switch to insert mode. Use =M-x shx RET= to start a new shell session with ~shx-mode~ enabled. /This version is tested with Emacs 26.1/. Check out the [[https://github.com/riscy/shx-for-emacs/releases][release log]]. * Install *** From MELPA =M-x package-install RET shx RET= to install =shx= from [[https://melpa.org/][MELPA]]. *** From GNU Guix =guix install emacs-shx= to install =shx= from [[https://guix.gnu.org/][GNU Guix]]. *** Manually Add the following to your =.emacs=: #+begin_src elisp (add-to-list 'load-path "~/path/to/shx/") ; add shx.el's directory to the load-path (require 'shx) ; load shell-extras #+end_src * Setup *** Quick-start Type =M-x shx RET=. Try out the following commands: 1. =:e ~/.bashrc= to edit your =.bashrc= (for example) 2. =:man ls= to display the man page for =ls= 3. =:help= to a start a completing read for other =shx= commands *** Enable automatically If you like shx-mode, you can enable it everywhere: #+begin_src elisp (shx-global-mode 1) ; toggle shx-mode on globally #+end_src Now shx will run automatically in any =comint-mode= buffer. If you don't want shx to run in every comint-mode buffer, you can use =M-x shx-mode= on a case-by-case basis, or just add hooks to the mode in question, for example: #+begin_src elisp (add-hook 'inferior-python-mode-hook #'shx-mode) #+end_src *** Customize Use =M-x customize-group RET shx RET= to see shx's many customization options. Here's an example customization using ~setq~: #+begin_src elisp (setq ;; resync the shell's default-directory with Emacs on "z" commands: shx-directory-tracker-regexp "^z " ;; vastly improve display performance by breaking up long output lines shx-max-output 1024 ;; prevent input longer than macOS's typeahead buffer from going through shx-max-input 1024 ;; prefer inlined images and plots to have a height of 250 pixels shx-img-height 250 ;; don't show any incidental hint messages about how to use shx shx-show-hints nil ;; flash the previous comint prompt for a full second when using C-c C-p shx-flash-prompt-time 1.0 ;; use `#' to prefix shx commands instead of the default `:' shx-leader "#") #+end_src * Key bindings | Key binding | Description | |-------------+--------------------------------------------------------------------------| | =C-RET= | If the cursor is not on the prompt, paste the current line to the input | | =RET= | If the cursor is on a filename or a URL, try to open it | | =SPC= | If the prompt is =:=, send =SPC= straight through to the process | | =q= | If the prompt is =:=, send =q= straight through to the process | Note the prompt will be =:= when reading through the output of =less= or a =man= page if you run the following: #+begin_src elisp (setenv "LESS" "--dumb --prompt=s") #+end_src * Markup in the shell shx's markup can enhance basic command-line applications and drive other events. If the output ever contains == on a line by itself, then a scaled rendering of =mountains.png= will be inlined within the text in the shell. This works because =view= is a shx command. shx will execute any (safe) shx command that appears with the following syntax: #+begin_src xml #+end_src where ~command~ is a shx command and ~arg1 ... argn~ is a space-separated list of arguments. Arguments don't need to be surrounded by quotes -- the command will figure out how to parse them. You can use this markup to create a barplot (=:plotbar=) after collecting some stats, or generate an =:alert= when a task is finished, and so forth. * Extra shell commands shx's 'extra' commands are invoked by typing a =:= followed by the command's name. (You can change the =:= prefix by customizing the ~shx-leader~ variable.) These commands are written in elisp and so can access all of Emacs' facilities. Type =:help= to see a complete listing of shx commands. One command I use frequently is the =:edit= (shorthand =:e=) command: #+begin_src bash # edit the .emacs file: :edit ~/.emacs # use tramp to edit .emacs on a remote host through ssh: :e /ssh:remote-host.com:~/.emacs # use tramp to edit .bashrc on a running docker container: :e /docker:02fbc948e009:~/.bashrc # edit a local file as root :sedit /etc/passwd #+end_src Thanks to [[https://github.com/CeleritasCelery][CeleritasCelery]] it's also possible to use environment variables in the argument list: #+begin_src bash :e $HOME/.emacs.d #+end_src (To see an environment variable's value, use ~(getenv "")~.) The =:ssh= and =:docker= commands are popular for opening "remote" shells: #+begin_src bash # open a shell on a remote host: :ssh user@remote-host.com # connect to a running docker container :docker 8a8335d63ff3 # reopen the shell on the localhost: :ssh #+end_src [[https://github.com/p3r7][Jordan Besly]] points out that you can customize the default interpreter for each "remote" using [[https://www.gnu.org/software/emacs/manual/html_node/tramp/Remote-processes.html][connection-profile-set-local-variables]]. I also use the =:kept= and =:keep= commands frequently: #+begin_src bash # write a complicated command: wget https://bootstrap.pypa.io/get-pip.py && python get-pip.py # save the last command: :keep # search for commands having to do with pip: :kept pip #+end_src Because these commands are written in elisp, shx gives =M-x shell= a lot of the same advantages as =eshell=. You can even evaluate elisp code directly in the buffer (see =:help eval=). *** General commands | Command | Description | |----------------------+-------------------------------------------------------| | =:alert= | Reveal the buffer with an alert. Useful for markup | | =:clear= | Clear the buffer | | =:date= | Show the date (even when the process is blocked) | | =:diff file1 file2= | Launch an Emacs diff between two files | | =:edit file= | Edit a file. Shortcut: =:e = | | =:eval (elisp-sexp)= | Evaluate some elisp code. Example: =:eval (pwd)= | | =:find = | Run a fuzzy-find for | | =:goto-url = | Completing-read for a URL | | =:header New header= | Change the current ~header-line-format~ | | =:kept regexp= | Show a list of your 'kept' commands matching regexp | | =:keep= | Add the previous command to the list of kept commands | | =:man topic= | Invoke the Emacs man page browser on a topic | | =:ssh = | Restart the shell on the specified host | There are more than this -- type =:help= for a listing of all user commands. *** Graphical commands | Command | Description | |------------------------------+------------------------| | =:view image_file.jpg= | Display an image | | =:plotbar data_file.txt= | Display a bar plot | | =:plotline data_file.txt= | Display a line plot | | =:plotmatrix data_file.txt= | Display a heatmap | | =:plotscatter data_file.txt= | Display a scatter plot | | =:plot3d data_file.txt= | Display a 3D plot | These are for displaying inline graphics and plots in the shell buffer. You can control how much vertical space an inline image occupies by customizing the ~shx-img-height~ variable. Note =convert= (i.e. ImageMagick) and =gnuplot= need to be installed. If the binaries are installed but these commands aren't working, customize the ~shx-path-to-convert~ and ~shx-path-to-gnuplot~ variables to point to the binaries. Also note these graphical commands aren't yet compatible with shells launched on remote hosts (e.g. over ssh or in a Docker container). *** Asynchronous commands | Command | Description | |-----------------------------------+---------------------------------------------------| | =:delay = | Run a shell command after a specific delay | | =:pulse = | Repeat a shell command forever with a given delay | | =:repeat = | Repeat a shell command ~~ times | | =:stop = | Cancel a repeating or delayed command | Use these to delay, pulse, or repeat a command a specific number of times. Unfortunately these only support your typical shell commands, and not shx's extra (colon-prefixed) commands. So this possible: #+begin_src bash # Run the 'pwd' command 10 seconds from now: :delay 10 pwd #+end_src But this is not possible: #+begin_src bash # Run the 'pwd' shx command 10 seconds from now (DOES NOT WORK) :delay 10 :pwd #+end_src *** Adding new commands New shx commands are written by defining single-argument elisp functions named ~shx-cmd-COMMAND-NAME~, where ~COMMAND-NAME~ is what the user would type to invoke it. ***** Example: a command to rename the buffer If you evaluate the following (or add it to your ~.emacs~), #+begin_src elisp (defun shx-cmd-rename (name) "(SAFE) Rename the current buffer to NAME." (if (not (ignore-errors (rename-buffer name))) (shx-insert 'error "Can't rename buffer.") (shx-insert "Renaming buffer to " name "\n") (shx--hint "Emacs won't save buffers starting with *"))) #+end_src then each shx buffer will immediately have access to the =:rename= command. When it's invoked, shx will also display a hint about buffer names. Note the importance of defining a docstring. This documents the command so that typing =:help rename= will give the user information on what the command does. Further, since the docstring begins with =(SAFE)=, it becomes part of shx's markup language. So in this case if: #+begin_src xml #+end_src appears on a line by itself in the output, the buffer will try to automatically rename itself. ***** Example: invoking ediff from the shell A command similar to this one is built into shx: #+begin_src elisp (defun shx-cmd-diff (files) "(SAFE) Launch an Emacs `ediff' between FILES." (setq files (shx-tokenize files)) (if (not (eq (length files) 2)) (shx-insert 'error "diff \n") (shx-insert "invoking ediff...\n") (shx--asynch-funcall #'ediff (mapcar #'expand-file-name files)))) #+end_src Note that ~files~ is supplied as a string, but it's immediately parsed into a list of strings using ~shx-tokenize~. Helpfully, this function is able to parse various styles of quoting and escaping, for example ~(shx-tokenize "'file one' file\\ two")~ evaluates to ~("file one" "file two")~. ***** Example: a command to browse URLs If you execute the following, #+begin_src elisp (defun shx-cmd-browse (url) "Browse the supplied URL." (shx-insert "Browsing " 'font-lock-keyword-face url) (browse-url url)) #+end_src then each shx buffer will have access to the =:browse= command. Note the docstring does not specify that this command is =SAFE=. This means == will not become part of shx's markup. That makes sense in this case, since you wouldn't want to give a process the power to open arbitrary URLs without prompting. * Related If you're here, these might be interesting: - [[https://www.masteringemacs.org/article/shell-comint-secrets-history-commands][Shell & Comint Secrets: History commands]] - [[https://www.masteringemacs.org/article/pcomplete-context-sensitive-completion-emacs][PComplete: Context-Sensitive Completion in Emacs]] - [[https://dev.to/_darrenburns/10-tools-to-power-up-your-command-line-4id4][10 tools to power up your command line]] - [[https://www.booleanworld.com/customizing-coloring-bash-prompt/][Creating dynamic bash prompts]] - [[https://github.com/Orkohunter/keep][The Keep Utility]] inspired the =kept= and =keep= commands - [[https://terminalsare.sexy/]["Terminals Are Sexy"]] (portal) - [[https://github.com/riscy/command_line_lint][Command-Line Lint]], another project I maintain - [[http://ohmyz.sh/][oh my zsh]], a community-driven zsh configuration - [[https://github.com/Bash-it/bash-it][bash-it]], a community driven bash configuration And if running a =dumb= terminal in Emacs isn't for you, here are some alternatives: - [[https://leanpub.com/the-tao-of-tmux/read][The Tao of tmux]], re: working in the terminal with tmux - [[https://github.com/zsh-users/zsh-syntax-highlighting][zsh-syntax-highlighting]] - [[https://hackernoon.com/macbook-my-command-line-utilities-f8a121c3b019#.clz934ly3][Shell configuration tips]] from Vitaly Belman - [[http://www.iterm2.com/documentation-shell-integration.html][Shell integration]] for iTerm2 on macOS - [[https://getbitbar.com/][BitBar]] adds program output to menus on macOS ================================================ FILE: shx.el ================================================ ;;; shx.el --- Extras for the comint-mode shell -*- lexical-binding: t -*- ;; Author: Chris Rayner and contributors ;; Maintainer: Chris Rayner ;; Created: May 23 2011 ;; Keywords: terminals, processes, comint, shell, repl ;; URL: https://github.com/riscy/shx-for-emacs ;; SPDX-License-Identifier: GPL-3.0-or-later ;; Package-Requires: ((emacs "24.4")) ;; Version: 1.5.2 ;;; Commentary: ;; shx ("shell-extras") extends comint-mode: it parses markup in the output ;; stream, enabling plots and graphics to be embedded, and adds command-line ;; functions which plug into Emacs (e.g. use :e to edit a file). ;; Type M-x shx RET to create a new shell session using shx. ;; Type M-x customize-group RET shx RET to see customization options. ;; You can enable shx in every comint-mode buffer with (shx-global-mode 1). ;;; Code: (require 'comint) (require 'files) (require 'shell) (require 'subr-x) (eval-when-compile (defvar evil-state) (defvar tramp-syntax)) (declare-function evil-insert-state "ext:evil-states.el" (&optional arg) t) ;;; customization options and other variables (defgroup shx nil "Extras for the (comint-mode) shell." :prefix "shx-" :group 'comint :link '(url-link :tag "URL" "https://github.com/riscy/shx-for-emacs") :link '(emacs-commentary-link :tag "Commentary" "shx.el")) (defcustom shx-disable-undo nil "Whether to automatically disable undo in shx buffers." :type 'boolean) (defcustom shx-path-to-convert "magick" "Path to ImageMagick's convert binary." :type 'string) (defcustom shx-mode-lighter " shx" "Lighter for the shx minor mode." :type 'string) (defcustom shx-path-to-gnuplot "gnuplot" "Path to gnuplot binary." :type 'string) (defcustom shx-img-height 300 "The height at which inlined images and plots are displayed." :type 'integer) (defcustom shx-use-magic-insert t "Whether to dynamically modify input using `shx-magic-insert'. If you change this you'll have to reload shx or restart Emacs." :link '(function-link shx-magic-insert) :type 'boolean) (defcustom shx-leader ":" "Prefix for calling user commands." :type 'regexp) (defcustom shx-comint-advise t "Whether to advise the behavior of a number of `comint-mode' functions." :type 'boolean) (defcustom shx-flash-prompt-time 0.25 "Length of time (in seconds) the prompt flashes, when so advised." :link '(function-link shx-flash-prompt) :type 'float) (defcustom shx-show-hints t "Whether to echo hints when running certain commands." :type 'boolean) (defcustom shx-triggers '(("https?://[A-Za-z0-9,./?=&;_-]+[[:graph:].\"'>)]+" . shx--parse-url)) "Triggers of the form: (regexp . function)." :type '(alist :key-type regexp :value-type function)) (defcustom shx-directory-tracker-regexp nil "Input regexp that triggers the `shell-resync-dirs' command." :link '(function-link shx--directory-tracker) :type '(choice regexp null)) (defcustom shx-kept-commands nil "Shell commands of the form (description . command)." :link '(function-link shx-cmd-kept) :link '(function-link shx-cmd-keep) :type '(alist :key-type string :value-type string)) (defcustom shx-max-input most-positive-fixnum "The largest input allowed in characters. A good value on macOS is 1024, the size of the typeahead buffer; or, set the terminal to canonical mode with `stty -icanon`." :type 'integer) (defcustom shx-max-output most-positive-fixnum "The length at which an output line is long enough to be broken. Setting this to 1024 can lead to enormous performance gains, but sacrifices the soundness of shx's markup and trigger matching." :link '(function-link shx--break-long-line-maybe) :type 'integer) (defvar shx-cmd-prefix "shx-cmd-" "Prefix for user-command functions.") (defvar shx-cmd-syntax "\\([[:graph:]]+\\)[[:space:]]*\\(.*[[:graph:]]?\\)" "Regex for recognizing shx commands in input or markup.") (defvar shx-markup-syntax (concat "^<" shx-cmd-syntax ">\n") "Regex for recognizing shx commands in markup.") (defvar shx-mode-map (let ((keymap (make-sparse-keymap))) (when shx-use-magic-insert (define-key keymap " " #'shx-magic-insert) (define-key keymap "q" #'shx-magic-insert)) ;; different RET keybindings to support different Emacs environments (define-key keymap (kbd "RET") #'shx-send-input-or-open-thing) (define-key keymap (kbd "") #'shx-send-input-or-open-thing) (define-key keymap (kbd "C-") #'shx-send-input-or-copy-line) keymap) "Keymap for shx.") (defvar shx-click-file (let ((keymap (make-sparse-keymap))) (define-key keymap [mouse-1] #'ffap-at-mouse) keymap) "Keymap for capturing mouse clicks on files/URLs.") (defvar-local shx-buffer nil "Local reference to the shx buffer.") (defvar-local shx-prompt-overlay nil "Overlay used to flash the prompt.") (defvar-local shx-urls nil "Local record of URLs seen.") (defvar-local shx--old-undo-disabled nil "Whether undo was disabled before `shx-mode' was enabled.") (defvar-local shx--asynch-point nil) (defvar-local shx--asynch-calling-buffer nil) ;;; input (defun shx-send-input-or-open-thing () "Open thing at point, or send input if no identifiable thing." (interactive) (if (shx-point-on-input-p) (shx-send-input) (find-file-at-point))) (defun shx-send-input-or-copy-line () "Copy current line to prompt, or send input if at the prompt." (interactive) (if (shx-point-on-input-p) (shx-send-input) (let ((line (string-trim (buffer-substring-no-properties (line-beginning-position) (line-end-position))))) (goto-char (point-max)) (insert line)))) (defun shx-send-input () "Send or parse the input currently written at the prompt. In normal circumstances this input is additionally filtered by `shx-filter-input' via `comint-mode'." (interactive) (cond ((not (comint-check-proc shx-buffer)) (shx--restart-shell)) ((>= (length (shx--current-input)) shx-max-input) (user-error "Input line exceeds `shx-max-input'")) (t (shx--propertize-prompt) (remove-text-properties (process-mark (get-buffer-process (current-buffer))) (point-max) '(field)) (comint-send-input)))) (defun shx-filter-input (process input) "Before sending to PROCESS, filter the INPUT. That means, if INPUT is a shx-command, do that command instead. This function overrides `comint-input-sender'." (let* ((regexp (concat "^" shx-leader shx-cmd-syntax)) (match (string-match regexp (string-trim-left input))) (shx-cmd (and match (shx--get-user-cmd (match-string 1 input))))) (if (not shx-cmd) (comint-simple-send process input) (condition-case-unless-debug error-descriptor (funcall shx-cmd (substitute-env-vars (match-string 2 input) t)) (error (shx-insert 'error (error-message-string error-descriptor) "\n"))) (with-current-buffer (process-buffer process) ;; advance the process mark to trick comint-mode (set-marker (process-mark process) (point))) ;; send a blank to fetch a new prompt (when (process-live-p process) (comint-send-string process "\n"))))) (defun shx--directory-tracker (input) "Check INPUT for prefixes that require a call to `shell-resync-dirs'. This is similar to `shell-mode's `shell-directory-tracker'. Adjust the behavior of this function by modifying `shx-directory-tracker-regexp'." (and shell-dirtrackp shx-directory-tracker-regexp (string-match shx-directory-tracker-regexp input 0) (shx--asynch-funcall #'shell-resync-dirs))) (defun shx--propertize-prompt () "Add a mouseover timestamp and `default-directory' info to the last prompt." (let ((inhibit-read-only t) (inhibit-field-text-motion t)) (add-text-properties (line-beginning-position) (process-mark (get-buffer-process (current-buffer))) `(help-echo ,(format-time-string "%x %X") shx-cwd ,default-directory)))) ;;; output (defun shx-parse-output-hook (&optional _output) "Hook to parse the output stream." (shx--parse-output-for-markup) (shx--break-long-line-maybe) (when shx-triggers (shx--parse-output-for-triggers))) (defun shx--parse-output-for-markup () "Look for markup in the latest output from the process." (save-excursion (shx--goto-last-input-or-output) (let ((originating-buffer shx-buffer)) (while (shx--search-forward shx-markup-syntax) (let ((command (shx--get-user-cmd (match-string 1))) (args (match-string 2))) (cond ((not command) nil) ((not (shx--safe-as-markup-p command)) (add-text-properties (line-beginning-position) (line-end-position) `(help-echo "shx: this markup was unsafe/undefined"))) (t (replace-match "") ; hide the markup (funcall command args) (set-buffer originating-buffer)))))))) (defun shx--parse-output-for-triggers () "Look for triggers in the latest output from the process (e.g. URLs)." (dolist (trigger shx-triggers nil) (save-excursion (shx--goto-last-input-or-output) (let ((originating-buffer shx-buffer)) (while (shx--search-forward (car trigger)) ;; emacs 25 had/has a bug where save-window-excursion moves the point ;; backward in the calling buffer (some funcalls might use ;; save-window-excursion) which can cause infinite triggering. For ;; now, handle this by wrapping the funcall in save-excursion. (save-excursion (funcall (cdr trigger))) (set-buffer originating-buffer)))))) (defun shx--goto-last-input-or-output () "Go to the beginning of the latest output from the process." (goto-char (if (marker-position comint-last-output-start) (max comint-last-output-start comint-last-input-end) comint-last-input-end)) (forward-line 0)) (defun shx--search-forward (pattern) "Search forward from the current point for PATTERN. But don't search the last line, which may be incomplete." (when (< (line-end-position) (point-max)) (re-search-forward pattern nil t))) (defun shx--break-long-line-maybe () "Break the current line if it's longer than `shx-max-output'." (when (> (current-column) shx-max-output) (or (re-search-backward "\\s-" (- (point) shx-max-output) t) (backward-char)) (insert-char ?\n) (goto-char (point-max)))) ;;; util (defun shx-browse-urls () "Prompt user for a URL to browse from the list `shx-urls'." (interactive) (let ((urls shx-urls)) ; clone url list so user edits don't modify the entries (browse-url (completing-read "URL: " urls)))) (defun shx-describe-command (shx-command) "Try to describe the named SHX-COMMAND." (let ((prefix (concat shx-cmd-prefix shx-command))) (if (functionp (intern prefix)) (describe-function (intern prefix)) (let ((comp (completing-read "Complete shx command: " (shx--all-commands) nil t prefix))) (describe-function (intern comp)))))) (defun shx--all-commands (&optional without-prefix) "Return a list of all shx commands. With non-nil WITHOUT-PREFIX, strip `shx-cmd-prefix' from each. >> (member \"shx-cmd-delay\" (shx--all-commands)) => (\"shx-cmd-delay\") ; i.e., not nil >> (not (member \"shx-cmd-prefix\" (shx--all-commands))) => t" (declare (side-effect-free t)) (mapcar (lambda (cmd) (if without-prefix (string-remove-prefix shx-cmd-prefix cmd) cmd)) (all-completions shx-cmd-prefix obarray #'functionp))) (defun shx-point-on-input-p () "Check if point is on the input region." (declare (side-effect-free t)) (or (eobp) (let ((process (get-buffer-process (current-buffer)))) (and process (>= (point-marker) (process-mark process)))))) (defun shx-tokenize (str) "Turn STR into a list of tokens, or nil if parsing fails. This is robust to various styles of quoting and escaping." (declare (side-effect-free t) (pure t)) (setq str (shx--replace-from-list ;; protect escaped single/double quotes and spaces: '(("\\\\'" "") ("\\\\ " "") ("\\\\\"" "") ; nofmt ("'" "\"") ; prefer double quoting ("\\\\\\(.\\)" "\\1")) ; remove escape chars str)) (mapcar (lambda (token) (shx--replace-from-list '(("" "'") ("" " ") ("" "\"")) token)) (ignore-errors (split-string-and-unquote str)))) (defun shx--replace-from-list (patterns str) "Replace multiple PATTERNS in STR -- in the supplied order." (declare (side-effect-free t) (pure t)) (dolist (pattern patterns nil) (setq str (replace-regexp-in-string (car pattern) (cadr pattern) str))) str) (defun shx-tokenize-filenames (str) "Turn STR into a list of filenames, or nil if parsing fails. If any path is absolute, prepend `comint-file-name-prefix' to it." (declare (side-effect-free t)) (mapcar (lambda (filename) (cond ((not (file-name-absolute-p filename)) filename) (t (concat comint-file-name-prefix filename)))) (shx-tokenize str))) (defun shx--hint (format-string &rest args) "Show a hint containing FORMAT-STRING with optional ARGS." (when shx-show-hints (apply #'message (cons format-string args)))) (defun shx--current-prompt () "Return text from start of line to current `process-mark'." (declare (side-effect-free t)) (cond ((get-buffer-process (current-buffer)) (save-excursion (goto-char (point-max)) (let ((inhibit-field-text-motion t)) (buffer-substring-no-properties (line-beginning-position) (process-mark (get-buffer-process (current-buffer))))))) (t (user-error "There is no process") ""))) (defun shx--current-input () "Return what's written after the prompt." (declare (side-effect-free t)) (buffer-substring (process-mark (get-buffer-process (current-buffer))) (line-end-position))) (defun shx--get-timer-list () "Get the list of resident timers." (declare (side-effect-free t)) (let ((timer-list-1 (mapcar (lambda (timer) (when (shx--timer-by-shx-p timer) timer)) timer-list))) ;; sort the timers for consistency (sort (remove nil timer-list-1) (lambda (first-timer second-timer) (string< (format "%s" (aref first-timer 5)) (format "%s" (aref second-timer 5))))))) (defun shx--timer-by-shx-p (timer) "Return non-nil if TIMER was created by shx." (declare (side-effect-free t)) (string-prefix-p "(lambda nil (shx--auto" (format "%s" (aref timer 5)))) (defun shx--get-user-cmd (cmd-prefix) "Return user command prefixed by CMD-PREFIX, or nil." (declare (side-effect-free t)) (let* ((prefix (format "%s%s" shx-cmd-prefix (downcase cmd-prefix))) (completion (try-completion prefix obarray #'functionp))) (when completion (let ((user-cmd (intern (if (eq completion t) prefix completion)))) (when (functionp user-cmd) user-cmd))))) (defun shx--parse-url () "Add a matched URL to `shx-urls' and apply `shx-click-file'." (let ((url (match-string-no-properties 0))) (unless (string= url (car shx-urls)) (push url shx-urls))) (add-text-properties (match-beginning 0) (match-end 0) `(keymap ,shx-click-file mouse-face highlight font-lock-face link))) (defun shx--restart-shell (&optional new-directory) "Guess the shell command and use `comint-exec' to restart. If optional NEW-DIRECTORY is set, use that for `default-directory'." ;; This can be tricky, so be proactive about telling the user what's going on (let ((default-directory (or new-directory default-directory))) (when (file-remote-p default-directory) (message "Restarting shell at %s (C-g to stop)" default-directory)) (let ((cmd (shx--shell-command))) (shx-insert 'font-lock-doc-face "\n" cmd " at " default-directory "\n") ;; manually align comint-file-name-prefix with the default-directory: (setq-local comint-file-name-prefix (or (file-remote-p default-directory) "")) (comint-exec (current-buffer) (buffer-name) cmd nil nil) ;; since tramp overrides `shell-file-name' with "/bin/sh" when remote: (setq-local explicit-shell-file-name cmd))) ;; if all that was successful, commit to the new default directory: (when new-directory (setq default-directory new-directory)) (when (file-remote-p default-directory) (shx--hint "Return to the localhost with '%sssh'" shx-leader))) (defun shx--shell-command () "Get the shell command, even if on a remote host or container." (declare (side-effect-free t)) (let* ((remote-id (or (file-remote-p default-directory) "")) ;; guess which shell command to run per `shell' convention: (cmd (or explicit-shell-file-name (getenv "ESHELL") shell-file-name))) (cond ((file-exists-p (concat remote-id cmd)) cmd) (t (completing-read "Shell command: " nil nil nil "/bin/sh" nil))))) (defun shx--match-last-line (regexp) "Return a form to find REGEXP on the last line of the buffer." `(lambda (bound) (let ((inhibit-field-text-motion t)) (when (eq (point-max) (line-end-position)) (re-search-forward ,regexp bound t))))) (defun shx--quote-regexp (delimiter &optional escape max-length) "Regexp matching strings delimited by DELIMITER. ESCAPE is the string that can be used to escape the delimiter \(defaults to backslash; ignored when set to the empty string). MAX-LENGTH is the length of the longest match (default 300)." (declare (side-effect-free t)) (setq escape (or escape "\\\\")) (concat delimiter "\\(" (unless (string= "" escape) (concat escape escape "\\|" ; two escapes OR escape delimiter "\\|")) ; escaped delimiter "[^" delimiter "]" "\\)" "\\{0," (format "%d" (or max-length 300)) "\\}" delimiter)) (defun shx--safe-as-markup-p (command) "Return t if COMMAND is safe to call to generate markup. In particular whether \"(SAFE)\" prepends COMMAND's docstring." (declare (side-effect-free t)) (let ((doc (documentation command))) (and doc (string-prefix-p "(SAFE)" doc)))) (defun shx--reveal-kept-commands (&optional regexp insert-kept-command) "Add commands from `shx-kept-commands' into `comint-input-ring'. REGEXP filters which commands to add. If INSERT-KEPT-COMMAND is not nil, then insert the command into the current buffer." (dolist (command shx-kept-commands nil) (when (string-match (or regexp ".") (concat (car command) (cdr command))) (when insert-kept-command (ring-insert comint-input-ring (cdr command))) (shx-insert 'font-lock-constant-face (car command) ": " 'font-lock-string-face command (cdr command) "\n")))) ;;; sending/inserting (defun shx-magic-insert () "Insert the key pressed or dynamically change the input. `comint-magic-space' completes substitutions like '!!', '!*', or '^pattern^replacement' and, if the prompt is a colon, SPC and q are sent straight through to the process to handle paging." (interactive) (let ((on-input (shx-point-on-input-p))) (if (and on-input (string-match "^\\s-*$" (shx--current-input)) (string-match ":$" (shx--current-prompt))) (progn (shx--hint "Sending '%s'" (this-command-keys)) (process-send-string nil (this-command-keys))) (unless on-input (goto-char (point-max))) (if shx-use-magic-insert (comint-magic-space 1) (self-insert-command 1))))) (defun shx-cat (&rest args) "Like `concat' but ARGS can be strings or face names." (declare (side-effect-free t)) (let ((string "") (face nil)) (dolist (arg args nil) (cond ((stringp arg) (setq string (concat string (propertize arg 'font-lock-face face 'rear-nonsticky t)))) ((facep arg) (setq face arg)))) string)) (defun shx-insert (&rest args) "Insert ARGS as an output field, combined using `shx-cat'." (insert (propertize (apply #'shx-cat args) 'field 'output))) (defun shx-insert-timer-list () "Insert a list of the Emacs timers currently in effect." (let ((sorted-timer-list (shx--get-timer-list))) (dotimes (timer-number (length sorted-timer-list)) (shx--insert-timer (1+ timer-number) (nth timer-number sorted-timer-list)) (shx-insert "\n")) (shx-insert "Active timers: " 'font-lock-constant-face (format "%d\n" (length sorted-timer-list))))) (defun shx-insert-image (filename) "Insert image FILENAME into the buffer." (let* ((img-name (make-temp-file "tmp" nil ".png")) (status (call-process shx-path-to-convert nil t nil (expand-file-name filename) "-resize" (format "x%d>" shx-img-height) img-name))) (when (zerop status) (let ((pos (point))) (insert-image (create-image img-name)) (add-text-properties pos (point) `(help-echo ,filename))))) (shx-insert "\n") (shx-show-output)) (defun shx-insert-plot (filename plot-command line-style) "Prepare a plot of the data in FILENAME. Use a gnuplot specific PLOT-COMMAND (for example `plot`) and LINE-STYLE (for example `w lp`); insert the plot in the buffer." (let* ((img-name (make-temp-file "tmp" nil ".png")) (color (face-attribute 'default :foreground)) (filename (shx--shell-quote-no-quotation-marks filename)) (status (call-process shx-path-to-gnuplot nil t nil "-e" (concat "set term png transparent truecolor;" "set border lc rgb \"" color "\";" "set out \"" img-name "\";" plot-command "\"" filename "\"" line-style " notitle")))) (when (zerop status) (shx-insert-image img-name)))) (defun shx--shell-quote-no-quotation-marks (str) "Shell-quote STR, but strip the \"s added in some `system-type's." (replace-regexp-in-string ; NOTE: in Emacs 26+ we can use `string-trim' "\"$" "" (replace-regexp-in-string "^\"" "" (shell-quote-argument str)))) (defun shx--insert-timer (timer-number timer) "Insert a line of the form ' '." (shx-insert 'font-lock-constant-face (format "%d. " timer-number) 'font-lock-string-face (format "%s" (shx--format-timer-string timer)) (when (aref timer 4) (format "\s(pulse: %d)" (aref timer 4))))) (defun shx--format-timer-string (timer) "Create a human-readable string out of TIMER." (declare (side-effect-free t)) (let* ((str (format "%s" (aref timer 5))) (output (string-remove-prefix "(lambda nil (shx--auto " (string-remove-suffix "))" str)))) (concat "[" output "]"))) ;;; asynch functions (defun shx--asynch-funcall (function &optional args delay) "Run FUNCTION with ARGS in the buffer after a short DELAY." (run-at-time (or delay 0.2) nil `(lambda () (with-current-buffer ,shx-buffer ,(cons function args))))) (defun shx--asynch-run (command) "Run shell COMMAND asynchronously; bring the results over when done. If a process is already running in the shx-asynch buffer, kill it." (let ((output-buffer (get-buffer-create " *shx-asynch*"))) (when (get-buffer-process output-buffer) (kill-process (get-buffer-process output-buffer)) (while (get-buffer-process output-buffer) (sleep-for 0.01))) (setq-local shx--asynch-point (point)) (shx-insert 'font-lock-comment-face "Wait..." 'default "\n") (let ((calling-buffer shx-buffer)) (save-window-excursion (async-shell-command command output-buffer)) (set-buffer output-buffer) (setq-local shx--asynch-calling-buffer calling-buffer) (let ((process (get-buffer-process output-buffer))) (set-process-sentinel process #'shx--asynch-sentinel) (set-process-query-on-exit-flag process nil))))) (defun shx--asynch-sentinel (process signal) "Sentinel called when PROCESS sees SIGNAL." (when (memq (process-status process) '(exit signal)) (set-buffer (process-buffer process)) (let* ((out (buffer-substring (point-min) (point-max)))) (set-buffer shx--asynch-calling-buffer) (when (>= shx--asynch-point (point-max)) (setq-local shx--asynch-point 0)) (save-excursion (goto-char shx--asynch-point) (let ((inhibit-read-only t)) (shx-insert 'font-lock-comment-face (capitalize signal) 'default out) (unless (= 0 shx--asynch-point) (delete-region (line-beginning-position) (min (point-max) (1+ (line-end-position)))))))))) (defun shx--delay-input (delay input &optional buffer repeat-interval) "After DELAY, process INPUT in the BUFFER. If BUFFER is nil, process in the current buffer. Optional REPEAT-INTERVAL specifies delays between repetitions." (let* ((process (get-buffer-process (buffer-name buffer))) (funcall `(lambda () ,(cons #'shx--auto (list process input))))) (run-at-time delay repeat-interval funcall))) (defun shx--auto (process command) "Send PROCESS a COMMAND. \(Makes the `shx-insert-timer-list' listing easier to parse.)" (process-send-string process (concat command "\n"))) ;;; asynch user commands (defun shx-cmd-delay (args) "Run a command after a specific delay. ARGS are . Cancel a delayed command with :stop (`shx-cmd-stop'). \nExample:\n :delay 10 echo Ten seconds are up!" (cond ((string-match "^\\([0-9.]+\\)\\s-+\\(.+\\)$" args) (let ((delay (match-string 1 args)) (command (match-string 2 args))) (shx-insert "Delaying " 'comint-highlight-input command 'default (format " %s seconds\n" delay)) (shx--delay-input (concat delay " sec") command)) (shx--hint "cancel a delayed command with :stop")) (t (shx-insert 'error "delay \n")))) (defun shx-cmd-pulse (args) "Repeat a shell command indefinitely with a given delay. ARGS are a string of the form ' '. Cancel a pulsing command with :stop (`shx-cmd-stop'). \nExample:\n :pulse 10 date" (cond ((string-match "^\\([0-9.]+\\)\\s-+\\(.+\\)$" args) (let ((delay (string-to-number (match-string 1 args))) (command (match-string 2 args))) (shx-insert "Pulsing " 'comint-highlight-input command 'default (format " every %d seconds\n" delay)) (shx--delay-input 0 command nil delay)) (shx--hint "cancel a pulsing command with :stop")) (t (shx-insert 'error "pulse \n")))) (defun shx-cmd-repeat (args) "Repeat a shell command a number of times with a given delay. ARGS are . Cancel a repeating command with :stop (`shx-cmd-stop'). \nExample:\n :repeat 3 1 echo Echo... echo... echo..." (cond ((string-match "^\\([0-9]+\\)\\s-+\\([0-9.]+\\)\\s-+\\(.+\\)$" args) (let ((reps (string-to-number (match-string 1 args))) (delay (string-to-number (match-string 2 args))) (command (match-string 3 args))) (shx-insert "Repeating " 'comint-highlight-input command 'default (format " %d times every %d seconds\n" reps delay)) (dotimes (ii reps) (shx--delay-input (* (1+ ii) delay) command))) (shx--hint "cancel a repeating command with :stop")) (t (shx-insert 'error "repeat \n")))) (defun shx-cmd-stop (timer-number) "(SAFE) Stop the specified shx timer. If a TIMER-NUMBER is not supplied, enumerate all shx timers. \nExamples:\n :stop :stop 3" (setq timer-number (1- (string-to-number timer-number))) (let ((shx-timer-list (shx--get-timer-list))) (and (>= timer-number 0) (< timer-number (length shx-timer-list)) (let ((timer (nth timer-number shx-timer-list))) (shx-insert "Stopped " 'font-lock-string-face (shx--format-timer-string timer) "\n") (cancel-timer timer)))) (shx-insert-timer-list)) ;;; general user commands (defun shx-cmd-alert (string) "(SAFE) Show the `shx-buffer' in the other window with STRING." (message "From %s at %s: '%s'" shx-buffer (format-time-string "%X") string) (display-buffer shx-buffer)) (defun shx-cmd-clear (_args) "(SAFE) Clear the buffer." ;; this is `comint-clear-buffer' from Emacs >= 25 : (let ((comint-buffer-maximum-size 0)) (comint-truncate-buffer))) (defun shx-cmd-date (_args) "(SAFE) Show the date." (shx-insert (current-time-string) "\n")) (defun shx-cmd-diff (files) "(SAFE) Launch an Emacs `ediff' between FILES. \nExample:\n :diff file1.txt \"file 2.csv\"" (setq files (shx-tokenize-filenames files)) (if (/= (length files) 2) (shx-insert 'error "diff " "\n") (shx-insert "Diffing " 'font-lock-doc-face (car files) 'default " and " 'font-lock-doc-face (cadr files) "\n") (shx--asynch-funcall #'ediff (mapcar #'expand-file-name files)))) (defun shx-cmd-edit (file) "(SAFE) Open FILE in the current window. \nExamples:\n :e directory/to/file \nOr edit a remote file using `tramp':\n :e /ssh:user@server#port:directory/to/file :e /docker:02fbc948e009:/directory/to/file" (setq file (car (shx-tokenize-filenames file))) (if (or (string= "" file) (not file)) (shx-insert 'error "Couldn't parse filename" "\n") (shx-insert "Editing " 'font-lock-doc-face file "\n") (shx--asynch-funcall #'find-file (list (expand-file-name file) t)))) (defalias 'shx-cmd-e #'shx-cmd-edit) (defun shx-cmd-eval (sexp) "Evaluate the elisp SEXP. \nExamples:\n :eval (format \"%d\" (+ 1 2)) :eval (* 2 (+ 3 5))" (let ((originating-buffer (current-buffer)) (output (prin1-to-string (eval (car (read-from-string sexp)))))) (with-current-buffer originating-buffer (shx-insert 'font-lock-constant-face "=> " output "\n")))) (defun shx-cmd-find (pattern) "Run fuzzy find for PATTERN. Depending on the contents of the current directory, this command may take a while and unfortunately blocks Emacs in the meantime. \nExamples:\n :f prefix :f *suffix" (if (equal pattern "") (shx-insert 'error "find " "\n") (let ((pattern (mapconcat #'char-to-string (string-to-list pattern) "*")) (filters "-not -path '*/.*' -not -path '*/__pycache__/*'")) (shx--asynch-run (format "find $PWD %s -iname '%s*'" filters pattern))))) (defun shx-cmd-pipe (command) "Pipe the output of COMMAND to a compilation buffer. \nExamples:\n :pipe make :pipe git repack -a -d --depth=250 --window=250" (if (equal command "") (shx-insert 'error "pipe " "\n") (switch-to-buffer-other-window "*shx-pipe*") (let ((compilation-buffer-name-function (lambda (_mode) "*shx-pipe*"))) (shx-insert "Piping " 'comint-highlight-input command 'default " to " "*shx-pipe*\n") (compile command t)))) (defun shx-cmd-g (pattern) "Launch a recursive grep for PATTERN." (grep (format "grep -irnH '%s' *" pattern))) (defun shx-cmd-goto-url (_arg) "Go to a a URL, offering completions from the buffer." (shx--asynch-funcall #'shx-browse-urls)) (defun shx-cmd-grep (args) "Launch a grep using the supplied command line ARGS. \nExamples:\n :grep -r pattern * :grep pattern * | grep -v exclusion" (grep (format "grep -nH %s" args))) (defun shx-cmd-header (header) "(SAFE) Set the header-line to HEADER. See `header-line-format' for formatting options. \nExamples:\n :header remote:%@ status:%s size:%i :header \nOr, adding
in markup form to your prompt:\n export PS1=\"
\\\\n$PS1\" export PS1=\"
/dev/null|paste -sd \\\" \\\" - )>\\\\n$PS1\"" (setq header-line-format (and (not (string-empty-p header)) header))) (defun shx-cmd-help (shx-command) "(SAFE) Display help on the SHX-COMMAND. If function doesn't exist (or none is supplied), read from user." (shx--asynch-funcall #'shx-describe-command (list shx-command))) (defalias 'shx-cmd-h #'shx-cmd-help) (defun shx-cmd-keep (_arg) "(SAFE) Add the previous command into `shx-kept-commands'. This enables it to be accessed later using `shx-cmd-kept'." (let* ((command (substring-no-properties (ring-ref comint-input-ring 1))) (desc (read-string (format "'%s'\nDescription: " command)))) (if (string-empty-p desc) (shx-insert 'error "Description is required" "\n") (add-to-list 'shx-kept-commands `(,desc . ,command)) (customize-save-variable 'shx-kept-commands shx-kept-commands) (shx-insert "Keeping as " 'font-lock-doc-face desc "\n") (shx--hint "type ':kept' or ':k' to see all kept commands")))) (defun shx-cmd-kept (regexp) "(SAFE) List the \"kept\" commands that match REGEXP. Each matching command is appended to the input history, enabling access via \\[comint-previous-input] and \\[comint-next-input].\n The list containing all of these commands is `shx-kept-commands'. That list can be added to using `shx-cmd-keep'." (cond ((string-empty-p regexp) (shx--reveal-kept-commands ".*" nil) (shx--hint "M-x customize-variable shx-kept-commands edits this list")) (t (shx--reveal-kept-commands regexp t) (shx--hint "Commands have been appended to session history")))) (defalias 'shx-cmd-k #'shx-cmd-kept) (defun shx-cmd-man (topic) "Launch an Emacs `man' window for TOPIC. See `Man-notify-method' for what happens when the page is ready." (man topic)) (defun shx-cmd-name (name) "(SAFE) Rename the current buffer to NAME." (rename-buffer (generate-new-buffer-name name))) (defun shx-cmd-oedit (file) "(SAFE) open FILE in other window. \nExamples:\n :oedit directory/to/file :oedit /username@server:~/directory/to/file" (setq file (car (shx-tokenize-filenames file))) (if (or (string= "" file) (not file)) (shx-insert 'error "Couldn't parse filename" "\n") (shx-insert "Editing " 'font-lock-doc-face file "\n") (find-file-other-window (expand-file-name file)))) (defun shx-cmd-pwd (_args) "(SAFE) Show what Emacs thinks the default directory is. \nNote if you're at a shell prompt, you can probably use \\[shell-resync-dirs] to reset Emacs' pwd to the shell's pwd." (shx-insert default-directory "\n")) (defun shx-cmd-ssh (host) "Open a shell on HOST using tramp. \nThis way you benefit from the remote host's completions, and commands like :pwd and :edit will work correctly. Use :ssh on its own to point the process back at the local filesystem. \nExample:\n :ssh username@hostname:port :ssh" (let ((host (substring-no-properties (replace-regexp-in-string ":" "#" host)))) (shx--restart-shell (cond ((string= "" host) (getenv "HOME")) ((eq tramp-syntax 'default) (format "/ssh:%s:~" host)) (t (concat "/" host "~:")))))) (defun shx-cmd-docker (container-id) "Open a shell in a Docker container with CONTAINER-ID." (if (and (version< emacs-version "29") (not (require 'docker-tramp nil t))) (shx-insert 'error "Install the 'docker-tramp' package first\n") (let ((host (substring-no-properties (replace-regexp-in-string ":" "#" container-id)))) (shx--restart-shell (cond ((string= "" host) (getenv "HOME")) ((eq tramp-syntax 'default) (format "/docker:%s:~" host)) (t (concat "/" host "~:"))))))) (defun shx-cmd-sedit (file) "Open local FILE using sudo (i.e. as super-user). \nExample:\n :sedit /etc/passwd" (shx-cmd-edit (concat "/sudo::" (expand-file-name file)))) ;;; graphical user commands (defun shx-cmd-plotbar (filename) "(SAFE) Show barplot of FILENAME. \nFor example, \":plotbar file.dat\" where file.dat contains:\n \"Topic 1\" YHEIGHT1 \"Topic 2\" YHEIGHT2 \"Topic 3\" YHEIGHT3" (shx-insert-plot (car (shx-tokenize-filenames filename)) (concat "set boxwidth 1.5 relative;" "set style data histograms;" "set xtic rotate by -40 scale 0 font \",10\";" "set yrange [0:];" "set style fill solid 1.0 border -1;" "plot") "u 2:xticlabels(1)")) (defun shx-cmd-plotmatrix (filename) "(SAFE) Show heatmap of FILENAME. \nFor example, \":plotmatrix file.dat\" where file.dat contains:\n 1.5 2 3\n 4 5 6\n 7 8 9.5" (shx-insert-plot (car (shx-tokenize-filenames filename)) (concat "set view map; unset xtics; unset ytics;" "unset title; set colorbox; set palette defined" "(0 \"#ffffff\", 1 \"#d5e585\", 2 \"#8cc555\"," "3 \"#55a550\", 4 \"#1e5500\");" "plot") "u 1:(-$2):3 matrix w image")) (defun shx-cmd-plotline (filename) "(SAFE) Show line plot of FILENAME. \nFor example, \":plotscatter file.dat\", where file.dat contains: 1 2\n 2 4\n 4 8\n Or just a single column: 1\n 2\n 3\n 5" (shx-insert-plot (car (shx-tokenize-filenames filename)) "plot" "w l lw 1")) (defun shx-cmd-plot3d (filename) "(SAFE) Show surface plot of FILENAME. Read about gnuplot's expectations of the data here: http://www.gnuplotting.org/tag/pm3d/" (shx-insert-plot (car (shx-tokenize-filenames filename)) "unset tics;set view 4, 20, 1.4, 1;splot" "w pm3d")) (defun shx-cmd-plotscatter (filename) "(SAFE) Show scatter plot of FILENAME. \nFor example, \":plotscatter file.dat\", where file.dat contains: 1 2\n 2 4\n 4 8\n Or just a single column: 1\n 2\n 3\n 5" (shx-insert-plot (car (shx-tokenize-filenames filename)) "plot" "w p ps 2 pt 7")) (defalias 'shx-cmd-plot #'shx-cmd-plotscatter) (defun shx-cmd-plotrug (filename) "(SAFE) Show a rug plot of the one-dimensional dataset in FILENAME. Use \":plotrug FILENAME\" where the contents of that file might be: \n 50\n 25\n 12\n 6\n 3\n 1" (shx-insert-plot (car (shx-tokenize-filenames filename)) (concat "set border 1;" "set xtics nomirror;" "set yrange [0:1];" "unset ytics;" "plot") "using 1:(1) with impulses")) (defun shx-cmd-view (filename) "(SAFE) View image with FILENAME directly in the buffer." (shx-insert-image (car (shx-tokenize-filenames filename)))) (defalias 'shx-cmd-imgcat #'shx-cmd-view) ;;; loading (defcustom shx-shell-mode-font-locks `((,(shx--match-last-line (shx--quote-regexp "`")) 0 'font-lock-builtin-face) ; nofmt (,(shx--match-last-line (shx--quote-regexp "\"")) 0 'font-lock-string-face) ; nofmt (,(shx--match-last-line (shx--quote-regexp "'")) 0 'font-lock-string-face) ; nofmt (,(shx--match-last-line "#.*[^#^\n]*$") 0 'font-lock-comment-face) ; nofmt (,(shx--match-last-line (regexp-opt '("~" ">" "<" "&" "|" ";"))) 0 'font-lock-keyword-face) ; nofmt ("\\(\\\\) .*\\'" 1 'font-lock-constant-face) ("\\(\\\\) .*\\'" 1 'font-lock-constant-face) ("\\(\\\\) .*\\'" 1 'font-lock-constant-face) ("\\(\\\\) .*\\'" 1 'font-lock-constant-face) ("\\(\\\\) .*\\'" 1 'font-lock-constant-face) ("\\(\\\\) .*\\'" 1 'font-lock-warning-face) ("\\(\\\\) .*\\'" 1 'font-lock-warning-face) ("\\(\\\\) .*\\'" 1 'font-lock-warning-face)) "Some additional syntax highlighting for `shell-mode' only." :type '(alist :key-type (choice regexp function))) (defcustom shx-font-locks `((,(concat "[^[:alnum:]" shx-leader "]" shx-leader "\\(\\<" (regexp-opt (shx--all-commands 'without-prefix)) "\\>\\).*\\'") 1 'font-lock-keyword-face)) "Syntax highlighting of builtin commands for the shx minor mode." :type '(alist :key-type (choice regexp function))) ;;;###autoload (define-minor-mode shx-mode "Toggle this minor mode on or off. \nThis minor mode provides extra functionality to `shell-mode' and `comint-mode' in general. Use `shx-global-mode' to enable `shx-mode' in all buffers that support it. \nProvides the following key bindings: \n\\{shx-mode-map}" :lighter shx-mode-lighter :keymap shx-mode-map (if shx-mode (shx--activate) (shx--deactivate))) (defun shx--activate () "Add font-locks, tweak defaults, add hooks/advice." (if (not (shx--compatible-p)) (error "WARNING: shx is incompatible with `%s'" major-mode) (when (derived-mode-p 'shell-mode) (font-lock-add-keywords nil shx-shell-mode-font-locks)) (font-lock-add-keywords nil shx-font-locks) (setq-local font-lock-keywords-case-fold-search t) (setq-local shx-buffer (current-buffer)) (setq-local shx--old-undo-disabled (eq t buffer-undo-list)) (when shx-disable-undo (buffer-disable-undo)) ;; do this one with a delay because spacemacs tries to set this variable too: (shx--asynch-funcall (lambda () (setq-local comint-input-sender 'shx-filter-input))) (make-local-variable 'comint-output-filter-functions) (make-local-variable 'comint-input-filter-functions) (add-hook 'comint-input-filter-functions #'shx--directory-tracker nil t) (add-hook 'comint-output-filter-functions #'shx-parse-output-hook nil t) (shx--advise))) (defun shx--deactivate () "Remove font-locks and hooks, and restore variable defaults." (when (derived-mode-p 'shell-mode) (font-lock-remove-keywords nil shx-shell-mode-font-locks)) (font-lock-remove-keywords nil shx-font-locks) (unless shx--old-undo-disabled (buffer-enable-undo)) (setq-local comint-input-sender (default-value 'comint-input-sender)) (setq-local font-lock-keywords-case-fold-search (default-value 'font-lock-keywords-case-fold-search)) (remove-hook 'comint-input-filter-functions #'shx--directory-tracker t) (remove-hook 'comint-output-filter-functions #'shx-parse-output-hook t)) ;;;###autoload (define-globalized-minor-mode shx-global-mode shx-mode shx--global-on) (defun shx--global-on () "Call the function `shx-mode' if appropriate for the buffer." (when (shx--compatible-p) (shx-mode +1))) (defun shx--compatible-p () "Return non-nil if shx can be activated in the current buffer." (and (derived-mode-p 'comint-mode) ;; modes that override comint-input-sender are incompatible (#32) (eq comint-input-sender (default-value 'comint-input-sender)) ;; modes that override the RET binding are incompatible (#25) (eq (local-key-binding (kbd "RET")) 'comint-send-input))) ;;;###autoload (defun shx (&optional name directory) "Create a new shx-enhanced shell session. The new buffer is called NAME and uses DIRECTORY as its `default-directory'. See the function `shx-mode' for details." (interactive) (let ((name (or name (generate-new-buffer-name "*shx*"))) (default-directory (or directory default-directory))) ;; `switch-to-buffer' first (`shell' uses the unpredictable `pop-to-buffer') (switch-to-buffer name) (let ((explicit-shell-file-name (shx--shell-command))) (shell name)) ;; shx might already be active due to shx-global-mode: (unless shx-mode (shx-mode)))) ;;; advice to change the behavior of some functions within `shx-mode' (defun shx-show-output (&rest _args) "Recenter window so that as much output as possible is shown. This function only works when the shx minor mode is active." (and shx-mode shx-comint-advise ;; `recenter'ing errors when this isn't the active buffer: (ignore-errors (comint-show-maximum-output)))) (defun shx-flash-prompt (&rest _args) "Flash the text on the line with the highlight face." (when (and shx-comint-advise (> shx-flash-prompt-time 0)) (setq-local shx-prompt-overlay (make-overlay (point) (line-end-position))) (overlay-put shx-prompt-overlay 'face 'highlight) (sit-for shx-flash-prompt-time) (delete-overlay shx-prompt-overlay))) (defun shx-switch-to-insert (&rest _args) "Switch to insert-mode (when applicable). This function only works when the shx minor mode is active." (and shx-mode shx-comint-advise (featurep 'evil-vars) (not (equal evil-state 'insert)) (featurep 'evil-states) (evil-insert-state))) (defun shx--with-shx-cwd (func &rest args) "Call FUNC with ARGS using the `shx-cwd' property as `default-directory'." (if (not shx-mode) (apply func args) (let* ((shx-comint-advise nil) (inhibit-field-text-motion t) (shx-cwd (save-excursion (comint-previous-prompt 1) (get-text-property (line-beginning-position) 'shx-cwd))) (default-directory (or shx-cwd default-directory))) (apply func args)))) (defun shx--advise () "Advise a number of functions with shx enhancements." (advice-add #'find-file-at-point :around #'shx--with-shx-cwd) (advice-add #'ffap-at-mouse :around #'shx--with-shx-cwd) (when shx-comint-advise (advice-add #'comint-kill-input :before #'shx-switch-to-insert) (advice-add #'comint-send-input :after #'shx-switch-to-insert) (advice-add #'comint-history-isearch-backward-regexp :before #'shx-show-output) (advice-add #'comint-kill-input :before #'shx-show-output) (advice-add #'comint-send-eof :before #'shx-show-output) ;; NOTE: comint-next-prompt is called by comint-previous prompt too (advice-add #'comint-next-prompt :after #'shx-flash-prompt))) (defun shx-unload-function () "Pre-cleanup when `unload-feature' is called." (advice-remove #'find-file-at-point #'shx--with-shx-cwd) (advice-remove #'ffap-at-mouse #'shx--with-shx-cwd) (advice-remove #'comint-kill-input #'shx-switch-to-insert) (advice-remove #'comint-send-input #'shx-switch-to-insert) (advice-remove #'comint-history-isearch-backward-regexp #'shx-show-output) (advice-remove #'comint-kill-input #'shx-show-output) (advice-remove #'comint-send-eof #'shx-show-output) (advice-remove #'comint-next-prompt #'shx-flash-prompt) nil) (provide 'shx) ;;; shx.el ends here ================================================ FILE: test/script.el ================================================ ;; To run unit tests from the project root: ;; `emacs -q --script ./test/script.el` (add-to-list 'load-path ".") (add-to-list 'load-path "test") (require 'shx) (require 'shx-test) ;; only the headless unit tests can be run in script mode (dolist (test (all-completions "shx-test-unit" obarray 'functionp)) (funcall (intern test))) ;; kill emacs with an error code corresponding to success (kill-emacs (if shx-test-recent-success 0 1)) ================================================ FILE: test/shx-test.el ================================================ ;;; shx-test.el --- Tests for shx ;; Authors: Chris Rayner (dchrisrayner @ gmail) ;; URL: https://github.com/riscy/shx-for-emacs ;; Package-Requires: ((emacs "24.4")) ;; Version: 0.0.0 ;; This file is NOT part of GNU Emacs. ;; This file 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, or (at your option) ;; any later version. ;; This file 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 file. If not, see . ;;; Commentary: ;; Tests for shx. To run in a comint session with shx active use :test ;;; Code: (require 'shx) (defvar shx-test-recent-success t "Whether the last test run succeeded.") (defun shx-cmd-test (_args) "Test shx. Example: :test" ;; Test the use of markup: (shx-insert "\n\n")) (defun shx-cmd-test-all (_args) "(SAFE) Call the 'shx-test-unit' and 'shx-test-integration' functions." (setq shx-test-recent-success t) (shx--asynch-funcall (lambda () (dolist (test-function (append (all-completions "shx-test-unit" obarray 'functionp) (all-completions "shx-test-integration" obarray 'functionp))) (funcall (intern test-function)))) (recenter -1))) (defun shx-test-assert (comment val) "Describe test with COMMENT; test truth of VAL." (save-excursion (goto-char (point-max)) (forward-line -1) (goto-char (point-at-eol)) (setq shx-test-recent-success (and shx-test-recent-success val)) (let ((output (format "%s %s\n" (if val "✔" "✘") comment))) (if (display-graphic-p) (shx-insert output) (send-string-to-terminal output))))) (defun shx-test-warn (text) "Warn with TEXT." (save-excursion (goto-char (point-max)) (forward-line -1) (goto-char (point-at-bol)) (shx-insert 'error text "\n"))) ;; tests! (defun shx-test-unit-checkdoc () "Run `checkdoc' against the shx.el file." (ignore-errors (kill-buffer "*Warnings*")) (let ((file (replace-regexp-in-string ".elc$" ".el" (symbol-file 'shx-mode)))) (if (fboundp 'checkdoc-file) (checkdoc-file file)) (shx-test-assert "shx.el passes checkdoc" (null (get-buffer "*Warnings*"))))) (defun shx-test-unit-byte-compile () "Test byte-compilation against the shx.el file." (ignore-errors (kill-buffer "*Compile-Log*")) (let ((file (replace-regexp-in-string ".elc$" ".el" (symbol-file 'shx-mode)))) (shx-test-assert "shx.el passes byte-compilation" (byte-compile-file file)))) (defun shx-test-unit-declare-function () "Test `declare-function'." (let ((file (replace-regexp-in-string ".elc$" ".el" (symbol-file 'shx-mode)))) (shx-test-assert "shx-el passes check-declare-file" (not (check-declare-file file))))) (defun shx-test-unit-quote-regexp () "Test pattern matching on delimited regexps like strings." (shx-test-assert "shx--quote-regexp matches escaped regexps correctly" (let ((pattern "`echo \\\\\\`echo\\\\\\``")) (string-match (shx--quote-regexp "`") pattern) (string= pattern (match-string 0 pattern)))) (shx-test-assert "shx--quote-regexp matches unescaped regexps correctly" (let ((pattern "'don\\'t'")) (string-match (shx--quote-regexp "'" "") pattern) (string= "'don\\'" (match-string 0 pattern))))) (defun shx-test-unit-safe-as-markup () "Test recognition of safe functions." (shx-test-assert "shx--safe-as-markup-p recognizes unsafe command" (not (shx--safe-as-markup-p #'shx-cmd-eval))) (shx-test-assert "shx--safe-as-markup-p recognizes a safe command" (shx--safe-as-markup-p #'shx-cmd-stop)) (shx-test-assert "shx--safe-as-markup-p handles undocumented command" (not (shx--safe-as-markup-p (lambda () t))))) (defun shx-test-unit-shell-quote-no-quotation-marks () "Test `shx--shell-quote-no-quotation-marks'." (shx-test-assert "shx--shell-quote-no-quotation-marks escapes string" (string= (shx--shell-quote-no-quotation-marks "test\"test") "test\\\"test"))) (defun shx-test-unit-get-user-cmd () "Test `shx--get-user-cmd'." (shx-test-assert "shx--get-user-cmd returns nil for empty string" (null (shx--get-user-cmd ""))) (shx-test-assert "shx--get-user-cmd returns command with correct prefix" (eq (shx--get-user-cmd "test-al") 'shx-cmd-test-all))) (defun shx-test-unit-shell-command () "Test `shx--shell-command'." (shx-test-assert "shx--shell-command finds the default shell" (not (string-empty-p (shx--shell-command))))) (defun shx-test-unit-replace-from-list () "Test `shx--replace-from-list'." (shx-test-assert "shx--replace-from-list acts sequentially" (string= "a" (shx--replace-from-list '(("aa" "b") ("b" "a")) "aa"))) (shx-test-assert "shx--replace-from-list performs the correct replacements" (string= "24" (shx--replace-from-list '(("1" "2") ("3" "4")) "13")))) (defun shx-test-integration-magic-insert () "Test `shx-magic-insert'." (let ((previous-input (comint-previous-input-string 0))) (insert "^" previous-input "^^") (shx-magic-insert) (shx-test-assert "shx-magic-insert performs inline substitution" (equal (shx--current-input) "")) (insert previous-input " !!") (shx-magic-insert) (shx-test-assert "shx-magic-insert performs command expansion" (equal (shx--current-input) (concat previous-input " " previous-input))) (comint-kill-input))) (defun shx-test-unit-tokenize () "Test string tokenizaton." (shx-test-assert "shx-tokenize works with apostrophes." (equal '("first" "second token" "third") (shx-tokenize "'first' 'second token' 'third'"))) (shx-test-assert "shx-tokenize works with partial apostrophes." (equal '("first-token" "secondtoken") (shx-tokenize "'first-token' secondtoken"))) (shx-test-assert "shx-tokenize returns nil when quoting doesn't match." (equal nil (shx-tokenize "first/token 'second token"))) (shx-test-assert "shx-tokenize works with apostrophes and quotation marks." (equal '("first token" "second token" "3") (shx-tokenize "'first token' \"second token\" 3"))) (shx-test-assert "shx-tokenize works with escaped spaces." (equal '("first token" "secondtoken") (shx-tokenize "first\\ token secondtoken"))) (shx-test-assert "shx-tokenize works with escaped quotation marks." (equal '("\"test file\"" "'test file'") (shx-tokenize "\\\"test\\ file\\\" \\\'test\\ file\\\'"))) (shx-test-assert "shx-tokenize works with escaped characters" (equal '("a" "b c.d") (shx-tokenize "a b\\ \\c\\.d"))) (shx-test-assert "shx-tokenize works with a directory specified." (equal '("~/././~/.spacemacs") (shx-tokenize "~/././~/.spacemacs")))) (defun shx-test-unit-tokenize-filenames () "Test filename tokenization." (shx-test-assert "shx-tokenize-filenames works with relative and absolute paths." (let ((comint-file-name-prefix "/docker:123:")) (equal '("test" "/docker:123:~/test" "/docker:123:/test") (shx-tokenize-filenames "test ~/test /test"))))) (defun shx-test-integration-point-predicates () "Test some predicate functions on the point." (shx-test-assert "shx-point-on-input-p works at point-max." (save-excursion (goto-char (point-max)) (shx-point-on-input-p))) (shx-test-assert "shx-point-on-input-p works on last line and point-max." (save-excursion (goto-char (point-max)) (backward-char) (not (shx-point-on-input-p)))) (shx-test-assert "shx-point-on-input-p fails when not on last line." (not (save-excursion (goto-char (point-min)) (shx-point-on-input-p)))) (goto-char (point-max))) (defun shx-test-integration-propertize-prompt () "Test that recent prompt gets propertized." (save-excursion (let ((shx-flash-prompt-time 0)) (comint-previous-prompt 1) (forward-line 0) (let ((help-echo (or (get-text-property (point) 'help-echo) ""))) (shx-test-assert "shx--propertize-prompt propertizes prompt text" (string-match "At [0-9][0-9]:[0-9][0-9]:[0-9][0-9]" help-echo)))))) (defun shx-test-integration-input-handling () "Test shx's input handling." (goto-char (point-max)) (insert "test") (shx-test-assert "shx--current-input recognizes recent input" (string= "test" (shx--current-input))) (comint-kill-input) (forward-line -2) (shx-send-input-or-copy-line) (shx-test-assert "shx--current-input copies test line" (string= (substring (shx--current-input) 0 1) "✔")) (comint-kill-input) (shx-test-assert "shx--current-input recognizes blank line" (string= (shx--current-input) ""))) (defun shx-test-integration-output-handling () "Test `shx-insert'." (save-excursion (goto-char (point-max)) (backward-char 1) (shx-test-assert "shx-insert propertizes the output" (eq (field-at-pos (point)) 'output)))) (defun shx-test-unit-cmd-syntax-regexps () "Test `shx-cmd-syntax' regexps." (string-match (concat "^" shx-leader shx-cmd-syntax) ":help ok") (shx-test-assert "shx-cmd-syntax recognizes command with arguments" (and (string= (match-string 1 ":help ok") "help") (string= (match-string 2 ":help ok") "ok"))) (string-match (concat "^" shx-leader shx-cmd-syntax) ":pwd") (shx-test-assert "shx-cmd-syntax recognizes alphabetical command names" (string= (match-string 1 ":pwd") "pwd")) (string-match (concat "^" shx-leader shx-cmd-syntax) ":plot-bar") (shx-test-assert "shx-cmd-syntax recognizes hyphenated command names" (string= (match-string 1 ":plot-bar") "plot-bar"))) (defun shx-test-unit-shx-cat () "Test the `shx-cat' command." (let ((concatenation (shx-cat "Test" 'font-lock-string-face "test"))) (shx-test-assert "shx-cat concatenates strings correctly" (string= concatenation "Testtest")) (shx-test-assert "shx-cat propertizes text correctly" (equal (get-text-property 4 'font-lock-face concatenation) 'font-lock-string-face)))) (defun shx-test-unit-timers () "Test functions that use Emacs' built-in timer." (if (shx--get-timer-list) (shx-test-warn "Warning: :stop all timers to run timing tests") (shx-test-assert "shx--get-timer-list is empty" (not (shx--get-timer-list))) (shx--delay-input "10 sec" "stub command") (shx-test-assert "shx--shx-timer-list grows by 1" (eq 1 (length (shx--get-timer-list)))) (cancel-timer (car (shx--get-timer-list))) (shx-test-assert "shx--get-timer-list becomes empty" (not (shx--get-timer-list))))) (provide 'shx-test) ;;; shx-test.el ends here