[
  {
    "path": ".gitignore",
    "content": "scripts/__pycache__/\nlua/zotcite/types\ndoc/tags\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Zotcite\n\n> [!Note]\n> Users of Vim and Neovim < 0.10.4 have to switch to the \"vim\" branch.\n\n> [!Note]\n> Users of Neovim < 0.11.5 have to switch to the \"pynvim\" branch.\n\n> [!Note]\n> Users of Zotero < 8 have to switch to zotcite 0.7 (tag v0.7) if using Better\n> BibTeX citation keys.\n\n> [!Note]\n> Zotcite now uses conventional citation keys based on a citation template\n> and no longer requires the `zotref` filter. Alternatively, it can use Better\n> BibTeX citation keys. There is also an option to use the internal Zotero\n> item keys and insert the \"Author-Year\" part of the citation key as virtual\n> text. If you have documents using the old system, and don't want to manually\n> convert then, you can use the \"pynvim\" branch.\n\n_Zotcite_ is a Neovim plugin that provides integration with Zotero for\nMarkdown, Quarto, Rmd, vimwiki, Typst, LaTeX, and Rnoweb file types. With\n_zotcite_ you can:\n\n  - Do auto-completion of citation keys from Zotero database in\n    Markdown, RMarkdown, Quarto, LaTeX, Rnoweb, and Typst documents.\n\n  - Quickly see on the status bar information on the reference under the cursor.\n\n  - Open the PDF attachment of the reference associated with the citation key\n    under the cursor.\n\n  - Extract notes and highlighted text from PDF attachments of\n    references.\n\n  - Extract Zotero notes and annotations from Zotero database.\n\n\n## Installation\n\n**Dependencies**\n\n- Required:\n\n  - Zotero >= 5 if not using Better-BibTeX. For Better-BibTeX users, Zotero >=\n    8 is required.\n\n  - The `sqlite3` command line application.\n\n  - [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter) as\n    well as the tree-sitter parser for `yaml`.\n\n- Optional:\n\n  - [telescope.nvim](https://github.com/nvim-telescope/telescope.nvim) for an\n    alternative way of inserting citation keys.\n\n  - Python 3 is required if you are going to convert OpenDocument texts (`odt`)\n    to markdown or extract annotations inserted in a PDF document by a PDF\n    viewer other than Zotero. Please, see the Zotcite documentation for details.\n\nZotcite can be installed as any Neovim plugin. Below is an example of how to\ninstall `zotcite` with [lazy.nvim](https://github.com/folke/lazy.nvim):\n\n```lua\n    {\n        \"jalvesaq/zotcite\",\n        dependencies = {\n            \"nvim-treesitter/nvim-treesitter\",\n            \"nvim-telescope/telescope.nvim\",\n        },\n        config = function ()\n            require(\"zotcite\").setup({\n                -- your options here (see doc/zotcite.txt)\n            })\n        end\n    },\n```\n\n> [!Note]\n> You don't need to lazy load zotcite because it is a filetype plugin. This\n> means that it already lazy loads its modules, which will be enabled only for\n> the supported file types.\n\n## Usage\n\nPlease, read the plugin's\n[documentation](https://raw.githubusercontent.com/jalvesaq/zotcite/master/doc/zotcite.txt)\nfor further instructions.\n\n## Screenshots\n\n[See the Wiki](https://github.com/jalvesaq/zotcite/wiki/Screenshots)\n\n## See also:\n\nZotcite's original Python code was based on the\n[citation.vim](https://github.com/rafaqz/citation.vim) project.\n\nSimilar project: [telescope-zotero.nvim](https://github.com/jmbuhr/telescope-zotero.nvim)\n"
  },
  {
    "path": "doc/zotcite.txt",
    "content": "*zotcite.txt*                                          Integration with Zotero\n\n\n 1. Overview                                                |zotcite_overview|\n 2. Usage                                                      |zotcite_usage|\n    2.1. Commands                                           |zotcite_commands|\n    2.2. Mappings                                           |zotcite_mappings|\n    2.3. Compiling documents                          |zotcite_compiling_docs|\n 3. Customization                                      |zotcite_customization|\n    3.1. Paths                                                 |zotcite_paths|\n    3.2. Change default maps                         |zotcite_change_mappings|\n    3.3. Zotcite engine                                       |zotcite_engine|\n    3.4. Syntax highlighting                            |zotcite_highlighting|\n    3.5. File types                                        |zotcite_filetypes|\n    3.6. Open attachment                              |zotcite_open_in_zotero|\n    3.7. Show errors of command to open attachment   |zotcite_wait_attachment|\n 4. Troubleshooting                                  |zotcite_troubleshooting|\n\n\n==============================================================================\n1. Overview                                                 *zotcite_overview*\n\n\nZotcite is a Vim plugin that provides integration with Zotero. Please, see a\ndescription of its features, including screenshots at:\n\n    https://github.com/jalvesaq/zotcite\n\n\n==============================================================================\n2. Usage                                                       *zotcite_usage*\n\n------------------------------------------------------------------------------\n2.1. Commands                                               *zotcite_commands*\n\nYou can use the command `:Zseek` to see what references have either a last\nauthor's name or title matching the pattern that you are seeking for. Example:\n>vim\n :Zseek marx\n\nOnly the first word is used as the search pattern. Thus, the following command\nwould give the same result as the above one:\n>vim\n :Zseek marx anything\n\nThe Telescope picker is filled with references that include the searched\npattern as a substring in the author's names or the work's title, but\nTelescope allows you to further fuzzy filter the results. If you want the\nTelescope picker filled with Zotero's entire database, run `:Zeek` without\narguments. The same Telescope dialogue is also used by `:Zannotations`,\n`:Zselectannotations`, `:Znote`, and `:Zpdfnote` (see below).\n\nZotcite can extract and insert into the markdown document (1) annotations that\nyou have made using Zotero's built-in PDF viewer, (2) notes that you have\nattached to a Zotero entry, and (3) annotations inserted in a PDF by an\nexternal PDF viewer.\n\nTo extract annotations made with Zotero's built-in PDF viewer, use the Vim\ncommand `:Zannotations key`. If the PDF has page labels, Zotero will register\nthem as the page numbers; otherwise, Zotero will consider the first page of\nthe PDF as page 1 which in most cases will be wrong. You can fix this by\npassing an integer number as a second argument to `:Zannotations`. For\nexample, if page 1 of a book is page 11 of its PDF, you will get the correct\npage numbers if you do:\n>vim\n :Zannotations key -10\n\nBy default, the colon separating the year from the page is replaced by \", p.\n\". If you want to use the colon or any other string as the separator, set the\nvalue of `year_page_sep` in your `config`. Example:\n>lua\n year_page_sep = ':'\n\nIf you want to extract annotations made with Zotero's built-in PDF viewer but\nwould prefer to make a selection of the annotations to be imported then use\nthe vim command `:Zselectannotations key`. After choosing the reference, a\nsecond dialogue will appear with the annotations and notes (if you have made\nnotes). You can scroll through the annotations list and press `enter` on the\nannotations you'd wish to import. Once finished making the selection you need\nto press `Esc` to escape the annotation selection dialogue.\n>vim\nTo extract notes from Zotero, use the Vim command `:Znote key`\n\nSimilarly, to extract annotations (notes and highlighted texts) that were\ninserted into a PDF document by an external PDF viewer, use the Vim command\n`:Zpdfnote`. The page numbers of the annotations might be wrong, so always\ncheck them after the extraction. You have also to manually add italics and\nother rich text formatting and put back hyphens incorrectly removed from the\nend of the PDF lines.\n\nTo insert citation keys, you can press <C-X><C-B> in Insert mode. The sequence\nof letters before the cursor will be used to filter the references (see\n`:Zseek` above).\n\n\n------------------------------------------------------------------------------\n2.2. Mappings                                               *zotcite_mappings*\n\nIn Insert mode, type the `@` letter and one or more letters of either the last\nname of the first author or the reference title. The matching of citation keys\nis case-insensitive.\n\nIn Vim's Insert mode, <c-x><c-b> inserts citation keys (requires Telescope).\n\nIn Vim's Normal mode, put the cursor over a citation key and press:\n\n  - <Leader>zo to open the reference's attachment as registered in Zotero's\n    database.\n\n  - <Leader>zi to see in the status bar the last name of all authors, the\n    year, and the title of the reference.\n\n  - <Leader>za to see all fields of a reference as stored by Zotcite.\n\n  - <leader>zb to insert the abstract (if available) into the current buffer.\n\n  - <Leader>zv to view the (pdf or html) document generated from the current\n    (Markdown, Rmd, or Quarto) document.\n\n\n------------------------------------------------------------------------------\n2.3. Compiling documents                              *zotcite_compiling_docs*\n\nNote: Make backup of your bib files because they will be overwritten by\nzotcite.\n\nzotcite will automatically save the bib file indicated in the YAML header when\nsaving the document. The citation key will have the format `@ABCDEFGH`, and\nthe `Author-Year` complement will be inserted as a virtual text.\n\nIf you have an old markdown document with citations including the no longer\nused `-Author-Year` real text, the Vim command below will delete the\n`-Author-Year` complements (with no automatic way of getting them back):\n>vim\n :%s/@\\([A-Z0-9]\\{8}\\)[-#][-:+_[:digit:][:lower:][:upper:]\\u00FF-\\uFFFF]\\+/@\\1/g\n<\nNote: make a backup of you Markdown document before running the command to\nbe able to revert the changes if anything goes wrong.\n\n\nConvert from ODT ~\n\nIf you have an OpenDocument Text with citations inserted by the Zotero\nextension and want to convert it to Markdown, you can use the `odt2md.py`\napplication from the `scripts` directory to help you convert the document.\nExample:\n>sh\n /path/to/zotcite/scripts/odt2md.py Document.odt\n\nWithin Neovim, you can run the command `:Zodt2md` to convert the ODT document\nand see the resulting Markdown document in a new tab:\n>vim\n :Zodt2md Document.odt\n\nNote that the conversion is not perfect because the visible text from the\ncitation fields is not deleted. You have to delete them manually, keeping what\nis needed, such as the page numbers that you have added manually. It is not\npossible to automate this step because LibreOffice allows the manual edition\nof the citation fields.\n\n\n\n==============================================================================\n3. Customization                                       *zotcite_customization*\n\n------------------------------------------------------------------------------\n3.1. Paths                                                     |zotcite_paths|\n\n\t\t\t\t\t\t\t  *zotero_sqlite_path*\nIf Zotcite cannot find the path to Zotero's database (`zotero.sqlite`), put\nthe correct path in your `config`. Example:\n>lua\n zotero_sqlite_path = '~/.zotero/zotero.sqlite'\n<\n\t\t\t\t\t\t\t\t      *tmpdir*\nIf Zotcite is trying to use a non-writable directory as its temporary and\ncache directory, set the value of `tmpdir`. Example:\n>lua\n tmpdir = '/dev/shm/zotcite-user_name'\n<\n\t\t\t\t\t\t\t   *tex_fallback_root*\nWhen editing LaTeX or Rnoweb documents, Zotcite first tries to find\n`\\addbibresource{...}` in the current buffer, then in the file pointed by\n`% !TeX root = ...`. If both checks fail, Zotcite looks for a fallback root\nfile at `bufdir .. \"/\" .. tex_fallback_root`.\nThe default is `\"../main.tex\"`. Example:\n>lua\n tex_fallback_root = \"../main.tex\"\n<\nZotcite adds its `scripts` directory to the environment variable `PATH`. If\nit's not correctly finding the directory, you can set it manually:\n>lua\n python_scripts_path = \"/path/to/zotcite/scripts\"\n<\n\t\t\t\t\t\t\t *zotcite_python_path*\nZotcite runs \"python3\" when extracting notes from PDF documents annotated by\nPDF viewers other than Zotero (`:Zpdfnote`) and when converting ODT to\nMarkdown (`:Zodt2md`). If \"python3\" is not in your path or if you are running\nPython from a virtual environment, you should set the correct path in your\nzotcite config. Example:\n>lua\n python_path = \"/home/user_name/.py3env/bin/python3\"\n<\n\n------------------------------------------------------------------------------\n3.2. Change default maps                             *zotcite_change_mappings*\n\nBelow are examples of how to change the available key bindings:\n>lua\n -- Insert citation key:\n vim.keymap.set(\"i\", \"<c-b>\", \"<Plug>ZCite\")\n\n -- Open reference attachment:\n vim.keymap.set(\"n\", \"<c-]>\", \"<Plug>ZOpenAttachment\")\n\n -- See basic information on the reference of a citation key:\n vim.keymap.set(\"n\", \"<Leader>I\", \"<Plug>ZCitationInfo\")\n\n -- See how the reference of a citation key is stored by Zotcite:\n vim.keymap.set(\"n\", \"<Leader>C\", \"<Plug>ZCitationCompleteInfo\")\n\n -- Extract the abstract into the current buffer from the citation under cursor:\n vim.keymap.set(\"n\", \"<Leader>A\", \"<Plug>ZExtractAbstract\")\n\n -- View the (pdf or html) document generated from the\n -- current (Markdown, Rmd, or Quarto) document:\n vim.keymap.set(\"n\", \"<Leader>V\", \"<Plug>ZViewDocument\")\n<\n\n------------------------------------------------------------------------------\n3.3. Zotcite engine                                           *zotcite_engine*\n\t\t\t\t\t\t\t    *zotcite_key_type*\nYou can use three different types of citation keys with Zotcite:\n\n  - Zotero keys.\n  - Keys based on the citation template.\n  - Better BibTeX citation keys (\"Citation Key\" field).\n\nZotero keys are sequences of random upper case letters and numbers with\nlength eight, such as `A1B2C3D4` or `ABCD1234`. These keys are generated by\nZotero.\n\nKeys based on the citation template are generated by zotcite according to the\n`citation_template` option explained below. Duplicates are fixed by appending\nalphabetic letters `a`, `b`, `c`, and so on. The letter that is appended\nfollows the chronological order of addition of references to Zotero's\ndatabase. This type of citation key is similar to what you get from Better\nBibTex.\n\nThe Better BibTeX citation keys are generated by Zotero's extension Better\nBibTex.\n\nAdvantages of each type:\n\n  - Zotero key: It is guaranteed to be unique. You will never get a duplicate.\n    But they are meaningless for humans because it is not based on an author\n    name, reference title, or year of publication. As a workaround, zotcite\n    conceals the Zotero key and inserts a virtual text based on the citation\n    template. The problem is that the cursor movement becomes strange as it\n    jumps over the virtual text.\n\n  - Key based on the citation template: You see the real text of the citation\n    key, and you see the cursor moving as usual. The problem is that if you\n    delete from Zotero's database a reference that was resulting in duplicate\n    citation key, the letters appended to the remaining references will change\n    unless the deleted reference was the last one added.\n\n  - Better BibTeX citation key: Same advantages and disadvantages of citation\n    keys based on a template.\n\nWhat is the best for you:\n\n  - If you are writing a book or paper alone (or if everyone is using Neovim\n    and zotcite) and the strange cursor movements isn't annoying to you,\n    then, the Zotero key is the best option.\n\n  - If you are writing alone (or if everyone is using Neovim and zotcite), but\n    you want normal cursor movements, and don't want to install Better BibTex,\n    then, a citation key based on the citation template is the best option.\n\n  - If you are writing with other people who use Better BibTeX, than, of\n    course, you have no choice but to use Better BibTeX keys too.\n\nThe type of citation key is defined with the option `key_type`. Valid values\nare \"template\" (the default), \"better-bibtex\", and \"zotero\". Example:\n>lua\n key_type = \"zotero\",\n<\nYou can also set a different value for each document. For a Markdown,\nRMarkdown or Quarto document, add the key `zotcite-key-type` to the YAML\nheader. Example:\n>yaml\n zotcite-key-type: better-bibtex\n<\nFor LaTeX, Rnoweb, or Tpyst, it should be within a commented line with the\ncomment string at the beginning of the line. Example for LaTeX:\n>tex\n % zotcite-key-type = zotero\n<\nand for Typst:\n>typst\n // zotcite-key-type = template\n<\n\t\t\t\t\t\t\t   *citation_template*\nWhen the `key_type` is \"zotero\", zotcite complements the citation key with a\nvirtual text in the format `Author_Year`. The citation key is the key\nattributed by Zotero to the references stored in its database, `Author` is the\nlast name of the first author, and `Year` is the full year (four digits). You\ncan define whether it will include or not the first author's last name (in\neither lower case `{author}` or title case `{Author}`), the last names of the\nfirst three authors (either `{authors}` or `{Authors}`), the first word of the\nwork title (in lower case `{title}` or as registered in Zotero `{Title}`),\nand the year (with either four digits `{Year}` or only two `{year}`). Example:\n>lua\n citation_template = '{Author}-{year}'\n<\nWhen Zotero's SQLite3 database is updated, zotcite copies it to its temporary\ndirectory. While copying, the slowest operation is writing the copy of the\nfile to disk. If you have enough RAM, you may want to set `tmpdir` as a\ndirectory in a file system mounted in virtual memory, as in the second example\nabove.\n\t\t\t\t\t\t\t      *exclude_fields*\nIf you want to exclude some of Zotero's fields from the bib file\ngenerated by Zotcite, set the value of `exclude_fields` to a white-separated\nlist of fields to be excluded. For example, if you want to exclude the fields\n\"Extra\" (which appears as `note` in the bib file) and \"file\" field, put\nthis in your `config`:\n>lua\n exclude_fields = \"note file\"\n<\n\t\t\t\t\t\t\t\t    *sort_key*\nBy default, zotcite uses the field \"dateModified\" to sort the results\ndisplayed by `:Zseek`. You can use a different field, such as \"date\", \"title\",\n\"alastnm\" or other fields whose values are strings or numbers (do\n`<Leader>za` over some citation keys to see the available fields):\n>lua\n sort_key = \"date\"\n<\n\t\t\t\t\t\t\t   *Zotero_collection*\nIf you want to restrict the search for references to specific collections\nwhile completing citation keys, set the value `collection` in the YAML header\nof the Markdown document, as in the examples:\n>\n ---\n collection: ['New Paper']\n ---\n\n ---\n collection: ['PhD Thesis', 'New Paper']\n ---\n\n\nThe Python script `pdfnote.py` imports the modules `PyQt5` and `popplerqt5`.\nOn Debian systems they can be installed with the command:\n>sh\n sudo apt install python3-pyqt5 python3-poppler-qt5\n<\nIn any system, if using `pip`:\n>sh\n pip install poppler-qt5\n pip install python-poppler-qt5\n<\nIf you have trouble install `poppler-qt5` or `python-poppler-qt5` you can add\nto your zotcite config:\n>lua\n pdf_extractor = \"pdfnotes2.py\",\n<\nThe Python script `pdfnotes2.py` requires the `pymupdf` module, which can be\ninstalled on Debian:\n>sh\n sudo apt install python3-pymupdf\n<\nor with `pip`:\n>sh\n pip install pymupdf\n<\n\n------------------------------------------------------------------------------\n3.4. Syntax Highlighting                                *zotcite_highlighting*\n\nSyntax highlighting customization is done with Vim variables.\n\n\t\t\t\t\t\t\t\t  *hl_cite_key*\nIf you want to disable Zotcite's syntax highlighting of citation keys, put in\nyour `config`:\n>lua\n hl_cite_key = false\n<\n\t\t\t\t\t\t\t*zotcite_conceallevel*\nZotcite will set the 'conceallevel' of the document if you set the value\n`conceallevel` in its config:\n>lua\n conceallevel = 0\n\nif `conceallevel` is a negative integer (the default), zotcite will do nothing.\n\n\n------------------------------------------------------------------------------\n3.5. File types                                            *zotcite_filetypes*\n\nZotcite is a filetype plugin and is enabled only if the file type is\n`markdown`, `pandoc`, `rmd`, `quarto`, `vimwiki`, `latex` or `rnoweb`. If you\nwant to disable it for some of these file types, you should set the value of\n`filetypes` in your `config`. Example:\n>lua\n filetypes = { 'markdown', 'pandoc', 'rmd', 'vimwiki' }\n\n\n------------------------------------------------------------------------------\n3.6. Open attachment                                  *zotcite_open_in_zotero*\n\nZotcite calls `vim.ui.open()` to open attachments. But you can change the\ncommand in your config:\n>lua\n open_cmd = \"my_open_script\"\n\nIf you want <Plug>ZOpenAttachment to open PDF attachments in Zotero (as\nopposed to your system's default PDF viewer), put the following in your\n`config`:\n>lua\n open_in_zotero = true\n\nNote that you'll need to have Zotero configured as the default app for\nopening `zotero://` links. On Linux, assuming your Zotero installation\nincluded a `zotero.desktop` file, you can do the following:\n>sh\n xdg-mime default zotero.desktop x-scheme-handler/zotero\n\n\n------------------------------------------------------------------------------\n3.7. Show errors of command to open attachment        *zotcite_wait_attachment*\n\nWhile opening an attachment, zotcite cannot catch errors because it doesn't\nwait for the application to finish. If zotcite fails to open a PDF attachment,\nyou may want to temporarily set `wait_attachment` as `true` in your `config`:\n>lua\n wait_attachment = true\n\nThen, Neovim should freeze until the attachment is closed, and, if the PDF\nviewer finishes with non-zero status, anything output to the `stderr` will be\ndisplayed as a warning message.\n\n\n==============================================================================\n4. Troubleshooting                                   *zotcite_troubleshooting*\n\n\t\t\t\t\t\t\t\t      *:Zinfo*\nIf either the plugin does not work or you want easy access to the values of\nsome internal variables, do the following command:\n>vim\n :Zinfo\n\nNote that, unless you are editing Quarto documents, Zotcite will not enable\nomni completion if any of the buffer's lines matches the regular pattern\n`^bibliography:.*\\.bib` when the markdown file is read.\n\n\t\t\t vim:tw=78:ts=8:ft=help:norl\n"
  },
  {
    "path": "ftplugin/bib_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "ftplugin/markdown_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "ftplugin/pandoc_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "ftplugin/quarto_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "ftplugin/rmd_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "ftplugin/rnoweb_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "ftplugin/tex_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "ftplugin/typst_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "ftplugin/vimwiki_zotcite.lua",
    "content": "require(\"zotcite.config\").init()\n"
  },
  {
    "path": "lua/zotcite/bib.lua",
    "content": "local zwarn = require(\"zotcite\").zwarn\n\nlocal M = {}\n\nlocal extract_addbibresource = function(lines)\n    for _, v in pairs(lines) do\n        if v:find(\"\\\\addbibresource%{\") then\n            local bib = v:gsub(\"\\\\addbibresource%{\", \"\")\n            bib = bib:gsub(\"}.*\", \"\")\n            return bib\n        end\n    end\n    return nil\nend\n\nlocal read_lines = function(path)\n    if not path or vim.fn.filereadable(path) == 0 then return nil end\n    return vim.fn.readfile(path)\nend\n\nlocal find_root_file = function(lines)\n    for _, v in pairs(lines) do\n        local root = v:match(\"^%s*%%+%s*!%s*[Tt][Ee][Xx]%s+root%s*=%s*(.-)%s*$\")\n        if root and root ~= \"\" then return root end\n    end\n    return nil\nend\n\nlocal resolve_path = function(base_dir, path)\n    if not path or path == \"\" then return path end\n    if path:match(\"^/\") or path:match(\"^%a:[/\\\\]\") then return path end\n    return vim.fn.fnamemodify(base_dir .. \"/\" .. path, \":p\")\nend\n\nlocal find_tex_bib = function()\n    local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)\n    local bufpath = vim.api.nvim_buf_get_name(0)\n    local bufdir = vim.fn.fnamemodify(bufpath, \":p:h\")\n\n    local bib = extract_addbibresource(lines)\n    if bib then return resolve_path(bufdir, bib) end\n\n    local root = find_root_file(lines)\n    if root then\n        local rootpath = resolve_path(bufdir, root)\n        local rootlines = read_lines(rootpath)\n        if not rootlines then\n            zwarn(\"Failed to read TeX root: '\" .. rootpath .. \"'\")\n            return nil\n        end\n        bib = extract_addbibresource(rootlines)\n        if not bib then\n            zwarn(\n                \"Could not find the '\\\\addbibresource' command in TeX root '\"\n                    .. rootpath\n                    .. \"'\"\n            )\n        end\n        local rootdir = vim.fn.fnamemodify(rootpath, \":p:h\")\n        return resolve_path(rootdir, bib)\n    end\n\n    local tfr = require(\"zotcite.config\").get_config().tex_fallback_root\n    local fallback_root = vim.fn.fnamemodify(bufdir .. \"/\" .. tfr, \":p\")\n    local fallback_lines = read_lines(fallback_root)\n    bib = fallback_lines and extract_addbibresource(fallback_lines) or nil\n    if bib then\n        local rootdir = vim.fn.fnamemodify(fallback_root, \":p:h\")\n        return resolve_path(rootdir, bib)\n    end\n    zwarn(\"Could not find the '\\\\addbibresource' command.\")\n    return nil\nend\n\nlocal find_typst_bib = function()\n    local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)\n    for _, v in pairs(lines) do\n        if v and v:find(\"#bibliography%(\") then\n            return v:match('#bibliography%(%s*\"(%S-)\".*')\n        end\n    end\n    zwarn(\"Could not find the `#bibliography` identifier.\")\n    return nil\nend\n\nlocal find_markdown_bib = function()\n    local ybib = require(\"zotcite.get\").yaml_field(\"bibliography\", 0)\n    if not ybib then\n        zwarn(\"Could not find 'bibliography' field in YAML header.\")\n        return nil\n    end\n\n    if type(ybib) == \"string\" then return ybib end\n\n    local bib = nil\n    if type(ybib) == \"table\" then\n        for _, v in pairs(ybib) do\n            if type(v) == \"string\" then\n                bib = v\n                if v:find(\"zotcite.bib\") then break end\n            else\n                zwarn('Invalid \"bibliography\" field: ' .. vim.inspect(bib))\n                return\n            end\n        end\n    end\n    return bib\nend\n\nlocal find_bib_fn = function()\n    if vim.bo.filetype == \"typst\" then return find_typst_bib() end\n    if vim.bo.filetype == \"tex\" or vim.bo.filetype == \"rnoweb\" then\n        return find_tex_bib()\n    end\n    return find_markdown_bib()\nend\n\nlocal get_typ_citations = function(kz)\n    local kp = kz and \"<[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]>\"\n        or \"<[%w%-\\192-\\244\\128-\\191]+>\"\n    local ckeys = {}\n    local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)\n    for _, v in pairs(lines) do\n        local i = 1\n        while true do\n            local s, e = v:find(kp, i)\n            if not s or not e then break end\n            table.insert(ckeys, v:sub(s + 1, e - 1))\n            i = e + 1\n        end\n    end\n    return ckeys\nend\n\nlocal get_md_citations = function(kz)\n    local kp = kz and \"@[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]\"\n        or \"@[%w%-\\192-\\244\\128-\\191]+\"\n    local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)\n    local ckeys = {}\n    for _, v in pairs(lines) do\n        local i = 1\n        while true do\n            local s, e = v:find(kp, i)\n            if not s or not e then break end\n            table.insert(ckeys, v:sub(s + 1, e))\n            i = e + 1\n        end\n    end\n    return ckeys\nend\n\nlocal get_tex_citations = function(kz)\n    local kp1 = \"\\\\%w*cit.*{\"\n    local kp2 = kz and \"[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]\"\n        or \"[%w%-\\192-\\244\\128-\\191]+\"\n    local ckeys = {}\n    local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)\n    for _, v in pairs(lines) do\n        local i = 1\n        while true do\n            local s, e = v:find(kp1, i)\n            if not s or not e then break end\n            local j = e\n            while true do\n                local s2, e2 = v:find(kp2, j)\n                if not s2 or not e2 then break end\n                table.insert(ckeys, v:sub(s2, e2))\n                j = e2 + 1\n            end\n            i = e + 1\n        end\n    end\n    return ckeys\nend\n\nM.update = function()\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local kz = kt == \"zotero\"\n    local ckeys\n    if vim.o.filetype == \"tex\" or vim.o.filetype == \"rnoweb\" then\n        ckeys = get_tex_citations(kz)\n    else\n        ckeys = get_md_citations(kz)\n    end\n    if vim.o.filetype == \"typst\" then\n        local ck2 = get_typ_citations(kz)\n        for _, v in pairs(ck2) do\n            table.insert(ckeys, v)\n        end\n    end\n    if #ckeys == 0 then return end\n\n    local bib = find_bib_fn()\n    if not bib then return end\n\n    require(\"zotcite.zotero\").update_bib(ckeys, bib, kt, false)\n    vim.schedule(require(\"zotcite.hl\").citations)\nend\n\nreturn M\n"
  },
  {
    "path": "lua/zotcite/config.lua",
    "content": "---@class ZotciteUserOpts\n---Whether to syntax highlight citation keys\n---@field hl_cite_key? boolean\n---Reference field to as sorting key by :Zseek\n---@field sort_key? string\n---Value to set the Vim option 'conceallevel'\n---@field conceallevel? -1 | 0 | 1 | 2 | 3\n---Freeze Neovim after opening a PDF attachment\n---@field wait_attachment? boolean\n---Open PDF attachments in Zotero\n---@field open_in_zotero? boolean\n---Space separated list of file types\n---for which Zotcite is enabled\n---@field filetypes? string[]\n---Absolute path to `python3` executable\n---@field python_path? string\n---Application to extract notes from PDF documents\n---@field pdf_extractor? '\"pdfnotes.py\"' | '\"pdfnotes2.py\"'\n---Template for citation keys\n---@field citation_template? string\n---Type of citation key (internal Zotero key or template based)\n---@field key_type? '\"template\"' | '\"better-bibtex\"' | '\"zotero\"'\n---Path to `zotero.sqlite`\n---@field zotero_sqlite_path? string\n---Path to attachments directory (if any)\n---@field attach_dir? string\n---Temporary directory\n---@field tmpdir? string\n---Directory of zotcite's Python scripts\n---@field python_scripts_path? string\n---Zotero encoding (by default, \"utf-8\" on Linux\n---and \"latin1\" on Windows)\n---@field zotero_encoding? string\n---Fields to be excluded from Zotero references\n---@field exclude_fields? string\n---String used to separate the year from the\n---page in references (by default, \", p. \")\n---@field year_page_sep? string\n---@field open_cmd? string Command to open attachments\n---Space separated list of title words to be\n---excluded from citation keys\n---@field banned_words? string\n---Relative path from buffer directory to a fallback TeX root file\n---used when no `% !TeX root = ...` is found\n---@field tex_fallback_root? string\n\n---@type ZotciteUserOpts\nlocal config = {\n    key_type = \"template\",\n    hl_cite_key = true,\n    sort_key = \"dateModified\",\n    conceallevel = -1,\n    wait_attachment = false,\n    open_in_zotero = false,\n    filetypes = {\n        \"tex\",\n        \"markdown\",\n        \"pandoc\",\n        \"quarto\",\n        \"rmd\",\n        \"rnoweb\",\n        \"typst\",\n        \"vimwiki\",\n    },\n    python_path = \"python3\",\n    pdf_extractor = \"pdfnotes.py\",\n    tex_fallback_root = \"../main.tex\",\n}\n\nlocal did_global_init = false\nlocal first_buf\nlocal key_type = {}\n\nlocal zwarn = require(\"zotcite\").zwarn\n\nlocal M = {}\n\nlocal b = {}\n\nM.info = {}\n\nM.show = function()\n    local info = {}\n    for k, v in pairs(config) do\n        table.insert(info, { k, \"Identifier\" })\n        table.insert(info, { \" = \", \"Operator\" })\n        table.insert(info, { vim.inspect(v) .. \"\\n\" })\n    end\n    vim.schedule(function() vim.api.nvim_echo(info, false, {}) end)\nend\n\nlocal set_buffer_key_type = function()\n    local bn = vim.api.nvim_get_current_buf()\n    if vim.tbl_contains({ \"tex\", \"rnoweb\", \"typst\" }, vim.bo.filetype) then\n        local ptrn = vim.bo.filetype == \"typst\" and \"^%s*//\" or \"^%s*%%\"\n        ptrn = ptrn .. \"%s*zotcite%-key%-type%s*=%s*\"\n        local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)\n        for _, v in pairs(lines) do\n            if v:find(ptrn) then\n                local kt = v:match(\".*zotcite%-key%-type%s*=%s*(%S*)\")\n                if vim.tbl_contains({ \"zotero\", \"template\", \"better-bibtex\" }, kt) then\n                    key_type[bn] = kt\n                    return\n                end\n            end\n        end\n    else\n        local kt = require(\"zotcite.get\").yaml_field(\"zotcite-key-type\", bn)\n        if kt and type(kt) == \"string\" then\n            if vim.tbl_contains({ \"zotero\", \"template\", \"better-bibtex\" }, kt) then\n                key_type[bn] = kt\n                return\n            end\n        end\n    end\n    key_type[bn] = config.key_type\nend\n\nM.get_key_type = function(bufnr) return key_type[bufnr] end\n\nlocal update_config = function()\n    local zotcite = require(\"zotcite\")\n    if zotcite.user_opts then\n        for k, v in pairs(zotcite.user_opts) do\n            config[k] = v\n        end\n    end\nend\n\nM.has_buffer = function(bufnr)\n    for _, v in pairs(b) do\n        if v.bufnr == bufnr then return v end\n    end\n    return nil\nend\n\nM.get_b = function() return b end\n\nlocal set_path = function()\n    if not config.python_scripts_path then\n        config.python_scripts_path = debug.getinfo(1, \"S\").source:match(\"^@(.*)/lua.*\")\n            .. \"/scripts\"\n    end\n    if vim.fn.has(\"win32\") == 1 then\n        local zpath = config.python_scripts_path:gsub(\"/\", \"\\\\\")\n        if not vim.env.PATH:find(zpath) then\n            vim.env.PATH = zpath .. \";\" .. vim.env.PATH\n        end\n    else\n        if not vim.env.PATH:find(config.python_scripts_path) then\n            vim.env.PATH = config.python_scripts_path .. \":\" .. vim.env.PATH\n        end\n    end\nend\n\nlocal global_init = function()\n    if vim.fn.executable(\"sqlite3\") == 0 then\n        zwarn(\"`sqlite3` executable not found. Please, install it.\", true)\n        return false\n    end\n    -- Get Zotero data\n    local t1 = vim.uv.hrtime()\n    require(\"zotcite.zotero\").init()\n    local t2 = vim.uv.hrtime()\n    M.info[\"Zotero init time (ms)\"] = math.floor(0.5 + (t2 - t1) / 1000000)\n    local info = require(\"zotcite.zotero\").info()\n    if not info then\n        zwarn(\"Failed to get information from Zotero\", true)\n        return false\n    end\n\n    require(\"zotcite.hl\").citations()\n    require(\"zotcite.lsp\").start()\n\n    set_path()\n    vim.env.RmdFile = vim.fn.expand(\"%:p\")\n\n    vim.api.nvim_create_user_command(\n        \"Zseek\",\n        function(tbl)\n            require(\"zotcite.seek\").refs(tbl.args, require(\"zotcite.seek\").print)\n        end,\n        { nargs = \"?\", desc = \"Zotcite: seek references\" }\n    )\n    vim.api.nvim_create_user_command(\n        \"Znote\",\n        function(tbl) require(\"zotcite.get\").note(tbl.args) end,\n        { nargs = \"?\", desc = \"Zotcite: insert Zotero notes\" }\n    )\n    vim.api.nvim_create_user_command(\n        \"Zannotations\",\n        function(tbl) require(\"zotcite.get\").annotations(tbl.args, false) end,\n        { nargs = \"?\", desc = \"Zotcite: insert Zotero annotations\" }\n    )\n    vim.api.nvim_create_user_command(\n        \"Zselectannotations\",\n        function(tbl) require(\"zotcite.get\").annotations(tbl.args, true) end,\n        { nargs = \"?\", desc = \"Zotcite: insert Zotero annotations\" }\n    )\n\n    vim.api.nvim_create_user_command(\n        \"Zpdfnote\",\n        function(tbl) require(\"zotcite.get\").PDFNote(tbl.args) end,\n        { nargs = \"?\", desc = \"Zotcite: insert PDF annotations\" }\n    )\n    vim.api.nvim_create_user_command(\n        \"Zodt2md\",\n        function(tbl) require(\"zotcite\").ODTtoMarkdown(tbl.args) end,\n        { nargs = 1, desc = \"Zotcite: convert ODT to Markdown\" }\n    )\n    vim.api.nvim_create_user_command(\"Zconfig\", require(\"zotcite.config\").show, {})\n    require(\"zotcite.get\").collection_name(first_buf)\n    return true\nend\n\nM.init = function()\n    -- Disable for LSP popup windows\n    if vim.o.buftype == \"nofile\" then return end\n\n    -- Do this only once\n    if did_global_init then\n        set_buffer_key_type()\n        require(\"zotcite.hl\").citations()\n        require(\"zotcite.lsp\").start()\n    else\n        update_config()\n        set_buffer_key_type()\n        did_global_init = true\n        if vim.v.vim_did_enter == 0 then\n            vim.api.nvim_create_autocmd(\"VimEnter\", {\n                callback = function() vim.schedule(global_init) end,\n            })\n        else\n            vim.schedule(global_init)\n        end\n    end\n\n    local bnr = vim.api.nvim_get_current_buf()\n    first_buf = bnr\n    if M.has_buffer(bnr) then return end\n\n    -- But repeat this for every buffer\n    if not vim.tbl_contains(config.filetypes, vim.bo[bnr].filetype) then return end\n\n    local create_map = function(m, p, s, c, d)\n        local opts = { silent = true, noremap = true, expr = false, desc = d }\n        if vim.fn.hasmapto(p, m) == 1 then\n            vim.api.nvim_buf_set_keymap(bnr, m, p, c, opts)\n        else\n            vim.api.nvim_buf_set_keymap(bnr, m, s, c, opts)\n        end\n    end\n\n    create_map(\n        \"i\",\n        \"<Plug>ZCite\",\n        \"<C-X><C-B>\",\n        \"<Cmd>lua require('zotcite.get').citation()<CR>\",\n        \"Zotcite: insert citation\"\n    )\n    create_map(\n        \"n\",\n        \"<Plug>ZOpenAttachment\",\n        \"<Leader>zo\",\n        \"<Cmd>lua require('zotcite.get').open_attachment()<CR>\",\n        \"Zotcite: open attachment\"\n    )\n    create_map(\n        \"n\",\n        \"<Plug>ZViewDocument\",\n        \"<Leader>zv\",\n        \"<Cmd>lua require('zotcite.utils').view_document()<CR>\",\n        \"Zotcite: view document\"\n    )\n    create_map(\n        \"n\",\n        \"<Plug>ZCitationInfo\",\n        \"<Leader>zi\",\n        \"<Cmd>lua require('zotcite.get').reference_data('ayt')<CR>\",\n        \"Zotcite: show reference info (short)\"\n    )\n    create_map(\n        \"n\",\n        \"<Plug>ZCitationCompleteInfo\",\n        \"<Leader>za\",\n        \"<Cmd>lua require('zotcite.get').reference_data('raw')<CR>\",\n        \"Zotcite: show reference info (complete)\"\n    )\n    create_map(\n        \"n\",\n        \"<Plug>ZExtractAbstract\",\n        \"<leader>zb\",\n        \"<Cmd>lua require('zotcite.get').abstract()<CR>\",\n        \"Zotcite: Paste abstract note in current buffer\"\n    )\n    if config.conceallevel >= 0 then vim.o.conceallevel = config.conceallevel end\n    vim.api.nvim_create_autocmd(\n        \"InsertLeave\",\n        { buffer = bnr, callback = require(\"zotcite.hl\").citations }\n    )\n    vim.api.nvim_create_autocmd(\n        \"BufWritePre\",\n        { buffer = bnr, callback = require(\"zotcite.bib\").update }\n    )\n    vim.api.nvim_create_autocmd(\"BufWritePost\", {\n        buffer = bnr,\n        callback = function(ev) require(\"zotcite.get\").collection_name(ev.buf) end,\n    })\nend\n\nM.get_config = function() return config end\n\nM.inited = function() return did_global_init end\n\nreturn M\n"
  },
  {
    "path": "lua/zotcite/get.lua",
    "content": "local config = require(\"zotcite.config\").get_config()\nlocal zwarn = require(\"zotcite\").zwarn\nlocal seek = require(\"zotcite.seek\")\nlocal zotero = require(\"zotcite.zotero\")\n\nlocal offset = 0\nlocal pdfnote_data = {}\nlocal sel_list = {}\n\nlocal citation = {\n    start_col = 0,\n    end_col = 0,\n}\n\nlocal M = {}\n\n---Convert key and path into valid path\n---@param attachment table\n---@return string | nil\nlocal translate_zpath = function(attachment, real_path)\n    if\n        not real_path\n        and config.open_in_zotero\n        and (\n            attachment.path:lower():find(\"%.pdf$\")\n            or attachment.path:lower():find(\"%.html$\")\n        )\n    then\n        return \"zotero://open-pdf/library/items/\" .. attachment.key\n    end\n\n    local fpath = tostring(attachment.path)\n    if attachment.path:find(\"attachments:\") then\n        -- The user has set Edit / Preferences / Files and Folders / Base directory for linked attachments\n        if not config.attach_dir then\n            zwarn(\n                \"Are you using a base directory for linked attachments? \"\n                    .. \"The config option `attach_dir` is not defined.\"\n            )\n            return nil\n        else\n            fpath =\n                attachment.path:gsub(\".*attachments:\", \"/\" .. config.attach_dir .. \"/\")\n        end\n    elseif attachment.path:find(\":/\") then\n        -- Absolute file path\n        fpath = attachment.path:gsub(\".*:/\", \"/\")\n    elseif attachment.path:find(\"storage:\") then\n        -- Default path\n        fpath = config.zotero_sqlite_path:match(\"(.*)/.-\")\n            .. attachment.path:gsub(\"storage:\", \"/storage/\" .. attachment.key .. \"/\")\n    end\n\n    if vim.fn.filereadable(fpath) == 0 then\n        zwarn('Could not find \"' .. fpath .. '\"')\n        fpath = \"\"\n    end\n    return fpath\nend\n\nlocal pdf_path = function(key, cb, real_path)\n    local repl, err = zotero.get_attachment(key)\n    if not repl then\n        zwarn(err)\n        return\n    end\n\n    local fpaths = {}\n    local item\n    for _, v in pairs(repl) do\n        item = translate_zpath(v, real_path)\n        if item then table.insert(fpaths, item) end\n    end\n    if #repl == 1 then\n        return fpaths[1]\n    else\n        local idx = 1\n        local items = {}\n        sel_list = {}\n        for _, v in pairs(fpaths) do\n            item = v:gsub(\".*/\", \"\")\n            item = vim.fn.slice(item, 0, 60)\n            table.insert(items, item)\n            table.insert(sel_list, v)\n            idx = idx + 1\n        end\n        vim.schedule(function() vim.ui.select(items, {}, cb) end)\n    end\nend\n\nlocal is_valid_char = function(c)\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    if kt == \"zotero\" then\n        return (c >= \"0\" and c <= \"9\")\n            or (c >= \"A\" and c <= \"z\")\n            or (c >= \"a\" and c <= \"z\")\n            or c:byte(1, 1) > 127\n    end\n    return c:find(\"[%w%-\\192-\\244\\128-\\191]\")\nend\n\nlocal citation_key_vt = function(line, pos)\n    pos = pos + 1\n    if line:sub(pos, pos) == \"@\" or line:sub(pos, pos) == \"<\" then\n        pos = pos + 1\n    elseif line:sub(pos, pos) == \">\" then\n        pos = pos - 1\n    end\n    local i = pos\n    local j = pos\n    while i > 0 and is_valid_char(line:sub(i, i)) do\n        i = i - 1\n    end\n    while j <= #line and is_valid_char(line:sub(j, j)) do\n        j = j + 1\n    end\n    local key = line:sub(i + 1, j - 1)\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    if kt == \"zotero\" then\n        if #key == 8 then return key end\n        return \"\"\n    else\n        return key\n    end\nend\n\nM.citation_key = function()\n    local lnum = vim.api.nvim_win_get_cursor(0)[1]\n    local line = vim.api.nvim_buf_get_lines(0, lnum - 1, lnum, true)[1]\n    local pos = vim.api.nvim_win_get_cursor(0)[2]\n    return citation_key_vt(line, pos)\nend\n\nM.reference_data = function(btype)\n    local wrd = M.citation_key()\n    if wrd ~= \"\" then\n        local repl = zotero.get_ref_data(wrd)\n        if type(repl) ~= \"table\" then\n            zwarn(\"Citation key not found\")\n            return\n        end\n        local info = {}\n        if btype == \"raw\" then\n            for k, v in pairs(repl) do\n                table.insert(info, { k, \"Title\" })\n                table.insert(info, { \": \" .. vim.inspect(v):gsub(\"\\n$\", \"\") .. \"\\n\" })\n            end\n        else\n            if repl.alastnm then\n                table.insert(info, { repl.alastnm .. \" \", \"Identifier\" })\n            end\n            if repl.year then table.insert(info, { repl.year .. \" \", \"Number\" }) end\n            if repl.title then table.insert(info, { repl.title, \"Title\" }) end\n        end\n        vim.schedule(function() vim.api.nvim_echo(info, false, {}) end)\n    end\nend\n\nlocal finish_citation = function(ref)\n    if not ref then return end\n    local rownr = vim.api.nvim_win_get_cursor(0)[1] - 1\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local cite = kt == \"zotero\" and ref.value.key or ref.value.cite\n    if not (vim.bo.filetype == \"tex\" or vim.bo.filetype == \"rnoweb\") then\n        cite = \"@\" .. cite\n    end\n    vim.api.nvim_buf_set_text(\n        0,\n        rownr,\n        citation.start_col,\n        rownr,\n        citation.end_col,\n        { cite }\n    )\n    local colnr = citation.start_col + #cite\n    vim.api.nvim_win_set_cursor(0, { rownr + 1, colnr })\n    vim.api.nvim_feedkeys(\"a\", \"n\", false)\n    vim.schedule(require(\"zotcite.hl\").citations)\nend\n\nM.citation = function()\n    local argmt = \"\"\n    local line = vim.api.nvim_get_current_line()\n    local last = vim.api.nvim_win_get_cursor(0)[2]\n    citation.start_col = last\n    citation.end_col = last\n    local c = line:sub(last, last):lower()\n    if (c >= \"a\" and c <= \"z\") or c > \"\\127\" then\n        local first = last - 1\n        while first > 0 and ((c >= \"a\" and c <= \"z\") or c > \"\\127\") do\n            first = first - 1\n            c = line:sub(first, first):lower()\n        end\n        argmt = line:sub(first + 1, last):lower()\n        citation.start_col = first\n    end\n    seek.refs(argmt, finish_citation)\nend\n\nM.abstract = function()\n    local wrd = M.citation_key()\n    if wrd ~= \"\" then\n        local repl = zotero.get_ref_data(wrd)\n        if type(repl) ~= \"table\" then\n            zwarn(\"Citation key not found\")\n            return\n        end\n        if repl.abstractNote then\n            vim.api.nvim_put({ repl.abstractNote }, \"l\", true, true)\n        else\n            zwarn(\"No abstract found associated with article\")\n        end\n    end\nend\n\nlocal get_annotations = function(sel)\n    local key = sel.value.key\n    local repl = zotero.get_annotations(key, offset)\n    if not repl then zwarn(\"No annotation found.\") end\n    return repl\nend\n\nlocal finish_annotations = function(sel)\n    if not sel then return end\n\n    local repl = get_annotations(sel)\n    if not repl then return end\n\n    local lnum = vim.api.nvim_win_get_cursor(0)[1]\n    vim.api.nvim_buf_set_lines(0, lnum, lnum, true, repl)\n    require(\"zotcite.hl\").citations()\nend\n\nlocal finish_annotations_selection = function(sel)\n    if not sel then return end\n    local lang = \"markdown\"\n    if vim.bo.filetype == \"typst\" then lang = \"typst\" end\n    if vim.bo.filetype == \"tex\" or vim.bo.filetype == \"noweb\" then lang = \"latex\" end\n    local raw_annotations = get_annotations(sel)\n    if raw_annotations then\n        local grouped_annotations = {}\n        local current_group = {}\n        local last_was_quote = false\n\n        for _, line in ipairs(raw_annotations) do\n            if\n                (lang == \"markdown\" and line:sub(1, 1) == \">\")\n                or (lang == \"typst\" and line:find(\"^#quote\"))\n                or (lang == \"latex\" and line:find(\"^\\\\begin%{quote%}\"))\n            then\n                if #current_group > 0 and not last_was_quote then\n                    table.insert(current_group, line)\n                    table.insert(grouped_annotations, table.concat(current_group, \"\\n\"))\n                    current_group = {}\n                else\n                    if #current_group > 0 then\n                        table.insert(\n                            grouped_annotations,\n                            table.concat(current_group, \"\\n\")\n                        )\n                        current_group = {}\n                    end\n                    table.insert(current_group, line)\n                end\n                last_was_quote = true\n            else\n                if last_was_quote and #current_group > 0 then\n                    table.insert(grouped_annotations, table.concat(current_group, \"\\n\"))\n                    current_group = {}\n                end\n                table.insert(current_group, line)\n                last_was_quote = false\n            end\n        end\n\n        if #current_group > 0 then\n            table.insert(grouped_annotations, table.concat(current_group, \"\\n\"))\n        end\n\n        local selected_indices = {}\n        local function select_annotation()\n            local opts = {}\n            local w = vim.o.columns - 10\n            if w > 140 then w = 140 end\n            for i, annotation in ipairs(grouped_annotations) do\n                if not selected_indices[i] then\n                    table.insert(opts, i .. \": \" .. annotation:sub(1, w)) -- Show first chars\n                end\n            end\n\n            if #opts == 0 then\n                if #selected_indices > 0 then\n                    local sel_annot = {}\n                    for index in pairs(selected_indices) do\n                        table.insert(sel_annot, grouped_annotations[index])\n                    end\n                    local lnum = vim.api.nvim_win_get_cursor(0)[1]\n                    local txt = table.concat(sel_annot, \"\\n\\n\")\n                    local lines = vim.split(txt, \"\\n\")\n                    vim.api.nvim_buf_set_lines(0, lnum, lnum, true, lines)\n                    require(\"zotcite.hl\").citations()\n                end\n                return\n            end\n\n            vim.ui.select(\n                opts,\n                { prompt = \"Select annotation (or cancel to finish)\" },\n                function(choice)\n                    if choice then\n                        local index = tonumber(vim.split(choice, \":\")[1])\n                        if index then\n                            selected_indices[index] = true\n                            select_annotation() -- Ask for the next selection\n                        end\n                    else\n                        if #selected_indices > 0 then\n                            local annot = {}\n                            for index in pairs(selected_indices) do\n                                table.insert(annot, grouped_annotations[index])\n                            end\n                            local lnum = vim.api.nvim_win_get_cursor(0)[1]\n                            vim.api.nvim_buf_set_lines(\n                                0,\n                                lnum,\n                                lnum,\n                                true,\n                                vim.split(table.concat(annot, \"\\n\\n\"), \"\\n\")\n                            )\n                            require(\"zotcite.hl\").citations()\n                        end\n                    end\n                end\n            )\n        end\n\n        select_annotation()\n    end\nend\n\nM.annotations = function(ko, use_selection)\n    local argmt\n    if ko:find(\" \") then\n        ko = vim.fn.split(ko)\n        argmt = ko[1]\n        if ko[2] then\n            local ko2 = tonumber(ko[2])\n            if ko2 then offset = ko2 end\n        end\n    else\n        argmt = ko\n        offset = 0\n    end\n    if use_selection then\n        seek.refs(argmt, finish_annotations_selection)\n    else\n        seek.refs(argmt, finish_annotations)\n    end\nend\n\nlocal finish_note = function(sel)\n    local key = sel.value.key\n    local repl = zotero.get_notes(key)\n    if not repl then\n        zwarn(\"No note found.\")\n    else\n        local lines = vim.fn.split(repl, \"\\n\")\n        local lnum = vim.api.nvim_win_get_cursor(0)[1]\n        vim.api.nvim_buf_set_lines(0, lnum, lnum, true, lines)\n        require(\"zotcite.hl\").citations()\n    end\nend\n\nM.note = function(key) seek.refs(key, finish_note) end\n\nlocal finish_pdfnote_2 = function(_, idx)\n    local fpath = sel_list[idx]\n\n    local lnum = vim.api.nvim_win_get_cursor(0)[1]\n    local key = pdfnote_data.citekey\n    local p = pdfnote_data.pg\n    if vim.fn.filereadable(fpath) == 0 then\n        zwarn('File not readable: \"' .. fpath .. '\"')\n        return\n    end\n\n    -- Determine which PDF extractor to use\n    local pdf_extractor = config.pdf_extractor or \"pdfnotes.py\"\n\n    vim.env.ZYearPageSep = config.year_page_sep\n    local notes = vim.system({\n        config.python_path,\n        config.python_scripts_path .. \"/\" .. pdf_extractor,\n        fpath,\n        key,\n        p,\n    }, { text = true }):wait()\n    if notes.code == 0 then\n        local lines = vim.fn.split(notes.stdout, \"\\n\")\n        if vim.bo.filetype == \"typst\" then\n            local tlines = {}\n            for _, v in pairs(lines) do\n                v = v:gsub(\n                    \"^> (.-) %[@(%S-), (.-)%]$\",\n                    '#quote[%1] #cite(<%2>, supplement: \"%3\")'\n                )\n                table.insert(tlines, v)\n            end\n            vim.api.nvim_buf_set_lines(0, lnum, lnum, true, tlines)\n        elseif vim.bo.filetype == \"tex\" or vim.bo.filetype == \"rnoweb\" then\n            local tlines = {}\n            for _, v in pairs(lines) do\n                v = v:gsub(\n                    \"^> (.-) %[@(%S-), (.-)%]$\",\n                    \"\\\\begin{quote}%1 \\\\cite[%3]{%2}\\\\end{quote}\"\n                )\n                table.insert(tlines, v)\n            end\n            vim.api.nvim_buf_set_lines(0, lnum, lnum, true, tlines)\n        else\n            vim.api.nvim_buf_set_lines(0, lnum, lnum, true, lines)\n        end\n        require(\"zotcite.hl\").citations()\n    elseif notes.code == 33 then\n        zwarn('Failed to load \"' .. fpath .. '\" as a valid PDF document.')\n    elseif notes.code == 34 then\n        zwarn(\"No annotations found.\")\n    else\n        zwarn(notes.stderr)\n    end\nend\n\nlocal finish_pdfnote = function(sel)\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local key = kt == \"zotero\" and sel.value.key or sel.value.cite\n    local repl = zotero.get_ref_data(key)\n    if type(repl) ~= \"table\" then\n        zwarn(\"Citation key not found\")\n        return\n    end\n    local citekey = \"@\"\n    if kt == \"zotero\" then\n        citekey = citekey .. sel.value.key\n    else\n        citekey = citekey .. sel.value.cite\n    end\n    local pg = \"1\"\n    if repl.pages and repl.pages:find(\"[0-9]-\") then pg = repl.pages end\n    pdfnote_data = { citekey = citekey, pg = pg }\n\n    local apath = pdf_path(key, finish_pdfnote_2, true)\n    if type(apath) == \"string\" then\n        sel_list = { apath }\n        finish_pdfnote_2(nil, 1)\n    end\nend\n\nM.PDFNote = function(key) seek.refs(key, finish_pdfnote) end\n\n--- Strip string from empty spaces and quotes\n---@param line string The string to be stripped\n---@return string\nlocal get_yaml_string = function(line)\n    local str\n    if line:find(\"^'.*'$\") then\n        str = line:match(\"^%s*'(.-)'%s*$\")\n    elseif line:find('^%s*\".*\"%s*$') then\n        str = line:match('^%s*\"(.-)\"%s*$')\n    else\n        str = line:match(\"^%s*(.-)%s*$\")\n    end\n    return str\nend\n\n--- Get the value of a YAML field\n---@param field string Field name\n---@param bn integer Buffer number\n---@return string | string[] | nil\nM.yaml_field = function(field, bn)\n    if vim.tbl_contains({ \"tex\", \"rnoweb\" }, vim.bo.filetype) then return nil end\n    local line1 = vim.api.nvim_buf_get_lines(bn, 0, 1, true)[1]\n    if line1 ~= \"---\" then return end\n\n    local lines = vim.api.nvim_buf_get_lines(bn, 0, -1, true)\n    local nlines = #lines\n    local i = 2\n    local value\n    while i < nlines do\n        if lines[i] == \"---\" then break end\n        if lines[i]:find(field .. \":\") then\n            if lines[i]:find(field .. \":%s*$\") then\n                -- multiline list\n                value = {}\n                i = i + 1\n                while lines[i]:find(\"^%s*%-\") do\n                    if lines[i] == \"---\" then break end\n                    local line = lines[i]:match(\"^%s*%-%s*(.-)%s*$\")\n                    table.insert(value, get_yaml_string(line))\n                    i = i + 1\n                end\n                if lines[i]:find(\"^%s*%w*:$\") then\n                    return lines[i]:match(\"^%s*(%w-):$\")\n                end\n            elseif lines[i]:find(field .. \":%s%[.*%]%s*$\") then\n                -- bracketed list in a single line\n                value = vim.split(lines[i]:match(\"^\" .. field .. \":%s*%[(.-)%]%s*$\"), \",\")\n                for k, v in pairs(value) do\n                    value[k] = get_yaml_string(v)\n                end\n            else\n                -- string\n                value = lines[i]:match(\"^%s*\" .. field .. \":%s*(.-)%s*$\")\n                value = get_yaml_string(value)\n            end\n            return value\n        end\n        i = i + 1\n    end\n    return nil\nend\n\n--- Get collection names from buffer and set them in zotero.lua\n---@param bn integer Buffer number\nM.collection_name = function(bn)\n    local newc = M.yaml_field(\"collection\", bn)\n    if not newc then return end\n\n    if type(newc) == \"string\" then newc = { newc } end\n    zotero.set_collections(vim.api.nvim_buf_get_name(0), newc)\nend\n\n--- Insert echo lines into table\n---@param info table The table with echo lines\n---@param ttl string Section title\n---@param lines string[] Lines to insert\nlocal function insert_info(info, ttl, lines)\n    table.insert(info, { ttl .. \"\\n\", \"Statement\" })\n    for k, v in pairs(lines) do\n        table.insert(info, { \"  \" .. k, \"Title\" })\n        table.insert(info, { \": \" })\n        local hl = type(v) == \"string\" and \"String\"\n            or type(v) == \"number\" and \"Number\"\n            or \"Normal\"\n        table.insert(info, { vim.inspect(v), hl })\n        table.insert(info, { \"\\n\" })\n    end\nend\n\nM.zotero_info = function()\n    if\n        not vim.tbl_contains(config.filetypes, vim.bo.filetype)\n        and vim.bo.filetype ~= \"bib\"\n    then\n        zwarn(\"zotcite doesn't support \" .. vim.bo.filetype .. \" filetype.\")\n        return\n    end\n\n    local out_lines = {}\n    insert_info(out_lines, \"Init information\", require(\"zotcite.config\").info)\n\n    insert_info(out_lines, \"Zotero information\", require(\"zotcite.zotero\").info())\n\n    local w = require(\"zotcite\").get_warns()\n    if #w > 0 then\n        table.insert(out_lines, { \"Know problems:\\n\", \"Statement\" })\n        for _, v in pairs(w) do\n            table.insert(out_lines, { v .. \"\\n\", \"WarningMsg\" })\n        end\n    end\n    vim.schedule(function() vim.api.nvim_echo(out_lines, false, {}) end)\nend\n\nlocal finish_open_attachment = function(_, idx)\n    if idx then require(\"zotcite.utils\").open(sel_list[idx]) end\nend\n\nM.open_attachment = function()\n    local key = M.citation_key()\n    local apath = pdf_path(key, finish_open_attachment, false)\n    if type(apath) == \"string\" then require(\"zotcite.utils\").open(apath) end\nend\n\nreturn M\n"
  },
  {
    "path": "lua/zotcite/hl.lua",
    "content": "local config = require(\"zotcite.config\").get_config()\n\nlocal M = {}\n\n--- Highlight citation key and add virtual text\n---@param ns integer Namespace id\n---@param i integer Line\n---@param s integer Column\n---@param e integer End column\n---@param a string\nlocal vt_citation = function(ns, i, s, e, c, a)\n    if not a then return end\n    local set_m = vim.api.nvim_buf_set_extmark\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    if kt == \"zotero\" then\n        a = a:gsub(\"%-\", \"_\")\n        set_m(0, ns, i - 1, s - 1, { end_col = e, hl_group = \"Ignore\", conceal = \"\" })\n        set_m(\n            0,\n            ns,\n            i - 1,\n            c,\n            { virt_text = { { a, \"Identifier\" } }, virt_text_pos = \"inline\" }\n        )\n    else\n        if vim.tbl_contains({ \"tex\", \"rnoweb\", \"bib\" }, vim.bo.filetype) then\n            set_m(0, ns, i - 1, s - 1, { end_col = e, hl_group = \"Identifier\" })\n        else\n            set_m(0, ns, i - 1, s - 1, { end_col = s, hl_group = \"Ignore\", conceal = \"\" })\n            set_m(0, ns, i - 1, s, { end_col = e, hl_group = \"Identifier\" })\n        end\n    end\nend\n\nlocal vt_citations_bib = function(lines, ns)\n    local set_m = vim.api.nvim_buf_set_extmark\n    local key = nil\n    local citekey = nil\n    local zotkey = nil\n    local zlnum = 0\n    local clnum = 0\n    local hl = \"WarningMsg\"\n    for k, v in pairs(lines) do\n        if v:find(\"^@%S*{.*,%s*$\") then\n            key = v:match(\"^@%S*{(.*),%s*$\")\n        elseif v:find(\"^%s*zotkey%s*=%s{%S*},\") then\n            zotkey = v:match(\"^%s*zotkey%s*=%s{(%S*)},\")\n            zlnum = k\n        elseif v:find(\"^%s*citekey%s*=%s{%S*},\") then\n            citekey = v:match(\"^%s*citekey%s*=%s{(%S*)},\")\n            clnum = k\n        end\n        if key and citekey and zotkey then\n            local grd = require(\"zotcite.zotero\").get_ref_data\n            local kt =\n                require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n            local r = kt == \"zotero\" and grd(zotkey) or grd(citekey)\n            if not r or r.zotkey ~= zotkey then\n                local s, e = lines[zlnum]:find(zotkey)\n                if s and e then\n                    set_m(0, ns, zlnum - 1, s - 1, { end_col = e, hl_group = hl })\n                end\n            end\n            if not r or r.citekey ~= citekey then\n                local s, e = lines[clnum]:find(citekey:gsub(\"%-\", \"%%-\"))\n                if s and e then\n                    set_m(0, ns, clnum - 1, s - 1, { end_col = e, hl_group = hl })\n                end\n            end\n            citekey = nil\n            zotkey = nil\n            key = nil\n        end\n    end\nend\n\nlocal vt_citations_md = function(ac, ns, lines)\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local kp = kt == \"zotero\"\n            and \"@[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]\"\n        or \"@[%w%-\\192-\\244\\128-\\191]+\"\n    local a = \"\"\n    for k, v in pairs(lines) do\n        local i = 1\n        local imax = #v\n        while i < imax do\n            local s, e = v:find(kp, i)\n            if not s or not e then break end\n            a = ac[v:sub(s + 1, e)]\n            vt_citation(ns, k, s, e, s, a)\n            i = e + 1\n        end\n    end\nend\n\nlocal vt_citations_typ = function(ac, ns, lines)\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local kp = kt == \"zotero\"\n            and \"<[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]>\"\n        or \"<[%w%-\\192-\\244\\128-\\191]+>\"\n    local a = \"\"\n    for k, v in pairs(lines) do\n        local i = 1\n        local imax = #v\n        while i < imax do\n            local s, e = v:find(kp, i)\n            if not s or not e then break end\n            a = ac[v:sub(s + 1, e - 1)]\n            vt_citation(ns, k, s, e, e, a)\n            i = e + 1\n        end\n    end\nend\n\nlocal vt_citations_tex = function(ac, ns, lines)\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local kp1 = \"\\\\%w*cit.*{\"\n    local kp2 = kt == \"zotero\"\n            and \"[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]\"\n        or \"[%w%-\\192-\\244\\128-\\191]+\"\n    local a = \"\"\n    for k, v in pairs(lines) do\n        local i = 1\n        local imax = #v\n        while i < imax do\n            local s, e = v:find(kp1, i)\n            if not s or not e then break end\n            local j = e\n            local l = v:find(\"%}\", j)\n            if not l then l = 1000 end\n            while j < l do\n                local s2, e2 = v:find(kp2, j)\n                if not s2 or not e2 then break end\n                a = ac[v:sub(s2, e2)]\n                vt_citation(ns, k, s2, e2, e2, a)\n                j = e2 + 1\n            end\n            i = e + 1\n        end\n    end\nend\n\nM.citations = function()\n    if not config.hl_cite_key then return end\n\n    local ac = require(\"zotcite.zotero\").get_all_citations()\n    local ns = vim.api.nvim_create_namespace(\"ZCitation\")\n    vim.api.nvim_buf_clear_namespace(0, ns, 0, -1)\n    local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)\n    if not vim.tbl_contains({ \"tex\", \"rnoweb\", \"bib\" }, vim.bo.filetype) then\n        vt_citations_md(ac, ns, lines)\n    end\n    if vim.bo.filetype == \"typst\" then\n        vt_citations_typ(ac, ns, lines)\n    elseif vim.bo.filetype == \"tex\" or vim.bo.filetype == \"rnoweb\" then\n        vt_citations_tex(ac, ns, lines)\n    elseif vim.bo.filetype == \"bib\" then\n        vt_citations_bib(lines, ns)\n    end\nend\n\nreturn M\n"
  },
  {
    "path": "lua/zotcite/init.lua",
    "content": "local M = {}\n\nlocal warns = {}\n\n--- Warning\n---@param msg string The message\n---@param store boolean? Whether to store the message\nM.zwarn = function(msg, store)\n    vim.notify(msg, vim.log.levels.WARN, { title = \"zotcite\" })\n    if store then table.insert(warns, msg) end\nend\n\nM.get_warns = function() return warns end\n\nM.user_opts = nil\n\n--- Setup\n---@param opts? ZotciteUserOpts\nM.setup = function(opts)\n    if opts then M.user_opts = opts end\nend\n\nreturn M\n"
  },
  {
    "path": "lua/zotcite/lsp.lua",
    "content": "local zwarn = require(\"zotcite\").zwarn\nlocal zotero = require(\"zotcite.zotero\")\n\nlocal last_line = 0\nlocal z_ls = {\n    name = \"zotero_ls\",\n    client_id = nil,\n    initialized = false,\n    stopped = true,\n}\n\nlocal compl_region = true\n\n--- Resolve selected menu item\n---@param key string\nlocal resolve = function(key)\n    local ref = zotero.get_ref_data(key)\n    if not ref then return nil end\n\n    local doc = \"\"\n    local ttl = ref.title and ref.title or nil\n    local etype = string.gsub(ref.etype, \"([A-Z])\", \" %1\")\n    etype = string.lower(etype)\n    doc = \"**\" .. ttl .. \"**\\n\\n\"\n    if ref.etype == \"journalArticle\" and ref.publicationTitle then\n        doc = doc .. \"*\" .. ref.publicationTitle .. \"*\\n\\n\"\n    elseif ref.etype == \"bookSection\" and ref.bookTitle then\n        doc = doc .. \"In *\" .. ref.bookTitle .. \"*\\n\\n\"\n    end\n    if ref.alastnm then doc = doc .. ref.alastnm end\n    if ref.year then\n        doc = doc .. \" (\" .. ref.year .. \") \"\n    else\n        doc = doc .. \" (????) \"\n    end\n    return etype, doc\nend\n\n--- Fill completion menu\n---@param lnum integer Line number\n---@param char integer Cursor column\nlocal complete = function(callback, lnum, char)\n    local line = vim.api.nvim_buf_get_lines(0, lnum, lnum + 1, true)[1]\n    local byte_idx = vim.fn.byteidx(line, char)\n    if byte_idx < 0 then byte_idx = #line end\n    local subline = line:sub(1, byte_idx)\n    local word\n    if vim.bo.filetype == \"rnoweb\" or vim.bo.filetype == \"tex\" then\n        word = subline:match(\".*{.-(%S+)$\")\n    else\n        word = subline:match(\".*@(%S+)$\")\n    end\n    if not word then\n        callback(nil, { isIncomplete = false, items = {} })\n        return\n    end\n\n    local compl_items = {}\n    local bnm = vim.api.nvim_buf_get_name(0)\n    if vim.fn.has(\"win32\") == 1 then bnm = string.gsub(tostring(bnm), \"\\\\\", \"/\") end\n    local itms = zotero.get_match(word, bnm)\n    local text_edit_range = {\n        start = {\n            line = lnum,\n            character = char - 1,\n        },\n        [\"end\"] = {\n            line = lnum,\n            character = char,\n        },\n    }\n    if itms then\n        for _, v in pairs(itms) do\n            local txt = string.format(\"%s (%s) %s\", v.alastnm, v.year, v.title)\n            if vim.fn.strwidth(txt) > 58 then\n                txt = vim.fn.strcharpart(txt, 0, 58) .. \"⋯\"\n            end\n            local kt =\n                require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n            table.insert(compl_items, {\n                label = txt,\n                kind = vim.lsp.protocol.CompletionItemKind.Variable,\n                textEdit = {\n                    newText = kt == \"zotero\" and v.zotkey or v.citekey,\n                    range = text_edit_range,\n                },\n            })\n        end\n    end\n    callback(nil, { isIncomplete = false, items = compl_items })\nend\n\n--- Hover implementation\n---@param lnum integer Line number\n---@param char integer Cursor column\n---@return table\nlocal hover = function(lnum, char)\n    local line = vim.api.nvim_buf_get_lines(0, lnum, lnum + 1, true)[1]\n\n    -- Find zotero key\n    local k = char\n    local pre\n    if vim.bo.filetype == \"tex\" or vim.bo.filetype == \"rnoweb\" then\n        pre = line:sub(1, k):match(\".-([%w%-\\192-\\244\\128-\\191]-)$\")\n    else\n        pre = line:sub(1, k):match(\".*@(.*)\")\n    end\n    if not pre then return {} end\n    local pos = line:sub(k + 1, -1):match(\"^(%S*).*\")\n    if not pos then return {} end\n    local subline = pre .. pos\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local ktnz = kt ~= \"zotero\"\n    local key = ktnz and subline:match(\"^([%w%-\\192-\\244\\128-\\191]+)\")\n        or subline:match(\n            \"^([0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z])\"\n        )\n    if not key then return {} end\n    local ttl, doc = resolve(key)\n    if not ttl then return {} end\n    local i, j\n    if ktnz then\n        i, j = line:find(key)\n    else\n        i, j = line:find(key .. \"[%w%-0-9]*\")\n    end\n    if i then\n        return {\n            range = {\n                start = {\n                    line = lnum,\n                    character = i - 1,\n                },\n                [\"end\"] = {\n                    line = lnum,\n                    character = j,\n                },\n            },\n            contents = { kind = \"markdown\", value = ttl .. \"\\n\\n---\\n\\n\" .. doc },\n        }\n    end\n    return { contents = { kind = \"markdown\", value = ttl .. \"\\n\\n---\\n\\n\" .. doc } }\nend\n\n--- Get list of \"zotero_ls\" servers attached to current buffer\n---@return integer[]\nlocal function get_z_id()\n    local cids = vim.lsp.get_clients({ buffer = vim.api.nvim_get_current_buf() })\n    local ids = {}\n    for _, v in pairs(cids) do\n        if v.name == z_ls.name then table.insert(ids, v.id) end\n    end\n    return ids\nend\n\n--- This function receives 4 arguments: method, params, callback, notify_callback\nlocal function lsp_request(method, params, callback, _)\n    if method == \"textDocument/completion\" then\n        if not compl_region then\n            callback(nil, { isIncomplete = false, items = {} })\n            return\n        end\n\n        vim.schedule(\n            function() complete(callback, params.position.line, params.position.character) end\n        )\n    elseif method == \"completionItem/resolve\" then\n        local key = params.textEdit.newText\n\n        local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n        if kt == \"zotero\" then key = key:gsub(\"%-.*\", \"\") end\n        local ttl, doc = resolve(key)\n        if ttl then\n            params.detail = ttl\n            params.documentation = { kind = \"zinfo\", value = doc }\n        end\n        callback(nil, params)\n    elseif method == \"textDocument/hover\" then\n        if not compl_region then\n            callback(nil, { result = nil })\n            return\n        end\n        local res = hover(params.position.line, params.position.character)\n        if res then callback(nil, res) end\n    elseif method == \"initialize\" then\n        callback(nil, {\n            capabilities = {\n                textDocument = {\n                    completion = { completionItem = { snippetSupport = false } },\n                },\n                hoverProvider = true,\n                completionProvider = {\n                    -- would work only if we could reset the completion\n                    -- triggerCharacters = { \"@\" },\n                    resolveProvider = true,\n                },\n            },\n        })\n    elseif method == \"shutdown\" then\n        z_ls.stopped = true\n        local zid = get_z_id()\n        if #zid > 0 then\n            for _, v in pairs(zid) do\n                if vim.lsp.buf_is_attached(0, v) then vim.lsp.buf_detach_client(0, v) end\n                vim.lsp.get_client_by_id(v):stop()\n            end\n        end\n    else\n        zwarn(\n            string.format(\n                'LSP method \"%s\" not implemented. Received `params`:\\n%s',\n                vim.inspect(method),\n                vim.inspect(params)\n            )\n        )\n    end\nend\n\n--- This function receives two arguments: method, params\nlocal function lsp_notify(method, _)\n    if method == \"initialized\" then\n        z_ls.initialized = true\n        z_ls.stopped = false\n    end\nend\n\n-- Inspired by null-ls (see none-ls.nvim/lua/null-ls/rpc.lua)\nlocal function lsp_start(_, _)\n    return {\n        request = lsp_request,\n        notify = lsp_notify,\n        is_closing = function() return z_ls.stopped end,\n        terminate = function() z_ls.stopped = true end,\n    }\nend\n\n--- Set the value of `compl_region` which indicates if the cursor is in a\n--- region where the completion of Zotero's keys is meaningful for Rnoweb or\n--- LaTeX documents\nlocal function set_compl_region_rnw()\n    local curpos = vim.api.nvim_win_get_cursor(0)\n    if not curpos then\n        compl_region = false\n        return\n    end\n    local line = vim.api.nvim_buf_get_lines(0, curpos[1] - 1, curpos[1], true)[1]\n    local subline = line:sub(1, curpos[2])\n    local pre, pos = subline:match(\".*(\\\\cite%S*{)(.*)\")\n    if pre and not pos:find(\"}\") then\n        compl_region = true\n    else\n        compl_region = false\n    end\nend\n\n--- Set the value of `compl_region` which indicates if the cursor is in a\n--- region where the completion of Zotero's keys is meaningful for Markdown\n--- documents\nlocal function set_compl_region_md()\n    local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_get_current_buf(), 0, -1, true)\n    local lnum = last_line\n\n    -- Check if we are within normal markdown text\n    compl_region = true\n    for i = lnum, 1, -1 do\n        if string.find(lines[i], \"^```{\") then\n            -- within code block\n            compl_region = false\n            break\n        else\n            if string.find(lines[i], \"^```$\") then\n                -- after a code block\n                break\n            else\n                if\n                    string.find(lines[i], \"^---$\") or string.find(lines[i], \"^%.%.%.$\")\n                then\n                    -- after or within YAML front matter\n                    break\n                end\n            end\n        end\n    end\nend\n\n--- Call the appropriate function to set the value `compl_region`\nlocal function on_cursor_move()\n    if vim.bo.filetype == \"rnoweb\" or vim.bo.filetype == \"tex\" then\n        set_compl_region_rnw()\n    end\n    local curpos = vim.api.nvim_win_get_cursor(0)\n    if not curpos then return end\n    local curline = curpos[1]\n    if curline == last_line then return end\n    last_line = curline\n    set_compl_region_md()\nend\n\nlocal M = {}\n\n--- Start or enable the language server\nfunction M.start()\n    -- TODO: remove this when nvim 0.12 is released\n    if not vim.lsp.config then return end\n\n    vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n        buffer = vim.api.nvim_get_current_buf(),\n        callback = on_cursor_move,\n    })\n    vim.api.nvim_create_autocmd(\"CompleteDone\", {\n        buffer = vim.api.nvim_get_current_buf(),\n        callback = require(\"zotcite.hl\").citations,\n    })\n\n    local config = require(\"zotcite.config\").get_config()\n    vim.lsp.config(z_ls.name, { cmd = lsp_start, filetypes = config.filetypes })\n    if z_ls.client_id then\n        vim.lsp.enable(z_ls.name)\n    else\n        z_ls.client_id = vim.lsp.start({ name = z_ls.name, cmd = lsp_start })\n    end\nend\n\nreturn M\n"
  },
  {
    "path": "lua/zotcite/seek.lua",
    "content": "local config = require(\"zotcite.config\").get_config()\nlocal ns = vim.api.nvim_create_namespace(\"ZSeekPreview\")\nlocal zotero = require(\"zotcite.zotero\")\n\nlocal M = {}\n\nlocal get_match = function(key)\n    local citeptrn = key:gsub(\" .*\", \"\")\n    local refs = zotero.get_match(citeptrn, vim.api.nvim_buf_get_name(0))\n    if #refs == 0 then\n        vim.schedule(\n            function() vim.api.nvim_echo({ { \"No matches found.\" } }, false, {}) end\n        )\n    end\n    return refs\nend\n\nM.print = function(ref)\n    local msg = {\n        { ref.value.alastnm, \"Identifier\" },\n        { \" \" },\n        { ref.value.year, \"Number\" },\n        { \" \" },\n        { ref.value.title, \"Title\" },\n    }\n    vim.schedule(function() vim.api.nvim_echo(msg, false, {}) end)\nend\n\nlocal format_preview = function(v)\n    local alist = {}\n    local authors\n    if v.author then\n        if #v.author > 5 then\n            authors = v.author[1][1] .. \", \" .. v.author[1][2] .. \" and others\"\n        else\n            for _, n in pairs(v.author) do\n                table.insert(alist, n[1] .. \", \" .. n[2])\n            end\n            authors = table.concat(alist, \"; \")\n        end\n    else\n        authors = \"?\"\n    end\n    local year = v.year or \"????\"\n    local title = v.title or \"????\"\n    local ptitle = v.publicationTitle or \"????\"\n    local txt\n    local hl = { { g = \"Identifier\", s = 0, e = #authors } }\n    table.insert(hl, { g = \"Number\", s = hl[1].e + 1, e = hl[1].e + 1 + #year })\n    table.insert(hl, { g = \"Title\", s = hl[2].e + 1, e = hl[2].e + 1 + #title })\n    if v.etype == \"journalArticle\" then\n        txt = string.format(\n            \"%s %s %s. %s.\\n\\n%s\\n\",\n            authors,\n            year,\n            title,\n            ptitle,\n            v.abstract or \"No abstract available.\"\n        )\n        table.insert(hl, { g = \"Include\", s = hl[3].e + 2, e = hl[3].e + 2 + #ptitle })\n    elseif v.etype == \"bookSection\" then\n        txt = string.format(\n            \"%s %s %s. In: %s.\\n\\n%s\\n\",\n            authors,\n            year,\n            title,\n            ptitle,\n            v.abstract or \"\"\n        )\n        table.insert(hl, { g = \"Include\", s = hl[3].e + 6, e = hl[3].e + 6 + #ptitle })\n    else\n        txt = string.format(\"%s %s %s.\\n\\n%s\\n\", authors, year, title, v.abstract or \"\")\n    end\n    return txt, hl\nend\n\n--- Use telescope to find and select a reference\n---@param key string Pattern to search\n---@param cb function Callback function\nM.refs = function(key, cb)\n    local pickers = require(\"telescope.pickers\")\n    local finders = require(\"telescope.finders\")\n    local sorters = require(\"telescope.config\").values\n    local actions = require(\"telescope.actions\")\n    local action_state = require(\"telescope.actions.state\")\n    local previewers = require(\"telescope.previewers\")\n    local entry_display = require(\"telescope.pickers.entry_display\")\n    local mtchs = get_match(key)\n    local references = {}\n\n    local awidth = 2\n    local awlim = vim.o.columns - 140\n    if awlim < 20 then awlim = 20 end\n    if awlim > 60 then awlim = 60 end\n    for _, v in pairs(mtchs) do\n        if #v.alastnm > awidth then awidth = #v.alastnm end\n        table.insert(references, {\n            display = v.alastnm .. \" \" .. v.year .. \" \" .. v.title,\n            etype = v.etype,\n            sort_key = v[config.sort_key] or \"0000-00-00 0000\",\n            publicationTitle = v.publicationTitle\n                or v.bookTitle\n                or v.proceedingsTitle\n                or v.conferenceName\n                or v.programTitle\n                or v.blogTitle\n                or v.code\n                or v.dictionaryTitle\n                or v.encyclopediaTitle\n                or v.forumTitle\n                or v.websiteTitle\n                or v.seriesTitle,\n            author = v.author\n                or v.artist\n                or v.performer\n                or v.director\n                or v.composer\n                or v.sponsor\n                or v.contributor\n                or v.interviewee\n                or v.cartographer\n                or v.inventor\n                or v.podcaster\n                or v.presenter\n                or v.programmer\n                or v.recipient\n                or v.editor\n                or v.seriesEditor\n                or v.translator,\n            alastnm = v.alastnm,\n            year = v.year,\n            title = v.title,\n            abstract = v.abstractNote,\n            key = v.zotkey,\n            cite = v.citekey,\n        })\n    end\n    if awidth > awlim then awidth = awlim end\n    table.sort(references, function(a, b) return (a.sort_key > b.sort_key) end)\n\n    pickers\n        .new({}, {\n            prompt_title = \"Search pattern\",\n            results_title = \"Zotero references\",\n            finder = finders.new_table({\n                results = references,\n                entry_maker = function(entry)\n                    local displayer = entry_display.create({\n                        separator = \" \",\n                        items = {\n                            { width = awidth }, -- Author\n                            { width = 4 }, -- Year\n                            { remaining = true }, -- Title\n                        },\n                    })\n                    return {\n                        value = entry,\n                        display = function(e)\n                            return displayer({\n                                { e.value.alastnm, \"Identifier\" },\n                                { e.value.year, \"Number\" },\n                                { e.value.title, \"Title\" },\n                            })\n                        end,\n                        ordinal = entry.display,\n                    }\n                end,\n            }),\n            sorter = sorters.generic_sorter({}),\n            previewer = previewers.new_buffer_previewer({\n                define_preview = function(self, entry, _)\n                    local bufnr = self.state.bufnr\n                    local preview_text, hl = format_preview(entry.value)\n                    vim.api.nvim_buf_set_lines(\n                        bufnr,\n                        0,\n                        -1,\n                        false,\n                        vim.split(preview_text, \"\\n\")\n                    )\n                    for _, h in pairs(hl) do\n                        vim.hl.range(bufnr, ns, h.g, { 0, h.s }, { 0, h.e }, {})\n                    end\n                end,\n            }),\n            attach_mappings = function(prompt_bufnr, map)\n                map({ \"i\", \"n\" }, \"<CR>\", function()\n                    local selection = action_state.get_selected_entry()\n                    actions.close(prompt_bufnr)\n                    -- Handle the selected reference here\n                    cb(selection)\n                end)\n                return true\n            end,\n        })\n        :find()\nend\n\n--  text wrapping in the preview window\nvim.api.nvim_create_autocmd(\"User\", {\n    pattern = \"TelescopePreviewerLoaded\",\n    callback = function()\n        vim.wo.wrap = true\n        vim.wo.linebreak = true\n    end,\n})\n\nreturn M\n"
  },
  {
    "path": "lua/zotcite/utils.lua",
    "content": "local config = require(\"zotcite.config\").get_config()\nlocal zwarn = require(\"zotcite\").zwarn\n\nlocal M = {}\n\nM.ODTtoMarkdown = function(odt)\n    require(\"zotcite.config\").set_path()\n    local mdf = vim.system({ config.python_path, \"odt2md.py\", odt }, { text = true })\n        :wait()\n    if mdf.code == 0 then\n        vim.cmd(\"tabnew \" .. mdf.stdout)\n    else\n        zwarn(mdf.stderr:gsub(\"\\n\", \" \"))\n    end\nend\n\n---@return string\nlocal get_output_ext = function()\n    if vim.tbl_contains({ \"tex\", \"rnoweb\", \"typst\" }, vim.bo.filetype) then\n        return \"pdf\"\n    end\n    local field = vim.bo.filetype == \"quarto\" and \"format\" or \"output\"\n    local fmt = require(\"zotcite.get\").yaml_field(field, vim.api.nvim_get_current_buf())\n    if fmt then\n        if type(fmt) == \"table\" then\n            fmt = #fmt > 0 and tostring(fmt[1]) or \"html\"\n        else\n            fmt = tostring(fmt)\n        end\n        if fmt == \"pdf_document\" or fmt == \"beamer\" then\n            return \"pdf\"\n        elseif fmt == \"odf_document\" then\n            return \"odt\"\n        end\n        return fmt\n    end\n    return \"html\"\nend\n\nM.view_document = function()\n    local ext = get_output_ext()\n    local doc = vim.fn.expand(\"%:p:r\") .. \".\" .. ext\n    if vim.fn.filereadable(doc) == 0 then\n        zwarn('File \"' .. doc .. '\" not found.')\n        return\n    end\n    M.open(doc)\nend\n\nM.open = function(fpath)\n    if config.wait_attachment then\n        local obj\n        local em\n        if config.open_cmd then\n            obj = vim.system({ config.open_cmd, fpath }, { text = true }):wait()\n            em = \"Error running `\" .. config.open_cmd .. ' \"' .. fpath .. '\"' .. \"`\"\n        else\n            obj = vim.ui.open(fpath):wait()\n            em = 'Error running `vim.ui.open(\"' .. fpath .. '\")`'\n        end\n        if obj.code ~= 0 then\n            em = em .. \":\\n  exit code: \" .. tostring(obj.code)\n            if obj.stdout and obj.stdout ~= \"\" then em = em .. \"\\n  \" .. obj.stdout end\n            if obj.stderr and obj.stderr ~= \"\" then em = em .. \"\\n  \" .. obj.stderr end\n            zwarn(em)\n        end\n        return\n    end\n    if config.open_cmd then\n        vim.system({ config.open_cmd, fpath }, { text = true })\n    else\n        vim.ui.open(fpath)\n    end\nend\n\nreturn M\n"
  },
  {
    "path": "lua/zotcite/zotero.lua",
    "content": "-- A lot of code was either adapted or plainly copied from citation_vim,\n-- written by Rafael Schouten: https://github.com/rafaqz/citation.vim\n-- Code and/or ideas were also adapted from zotxt, pypandoc, and pandocfilters.\n\n-- To debug this code, create a /tmp/test.md file and do:\n-- pandoc /tmp/test.md -F /full/path/to/zotcite/lua/zotcite/zotref.lua\n\n-- We can't use the \"vim\" module because zotref will be called by external\n-- tools. For the same reason, we can't use the \"zotcite\" module\n\nlocal config = require(\"zotcite.config\").get_config()\n\nlocal cite_template\nlocal banned_words = {}\nlocal zcopy\nlocal ztime\nlocal exclude_fields = {}\nlocal entry = {}\nlocal collections = {}\nlocal docs = {}\n\n--- Create an object storing all references from ~/Zotero/zotero.sqlite\n\n-- Conversion from zotero.sqlite to bib types\nlocal _zbt = {\n    artwork = \"Misc\",\n    audioRecording = \"Misc\",\n    blogPost = \"Misc\",\n    book = \"Book\",\n    bookSection = \"InCollection\",\n    case = \"Misc\",\n    computerProgram = \"Book\",\n    conferencePaper = \"InProceedings\",\n    dictionaryEntry = \"InCollection\",\n    document = \"TechReport\",\n    email = \"Misc\",\n    encyclopediaArticle = \"InCollection\",\n    film = \"Misc\",\n    forumPost = \"Misc\",\n    hearing = \"Misc\",\n    instantMessage = \"Misc\",\n    interview = \"Misc\",\n    journalArticle = \"Article\",\n    letter = \"Misc\",\n    magazineArticle = \"Article\",\n    newspaperArticle = \"Article\",\n    note = \"Misc\",\n    podcast = \"Misc\",\n    presentation = \"Misc\",\n    radioBroadcast = \"Misc\",\n    statute = \"Misc\",\n    thesis = \"Thesis\",\n    tvBroadcast = \"Misc\",\n    videoRecording = \"Misc\",\n}\n\n-- Conversion from zotero.sqlite to bib fields\n-- It's incomplete and accuracy isn't guaranteed!\nlocal _zbf = {\n    abstractNote = \"abstract\",\n    accessDate = \"urldate\",\n    applicationNumber = \"call-number\",\n    archiveLocation = \"archive_location\",\n    artworkMedium = \"medium\",\n    artworkSize = \"dimensions\",\n    attachment = \"file\",\n    audioFileType = \"medium\",\n    blogTitle = \"booktitle\",\n    bookTitle = \"booktitle\",\n    callNumber = \"call-number\",\n    code = \"booktitle\",\n    codeNumber = \"volume\",\n    codePages = \"pages\",\n    codeVolume = \"volume\",\n    conferenceName = \"event\",\n    court = \"authority\",\n    date = \"issued\",\n    issueDate = \"issued\",\n    dictionaryTitle = \"booktitle\",\n    distributor = \"publisher\",\n    encyclopediaTitle = \"booktitle\",\n    extra = \"note\",\n    filingDate = \"submitted\",\n    forumTitle = \"booktitle\",\n    genre = \"type\",\n    history = \"references\",\n    institution = \"publisher\",\n    interviewMedium = \"medium\",\n    issue = \"number\",\n    issuingAuthority = \"authority\",\n    legalStatus = \"status\",\n    legislativeBody = \"authority\",\n    libraryCatalog = \"source\",\n    meetingName = \"event\",\n    numPages = \"pages\",\n    numberOfVolumes = \"volume\",\n    place = \"address\",\n    priorityNumbers = \"issue\",\n    proceedingsTitle = \"booktitle\",\n    programTitle = \"booktitle\",\n    programmingLanguage = \"type\",\n    publicationTitle = \"booktitle\",\n    reporter = \"booktitle\",\n    runningTime = \"dimensions\",\n    seriesNumber = \"number\",\n    session = \"chapter-number\",\n    shortTitle = \"shorttitle\",\n    system = \"medium\",\n    thesisType = \"type\",\n    university = \"publisher\",\n    url = \"URL\",\n    versionNumber = \"version\",\n    websiteTitle = \"booktitle\",\n    websiteType = \"type\",\n}\n\nlocal _creators = {\n    \"editor\",\n    \"seriesEditor\",\n    \"translator\",\n    \"reviewedAuthor\",\n    \"artist\",\n    \"performer\",\n    \"composer\",\n    \"director\",\n    \"podcaster\",\n    \"cartographer\",\n    \"programmer\",\n    \"presenter\",\n    \"interviewee\",\n    \"interviewer\",\n    \"recipient\",\n    \"sponsor\",\n    \"inventor\",\n}\n\nlocal zwarn = require(\"zotcite\").zwarn\n\nlocal function expand_tilde(path)\n    if path:match(\"^~(/.*)\") then\n        local home = os.getenv(\"HOME\")\n        if not home then home = os.getenv(\"USERPROFILE\") end\n        if home then return path:gsub(\"~\", home, 1) end\n    end\n    return path\nend\n\n--- Check if a directory is writable\n---@param dir string The directory path\n---@return boolean\nlocal function is_directory(dir)\n    -- Can't use vim.uv.fs_access(dir, \"rw\") because it returns `true` for files\n    local fname = dir .. \"/Test_If_Dir_Is_Writable_By_Zotcite\"\n    local f = io.open(fname, \"w\")\n    if f then\n        f:close()\n        os.remove(fname)\n        return true\n    end\n    return false\nend\n\n-- Split a string 's' by a delimiter 'sep'\nlocal function str_split(s, sep)\n    local results = {}\n    for part in string.gmatch(s, \"([^\" .. sep .. \"]+)\") do\n        table.insert(results, part)\n    end\n    return results\nend\n\nlocal M = {}\n\n--- Reads profile.ini to find prefs.js and then find the values of `data_dir`\n--- and `attachment_dir`.\n---@return string?, string?\nlocal function get_zotero_prefs()\n    local p1 = vim.env.APPDATA and vim.env.APPDATA .. \"/Zotero/Zotero/profiles.ini\"\n        or expand_tilde(\"~/.zotero/zotero/profiles.ini\")\n    local zps = { p1, expand_tilde(\"~/Library/Application Support/Zotero/profiles.ini\") }\n    local zp = nil\n    for _, p in pairs(zps) do\n        if vim.uv.fs_access(p, \"r\") then\n            zp = p\n            break\n        end\n    end\n    if not zp then\n        zwarn(\"Could not find Zotero's `profiles.ini`\", true)\n        return\n    end\n\n    local adir\n    local zsql\n    local zotero_basedir = zp:match(\"^(.*)/.-\")\n    local lines = vim.fn.readfile(zp)\n    for _, line in pairs(lines) do\n        if line:find(\"Path=\") == 1 then\n            local zprofile = line:gsub(\"Path=\", \"\")\n            local zprefs = zotero_basedir .. \"/\" .. zprofile .. \"/\" .. \"prefs.js\"\n            if vim.uv.fs_access(zprefs, \"r\") then\n                local prefs = vim.fn.readfile(zprefs)\n                for _, pref in pairs(prefs) do\n                    if\n                        pref:find(\"extensions.zotero.baseAttachmentPath\")\n                        and pref:find(\"extensions.zotero.baseAttachmentPath\") > 0\n                    then\n                        adir = pref:match('.*\", \"(.*)\".*\\n')\n                    end\n                    if\n                        pref:find(\"extensions.zotero.dataDir\")\n                        and pref:find(\"extensions.zotero.dataDir\") > 0\n                    then\n                        local data_dir = pref:match('.*\", \"(.*)\".*')\n                        if vim.uv.fs_access(data_dir .. \"/zotero.sqlite\", \"r\") then\n                            zsql = data_dir .. \"/zotero.sqlite\"\n                        end\n                    end\n                end\n            end\n        end\n    end\n    return adir, zsql\nend\n\n---Define which Zotero collections each markdown document uses\n---@param d string The name of the markdown document\n---@param cl string[] The list of collections to be searched for citation keys when seeking references for the document 'd'.\nfunction M.set_collections(d, cl)\n    docs[d] = {}\n    for _, c in pairs(cl) do\n        if collections[c] then\n            table.insert(docs[d], c)\n        else\n            zwarn('Collection \"' .. c .. '\" not found in Zotero database.')\n        end\n    end\nend\n\n--- Check modification time of file\n---@param path string File path\n---@return integer\nlocal function getmtime(path)\n    -- TODO: Check how frequently this function is called by different completion plugins\n    -- local time_now = vim.uv.gettimeofday()\n    -- vim.notify(\"time now: \" .. tostring(time_now))\n    local fd = vim.uv.fs_open(path, \"r\", tonumber(\"0444\", 8))\n    if fd then\n        local fstat = vim.uv.fs_fstat(fd)\n        vim.uv.fs_close(fd)\n        if fstat then return fstat.mtime.sec end\n    end\n    return 0\nend\n\nlocal function copy_zotero_data()\n    local zf = config.zotero_sqlite_path\n    if not zf then return end\n    ztime = getmtime(zf)\n    zcopy = config.tmpdir .. \"/copy_of_zotero.sqlite\"\n    local zcopy_time = getmtime(zcopy)\n\n    -- Make a copy of zotero.sqlite to avoid locks\n    if ztime > zcopy_time then vim.uv.fs_copyfile(zf, zcopy) end\nend\n\n--- Run sqlite3 and get the output\n---@param query string The SQL query\n---@param sqlfile string | nil The path to the SQL data base\n---@return table | nil\nlocal function get_sql_data(query, sqlfile)\n    local sf = sqlfile and sqlfile or zcopy\n    local obj = vim.system({ \"sqlite3\", \"-json\", sf, query }, { text = true }):wait(3000)\n    if obj.code ~= 0 then\n        if sf and obj.code == 11 then\n            vim.uv.fs_utime(sf, 0, 0)\n            copy_zotero_data()\n        end\n        if obj.stderr then zwarn(string.format(\"[%d] %s\", obj.code, obj.stderr)) end\n        return nil\n    end\n    if not obj.stdout then return nil end\n    if obj.stdout == \"\" then return nil end\n    return vim.json.decode(obj.stdout)\nend\n\nlocal function get_collections()\n    collections = {}\n    local query = \"SELECT collections.collectionName, collectionItems.itemID \"\n        .. \"FROM collections, collectionItems \"\n        .. \"WHERE collections.collectionID = collectionItems.collectionID\"\n\n    local sql_data = get_sql_data(query)\n    if not sql_data then return end\n    for _, v in pairs(sql_data) do\n        if not collections[v.collectionName] then collections[v.collectionName] = {} end\n        table.insert(collections[v.collectionName], v.itemID)\n    end\nend\n\nlocal function get_items_key_type()\n    local query = \"SELECT items.itemID, items.dateAdded, items.key, itemTypes.typeName\"\n        .. \" FROM items, itemTypes\"\n        .. \" WHERE items.itemTypeID = itemTypes.itemTypeID\"\n\n    local sql_data = get_sql_data(query)\n    if not sql_data then return end\n    entry = {}\n    for _, v in pairs(sql_data) do\n        if\n            v.typeName ~= \"attachment\"\n            and v.typeName ~= \"annotation\"\n            and v.typeName ~= \"note\"\n        then\n            entry[v.itemID] =\n                { zotkey = v.key, etype = v.typeName, added = v.dateAdded, alastnm = \"\" }\n        end\n    end\nend\n\nlocal function add_most_fields()\n    local query = \"SELECT items.itemID, fields.fieldName, itemDataValues.value\"\n        .. \"  FROM items, fields, itemData, itemDataValues\"\n        .. \"  WHERE items.itemID = itemData.itemID\"\n        .. \"    and itemData.fieldID = fields.fieldID\"\n        .. \"    and itemData.valueID = itemDataValues.valueID\"\n    local sql_data = get_sql_data(query)\n    if not sql_data then return end\n    for _, v in pairs(sql_data) do\n        if entry[v.itemID] then entry[v.itemID][v.fieldName] = v.value end\n    end\nend\n\nlocal function add_authors()\n    local query = \"SELECT items.itemID, creatorTypes.creatorType, creators.lastName, creators.firstName\"\n        .. \"  FROM items, itemCreators, creators, creatorTypes\"\n        .. \"  WHERE items.itemID = itemCreators.itemID\"\n        .. \"    and itemCreators.creatorID = creators.creatorID\"\n        .. \"    and itemCreators.creatorTypeID = creatorTypes.creatorTypeID\"\n\n    local sql_data = get_sql_data(query)\n    if not sql_data then return end\n    for _, v in pairs(sql_data) do\n        if entry[v.itemID] ~= nil then\n            if entry[v.itemID][v.creatorType] ~= nil then\n                table.insert(entry[v.itemID][v.creatorType], { v.lastName, v.firstName })\n            else\n                entry[v.itemID][v.creatorType] = { { v.lastName, v.firstName } }\n            end\n            -- Special field for citation seeking\n            if v.creatorType == \"author\" then\n                entry[v.itemID].alastnm = entry[v.itemID].alastnm .. \", \" .. v.lastName\n            else\n                local sought = { \"author\" }\n                for _, c in pairs(_creators) do\n                    if v.creatorType == c then\n                        local flag = false\n                        for _, s in pairs(sought) do\n                            if entry[v.itemID][s] ~= nil then\n                                flag = true\n                                break\n                            end\n                        end\n                        if not flag then\n                            entry[v.itemID].alastnm = entry[v.itemID].alastnm\n                                .. \", \"\n                                .. v.lastName\n                        end\n                    end\n                    table.insert(sought, c)\n                end\n            end\n        end\n    end\n\n    for _, v in pairs(entry) do\n        v.alastnm = v.alastnm:gsub(\"^, \", \"\")\n    end\nend\n\nlocal function get_year(e)\n    local y\n    if e.date then y = e.date:match(\"^([0-9][0-9][0-9][0-9])\") end\n    if not y and e.issueDate then y = e.issueDate:match(\"^([0-9][0-9][0-9][0-9])\") end\n    if y then\n        return y\n    else\n        return \"????\"\n    end\nend\n\nlocal function calculate_ck(v, has_a, has_t, has_y)\n    local key = cite_template\n    if has_a then\n        local lastname = \"No_author\"\n        local lastnames = \"No_author\"\n        local creators = { \"author\" }\n        for _, x in pairs(_creators) do\n            table.insert(creators, x)\n        end\n        local n = 0\n        local lnms = {}\n        for _, c in pairs(creators) do\n            if v[c] then\n                lastname = v[c][1][1]\n                for _, ln in pairs(v[c]) do\n                    table.insert(lnms, ln[1])\n                    n = n + 1\n                end\n                break\n            end\n        end\n        if n > 3 then\n            lastnames = lnms[1] .. \"-etal\"\n        else\n            if n > 0 then lastnames = table.concat(lnms, \"-\") end\n        end\n        lastname = lastname:gsub(\"%W\", \"\")\n        key = key:gsub(\"%{author%}\", lastname:lower(), 1)\n        key = key:gsub(\"%{Author%}\", lastname, 1)\n        key = key:gsub(\"%{authors%}\", lastnames:lower(), 1)\n        key = key:gsub(\"%{Authors%}\", lastnames, 1)\n    end\n\n    if has_t then\n        local ttl = v.title:gsub(\"[,;:\\\\.!?].*\", \"\")\n        ttl = ttl:gsub(\"%s%s*\", \" \")\n        local titlew = \"\"\n        local ttl_ls = vim.split(ttl, \" \")\n        for _, t in pairs(ttl_ls) do\n            if not vim.tbl_contains(banned_words, t:lower()) then\n                titlew = t\n                break\n            end\n        end\n        key = key:gsub(\"%{title%}\", titlew:lower())\n        key = key:gsub(\"%{Title%}\", titlew)\n    end\n\n    if has_y then\n        key = key:gsub(\"%{year%}\", v.year:gsub(\"^[0-9][0-9]\", \"\"))\n        key = key:gsub(\"%{Year%}\", v.year)\n    end\n\n    -- Delete punctuation marks\n    key = key:gsub(\"[%./ -,:-@\\\\[-`{-~]\", \"\")\n    return key\nend\n\nlocal function calculate_citekeys()\n    local ct = cite_template:lower()\n    local has_a = ct:find(\"author\") and true or false\n    local has_t = ct:find(\"title\") and true or false\n    local has_y = ct:find(\"year\") and true or false\n    for _, v in pairs(entry) do\n        v.year = get_year(v)\n        if not v.title then v.title = \"???\" end\n        if not v.citekey then v.citekey = calculate_ck(v, has_a, has_t, has_y) end\n    end\nend\n\nlocal function get_sequence_string(n)\n    local alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n    local s = \"\"\n    while n > 0 do\n        local remainder = (n - 1) % 26\n        s = string.sub(alphabet, remainder + 1, remainder + 1) .. s\n        n = math.floor((n - 1) / 26)\n    end\n    return s\nend\n\nlocal function add_citekeys()\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    if kt == \"better-bibtex\" then\n        local missing_ck = {}\n        for _, v in pairs(entry) do\n            if v.citationKey then\n                v.citekey = v.citationKey\n            else\n                table.insert(\n                    missing_ck,\n                    vim.inspect(v.author) .. \" \" .. vim.inspect(v.title)\n                )\n            end\n        end\n\n        if #missing_ck > 40 then\n            zwarn(\"Missing 'Citation Key' for \" .. tostring(#missing_ck) .. \" entries\")\n        elseif #missing_ck > 0 then\n            zwarn(\"Missing 'Citation Key' for:\\n\" .. table.concat(missing_ck, \"\\n\"))\n        end\n    end\n\n    calculate_citekeys()\n    if kt == \"template\" then\n        -- Fix duplicates\n        for k1, v1 in pairs(entry) do\n            local dup = { v1 }\n            for k2, v2 in pairs(entry) do\n                if k1 ~= k2 and v1.citekey == v2.citekey then table.insert(dup, v2) end\n            end\n            if #dup > 1 then\n                table.sort(dup, function(a, b) return a.added > b.added end)\n                local i = 1\n                for _, v in pairs(dup) do\n                    v.citekey = v.citekey .. get_sequence_string(i)\n                    i = i + 1\n                end\n            end\n        end\n    end\nend\n\nlocal function delete_items()\n    local sql_data = get_sql_data(\"SELECT itemID FROM deletedItems\")\n    if not sql_data then return end\n    for _, v in pairs(sql_data) do\n        entry[v.itemID] = nil\n        for k, _ in pairs(collections) do\n            for i, c in pairs(collections[k]) do\n                if c == v.itemID then\n                    table.remove(collections[k], i)\n                    break\n                end\n            end\n        end\n    end\nend\n\nlocal function sanitize_markdown(s)\n    s = s:gsub(\"%[\", \"\\\\[\")\n    s = s:gsub(\"%]\", \"\\\\]\")\n    s = s:gsub(\"@\", \"\\\\@\")\n    s = s:gsub(\"%*\", \"\\\\*\")\n    s = s:gsub(\"_\", \"\\\\_\")\n    return s\nend\n\nlocal function sanitize_latex(s)\n    s = s:gsub(\"\\\\\", \"TeXtBacKsLasH\")\n    s = s:gsub(\"%%\", \"\\\\%%\")\n    s = s:gsub(\"&\", \"\\\\&\")\n    s = s:gsub(\"%$\", \"\\\\$\")\n    s = s:gsub(\"#\", \"\\\\#\")\n    s = s:gsub(\"_\", \"\\\\_\")\n    s = s:gsub(\"{\", \"\\\\{\")\n    s = s:gsub(\"}\", \"\\\\}\")\n    s = s:gsub(\"~\", \"\\\\textasciitilde{}\")\n    s = s:gsub(\"%^\", \"\\\\textasciicircum{}\")\n    s = s:gsub(\"TeXtBacKsLasH\", \"\\\\textbackslash{}\")\n    return s\nend\n\nlocal function sanitize(s)\n    if vim.tbl_contains({ \"tex\", \"rnoweb\" }, vim.bo.filetype) then\n        return sanitize_latex(s)\n    end\n    return sanitize_markdown(s)\nend\n\n---@param item table The Zotero item\n---@param ktype string Type of citation key\nlocal function get_bib_ref(item, ktype)\n    local e = {}\n    e = vim.tbl_extend(\"force\", e, item)\n\n    -- Fix the type\n    if e[\"etype\"] and _zbt and _zbt[e[\"etype\"]] then\n        e[\"etype\"] = e[\"etype\"]:gsub(e[\"etype\"], _zbt[e[\"etype\"]])\n    end\n\n    -- Escape quotes of all fields\n    for f, v in pairs(e) do\n        if type(v) == \"string\" then e[f] = v:gsub('\"', '\\\\\"') end\n    end\n\n    -- Rename some fields\n    local ekeys = {}\n    for k, _ in pairs(e) do\n        table.insert(ekeys, k)\n    end\n    for _, f in pairs(ekeys) do\n        if _zbf[f] then\n            e[_zbf[f]] = e[f]\n            e[f] = nil\n        end\n    end\n\n    if e[\"etype\"] == \"Article\" and e[\"booktitle\"] then\n        e[\"journal\"] = e[\"booktitle\"]\n        e[\"booktitle\"] = nil\n    end\n    if e[\"etype\"] == \"InCollection\" and not e[\"editor\"] then e[\"etype\"] = \"InBook\" end\n\n    for _, aa in pairs({\n        \"title\",\n        \"journal\",\n        \"booktitle\",\n        \"journalAbbreviation\",\n        \"address\",\n        \"publisher\",\n    }) do\n        if e[aa] then\n            e[aa] = string.gsub(e[aa], '\\\\\"', '\"')\n            e[aa] = string.gsub(e[aa], \"\\\\\\\\\", \"\\1\")\n            e[aa] = string.gsub(e[aa], \"([&%%$#_%[%]{}])\", \"\\\\%1\")\n            e[aa] = string.gsub(e[aa], \"\\1\", \"{\\\\\\\\textbackslash}\")\n            e[aa] = string.gsub(e[aa], \"<i>(.-)</i>\", \"\\\\\\\\textit{%1}\")\n            e[aa] = string.gsub(e[aa], \"<b>(.-)</b>\", \"\\\\\\\\textbf{%1}\")\n            e[aa] = string.gsub(e[aa], \"<sub>(.-)</sub>\", \"$_{\\\\\\\\textrm{%1}}$\")\n            e[aa] = string.gsub(e[aa], \"<sup>(.-)</sup>\", \"$^{\\\\\\\\textrm{%1}}$\")\n            e[aa] = string.gsub(\n                e[aa],\n                '<span style=\"font%-variant:small%-caps;\">(.-)</span>',\n                \"\\\\\\\\textsc{%1}\"\n            )\n            e[aa] = string.gsub(e[aa], '<span class=\"nocase\">(.-)</span>', \"{%1}\")\n            e[aa] = string.gsub(e[aa], \"\\n\", \" \")\n        end\n    end\n\n    local ekey = ktype == \"zotero\" and e.zotkey or e.citekey\n    local ref = { \"@\" .. e[\"etype\"] .. \"{\" .. ekey .. \",\" }\n    for _, aa in pairs({\n        \"author\",\n        \"editor\",\n        \"contributor\",\n        \"translator\",\n        \"container-author\",\n    }) do\n        if e[aa] then\n            local names = {}\n            for _, pair in pairs(e[aa]) do\n                local last, first = pair[1], pair[2]\n                table.insert(names, last .. \", \" .. first)\n            end\n            table.insert(\n                ref,\n                \"  \" .. aa .. \" = {\" .. table.concat(names, \" and \") .. \"},\"\n            )\n        end\n    end\n    if e[\"issued\"] then\n        local ds = e[\"issued\"]\n        ds = ds:gsub(\" .*\", \"\")\n        local d = str_split(ds, \"-\")\n        if d[1] ~= \"0000\" then\n            table.insert(ref, \"  year = {\" .. e[\"year\"] .. \"},\")\n            if d[2] ~= \"00\" then table.insert(ref, \"  month = {\" .. d[2] .. \"},\") end\n            if d[3] ~= \"00\" then table.insert(ref, \"  day = {\" .. d[3] .. \"},\") end\n        end\n    end\n    if e[\"urldate\"] then e[\"urldate\"] = string.gsub(e[\"urldate\"], \" .*\", \"\") end\n    if e[\"pages\"] then\n        e[\"pages\"] = string.gsub(e[\"pages\"], \"([0-9])-([0-9])\", \"%1--%2\")\n    end\n    local dont = {\n        \"etype\",\n        \"issued\",\n        \"abstract\",\n        \"collection\",\n        \"author\",\n        \"editor\",\n        \"contributor\",\n        \"translator\",\n        \"alastnm\",\n        \"container-author\",\n        \"year\",\n    }\n    for _, v in pairs(exclude_fields or {}) do\n        table.insert(dont, v)\n    end\n\n    for f, val in pairs(e) do\n        local skip = false\n        for _, d in pairs(dont) do\n            if f == d then\n                skip = true\n                break\n            end\n        end\n        if not skip then\n            local v = tostring(val):gsub(\"\\n\", \" \")\n            table.insert(ref, \"  \" .. f .. \" = {\" .. v .. \"},\")\n        end\n    end\n    table.insert(ref, \"}\")\n    table.insert(ref, \"\")\n    return ref\nend\n\n--- Build the contents of a .bib file\n---@param keys string[] List of Zotero keys\n---@param ktype string Type of citation key\n---@return table\nlocal function get_bib(keys, ktype)\n    local ref = {}\n    for _, k in pairs(keys) do\n        for _, e in pairs(entry) do\n            local key = ktype == \"zotero\" and e.zotkey or e.citekey\n            if k == key then ref[k] = get_bib_ref(e, ktype) end\n        end\n    end\n    return ref\nend\n\n--- Build the contents of a .bib file\n---@param zkeys string[] List of Zotero keys\n---@param bibf string Name of bib file\n---@param ktype string Type of citation key\n---@param verbose boolean Whether to print debugging information or not\nfunction M.update_bib(zkeys, bibf, ktype, verbose)\n    local bib = {}\n\n    local f = io.open(bibf, \"r\")\n    if f then\n        if verbose then zwarn('zotcite: updating \"' .. tostring(bibf) .. '\"\\n') end\n        local key = nil\n        for line in f:lines() do\n            if string.sub(line, 1, 1) == \"@\" then\n                local clean_line = string.gsub(line, \",%s*$\", \"\")\n                key = string.gsub(clean_line, \"^@.*{\", \"\")\n                bib[key] = {}\n            end\n            if key then table.insert(bib[key], line) end\n        end\n        f:close()\n    else\n        if verbose then zwarn('zotcite: writing \"' .. tostring(bibf) .. '\"\\n') end\n        bib = get_bib(zkeys, ktype)\n    end\n\n    -- Replace existing references and add new ones\n    local newbib = get_bib(zkeys, ktype)\n    for k, v in pairs(newbib) do\n        bib[k] = v\n    end\n\n    f = io.open(bibf, \"w\")\n    if f then\n        for _, v in pairs(bib) do\n            f:write(table.concat(v, \"\\n\") .. \"\\n\")\n        end\n        f:close()\n    end\nend\n\n---Return list of attachments associated with the citation key\n---@param key string The citation key\n---@return table | nil, string\nfunction M.get_attachment(key)\n    local attachments = {}\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local field = kt == \"zotero\" and \"zotkey\" or \"citekey\"\n    for k, _ in pairs(entry) do\n        if entry[k][field] == key then\n            local query = \"SELECT items.itemID, items.key, itemAttachments.path\"\n                .. \" FROM items, itemAttachments\"\n                .. \" WHERE items.itemID = itemAttachments.itemID and itemAttachments.parentItemID = '\"\n                .. k\n                .. \"'\"\n            local sql_data = get_sql_data(query)\n            if not sql_data then return nil, \"SQL query failed\" end\n            for _, v in pairs(sql_data) do\n                if type(v.path) == \"string\" then\n                    table.insert(attachments, v)\n                else\n                    zwarn(\"Path is not a string: \" .. vim.inspect(v.path))\n                end\n            end\n\n            if #attachments == 0 then return nil, \"No attachments found\" end\n            return attachments, \"\"\n        end\n    end\n    return nil, \"Citation key not found\"\nend\n\nfunction M.get_all_citations()\n    -- Return a list of all [zotkey, citekey].\n    local res = {}\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    if kt == \"zotero\" then\n        for _, e in pairs(entry) do\n            res[e.zotkey] = e.citekey\n        end\n    else\n        for k, e in pairs(entry) do\n            if e.citekey and e.zotkey then\n                res[e.citekey] = e.zotkey\n            else\n                zwarn(\"Missing citation key for itemID \" .. tostring(k))\n            end\n        end\n    end\n    return res\nend\n\nlocal get_ref_data_template = function(citekey)\n    for _, v in pairs(entry) do\n        if v.citekey == citekey then return v end\n    end\n    return nil\nend\n\nlocal get_ref_data_zotkey = function(zotkey)\n    for _, v in pairs(entry) do\n        if v.zotkey == zotkey then return v end\n    end\n    return nil\nend\n\nfunction M.get_ref_data(key)\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    if kt == \"zotero\" then\n        return get_ref_data_zotkey(key)\n    else\n        return get_ref_data_template(key)\n    end\nend\n\nlocal get_ft_lang = function()\n    if vim.tbl_contains({ \"tex\", \"rnoweb\" }, vim.bo.filetype) then\n        return \"latex\"\n    elseif vim.bo.filetype == \"typst\" then\n        return \"typst\"\n    end\n    return \"markdown\"\nend\n\n--- Get year-page separator\n---@param lang string\n---@return string\nlocal function get_ypsep(lang)\n    local ypsep = config.year_page_sep\n    if not ypsep then\n        if lang == \"markdown\" then\n            ypsep = \", p. \"\n        elseif lang == \"typst\" then\n            ypsep = \"p. \"\n        else\n            ypsep = \"p.~\"\n        end\n    end\n    return ypsep\nend\n\nlocal get_key_id = function(zotkey)\n    local key_id = nil\n    for k, v in pairs(entry) do\n        if v.zotkey == zotkey then\n            key_id = k\n            break\n        end\n    end\n    return key_id\nend\n\n--- Return user annotations made using Zotero's PDF viewer.\n---@param key string\n---@param offset integer\n---@return string[] | nil\nfunction M.get_annotations(key, offset)\n    local lang = get_ft_lang()\n    if not config.zotero_sqlite_path then return end\n    copy_zotero_data()\n\n    local key_id = get_key_id(key)\n    if not key_id then return end\n\n    local query = \"SELECT itemAttachments.itemID, itemAttachments.parentItemID,\"\n        .. \"\\n  itemAnnotations.parentItemID, itemAnnotations.type,\"\n        .. \"\\n  itemAnnotations.position, itemAnnotations.pageLabel,\"\n        .. \"\\n  itemAnnotations.authorName, itemAnnotations.text,\"\n        .. \"\\n  itemAnnotations.comment\"\n        .. \"\\nFROM itemAttachments, itemAnnotations\"\n        .. \"\\nWHERE itemAttachments.parentItemID = \"\n        .. key_id\n        .. \" and itemAnnotations.parentItemID = itemAttachments.ItemID\"\n    local sql_data = get_sql_data(query)\n    if not sql_data then return end\n\n    local kt = require(\"zotcite.config\").get_key_type(vim.api.nvim_get_current_buf())\n    local ckey = kt == \"zotero\" and key or entry[key_id].citekey\n    -- Year-page separator\n    local s = get_ypsep(lang)\n\n    local notes = {}\n    for _, v in pairs(sql_data) do\n        local position = vim.json.decode(v.position)\n        local page\n        if v.pageLabel ~= vim.NIL then\n            page = v.pageLabel\n        else\n            page = tostring(position.pageIndex + offset)\n        end\n        table.insert(notes, {\n            p = page,\n            pos_page = position.pageIndex,\n            pos_x = position.rects[1][1],\n            pos_y = position.rects[1][2],\n            c = v.comment ~= vim.NIL and v.comment,\n            t = v.text ~= vim.NIL and v.text,\n            type = v.type,\n        })\n    end\n    table.sort(notes, function(a, b)\n        if a.pos_page ~= b.pos_page then\n            return a.pos_page < b.pos_page\n        else\n            return a.pos_y > b.pos_y\n        end\n    end)\n    local lines = {}\n    for _, v in pairs(notes) do\n        if v.c then\n            local txt = sanitize(v.c)\n            if lang == \"latex\" then\n                txt =\n                    string.format(\"%s [comment on \\\\citet[%s%s]{%s}]\", txt, s, v.p, ckey)\n            elseif lang == \"typst\" then\n                txt = string.format(\n                    '%s [comment on #cite(<%s>, supplement: \"%s%s\")]',\n                    txt,\n                    ckey,\n                    s,\n                    v.p\n                )\n            else\n                txt = string.format(\"%s [comment on @%s%s%s]\", txt, ckey, s, v.p)\n            end\n            table.insert(lines, txt)\n            table.insert(lines, \"\")\n        end\n        if v.t then\n            local txt = sanitize(v.t)\n            if lang == \"latex\" then\n                table.insert(lines, \"\\\\begin{quote}\")\n                txt = string.format(\"%s \\\\cite[%s%s]{%s}\", txt, s, v.p, ckey)\n                table.insert(lines, txt)\n                table.insert(lines, \"\\\\end{quote}\")\n            elseif lang == \"typst\" then\n                txt = string.format(\n                    '#quote[%s] #cite(<%s>, supplement: \"%s%s\")',\n                    txt,\n                    ckey,\n                    s,\n                    v.p\n                )\n                table.insert(lines, txt)\n            else\n                txt = string.format(\"> %s [@%s%s%s]\", txt, ckey, s, v.p)\n                table.insert(lines, txt)\n            end\n            table.insert(lines, \"\")\n        end\n    end\n\n    local repl = {}\n    for _, v in pairs(lines) do\n        if v:find(\"\\n\") then\n            local vlist = vim.split(v, \"\\n\")\n            for _, v2 in pairs(vlist) do\n                table.insert(repl, v2)\n            end\n        else\n            table.insert(repl, v)\n        end\n    end\n\n    return repl\nend\n\n--- Convert HTML to LaTeX\n---@param notes string\nlocal notes_to_tex = function(notes)\n    -- Year-page separator\n    local ypsep = get_ypsep(\"latex\")\n\n    notes = notes:gsub(\"<h1>(.-)</h1>\", \"\\\\section{%1}\\n\")\n    notes = notes:gsub(\"<h2>(.-)</h2>\", \"\\\\subsection{%1}\\n\")\n    notes = notes:gsub(\"<h3>(.-)</h3>\", \"\\\\subsubsection{%1}\\n\")\n    notes = notes:gsub(\"<h4>(.-)</h4>\", \"\\\\subsubsection{%1}\\n\")\n    notes = notes:gsub(\"<h5>(.-)</h5>\", \"\\\\subsubsection{%1}\\n\")\n    notes = notes:gsub(\"<strong>(.-)</strong>\", \"\\\\textbf{%1}\")\n    notes = notes:gsub(\"<b>(.-)</b>\", \"\\\\textbf{%1}\")\n    notes = notes:gsub(\"<em>(.-)</em>\", \"\\\\em{%1}\")\n    notes = notes:gsub(\"<i>(.-)</i>\", \"\\\\em{%1}\")\n    notes = notes:gsub(\n        '<span style=\"text%-decoration: line%-through\">(.-)</span>',\n        \"\\\\strikethrough{%1}\"\n    )\n    notes = notes:gsub(' rel=\"noopener noreferrer nofollow\"', \"\")\n    notes = notes:gsub('<a href=\"(.-)\">(.-)</a>', \"\\\\href{%1}{%2}\")\n    notes = notes:gsub('%(<span class=\"citation%-item\">.-</span>%)', \"\")\n    notes = notes:gsub(\n        '<span class=\"citation\" data%-citation=\".-items%%2F(.-)%%.-locator%%22%%3A%%22(.-)%%22.-\">.-</span>',\n        \"\\\\cite[\" .. ypsep .. \"%2]{%1}\"\n    )\n    notes = notes:gsub(\n        '<span class=\"citation\" data%-citation=\".-items%%2F(.-)%%.-\">',\n        \"\\\\cite{%1}\"\n    )\n    notes = notes:gsub(\"<li>%s*(.-)%s*</li>\", \"\\n  \\\\item %1\")\n    notes = notes:gsub(\"<ul>(.-)</ul>\", \"\\n\\\\begin{itemize}%1\\\\end{itemize}\\n\")\n    notes = notes:gsub(\"<ol>(.-)</ol>\", \"\\n\\\\begin{enumerate}%1\\\\end{enumerate}\\n\")\n    notes = notes:gsub(\n        \"<blockquote>%s*(.-)%s*</blockquote>\",\n        \"\\n\\\\begin{quote}\\n%1\\n\\\\end{quote}\\n\"\n    )\n    notes = notes:gsub('<pre class=\"math\">(.-)</pre>', \"\\n%1\\n\")\n    notes = notes:gsub(\"<pre>(.-)</pre>\", \"\\n\\\\begin{verbatim}\\n%1\\nend{verbatim}\\n\")\n    notes = notes:gsub(\"<br/>\", \"\\\\linebreak\\n\")\n    notes = notes:gsub(\"<br>\", \"\\\\linebreak\\n\")\n    notes = notes:gsub(\"<p>(.-)</p>\", \"%1\\n\\n\")\n    notes = notes:gsub(' class=\"highlight\" data%-annotation=\".-\"(.-)', \"\")\n    notes = notes:gsub(\"<div .->\", \"\")\n    notes = notes:gsub(\"</div>\", \"\")\n    notes = notes:gsub(\"<span>\", \"\")\n    notes = notes:gsub(\"</span>\", \"\")\n    notes = notes:gsub(\"\\n\\n\\n\", \"\\n\\n\")\n    return notes .. \"\\n\"\nend\n\n--- Convert HTML to Markdown\n---@param notes string\nlocal notes_to_md = function(notes)\n    -- Year-page separator\n    local ypsep = get_ypsep(\"markdown\")\n\n    notes = notes:gsub(\"<h1>(.-)</h1>\", \"# %1\\n\")\n    notes = notes:gsub(\"<h2>(.-)</h2>\", \"## %1\\n\")\n    notes = notes:gsub(\"<h3>(.-)</h3>\", \"### %1\\n\")\n    notes = notes:gsub(\"<h4>(.-)</h4>\", \"#### %1\\n\")\n    notes = notes:gsub(\"<h5>(.-)</h5>\", \"##### %1\\n\")\n    notes = notes:gsub(\"<strong>(.-)</strong>\", \"**%1**\")\n    notes = notes:gsub(\"<b>(.-)</b>\", \"**%1**\")\n    notes = notes:gsub(\"<em>(.-)</em>\", \"*%1*\")\n    notes = notes:gsub(\"<i>(.-)</i>\", \"*%1*\")\n    notes =\n        notes:gsub('<span style=\"text%-decoration: line%-through\">(.-)</span>', \"~~%1~~\")\n    notes = notes:gsub(' rel=\"noopener noreferrer nofollow\"', \"\")\n    notes = notes:gsub('<a href=\"(.-)\">(.-)</a>', \"[%2](%1)\")\n    notes = notes:gsub('%(<span class=\"citation%-item\">.-</span>%)', \"\")\n    notes = notes:gsub(\n        '<span class=\"citation\" data%-citation=\".-items%%2F(.-)%%.-locator%%22%%3A%%22(.-)%%22.-\">.-</span>',\n        \"[@%1\" .. ypsep .. \"%2]\"\n    )\n    notes =\n        notes:gsub('<span class=\"citation\" data%-citation=\".-items%%2F(.-)%%.-\">', \"@%1\")\n    notes = notes:gsub(\"<li>%s*(.-)%s*</li>\", \"\\n  - %1\")\n    notes = notes:gsub(\"<ul>(.-)</ul>\", \"\\n%1\\n\")\n    notes = notes:gsub(\"<ol>(.-)</ol>\", \"\\n%1\\n\")\n    notes = notes:gsub(\"<blockquote>%s*(.-)%s*</blockquote>\", \"\\n> %1\\n\")\n    notes = notes:gsub('<pre class=\"math\">(.-)</pre>', \"\\n%1\\n\")\n    notes = notes:gsub(\"<pre>(.-)</pre>\", \"\\n```\\n%1\\n```\\n\")\n    notes = notes:gsub(\"<br/>\", \"\\n\\n\")\n    notes = notes:gsub(\"<br>\", \"\\n\\n\")\n    notes = notes:gsub(\"<p>(.-)</p>\", \"%1\\n\\n\")\n    notes = notes:gsub(' class=\"highlight\" data%-annotation=\".-\"(.-)', \"\")\n    notes = notes:gsub(\"<div .->\", \"\")\n    notes = notes:gsub(\"</div>\", \"\")\n    notes = notes:gsub(\"<span>\", \"\")\n    notes = notes:gsub(\"</span>\", \"\")\n    notes = notes:gsub(\"\\n\\n\\n\", \"\\n\\n\")\n    return notes .. \"\\n\"\nend\n\n--- Convert HTML to Typst\n---@param notes string\nlocal notes_to_typ = function(notes)\n    -- Year-page separator\n    local ypsep = get_ypsep(\"typst\")\n\n    notes = notes:gsub(\"<h1>(.-)</h1>\", \"= %1\\n\")\n    notes = notes:gsub(\"<h2>(.-)</h2>\", \"== %1\\n\")\n    notes = notes:gsub(\"<h3>(.-)</h3>\", \"=== %1\\n\")\n    notes = notes:gsub(\"<h4>(.-)</h4>\", \"==== %1\\n\")\n    notes = notes:gsub(\"<h5>(.-)</h5>\", \"===== %1\\n\")\n    notes = notes:gsub(\"<strong>(.-)</strong>\", \"*%1*\")\n    notes = notes:gsub(\"<b>(.-)</b>\", \"*%1*\")\n    notes = notes:gsub(\"<em>(.-)</em>\", \"_%1_\")\n    notes = notes:gsub(\"<i>(.-)</i>\", \"_%1_\")\n    notes =\n        notes:gsub('<span style=\"text%-decoration: line%-through\">(.-)</span>', \"~~%1~~\")\n    notes = notes:gsub(' rel=\"noopener noreferrer nofollow\"', \"\")\n    notes = notes:gsub('<a href=\"(.-)\">(.-)</a>', '#link(\"%1\")[%2]')\n    notes = notes:gsub('%(<span class=\"citation%-item\">.-</span>%)', \"\")\n    notes = notes:gsub(\n        '<span class=\"citation\" data%-citation=\".-items%%2F(.-)%%.-locator%%22%%3A%%22(.-)%%22.-\">.-</span>',\n        '#cite(<%1>, supplement: \"' .. ypsep .. '%2\", form: \"normal\")'\n    )\n    notes =\n        notes:gsub('<span class=\"citation\" data%-citation=\".-items%%2F(.-)%%.-\">', \"@%1\")\n    notes = notes:gsub(\"<li>%s*(.-)%s*</li>\", \"\\n  - %1\")\n    notes = notes:gsub(\"<ul>(.-)</ul>\", \"\\n%1\\n\")\n    notes = notes:gsub(\"<ol>(.-)</ol>\", \"\\n%1\\n\")\n    notes = notes:gsub(\"<blockquote>%s*(.-)%s*</blockquote>\", \"\\n#quote[%1]\\n\")\n    notes = notes:gsub('<pre class=\"math\">(.-)</pre>', \"\\n%1\\n\")\n    notes = notes:gsub(\"<pre>(.-)</pre>\", \"\\n```\\n%1\\n```\\n\")\n    notes = notes:gsub(\"<br/>\", \"\\n\\n\")\n    notes = notes:gsub(\"<br>\", \"\\n\\n\")\n    notes = notes:gsub(\"<p>(.-)</p>\", \"%1\\n\\n\")\n    notes = notes:gsub(' class=\"highlight\" data%-annotation=\".-\"(.-)', \"\")\n    notes = notes:gsub(\"<div .->\", \"\")\n    notes = notes:gsub(\"</div>\", \"\")\n    notes = notes:gsub(\"<span>\", \"\")\n    notes = notes:gsub(\"</span>\", \"\")\n    notes = notes:gsub(\"\\n\\n\\n\", \"\\n\\n\")\n    return notes .. \"\\n\"\nend\n\n-- Return user notes from a reference.\n---@param key string The Zotero key\n---@return string | nil\nfunction M.get_notes(key)\n    if not config.zotero_sqlite_path then return end\n    copy_zotero_data()\n\n    local key_id = get_key_id(key)\n    if not key_id then return end\n\n    local query = \"SELECT parentItemID, note FROM itemNotes WHERE parentItemID = \"\n        .. tostring(key_id)\n    local sql_data = get_sql_data(query)\n    if not sql_data then return end\n\n    local notes = \"\"\n    for _, v in pairs(sql_data) do\n        notes = notes .. v.note\n    end\n    if notes == \"\" then return nil end\n\n    local lang = get_ft_lang()\n    notes = sanitize(notes)\n    if lang == \"typst\" then\n        notes = notes_to_typ(notes)\n    elseif lang == \"latex\" then\n        notes = notes_to_tex(notes)\n    else\n        notes = notes_to_md(notes)\n    end\n    return notes\nend\n\n--- Return information useful for debugging the application\n---@return table\nfunction M.info()\n    local ntypes = {}\n    local n = 0\n    for _, v in pairs(entry) do\n        n = n + 1\n        if ntypes[v.etype] then\n            ntypes[v.etype] = ntypes[v.etype] + 1\n        else\n            ntypes[v.etype] = 1\n        end\n    end\n\n    local r = {\n        [\"attach_dir\"] = config.attach_dir,\n        [\"zotero.sqlite\"] = config.zotero_sqlite_path,\n        [\"tmpdir\"] = config.tmpdir,\n        [\"docs\"] = docs,\n        [\"citation template\"] = cite_template,\n        [\"banned words\"] = table.concat(banned_words, \" \"),\n        [\"excluded fields\"] = table.concat(exclude_fields, \", \"),\n        [\"n refs\"] = n,\n        [\"types\"] = ntypes,\n    }\n    return r\nend\n\nlocal function load_zotero_data()\n    if not config.zotero_sqlite_path then return end\n    copy_zotero_data()\n\n    get_collections()\n    get_items_key_type()\n    delete_items()\n    add_most_fields()\n    add_authors()\n    add_citekeys()\nend\n\n--- Find citation key and return list of completions\n---@param ptrn string Search pattern\n---@param d string Buffer name\n---@return table\nfunction M.get_match(ptrn, d)\n    if getmtime(config.zotero_sqlite_path) > ztime then load_zotero_data() end\n\n    local keys = {}\n    if docs[d] then\n        for _, c in pairs(docs[d]) do\n            for _, v in pairs(collections[c]) do\n                table.insert(keys, v)\n            end\n        end\n    end\n    if #keys == 0 then\n        for k, _ in pairs(entry) do\n            table.insert(keys, k)\n        end\n    end\n\n    -- priority level\n    local p1, p2, p3, p4, p5, p6 = {}, {}, {}, {}, {}, {}\n\n    ptrn = ptrn:lower()\n    for _, v in ipairs(keys) do\n        local e = entry[v]\n        if e.citekey:lower():find(ptrn) == 1 then\n            table.insert(p1, e)\n        elseif e.alastnm and e.alastnm[1] and e.alastnm[1][1]:lower():find(ptrn) == 1 then\n            table.insert(p2, e)\n        elseif e.title and e.title:lower():find(ptrn) == 1 then\n            table.insert(p3, e)\n        elseif e.citekey:lower():find(ptrn) and e.citekey:lower():find(ptrn) > 1 then\n            table.insert(p4, e)\n        elseif\n            e.alastnm\n            and e.alastnm[1]\n            and e.alastnm[1][1]:lower():find(ptrn)\n            and e.alastnm[1][1]:lower():find(ptrn) > 1\n        then\n            table.insert(p5, e)\n        elseif\n            e.title\n            and e.title:lower():find(ptrn)\n            and e.title:lower():find(ptrn) > 1\n        then\n            table.insert(p6, e)\n        end\n    end\n\n    local resp = {}\n    for _, v in pairs(p1) do\n        table.insert(resp, v)\n    end\n    for _, v in pairs(p2) do\n        table.insert(resp, v)\n    end\n    for _, v in pairs(p3) do\n        table.insert(resp, v)\n    end\n    for _, v in pairs(p4) do\n        table.insert(resp, v)\n    end\n    for _, v in pairs(p5) do\n        table.insert(resp, v)\n    end\n    for _, v in pairs(p6) do\n        table.insert(resp, v)\n    end\n    return resp\nend\n\n--- Get Zotero data\n---@return boolean\nfunction M.init()\n    -- Template for citation keys\n    cite_template = config.citation_template\n    if not cite_template then cite_template = \"{Authors}-{Year}\" end\n\n    -- Title words to be ignored\n    if config.banned_words then\n        banned_words = vim.split(config.banned_words, \" \")\n    else\n        banned_words =\n            { \"a\", \"an\", \"the\", \"some\", \"from\", \"on\", \"in\", \"to\", \"of\", \"do\", \"with\" }\n    end\n\n    -- Path to zotero.sqlite\n    if config.zotero_sqlite_path then\n        if not vim.uv.fs_access(config.zotero_sqlite_path, \"r\") then\n            local msg = 'Please, check if the config option `zotero_sqlite_path` is set correctly: \"'\n                .. config.zotero_sqlite_path\n                .. '\" not found.'\n            zwarn(msg)\n            return false\n        end\n    end\n\n    -- Path to attachments directory\n    if config.attach_dir and not is_directory(config.attach_dir) then\n        local msg = \"Please, fix the value `attach_dir` in your config. The directory \"\n            .. config.attach_dir\n            .. \" is not writable.\"\n        zwarn(msg)\n        return false\n    end\n\n    if not config.zotero_sqlite_path then\n        local adir, zdir = get_zotero_prefs()\n        if adir and not config.attach_dir then config.attach_dir = adir end\n        if zdir then\n            config.zotero_sqlite_path = zdir\n        else\n            return false\n        end\n    end\n\n    -- Temporary directory\n    if not config.tmpdir then\n        if os.getenv(\"XDG_CACHE_HOME\") then\n            config.tmpdir = os.getenv(\"XDG_CACHE_HOME\") .. \"/zotcite\"\n        elseif os.getenv(\"APPDATA\") then\n            config.tmpdir = os.getenv(\"APPDATA\") .. \"/zotcite\"\n        elseif is_directory(expand_tilde(\"~/.cache\")) then\n            config.tmpdir = expand_tilde(\"~/.cache/zotcite\")\n        elseif is_directory(expand_tilde(\"~/Library/Caches\")) then\n            config.tmpdir = expand_tilde(\"~/Library/Caches/zotcite\")\n        else\n            config.tmpdir = \"/tmp/.zotcite\"\n        end\n    end\n\n    if not is_directory(config.tmpdir) then\n        if vim.fn.mkdir(config.tmpdir, \"p\", \"0o700\") == 0 then\n            zwarn(\"Error creating directory '\" .. config.tmpdir .. \"'\")\n            return false\n        end\n        if not is_directory(config.tmpdir) then\n            zwarn(\n                'Please, either set or fix the value of `tmpdir` in your zotcite config: \"'\n                    .. config.tmpdir\n                    .. '\" is not writable.'\n            )\n            return false\n        end\n    end\n\n    -- Fields that should not be added to the bib entries:\n    local zexcl = config.exclude_fields\n    if not zexcl then\n        exclude_fields = {}\n    else\n        exclude_fields = str_split(zexcl, \" \")\n    end\n\n    load_zotero_data()\n\n    return true\nend\n\nreturn M\n"
  },
  {
    "path": "plugin/zotcite.lua",
    "content": "local did_plugin = false\nif did_plugin then return end\ndid_plugin = true\nvim.api.nvim_create_user_command(\"Zinfo\", \"lua require('zotcite.get').zotero_info()\", {})\n"
  },
  {
    "path": "scripts/abntfix.py",
    "content": "#!/usr/bin/env python3\n\n\"\"\"\nPandoc filter to fix ABNT citations.\n\"\"\"\n\nimport sys\nimport io\nimport json\n\ndef TitleCase(x):\n    if x in [ 'et', 'al.', 'a', 'an', 'and', 'in', 'the', 'de', 'do', 'da',\n             'dos', 'das', 'com', 'na', 'no', 'nas', 'nos', 'e', 'um', 'uma']:\n        return x\n    return x.title()\n\ndef WalkFix(x):\n    if isinstance(x, dict) and 't' in x.keys() and  x['t'] == 'Cite' and x['c'][0][0]['citationMode']['t'] == 'AuthorInText':\n        ultimo = 1000\n        for s, vs in enumerate(x['c'][1]):\n            if vs['t'] == 'Str':\n                vs['c'] = TitleCase(vs['c'])\n                if vs['c'].find(';') > -1:\n                    ultimo = s\n                    vs['c'] = vs['c'].replace(\";\", \",\")\n        if ultimo < 1000:\n            x['c'][1][ultimo]['c'] = x['c'][1][ultimo]['c'].replace(\",\", \" e\")\n    else:\n        if isinstance(x, dict) and 'c' in x.keys() and isinstance(x['c'], list):\n            for y in x['c']:\n                WalkFix(y)\n        else:\n            if isinstance(x, list):\n                for y in x:\n                    WalkFix(y)\n\nif __name__ == \"__main__\":\n    sys.stderr.write('Running abntfix...\\n')\n    sys.stderr.flush()\n\n    # Get json from pandoc (stdin)\n    i = sys.stdin.read()\n    j = json.load(io.StringIO(i))\n\n    WalkFix(j['blocks'])\n\n    # Print the json representation of the new document\n    sys.stdout.write(json.dumps(j))\n"
  },
  {
    "path": "scripts/apafix",
    "content": "The R package rmdfiltr includes an ampersand replacement filter:\nhttps://cran.r-project.org/web/packages/rmdfiltr/index.html\n"
  },
  {
    "path": "scripts/odt2md.py",
    "content": "#!/usr/bin/env python3\n\n\"\"\"\nConvert an ODT file into Markdown, converting citations into zotcite format.\n\"\"\"\n\nimport sys\nimport subprocess\nimport re\nimport json\nfrom pathlib import Path\nfrom zotero import ZoteroEntries\n\nif __name__ == \"__main__\":\n    cmd = ['pandoc', sys.argv[1], '-t', 'markdown']\n    doc = subprocess.run(cmd, capture_output=True, text=True).stdout\n    z = ZoteroEntries()\n    while True:\n        res = re.search(\n            r\"\\[\\]{#ZOTERO_ITEM CSL_CITATION\\s(.*?),\\\\\\\"schema\\\\\\\":\\\\\\\"[\\w:/\\.-]*?\\\\\\\"}\\s\\w+}\\(.*?\\)\", doc, re.DOTALL)\n        if not res:\n            break\n        cit = res.group(1)\n        cit += \"}\"\n        cit = cit.replace(\"\\\\\\\"\", \"\\\"\")\n        cit = cit.replace(\"\\\\\\\\\", \"\\\\\")\n        try:\n            cit = json.loads(cit)\n        except Exception as e:\n            with open(\"debug.txt\", \"w\") as fh:\n                fh.write(cit)\n            raise (e)\n        cit_new = \"[\"\n        for cit_item in cit[\"citationItems\"]:\n            cit_new += z.GetCitationById(cit_item[\"id\"]) + \";\"\n        cit_new = cit_new[:-1] + \"]\"\n        doc = doc[:res.start()] + cit_new + doc[res.end():]\n    inf = Path(sys.argv[1])\n    outf = inf.parent / (inf.stem+\".md\")\n    with open(outf, \"w\") as fh:\n        fh.write(doc)\n"
  },
  {
    "path": "scripts/pdfnotes.py",
    "content": "#!/usr/bin/env python3\n\n\"\"\"\nAdapted from code written by Hamed MP, published at\nhttps://gist.github.com/HamedMP/03440cca542ee7ae279175b78499fabf\n\"\"\"\n\nimport sys\nimport os\nimport re\n\ntry:\n    import PyQt5\nexcept ImportError:\n    sys.stderr.write(\"Please, install the Python3 module PyQt5\")\n    sys.exit(1)\n\ntry:\n    import popplerqt5\nexcept ImportError:\n    sys.stderr.write(\"Please, install the Python3 module python-poppler-qt5\")\n    sys.exit(1)\n\ndef main():\n\n    doc = popplerqt5.Poppler.Document.load(sys.argv[1])\n    if doc is None:\n        sys.exit(33)\n\n    if len(sys.argv) > 2:\n        citekey = sys.argv[2]\n    else:\n        citekey = ''\n\n    # Sometimes, the page labels are spurious. So the priority is:\n    # 1. given page range; 2. page label; 3. given starting page.\n    page1 = 1\n    has_pg_range = False\n    if len(sys.argv) > 3:\n        pg = sys.argv[3]\n        if pg.find(\"-\"):\n            has_pg_range = True\n            pIni = int(re.sub(\"-.*\", \"\", pg))\n            pEnd = int(re.sub(\".*-\", \"\", pg))\n            nPgs = pEnd - pIni + 1\n\n            # Some documents have 1 or 2 extra presentation pages. Ignore them.\n            if doc.numPages() <= nPgs and (nPgs - doc.numPages()) < 2:\n                page1 = pEnd - doc.numPages() + 1\n        else:\n            page1 = int(sys.argv[3])\n\n    if os.getenv('ZYearPageSep') is None:\n        ypsep = ', p. '\n    else:\n        ypsep = os.getenv('ZYearPageSep')\n\n    notes = []\n\n    # Count the pages because not all page labels can be easily converted into\n    # numbers (examples: A1 and III)\n    pnum = 0\n\n    for i in range(doc.numPages()):\n        page = doc.page(i)\n        pnum += 1\n        pgnum = str(i + page1)\n        if not has_pg_range and page.label():\n            pgnum = page.label()\n\n        annotations = page.annotations()\n        (pwidth, pheight) = (page.pageSize().width(), page.pageSize().height())\n        if annotations:\n            for a in annotations:\n                if isinstance(a, popplerqt5.Poppler.Annotation):\n                    # Guess the annotation's column for pages with two columns\n                    if a.boundary().topRight().x() < 0.6:\n                        c = 1\n                    else:\n                        c = 2\n\n                    # Get the y coordinate to to print the annotations in the\n                    # correct order\n                    y = a.boundary().topRight().y()\n\n                    if a.contents():\n                        txt = a.contents() + ' [annotation'\n                        if a.author():\n                            txt = txt + ' by ' + a.author()\n                        if citekey:\n                            txt = txt + ' on ' + citekey\n                        txt = txt + ypsep + pgnum + ']\\n'\n\n                        # Decrease the value of y to ensure that the comment\n                        # on a highlighted text will be printed before the\n                        # highlighted text itself\n                        notes.append([pnum, c, y - 0.0000001, txt])\n\n                    if isinstance(a, popplerqt5.Poppler.HighlightAnnotation):\n                        quads = a.highlightQuads()\n                        txt = ''\n                        for quad in quads:\n                            rect = (quad.points[0].x() * pwidth,\n                                    quad.points[0].y() * pheight,\n                                    quad.points[2].x() * pwidth,\n                                    quad.points[2].y() * pheight)\n                            bdy = PyQt5.QtCore.QRectF()\n                            bdy.setCoords(*rect)\n                            txt = txt + str(page.text(bdy)) + '\\n'\n\n                        txt = txt.replace('-\\n', '')\n                        txt = txt.replace('\\n', ' ')\n                        txt = re.sub('^ *', '', txt)\n                        txt = re.sub(' *$', '', txt)\n                        if txt:\n                            txt = '> ' + txt + ' ['\n                            if citekey:\n                                txt = txt + citekey\n                            txt = txt + ypsep + pgnum + ']\\n'\n                            notes.append([pnum, c, y, txt])\n\n    if notes:\n        snotes = sorted(notes, key=lambda x: (x[0], x[1], x[2]))\n        for n in snotes:\n            print(n[3])\n    else:\n        sys.exit(34)\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/pdfnotes2.py",
    "content": "#!/usr/bin/env python3\n\n\"\"\"\nPDF annotation extraction tool for zotcite using PyMuPDF (fitz)\n\"\"\"\n\nimport sys\nimport os\nimport re\n\ntry:\n    import fitz  # PyMuPDF\nexcept ImportError:\n    sys.stderr.write(\"Please install the Python3 module pymupdf: pip install pymupdf\")\n    sys.exit(1)\n\ndef main():\n    # Check arguments\n    if len(sys.argv) < 2:\n        sys.stderr.write(\"Usage: pdfnotes.py PDF_FILE [CITEKEY] [PAGE_OFFSET]\\n\")\n        sys.exit(1)\n\n    # Load the PDF file\n    try:\n        doc = fitz.open(sys.argv[1])\n    except Exception as e:\n        sys.stderr.write(f\"Error opening PDF: {e}\\n\")\n        sys.exit(33)\n\n    # Get the citation key if provided\n    if len(sys.argv) > 2:\n        citekey = sys.argv[2]\n    else:\n        citekey = ''\n\n    # Get page offset\n    page1 = 1\n    has_pg_range = False\n    if len(sys.argv) > 3:\n        pg = sys.argv[3]\n        try:\n            # Check if it's a page range with hyphen\n            if \"-\" in pg:\n                has_pg_range = True\n                pIni = int(re.sub(\"-.*\", \"\", pg))\n                pEnd = int(re.sub(\".*-\", \"\", pg))\n                nPgs = pEnd - pIni + 1\n\n                # Some documents have 1 or 2 extra presentation pages. Ignore them.\n                if doc.page_count <= nPgs and (nPgs - doc.page_count) < 2:\n                    page1 = pEnd - doc.page_count + 1\n            else:\n                # Try to convert to an integer\n                try:\n                    page1 = int(pg)\n                except ValueError:\n                    # Not a valid page number, might be a Zotero key passed by mistake\n                    sys.stderr.write(f\"Warning: Third argument '{pg}' is not a valid page number. Using default page 1.\\n\")\n                    page1 = 1\n        except Exception as e:\n            # Catch any other errors in page number parsing\n            sys.stderr.write(f\"Warning: Error parsing page number: {e}. Using default page 1.\\n\")\n            page1 = 1\n\n    # Get year-page separator from environment\n    ypsep = os.getenv('ZYearPageSep')\n    if ypsep is None:\n        ypsep = ', p. '\n\n    notes = []\n\n    # Process each page\n    for page_idx in range(doc.page_count):\n        page = doc[page_idx]\n        pnum = page_idx + 1\n\n        # Handle page numbering\n        pgnum = str(page_idx + page1)\n\n        # Try to use page labels if available and not using a range\n        if not has_pg_range:\n            try:\n                # Get page label if available (Roman numerals, etc.)\n                if hasattr(doc, \"get_page_labels\"):\n                    label = doc.get_page_labels()[page_idx]\n                    if label and label.strip():\n                        pgnum = label\n            except:\n                pass  # Fallback to numeric page\n\n        # Get annotations\n        annots = page.annots()\n        if not annots:\n            continue\n\n        # Page dimensions for positioning\n        pwidth, _ = page.rect.width, page.rect.height\n\n        # Process annotations on this page\n        for annot in annots:\n            # Get annotation type\n            annot_type = annot.type[1]\n\n            # Get coordinates for sorting (top of annotation)\n            rect = annot.rect\n            x, y = rect.x0, rect.y0\n\n            # Guess column (for dual-column documents)\n            c = 1 if x < (pwidth / 2) else 2\n\n            # Get contents (annotation text)\n            contents = annot.info.get(\"content\", \"\")\n\n            # Get author if available\n            author = annot.info.get(\"title\", \"\")\n\n            # Process text comments/notes\n            if contents and annot_type in [\"Text\", \"FreeText\", \"Note\"]:\n                txt = contents + ' [annotation'\n                if author:\n                    txt += ' by ' + author\n                if citekey:\n                    txt += ' on ' + citekey\n                txt += ypsep + pgnum + ']\\n'\n\n                # Add to notes list (with slight y-offset to ensure comments come before highlights)\n                notes.append([pnum, c, y - 0.0000001, txt])\n\n            # Process highlighted text\n            if annot_type in [\"Highlight\", \"Underline\"]:\n                # Extract text from the highlighted region\n                text = \"\"\n                try:\n                    # Use word extraction so that only words mostly inside the highlight are included.\n                    words = page.get_text(\"words\")\n                    for word in words:\n                        if len(word) >= 5:  # Ensure all required fields are present\n                            word_rect = fitz.Rect(word[:4])\n                            inter_rect = rect & word_rect  # Compute the intersection rectangle\n                            # Only add the word if more than 50% of its area is inside the annotation\n                            if word_rect.get_area() > 0 and (inter_rect.get_area() / word_rect.get_area()) > 0.5:\n                                text += word[4] + \" \"\n                except Exception:\n                    try:\n                        all_text = page.get_text(\"text\")\n                        if all_text:\n                            text = \"[Highlighted text could not be extracted precisely]\"\n                    except Exception:\n                        pass\n\n                # Clean up the text\n                if text:\n                    text = text.replace('-\\n', '')\n                    text = text.replace('\\n', ' ')\n                    text = re.sub(r'^\\s*', '', text)\n                    text = re.sub(r'\\s*$', '', text)\n                    text = re.sub(r'\\s+', ' ', text)\n\n                    if text.strip():\n                        txt = '> ' + text + ' ['\n                        if citekey:\n                            txt += citekey\n                        txt += ypsep + pgnum + ']\\n'\n                        notes.append([pnum, c, y, txt])\n\n    # Close the document\n    doc.close()\n\n    # Check if we found any notes\n    if notes:\n        # Sort notes by page, column, and y-position\n        snotes = sorted(notes, key=lambda x: (x[0], x[1], x[2]))\n        for n in snotes:\n            print(n[3], end='\\n')\n    else:\n        sys.stderr.write(f\"No annotations found in the PDF: {sys.argv[1]}\\n\")\n        sys.exit(34)\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/zotid2bbtcitkey.py",
    "content": "#!/usr/bin/env python3\n\n# Convert Zotero IDs into Better BibTeX (BBT) citation keys in a Markdown document\n# These are the citation keys exported by Zotero File->Export Library with the \"Better BibLaTeX\" format\n# and can be used in Quarto by setting the `bibliography:` YAML parameter to the exported .bib file\n\nimport requests\nimport sys\nimport json\nimport re\n\n\ndef zotid2citkey(zotid):\n    # Convert a Zotero ID into a Better BibTeX (BBT) citation key\n    #\n    # See\n    # https://github.com/retorquere/zotero-better-bibtex/discussions/3034#discussioncomment-11029462\n    url = \"http://localhost:23119/better-bibtex/json-rpc\"\n    headers = {\n        \"Content-Type\": \"application/json\",\n        \"Accept\": \"application/json\"\n    }\n    data = {\n        \"jsonrpc\": \"2.0\",\n        \"method\": \"item.citationkey\",\n        \"params\": {\"item_keys\": [zotid]}\n    }\n    res = requests.post(url=url, headers=headers, data=json.dumps(data))\n    ress = list(res.json()[\"result\"].items())\n    citkey = ress[0][1]\n    return (citkey)\n\n\nfh = open(sys.argv[1], \"r\")\ninf = fh.read()\nfh.close()\n\nms = re.finditer(r\"@\\w+#[\\w-]+(?=\\]|;)\", inf)\n\nlast_m = None\nfor m in ms:\n    if last_m is None:\n        outs = inf[0:m.start()]\n    else:\n        outs += inf[last_m.end():m.start()]\n    last_m = m\n    zotid = m.group(0)\n    if \"#\" in zotid:\n        zotid = zotid.split(\"#\")[0]\n    zotid = re.sub(\"^@\", \"\", zotid)\n    bbtid = zotid2citkey(zotid)\n    outs += \"@\" + bbtid\n\n# Insert last part\nouts += inf[last_m.end():]\n\nwith open(sys.argv[2], \"w\") as fh:\n    fh.write(outs)\n"
  },
  {
    "path": "selene.toml",
    "content": "# Set the base std to your custom library, which you'll put in std_dirs\nstd = \"vim\"\n\n[rules]\nmultiple_statements = \"allow\"\n\n[config]\n# Point Selene to the directory containing your nvim.toml file.\n# Assuming nvim.toml is in the same directory as selene.toml ('.').\nstd_dirs = [ \".\" ]\n"
  },
  {
    "path": "stylua.toml",
    "content": "column_width = 90\nline_endings = \"Unix\"\nindent_type = \"Spaces\"\nindent_width = 4\nquote_style = \"AutoPreferDouble\"\ncall_parentheses = \"Always\"\ncollapse_simple_statement = \"Always\"\n\n[sort_requires]\nenabled = false\n"
  },
  {
    "path": "vim.yml",
    "content": "---\nbase: lua51\nglobals:\n  vim:\n    any: true\n  pandoc:\n    any: true\n"
  }
]