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