Full Code of alphapapa/hammy.el for AI

master 5d33d41f0aa0 cached
8 files
151.0 KB
35.4k tokens
1 requests
Download .txt
Repository: alphapapa/hammy.el
Branch: master
Commit: 5d33d41f0aa0
Files: 8
Total size: 151.0 KB

Directory structure:
gitextract_spqoipe_/

├── .dir-locals.el
├── .gitattributes
├── .gitignore
├── LICENSE
├── NOTES.org
├── README.org
├── hammy.el
└── makem.sh

================================================
FILE CONTENTS
================================================

================================================
FILE: .dir-locals.el
================================================
;;; Directory Local Variables
;;; For more information see (info "(emacs) Directory Variables")

((magit-status-mode . ((magit-todos-exclude-globs . ("makem.sh")))))


================================================
FILE: .gitattributes
================================================
makem.sh linguist-vendored


================================================
FILE: .gitignore
================================================
/scratch.el
*.elc
/.sandbox/
/worktrees/


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: NOTES.org
================================================
#+TITLE: Hammy.el notes

* Mascot

** https://commons.wikimedia.org/wiki/File:Hamster_standing_in_exercise_wheel.jpg_in_exercise_wheel.jpg :ATTACH:
:PROPERTIES:
:ID:       1fc48051-7b36-4631-bd9a-d3a8b1217914
:END:

#+NAME: Summary
| Description | Hamster         |
| Date        | 22 January 2008 |
| Source      | Own work        |
| Author      | Rlicul          |

#+NAME: Licensing
#+begin_quote
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled GNU Free Documentation License.
#+end_quote

** https://commons.wikimedia.org/wiki/File:Pearl_Winter_White_Russian_Dwarf_Hamster_-_Front.jpg :ATTACH:
:PROPERTIES:
:ID:       003edf0e-d59f-45fe-bb16-9934c7e944f2
:END:

#+NAME: Summary
| Description | English: Front of a Pearl Winter White Russian Dwarf Hamster. |
| Date        | 12 January 2007 (original upload date)                        |
| Source      | Own work                                                      |
| Author      | Jpbarrass                                                     |

#+NAME: Licensing
#+begin_quote
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled GNU Free Documentation License. Subject to disclaimers.
#+end_quote

** https://commons.wikimedia.org/wiki/File:KoreaHamster.jpg          :ATTACH:
:PROPERTIES:
:ID:       37a3738f-2ad8-416c-9b0c-e9f440b96bd6
:END:

** https://pixabay.com/photos/hamster-animal-chair-wood-wall-887661/ :ATTACH:
:PROPERTIES:
:ID:       e30448d4-ec54-4c6a-8c50-a11599fe984d
:END:

It's under the not-quite-free Pixabay License, but it's the most appropriate I've found so far.  Uploaded to Pixabay by "Inactive account – ID 1267434".  For the sake of showing in this readme, it's good enough.

#+begin_quote
Simplified Pixabay License

Our license empowers creators and protects our community. We want to keep it as simple as possible. Here is an overview of what Pixabay content can and can't be used for.

What is allowed?

✓	All content (e.g. images, videos, music) on Pixabay can be used for free for commercial and noncommercial use across print and digital, except in the cases mentioned in "What is not allowed".
✓	Attribution is not required. Giving credit to the artist or Pixabay is not necessary but is always appreciated by our community.
✓	You can make modifications to content from Pixabay.


What is not allowed?

This section only applies to media users and not to the appropriate artists.

✕	Don't redistribute or sell Pixabay content on other stock or wallpaper platforms.
✕	Don't sell unaltered copies of content, e.g. don't sell an exact copy of a stock photo as a poster, print or on a physical product.
✕	Don't portray identifiable people in a bad light or in a way that is offensive.
✕	Don't use content with identifiable persons or brands to create a misleading association with a product or service.
#+end_quote

* Non-sexp syntax
:PROPERTIES:
:ID:       452d3bf2-8a6e-44a6-9f6b-5052f20b25fe
:END:

Could be something like:

#+begin_src elisp
  "Play=5-15s;Work=5-45s,stop"
#+end_src

* PROJECT Org clocking
:LOGBOOK:
- State "PROJECT"    from "DONE"       [2022-08-29 Mon 20:46]
- State "DONE"       from "PROJECT"    [2022-08-29 Mon 03:41] \\
  Seems to work well.
- State "PROJECT"    from              [2022-08-29 Mon 02:05]
:END:

It would be helpful to be able to integrate clocking Org tasks, but how?  Some ideas:

1. A command that starts a hammy and clocks in to an Org task.
   - Probably the most flexible option.  Just call, e.g. ~hammy-start-org-clock-in~ instead of ~hammy-start~.
   - That command should probably set an entry in ~hammy-etc~ to show which Org task was clocked in, and then ~hammy-stop~, et al. should check that entry and clock out when necessary.
2. A mode that causes ~hammy-start~ to clock in to an Org task.
   - Less flexible in that the user might want to start another timer without clocking and would have to toggle the mode to do so.
3. Add a function to ~hammy-start-hook~ to clock in to an Org task.
   - Also not very flexible, because the user probably wouldn't always want to clock in when starting a timer.
4. Define individual timers to clock in to an Org task.
   - Probably the least flexible option.

[2022-08-29 Mon 20:41]  Thinking about it further, this isn't quite as flexible as it should be.  For example, if the user calls this command to clock in to an Org task and start a hammy, and then clocks into a different task before the hammy ends, when the hammy clocks back in at the start of the next word period, it would clock back in to the first task rather than the one the user was clocked in to when the work period ended.  So it probably needs to record the active task when the work period ends rather than when the work period begins.

** TODO Clocks out work if first interval is rest                      :bug:

[2022-11-10 Thu 20:40] Noticed an annoying bug: if I use ~hammy-start-org-clock-in~ on a hammy that starts with a rest interval, it will clock in during the rest interval and then clock out during the work interval, leaving all of the work time unclocked!  Not sure of how to fix this reliably.  Maybe a way to canonically mark an interval as the work/rest interval?


================================================
FILE: README.org
================================================
#+TITLE: Hammy.el

#+HTML: <img src="images/mascot.png" align="right">

Hammy provides programmable, interactive interval timers for Emacs.  They can be used, e.g. to alternate between working and resting periods, to remind yourself to stretch your legs, etc.  Timers, known as "hammys", are easily defined by the user to behave as desired, and they can be integrated into other programs by calling Lisp functions in the hammys' definitions.

* Contents
:PROPERTIES:
:TOC:      :include siblings :ignore this
:END:
:CONTENTS:
- [[#installation][Installation]]
- [[#usage][Usage]]
- [[#changelog][Changelog]]
- [[#faq][FAQ]]
:END:

* Installation
:PROPERTIES:
:ID:       f9d7bc00-8bd4-4653-b69e-fdbb1663f5cd
:END:

Hammy is distributed on [[https://melpa.org/][MELPA]], so it can be installed with ~M-x package-install RET hammy RET~.

Other than that, the recommended way to install it is to use [[https://github.com/quelpa/quelpa-use-package][quelpa-use-package]], like this:

#+BEGIN_SRC elisp
  (use-package hammy
    :quelpa (hammy :fetcher github :repo "alphapapa/hammy.el"))
#+END_SRC

* Usage
:PROPERTIES:
:ID:       fae3cf22-c6d7-4d60-95b7-f3d30941959f
:TOC:      :include descendants :ignore (descendants) 
:END:

:CONTENTS:
- [[#examples][Examples]]
- [[#tips][Tips]]
:END:

First, define a hammy timer using the domain-specific language Hammy offers for this purpose.  (The ones in the following examples are defined by default, so you can use them upon installation of the package.)

Let's look at a classic example, the "pomodoro timer."  Here's how it's implemented in Hammy:

#+begin_src elisp
  ;; We name the timer with the Unicode TOMATO character, and propertize
  ;; it with a tomato-colored face.
  (hammy-define (propertize "🍅" 'face '(:foreground "tomato"))
    :documentation "The classic pomodoro timer."
    :intervals
    (list
     (interval :name "Work"
               :duration "25 minutes"
               :before (do (announce "Starting work time.")
                           (notify "Starting work time."))
               :advance (do (announce "Break time!")
                            (notify "Break time!")))
     (interval :name "Break"
               :duration (do (if (and (not (zerop cycles))
                                      (zerop (mod cycles 3)))
                                 ;; If a multiple of three cycles have
                                 ;; elapsed, the fourth work period was
                                 ;; just completed, so take a longer break.
                                 "30 minutes"
                               "5 minutes"))
               :before (do (announce "Starting break time.")
                           (notify "Starting break time."))
               :advance (do (announce "Break time is over!")
                            (notify "Break time is over!")))))
#+end_src

Then you can use these commands, which will prompt you to choose a defined hammy:

| ~hammy-start~              | Start a hammy.                                                                                                                                                                                             |
| ~hammy-start-org-clock-in~ | Call ~org-clock-in~, then ~hammy-start~.  (The Org task will then automatically be clocked out during the hammy's next interval (and when the hammy is stopped), and back in when the first interval resumes.) |
| ~hammy-next~               | Advance to the next interval of a hammy (when it's defined to not advance automatically).                                                                                                                  |
| ~hammy-toggle~             | Pause or unpause a hammy.                                                                                                                                                                                  |
| ~hammy-adjust~             | Adjust the durations of a hammy's intervals (which can be reset later).                                                                                                                                    |
| ~hammy-reset~              | Reset a hammy (useful when a hammy is defined to behave differently the longer it runs).                                                                                                                   |
| ~hammy-stop~               | Stop a hammy.                                                                                                                                                                                              |

You may also use these commands:

| ~hammy-mode~     | Show the current hammy in the mode-line. |
| ~hammy-view-log~ | Show the log buffer.                     |

The mode-line looks like this (when no hammy is active, when one is active, and when one is "overdue", waiting for the user to manually advance to the next interval):

[[images/mode-line.png]]

You can see the lighter prefix (~🐹~), the status (~:~, or ~!~ when overdue), the current hammy's name (~Move~), the current interval's name (~💺~), and the time elapsed (prefixed by ~-~ when counting down, and ~+~ when overdue and counting up).

Of course, if you have something against hamsters, the lighter prefix can be customized, as well as various faces for parts of the mode line.  See ~M-x customize-group RET hammy RET~.

** Examples
:PROPERTIES:
:ID:       495c83de-90ea-41a9-a491-618758ddbbfa
:END:

These examples have more detailed comments to explain how a hammy is defined.

This timer reminds you to stand up every so often (e.g. to prevent RSI):

#+begin_src elisp
  (hammy-define "Move"
    :documentation "Don't forget to stretch your legs."
    :intervals
    ;; A list of intervals, each defined with the `interval' function.
    (list (interval
           ;; The name of the interval is a string, used when selecting
           ;; hammys and shown in the mode line.
           :name "💺"
           ;; The duration of the interval: a number of seconds, a string
           ;; passed to `timer-duration', or a function which returns such.
           :duration "45 minutes"
           ;; Optionally, a face in which to show the
           ;; interval's name in the mode line.
           :face 'font-lock-type-face
           ;; A list of actions to take before starting the interval
           ;; (really, one or a list of functions to call with the hammy
           ;; as the argument).  The `do' macro expands to a lambda,
           ;; which the interval's `before' slot is set to.  In its
           ;; body, we call two built-in helper functions.
           :before (do (announce "Whew!")
                       (notify "Whew!"))
           ;; We want this interval to not automatically advance to the
           ;; next one; rather, we want the user to call the
           ;; `hammy-next' command to indicate when the standing-up is
           ;; actually happening.  So we provide a list of actions to
           ;; take when it's time to advance to the next interval.  We
           ;; wrap the list in a call to the built-in `remind' function,
           ;; which causes the actions to be repeated every 10 minutes
           ;; until the user manually advances to the next interval.
           :advance (remind "10 minutes"
                            ;; Every 10 minutes, while the hammy is waiting
                            ;; to be advanced to the next interval, remind
                            ;; the user by doing these things:
                            (do (announce "Time to stretch your legs!")
                                (notify "Time to stretch your legs!")
                                (play-sound-file "~/Misc/Sounds/mooove-it.wav"))))
          (interval :name "🤸"
                    :duration "5 minutes"
                    :face 'font-lock-builtin-face
                    :before (do (announce "Mooove it!")
                                (notify "Mooove it!"))
                    ;; Again, the interval should not advance automatically
                    ;; to the next--the user should indicate when he's
                    ;; actually sat down again.  (If we omitted the
                    ;; `:advance' slot, the interval would automatically
                    ;; advance when it reached its duration.)
                    :advance (do (announce "Time for a sit-down...")
                                 (notify "Time for a sit-down...")
                                 (play-sound-file "~/Misc/Sounds/relax.wav")))))
#+end_src

Here's a more interesting example, a "flywheel timer" (so called because it helps to build momentum), which interleaves rest periods with gradually lengthening work periods.

#+begin_src elisp
  (hammy-define "Flywheel"
    :documentation "Get your momentum going!"
    :intervals
    (list
     (interval :name "Play"
               :face 'font-lock-type-face
               ;; The play/rest interval will always be 5 minutes long.
               :duration "5 minutes"
               ;; Before starting the interval, announce and notify, to
               ;; show the user that the interval has begun.
               :before (do (announce "Play time!")
                           (notify "Play time!"))
               ;; When the interval's time is up, remind the user every
               ;; 5 minutes to get back to work.
               :advance (remind "5 minutes"
                                (do (announce "Play time is over!")
                                    (notify "Play time is over!")
                                    (play-sound-file "~/Misc/Sounds/get-to-workin.wav"))))
     (interval :name "Work"
               :face 'font-lock-builtin-face
               ;; For the work interval, rather than the duration being
               ;; the same each time, it "climbs" from 5 minutes to 45
               ;; minutes in 5-minute steps, and then descends back to 5
               ;; minutes.  For this, we use the built-in helper
               ;; function `climb', which returns a lambda function
               ;; that, when called at "hammy time," returns the
               ;; appropriate duration each time this interval begins.
               :duration (climb "5 minutes" "45 minutes"
                                :descend t :step "5 minutes")
               :before (do (announce "Work time!")
                           (notify "Work time!"))
               :advance (remind "10 minutes"
                                (do (announce "Work time is over!")
                                    (notify "Work time is over!")
                                    (play-sound-file "~/Misc/Sounds/relax.wav")))))
    ;; The `complete-p' predicate returns non-nil when a full session
    ;; has been completed (i.e. when at least one cycle has been
    ;; completed, the work interval is active and has reached its
    ;; duration, and its duration is 5 minutes, in which case the work
    ;; interval will have "climbed" to 45 minutes and back down).

    ;; Note that the `do' macro expands to a lambda within the body of
    ;; which certain special forms are bound, including `hammy',
    ;; `cycles', `interval-name', and `current-duration', allowing
    ;; introspection at runtime.  The predicate is called at "hammy
    ;; time", i.e. when the timer's code is run between intervals to
    ;; determine what to do next.
    :complete-p (do (and (> cycles 1)
                         (equal interval-name "Work")
                         ;; The built-in `duration' function converts
                         ;; its argument to a number of seconds.
                         (equal current-duration (duration "5 minutes"))))
    ;; Then, when the hammy has completed all of its cycles, play this
    ;; sound to celebrate.
    :after (do (play-sound-file "~/Misc/Sounds/all-done.wav")))
#+end_src

Note the use of ~:descend t~ in the arguments to the ~climb~ function in the ~Work~ interval's ~:duration~ slot: because of that, it may also be known as a "ladder timer" or a "hill-climb timer", because after the work interval reaches the maximum duration of 45 minutes, it begins decreasing until it reaches the minimum duration.   In this way, the user "spins up", gaining momentum to build endurance, and then "spins down" to finish the session.  This kind of timer may be helpful when working on large projects that are difficult to get started on.

Finally, an example of a "third time" timer, in which break periods are one-third as long as the last work interval:

#+begin_src elisp
  (hammy-define "⅓-time"
    :documentation "Breaks that are ⅓ as long as the last work interval."
    :intervals
    (list
     (interval :name "Work"
               ;; It's intended that the user manually end this interval
               ;; when ready, but we specify a maximum of 90 minutes by
               ;; default.
               :duration "90 minutes"
               :before (do (announce "Starting work time (advance to break when ready).")
                           (notify "Starting work time (advance to break when ready)."))
               :advance (remind "10 minutes"
                                (do (let* ((current-duration (ts-human-format-duration
                                                              (float-time
                                                               (time-subtract (current-time) current-interval-start-time))))
                                           (message (format "You've worked for %s!" current-duration)))
                                      (announce message)
                                      (notify message)
                                      (when hammy-sound-end-work
                                        (play-sound-file hammy-sound-end-work))))))
     (interval :name "Break"
               :duration (do (pcase-let* ((`(,_interval ,start ,end) (car history))
                                          (work-seconds (float-time (time-subtract end start))))
                               (* work-seconds 0.33)))
               :before (do (let ((message (format "Starting break for %s."
                                                  (ts-human-format-duration current-duration))))
                             (announce message)
                             (notify message)))
               :advance (remind "5 minutes"
                                (do (announce "Break time is over!")
                                    (notify "Break time is over!")
                                    (when hammy-sound-end-break
                                      (play-sound-file hammy-sound-end-break)))))))
#+end_src

** Tips
:PROPERTIES:
:TOC:      :depth 0
:END:

*** Show hammy-mode in tab-bar

If you use ~tab-bar-mode~, rather than showing the Hammy status in each window's mode line, you might prefer to show it once, in the tab bar.  This can easily be enabled like this:

#+begin_src elisp
  (use-package tab-bar
    :config
    (setf mode-line-misc-info
          ;; When the tab-bar is active, don't show global-mode-string
          ;; in mode-line-misc-info, because we now show that in the
          ;; tab-bar using `tab-bar-format-align-right' and
          ;; `tab-bar-format-global'.
          (remove '(global-mode-string ("" global-mode-string))
                  mode-line-misc-info))
    (unless (member 'tab-bar-format-global tab-bar-format)
      ;; Show `global-mode-string' in the tab bar.
      (setf tab-bar-format (append tab-bar-format '(tab-bar-format-align-right tab-bar-format-global)))))
#+end_src

* Changelog
:PROPERTIES:
:TOC:      :ignore (descendants)
:END:

** 0.3

*Additions*
+ Built-in "1-shot" timer that prompts for a name and duration on each use.
+ Command ~hammy-status~ shows information about active hammys in the echo area.
+ Option ~hammy-mode-lighter-pie~ shows a "progress pie" next to the time remaining.  (See associated faces for customization.)
  - Option ~hammy-mode-lighter-pie-height~ sets the size of the progress pie.
+ Option ~hammy-mode-lighter-seconds-format~, used when the time remaining is less than one minute.
+ Faces ~hammy-mode-lighter-name~ and ~hammy-mode-lighter-interval~.

*Changes*
+ Add 10-minute reminders to default pomodoro timer.
+ Command ~hammy-next~ interprets a numeric prefix argument as a number of minutes (rather than a number of seconds).
+ Command ~hammy-summary~ shows the times at which a hammy's first interval was started and its last interval ended.
+ Internal optimization of mode line lighter.

*Fixes*
+ Command ~hammy-toggle~ now works correctly.  ([[https://github.com/alphapapa/hammy.el/issues/11][#11]].  Thanks to [[https://github.com/Edgaras1][Edgaras1]] for reporting.)
+ Command ~hammy-stop~'s printing of "Stopped" message.
+ "⅓-time" timer toggles and resets properly.  ([[https://github.com/alphapapa/hammy.el/issues/11][#11]].  Thanks to [[https://github.com/Edgaras1][Edgaras1]] for reporting.)
+ Listify hammys' ~stopped~ slot.  ([[https://github.com/alphapapa/hammy.el/issues/13][#13]].  Thanks to [[https://github.com/Rickyfs][Rickyfs]] for reporting.)
+ Update mode line immediately when stopping a hammy.

** 0.2.1

*Fixes*
+ Command ~hammy-stop~ unsets the hammy's current interval.
+ Command ~hammy-adjust~ accepts empty input to not change an interval's duration.

** 0.2

*Changes*
+ Log "Stopped" when a hammy is stopped.

*Fixes*
+ Command ~hammy-start-org-clock-in~ when a hammy is not yet running.

** 0.1

First tagged version.

* FAQ

/Why are timers called hammys?  Isn't that silly?/

Probably, but is it sillier than calling them tomatoes?  Besides, it helps to distinguish them from Emacs's timers, which are used in the implementation.

* License
:PROPERTIES:
:TOC:      :ignore (this)
:END:

GPLv3

* COMMENT Config

# Local Variables:
# before-save-hook: (org-make-toc)
# End:


================================================
FILE: hammy.el
================================================
;;; hammy.el --- Programmable, interactive interval timers  -*- lexical-binding: t; -*-

;; Copyright (C) 2022  Adam Porter

;; Author: Adam Porter <adam@alphapapa.net>
;; URL: https://github.com/alphapapa/hammy.el
;; Version: 0.3
;; Package-Requires: ((emacs "28.1") (svg-lib "0.2.5") (ts "0.2.2"))
;; Keywords: convenience

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; This library provides programmable, interactive interval timers for
;; Emacs.  They can be used, e.g. to alternate between working and
;; resting periods, to remind yourself to stretch your legs, etc.
;; Timers, called "hammys," are easily defined by the user to behave
;; as desired, and they can be integrated into other programs by
;; calling Lisp functions in the hammys' definitions.

;;;; FAQ

;; Q: Why are timers called hammys?  Isn't that silly?

;; A: Probably, but is it sillier than calling them tomatoes?
;; Besides, it helps to distinguish them from Emacs's timers, which
;; are used in the implementation.

;;; Code:

;; TODO: Pausing.
;; TODO: Summarize logged interval times.
;; TODO: Menu bar/clicking for mode line lighter.  See `tab-bar-menu-bar', et al.

;;;; Requirements

(require 'cl-lib)
(require 'map)
(require 'ring)

(eval-when-compile
  ;; For `org-with-point-at'.
  (require 'org-macs))

(require 'svg-lib)
(require 'ts)

;;;; Structs

(cl-defstruct hammy
  (name "" :type 'string) (documentation "" :documentation "Documentation.")
  (history nil :documentation "List of elapsed intervals.
Each element is a list of three elements: the interval, the time
it began, and the time it ended.")
  (cycles 0 :documentation "Number of times the timer has gone through a cycle of all intervals.")
  (intervals nil :documentation "List of defined intervals.")
  (interval nil :documentation "Current interval, if any.")
  (current-interval-start-time nil :documentation "Time at which the current interval started.")
  (current-duration)
  (last-duration nil :documentation "Length in seconds of last interval.")
  (timer nil :documentation "Emacs timer for this timer.")
  (etc nil :documentation "Alist which may be used to store any extra data.")
  (before nil :documentation "Function called before running timer.
Called with one argument, the hammy.")
  (after nil :documentation "Function(s) called after timer has completed.
Called with one argument, the hammy.  Called when the hammy's
completion predicate returns non-nil.")
  (stopped nil :documentation "Function(s) called after stopping timer.
Called with one argument, the hammy.  Called by `hammy-stop'.")
  (complete-p nil :documentation "Predicate that returns non-nil when hammy is complete.
Called with one argument, the hammy.  Called after each interval
is complete, before starting the next interval.")
  (overduep))

(cl-defstruct hammy-interval
  (name "" :type 'string)
  (documentation "" :documentation "Documentation.") ; !
  (face nil :documentation "Optional face in which to show the name of the interval.")
  (duration nil :documentation "Number of seconds or function that returns such.
If a function, it is given one argument, the timer it is being
run in.")
  (before nil :documentation "Function(s) called before interval begins.
Called with one argument, the Hammy timer.")
  (after nil :documentation "Function(s) called when interval ends.
Called with one argument, the Hammy timer.  Note that when an
interval's `advance' slot is not `auto', the `after' slot's
functions are not called until the user manually advances to the
next interval.")
  (advance 'auto :documentation "How to advance to the next interval when this one ends.
If `auto', do so automatically.  Otherwise, a list of functions
to call when the interval is ready to be advanced, and don't
advance until the user calls `hammy-next'."))

(define-error 'hammy-complete "Hammy is over!")

;;;; Macros

;;;###autoload
(defmacro hammy-define (name &rest args)
  "Define a new Hammy named NAME made with ARGS.
Returns the hammy, and adds hammy to `hammy-hammys'.  NAME is a
string.  ARGS are passed to `make-hammy', which see.  Useful ones
include:

  `:documentation': An optional documentation string.

  `:intervals': A list of intervals.  Each one is defined with
    the local function `interval', which calls
    `make-hammy-interval', which see for its arguments.

  `:before': One or a list of functions which are called when the
    interval begins.  See the `do' macro, documented later.

  `:after': One or a list of functions which are called when the
    interval ends.  See the `do' macro, documented later.

  `:duration': A number of seconds, or a string passed to
    `timer-duration' to return such, or a function which returns
    such (called before starting the interval each cycle).  See
    the `do' macro, documented later.

  `:advance': Nil to advance automatically, or one or a list of
    functions to call when the interval's timer has elapsed and
    the user should be prompted to manually advance to the next
    interval.  See the `do' and `remind' macros, documented
    later.

Within ARGS, these pseudo-functions and forms available:

  `announce (message)': Announce MESSAGE in the echo area.
  `notify (message)`: Send MESSAGE as a desktop notification.

  `climb (from to &key descend step)': Return a function that
    returns a duration gradually increasing from FROM to TO, and
    optionally decreasing back to TO, by STEP.  FROM, TO, and
    STEP may be numbers or strings (passed to `timer-duration',
    which see).  DESCEND, if non-nil, causes the duration to
    gradually decrease back to FROM after reaching TO.

  `duration (interval)': Return a number of seconds equivalent to
    INTERVAL (a string like \"10 minutes\").  Calls
    `timer-duration', which see.

  `do (&rest body)': Expands to a lambda that binds `hammy' to
    the current hammy and evaluates BODY.  Within its BODY, these
    forms are bound:

    `current-duration': The duration in seconds of the current interval.
    `current-interval-start-time': The time at which the current interval began.
    `cycles': The number of cycles the hammy has completed.
    `etc': The hammy's `etc' slot.
    `history': The hammy's history list.
    `interval': The current interval (a `hammy-interval' struct).
    `interval-name': The name of the current interval.

  `elapsed (&optional interval)': Calls `hammy-elapsed' with the
    hammy, which see.

  `interval (&rest args)': Calls `make-hammy-interval', which
    see.

  `num-intervals ()': Returns the hammy's number of intervals.

  `remind (delay &rest fns)': Return a function that is called
    every DELAY seconds until the interval is manually advanced,
    calling FNS each time.  (The function automatically makes
    necessary adjustments to the hammy to set and cancel the
    periodic reminders.)

  `run (command)': Runs COMMAND (a string) asynchronously with
    `make-process', discarding its output and return value."
  (declare (indent defun))
  ;; In some ways, it might be preferable for this macro to expand to
  ;; the hammy struct, but then it wouldn't be forward-compatible if
  ;; the structure changes, so we just expand to the code that makes
  ;; the struct.

  ;; NOTE: This macro essentially expands to a call to `make-hammy'
  ;; with the given arguments, wrapping some of them in macrolet,
  ;; symbol-macrolet, and labels forms, and lambdas.  This way, we get
  ;; some checking for free at macro expansion time and compilation
  ;; time, rather than those errors happening at runtime.

  ;; NOTE: If a user byte-compiles a config file containing a
  ;; `hammy-define' call, and the definition of this macro changes in
  ;; a later version, it will be a problem.  So it would be nice if
  ;; this were a function instead of a macro, but that would mean that
  ;; the user would have to quote the argument to prevent evaluation,
  ;; which would likely be confusing to many users.  So, for now, at
  ;; least, it will be a macro.
  `(cl-macrolet ((announce (message)
                   `(hammy-announce hammy ,message))
                 (notify (message)
                   `(hammy-notify hammy ,message))
                 (cycles ()
                   `(hammy-cycles hammy))
                 (listify (place)
                   `(unless (listp ,place)
                      (setf ,place (list ,place))))
                 (listify-functions (place)
                   `(when (functionp ,place)
                      (setf ,place (list ,place))))
                 (do (&rest body)
                   `(lambda (hammy)
                      (cl-symbol-macrolet ((current-duration (hammy-current-duration hammy))
                                           (current-interval-start-time (hammy-current-interval-start-time hammy))
                                           (cycles (hammy-cycles hammy))
                                           (etc (hammy-etc hammy))
                                           (history (hammy-history hammy))
                                           (interval (hammy-interval hammy))
                                           (interval-name (hammy-interval-name interval)))
                        (ignore hammy)
                        ,@body))))
     ;; NOTE: Some of these functions are called at "hammy time" (I
     ;; know...), while others return lambdas to be called at hammy
     ;; time.
     (cl-labels ((run (command)
                   ;; This makes it easier to run a shell command without
                   ;; having to hack around `async-shell-command' to prevent
                   ;; it from displaying an output buffer, or deal with
                   ;; `call-process's awkward arguments.
                   (let* ((command (split-string command))
                          (name (format "hammy: Calling process %S" (car command))))
                     (make-process :name name :command command :noquery t)))
                 (duration (interval)
                   (timer-duration interval) )
                 (interval (&rest args)
                   (apply #'make-hammy-interval args))
                 (elapsed (hammy &optional interval)
                   "Call `hammy-elapsed', which see."
                   (hammy-elapsed hammy interval))
                 (num-intervals (hammy)
                   (ring-length (hammy-intervals hammy)))
                 (history (hammy)
                   (hammy-history hammy))
                 (cycles (hammy)
                   (hammy-cycles hammy))
                 (climb (from to &key descend step)
                   (lambda (hammy)
                     (let* ((from (duration from))
                            (to (duration to))
                            (apex (/ to from))
                            (step (cl-typecase step
                                    (string (duration step))
                                    (number step)))
                            (duration (cl-labels
                                          ((ascend
                                             () (min (* (pcase (cycles hammy)
                                                          (0 1)
                                                          (height (1+ height)))
                                                        from)
                                                     to))
                                           (descend
                                             () (min (* (pcase (- (* 2 apex) (cycles hammy))
                                                          (0 1)
                                                          (height (1- height)))
                                                        from)
                                                     to)))
                                        (if (< (cycles hammy) apex)
                                            ;; Spin up!
                                            (if step
                                                (+ from (* step (cycles hammy)))
                                              (ascend))
                                          ;; Spin down...
                                          (pcase-exhaustive descend
                                            (`nil (ascend))
                                            (`t (hammy-log hammy
                                                           (format "Descending... (Cycles:%s  Apex:%s  From:%s  To:%s  Step:%s"
                                                                   (cycles hammy) apex from to step))
                                                (if step
                                                    (+ from (* step (- (* 2 apex) (cycles hammy))))
                                                  (descend))))))))
                       duration)))
                 (remind (delay &rest fns)
                   (lambda (hammy)
                     (listify (hammy-after hammy))
                     (cl-pushnew #'cancel-reminder (hammy-after hammy))
                     (dolist (fn fns)
                       (funcall fn hammy))
                     (let ((delay-secs (duration delay)))
                       ;; TODO: Allow the duration to also be a function to return the reminder delay.
                       (setf (alist-get 'reminder (hammy-etc hammy))
                             (run-with-timer delay-secs delay-secs
                                             (lambda (hammy)
                                               (dolist (fn fns)
                                                 (funcall fn hammy)))
                                             hammy)))
                     ;; TODO: Might need to cancel and restart
                     ;; the reminder when a hammy is paused,
                     ;; too.
                     (listify (hammy-interval-after (hammy-interval hammy)))
                     (cl-pushnew #'cancel-reminder (hammy-interval-after (hammy-interval hammy)))))
                 (cancel-reminder (hammy)
                   (when (alist-get 'reminder (hammy-etc hammy))
                     (cancel-timer (alist-get 'reminder (hammy-etc hammy)))
                     (setf (alist-get 'reminder (hammy-etc hammy)) nil))))
       (let* ((hammy (make-hammy :name ,name ,@args))
              (ring (make-ring (length (hammy-intervals hammy)))))
         (dolist (interval (hammy-intervals hammy))
           (progn
             ;; Ensure that function slots are lists of functions, not just a function.
             (listify-functions (hammy-interval-before interval))
             (listify-functions (hammy-interval-after interval))
             (listify-functions (hammy-interval-advance interval)))
           (ring-insert-at-beginning ring interval))
         (listify-functions (hammy-stopped hammy))
         (setf (hammy-intervals hammy) ring)
         (setf hammy-hammys (cl-delete ,name hammy-hammys :test #'equal :key #'hammy-name))
         (push hammy hammy-hammys)
         hammy))))

(defun hammy-call (fn-or-fns &rest args)
  "Call FN-OR-FNS with ARGS.
If FN-OR-FNS is a function, call it; if a list of functions, call
each of them; if nil, do nothing."
  (cl-typecase fn-or-fns
    (null nil)
    (function (apply fn-or-fns args))
    (list (dolist (fn fn-or-fns)
            (apply fn args)))))

;;;; Inline functions

(defsubst hammy--current-interval-elapsed (hammy)
  "Return elapsed seconds in HAMMY's current interval."
  (float-time (time-subtract (current-time) (hammy-current-interval-start-time hammy))))

(defsubst hammy--current-interval-remaining (hammy)
  "Return remaining seconds in HAMMY's current interval."
  ;; TODO: Use this in more places, probably.
  (- (hammy-current-duration hammy) (hammy--current-interval-elapsed hammy)))

;;;; Variables

(defvar org-clock-hd-marker)

(defvar hammy-mode-lighter-last nil
  "Last `hammy-mode' lighter shown in the mode line.
Used to avoid calling `force-mode-line-update' more than
necessary.")

(defvar hammy-hammys nil
  "List of defined hammys.
Define a hammy with `hammy-define'.")

(defvar hammy-active nil
  "List of active hammys.")

;;;; Customization

(defgroup hammy nil
  "Programmable interval timers."
  :group 'convenience)

(defcustom hammy-log-buffer-name "*Hammy Log*"
  "Name of Hammy log buffer."
  :type 'string)

(defcustom hammy-start-hook '((lambda (hammy) (hammy-log hammy "Starting...")))
  "Functions run when a hammy is started.
Called with the hammy."
  :type 'hook)

(defcustom hammy-stopped '((lambda (hammy)
                             (hammy-log hammy "Stopped.")
                             (hammy-log hammy (hammy-summary hammy))))
  "Functions run when a hammy is stopped.
Called with the hammy."
  :type 'hook)

(defcustom hammy-complete-hook '((lambda (hammy)
                                   (hammy-log hammy "Completed.")
                                   (hammy-log hammy (hammy-summary hammy))))
  "Functions run when a hammy is completed.
That is, when the hammy completes its programmed cycles (not when
manually interrupted).  Called with the hammy, and optionally a
message."
  :type 'hook)

(defcustom hammy-interval-hook '((lambda (hammy &optional message) (hammy-log hammy message)))
  "Functions run when a hammy completes an interval.
Called with the hammy, and optionally a message."
  :type 'hook)

(defcustom hammy-cycle-hook '((lambda (hammy) (hammy-log hammy "Cycled.")))
  "Functions run when a hammy completes a cycle.
Called with the hammy, and optionally a message."
  :type 'hook)

(defcustom hammy-sound-end-break nil
  "Play this sound when a break interval ends."
  :type '(choice file (const :tag "No sound" nil)))

(defcustom hammy-sound-end-work nil
  "Play this sound when a work interval ends."
  :type '(choice file (const :tag "No sound" nil)))

(defcustom hammy-mode-lighter-seconds-format "%x%hh%mm%z"
  "Format string passed to `format-seconds', which see.
Used when remaining time is greater than one minute."
  :type 'string)

;;;; Commands

(defun hammy-adjust (hammy)
  "Adjust HAMMY's interval durations."
  (interactive (list (hammy-complete "Adjust hammy: " hammy-hammys)))
  ;; TODO: Reset durations in `hammy-reset'.
  (cl-labels
      ((adjust-interval (interval)
         (cl-symbol-macrolet
             ((original-duration
                (alist-get interval (alist-get 'original-durations (hammy-etc hammy)))))
           (let* ((old-duration (hammy-interval-duration interval))
                  (input-duration
                   (read-string
                    (format "New duration (number, function, or quoted-string duration) for interval \"%s\": "
                            (hammy-interval-name interval))
                    nil nil (prin1-to-string old-duration)))
                  (new-duration
                   (unless (string-empty-p input-duration)
                     ;; TODO: Allow the user to type, e.g. "25 minutes" without enclosing quotes.
                     (car (read-from-string input-duration)))))
             (when new-duration
               (cl-check-type new-duration (or number function string))
               (unless original-duration
                 ;; Only save the original duration the first time the interval is adjusted.
                 (setf original-duration old-duration))
               (setf (hammy-interval-duration interval) new-duration))))))
    (mapc #'adjust-interval (ring-elements (hammy-intervals hammy)))))

;;;###autoload
(cl-defun hammy-start (hammy &key duration interval)
  "Start HAMMY and return it.
If DURATION, set its first interval to last that many seconds.
INTERVAL may be an interval in the hammy to start
with (interactively, with universal prefix, prompt for the
interval with completion)."
  (interactive
   (let ((hammy (hammy-complete "Start hammy: " (cl-remove-if #'hammy-timer hammy-hammys))))
     (list hammy
           :duration (cl-typecase current-prefix-arg
                       (number current-prefix-arg))
           :interval (cl-typecase current-prefix-arg
                       (null nil)
                       (list (hammy-complete-interval hammy :prompt "Start with interval: "))))))
  (when (map-elt (hammy-etc hammy) 'pausedp)
    (user-error "Hammy paused: %s  (Use `hammy-toggle' to resume.)" (hammy-format hammy)))
  (when (hammy-interval hammy)
    (user-error "Hammy already started: %s" (hammy-format hammy)))
  (run-hook-with-args 'hammy-start-hook hammy)
  (hammy-call (hammy-before hammy) hammy)
  (hammy-next hammy :duration duration :advance t :interval interval)
  (push hammy hammy-active)
  hammy)

(declare-function org-before-first-heading-p "org")
;;;###autoload
(defun hammy-start-org-clock-in (&rest _ignore)
  "Call `org-clock-in' and start a hammy (or use an already-started one).
If point is in an Org entry, clock into it; otherwise, offer a
list of recently clocked tasks to clock into.  The Org task will
then automatically be clocked out during the hammy's second
interval (and when the hammy is stopped), and back in when the
first interval resumes.  (If the user clocks into a different
task while the hammy is running, the task that is clocked-in when
the work interval ends will be clocked back into when the next
work interval begins.)

Returns the hammy from `hammy-start'.  Assumes that the hammy's
first interval is the work interval (i.e. the one during which
the task should be clocked in)."
  (interactive)
  (require 'org)
  ;; MAYBE: Take a point-or-marker argument for the task to clock into.
  (if (and (eq major-mode 'org-mode)
           (not (org-before-first-heading-p)))
      ;; At an Org entry: clock in to heading at point.
      (org-clock-in)
    ;; Not in an Org entry: offer a list to choose from.
    (org-clock-in '(4)))
  (let ((hammy (hammy-complete "Clock in with Hammy: " hammy-hammys)))
    (unless (hammy-interval hammy)
      (hammy-start hammy))
    (cl-macrolet ((pushfn (fn place)
                    `(cl-pushnew ,fn ,place :test #'equal)))
      (pushfn #'hammy--org-clock-in (hammy-interval-before (hammy-interval hammy)))
      (pushfn #'hammy--org-clock-out (hammy-interval-after (hammy-interval hammy)))
      (pushfn #'hammy--org-clock-out (hammy-stopped hammy)))
    hammy))

(defun hammy-stop (hammy &optional quietly)
  "Stop HAMMY timer.
If QUIETLY, don't say so."
  (interactive
   (list (or (hammy-complete "Stop hammy: " hammy-active)
             (user-error "No active hammys"))))
  (pcase-let* (((cl-struct hammy (timer internal-timer)
                           (etc (map reminder)))
                hammy)
               ;; TODO: Logging, totals, etc.
               )
    (when internal-timer
      (cancel-timer internal-timer)
      (setf (hammy-timer hammy) nil))
    (when reminder
      (cancel-timer reminder)
      (setf (alist-get 'reminder (hammy-etc hammy)) nil))
    ;; Run the hook after having stopped the hammy, so any errors in
    ;; stopped functions won't prevent the hammy from stopping
    ;; correctly; and do it before resetting the hammy, so functions
    ;; in the stop hook can access the hammy's data before resetting.
    (hammy--record-interval hammy)
    (run-hook-with-args 'hammy-stopped hammy)
    (hammy-call (hammy-stopped hammy) hammy)
    (setf (hammy-interval hammy) nil
          hammy-active (remove hammy hammy-active))
    (defvar hammy-mode) ; `hammy-mode' is defined later in the file.
    (when hammy-mode
      ;; HACK: `hammy--mode-line-update' only updates when a hammy is
      ;; active, so we do it directly.
      (force-mode-line-update 'all))
    (unless quietly
      (message (hammy-format hammy "Stopped.")))
    hammy))

(cl-defun hammy-next (hammy &key duration advance interval)
  "Advance to HAMMY's next interval.
If DURATION (interactively, with numeric prefix), set the
interval's duration to DURATION minutes.  If ADVANCE, advance to
the next interval even if the previous interval has an
unsatisfied ADVANCE predicate.  INTERVAL may be an interval in
the hammy to advance to (interactively, with universal prefix,
prompt for the interval with completion)."
  (interactive
   (if-let ((hammy (hammy-complete "Advance hammy: " hammy-active)))
       (list hammy
             :duration (cl-typecase current-prefix-arg
                         (number (* 60 current-prefix-arg)))
             :advance t
             :interval (cl-typecase current-prefix-arg
                         (null nil)
                         (list (hammy-complete-interval hammy :prompt "Advance to interval: "))))
     (user-error (substitute-command-keys "No active hammys (use \"\\[hammy-start]\")"))))
  (when (hammy-timer hammy)
    ;; Cancel any outstanding timer.
    (cancel-timer (hammy-timer hammy))
    (setf (hammy-timer hammy) nil))
  (cl-labels ((advancep ()
                (or (and (hammy-interval hammy)
                         (eq 'auto (hammy-interval-advance (hammy-interval hammy))))
                    advance)))
    (when (hammy-interval hammy)
      ;; Hammy already started, interval completed (or ready to be
      ;; advanced).
      (when (and (advancep)
                 (equal (hammy-interval hammy)
                        (ring-ref (hammy-intervals hammy)
                                  (1- (ring-length (hammy-intervals hammy))))))
        ;; Cycle completed.
        (cl-incf (hammy-cycles hammy))
        ;; TODO: Not sure if it makes sense to run the cycle hook here
        ;; or later, after running other hooks.
        (run-hook-with-args 'hammy-cycle-hook hammy)))
    (if (and (advancep)
             (hammy-complete-p hammy)
             (funcall (hammy-complete-p hammy) hammy))
        ;; Hammy complete.
        (progn
          (hammy-stop hammy 'quietly)
          (run-hook-with-args 'hammy-complete-hook hammy)
          (hammy-call (hammy-after hammy) hammy))
      ;; Hammy not complete: start next interval.
      (pcase-let* (((cl-struct hammy (interval current-interval)) hammy)
                   (next-interval (or interval
                                      (if current-interval
                                          (ring-next (hammy-intervals hammy) current-interval)
                                        (ring-ref (hammy-intervals hammy) 0))))
                   (next-duration))
        (if (not (advancep))
            ;; Interval requires manual advancing.
            (progn
              (hammy-log hammy "Waiting for user to advance...")
              (setf (hammy-overduep hammy) t)
              (hammy-call (hammy-interval-advance (hammy-interval hammy)) hammy))
          ;; Automatically advancing, manually advancing, or starting the hammy.
          (when (hammy-interval hammy)
            ;; Advancing to the next interval (rather than starting the hammy).
            ;; NOTE: We call the interval-hook and the interval's after
            ;; functions when actually advancing to the next interval.
            (hammy--record-interval hammy)
            (hammy-log hammy (format "Elapsed: %s" (hammy-format-current-times hammy)))
            (run-hook-with-args 'hammy-interval-hook hammy
                                (format "Interval ended: %s"
                                        (hammy-interval-name (hammy-interval hammy))))
            (hammy-call (hammy-interval-after (hammy-interval hammy)) hammy))
          (setf (hammy-interval hammy) next-interval
                (hammy-current-interval-start-time hammy) (current-time)
                ;; We calculate the next duration after recording the
                ;; previous interval so, e.g. the ⅓-time hammy can
                ;; refer to its duration.
                next-duration (or duration
                                  (pcase-exhaustive
                                      (cl-etypecase (hammy-interval-duration next-interval)
                                        (function (condition-case _err
                                                      (funcall (hammy-interval-duration next-interval) hammy)
                                                    (hammy-complete
                                                     (run-hook-with-args 'hammy-complete-hook hammy)
                                                     (message "Hammy is over!  (%s)" (hammy-name hammy))
                                                     nil)))
                                        ((or number string) (hammy-interval-duration next-interval)))
                                    ((and (pred numberp) it) it)
                                    ((and (pred stringp) it) (timer-duration it))))
                (hammy-current-duration hammy) next-duration
                (hammy-overduep hammy) nil)
          (when next-duration
            ;; Starting next interval.
            (hammy-call (hammy-interval-before next-interval) hammy)
            ;; TODO: Mention elapsed time of just-completed interval.
            (run-hook-with-args 'hammy-interval-hook hammy
                                (format "Interval started: %s (%s)"
                                        (hammy-interval-name (hammy-interval hammy))
                                        (ts-human-format-duration (hammy-current-duration hammy)
                                                                  'abbr)))
            (setf (hammy-timer hammy) (run-at-time next-duration nil #'hammy-next hammy)))))))
  hammy)

(defun hammy-reset (hammy)
  "Reset HAMMY timer.
If already running, restarts it."
  (interactive (list (hammy-complete "Reset hammy: " hammy-hammys)))
  (let ((runningp (hammy-timer hammy)))
    (when runningp
      (hammy-stop hammy 'quietly))
    ;; TODO(someday): Use `with-slots', which supports structs in Emacs 29+.
    (setf (hammy-cycles hammy) 0
          (hammy-etc hammy) nil
          (hammy-history hammy) nil
          (hammy-interval hammy) nil
          (hammy-current-interval-start-time hammy) nil
          (hammy-overduep hammy) nil)
    (when (alist-get 'original-durations (hammy-etc hammy))
      ;; Restore any original durations.
      (cl-loop for (interval . duration) in (alist-get 'original-durations (hammy-etc hammy))
               do (progn
                    (setf (hammy-interval-duration interval) duration)
                    (cl-callf2 assoc-delete-all 'original-durations (hammy-etc hammy)))))
    (when runningp
      (hammy-start hammy))
    hammy))

(defun hammy-toggle (hammy)
  "Toggle HAMMY.
If running, pause it; if paused, resume it.

Pausing records the current interval and remaining time and calls
`hammy-stop'.  Resuming calls `hammy-start' with the recorded
interval and remaining time."
  (interactive
   (list (hammy-complete "Toggle hammy: "
                         (append (cl-remove-if-not (lambda (hammy)
                                                     (map-elt (hammy-etc hammy) 'pausedp))
                                                   hammy-hammys)
                                 hammy-active))))
  ;; Using `τ' as a prefix for place symbols ("τόπος" meaning "place").
  (cl-symbol-macrolet ((τpausedp (map-elt (hammy-etc hammy) 'pausedp))
                       (τlast-remaining (map-elt (hammy-etc hammy) 'last-remaining))
                       (τlast-interval (map-elt (hammy-etc hammy) 'last-interval)))
    (if (not τpausedp)
        (let ((elapsed (hammy--current-interval-elapsed hammy))
              (remaining (hammy--current-interval-remaining hammy))
              (interval (hammy-interval hammy)))
          (setf τpausedp t
                τlast-remaining remaining
                τlast-interval interval)
          (hammy-stop hammy 'quietly)
          (hammy-log hammy (format "Paused after %.0f seconds.  %.0f seconds remaining in interval %S."
                                   elapsed remaining (hammy-interval-name interval))))
      (let ((remaining τlast-remaining)
            (interval τlast-interval))
        (setf τpausedp nil
              τlast-remaining nil
              τlast-interval nil)
        (hammy-start hammy :interval interval :duration remaining))))
  hammy)

;;;; Functions

(cl-defun hammy-complete-interval (hammy &key (prompt "Interval: "))
  "Return an interval selected in HAMMY with completion.
PROMPT may be specified."
  (let* ((intervals (ring-elements (hammy-intervals hammy)))
         (names (mapcar #'hammy-interval-name intervals))
         (selected-name (completing-read prompt names nil t)))
    (cl-find selected-name intervals
             :test (lambda (name interval)
                     (equal name (hammy-interval-name interval))))))

(defun hammy-format (hammy &optional message)
  "Return formatted status for HAMMY, optionally with MESSAGE."
  (let* ((interval (cond ((hammy-interval hammy)
                          (format "%s (%s)"
                                  (hammy-interval-name (hammy-interval hammy))
                                  (ts-human-format-duration (hammy-current-duration hammy) 'abbr)))
                         ((and (hammy-complete-p hammy)
                               (funcall (hammy-complete-p hammy) hammy))
                          "Completed.")
                         (t
                          "None")))
         (message (if message (format "  Message:%S" message) "")))
    (format "Hammy (%s): Interval:%s  Cycles:%s%s"
            (hammy-name hammy) interval (hammy-cycles hammy) message)))

(defun hammy-log (hammy &optional message)
  "Log MESSAGE for HAMMY to log buffer."
  (with-current-buffer (hammy-log-buffer)
    (let* ((inhibit-read-only t)
           (buffer-window (get-buffer-window (current-buffer)))
           (point-at-eob-p (equal (point-max)
                                  (if buffer-window
                                      (window-point buffer-window)
                                    (point)))))
      (save-excursion
        (goto-char (point-max))
        (insert (format-time-string "%Y-%m-%d %H:%M:%S  ") (hammy-format hammy message) "\n"))
      (when point-at-eob-p
        (if buffer-window
            (setf (window-point buffer-window) (point-max))
          (setf (point) (point-max)))))))

(defun hammy-format-current-times (hammy)
  "Return current times for HAMMY formatted.
String includes elapsed time of the current interval and any
overrun time."
  (let* ((elapsed-secs (float-time
                        (time-subtract (current-time)
                                       (hammy-current-interval-start-time hammy))))
         (difference (float-time
                      (time-subtract (hammy-current-duration hammy) elapsed-secs))))
    (format "%s%s"
            (ts-human-format-duration elapsed-secs 'abbr)
            (if (not (zerop difference))
                (let ((sign (if (< 0 difference) "-" "+")))
                  (format " (%s%s)" sign (ts-human-format-duration (abs difference) 'abbr)))
              ""))))

(defun hammy-elapsed (hammy &optional interval)
  "Return HAMMY's elapsed time in seconds.
If INTERVAL (an interval struct or an interval name string),
return the elapsed time for that interval (summed across all
cycles)."
  (pcase-let* (((cl-struct hammy history) hammy)
               (interval-history
                (cl-typecase interval
                  (hammy-interval (cl-remove-if-not (lambda (element)
                                                      (eq interval (car element)))
                                                    history))
                  (string (cl-remove-if-not (lambda (element)
                                              (equal interval (hammy-interval-name (car element))))
                                            history))
                  (t history))))
    (cl-loop for (_interval start-time end-time) in interval-history
             sum (float-time (time-subtract end-time start-time)))))

(defun hammy-complete (prompt hammys)
  "Return one of HAMMYS selected with completion and PROMPT."
  (cl-labels ((describe (hammy)
                (format "%s (%s)"
                        (hammy-name hammy)
                        (hammy-documentation hammy))))
    (pcase (length hammys)
      (0 nil)
      (1 (car hammys))
      (_ (let* ((map (cl-loop for hammy in hammys
                              collect (cons (describe hammy) hammy)))
                (description (completing-read prompt map nil t)))
           (alist-get description map nil nil #'equal))))))

(defun hammy-announce (hammy message)
  "Announce MESSAGE in the echo area for HAMMY."
  (message "Hammy (%s): %s"
           (hammy-name hammy) message))

(defun hammy-summary (hammy)
  "Return a summary string for HAMMY.
Summary includes elapsed times, etc."
  (pcase-let* ((history (hammy-history hammy))
               (`(,_first-interval . (,first-started ,_first-stopped))
                (car (last history)))
               (`(,_last-interval . (,_last-started ,last-stopped))
                (car history)))
    (format "Total elapsed:%s  Intervals:%s  Cycles:%s  Started:%s  Stopped:%s"
            (ts-human-format-duration (hammy-elapsed hammy) 'abbr)
            (mapconcat (lambda (interval)
                         (format "(%s:%s)"
                                 (hammy-interval-name interval)
                                 (ts-human-format-duration (hammy-elapsed hammy interval) 'abbr)))
                       (ring-elements (hammy-intervals hammy))
                       "")
            (hammy-cycles hammy)
            (format-time-string "%Y-%m-%d %H:%M:%S" first-started)
            (format-time-string "%Y-%m-%d %H:%M:%S" last-stopped))))

(declare-function org-clock-in "org-clock")
(defun hammy--org-clock-in (hammy)
  "Clock in to HAMMY's Org task."
  (cl-symbol-macrolet ((marker (alist-get 'org-clock-hd-marker (hammy-etc hammy))))
    (when marker
      (org-with-point-at marker
        (org-clock-in))
      ;; Unset the saved marker, because it will be saved again when
      ;; clocking out.
      (setf marker nil))))

(declare-function org-clocking-p "org-clock")
(declare-function org-clock-out "org-clock")
(defun hammy--org-clock-out (hammy)
  "Clock out of HAMMY's Org task."
  (when (org-clocking-p)
    ;; Record the clocked-in task so we can clock back in to it later.
    ;; `org-clock-out' kills the marker, so we have to copy it for
    ;; future reference.
    (setf (alist-get 'org-clock-hd-marker (hammy-etc hammy))
          (copy-marker org-clock-hd-marker))
    (org-clock-out)))

(defun hammy--record-interval (hammy)
  "Record current interval in HAMMY's history."
  (push (list (hammy-interval hammy)
              (hammy-current-interval-start-time hammy)
              (current-time))
        (hammy-history hammy)))

;;;; Mode

(defcustom hammy-mode-always-show-lighter t
  "Show lighter even when no hammys are running."
  :type 'boolean)

(defcustom hammy-mode-lighter-prefix "🐹"
  "Show lighter even when no hammys are running."
  :type 'string)

(defcustom hammy-mode-lighter-overdue "!"
  "Shown when hammy is due to be manually advanced."
  :type 'string)

(defcustom hammy-mode-lighter-suffix-inactive "None"
  "Shown when no hammys are running."
  :type 'string)

(defcustom hammy-mode-lighter-pie t
  "Show progress pie in the lighter."
  :type 'boolean)

(defcustom hammy-mode-lighter-pie-update-interval 10
  "Update a hammy's pie every this many seconds."
  :type 'integer)

(defcustom hammy-mode-lighter-pie-height 0.9
  "Size of pie, as a fraction of line height.
While a value of 1.0 may make the most circular and
nicest-looking pie, it may result in the horizontal edges being
cropped, depending on font."
  :type 'number)

(defcustom hammy-mode-update-mode-line-continuously t
  "Update the mode line every second while a hammy is running."
  :type 'boolean)

(defface hammy-mode-lighter-name '((t (:inherit bold)))
  "Applied to hammy names in the lighter.")

(defface hammy-mode-lighter-interval '((t (:inherit italic)))
  "Applied to interval names in the lighter.")

(defface hammy-mode-lighter-prefix-inactive '((t (:inherit warning)))
  "Used when no hammy is active.")

(defface hammy-mode-lighter-prefix-active '((t (:inherit font-lock-type-face)))
  "Used when no hammy is active.")

(defface hammy-mode-lighter-overdue '((t (:inherit error)))
  "Used when no hammy is active.")

(defvar hammy-mode-update-mode-line-timer nil
  "Timer used to update the mode line.")

(defvar hammy-mode-lighter nil)
(put 'hammy-mode-lighter 'risky-local-variable t)

(defface hammy-mode-lighter-pie '((t (:inherit mode-line)))
  "Hammy progress pies.
If showing progress in the mode line or tab bar, inherit from the
appropriate face to ensure proper appearance.")

(defface hammy-mode-lighter-pie-normal '((t (:inherit hammy-mode-lighter-pie)))
  "Hammy with > 50% remaining.")

(defface hammy-mode-lighter-pie-50 '((t (:inherit hammy-mode-lighter-pie)))
  "Hammy with <= 50% remaining.")

(defface hammy-mode-lighter-pie-25 '((t (:inherit font-lock-variable-name-face)))
  "Hammy with <= 25% remaining.")

(defface hammy-mode-lighter-pie-10 '((t (:inherit  font-lock-warning-face)))
  "Hammy with <= 10% remaining.")

(defface hammy-mode-lighter-pie-0 '((t (:inherit error)))
  "Hammy that is overdue.")

;;;###autoload
(define-minor-mode hammy-mode
  "Show active hammy in the mode line."
  :global t
  (let ((lighter '(hammy-mode hammy-mode-lighter)))
    (if hammy-mode
        (progn
          (when hammy-mode-update-mode-line-continuously
            ;; TODO: Only run this timer when a hammy is running.
            (when (timerp hammy-mode-update-mode-line-timer)
              ;; Cancel any existing timer.  Generally shouldn't happen, but not impossible.
              (cancel-timer hammy-mode-update-mode-line-timer))
            (setf hammy-mode-update-mode-line-timer (run-with-timer 1 1 #'hammy--mode-line-update)))
          (add-hook 'hammy-interval-hook #'hammy--mode-line-update)
          ;; Avoid adding the lighter multiple times if the mode is activated again.
          (cl-pushnew lighter global-mode-string :test #'equal))
      (when hammy-mode-update-mode-line-timer
        (cancel-timer hammy-mode-update-mode-line-timer)
        (setf hammy-mode-update-mode-line-timer nil))
      (remove-hook 'hammy-interval-hook #'hammy--mode-line-update)
      (setf global-mode-string
            (remove lighter global-mode-string)))))

(defun hammy-mode-lighter ()
  "Return lighter for `hammy-mode'."
  (cl-labels
      ((format-hammy (hammy)
         (let ((remaining
                (abs
                 ;; We use the absolute value because `ts-human-format-duration'
                 ;; returns 0 for negative numbers.
                 (- (hammy-current-duration hammy)
                    (float-time (time-subtract (current-time)
                                               (hammy-current-interval-start-time hammy)))))))
           (format "%s(%s%s:%s)"
                   (propertize (hammy-name hammy)
                               'face 'hammy-mode-lighter-name)
                   (if (hammy-overduep hammy)
                       (propertize hammy-mode-lighter-overdue
                                   'face 'hammy-mode-lighter-overdue)
                     "")
                   (propertize (hammy-interval-name (hammy-interval hammy))
                               'face `(hammy-mode-lighter-interval
                                       ,(hammy-interval-face (hammy-interval hammy))))
                   (concat (when hammy-mode-lighter-pie
                             (propertize " " 'display (hammy--pie hammy)))
                           (if (hammy-overduep hammy)
                               ;; We use the negative sign when counting down to
                               ;; the end of an interval (i.e. "T-minus...") .
                               "+" "-")
                           (format-seconds (if (< remaining 60)
                                               "%2ss" hammy-mode-lighter-seconds-format)
                                           remaining))))))
    (if hammy-active
        (concat (propertize hammy-mode-lighter-prefix
                            'face 'hammy-mode-lighter-prefix-active)
                ":"
                (mapconcat #'format-hammy hammy-active ",") " ")
      ;; No active hammys.
      (when hammy-mode-always-show-lighter
        (concat (propertize hammy-mode-lighter-prefix
                            'face 'hammy-mode-lighter-prefix-inactive)
                (if hammy-mode-lighter-suffix-inactive
                    (concat ":" hammy-mode-lighter-suffix-inactive))
                " ")))))

(defun hammy-status ()
  "Show the status of any active hammys in the echo area."
  (interactive)
  (message "%s"
           (mapconcat (lambda (hammy)
                        (concat (hammy-format hammy)
                                "  Elapsed:" (hammy-format-current-times hammy) ""))
                      hammy-active "\n")))

(defun hammy--mode-line-update (&rest _ignore)
  "Update all mode lines as necessary for active hammys."
  (setf hammy-mode-lighter (hammy-mode-lighter))
  (unless (equal hammy-mode-lighter-last hammy-mode-lighter)
    (force-mode-line-update 'all)
    (setf hammy-mode-lighter-last hammy-mode-lighter)))

(defun hammy--pie (hammy)
  "Return HAMMY's pie, updating it if necessary."
  ;; This function is carefully designed and tested to not make more pie than
  ;; necessary (because the mode line, header line, tab bar, etc. are updated
  ;; more often than one would expect).  And the unusual construction is
  ;; designed to minimize the number of times the `τpie' is accessed
  ;; (which requires type-checking the struct each time).
  (cl-symbol-macrolet
      ((τpie (alist-get 'pie (hammy-etc hammy)))
       (τlast-pie-elapsed (alist-get 'last-pie-elapsed (hammy-etc hammy))))
    (let* (🥧
           (elapsed (floor (hammy--current-interval-elapsed hammy)))
           (update-pie-p (or (and (not (equal elapsed τlast-pie-elapsed))
                                  (zerop (mod elapsed hammy-mode-lighter-pie-update-interval)))
                             (not (setf 🥧 τpie)))))
      (when update-pie-p
        (setf 🥧 (setf τlast-pie-elapsed elapsed
                       τpie (hammy--make-pie hammy))))
      🥧)))

(defun hammy--make-pie (hammy)
  "Return an SVG progress pie for HAMMY.
Suitable for inserting with `insert-image'."
  (let* ((elapsed (hammy--current-interval-elapsed hammy))
         (remaining (- (hammy-current-duration hammy) elapsed))
         (fraction (/ remaining (hammy-current-duration hammy)))
         (face (pcase fraction
                 ((pred (< 0.50)) 'hammy-mode-lighter-pie-normal)
                 ((pred (< 0.25)) 'hammy-mode-lighter-pie-50)
                 ((pred (< 0.10)) 'hammy-mode-lighter-pie-25)
                 ((pred (< 0.00)) 'hammy-mode-lighter-pie-10)
                 (_ 'hammy-mode-lighter-pie-0))))
    ;; After choosing face, pass the absolute value of the fraction so
    ;; it will fill up again as it becomes further overdue.
    (svg-lib-progress-pie (abs fraction) nil :height hammy-mode-lighter-pie-height
                          :background (face-attribute 'hammy-mode-lighter-pie :background nil t)
                          :foreground (face-attribute face :foreground nil t))))

;;;; Log buffer

(define-derived-mode hammy-log-mode read-only-mode "Hammy-Log"
  :interactive nil)

(progn
  (define-key hammy-log-mode-map "q" #'bury-buffer))

(defun hammy-view-log ()
  "Show Hammy log buffer."
  (interactive)
  (pop-to-buffer (hammy-log-buffer)))

(defun hammy-log-buffer ()
  "Return Hammy log buffer."
  (or (get-buffer hammy-log-buffer-name)
      (with-current-buffer (get-buffer-create hammy-log-buffer-name)
        (hammy-log-mode)
        (current-buffer))))

;;;; Notifications

(require 'notifications)

(defun hammy-notify (hammy &optional message)
  "Call `notifications-notify' for HAMMY with MESSAGE."
  (notifications-notify :title (format "Hammy (%s)"
                                       (hammy-name hammy))
                        :body (or message (hammy-format hammy))))

;;;; Hammys

;; Pre-defined for convenience.

(hammy-define "Flywheel"
  :documentation "Get your momentum going!"
  :intervals (list (interval :name "Rest"
                             :face 'font-lock-type-face
                             :duration "5 minutes"
                             :before (do (announce "Rest time!")
                                         (notify "Rest time!"))
                             :advance (do (announce "Rest time is over!")
                                          (notify "Rest time is over!")))
                   (interval :name "Work"
                             :face 'font-lock-builtin-face
                             :duration (climb "5 minutes" "45 minutes"
                                              :descend t :step "5 minutes")
                             :before (do (announce "Work time!")
                                         (notify "Work time!"))
                             :advance (do (announce "Work time is over!")
                                          (notify "Work time is over!"))))
  :after (do (announce "Flywheel session complete!")
             (notify "Flywheel session complete!"))
  :complete-p (do (and (> cycles 1)
                       interval
                       (equal "Work" interval-name)
                       (equal (duration "5 minutes") current-duration))))

(hammy-define "Move"
  :documentation "Don't forget to stretch your legs!"
  :intervals (list (interval :name "💺"
                             :duration "45 minutes"
                             :face 'font-lock-type-face
                             :before (do (announce "Whew!")
                                         (notify "Whew!"))
                             :advance (remind "10 minutes"
                                              (do (announce "Time to stretch your legs!")
                                                  (notify "Time to stretch your legs!"))))
                   (interval :name "🤸"
                             :duration "5 minutes"
                             :face 'font-lock-builtin-face
                             :before (do (announce "Move it!")
                                         (notify "Move it!"))
                             :advance (do (announce "Time for a sit-down...")
                                          (notify "Time for a sit-down...")))))

(hammy-define (propertize "🍅" 'face '(:foreground "tomato"))
  :documentation "The classic pomodoro timer."
  :intervals
  (list
   (interval :name "Working"
             :duration "25 minutes"
             :before (do (announce "Starting work time.")
                         (notify "Starting work time."))
             :advance (remind "10 minutes"
                              (do (announce "Break time!")
                                  (notify "Break time!"))))
   (interval :name "Resting"
             :duration (do (if (and (not (zerop cycles))
                                    (zerop (mod cycles 3)))
                               ;; If a multiple of three cycles have
                               ;; elapsed, the fourth work period was
                               ;; just completed, so take a longer break.
                               "30 minutes"
                             "5 minutes"))
             :before (do (announce "Starting break time.")
                         (notify "Starting break time."))
             :advance (remind "10 minutes"
                              (do (announce "Break time is over!")
                                  (notify "Break time is over!"))))))

(hammy-define "⅓-time"
  :documentation "Breaks that are ⅓ as long as the last work interval."
  :intervals
  (list
   (interval :name "Work"
             ;; It's intended that the user manually end this interval
             ;; when ready, but we specify a maximum of 90 minutes by
             ;; default.
             :duration "90 minutes"
             :before (do (announce "Starting work time (advance to break when ready).")
                         (notify "Starting work time (advance to break when ready)."))
             :advance (remind "10 minutes" 
                              (do (let* ((current-duration
                                          (ts-human-format-duration
                                           (float-time
                                            (time-subtract (current-time)
                                                           current-interval-start-time))))
                                         (message (format "You've worked for %s!" current-duration)))
                                    (announce message)
                                    (notify message)
                                    (when hammy-sound-end-work
                                      (play-sound-file hammy-sound-end-work))))))
   (interval :name "Break"
             :duration (do
                        (cl-assert (equal "Work" (hammy-interval-name (caar history))))
                        (let ((duration (cl-loop for (interval start end) in history
                                                 while (equal "Work" (hammy-interval-name interval))
                                                 sum (float-time (time-subtract end start))
                                                 into work-seconds
                                                 finally return (* work-seconds 0.33))))
                          (when (alist-get 'unused-break etc)
                            ;; Add unused break time.
                            (cl-incf duration (alist-get 'unused-break etc))
                            (setf (alist-get 'unused-break etc) nil))
                          duration))
             :before (do (let ((message (format "Starting break for %s."
                                                (ts-human-format-duration current-duration))))
                           (announce message)
                           (notify message)))
             :after (do (let* ((elapsed
                                (float-time
                                 (time-subtract (current-time) current-interval-start-time)))
                               (unused (- current-duration elapsed)))
                          (when (> unused 0)
                            ;; "Bank" unused break time.
                            (if (alist-get 'unused-break etc)
                                (cl-incf (alist-get 'unused-break etc) unused)
                              (setf (alist-get 'unused-break etc) unused)))))
             :advance (remind "5 minutes"
                              (do (announce "Break time is over!")
                                  (notify "Break time is over!")
                                  (when hammy-sound-end-break
                                    (play-sound-file hammy-sound-end-break)))))))

(hammy-define "1-shot"
  :documentation "Single-use timer that prompts for name and duration."
  :complete-p (do (> cycles 0))
  :before
  (lambda (hammy)
    (hammy-reset hammy)
    (setf (hammy-intervals hammy)
          (ring-convert-sequence-to-ring
           (list (interval
                  :name (read-string "Interval name (optional): " nil nil "")
                  :duration (read-string "Duration: ")
                  :advance (remind "5 minutes"
                                   (do (let ((message (format "%s is over!" interval-name)))
                                         (announce message)
                                         (notify message))))))))))

;;;; Footer

(provide 'hammy)

;;; hammy.el ends here


================================================
FILE: makem.sh
================================================
#!/usr/bin/env bash

# * makem.sh --- Script to aid building and testing Emacs Lisp packages

# URL: https://github.com/alphapapa/makem.sh
# Version: 0.6-pre

# * Commentary:

# makem.sh is a script that helps to build, lint, and test Emacs Lisp
# packages.  It aims to make linting and testing as simple as possible
# without requiring per-package configuration.

# It works similarly to a Makefile in that "rules" are called to
# perform actions such as byte-compiling, linting, testing, etc.

# Source and test files are discovered automatically from the
# project's Git repo, and package dependencies within them are parsed
# automatically.

# Output is simple: by default, there is no output unless errors
# occur.  With increasing verbosity levels, more detail gives positive
# feedback.  Output is colored by default to make reading easy.

# The script can run Emacs with the developer's local Emacs
# configuration, or with a clean, "sandbox" configuration that can be
# optionally removed afterward.  This is especially helpful when
# upstream dependencies may have released new versions that differ
# from those installed in the developer's personal configuration.

# * License:

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# * Functions

function usage {
    cat <<EOF
$0 [OPTIONS] RULES...

Linter- and test-specific rules will error when their linters or tests
are not found.  With -vv, rules that run multiple rules will show a
message for unavailable linters or tests.

Rules:
  all      Run all lints and tests.
  compile  Byte-compile source files.

  lint           Run all linters, ignoring unavailable ones.
  lint-checkdoc  Run checkdoc.
  lint-compile   Byte-compile source files with warnings as errors.
  lint-declare   Run check-declare.
  lint-elsa      Run Elsa (not included in "lint" rule).
  lint-indent    Lint indentation.
  lint-package   Run package-lint.
  lint-regexps   Run relint.

  test, tests           Run all tests, ignoring missing test types.
  test-buttercup        Run Buttercup tests.
  test-ert              Run ERT tests.
  test-ert-interactive  Run ERT tests interactively.

  batch        Run Emacs in batch mode, loading project source and test files
               automatically, with remaining args (after "--") passed to Emacs.
  interactive  Run Emacs interactively, loading project source and test files
               automatically, with remaining args (after "--") passed to Emacs.

Options:
  -d, --debug    Print debug info.
  -h, --help     I need somebody!
  -v, --verbose  Increase verbosity, up to -vvv.
  --no-color     Disable color output.

  --debug-load-path  Print load-path from inside Emacs.

  -E, --emacs PATH  Run Emacs at PATH.

  -e, --exclude FILE  Exclude FILE from linting and testing.
  -f, --file FILE     Check FILE in addition to discovered files.

  -c, --compile-batch  Batch-compile files (instead of separately; quicker, but
                                            may hide problems).
  -C, --no-compile     Don't compile files automatically.

Sandbox options:
  -s[DIR], --sandbox[=DIR]  Run Emacs with an empty config in a sandbox DIR.
                            If DIR does not exist, make it.  If DIR is not
                            specified, use a temporary sandbox directory and
                            delete it afterward, implying --install-deps and
                            --install-linters.
  --install-deps            Automatically install package dependencies.
  --install-linters         Automatically install linters.
  -i, --install PACKAGE     Install PACKAGE before running rules.

  An Emacs version-specific subdirectory is automatically made inside
  the sandbox, allowing testing with multiple Emacs versions.  When
  specifying a sandbox directory, use options --install-deps and
  --install-linters on first-run and omit them afterward to save time.

Source files are automatically discovered from git, or may be
specified with options.  Package dependencies are discovered from
"Package-Requires" headers in source files, from -pkg.el files, and
from a Cask file.
EOF
}

# ** Elisp

# These functions return a path to an elisp file which can be loaded
# by Emacs on the command line with -l or --load.

function elisp-buttercup-file {
    # The function buttercup-run, which is called by buttercup-run-discover,
    # signals an error if it can't find any Buttercup test suites.  We don't
    # want that to be an error, so we define advice which ignores that error.
    local file=$(mktemp)
    cat >$file <<EOF
(defun makem-buttercup-run (oldfun &rest r)
  "Call buttercup-run only if \`buttercup-suites' is non-nil."
  (when buttercup-suites
    (apply oldfun r)))

(advice-add #'buttercup-run :around #'makem-buttercup-run)
EOF
    echo $file
}

function elisp-elint-file {
    local file=$(mktemp)
    cat >$file <<EOF
(require 'cl-lib)
(require 'elint)
(defun makem-elint-file (file)
  (let ((errors 0))
    (cl-letf (((symbol-function 'orig-message) (symbol-function 'message))
              ((symbol-function 'message) (symbol-function 'ignore))
              ((symbol-function 'elint-output)
               (lambda (string)
                 (cl-incf errors)
                 (orig-message "%s" string))))
      (elint-file file)
      ;; NOTE: \`errors' is not actually the number of errors, because
      ;; it's incremented for non-error header strings as well.
      (kill-emacs errors))))
EOF
    echo "$file"
}

function elisp-checkdoc-file {
    # Since checkdoc doesn't have a batch function that exits non-zero
    # when errors are found, we make one.
    local file=$(mktemp)

    cat >$file <<EOF
(defvar makem-checkdoc-errors-p nil)

(defun makem-checkdoc-files-and-exit ()
  "Run checkdoc-file on files remaining on command line, exiting non-zero if there are warnings."
  (let* ((files (mapcar #'expand-file-name command-line-args-left))
         (checkdoc-create-error-function
          (lambda (text start end &optional unfixable)
            (let ((msg (concat (checkdoc-buffer-label) ":"
                               (int-to-string (count-lines (point-min) (or start (point-min))))
                               ": " text)))
              (message msg)
              (setq makem-checkdoc-errors-p t)
              ;; Return nil because we *are* generating a buffered list of errors.
              nil))))
    (mapcar #'checkdoc-file files)
    (when makem-checkdoc-errors-p
      (kill-emacs 1))))

(setq checkdoc-spellcheck-documentation-flag t)
(makem-checkdoc-files-and-exit)
EOF
    echo $file
}

function elisp-byte-compile-file {
    # This seems to be the only way to make byte-compilation signal
    # errors for warnings AND display all warnings rather than only
    # the first one.
    local file=$(mktemp)
    # TODO: Add file to $paths_temp in other elisp- functions.
    paths_temp+=("$file")

    cat >"$file" <<EOF
(defun makem-batch-byte-compile (&rest args)
  ""
  (let ((num-errors 0)
        (num-warnings 0))
    ;; NOTE: Only accepts files as args, not directories.
    (dolist (file command-line-args-left)
      (pcase-let ((\`(,errors ,warnings) (makem-byte-compile-file file)))
        (cl-incf num-errors errors)
        (cl-incf num-warnings warnings)))
    (zerop num-errors)))

(defun makem-byte-compile-file (filename &optional load)
  "Call \`byte-compile-warn', returning the number of errors and the number of warnings."
  (let ((num-warnings 0)
        (num-errors 0))
    (cl-letf (((symbol-function 'byte-compile-warn)
               (lambda (format &rest args)
                 ;; Copied from \`byte-compile-warn'.
                 (cl-incf num-warnings)
                 (setq format (apply #'format-message format args))
                 (byte-compile-log-warning format t :warning)))
              ((symbol-function 'byte-compile-report-error)
               (lambda (error-info &optional fill &rest args)
                 (cl-incf num-errors)
                 ;; Copied from \`byte-compile-report-error'.
                 (setq byte-compiler-error-flag t)
                 (byte-compile-log-warning
                  (if (stringp error-info) error-info
                    (error-message-string error-info))
                  fill :error))))
      (byte-compile-file filename load))
    (list num-errors num-warnings)))
EOF
    echo "$file"
}

function elisp-check-declare-file {
    # Since check-declare doesn't have a batch function that exits
    # non-zero when errors are found, we make one.
    local file=$(mktemp)

    cat >$file <<EOF
(require 'check-declare)

(defun makem-check-declare-files-and-exit ()
  "Run check-declare-files on files remaining on command line, exiting non-zero if there are warnings."
  (let* ((files (mapcar #'expand-file-name command-line-args-left))
         (errors (apply #'check-declare-files files)))
    (when errors
      (with-current-buffer check-declare-warning-buffer
        (print (buffer-string)))
      (kill-emacs 1))))
EOF
    echo $file
}

function elisp-lint-indent-file {
    # This function prints warnings for indentation errors and exits
    # non-zero when errors are found.
    local file=$(mktemp)

    cat >"$file" <<EOF
(require 'cl-lib)

(defun makem-lint-indent-batch-and-exit ()
  "Print warnings for files which are not indented properly, then exit.
Exits non-zero if mis-indented lines are found.  Checks files in
'command-line-args-left'."
  (let ((errors-p))
    (cl-labels ((lint-file (file)
                           (find-file file)
                           (let ((inhibit-message t))
                             (indent-region (point-min) (point-max)))
                           (when buffer-undo-list
                             ;; Indentation changed: warn for each line.
                             (dolist (line (undo-lines buffer-undo-list))
                               (message "%s:%s: Indentation mismatch" (buffer-name) line))
                             (setf errors-p t)))
                (undo-pos (entry)
                           (cl-typecase (car entry)
                             (number (car entry))
                             (string (abs (cdr entry)))))
                (undo-lines (undo-list)
                            ;; Return list of lines changed in UNDO-LIST.
                            (nreverse (cl-loop for elt in undo-list
                                               for pos = (undo-pos elt)
                                               when pos
                                               collect (line-number-at-pos pos)))))
      (mapc #'lint-file (mapcar #'expand-file-name command-line-args-left))
      (when errors-p
        (kill-emacs 1)))))
EOF

    echo "$file"
}

function elisp-package-initialize-file {
    local file=$(mktemp)

    cat >$file <<EOF
(require 'package)
(setq package-archives (list (cons "gnu" "https://elpa.gnu.org/packages/")
                             (cons "melpa" "https://melpa.org/packages/")
                             (cons "melpa-stable" "https://stable.melpa.org/packages/")))
$elisp_org_package_archive
(package-initialize)
EOF
    echo $file
}

# ** Emacs

function run_emacs {
    # NOTE: The sandbox args need to come before the package
    # initialization so Emacs will use the sandbox's packages.
    local emacs_command=(
        "${emacs_command[@]}"
        -Q
        --eval "(setq load-prefer-newer t)"
        "${args_debug[@]}"
        "${args_sandbox[@]}"
        -l $package_initialize_file
        $arg_batch
        "${args_load_paths[@]}"
    )

    # Show debug message with load-path from inside Emacs.
    [[ $debug_load_path ]] \
        && debug $("${emacs_command[@]}" \
                       --batch \
                       --eval "(message \"LOAD-PATH: %s\" load-path)" \
                    2>&1)

    # Set output file.
    output_file=$(mktemp) || die "Unable to make output file."
    paths_temp+=("$output_file")

    # Run Emacs.
    debug "run_emacs: ${emacs_command[@]} $@ &>\"$output_file\""
    "${emacs_command[@]}" "$@" &>"$output_file"

    # Check exit code and output.
    exit=$?
    [[ $exit != 0 ]] \
        && debug "Emacs exited non-zero: $exit"

    [[ $verbose -gt 1 || $exit != 0 ]] \
        && cat $output_file

    return $exit
}

# ** Compilation

function batch-byte-compile {
    debug "batch-byte-compile: ERROR-ON-WARN:$compile_error_on_warn"

    [[ $compile_error_on_warn ]] && local error_on_warn=(--eval "(setq byte-compile-error-on-warn t)")

    run_emacs \
        --load "$(elisp-byte-compile-file)" \
        "${error_on_warn[@]}" \
        --eval "(unless (makem-batch-byte-compile) (kill-emacs 1))" \
        "$@"
}

function byte-compile-file {
    debug "byte-compile: ERROR-ON-WARN:$compile_error_on_warn"
    local file="$1"

    [[ $compile_error_on_warn ]] && local error_on_warn=(--eval "(setq byte-compile-error-on-warn t)")

    # FIXME: Why is the line starting with "&& verbose 3" not indented properly?  Emacs insists on indenting it back a level.
    run_emacs \
        --load "$(elisp-byte-compile-file)" \
        "${error_on_warn[@]}" \
        --eval "(pcase-let ((\`(,num-errors ,num-warnings) (makem-byte-compile-file \"$file\"))) (when (or (and byte-compile-error-on-warn (not (zerop num-warnings))) (not (zerop num-errors))) (kill-emacs 1)))" \
        && verbose 3 "Compiling $file finished without errors." \
            || { verbose 3 "Compiling file failed: $file"; return 1; }
}

# ** Files

function dirs-project {
    # Echo list of directories to be used in load path.
    files-project-feature | dirnames
    files-project-test | dirnames
}

function files-project-elisp {
    # Echo list of Elisp files in project.
    git ls-files 2>/dev/null \
        | egrep "\.el$" \
        | filter-files-exclude-default \
        | filter-files-exclude-args
}

function files-project-feature {
    # Echo list of Elisp files that are not tests and provide a feature.
    files-project-elisp \
        | egrep -v "$test_files_regexp" \
        | filter-files-feature
}

function files-project-test {
    # Echo list of Elisp test files.
    files-project-elisp | egrep "$test_files_regexp"
}

function dirnames {
    # Echo directory names for files on STDIN.
    while read file
    do
        dirname "$file"
    done
}

function filter-files-exclude-default {
    # Filter out paths (STDIN) which should be excluded by default.
    egrep -v "(/\.cask/|-autoloads.el|.dir-locals)"
}

function filter-files-exclude-args {
    # Filter out paths (STDIN) which are excluded with --exclude.
    if [[ ${files_exclude[@]} ]]
    then
        (
            # We use a subshell to set IFS temporarily so we can send
            # the list of files to grep -F.  This is ugly but more
            # correct than replacing spaces with line breaks.  Note
            # that, for some reason, using IFS="\n" or IFS='\n' doesn't
            # work, and a literal line break seems to be required.
            IFS="
"
            grep -Fv "${files_exclude[*]}"
        )
    else
        cat
    fi
}

function filter-files-feature {
    # Read paths on STDIN and echo ones that (provide 'a-feature).
    while read path
    do
        egrep "^\\(provide '" "$path" &>/dev/null \
            && echo "$path"
    done
}

function args-load-files {
    # For file in $@, echo "--load $file".
    for file in "$@"
    do
        sans_extension=${file%%.el}
        printf -- '--load %q ' "$sans_extension"
    done
}

function args-load-path {
    # Echo load-path arguments.
    for path in $(dirs-project | sort -u)
    do
        printf -- '-L %q ' "$path"
    done
}

function test-files-p {
    # Return 0 if $files_project_test is non-empty.
    [[ "${files_project_test[@]}" ]]
}

function buttercup-tests-p {
    # Return 0 if Buttercup tests are found.
    test-files-p || die "No tests found."
    debug "Checking for Buttercup tests..."

    grep "(require 'buttercup)" "${files_project_test[@]}" &>/dev/null
}

function ert-tests-p {
    # Return 0 if ERT tests are found.
    test-files-p || die "No tests found."
    debug "Checking for ERT tests..."

    # We check for this rather than "(require 'ert)", because ERT may
    # already be loaded in Emacs and might not be loaded with
    # "require" in a test file.
    grep "(ert-deftest" "${files_project_test[@]}" &>/dev/null
}

function package-main-file {
    # Echo the package's main file.
    file_pkg=$(git ls-files ./*-pkg.el 2>/dev/null)

    if [[ $file_pkg ]]
    then
        # Use *-pkg.el file if it exists.
        echo "$file_pkg"
    else
        # Use shortest filename (a sloppy heuristic that will do for now).
        for file in "${files_project_feature[@]}"
        do
            echo ${#file} "$file"
        done \
            | sort -h \
            | head -n1 \
            | sed -r 's/^[[:digit:]]+ //'
    fi
}

function dependencies {
    # Echo list of package dependencies.

    # Search package headers.  Use -a so grep won't think that an Elisp file containing
    # control characters (rare, but sometimes necessary) is binary and refuse to search it.
    egrep -a -i '^;; Package-Requires: ' $(files-project-feature) $(files-project-test) \
        | egrep -o '\([^([:space:]][^)]*\)' \
        | egrep -o '^[^[:space:])]+' \
        | sed -r 's/\(//g' \
        | egrep -v '^emacs$'  # Ignore Emacs version requirement.

    # Search Cask file.
    if [[ -r Cask ]]
    then
        egrep '\(depends-on "[^"]+"' Cask \
            | sed -r -e 's/\(depends-on "([^"]+)".*/\1/g'
    fi

    # Search -pkg.el file.
    if [[ $(git ls-files ./*-pkg.el 2>/dev/null) ]]
    then
        sed -nr 's/.*\(([-[:alnum:]]+)[[:blank:]]+"[.[:digit:]]+"\).*/\1/p' $(git ls-files ./*-pkg.el 2>/dev/null)
    fi
}

# ** Sandbox

function sandbox {
    verbose 2 "Initializing sandbox..."

    # *** Sandbox arguments

    # MAYBE: Optionally use branch-specific sandbox?

    # Check or make user-emacs-directory.
    if [[ $sandbox_dir ]]
    then
        # Directory given as argument: ensure it exists.
        if ! [[ -d $sandbox_dir ]]
        then
            debug "Making sandbox directory: $sandbox_dir"
            mkdir -p "$sandbox_dir" || die "Unable to make sandbox dir."
        fi

        # Add Emacs version-specific subdirectory, creating if necessary.
        sandbox_dir="$sandbox_dir/$(emacs-version)"
        if ! [[ -d $sandbox_dir ]]
        then
            mkdir "$sandbox_dir" || die "Unable to make sandbox subdir: $sandbox_dir"
        fi
    else
        # Not given: make temp directory, and delete it on exit.
        local sandbox_dir=$(mktemp -d) || die "Unable to make sandbox dir."
        paths_temp+=("$sandbox_dir")
    fi

    # Make argument to load init file if it exists.
    init_file="$sandbox_dir/init.el"

    # Set sandbox args.  This is a global variable used by the run_emacs function.
    args_sandbox=(
        --title "makem.sh: $(basename $(pwd)) (sandbox: $sandbox_dir)"
        --eval "(setq user-emacs-directory (file-truename \"$sandbox_dir\"))"
        --load package
        --eval "(setq package-user-dir (expand-file-name \"elpa\" user-emacs-directory))"
        --eval "(setq user-init-file (file-truename \"$init_file\"))"
    )

    # Add package-install arguments for dependencies.
    if [[ $install_deps ]]
    then
        local deps=($(dependencies))
        debug "Installing dependencies: ${deps[@]}"

        for package in "${deps[@]}"
        do
            args_sandbox_package_install+=(--eval "(package-install '$package)")
        done
    fi

    # Add package-install arguments for linters.
    if [[ $install_linters ]]
    then
        debug "Installing linters: package-lint relint"

        args_sandbox_package_install+=(
            --eval "(package-install 'elsa)"
            --eval "(package-install 'package-lint)"
            --eval "(package-install 'relint)")
    fi

    # *** Install packages into sandbox

    if [[ ${args_sandbox_package_install[@]} ]]
    then
        # Initialize the sandbox (installs packages once rather than for every rule).
        verbose 1 "Installing packages into sandbox..."

        run_emacs \
            --eval "(package-refresh-contents)" \
            "${args_sandbox_package_install[@]}" \
            && success "Packages installed." \
                || die "Unable to initialize sandbox."
    fi

    verbose 2 "Sandbox initialized."
}

# ** Utility

function cleanup {
    # Remove temporary paths (${paths_temp[@]}).

    for path in "${paths_temp[@]}"
    do
        if [[ $debug ]]
        then
            debug "Debugging enabled: not deleting temporary path: $path"
        elif [[ -r $path ]]
        then
            rm -rf "$path"
        else
            debug "Temporary path doesn't exist, not deleting: $path"
        fi
    done
}

function echo-unset-p {
    # Echo 0 if $1 is set, otherwise 1.  IOW, this returns the exit
    # code of [[ $1 ]] as STDOUT.
    [[ $1 ]]
    echo $?
}

function ensure-package-available {
    # If package $1 is available, return 0.  Otherwise, return 1, and
    # if $2 is set, give error otherwise verbose.  Outputting messages
    # here avoids repetition in callers.
    local package=$1
    local direct_p=$2

    if ! run_emacs --load $package &>/dev/null
    then
        if [[ $direct_p ]]
        then
            error "$package not available."
        else
            verbose 2 "$package not available."
        fi
        return 1
    fi
}

function ensure-tests-available {
    # If tests of type $1 (like "ERT") are available, return 0.  Otherwise, if
    # $2 is set, give an error and return 1; otherwise give verbose message.  $1
    # should have a corresponding predicate command, like ert-tests-p for ERT.
    local test_name=$1
    local test_command="${test_name,,}-tests-p"  # Converts name to lowercase.
    local direct_p=$2

    if ! $test_command
    then
        if [[ $direct_p ]]
        then
            error "$test_name tests not found."
        else
            verbose 2 "$test_name tests not found."
        fi
        return 1
    fi
}

function echo_color {
    # This allows bold, italic, etc. without needing a function for
    # each variation.
    local color_code="COLOR_$1"
    shift

    if [[ $color ]]
    then
        echo -e "${!color_code}${@}${COLOR_off}"
    else
        echo "$@"
    fi
}
function debug {
    if [[ $debug ]]
    then
        function debug {
            echo_color yellow "DEBUG ($(ts)): $@" >&2
        }
        debug "$@"
    else
        function debug {
            true
        }
    fi
}
function error {
    echo_color red "ERROR ($(ts)): $@" >&2
    ((errors++))
    return 1
}
function die {
    [[ $@ ]] && error "$@"
    exit $errors
}
function log {
    echo "LOG ($(ts)): $@" >&2
}
function log_color {
    local color_name=$1
    shift
    echo_color $color_name "LOG ($(ts)): $@" >&2
}
function success {
    if [[ $verbose -ge 2 ]]
    then
        log_color green "$@" >&2
    fi
}
function verbose {
    # $1 is the verbosity level, rest are echoed when appropriate.
    if [[ $verbose -ge $1 ]]
    then
        [[ $1 -eq 1 ]] && local color_name=blue
        [[ $1 -eq 2 ]] && local color_name=cyan
        [[ $1 -ge 3 ]] && local color_name=white

        shift
        log_color $color_name "$@" >&2
    fi
}

function ts {
    date "+%Y-%m-%d %H:%M:%S"
}

function emacs-version {
    # Echo Emacs version number.

    # Don't use run_emacs function, which does more than we need.
    "${emacs_command[@]}" -Q --batch --eval "(princ emacs-version)" \
        || die "Unable to get Emacs version."
}

function rule-p {
    # Return 0 if $1 is a rule.
    [[ $1 =~ ^(lint-?|tests?)$ ]] \
        || [[ $1 =~ ^(batch|interactive)$ ]] \
        || [[ $(type -t "$2" 2>/dev/null) =~ function ]]
}

# * Rules

# These functions are intended to be called as rules, like a Makefile.
# Some rules test $1 to determine whether the rule is being called
# directly or from a meta-rule; if directly, an error is given if the
# rule can't be run, otherwise it's skipped.

function all {
    verbose 1 "Running all rules..."

    lint
    tests
}

function compile-batch {
    [[ $compile ]] || return 0
    unset compile  # Only compile once.

    verbose 1 "Compiling..."
    verbose 2 "Batch-compiling files..."
    debug "Byte-compile files: ${files_project_byte_compile[@]}"

    batch-byte-compile "${files_project_byte_compile[@]}"
}

function compile-each {
    [[ $compile ]] || return 0
    unset compile  # Only compile once.

    verbose 1 "Compiling..."
    debug "Byte-compile files: ${files_project_byte_compile[@]}"

    local compile_errors
    for file in "${files_project_byte_compile[@]}"
    do
        verbose 2 "Compiling file: $file..."
        byte-compile-file "$file" \
            || compile_errors=t
    done

    [[ ! $compile_errors ]]
}

function compile {
    if [[ $compile = batch ]]
    then
        compile-batch "$@"
    else
        compile-each "$@"
    fi
    local status=$?

    if [[ $compile_error_on_warn ]]
    then
        # Linting: just return status code, because lint rule will print messages.
        [[ $status = 0 ]]
    else
        # Not linting: print messages here.
        [[ $status = 0 ]] \
            && success "Compiling finished without errors." \
                || error "Compiling failed."
    fi
}

function batch {
    # Run Emacs in batch mode with ${args_batch_interactive[@]} and
    # with project source and test files loaded.
    verbose 1 "Executing Emacs with arguments: ${args_batch_interactive[@]}"

    run_emacs \
        $(args-load-files "${files_project_feature[@]}" "${files_project_test[@]}") \
        "${args_batch_interactive[@]}"
}

function interactive {
    # Run Emacs interactively.  Most useful with --sandbox and --install-deps.
    local load_file_args=$(args-load-files "${files_project_feature[@]}" "${files_project_test[@]}")
    verbose 1 "Running Emacs interactively..."
    verbose 2 "Loading files: ${load_file_args//--load /}"

    [[ $compile ]] && compile

    unset arg_batch
    run_emacs \
        $load_file_args \
        --eval "(load user-init-file)" \
        "${args_batch_interactive[@]}"
    arg_batch="--batch"
}

function lint {
    verbose 1 "Linting..."

    lint-checkdoc
    lint-compile
    lint-declare
    # NOTE: Elint doesn't seem very useful at the moment.  See comment
    # in lint-elint function.
    # lint-elint
    lint-indent
    lint-package
    lint-regexps
}

function lint-checkdoc {
    verbose 1 "Linting checkdoc..."

    local checkdoc_file="$(elisp-checkdoc-file)"
    paths_temp+=("$checkdoc_file")

    run_emacs \
        --load="$checkdoc_file" \
        "${files_project_feature[@]}" \
        && success "Linting checkdoc finished without errors." \
            || error "Linting checkdoc failed."
}

function lint-compile {
    verbose 1 "Linting compilation..."

    compile_error_on_warn=true
    compile "${files_project_byte_compile[@]}" \
        && success "Linting compilation finished without errors." \
            || error "Linting compilation failed."
    unset compile_error_on_warn
}

function lint-declare {
    verbose 1 "Linting declarations..."

    local check_declare_file="$(elisp-check-declare-file)"
    paths_temp+=("$check_declare_file")

    run_emacs \
        --load "$check_declare_file" \
        -f makem-check-declare-files-and-exit \
        "${files_project_feature[@]}" \
        && success "Linting declarations finished without errors." \
            || error "Linting declarations failed."
}

function lint-elsa {
    verbose 1 "Linting with Elsa..."

    # MAYBE: Install Elsa here rather than in sandbox init, to avoid installing
    # it when not needed.  However, we should be careful to be clear about when
    # packages are installed, because installing them does execute code.
    run_emacs \
        --load elsa \
        -f elsa-run-files-and-exit \
        "${files_project_feature[@]}" \
        && success "Linting with Elsa finished without errors." \
            || error "Linting with Elsa failed."
}

function lint-elint {
    # NOTE: Elint gives a lot of spurious warnings, apparently because it doesn't load files
    # that are `require'd, so its output isn't very useful.  But in case it's improved in
    # the future, and since this wrapper code already works, we might as well leave it in.
    verbose 1 "Linting with Elint..."

    local errors=0
    for file in "${files_project_feature[@]}"
    do
        verbose 2 "Linting with Elint: $file..."
        run_emacs \
            --load "$(elisp-elint-file)" \
            --eval "(makem-elint-file \"$file\")" \
            && verbose 3 "Linting with Elint found no errors." \
                || { error "Linting with Elint failed: $file"; ((errors++)) ; }
    done

    [[ $errors = 0 ]] \
        && success "Linting with Elint finished without errors." \
            || error "Linting with Elint failed."
}

function lint-indent {
    verbose 1 "Linting indentation..."

    # We load project source files as well, because they may contain
    # macros with (declare (indent)) rules which must be loaded to set
    # indentation.

    run_emacs \
        --load "$(elisp-lint-indent-file)" \
        $(args-load-files "${files_project_feature[@]}" "${files_project_test[@]}") \
        --funcall makem-lint-indent-batch-and-exit \
        "${files_project_feature[@]}" "${files_project_test[@]}" \
        && success "Linting indentation finished without errors." \
            || error "Linting indentation failed."
}

function lint-package {
    ensure-package-available package-lint $1 || return $(echo-unset-p $1)

    verbose 1 "Linting package..."

    run_emacs \
        --load package-lint \
        --eval "(setq package-lint-main-file \"$(package-main-file)\")" \
        --funcall package-lint-batch-and-exit \
        "${files_project_feature[@]}" \
        && success "Linting package finished without errors." \
            || error "Linting package failed."
}

function lint-regexps {
    ensure-package-available relint $1 || return $(echo-unset-p $1)

    verbose 1 "Linting regexps..."

    run_emacs \
        --load relint \
        --funcall relint-batch \
        "${files_project_source[@]}" \
        && success "Linting regexps finished without errors." \
            || error "Linting regexps failed."
}

function tests {
    verbose 1 "Running all tests..."

    test-ert
    test-buttercup
}

function test-ert-interactive {
    verbose 1 "Running ERT tests interactively..."

    unset arg_batch
    run_emacs \
        $(args-load-files "${files_project_test[@]}") \
        --eval "(ert-run-tests-interactively t)"
    arg_batch="--batch"
}

function test-buttercup {
    ensure-tests-available Buttercup $1 || return $(echo-unset-p $1)
    compile || die

    verbose 1 "Running Buttercup tests..."

    local buttercup_file="$(elisp-buttercup-file)"
    paths_temp+=("$buttercup_file")

    run_emacs \
        $(args-load-files "${files_project_test[@]}") \
        --load "$buttercup_file" \
        --eval "(progn (setq backtrace-on-error-noninteractive nil) (buttercup-run))" \
        && success "Buttercup tests finished without errors." \
            || error "Buttercup tests failed."
}

function test-ert {
    ensure-tests-available ERT $1 || return $(echo-unset-p $1)
    compile || die

    verbose 1 "Running ERT tests..."
    debug "Test files: ${files_project_test[@]}"

    run_emacs \
        $(args-load-files "${files_project_test[@]}") \
        -f ert-run-tests-batch-and-exit \
        && success "ERT tests finished without errors." \
            || error "ERT tests failed."
}

# * Defaults

test_files_regexp='^((tests?|t)/)|-tests?.el$|^test-'

emacs_command=("emacs")
errors=0
verbose=0
compile=true
arg_batch="--batch"
compile=each

# MAYBE: Disable color if not outputting to a terminal.  (OTOH, the
# colorized output is helpful in CI logs, and I don't know if,
# e.g. GitHub Actions logging pretends to be a terminal.)
color=true

# TODO: Using the current directory (i.e. a package's repo root directory) in
# load-path can cause weird errors in case of--you guessed it--stale .ELC files,
# the zombie problem that just won't die.  It's incredible how many different ways
# this problem presents itself.  In this latest example, an old .ELC file, for a
# .EL file that had since been renamed, was present on my local system, which meant
# that an example .EL file that hadn't been updated was able to "require" that .ELC
# file's feature without error.  But on another system (in this case, trying to
# setup CI using GitHub Actions), the old .ELC was not present, so the example .EL
# file was not able to load the feature, which caused a byte-compilation error.

# In this case, I will prevent such example files from being compiled.  But in
# general, this can cause weird problems that are tedious to debug.  I guess
# the best way to fix it would be to actually install the repo's code as a
# package into the sandbox, but doing that would require additional tooling,
# pulling in something like Quelpa or package-build--and if the default recipe
# weren't being used, the actual recipe would have to be fetched off MELPA or
# something, which seems like getting too smart for our own good.

# TODO: Emit a warning if .ELC files that don't match any .EL files are detected.

# ** Colors

COLOR_off='\e[0m'
COLOR_black='\e[0;30m'
COLOR_red='\e[0;31m'
COLOR_green='\e[0;32m'
COLOR_yellow='\e[0;33m'
COLOR_blue='\e[0;34m'
COLOR_purple='\e[0;35m'
COLOR_cyan='\e[0;36m'
COLOR_white='\e[0;37m'

# ** Package system args

args_package_archives=(
    --eval "(add-to-list 'package-archives '(\"gnu\" . \"https://elpa.gnu.org/packages/\") t)"
    --eval "(add-to-list 'package-archives '(\"melpa\" . \"https://melpa.org/packages/\") t)"
)

args_org_package_archives=(
    --eval "(add-to-list 'package-archives '(\"org\" . \"https://orgmode.org/elpa/\") t)"
)

args_package_init=(
    --eval "(package-initialize)"
)

elisp_org_package_archive="(add-to-list 'package-archives '(\"org\" . \"https://orgmode.org/elpa/\") t)"

# * Args

args=$(getopt -n "$0" \
              -o dhce:E:i:s::vf:CO \
              -l compile-batch,exclude:,emacs:,install-deps,install-linters,debug,debug-load-path,help,install:,verbose,file:,no-color,no-compile,no-org-repo,sandbox:: \
              -- "$@") \
    || { usage; exit 1; }
eval set -- "$args"

while true
do
    case "$1" in
        --install-deps)
            install_deps=true
            ;;
        --install-linters)
            install_linters=true
            ;;
        -d|--debug)
            debug=true
            verbose=2
            args_debug=(--eval "(setq init-file-debug t)"
                        --eval "(setq debug-on-error t)")
            ;;
        --debug-load-path)
            debug_load_path=true
            ;;
        -h|--help)
            usage
            exit
            ;;
        -c|--compile-batch)
            debug "Compiling files in batch mode"
            compile=batch
            ;;
        -E|--emacs)
            shift
            emacs_command=($1)
            ;;
        -i|--install)
            shift
            args_sandbox_package_install+=(--eval "(package-install '$1)")
            ;;
        -s|--sandbox)
            sandbox=true
            shift
            sandbox_dir="$1"

            if ! [[ $sandbox_dir ]]
            then
                debug "No sandbox dir: installing dependencies."
                install_deps=true
            else
                debug "Sandbox dir: $1"
            fi
            ;;
        -v|--verbose)
            ((verbose++))
            ;;
        -e|--exclude)
            shift
            debug "Excluding file: $1"
            files_exclude+=("$1")
            ;;
        -f|--file)
            shift
            args_files+=("$1")
            ;;
        -O|--no-org-repo)
            unset elisp_org_package_archive
            ;;
        --no-color)
            unset color
            ;;
        -C|--no-compile)
            unset compile
            ;;
        --)
            # Remaining args (required; do not remove)
            shift
            rest=("$@")
            break
            ;;
    esac

    shift
done

debug "ARGS: $args"
debug "Remaining args: ${rest[@]}"

# Set package elisp (which depends on --no-org-repo arg).
package_initialize_file="$(elisp-package-initialize-file)"
paths_temp+=("$package_initialize_file")

# * Main

trap cleanup EXIT INT TERM

# Discover project files.
files_project_feature=($(files-project-feature))
files_project_test=($(files-project-test))
files_project_byte_compile=("${files_project_feature[@]}" "${files_project_test[@]}")

if [[ ${args_files[@]} ]]
then
    # Add specified files.
    files_project_feature+=("${args_files[@]}")
    files_project_byte_compile+=("${args_files[@]}")
fi

debug "EXCLUDING FILES: ${files_exclude[@]}"
debug "FEATURE FILES: ${files_project_feature[@]}"
debug "TEST FILES: ${files_project_test[@]}"
debug "BYTE-COMPILE FILES: ${files_project_byte_compile[@]}"
debug "PACKAGE-MAIN-FILE: $(package-main-file)"

if ! [[ ${files_project_feature[@]} ]]
then
    error "No files specified and not in a git repo."
    exit 1
fi

# Set load path.
args_load_paths=($(args-load-path))
debug "LOAD PATH ARGS: ${args_load_paths[@]}"

# If rules include linters and sandbox-dir is unspecified, install
# linters automatically.
if [[ $sandbox && ! $sandbox_dir ]] && [[ "${rest[@]}" =~ lint ]]
then
    debug "Installing linters automatically."
    install_linters=true
fi

# Initialize sandbox.
[[ $sandbox ]] && sandbox

# Run rules.
for rule in "${rest[@]}"
do
    if [[ $batch || $interactive ]]
    then
        debug "Adding batch/interactive argument: $rule"
        args_batch_interactive+=("$rule")

    elif [[ $rule = batch ]]
    then
        # Remaining arguments are passed to Emacs.
        batch=true
    elif [[ $rule = interactive ]]
    then
        # Remaining arguments are passed to Emacs.
        interactive=true

    elif type -t "$rule" 2>/dev/null | grep function &>/dev/null
    then
        # Pass called-directly as $1 to indicate that the rule is
        # being called directly rather than from a meta-rule.
        $rule called-directly
    elif [[ $rule = test ]]
    then
        # Allow the "tests" rule to be called as "test".  Since "test"
        # is a shell builtin, this workaround is required.
        tests
    else
        error "Invalid rule: $rule"
    fi
done

# Batch/interactive rules.
[[ $batch ]] && batch
[[ $interactive ]] && interactive

if [[ $errors -gt 0 ]]
then
    log_color red "Finished with $errors errors."
else
    success "Finished without errors."
fi

exit $errors
Download .txt
gitextract_spqoipe_/

├── .dir-locals.el
├── .gitattributes
├── .gitignore
├── LICENSE
├── NOTES.org
├── README.org
├── hammy.el
└── makem.sh
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (160K chars).
[
  {
    "path": ".dir-locals.el",
    "chars": 166,
    "preview": ";;; Directory Local Variables\n;;; For more information see (info \"(emacs) Directory Variables\")\n\n((magit-status-mode . ("
  },
  {
    "path": ".gitattributes",
    "chars": 27,
    "preview": "makem.sh linguist-vendored\n"
  },
  {
    "path": ".gitignore",
    "chars": 41,
    "preview": "/scratch.el\n*.elc\n/.sandbox/\n/worktrees/\n"
  },
  {
    "path": "LICENSE",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "NOTES.org",
    "chars": 5708,
    "preview": "#+TITLE: Hammy.el notes\n\n* Mascot\n\n** https://commons.wikimedia.org/wiki/File:Hamster_standing_in_exercise_wheel.jpg_in_"
  },
  {
    "path": "README.org",
    "chars": 17879,
    "preview": "#+TITLE: Hammy.el\n\n#+HTML: <img src=\"images/mascot.png\" align=\"right\">\n\nHammy provides programmable, interactive interva"
  },
  {
    "path": "hammy.el",
    "chars": 56278,
    "preview": ";;; hammy.el --- Programmable, interactive interval timers  -*- lexical-binding: t; -*-\n\n;; Copyright (C) 2022  Adam Por"
  },
  {
    "path": "makem.sh",
    "chars": 39390,
    "preview": "#!/usr/bin/env bash\n\n# * makem.sh --- Script to aid building and testing Emacs Lisp packages\n\n# URL: https://github.com/"
  }
]

About this extraction

This page contains the full source code of the alphapapa/hammy.el GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (151.0 KB), approximately 35.4k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!