File jinx-2.1.obscpio of Package emacs-jinx

07070100000000000081A400000000000000000000000167EFC12900000047000000000000000000000000000000000000001400000000jinx-2.1/.gitignore*-autoloads.el
*-pkg.el
*.elc
*.info
*.so
*.texi
*~
\#*\#
/README-elpa
07070100000001000081A400000000000000000000000167EFC12900001C90000000000000000000000000000000000000001700000000jinx-2.1/CHANGELOG.org#+title: jinx.el - Changelog
#+author: Daniel Mendler
#+language: en

* Version 2.1 (2025-04-04)

- ~jinx-correct~: For capitalized words, offer lower case variants to save in
  personal dictionary and file local variables.
- Add ~help-echo~ to the Jinx overlays.

* Version 2.0 (2025-03-11)

- Add ~jinx-dir-local-words~ saved in ~.dir-locals.el~. Words can be added to the
  ~.dir-locals.el~ with the ~/~ key in the ~jinx-correct~ dialog. The ~.dir-locals.el~
  file of the current or a parent directory is used. If it does not exist it is
  created in the project root or the current directory.

* Version 1.12 (2025-01-28)

- Improve performance in large folded Org buffers.
- Support ~lisp-data-mode~.
- Retain dictionaries in weak hash table for sharing.

* Version 1.11 (2024-12-22)

- Require Emacs 28.1.
- Remove special ~org-fold~ code. Set ~org-fold-core-style~ to ~overlays~ if unfolding
  in Org files does not work for you.
- ~jinx-languages~: Group dictionaries by dictionary provider.

* Version 1.10 (2024-07-23)

- Bump Compat dependency to Compat 30.
- Add include and linkpaths from FreeBSD for compilation.
- Add ~jinx--syntax-overrides~ to override syntax table.

* Version 1.9 (2024-06-29)

- Bugfix: In some rare scenarios, Jinx could hang when checking pending regions.
- ~jinx-correct-all~: Add ~ONLY-CHECK~ prefix argument.

* Version 1.8 (2024-06-19)

- Bugfix in ~jinx-correct~: Fix ~wrong-type-argument~ error if no Enchant
  dictionaries are found.

* Version 1.7 (2024-05-15)

- ~jinx--word-valid-p~: Do not error on invalid characters.
- ~jinx-save-languages~: New custom variable.

* Version 1.6 (2024-04-12)

- Bugfix (again): Ensure that directory local variables work correctly with
  Jinx. It is possible to turn Jinx on or off via dir-locals, and also configure
  the language and local words.

* Version 1.5 (2024-04-04)

- Bugfix: Ensure that ~jinx-next~ unfolds hidden misspellings.
- Bugfix: Ensure that directory local variable enabling ~jinx-mode~ works.

* Version 1.4 (2024-03-10)

- Bugfix: Ensure that ~jinx-correct~ saves words without text properties in the
  file-local variable ~jinx-local-words~.
- Bugfix: Ensure that ~eval~ local variable enabling ~jinx-mode~ works.
- ~jinx-correct~: If a region is marked, call ~jinx-correct-all~ and restrict
  corrections to the marked region.
- ~jinx-exclude-faces~, ~jinx-include-faces~, ~jinx-exclude-regexps~: Support mode
  aliases.

* Version 1.3 (2024-02-23)

- Fix interaction bug with the newest version of AUCTeX, where the major mode
  got changed unexpectedly.

* Version 1.2 (2024-01-22)

- Fix deadlock on MacOS during Jinx startup.
- Timer optimizations.

* Version 1.1 (2023-12-27)

- Add mouse context menu to correct misspellings. The menu is triggered by a
  right click on a misspelling.

* Version 1.0 (2023-12-01)

- Allow capitalized form of a word if non-capitalized word is stored in the
  session word list.
- Replace =jinx-excluded-modes= with =global-jinx-modes=, the Emacs 28 convention
  for globalized minor modes.
- =jinx-correct=: Offer session words as suggestions.
- Add =jinx-correct-nearest=, =jinx-correct-all= and =jinx-correct-word= commands. The
  command =jinx-correct= dispatches to one of those commands depending on the
  prefix argument.
- Recommend libenchant 2.3.1 or newer. Print a message if Enchant is outdated.
- Support $LANG=C and $LANG=POSIX environment variable settings.

* Version 0.9 (2023-07-02)

- šŸŖ„ Make sure that Emojis are not marked as misspelled šŸ§™šŸ¼ā€ā™€ļø.
- Rename =jinx-correct-next/previous= to =jinx-next/previous=. The commands can be
  used outside the minibuffer.
- Bind =M-n= and =M-p= to =jinx-next/previous= in =jinx-overlay-map=.
- Bind =M-$= to =jinx-correct= in the =jinx-overlay-map=.
- Add =jinx-repeat-map=.
- Rename category of Jinx overlays to =jinx-overlay=.
- Rename =jinx-misspelled-map= to =jinx-overlay-map=.
- Add many more language modes to =jinx-camel-modes=.

* Version 0.8 (2023-04-28)

- =jinx-correct=: Consistently move backward to the previous misspelling. In order
  to move backward further, press =M-$= again (or =M-p=). Move forward with =M-n=.
- =jinx-correct-select=: Support more than 10 quick keys.
- =jinx-languages=: New argument =LANGS=.
- Add =jinx-faces= customization group.
- Add configurable save actions via =jinx--save-keys=.
- Detect C compiler via $CC or =executable-find=.

* Version 0.7 (2023-04-21)

- Bugfixes
- =jinx-languages=: Only ask in file-backed buffers if file-local variable should
  be saved.
- Push =undo-boundary= before correcting a word, such that corrections are not
  undone in a single step.
- =jinx-correct=: Use =+= as prefix to add word to the current session.
- Add =jinx-correct-map= bound in the =jinx-correct= minibuffer.
- Add navigation keys to correction UI. The commands =jinx-correct-next= and
  =jinx-correct-previous= are bound to the keys =M-n= and =M-p= in the
  =jinx-correct-map= respectively. The commands accept prefix arguments to skip
  over a number of misspellings.
- Add quick selection keys to correction UI. The command =jinx-correct-select= is
  bound to the keys =1= to =9= in the =jinx-correct-map=.
- Try to locate the native module =jinx-mod.so= first on the =load-path= before
  attempting to compile it. This is useful if the module is packed and installed
  separately.

* Version 0.6 (2023-04-17)

- Fix the type of a few characters: =.= punctuation character, ='= word character, =%=
  and =$= identifier characters.
- Abandon =flyspell-mode-predicate= completely. Rely on faces only.
- =jinx-languages=: The value must be a string now. Multiple language codes can be
  separated by space.
- =jinx-languages=: Ask if the file-local variable should be saved when changing
  the language.
- Add =jinx-local-words= to save file-local words. =jinx-correct= supports saving to
  =jinx-local-words= by pressing =*=.
- Add a lighter and a minor mode menu.
- Avoid scheduling the idle timer while typing a word.

* Version 0.5 (2023-04-05)

- Add =jinx-languages= command to switch languages locally or globally.
- =jinx-correct=: When checking the whole buffer via =C-u M-$=, don't restore
  original point position upon =C-g= to ease cursory edits. Instead push a mark
  which can be used to go back to the original position.
- Add =jinx-mode-map= to make it easy to bind keys if =jinx-mode= is enabled. The
  map is empty by default.
- Ignore single quotes and apostrophes at the beginning and end of words. Please
  provide feedback if this is a reasonable approach.
- Support spell checking of camelCased words via the =jinx-camel-modes= variable.

* Version 0.4 (2023-03-27)

- =jinx-languages=: Fall back to =$LANG= environment variable, since
  =current-locale-environment= is an Emacs 29 addition.
- =jinx--mod-wordchars=: Handle non-UTF8 return values gracefully.
- =jinx-correct=: Always start from nearest overlay.
- =jinx-misspelled=: Use less obtrusive color for the underlining.

* Version 0.3 (2023-03-27)

- Add =jinx-misspelled-map=.
- =jinx-correct=: Unfold invisible line when correcting misspellings.
- =jinx-correct=: Show number of misspellings.
- Add =emacs-module.h= to avoid compilation problems.
- =jinx-languages=: Use =current-locale-environment= by default.

* Version 0.2 (2023-03-26)

- Start of changelog.
07070100000002000081A400000000000000000000000167EFC1290000894D000000000000000000000000000000000000001100000000jinx-2.1/LICENSE                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
07070100000003000081A400000000000000000000000167EFC12900002930000000000000000000000000000000000000001400000000jinx-2.1/README.org#+title: jinx.el - Enchanted Spell Checker
#+author: Daniel Mendler
#+language: en
#+export_file_name: jinx.texi
#+texinfo_dir_category: Emacs misc features
#+texinfo_dir_title: Jinx: (jinx).
#+texinfo_dir_desc: Enchanted Spell Checker

#+html: <a href="https://www.gnu.org/software/emacs/"><img alt="GNU Emacs" src="https://github.com/minad/corfu/blob/screenshots/emacs.svg?raw=true"/></a>
#+html: <a href="https://elpa.gnu.org/packages/jinx.html"><img alt="GNU ELPA" src="https://elpa.gnu.org/packages/jinx.svg"/></a>
#+html: <a href="https://elpa.gnu.org/devel/jinx.html"><img alt="GNU-devel ELPA" src="https://elpa.gnu.org/devel/jinx.svg"/></a>
#+html: <a href="https://melpa.org/#/jinx"><img alt="MELPA" src="https://melpa.org/packages/jinx-badge.svg"/></a>
#+html: <a href="https://stable.melpa.org/#/jinx"><img alt="MELPA Stable" src="https://stable.melpa.org/packages/jinx-badge.svg"/></a>

Jinx is a fast just-in-time spell-checker for Emacs. Jinx highlights misspelled
words in the text of the visible portion of the buffer. For efficiency, Jinx
highlights misspellings lazily, recognizes window boundaries and text folding,
if any. For example, when unfolding or scrolling, only the newly visible part of
the text is checked if it has not been checked before. Each misspelling can be
corrected from a list of dictionary words presented as a completion menu.

Installing Jinx is straight-forward and configuring should not need much
intervention. Jinx can be used completely on its own, but can also safely
co-exist with Emacs's built-in spell-checker Ispell.

Jinx's high performance and low resource usage comes from directly calling the
API of the [[https://rrthomas.github.io/enchant/][Enchant library]]. Jinx automatically compiles =jinx-mod.c= and loads the
dynamic module at startup. By binding directly to the native Enchant API, Jinx
avoids slower inter-process communication. Enchant is used by other text editors
and supports multiple backends like [[https://nuspell.github.io/][Nuspell]], [[http://hunspell.github.io/][Hunspell]] and [[http://aspell.net/][Aspell]].

Jinx supports spell-checking multiple languages in the same buffer. See the
=jinx-languages= variable to customize for multiple languages. Jinx can flexibly
ignore misspellings via faces (=jinx-exclude-faces= and =jinx-include-faces=),
regular expressions (=jinx-exclude-regexps=), and programmable predicates. Jinx
comes preconfigured for the most important Emacs major modes. Modes like
JavaScript, TypeScript, Java, Ruby or Rust are listed in =jinx-camel-modes=. For
these modes composite words in =camelCase= and =PascalCase= are accepted.

#+html: <img src="https://github.com/minad/jinx/blob/screenshots/screenshot.png?raw=true">

* Installation

Jinx can be installed from GNU ELPA or MELPA directly with =package-install=.

Most importantly your Emacs must be compiled with dynamic module support. Jinx
requires =libenchant=, which is needed to compile the native module at install
time. If =pkgconf= or =pkg-config= is available, Jinx will use it to locate
=libenchant= during installation. Depending on your BSD or Linux distribution you
have to install different packages:

- Debian, Ubuntu: =libenchant-2-dev=, =pkgconf=
- Arch, Gentoo: =enchant=, =pkgconf=
- Guix: =emacs-jinx= defined in =emacs-xyz.scm=
- Nix: =jinx= defined in =elpa-packages.nix=
- Void, Fedora: =enchant2-devel=, =pkgconf=
- OpenSUSE: =emacs-jinx= or =enchant=, =pkgconf=
- FreeBSD, OpenBSD, Mac: =enchant2=, =pkgconf=

On Windows the installation of the native module may require manual
intervention.

* Configuration

Jinx has two modes: the command, =global-jinx-mode= activates globally; and the
command, =jinx-mode=, for activating for specific modes.

#+begin_src emacs-lisp
;; Alternative 1: Enable Jinx globally
(add-hook 'emacs-startup-hook #'global-jinx-mode)

;; Alternative 2: Enable Jinx per mode
(dolist (hook '(text-mode-hook prog-mode-hook conf-mode-hook))
  (add-hook hook #'jinx-mode))
#+end_src

The commands =jinx-correct= and =jinx-languages= are marked as autoloads. Invoking
=jinx-correct= corrects the misspellings. Binding =jinx-correct= to =M-$= takes over
that key from the default assignment to =ispell-word=. Since Jinx is independent
of the Ispell package, =M-$= can be re-used.

#+begin_src emacs-lisp
(keymap-global-set "M-$" #'jinx-correct)
(keymap-global-set "C-M-$" #'jinx-languages)
#+end_src

- =M-$= triggers correction for the misspelled word before point.
- =C-u M-$= triggers correction for the entire buffer.
- =C-u C-u M-$= forces correction of the word at point, even if it is not
  misspelled.

A sample configuration with the popular =use-package= macro is shown here:

#+begin_src emacs-lisp
(use-package jinx
  :hook (emacs-startup . global-jinx-mode)
  :bind (("M-$" . jinx-correct)
         ("C-M-$" . jinx-languages)))
#+end_src

See also the [[https://github.com/minad/jinx/wiki][Jinx Wiki]] for additional configuration tips. The wiki documents
configurations to save misspellings as global abbreviations and support for
Ispell =LocalWords=.

* Correcting misspellings

The easiest way to correct a misspelling is to right click on the word,
underlined with a wavy line. Then a context menu will open where you can select
from suggestions.

If you prefer to use the keyboard, invoke the command =jinx-correct=. The
recommended binding is =M-$=, see the configuration section. Suggested corrections
will be displayed as a completion menu. You can press the displayed digit keys
to quickly select a suggestion. Furthermore the menu offers options to save the
word temporarily for the current session, in the personal dictionary or in the
file-local or directory-local variables.

You can enter arbitrary input at the correction prompt in order to make the
correction or to store a modified word in the personal dictionary. For example
if you typed =alotriomorpc=, the prompt offers you the option =@alotriomorpc= which
would add this word to your personal dictionary upon selection. You can then
correct the option to =@allotriomorphic= and add it to the dictionary.

While inside the =jinx-correct= prompt, the keys =M-n= and =M-p= are bound to
=jinx-next= and =jinx-previous= respectively and allow you to move the next and
previous misspelled word.

The completion menu is compatible with all popular completion UIs: Vertico, Mct,
Icomplete, Ivy, Helm and the default completions buffer. In case you use Vertico
I suggest that you tweak the completion display via =vertico-multiform-mode= for
the completion category =jinx=. You can for example use the grid display such that
more suggestions fit on the screen and enable annotations.

#+begin_src emacs-lisp
(add-to-list 'vertico-multiform-categories
             '(jinx grid (vertico-grid-annotate . 20) (vertico-count . 4)))
(vertico-multiform-mode 1)
#+end_src

* Navigating between misspellings

When correcting a word with =jinx-correct=, the movement commands =jinx-next= and
=jinx-previous= are available on the keys =M-n= and =M-p= to navigate to the next and
previous misspelling respectively. The movement commands work from within the
minibuffer during =jinx-correct= and also globally outside the minibuffer context.

While the commands are not bound globally by default, they are available as =M-n=
and =M-p= if point is placed on top of a misspelled word overlay. If you want you
can add them and other commands to the =jinx-mode-map=, such that they are always
available independent of point placement. If =repeat-mode= from Emacs 28 is
enabled, the movement can be repeated with the keys =n= and =p=.

* Enchant backends and personal dictionaries

Enchant uses different backends for different languages. The backends are
ordered as specified in the personal configuration file
=~/.config/enchant/enchant.ordering= and the system-wide configuration file
=/usr/share/enchant-2/enchant.ordering=. Enchant uses Hunspell as default backend
for most languages. For English Enchant prefers Aspell and for Finnish and
Turkish special backends called Voikko and Zemberek are used.

Depending on the backend the personal dictionary will be taken from different
locations, e.g., =~/.aspell.LANG.pws= or =~/.config/enchant/LANG.dic=. It is
possible to symlink different personal dictionaries such that they are shared by
different spell checkers. See the [[https://rrthomas.github.io/enchant/lib/enchant.html][Enchant manual]] for details.

* Alternatives

There exist multiple alternative spell-checking packages for Emacs, most
famously the builtin ispell.el and flyspell.el packages. The main advantages of
Jinx are its automatic checking of the visible text, its sharp focus on
performance and the ability to easily use multiple dictionaries at once. The
following three alternative packages come closest to the behavior of Jinx.

- [[https://github.com/astoff/jit-spell][jit-spell]]: Jinx borrows ideas from Augusto Stoffel's Jit-spell. Jit-spell uses
  the less efficient Ispell process communication instead of Jinx's calling a
  native API. Since Jit-spell does not restrict spell checking to the visible
  text only, it may enqueue the entire buffer too eagerly for checking. This
  happens when scrolling around or when stealth font locking is enabled. For
  this reason, Jit-spell affected load and latency in my tests ([[https://github.com/astoff/jit-spell/issues/9][issue on Github]]).

- [[https://codeberg.org/ideasman42/emacs-spell-fu][spell-fu]]: The idea to check words just in the visible text came from Campbell
  Barton's spell-fu package. Spell-fu is fast but incurs high memory overhead on
  account of its dictionary in a hash table. For languages with compound words
  and inflected word forms, this overhead magnifies ([[https://codeberg.org/ideasman42/emacs-spell-fu/issues/40][issue on Codeberg]]). By
  accessing the Enchant API directly, Jinx avoids any overhead. Jinx also
  benefits from the advanced spell-checker algorithms of Enchant (affixation,
  compound words, etc.).

- flyspell: Flyspell is a built-in package. Flyspell highlights misspellings
  while typing. Only the word under the cursor is spell-checked. Jinx, on the
  other hand, is more effective because it automatically checks for misspellings
  in the entire visible text of the buffer at once. Flyspell can check the
  entire buffer but must be instructed to do so via the command =flyspell-buffer=.

* Contributions

Since this package is part of [[https://elpa.gnu.org/packages/jinx.html][GNU ELPA]] contributions require a copyright
assignment to the FSF.
07070100000004000081A400000000000000000000000167EFC129000060E8000000000000000000000000000000000000001800000000jinx-2.1/emacs-module.h/* emacs-module.h - GNU Emacs module API.

Copyright (C) 2015-2021 Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs 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.

GNU Emacs 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 GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

/*
This file defines the Emacs module API.  Please see the chapter
`Dynamic Modules' in the GNU Emacs Lisp Reference Manual for
information how to write modules and use this header file.
*/

#ifndef EMACS_MODULE_H
#define EMACS_MODULE_H

#include <stddef.h>
#include <stdint.h>
#include <time.h>

#ifndef __cplusplus
#include <stdbool.h>
#endif

#define EMACS_MAJOR_VERSION 28

#if defined __cplusplus && __cplusplus >= 201103L
# define EMACS_NOEXCEPT noexcept
#else
# define EMACS_NOEXCEPT
#endif

#if defined __cplusplus && __cplusplus >= 201703L
# define EMACS_NOEXCEPT_TYPEDEF noexcept
#else
# define EMACS_NOEXCEPT_TYPEDEF
#endif

#if 3 < __GNUC__ + (3 <= __GNUC_MINOR__)
# define EMACS_ATTRIBUTE_NONNULL(...) \
   __attribute__ ((__nonnull__ (__VA_ARGS__)))
#elif (defined __has_attribute \
       && (!defined __clang_minor__ \
	   || 3 < __clang_major__ + (5 <= __clang_minor__)))
# if __has_attribute (__nonnull__)
#  define EMACS_ATTRIBUTE_NONNULL(...) \
    __attribute__ ((__nonnull__ (__VA_ARGS__)))
# endif
#endif
#ifndef EMACS_ATTRIBUTE_NONNULL
# define EMACS_ATTRIBUTE_NONNULL(...)
#endif

#ifdef __cplusplus
extern "C" {
#endif

/* Current environment.  */
typedef struct emacs_env_28 emacs_env;

/* Opaque pointer representing an Emacs Lisp value.
   BEWARE: Do not assume NULL is a valid value!  */
typedef struct emacs_value_tag *emacs_value;

enum { emacs_variadic_function = -2 };

/* Struct passed to a module init function (emacs_module_init).  */
struct emacs_runtime
{
  /* Structure size (for version checking).  */
  ptrdiff_t size;

  /* Private data; users should not touch this.  */
  struct emacs_runtime_private *private_members;

  /* Return an environment pointer.  */
  emacs_env *(*get_environment) (struct emacs_runtime *runtime)
    EMACS_ATTRIBUTE_NONNULL (1);
};

/* Type aliases for function pointer types used in the module API.
   Note that we don't use these aliases directly in the API to be able
   to mark the function arguments as 'noexcept' before C++20.
   However, users can use them if they want.  */

/* Function prototype for the module Lisp functions.  These must not
   throw C++ exceptions.  */
typedef emacs_value (*emacs_function) (emacs_env *env, ptrdiff_t nargs,
                                       emacs_value *args,
                                       void *data)
  EMACS_NOEXCEPT_TYPEDEF EMACS_ATTRIBUTE_NONNULL (1);

/* Function prototype for module user-pointer and function finalizers.
   These must not throw C++ exceptions.  */
typedef void (*emacs_finalizer) (void *data) EMACS_NOEXCEPT_TYPEDEF;

/* Possible Emacs function call outcomes.  */
enum emacs_funcall_exit
{
  /* Function has returned normally.  */
  emacs_funcall_exit_return = 0,

  /* Function has signaled an error using `signal'.  */
  emacs_funcall_exit_signal = 1,

  /* Function has exit using `throw'.  */
  emacs_funcall_exit_throw = 2
};

/* Possible return values for emacs_env.process_input.  */
enum emacs_process_input_result
{
  /* Module code may continue  */
  emacs_process_input_continue = 0,

  /* Module code should return control to Emacs as soon as possible.  */
  emacs_process_input_quit = 1
};

/* Define emacs_limb_t so that it is likely to match GMP's mp_limb_t.
   This micro-optimization can help modules that use mpz_export and
   mpz_import, which operate more efficiently on mp_limb_t.  It's OK
   (if perhaps a bit slower) if the two types do not match, and
   modules shouldn't rely on the two types matching.  */
typedef size_t emacs_limb_t;
#define EMACS_LIMB_MAX SIZE_MAX

struct emacs_env_25
{
  /* Structure size (for version checking).  */
  ptrdiff_t size;

  /* Private data; users should not touch this.  */
  struct emacs_env_private *private_members;

  /* Memory management.  */

  emacs_value (*make_global_ref) (emacs_env *env, emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*free_global_ref) (emacs_env *env, emacs_value global_value)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Non-local exit handling.  */

  enum emacs_funcall_exit (*non_local_exit_check) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*non_local_exit_clear) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  enum emacs_funcall_exit (*non_local_exit_get)
    (emacs_env *env, emacs_value *symbol, emacs_value *data)
    EMACS_ATTRIBUTE_NONNULL(1, 2, 3);

  void (*non_local_exit_signal) (emacs_env *env,
				 emacs_value symbol, emacs_value data)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*non_local_exit_throw) (emacs_env *env,
				emacs_value tag, emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Function registration.  */

  emacs_value (*make_function) (emacs_env *env,
				ptrdiff_t min_arity,
				ptrdiff_t max_arity,
				emacs_value (*func) (emacs_env *env,
                                                     ptrdiff_t nargs,
                                                     emacs_value* args,
                                                     void *data)
				  EMACS_NOEXCEPT
                                  EMACS_ATTRIBUTE_NONNULL(1),
				const char *docstring,
				void *data)
    EMACS_ATTRIBUTE_NONNULL(1, 4);

  emacs_value (*funcall) (emacs_env *env,
                          emacs_value func,
                          ptrdiff_t nargs,
                          emacs_value* args)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*intern) (emacs_env *env, const char *name)
    EMACS_ATTRIBUTE_NONNULL(1, 2);

  /* Type conversion.  */

  emacs_value (*type_of) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  bool (*is_not_nil) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  bool (*eq) (emacs_env *env, emacs_value a, emacs_value b)
    EMACS_ATTRIBUTE_NONNULL(1);

  intmax_t (*extract_integer) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*make_integer) (emacs_env *env, intmax_t n)
    EMACS_ATTRIBUTE_NONNULL(1);

  double (*extract_float) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*make_float) (emacs_env *env, double d)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Copy the content of the Lisp string VALUE to BUFFER as an utf8
     null-terminated string.

     SIZE must point to the total size of the buffer.  If BUFFER is
     NULL or if SIZE is not big enough, write the required buffer size
     to SIZE and return true.

     Note that SIZE must include the last null byte (e.g. "abc" needs
     a buffer of size 4).

     Return true if the string was successfully copied.  */

  bool (*copy_string_contents) (emacs_env *env,
                                emacs_value value,
                                char *buf,
                                ptrdiff_t *len)
    EMACS_ATTRIBUTE_NONNULL(1, 4);

  /* Create a Lisp string from a utf8 encoded string.  */
  emacs_value (*make_string) (emacs_env *env,
			      const char *str, ptrdiff_t len)
    EMACS_ATTRIBUTE_NONNULL(1, 2);

  /* Embedded pointer type.  */
  emacs_value (*make_user_ptr) (emacs_env *env,
				void (*fin) (void *) EMACS_NOEXCEPT,
				void *ptr)
    EMACS_ATTRIBUTE_NONNULL(1);

  void *(*get_user_ptr) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);
  void (*set_user_ptr) (emacs_env *env, emacs_value arg, void *ptr)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*(*get_user_finalizer) (emacs_env *env, emacs_value uptr))
    (void *) EMACS_NOEXCEPT EMACS_ATTRIBUTE_NONNULL(1);
  void (*set_user_finalizer) (emacs_env *env, emacs_value arg,
			      void (*fin) (void *) EMACS_NOEXCEPT)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Vector functions.  */
  emacs_value (*vec_get) (emacs_env *env, emacs_value vector, ptrdiff_t index)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*vec_set) (emacs_env *env, emacs_value vector, ptrdiff_t index,
		   emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  ptrdiff_t (*vec_size) (emacs_env *env, emacs_value vector)
    EMACS_ATTRIBUTE_NONNULL(1);
};

struct emacs_env_26
{
  /* Structure size (for version checking).  */
  ptrdiff_t size;

  /* Private data; users should not touch this.  */
  struct emacs_env_private *private_members;

  /* Memory management.  */

  emacs_value (*make_global_ref) (emacs_env *env, emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*free_global_ref) (emacs_env *env, emacs_value global_value)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Non-local exit handling.  */

  enum emacs_funcall_exit (*non_local_exit_check) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*non_local_exit_clear) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  enum emacs_funcall_exit (*non_local_exit_get)
    (emacs_env *env, emacs_value *symbol, emacs_value *data)
    EMACS_ATTRIBUTE_NONNULL(1, 2, 3);

  void (*non_local_exit_signal) (emacs_env *env,
				 emacs_value symbol, emacs_value data)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*non_local_exit_throw) (emacs_env *env,
				emacs_value tag, emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Function registration.  */

  emacs_value (*make_function) (emacs_env *env,
				ptrdiff_t min_arity,
				ptrdiff_t max_arity,
				emacs_value (*func) (emacs_env *env,
                                                     ptrdiff_t nargs,
                                                     emacs_value* args,
                                                     void *data)
				  EMACS_NOEXCEPT
                                  EMACS_ATTRIBUTE_NONNULL(1),
				const char *docstring,
				void *data)
    EMACS_ATTRIBUTE_NONNULL(1, 4);

  emacs_value (*funcall) (emacs_env *env,
                          emacs_value func,
                          ptrdiff_t nargs,
                          emacs_value* args)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*intern) (emacs_env *env, const char *name)
    EMACS_ATTRIBUTE_NONNULL(1, 2);

  /* Type conversion.  */

  emacs_value (*type_of) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  bool (*is_not_nil) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  bool (*eq) (emacs_env *env, emacs_value a, emacs_value b)
    EMACS_ATTRIBUTE_NONNULL(1);

  intmax_t (*extract_integer) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*make_integer) (emacs_env *env, intmax_t n)
    EMACS_ATTRIBUTE_NONNULL(1);

  double (*extract_float) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*make_float) (emacs_env *env, double d)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Copy the content of the Lisp string VALUE to BUFFER as an utf8
     null-terminated string.

     SIZE must point to the total size of the buffer.  If BUFFER is
     NULL or if SIZE is not big enough, write the required buffer size
     to SIZE and return true.

     Note that SIZE must include the last null byte (e.g. "abc" needs
     a buffer of size 4).

     Return true if the string was successfully copied.  */

  bool (*copy_string_contents) (emacs_env *env,
                                emacs_value value,
                                char *buf,
                                ptrdiff_t *len)
    EMACS_ATTRIBUTE_NONNULL(1, 4);

  /* Create a Lisp string from a utf8 encoded string.  */
  emacs_value (*make_string) (emacs_env *env,
			      const char *str, ptrdiff_t len)
    EMACS_ATTRIBUTE_NONNULL(1, 2);

  /* Embedded pointer type.  */
  emacs_value (*make_user_ptr) (emacs_env *env,
				void (*fin) (void *) EMACS_NOEXCEPT,
				void *ptr)
    EMACS_ATTRIBUTE_NONNULL(1);

  void *(*get_user_ptr) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);
  void (*set_user_ptr) (emacs_env *env, emacs_value arg, void *ptr)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*(*get_user_finalizer) (emacs_env *env, emacs_value uptr))
    (void *) EMACS_NOEXCEPT EMACS_ATTRIBUTE_NONNULL(1);
  void (*set_user_finalizer) (emacs_env *env, emacs_value arg,
			      void (*fin) (void *) EMACS_NOEXCEPT)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Vector functions.  */
  emacs_value (*vec_get) (emacs_env *env, emacs_value vector, ptrdiff_t index)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*vec_set) (emacs_env *env, emacs_value vector, ptrdiff_t index,
		   emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  ptrdiff_t (*vec_size) (emacs_env *env, emacs_value vector)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Returns whether a quit is pending.  */
  bool (*should_quit) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);
};

struct emacs_env_27
{
  /* Structure size (for version checking).  */
  ptrdiff_t size;

  /* Private data; users should not touch this.  */
  struct emacs_env_private *private_members;

  /* Memory management.  */

  emacs_value (*make_global_ref) (emacs_env *env, emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*free_global_ref) (emacs_env *env, emacs_value global_value)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Non-local exit handling.  */

  enum emacs_funcall_exit (*non_local_exit_check) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*non_local_exit_clear) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  enum emacs_funcall_exit (*non_local_exit_get)
    (emacs_env *env, emacs_value *symbol, emacs_value *data)
    EMACS_ATTRIBUTE_NONNULL(1, 2, 3);

  void (*non_local_exit_signal) (emacs_env *env,
				 emacs_value symbol, emacs_value data)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*non_local_exit_throw) (emacs_env *env,
				emacs_value tag, emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Function registration.  */

  emacs_value (*make_function) (emacs_env *env,
				ptrdiff_t min_arity,
				ptrdiff_t max_arity,
				emacs_value (*func) (emacs_env *env,
                                                     ptrdiff_t nargs,
                                                     emacs_value* args,
                                                     void *data)
				  EMACS_NOEXCEPT
                                  EMACS_ATTRIBUTE_NONNULL(1),
				const char *docstring,
				void *data)
    EMACS_ATTRIBUTE_NONNULL(1, 4);

  emacs_value (*funcall) (emacs_env *env,
                          emacs_value func,
                          ptrdiff_t nargs,
                          emacs_value* args)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*intern) (emacs_env *env, const char *name)
    EMACS_ATTRIBUTE_NONNULL(1, 2);

  /* Type conversion.  */

  emacs_value (*type_of) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  bool (*is_not_nil) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  bool (*eq) (emacs_env *env, emacs_value a, emacs_value b)
    EMACS_ATTRIBUTE_NONNULL(1);

  intmax_t (*extract_integer) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*make_integer) (emacs_env *env, intmax_t n)
    EMACS_ATTRIBUTE_NONNULL(1);

  double (*extract_float) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*make_float) (emacs_env *env, double d)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Copy the content of the Lisp string VALUE to BUFFER as an utf8
     null-terminated string.

     SIZE must point to the total size of the buffer.  If BUFFER is
     NULL or if SIZE is not big enough, write the required buffer size
     to SIZE and return true.

     Note that SIZE must include the last null byte (e.g. "abc" needs
     a buffer of size 4).

     Return true if the string was successfully copied.  */

  bool (*copy_string_contents) (emacs_env *env,
                                emacs_value value,
                                char *buf,
                                ptrdiff_t *len)
    EMACS_ATTRIBUTE_NONNULL(1, 4);

  /* Create a Lisp string from a utf8 encoded string.  */
  emacs_value (*make_string) (emacs_env *env,
			      const char *str, ptrdiff_t len)
    EMACS_ATTRIBUTE_NONNULL(1, 2);

  /* Embedded pointer type.  */
  emacs_value (*make_user_ptr) (emacs_env *env,
				void (*fin) (void *) EMACS_NOEXCEPT,
				void *ptr)
    EMACS_ATTRIBUTE_NONNULL(1);

  void *(*get_user_ptr) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);
  void (*set_user_ptr) (emacs_env *env, emacs_value arg, void *ptr)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*(*get_user_finalizer) (emacs_env *env, emacs_value uptr))
    (void *) EMACS_NOEXCEPT EMACS_ATTRIBUTE_NONNULL(1);
  void (*set_user_finalizer) (emacs_env *env, emacs_value arg,
			      void (*fin) (void *) EMACS_NOEXCEPT)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Vector functions.  */
  emacs_value (*vec_get) (emacs_env *env, emacs_value vector, ptrdiff_t index)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*vec_set) (emacs_env *env, emacs_value vector, ptrdiff_t index,
		   emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  ptrdiff_t (*vec_size) (emacs_env *env, emacs_value vector)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Returns whether a quit is pending.  */
  bool (*should_quit) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Processes pending input events and returns whether the module
     function should quit.  */
  enum emacs_process_input_result (*process_input) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL (1);

  struct timespec (*extract_time) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL (1);

  emacs_value (*make_time) (emacs_env *env, struct timespec time)
    EMACS_ATTRIBUTE_NONNULL (1);

  bool (*extract_big_integer) (emacs_env *env, emacs_value arg, int *sign,
                               ptrdiff_t *count, emacs_limb_t *magnitude)
    EMACS_ATTRIBUTE_NONNULL (1);

  emacs_value (*make_big_integer) (emacs_env *env, int sign, ptrdiff_t count,
                                   const emacs_limb_t *magnitude)
    EMACS_ATTRIBUTE_NONNULL (1);
};

struct emacs_env_28
{
  /* Structure size (for version checking).  */
  ptrdiff_t size;

  /* Private data; users should not touch this.  */
  struct emacs_env_private *private_members;

  /* Memory management.  */

  emacs_value (*make_global_ref) (emacs_env *env, emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*free_global_ref) (emacs_env *env, emacs_value global_value)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Non-local exit handling.  */

  enum emacs_funcall_exit (*non_local_exit_check) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*non_local_exit_clear) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  enum emacs_funcall_exit (*non_local_exit_get)
    (emacs_env *env, emacs_value *symbol, emacs_value *data)
    EMACS_ATTRIBUTE_NONNULL(1, 2, 3);

  void (*non_local_exit_signal) (emacs_env *env,
				 emacs_value symbol, emacs_value data)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*non_local_exit_throw) (emacs_env *env,
				emacs_value tag, emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Function registration.  */

  emacs_value (*make_function) (emacs_env *env,
				ptrdiff_t min_arity,
				ptrdiff_t max_arity,
				emacs_value (*func) (emacs_env *env,
                                                     ptrdiff_t nargs,
                                                     emacs_value* args,
                                                     void *data)
				  EMACS_NOEXCEPT
                                  EMACS_ATTRIBUTE_NONNULL(1),
				const char *docstring,
				void *data)
    EMACS_ATTRIBUTE_NONNULL(1, 4);

  emacs_value (*funcall) (emacs_env *env,
                          emacs_value func,
                          ptrdiff_t nargs,
                          emacs_value* args)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*intern) (emacs_env *env, const char *name)
    EMACS_ATTRIBUTE_NONNULL(1, 2);

  /* Type conversion.  */

  emacs_value (*type_of) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  bool (*is_not_nil) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  bool (*eq) (emacs_env *env, emacs_value a, emacs_value b)
    EMACS_ATTRIBUTE_NONNULL(1);

  intmax_t (*extract_integer) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*make_integer) (emacs_env *env, intmax_t n)
    EMACS_ATTRIBUTE_NONNULL(1);

  double (*extract_float) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);

  emacs_value (*make_float) (emacs_env *env, double d)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Copy the content of the Lisp string VALUE to BUFFER as an utf8
     null-terminated string.

     SIZE must point to the total size of the buffer.  If BUFFER is
     NULL or if SIZE is not big enough, write the required buffer size
     to SIZE and return true.

     Note that SIZE must include the last null byte (e.g. "abc" needs
     a buffer of size 4).

     Return true if the string was successfully copied.  */

  bool (*copy_string_contents) (emacs_env *env,
                                emacs_value value,
                                char *buf,
                                ptrdiff_t *len)
    EMACS_ATTRIBUTE_NONNULL(1, 4);

  /* Create a Lisp string from a utf8 encoded string.  */
  emacs_value (*make_string) (emacs_env *env,
			      const char *str, ptrdiff_t len)
    EMACS_ATTRIBUTE_NONNULL(1, 2);

  /* Embedded pointer type.  */
  emacs_value (*make_user_ptr) (emacs_env *env,
				void (*fin) (void *) EMACS_NOEXCEPT,
				void *ptr)
    EMACS_ATTRIBUTE_NONNULL(1);

  void *(*get_user_ptr) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL(1);
  void (*set_user_ptr) (emacs_env *env, emacs_value arg, void *ptr)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*(*get_user_finalizer) (emacs_env *env, emacs_value uptr))
    (void *) EMACS_NOEXCEPT EMACS_ATTRIBUTE_NONNULL(1);
  void (*set_user_finalizer) (emacs_env *env, emacs_value arg,
			      void (*fin) (void *) EMACS_NOEXCEPT)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Vector functions.  */
  emacs_value (*vec_get) (emacs_env *env, emacs_value vector, ptrdiff_t index)
    EMACS_ATTRIBUTE_NONNULL(1);

  void (*vec_set) (emacs_env *env, emacs_value vector, ptrdiff_t index,
		   emacs_value value)
    EMACS_ATTRIBUTE_NONNULL(1);

  ptrdiff_t (*vec_size) (emacs_env *env, emacs_value vector)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Returns whether a quit is pending.  */
  bool (*should_quit) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL(1);

  /* Processes pending input events and returns whether the module
     function should quit.  */
  enum emacs_process_input_result (*process_input) (emacs_env *env)
    EMACS_ATTRIBUTE_NONNULL (1);

  struct timespec (*extract_time) (emacs_env *env, emacs_value arg)
    EMACS_ATTRIBUTE_NONNULL (1);

  emacs_value (*make_time) (emacs_env *env, struct timespec time)
    EMACS_ATTRIBUTE_NONNULL (1);

  bool (*extract_big_integer) (emacs_env *env, emacs_value arg, int *sign,
                               ptrdiff_t *count, emacs_limb_t *magnitude)
    EMACS_ATTRIBUTE_NONNULL (1);

  emacs_value (*make_big_integer) (emacs_env *env, int sign, ptrdiff_t count,
                                   const emacs_limb_t *magnitude)
    EMACS_ATTRIBUTE_NONNULL (1);

  /* Add module environment functions newly added in Emacs 28 here.
     Before Emacs 28 is released, remove this comment and start
     module-env-29.h on the master branch.  */

  void (*(*EMACS_ATTRIBUTE_NONNULL (1)
            get_function_finalizer) (emacs_env *env,
                                     emacs_value arg)) (void *) EMACS_NOEXCEPT;

  void (*set_function_finalizer) (emacs_env *env, emacs_value arg,
                                  void (*fin) (void *) EMACS_NOEXCEPT)
    EMACS_ATTRIBUTE_NONNULL (1);

  int (*open_channel) (emacs_env *env, emacs_value pipe_process)
    EMACS_ATTRIBUTE_NONNULL (1);

  void (*make_interactive) (emacs_env *env, emacs_value function,
                            emacs_value spec)
    EMACS_ATTRIBUTE_NONNULL (1);

  /* Create a unibyte Lisp string from a string.  */
  emacs_value (*make_unibyte_string) (emacs_env *env,
				      const char *str, ptrdiff_t len)
    EMACS_ATTRIBUTE_NONNULL(1, 2);
};

/* Every module should define a function as follows.  */
extern int emacs_module_init (struct emacs_runtime *runtime)
  EMACS_NOEXCEPT
  EMACS_ATTRIBUTE_NONNULL (1);

#ifdef __cplusplus
}
#endif

#endif /* EMACS_MODULE_H */
07070100000005000081A400000000000000000000000167EFC12900001D66000000000000000000000000000000000000001400000000jinx-2.1/jinx-mod.c/* Jinx bindings to libenchant

Copyright (C) 2023-2025 Free Software Foundation, Inc.

GNU Emacs 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.

GNU Emacs 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 GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

#include <emacs-module.h>
#include <enchant.h>
#include <stdlib.h>
#include <string.h>

#define jinx_unused(var) _##var __attribute__((unused))
#define jinx_autofree    __attribute__((cleanup(jinx_autofree_cleanup)))

int plugin_is_GPL_compatible;

static EnchantBroker* broker = 0;
static emacs_value Qt, Qnil, Qcons;

static EnchantBroker* jinx_broker(void) {
    return broker ? broker : (broker = enchant_broker_init());
}

static void jinx_autofree_cleanup(char **p) {
    free(*(void**)p);
}

static emacs_value jinx_str(emacs_env* env, const char* str) {
    return env->make_string(env, str, strlen(str));
}

static emacs_value jinx_cons(emacs_env* env, emacs_value a, emacs_value b) {
    return env->funcall(env, Qcons, 2, (emacs_value[]){a, b});
}

static char* jinx_cstr(emacs_env* env, emacs_value val) {
    ptrdiff_t size = 0;
    if (!env->copy_string_contents(env, val, 0, &size))
        return 0;
    char* str = malloc(size);
    if (!str) {
        env->non_local_exit_signal(env,
                                   env->intern(env, "memory-full"),
                                   Qnil);
        return 0;
    }
    if (!env->copy_string_contents(env, val, str, &size)) {
        free(str);
        return 0;
    }
    return str;
}

static void jinx_defun(emacs_env* env, const char* name,
                       ptrdiff_t min, ptrdiff_t max, void* fun) {
    env->funcall(env, env->intern(env, "defalias"), 2,
                 (emacs_value[]){
                     env->intern(env, name),
                     env->make_function(env, min, max, fun, 0, 0)
                 });
}

static void jinx_free_dict(void* dict) {
    enchant_broker_free_dict(broker, dict);
}

static emacs_value jinx_dict(emacs_env* env, ptrdiff_t jinx_unused(nargs),
                             emacs_value args[], void* jinx_unused(data)) {
    jinx_autofree char* str = jinx_cstr(env, args[0]);
    EnchantDict* dict =
        str ? enchant_broker_request_dict(jinx_broker(), str) : 0;
    return dict
        ? env->make_user_ptr(env, jinx_free_dict, dict)
        : Qnil;
}

static void jinx_describe_cb(const char* const lang_tag,
                             const char* const provider_name,
                             const char* const jinx_unused(provider_desc),
                             const char* const jinx_unused(provider_file),
                             void* data) {
    emacs_env* env = ((emacs_env**)data)[0];
    ((emacs_value*)data)[1] = jinx_cons(env,
                                        jinx_str(env, lang_tag),
                                        jinx_str(env, provider_name));
}

static emacs_value jinx_describe(emacs_env* env, ptrdiff_t jinx_unused(nargs),
                                 emacs_value args[], void* jinx_unused(data)) {
    EnchantDict* dict = env->get_user_ptr(env, args[0]);
    if (!dict)
        return Qnil;
    void* data[] = { env, 0 };
    enchant_dict_describe(dict, jinx_describe_cb, data);
    return data[1];
}

static void jinx_langs_cb(const char* const lang_tag,
                          const char* const provider_name,
                          const char* const jinx_unused(provider_desc),
                          const char* const jinx_unused(provider_file),
                          void* data) {
    emacs_env* env = ((emacs_env**)data)[0];
    ((emacs_value*)data)[1] = jinx_cons(env,
                                        jinx_cons(env,
                                                  jinx_str(env, lang_tag),
                                                  jinx_str(env, provider_name)),
                                        ((emacs_value*)data)[1]);
}

static emacs_value jinx_langs(emacs_env* env, ptrdiff_t jinx_unused(nargs),
                              emacs_value jinx_unused(args[]),
                              void* jinx_unused(data)) {
    void* data[] = { env, Qnil };
    enchant_broker_list_dicts(jinx_broker(), jinx_langs_cb, data);
    return data[1];
}

static emacs_value jinx_check(emacs_env* env, ptrdiff_t jinx_unused(nargs),
                              emacs_value args[], void* jinx_unused(data)) {
    EnchantDict* dict = env->get_user_ptr(env, args[0]);
    jinx_autofree char* str = jinx_cstr(env, args[1]);
    // Do not error in the checking function (Non-Unicode strings)
    env->non_local_exit_clear(env);
    return !dict || !str || enchant_dict_check(dict, str, -1) ? Qnil : Qt;
}

static emacs_value jinx_add(emacs_env* env, ptrdiff_t jinx_unused(nargs),
                            emacs_value args[], void* jinx_unused(data)) {
    EnchantDict* dict = env->get_user_ptr(env, args[0]);
    jinx_autofree char* str = jinx_cstr(env, args[1]);
    if (dict && str)
        enchant_dict_add(dict, str, -1);
    return Qnil;
}

static emacs_value jinx_wordchars(emacs_env* env, ptrdiff_t jinx_unused(nargs),
                                  emacs_value args[], void* jinx_unused(data)) {
    EnchantDict* dict = env->get_user_ptr(env, args[0]);
    if (dict) {
        // Enchant older than 2.3.1 does not enforce UTF-8 <gh:rrthomas/enchant#278>
        emacs_value str = jinx_str(env, enchant_dict_get_extra_word_characters(dict));
        if (env->non_local_exit_check(env) == emacs_funcall_exit_return)
            return str;
        env->non_local_exit_clear(env);
    }
    return Qnil;
}

static emacs_value jinx_suggest(emacs_env* env, ptrdiff_t jinx_unused(nargs),
                                emacs_value args[], void* jinx_unused(data)) {
    EnchantDict* dict = env->get_user_ptr(env, args[0]);
    jinx_autofree char* str = jinx_cstr(env, args[1]);
    emacs_value list = Qnil;
    size_t count = 0;
    char** suggs = str && dict ? enchant_dict_suggest(dict, str, -1, &count) : 0;
    if (suggs) {
        while (count > 0)
            list = jinx_cons(env, jinx_str(env, suggs[--count]), list);
        enchant_dict_free_string_list(dict, suggs);
    }
    return list;
}

int emacs_module_init(struct emacs_runtime *runtime) {
    // Require Emacs binary compatibility
    if ((size_t)runtime->size < sizeof (*runtime))
        return 1;
    emacs_env* env = runtime->get_environment(runtime);
    if ((size_t)env->size < sizeof (*env))
        return 2;
    Qt = env->make_global_ref(env, env->intern(env, "t"));
    Qnil = env->make_global_ref(env, env->intern(env, "nil"));
    Qcons = env->make_global_ref(env, env->intern(env, "cons"));
    jinx_defun(env, "jinx--mod-suggest", 2, 2, jinx_suggest);
    jinx_defun(env, "jinx--mod-check", 2, 2, jinx_check);
    jinx_defun(env, "jinx--mod-add", 2, 2, jinx_add);
    jinx_defun(env, "jinx--mod-dict", 1, 1, jinx_dict);
    jinx_defun(env, "jinx--mod-langs", 0, 0, jinx_langs);
    jinx_defun(env, "jinx--mod-describe", 1, 1, jinx_describe);
    jinx_defun(env, "jinx--mod-wordchars", 1, 1, jinx_wordchars);
    return 0;
}
07070100000006000081A400000000000000000000000167EFC1290000BBF6000000000000000000000000000000000000001100000000jinx-2.1/jinx.el;;; jinx.el --- Enchanted Spell Checker -*- lexical-binding: t -*-

;; Copyright (C) 2023-2025 Free Software Foundation, Inc.

;; Author: Daniel Mendler <mail@daniel-mendler.de>
;; Maintainer: Daniel Mendler <mail@daniel-mendler.de>
;; Created: 2023
;; Version: 2.1
;; Package-Requires: ((emacs "28.1") (compat "30"))
;; URL: https://github.com/minad/jinx
;; Keywords: convenience, text

;; This file is part of GNU Emacs.

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

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

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

;;; Commentary:

;; Jinx is a fast just-in-time spell-checker for Emacs.  Jinx
;; highlights misspelled words in the text of the visible portion of
;; the buffer.  For efficiency, Jinx highlights misspellings lazily,
;; recognizes window boundaries and text folding, if any.  For
;; example, when unfolding or scrolling, only the newly visible part
;; of the text is checked if it has not been checked before.  Each
;; misspelling can be corrected from a list of dictionary words
;; presented as a completion menu.

;; Installing Jinx is straight-forward and configuring should not need
;; much intervention.  Jinx can be used completely on its own, but can
;; also safely co-exist with Emacs's built-in spell-checker Ispell.

;; Jinx's high performance and low resource usage comes from directly
;; calling the API of the Enchant library, see
;; https://rrthomas.github.io/enchant/.  Jinx automatically compiles
;; jinx-mod.c and loads the dynamic module at startup.  By binding
;; directly to the native Enchant API, Jinx avoids slower
;; inter-process communication.

;; See the manual for further information.

;;; Code:

(require 'compat)
(eval-when-compile
  (require 'cl-lib)
  (require 'subr-x))

;;;; Customization

(defgroup jinx nil
  "Enchanted Spell Checker."
  :link '(info-link :tag "Info Manual" "(jinx)")
  :link '(url-link :tag "Website" "https://github.com/minad/jinx")
  :link '(url-link :tag "Wiki" "https://github.com/minad/jinx/wiki")
  :link '(emacs-library-link :tag "Library Source" "jinx.el")
  :group 'text
  :prefix "jinx-")

(defcustom jinx-delay 0.2
  "Idle timer delay."
  :type 'float)

(defcustom jinx-languages
  (replace-regexp-in-string
   "\\..*\\'" ""
   (or (bound-and-true-p current-locale-environment)
       (pcase (getenv "LANG")
         ((or "C" "POSIX") nil)
         (lang lang))
       "en_US"))
  "Dictionary language codes, as a string separated by whitespace."
  :type 'string)

(defcustom jinx-save-languages 'ask
  "Save the variable `jinx-languages' as file-local variable?"
  :type '(choice (const :tag "Never"  nil)
                 (const :tag "Always" t)
                 (const :tag "Ask"    ask)))

;;;###autoload
(put 'jinx-languages 'safe-local-variable #'stringp)

(defcustom jinx-include-faces
  '((prog-mode font-lock-comment-face
               font-lock-doc-face
               font-lock-string-face)
    (conf-mode font-lock-comment-face
               font-lock-string-face)
    ;; `yaml-mode' and `yaml-ts-mode' are text-modes,
    ;; while they should better be conf- or prog-modes.
    (yaml-mode . conf-mode)
    (yaml-ts-mode . conf-mode))
  "Alist of faces per major mode.
These faces mark regions which should be included in spell
checking."
  :type '(alist :key-type symbol :value-type (choice symbol (repeat face))))

(defcustom jinx-camel-modes
  '(java-mode java-ts-mode js-mode js-ts-mode ruby-mode ruby-ts-mode rust-mode
    rust-ts-mode haskell-mode kotlin-mode swift-mode csharp-mode csharp-ts-mode
    objc-mode typescript-ts-mode typescript-mode tsx-ts-mode python-mode
    python-ts-mode dart-mode go-mode go-ts-mode scala-mode groovy-mode)
  "Modes where camelCase or PascalCase words should be accepted.
Set to t to enable camelCase everywhere."
  :type '(choice (const t) (repeat symbol)))

(defcustom jinx-exclude-faces
  '((markdown-mode
     markdown-code-face markdown-html-attr-name-face
     markdown-html-attr-value-face markdown-html-tag-name-face
     markdown-inline-code-face markdown-link-face markdown-markup-face
     markdown-plain-url-face markdown-reference-face markdown-url-face)
    (org-mode
     org-block org-block-begin-line org-block-end-line org-code org-cite
     org-cite-key org-date org-document-info-keyword org-done org-drawer
     org-footnote org-formula org-latex-and-related org-link org-macro
     org-meta-line org-property-value org-special-keyword org-tag org-todo
     org-verbatim org-warning
     ;; org-modern
     org-modern-tag org-modern-date-active org-modern-date-inactive)
    (tex-mode
     tex-math font-latex-math-face font-latex-sedate-face
     font-latex-verbatim-face font-lock-function-name-face
     font-lock-keyword-face font-lock-variable-name-face)
    (texinfo-mode
     font-lock-function-name-face font-lock-keyword-face
     font-lock-variable-name-face)
    (rst-mode
     rst-literal rst-external rst-directive rst-definition rst-reference)
    (sgml-mode
     font-lock-function-name-face font-lock-variable-name-face)
    (lisp-data-mode
     font-lock-constant-face font-lock-warning-face)
    (message-mode
     message-separator message-header-cc message-header-name
     message-header-newsgroups message-header-other message-header-to
     message-header-xheader message-cited-text-1 message-cited-text-2
     message-cited-text-3 message-cited-text-4 gnus-cite-1 gnus-cite-2
     gnus-cite-3 gnus-cite-4 gnus-cite-5 gnus-cite-6 gnus-cite-7 gnus-cite-8
     gnus-cite-9 gnus-cite-10 gnus-cite-11))
  "Alist of faces per major mode.
These faces mark regions which should be excluded in spell
checking."
  :type '(alist :key-type symbol :value-type (choice symbol (repeat face))))

(defcustom jinx-exclude-regexps
  '((emacs-lisp-mode "Package-Requires:.*$")
    (t "[A-Z]+\\>"         ;; Uppercase words
       "-+\\>"             ;; Hyphens used as lines or bullet points
       "\\w*?[0-9]\\w*\\>" ;; Words with numbers, hex codes
       "[a-z]+://\\S-+"    ;; URI
       "<?[-+_.~a-zA-Z][-+_.~:a-zA-Z0-9]*@[-.a-zA-Z0-9]+>?" ;; Email
       "\\(?:Local Variables\\|End\\):\\s-*$" ;; Local variable indicator
       "jinx-\\(?:languages\\|local-words\\):\\s-+.*$")) ;; Local variables
  "List of excluded regexps per major mode."
  :type '(alist :key-type symbol :value-type (choice symbol (repeat regexp))))

(defcustom jinx-suggestion-distance 3
  "Maximal edit distance for session words to be included in suggestions."
  :type 'natnum)

(defcustom jinx-menu-suggestions 10
  "Maximal number of suggestions shown in the context menu."
  :type 'natnum)

(defvar-local jinx-local-words ""
  "File-local words, as a string separated by whitespace.")

(defvar-local jinx-dir-local-words ""
  "Directory-local words, as a string separated by whitespace.")

;;;###autoload
(progn
  (put 'jinx-local-words 'safe-local-variable #'stringp)
  (put 'jinx-dir-local-words 'safe-local-variable #'stringp)
  (put 'jinx-mode 'safe-local-variable #'not))

;;;; Faces

(defgroup jinx-faces nil
  "Faces used by Jinx."
  :group 'jinx
  :group 'faces)

(defface jinx-misspelled
  '((((class color) (min-colors 88) (background dark)
      (supports :underline (:style wave)))
     :underline (:style wave :color "#d2b580"))
    (((class color) (min-colors 88) (background light)
      (supports :underline (:style wave)))
     :underline (:style wave :color "#5f4400"))
    (t :underline t :inherit error))
  "Face used for misspelled words.")

(defface jinx-highlight
  '((t :inherit isearch))
  "Face used to highlight current misspelled word during correction.")

(defface jinx-save
  '((t :inherit warning))
  "Face used for the save actions during correction.")

(defface jinx-key
  '((t :inherit completions-annotations))
  "Face used for the select key during correction.")

(defface jinx-annotation
  '((t :inherit completions-annotations))
  "Face used for the annotation during correction.")

;;;; Keymaps

(defvar-keymap jinx-overlay-map
  :doc "Keymap attached to misspelled words."
  "<down-mouse-3>" `(menu-item "" (keymap) :filter ,#'jinx--correct-menu)
  "M-n" #'jinx-next
  "M-p" #'jinx-previous
  "M-$" #'jinx-correct)

(fset 'jinx-overlay-map jinx-overlay-map)

(defvar-keymap jinx-repeat-map
  :doc "Repeat keymap for navigation commands."
  :repeat (:exit (jinx-correct))
  "M-n" #'jinx-next
  "M-p" #'jinx-previous
  "n" #'jinx-next
  "p" #'jinx-previous
  "$" #'jinx-correct)

(defvar-keymap jinx-correct-map
  :doc "Keymap active in the correction minibuffer."
  "SPC" #'self-insert-command
  "M-n" #'jinx-next
  "M-p" #'jinx-previous
  "M-$" #'jinx-previous
  "0 <t>" #'jinx-correct-select)
(dotimes (i 9)
  (define-key jinx-correct-map (vector (+ ?1 i)) #'jinx-correct-select))

(defvar-keymap jinx-mode-map
  :doc "Keymap used when Jinx is active.")

(easy-menu-define jinx-mode-menu jinx-mode-map
  "Menu used when Jinx is active."
  '("Jinx"
    ["Correct nearest" jinx-correct]
    ["Correct all" jinx-correct-all
     :keys "\\[universal-argument] \\[jinx-correct]"]
    ["Correct word" jinx-correct-word
     :keys "\\[universal-argument] \\[universal-argument] \\[jinx-correct]"]
    ["Change languages" jinx-languages]
    "----"
    ["Manual" (info "(jinx)")]
    ["Customize" (customize-group 'jinx)]
    ["Turn off" (jinx-mode -1)]))

;;;; Internal variables

(defvar jinx--compile-flags
  '("-I." "-O2" "-Wall" "-Wextra" "-fPIC" "-shared")
  "List of compile flags passed to the C compiler.")

(defvar jinx--reschedule-hooks
  '(window-selection-change-functions window-scroll-functions
    window-state-change-hook post-command-hook)
  "Hooks which reschedule the spell checking timer, see `jinx--reschedule'.")

(defvar jinx--predicates
  (list #'jinx--face-ignored-p
        #'jinx--regexp-ignored-p
        #'jinx--word-valid-p)
  "Predicate functions called at point with argument START.
Predicate should return t if the word before point is valid.
Predicate may return a position to skip forward.")

(defvar jinx--timer (timer-create)
  "Global timer to check pending regions.")

(defvar jinx--base-syntax-table
  (let ((st (make-syntax-table)))
    (modify-syntax-entry ?$ "_" st)
    (modify-syntax-entry ?% "_" st)
    (modify-syntax-entry '(#xe000 . #xf8ff) "_" st)    ;; Priv. use area
    (modify-syntax-entry '(#xf0000 . #xffffd) "_" st)  ;; Supp. priv. use area A
    (modify-syntax-entry '(#x100000 . #x10fffd) "_" st);; Supp. priv. use area B
    (modify-syntax-entry '(#x80 . #x9f) "_" st)        ;; Control characters
    (modify-syntax-entry '(#x2150 . #x2bff) "_" st)    ;; Number Forms - Misc. Arrows
    (modify-syntax-entry '(#xfe00 . #xfe0f) "_" st)    ;; Variation Selectors
    (modify-syntax-entry '(#x1cf00 . #x1d7ff) "_" st)  ;; Znamenny Musical - Math. Alpha.
    (modify-syntax-entry '(#x1ee00 . #x1fbff) "_" st)  ;; Arabic Math. - Legacy Computing
    st)
  "Parent syntax table of `jinx--syntax-table'.")

(defvar jinx--syntax-overrides
  '((?' . "w")
    (?’ . "w")
    (?. . "."))
  "Syntax table overrides used for `jinx--syntax-table'.")

(defvar jinx--select-keys
  "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  "Quick select keys used by `jinx-correct'.")

(defvar jinx--save-keys
  `((?@ . ,#'jinx--save-personal)
    (?* . ,#'jinx--save-file)
    (?/ . ,#'jinx--save-dir)
    (?+ . ,#'jinx--save-session))
  "Keys for save actions used by `jinx-correct'.")

(defvar-local jinx--exclude-faces nil
  "List of excluded faces.")

(defvar-local jinx--include-faces nil
  "List of included faces.")

(defvar-local jinx--exclude-regexp nil
  "Ignore regexp.")

(defvar-local jinx--camel nil
  "Accept camel case.")

(defvar-local jinx--dicts nil
  "List of dictionaries.")

(defvar jinx--dicts-hash (make-hash-table :test #'equal :weakness 'value)
  "Weak hash table of all loaded dictionaries.")

(defvar-local jinx--syntax-table nil
  "Syntax table used during checking.
The table inherits from `jinx--base-syntax-table'.  The table is
configured according to the word characters defined by the local
dictionaries.  Afterwards `jinx--syntax-overrides' are applied.")

(defvar-local jinx--session-words nil
  "List of words accepted in this session.")

;;;; Declarations for the bytecode compiler

(defvar repeat-mode)
(defvar jinx-mode)
(declare-function jinx--mod-check nil)
(declare-function jinx--mod-add nil)
(declare-function jinx--mod-suggest nil)
(declare-function jinx--mod-dict nil)
(declare-function jinx--mod-describe nil)
(declare-function jinx--mod-langs nil)
(declare-function jinx--mod-wordchars nil)

;;;; Overlay properties

(put 'jinx-overlay 'evaporate             t)
(put 'jinx-overlay 'face                  'jinx-misspelled)
(put 'jinx-overlay 'mouse-face            '(jinx-misspelled jinx-highlight))
(put 'jinx-overlay 'modification-hooks    (list #'jinx--overlay-modified))
(put 'jinx-overlay 'insert-in-front-hooks (list #'jinx--overlay-modified))
(put 'jinx-overlay 'insert-behind-hooks   (list #'jinx--overlay-modified))
(put 'jinx-overlay 'keymap                'jinx-overlay-map)
(put 'jinx-overlay 'help-echo             "Jinx: \\`mouse-3' menu, \\[jinx-correct] correct, \\`M-p' previous, \\`M-n' next")

;;;; Predicates

(defun jinx--regexp-ignored-p (start)
  "Return non-nil if word at START matches ignore regexps."
  (save-excursion
    (goto-char start)
    (when (and jinx--exclude-regexp (looking-at-p jinx--exclude-regexp))
      (save-match-data
        (looking-at jinx--exclude-regexp)
        (match-end 0)))))

(defun jinx--face-ignored-p (start)
  "Return non-nil if face at START of word is ignored."
  (let ((face (get-text-property start 'face)))
    (or
     (and jinx--include-faces
          (if (listp face)
              (cl-loop for f in face never (memq f jinx--include-faces))
            (not (memq face jinx--include-faces))))
     (and jinx--exclude-faces
          (if (listp face)
              (cl-loop for f in face thereis (memq f jinx--exclude-faces))
            (memq face jinx--exclude-faces))))))

(defun jinx--word-valid-p (word)
  "Return non-nil if WORD is valid.
WORD can also be a start position."
  (unless (stringp word)
    (setq word (buffer-substring-no-properties word (point))))
  (or (member word jinx--session-words)
      ;; Allow capitalized words
      (let (case-fold-search)
        (and (string-match-p "\\`[[:upper:]][[:lower:]]+\\'" word)
             (cl-loop
              for w in jinx--session-words
              thereis (and (string-equal-ignore-case word w)
                           (string-match-p "\\`[[:lower:]]+\\'" w)))))
      (cl-loop for dict in jinx--dicts
               thereis (jinx--mod-check dict word))))

;;;; Internal functions

(defun jinx--in-base-buffer (&rest app)
  "Apply APP in `buffer-base-buffer', as required by `jit-lock' functions."
  (with-current-buffer (or (buffer-base-buffer) (current-buffer))
    (apply app)))

(defun jinx--overlay-modified (overlay &rest _)
  "Delete modified OVERLAY.
This function is a modification hook for the overlay."
  (delete-overlay overlay))

(defun jinx--find-visible (start end visible)
  "Find (in)visible region between START and END.
VISIBLE must be nil or t."
  (while (and (< start end) (eq (not visible) (not (invisible-p start))))
    (let ((next (next-single-char-property-change start 'invisible nil end)))
      ;; END can be outside the buffer if the buffer size has changed in
      ;; between. Then `next-single-property-change' will return (point-max)
      ;; instead of END. See gh:minad/jinx#156.
      (setq start (if (> next start) next end))))
  start)

(defun jinx--check-pending (start end)
  "Check pending visible region between START and END."
  (let ((retry (and (eq (window-buffer) (current-buffer))
                    (symbolp real-last-command)
                    (string-match-p "self-insert-command\\'"
                                    (symbol-name real-last-command))
                    (window-point))))
    (while (< start end)
      (let* ((vfrom (jinx--find-visible start end t))
             (vto (jinx--find-visible vfrom end nil)))
        (while (< vfrom vto)
          (let* ((pfrom (or (text-property-any vfrom vto 'jinx--pending t) vto))
                 (pto (or (text-property-not-all pfrom vto 'jinx--pending t) vto)))
            (when (< pfrom pto)
              (jinx--check-region pfrom pto retry))
            (setq vfrom pto)))
        (setq start vto)))))

(defun jinx--check-region (start end &optional retry)
  "Check region between START and END.
Optionally RETRY word at given position.  Return updated END
position."
  (let ((st (syntax-table)) case-fold-search
        retry-start retry-end)
    (unwind-protect
        (with-silent-modifications
          (save-excursion
            (save-match-data
              ;; Use dictionary-dependent syntax table
              (set-syntax-table jinx--syntax-table)
              ;; Ensure that region starts and ends at word boundaries
              (goto-char start)
              (unless (looking-at-p "\\<")
                (re-search-backward "\\<\\|^")
                (setq start (match-beginning 0)))
              (goto-char end)
              (unless (looking-at-p "\\>")
                (re-search-forward "\\>\\|$")
                (setq end (match-beginning 0)))
              (jinx--delete-overlays start end)
              (goto-char start)
              (while (re-search-forward "\\<\\w+\\>" end t)
                (let ((word-start (match-beginning 0))
                      (word-end (match-end 0)))
                  ;; No quote or apostrophe at start or end
                  (while (and (< word-start word-end)
                              (let ((c (char-after word-start)))
                                (or (= c ?') (= c ?’))))
                    (cl-incf word-start))
                  (while (and (< word-start word-end)
                              (let ((c (char-before word-end)))
                                (or (= c ?') (= c ?’))))
                    (cl-decf word-end))
                  (while (< word-start word-end)
                    (let ((subword-end word-end))
                      (when jinx--camel
                        (goto-char word-start)
                        (when (looking-at "\\([[:upper:]]?[[:lower:]]+\\)\\(?:[[:upper:]][[:lower:]]+\\)+\\>")
                          (setq subword-end (match-end 1))))
                      (goto-char subword-end)
                      (pcase (run-hook-with-args-until-success 'jinx--predicates word-start)
                        ((and (pred integerp) skip)
                         (goto-char (max subword-end (min end skip))))
                        ('nil
                         (if (and retry (<= word-start retry subword-end))
                             (setq retry-start word-start retry-end subword-end retry nil)
                           (overlay-put (make-overlay word-start subword-end) 'category 'jinx-overlay))))
                      (setq word-start subword-end)))))
              (remove-list-of-text-properties start end '(jinx--pending))
              (when retry-start
                (put-text-property retry-start retry-end 'jinx--pending t)))))
      (set-syntax-table st))))

(defun jinx--get-overlays (start end &optional visible)
  "Return misspelled word overlays between START and END.
If VISIBLE is non-nil, only include visible overlays."
  (let ((pt (point)) before overlays)
    (dolist (ov (overlays-in start end))
      (when (and (eq (overlay-get ov 'category) 'jinx-overlay)
                 (not (and visible (invisible-p (overlay-start ov)))))
        (push ov overlays)))
    (setq overlays
          (sort overlays
                (lambda (a b) (< (overlay-start a) (overlay-start b)))))
    (while (and (cdr overlays) (<= (overlay-start (cadr overlays)) pt))
      (push (pop overlays) before))
    (nconc overlays (nreverse before))))

(cl-defun jinx--force-overlays (start end &key visible check)
  "Return misspelled word overlays between START and END, enforce checking.
If VISIBLE is non-nil, only include visible overlays.
If CHECK is non-nil, always check first."
  (or (and (not check) (jinx--get-overlays start end visible))
      (progn
        (with-delayed-message (1 "Fontifying...")
          (jinx--in-base-buffer #'jit-lock-fontify-now start end))
        (with-delayed-message (1 "Checking...")
          (jinx--check-region start end))
        (jinx--get-overlays start end visible))
      (user-error (if visible "No misspelled word in visible text"
                    "No misspelled word in whole buffer"))))

(defun jinx--delete-overlays (start end)
  "Delete overlays between START and END."
  (dolist (ov (overlays-in start end))
    (when (eq (overlay-get ov 'category) 'jinx-overlay)
      (delete-overlay ov))))

(defun jinx--cleanup ()
  "Cleanup all overlays and trigger fontification."
  (with-silent-modifications
    (without-restriction
      (jinx--delete-overlays (point-min) (point-max))
      (remove-list-of-text-properties (point-min) (point-max) '(jinx--pending))
      (jinx--in-base-buffer #'jit-lock-refontify))))

(defun jinx--mark-pending (start end)
  "Mark region between START and END as pending."
  (put-text-property start end 'jinx--pending t)
  (unless inhibit-quit ;; non-nil for stealth locking
    (jinx--schedule))
  nil)

(defun jinx--mode-list (list)
  "Lookup by major mode in LIST."
  (cl-loop for (mode . vals) in list
           if (or (eq mode t) (derived-mode-p mode))
           append (if (symbolp vals) (alist-get vals list) vals)))

(defun jinx--get-org-language ()
  "Get language from Org #+language keyword."
  (when (and (not (local-variable-p 'jinx-languages))
             (derived-mode-p 'org-mode))
    (save-excursion
      (save-match-data
        (goto-char (point-min))
        (when (re-search-forward "^ *#\\+language: +\\([a-z_]+\\) *$" nil t)
          (setq-local jinx-languages (match-string-no-properties 1)))))))

(defun jinx--timer-handler ()
  "Global timer handler, checking the pending regions in all windows."
  (timer-set-function jinx--timer nil)
  (dolist (frame (frame-list))
    (dolist (win (window-list frame 'no-miniwindow))
      (when-let ((buffer (window-buffer win))
                 ((buffer-local-value 'jinx-mode buffer)))
        (with-current-buffer buffer
          (jinx--check-pending (window-start win) (window-end win)))))))

(defun jinx--reschedule (&rest _)
  "Restart the global idle timer."
  (when (timer--function jinx--timer)
    (cancel-timer jinx--timer)
    (timer-set-function jinx--timer nil))
  (jinx--schedule))

(defun jinx--schedule ()
  "Start the global idle timer."
  (when (and (not (timer--function jinx--timer))
             (not completion-in-region-mode) ;; Corfu completion
             (get-buffer-window)) ;; Buffer visible
    (timer-set-function jinx--timer #'jinx--timer-handler)
    (timer-set-idle-time jinx--timer jinx-delay)
    (timer-activate-when-idle jinx--timer t)))

(defun jinx--load-module ()
  "Compile and load dynamic module."
  (unless (fboundp #'jinx--mod-dict)
    (unless module-file-suffix
      (error "Jinx: Dynamic modules are not supported"))
    (let* ((mod-name (file-name-with-extension "jinx-mod" module-file-suffix))
           (mod-file (locate-library mod-name t)))
      (unless mod-file
        (let* ((cc (or (getenv "CC")
                       (seq-find #'executable-find '("gcc" "clang" "cc"))
                       (error "Jinx: No C compiler found")))
               (c-name (file-name-with-extension mod-name ".c"))
               (default-directory (file-name-directory
                                   (or (locate-library c-name t)
                                       (error "Jinx: %s not found" c-name))))
               (command
                `(,cc ,@jinx--compile-flags "-o" ,mod-name ,c-name
                  ,@(split-string-and-unquote
                     (condition-case nil
                         (car (process-lines "pkg-config" "--cflags" "--libs" "enchant-2"))
                       (error "-I/usr/include/enchant-2 -I/usr/local/include/enchant-2 -L/usr/local/lib -lenchant-2"))))))
          (with-current-buffer (get-buffer-create "*jinx module compilation*")
            (let ((inhibit-read-only t))
              (erase-buffer)
              (compilation-mode)
              (insert (string-join command " ") "\n")
              (if (equal 0 (apply #'call-process (car command) nil (current-buffer) t (cdr command)))
                  (insert (message "Jinx: %s compiled successfully" mod-name))
                (let ((msg (format "Jinx: Compilation of %s failed" mod-name)))
                  (insert msg)
                  (pop-to-buffer (current-buffer))
                  (error msg)))))
          (setq mod-file (expand-file-name mod-name))))
      ;; Initialize Mac spell checker to avoid dead lock (gh:minad/jinx#91).
      (when (and (eq window-system 'mac) (fboundp 'mac-do-applescript))
        (mac-do-applescript
         "use framework \"AppKit\"
          set spellChecker to current application's NSSpellChecker's sharedSpellChecker()"))
      (module-load mod-file))))

(defmacro jinx--correct-guard (&rest body)
  "Guard BODY during correction loop."
  `(cl-letf (((symbol-function #'jinx--timer-handler) #'ignore) ;; Inhibit
             (repeat-mode nil)) ;; No repeating of jinx-next and jinx-previous
     (unless jinx-mode (jinx-mode 1))
     ,@body))

(defun jinx--invisible-open-temporarily ()
  "Temporarily open overlays which hide the current line.
See `isearch-open-necessary-overlays' and `isearch-open-overlay-temporary'."
  (let (restore)
    (dolist (ov (overlays-in (pos-bol) (pos-eol)) restore)
      (let ((inv (overlay-get ov 'invisible)))
        (when (and (invisible-p inv) (overlay-get ov 'isearch-open-invisible))
          (push (if-let ((fun (overlay-get ov 'isearch-open-invisible-temporary)))
                    (progn
                      (funcall fun ov nil)
                      (lambda () (funcall fun ov t)))
                  (overlay-put ov 'invisible nil)
                  (lambda () (overlay-put ov 'invisible inv)))
                restore))))))

(defun jinx--invisible-open-permanently ()
  "Open overlays which hide the current line.
See `isearch-open-necessary-overlays' and `isearch-open-overlay-temporary'."
  (dolist (ov (overlays-in (pos-bol) (pos-eol)))
    (when-let (fun (overlay-get ov 'isearch-open-invisible))
      (when (invisible-p (overlay-get ov 'invisible))
        (funcall fun ov)))))

(defun jinx--correct-highlight (overlay fun)
  "Highlight and show OVERLAY during FUN."
  (declare (indent 1))
  (let (restore)
    (goto-char (overlay-end overlay))
    (unwind-protect
        (let ((hl (make-overlay (overlay-start overlay) (overlay-end overlay))))
          (overlay-put hl 'face 'jinx-highlight)
          (overlay-put hl 'window (selected-window))
          (setq restore (cons (lambda () (delete-overlay hl))
                              (jinx--invisible-open-temporarily)))
          (funcall fun))
      (mapc #'funcall restore))))

(defun jinx--recheck-overlays ()
  "Recheck all overlays in buffer after a dictionary update."
  (save-excursion
    (without-restriction
      (dolist (ov (overlays-in (point-min) (point-max)))
        (when (eq (overlay-get ov 'category) 'jinx-overlay)
          (goto-char (overlay-end ov))
          (when (jinx--word-valid-p (overlay-start ov))
            (delete-overlay ov)))))))

(defun jinx--correct-setup ()
  "Setup minibuffer for correction."
  (use-local-map (make-composed-keymap (list jinx-correct-map) (current-local-map)))
  ;; TODO Use `eager-display' on Emacs 31
  (when (and (eq completing-read-function #'completing-read-default)
             (not (bound-and-true-p vertico-mode))
             (not (bound-and-true-p icomplete-mode)))
    (let ((message-log-max nil)
          (inhibit-message t))
      (minibuffer-completion-help))))

(defun jinx--add-suggestion (list ht word group)
  "Add suggestion WORD to LIST and HT.
The word will be associated with GROUP and get a prefix key."
  (unless (gethash word ht)
    (add-text-properties
     0 (length word)
     (list 'jinx--group group
           'jinx--prefix
           (let ((idx (1+ (hash-table-count ht))))
             (cond
              ((< idx 10)
               (format #("%d " 0 3 (face jinx-key))
                       idx))
              ((< (- idx 10) (length jinx--select-keys))
               (format #("0%c " 0 4 (face jinx-key))
                       (aref jinx--select-keys (- idx 10)))))))
     word)
    (push word list)
    (puthash word t ht))
  list)

(defun jinx--session-suggestions (word)
  "Retrieve suggestions for WORD from session."
  (mapcar #'cdr
          (sort (cl-loop for w in jinx--session-words
                         for d = (string-distance word w)
                         if (<= d jinx-suggestion-distance)
                         collect (cons d w))
                #'car-less-than-car)))

(defun jinx--correct-suggestions (word)
  "Retrieve suggestions for WORD from all dictionaries."
  (let ((ht (make-hash-table :test #'equal))
        (list nil))
    (dolist (dict jinx--dicts)
      (let* ((desc (jinx--mod-describe dict))
             (group (format "Suggestions from dictionary ā€˜%s’ - %s"
                            (car desc) (cdr desc))))
        (dolist (w (jinx--mod-suggest dict word))
          (setq list (jinx--add-suggestion list ht w group)))))
    (dolist (w (jinx--session-suggestions word))
      (setq list (jinx--add-suggestion list ht w "Suggestions from session")))
    (cl-loop
     for (key . fun) in jinx--save-keys
     for actions = (funcall fun nil key word) do
     (when (and actions (not (consp (car actions))))
       (setq actions (list actions)))
     (cl-loop
      for (k w a) in actions
      for k2 = (propertize (if (stringp k) k (char-to-string k))
                           'face 'jinx-save 'rear-nonsticky t)
      for a2 = (format #(" [%s]" 0 5 (face jinx-annotation)) a)
      do (cl-loop
          for w2 in (delete-consecutive-dups (list w (downcase w))) do
          (push (propertize (concat k2 w2)
                            'jinx--group "Accept and save"
                            'jinx--suffix a2)
                list))))
    (nreverse list)))

(defun jinx--correct-affixation (cands)
  "Affixate CANDS during completion."
  (cl-loop for cand in cands collect
           (list cand
                 (or (get-text-property 0 'jinx--prefix cand) "")
                 (or (get-text-property 0 'jinx--suffix cand) ""))))

(defun jinx--correct-annotation (cand)
  "Annotate CAND during completion."
  (if-let ((prefix (get-text-property 0 'jinx--prefix cand)))
      (format #(" (%s)" 0 5 (face jinx-key)) (string-trim prefix))
    (get-text-property 0 'jinx--suffix cand)))

(defun jinx--group (word transform)
  "Group WORD during completion, TRANSFORM candidate if non-nil."
  (if transform
      word
    (get-text-property 0 'jinx--group word)))

;; TODO: Use `completion-table-with-metadata'
(defun jinx--table-with-metadata (table metadata)
  "Return new completion TABLE with METADATA."
  (lambda (string pred action)
    (if (eq action 'metadata)
        `(metadata . ,metadata)
      (complete-with-action action table string pred))))

(cl-defun jinx--correct-overlay (overlay &key info initial)
  "Correct word at OVERLAY.
Optionally show prompt INFO and insert INITIAL input."
  (catch 'jinx--goto
    (let* ((word (buffer-substring-no-properties
                  (overlay-start overlay) (overlay-end overlay)))
           (choice
            (jinx--correct-highlight overlay
              (lambda ()
                (when (or (< (point) (window-start)) (> (point) (window-end nil t)))
                  (recenter))
                (minibuffer-with-setup-hook
                    #'jinx--correct-setup
                  (or (completing-read
                       (format "Correct ā€˜%s’%s: " word (or info ""))
                       (jinx--table-with-metadata
                        (jinx--correct-suggestions word)
                        `((category . jinx)
                          (display-sort-function . ,#'identity)
                          (cycle-sort-function . ,#'identity)
                          (group-function . ,#'jinx--group)
                          (affixation-function . ,#'jinx--correct-affixation)
                          (annotation-function . ,#'jinx--correct-annotation)))
                       nil nil initial t word)
                      word)))))
           (len (length choice)))
      (pcase (and (> len 0) (assq (aref choice 0) jinx--save-keys))
        (`(,key . ,fun)
         (funcall fun 'save key
                  (if (> len 1) (substring-no-properties choice 1) word))
         (jinx--recheck-overlays))
        ((guard (not (equal choice word)))
         (jinx--correct-replace overlay choice)))
      nil)))

(defun jinx--correct-replace (overlay word)
  "Replace OVERLAY with WORD."
  (when-let ((start (overlay-start overlay))
             (end (overlay-end overlay)))
    (undo-boundary)
    (delete-overlay overlay)
    (goto-char end)
    (insert-before-markers word)
    (delete-region start end)))

(defun jinx--correct-menu (&rest _)
  "Return popup mouse menu to correct misspelling."
  (when-let ((posn (event-start last-input-event))
             (pt (posn-point posn))
             (ov (car (jinx--get-overlays pt pt t))))
    (let ((menu nil)
          (word (buffer-substring-no-properties
                 (overlay-start ov) (overlay-end ov))))
      (dolist (dict jinx--dicts)
        (when-let ((desc (jinx--mod-describe dict))
                   (suggestions (jinx--mod-suggest dict word)))
          (push `[,(concat "── " (car desc) " ─ " (cdr desc) " ──") :active nil] menu)
          (cl-loop for w in suggestions repeat jinx-menu-suggestions do
                   (push `[,w (jinx--correct-replace ,ov ,w)] menu))))
      (when-let ((suggestions (jinx--session-suggestions word)))
        (push ["── Session ──" :active nil] menu)
        (cl-loop for w in suggestions repeat jinx-menu-suggestions do
          (push `[,w (jinx--correct-replace ,ov ,w)] menu)))
      (push ["── Accept and save ──" :active nil] menu)
      (cl-loop for (key . fun) in jinx--save-keys
               for actions = (funcall fun nil key word) do
               (unless (consp (car actions)) (setq actions (list actions)))
               (cl-loop for (k w a) in actions do
                        (push `[,a (jinx-correct-word
                                    ,(overlay-start ov) ,(overlay-end ov)
                                    ,(concat (if (stringp k) k (char-to-string k)) w))]
                              menu)))
      (easy-menu-create-menu (format "Correct \"%s\"" word)
                             (delete-dups (nreverse menu))))))

(defun jinx--load-dicts ()
  "Load dictionaries and setup syntax table."
  (setq jinx--dicts (cl-loop for lang in (split-string jinx-languages)
                             ;; Keep a weak reference to loaded dictionaries.
                             ;; See <gh:rrthomas/enchant#402>.
                             for dict = (with-memoization (gethash lang jinx--dicts-hash)
                                          (jinx--mod-dict lang))
                             if dict collect dict)
        jinx--syntax-table (make-syntax-table jinx--base-syntax-table))
  (unless jinx--dicts
    (message "Jinx: No dictionaries available for %S" jinx-languages))
  (dolist (dict jinx--dicts)
    (cl-loop for c across (jinx--mod-wordchars dict) do
             (modify-syntax-entry c "w" jinx--syntax-table)))
  (cl-loop for (k . v) in jinx--syntax-overrides do
           (modify-syntax-entry k v jinx--syntax-table)))

(defun jinx--bounds-of-word ()
  "Return bounds of word at point using `jinx--syntax-table'."
  (save-excursion
    (save-match-data
      (with-syntax-table jinx--syntax-table
        (unless (looking-at-p "\\<")
          (re-search-backward "\\<"))
        (when (re-search-forward "\\<\\w+\\>" nil t)
          (cons (match-beginning 0) (match-end 0)))))))

(defun jinx--read-languages ()
  "Read languages via `completing-read-multiple'."
  (jinx--load-module)
  (let ((langs (delete-dups
                (cl-loop for (l . p) in (jinx--mod-langs) collect
                         (propertize l 'jinx--group (format "Provider %s" p))))))
      (string-join
       (or (completing-read-multiple
            (format "Change languages (%s): "
                    (string-join (split-string jinx-languages) ", "))
            (jinx--table-with-metadata langs `((group-function . ,#'jinx--group)))
            nil t)
           (user-error "No languages selected"))
       " ")))

(defun jinx--add-local-word (var word)
  "Add WORD to local word list VAR."
  (add-to-list 'jinx--session-words word)
  (set var
       (string-join
        (sort (delete-dups (cons word (split-string (symbol-value var))))
              #'string<)
        " ")))

;;;; Save functions

(defun jinx--save-personal (save key word)
  "Save WORD in personal dictionary.
If SAVE is non-nil save, otherwise format candidate given action KEY."
  (if save
      (let ((idx (seq-position word key (lambda (x y) (not (equal x y))))))
        (jinx--mod-add (or (nth idx jinx--dicts)
                           (user-error "Invalid dictionary"))
                       (substring word idx)))
    (cl-loop
     for dict in jinx--dicts for idx from 1
     for at = (make-string idx key)
     for ann = (format "Personal:%s" (car (jinx--mod-describe dict))) collect
     (list at word ann))))

(defun jinx--save-file (save key word)
  "Save WORD in file-local variable.
If SAVE is non-nil save, otherwise format candidate given action KEY."
  (if save
      (progn
        (jinx--add-local-word 'jinx-local-words word)
        (add-file-local-variable 'jinx-local-words jinx-local-words))
    (list key word "File")))

(defun jinx--save-dir (save key word)
  "Save WORD in directory-local variable.
Uses a .dir-locals.el file in the current directory or any parent
directory.  If no .dir-locals.el file is found, it is created in the
project root.  If no project root is found, it is created in the current
directory.  If SAVE is non-nil save, otherwise format candidate given
action KEY."
  (if save
      (progn
        (jinx--add-local-word 'jinx-dir-local-words word)
        (let ((default-directory
               (or (locate-dominating-file default-directory ".dir-locals.el")
                   (when-let (proj (project-current))
                     (declare-function project-root "project")
                     (project-root proj))
                   default-directory)))
          (add-dir-local-variable nil 'jinx-dir-local-words jinx-dir-local-words)))
    (list key word "Directory")))

(defun jinx--save-session (save key word)
  "Save WORD for the current session.
If SAVE is non-nil save, otherwise format candidate given action KEY."
  (if save
      (add-to-list 'jinx--session-words word)
    (list key word "Session")))

;;;; Public commands

;;;###autoload
(defun jinx-languages (langs &optional global)
  "Set languages locally or globally to LANGS.
LANGS should be one or more language codes as a string, separated
by whitespace.  When called interactively, the language codes are
read via `completing-read-multiple'.  If the prefix argument
GLOBAL is non-nil, the languages are changed globally for all
buffers.  See also the variable `jinx-languages'."
  (interactive (list (jinx--read-languages) current-prefix-arg))
  (unless jinx-mode (jinx-mode 1))
  (cond
   (global
    (kill-local-variable 'jinx-languages)
    (setq-default jinx-languages langs))
   (t
    (setq-local jinx-languages langs)
    (when (or (assq 'jinx-languages file-local-variables-alist)
              (if (eq jinx-save-languages 'ask)
                  (and buffer-file-name
                       (y-or-n-p "Save `jinx-languages' as file-local variable? "))
                jinx-save-languages))
      (add-file-local-variable 'jinx-languages jinx-languages)
      (setf (alist-get 'jinx-languages file-local-variables-alist) jinx-languages))))
  (jinx--load-dicts)
  (jinx--cleanup))

;;;###autoload
(defun jinx-correct-all (&optional only-check)
  "Correct all misspelled words in the buffer.
With prefix argument ONLY-CHECK, only check the buffer and highlight all
misspellings, but do not open the correction UI."
  (interactive "*P")
  (jinx--correct-guard
   (let* ((overlays (jinx--force-overlays (or (use-region-beginning) (point-min))
                                          (or (use-region-end) (point-max))
                                          :check t))
          (count (length overlays))
          (idx 0))
     (unless only-check
       (deactivate-mark)
       (push-mark)
       (while-let ((ov (nth idx overlays)))
         (if-let (((overlay-buffer ov))
                  (skip (jinx--correct-overlay ov :info (format " (%d of %d)" (1+ idx) count))))
             (setq idx (mod (+ idx skip) count))
           (cl-incf idx)))))))

;;;###autoload
(defun jinx-correct-nearest ()
  "Correct nearest misspelled word."
  (interactive "*")
  (save-excursion
    (jinx--correct-guard
     (let* ((overlays (jinx--force-overlays (window-start) (window-end) :visible t))
            (count (length overlays))
            (idx 0))
       ;; Not using `while-let' is intentional here.
       (while (when-let ((ov (nth idx overlays)))
                (if (overlay-buffer ov)
                    (when-let ((skip (jinx--correct-overlay ov)))
                      (setq idx (mod (+ idx skip) count)))
                  (cl-incf idx)))))))) ;; Skip deleted overlay

;;;###autoload
(defun jinx-correct-word (&optional start end initial)
  "Correct word between START and END, by default the word before point.
Suggest corrections even if the word is not misspelled.
Optionally insert INITIAL input in the minibuffer."
  (interactive)
  (unless (and start end)
    (setf (cons start end) (or (jinx--bounds-of-word)
                               (user-error "No word at point"))))
  (save-excursion
    (jinx--correct-guard
     (while-let ((skip (let ((ov (make-overlay start end)))
                         (unwind-protect
                             (jinx--correct-overlay ov :initial initial)
                         (delete-overlay ov)))))
       (forward-to-word skip)
       (when-let ((bounds (jinx--bounds-of-word)))
         (setf (cons start end) bounds
               initial nil))))))

;;;###autoload
(defun jinx-correct (&optional arg)
  "Correct word depending on prefix ARG.
This command dispatches to the following commands:
  - `jinx-correct-nearest': If prefix ARG is nil, correct nearest
    misspelled word.
  - `jinx-correct-all': If a region is marked, or if prefix ARG
    is 4, corresponding to \\[universal-argument] pressed once,
    correct all misspelled words.
  - `jinx-correct-word': If prefix ARG is 16, corresponding to
    \\[universal-argument] pressed twice, correct word before point.
  - If prefix ARG is 64, corresponding to \\[universal-argument] pressed
    three times, check the whole buffer, but do not open the correction
    UI."
  (interactive "*P")
  (pcase arg
    ('nil (if (use-region-p) (jinx-correct-all) (jinx-correct-nearest)))
    ('(16) (jinx-correct-word))
    ('(64) (jinx-correct-all t))
    (_ (jinx-correct-all))))

(defun jinx-correct-select ()
  "Quick selection key for corrections."
  (declare (completion ignore))
  (interactive)
  (let* ((keys (this-command-keys-vector))
         (word (nth (if (eq (aref keys 0) ?0)
                        (+ 9 (or (seq-position jinx--select-keys (aref keys 1)) 999))
                      (- (aref keys 0) ?1))
                    (all-completions "" minibuffer-completion-table))))
    (unless (and word (get-text-property 0 'jinx--prefix word))
      (user-error "Invalid select key `%s'" (key-description keys)))
    (delete-minibuffer-contents)
    (insert word)
    (exit-minibuffer)))

(defun jinx-next (n)
  "Go to to Nth next misspelled word."
  (interactive "p" jinx-mode)
  (unless (= n 0)
    (if (minibufferp)
        (throw 'jinx--goto n)
      (let ((ov (jinx--force-overlays (point-min) (point-max))))
        (unless (or (> n 0) (<= (overlay-start (car ov)) (point) (overlay-end (car ov))))
          (cl-incf n))
        (goto-char (overlay-end (nth (mod n (length ov)) ov)))
        (jinx--invisible-open-permanently)))))

(defun jinx-previous (n)
  "Go to to Nth previous misspelled word."
  (interactive "p" jinx-mode)
  (jinx-next (- n)))

;;;###autoload
(define-minor-mode jinx-mode
  "Enchanted Spell Checker."
  :lighter (" " (:eval (concat "Jinx[" jinx-languages "]")))
  :group 'jinx
  :keymap jinx-mode-map
  (cond
   ((buffer-base-buffer) ;; Do not enable in indirect buffers
    (when jinx-mode
      (jinx-mode -1)))
   (jinx-mode
    (jinx--load-module)
    (cl-letf* ((enable-local-variables :safe)
               (enable-local-eval nil)
               ;; Fix reentrancy problem (gh:minad/jinx#158)
               ((symbol-function #'jinx-mode) #'ignore))
      (hack-local-variables 'ignore-mode))
    (jinx--get-org-language)
    (setq jinx--exclude-regexp
          (when-let ((regexps (jinx--mode-list jinx-exclude-regexps)))
            (mapconcat (lambda (r) (format "\\(?:%s\\)" r))
                       regexps "\\|"))
          jinx--include-faces (jinx--mode-list jinx-include-faces)
          jinx--exclude-faces (jinx--mode-list jinx-exclude-faces)
          jinx--camel (or (eq jinx-camel-modes t)
                          (seq-some #'derived-mode-p jinx-camel-modes))
          jinx--session-words (nconc (split-string jinx-dir-local-words)
                                     (split-string jinx-local-words)))
    (jinx--load-dicts)
    (dolist (hook jinx--reschedule-hooks)
      (add-hook hook #'jinx--reschedule nil t))
    (jit-lock-register #'jinx--mark-pending))
   (t
    (mapc #'kill-local-variable '(jinx--exclude-regexp jinx--include-faces
                                  jinx--exclude-faces jinx--camel
                                  jinx--dicts jinx--syntax-table
                                  jinx--session-words))
    (dolist (hook jinx--reschedule-hooks)
      (remove-hook hook #'jinx--reschedule t))
    (jit-lock-unregister #'jinx--mark-pending)
    (jinx--cleanup))))

;; TODO use `:predicate' on Emacs 29
(defcustom global-jinx-modes '(text-mode prog-mode conf-mode)
  "List of modes where Jinx should be enabled.
The variable can either be t, nil or a list of t, nil, mode
symbols or elements of the form (not modes)."
  :type '(repeat sexp))

;;;###autoload
(define-globalized-minor-mode global-jinx-mode
  jinx-mode jinx--on
  :group 'jinx)

(defun jinx--on ()
  "Turn `jinx-mode' on."
  (when (and (not (or noninteractive
                      buffer-read-only
                      (buffer-base-buffer) ;; Do not enable in indirect buffers
                      (eq (aref (buffer-name) 0) ?\s)))
             ;; TODO use `:predicate' on Emacs 29
             (or (eq t global-jinx-modes)
                 (eq t (cl-loop for p in global-jinx-modes thereis
                                (pcase-exhaustive p
                                  ('t t)
                                  ('nil 0)
                                  ((pred symbolp) (and (derived-mode-p p) t))
                                  (`(not . ,m) (and (seq-some #'derived-mode-p m) 0)))))))
    (jinx-mode 1)))

(provide 'jinx)
;;; jinx.el ends here
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!263 blocks
openSUSE Build Service is sponsored by