html2text-2020.1.16/0000775000175000017500000000000013610070526013356 5ustar jonjon00000000000000html2text-2020.1.16/AUTHORS.rst0000664000175000017500000000210513442727054015243 0ustar jonjon00000000000000``html2text`` was originally written by Aaron Swartz. The AUTHORS/Contributors are (and/or have been): * Aaron Swartz * Yariv Barkan * Alex Musayev * Matěj Cepl * Stefano Rivera * Alireza Savand * Ivan Gromov * Jocelyn Delalande * Matt Dorn * Miguel Tavares * Scott Blackburn * Peter Wu * Arjoonn Sharma * Ali Mohammad * Albert Berger * Etienne Millon * John C F * Mikhail Melnik * Andres Rey * Ciprian Miclaus * Toshihiro Kamiya * Matt Dennewitz * Jonathan Sundqvist * Simon Meers * Kurt McKee * Germain Z. * Jacek Kołodziej * Jonathan Vanasco * Jon Dufresne Maintainer: * Alireza Savand html2text-2020.1.16/COPYING0000664000175000017500000010451313434106424014416 0ustar jonjon00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . html2text-2020.1.16/ChangeLog.rst0000664000175000017500000001644413610070441015744 0ustar jonjon000000000000002020.1.16 ========= ---- * Add type annotations. * Add support for Python 3.8. * Performance improvements when ``wrap_links`` is ``False`` (the default). * Configure setuptools using setup.cfg. 2019.9.26 ========= ---- * Fix long blockquotes wrapping. * Remove the trailing whitespaces that were added after wrapping list items & blockquotes. * Remove support for Python ≤ 3.4. Now requires Python 3.5+. * Fix memory leak when processing a document containing a ```` tag. * Fix ``AttributeError`` when reading text from stdin. * Fix ``UnicodeEncodeError`` when writing output to stdout. 2019.8.11 ========= ---- * Add support for wrapping list items. * Fix #201: handle ‎/‏ marks mid-text within stressed tags or right after stressed tags. * Feature #213: ``images_as_html`` config option to always generate an ``img`` html tag. preserves "height", "width" and "alt" if possible. * Remove support for end-of-life Pythons. Now requires Python 2.7 or 3.4+. * Remove support for retrieving HTML over the network. * Add ``__main__.py`` module to allow running the CLI using ``python -m html2text ...``. * Fix #238: correct spacing when a HTML entity follows a non-stressed tags which follow a stressed tag. * Remove unused or deprecated: * ``html2text.compat.escape()`` * ``html2text.config.RE_UNESCAPE`` * ``html2text.HTML2Text.replaceEntities()`` * ``html2text.HTML2Text.unescape()`` * ``html2text.unescape()`` * Fix #208: handle LEFT-TO-RIGHT MARK after a stressed tag. 2018.1.9 ======== ---- * Fix #188: Non-ASCII in title attribute causes encode error. * Feature #194: Add support for the tag. * Feature #193: Add support for the tag. 2017.10.4 ========== ---- * Fix #157: Fix images link with div wrap * Fix #55: Fix error when empty title tags * Fix #160: The html2text tests are failing on Windows and on Cygwin due to differences in eol handling between windows/*nix * Feature #164: Housekeeping: Add flake8 to the travis build, cleanup existing flake8 violations, add py3.6 and pypy3 to the travis build * Fix #109: Fix for unexpanded < > & * Fix #143: Fix line wrapping for the lines starting with bold * Adds support for numeric bold text indication in ``font-weight``, as used by Google (and presumably others.) * Fix #173 and #142: Stripping whitespace in crucial markdown and adding whitespace as necessary * Don't drop any cell data on tables uneven row lengths (e.g. colspan in use) 2016.9.19 ========= ---- * Default image alt text option created and set to a default of empty string "" to maintain backward compatibility * Fix #136: --default-image-alt now takes a string as argument * Fix #113: Stop changing quiet levels on \/script tags. * Merge #126: Fix deprecation warning on py3 due to html.escape * Fix #145: Running test suite on Travis CI for Python 2.6. 2016.5.29 ========= ---- * Fix #125: --pad_tables now pads table cells to make them look nice. * Fix #114: Break does not interrupt blockquotes * Deprecation warnings for URL retrieval. 2016.4.2 ========= ---- * Fix #106: encoding by stdin * Fix #89: Python 3.5 support. * Fix #113: inplace baseurl substitution for and tags. * Feature #118: Update the badges to badge.kloud51.com * Fix #119: new-line after a list is inserted 2016.1.8 ========= ---- * Feature #99: Removed duplicated initialisation. * Fix #100: Get element style key error. * Fix #101: Fix error end tag pop exception * , , now rendered as ~~text~~. 2015.11.4 ========= ---- * Fix #38: Long links wrapping controlled by ``--no-wrap-links``. * Note: ``--no-wrap-links`` implies ``--reference-links`` * Feature #83: Add callback-on-tag. * Fix #87: Decode errors can be handled via command line. * Feature #95: Docs, decode errors spelling mistake. * Fix #84: Make bodywidth kwarg overridable using config. 2015.6.21 ========= ---- * Fix #31: HTML entities stay inside link. * Fix #71: Coverage detects command line tests. * Fix #39: Documentation update. * Fix #61: Functionality added for optional use of automatic links. * Feature #80: ``title`` attribute is preserved in both inline and reference links. * Feature #82: More command line options. See docs. 2015.6.12 ========= ---- * Feature #76: Making ``pre`` blocks clearer for further automatic formatting. * Fix #71: Coverage detects tests carried out in ``subprocesses`` 2015.6.6 ======== ---- * Fix #24: ``3.200.3`` vs ``2014.7.3`` output quirks. * Fix #61. Malformed links in markdown output. * Feature #62: Automatic version number. * Fix #63: Nested code, anchor bug. * Fix #64: Proper handling of anchors with content that starts with tags. * Feature #67: Documentation all over the module. * Feature #70: Adding tests for the module. * Fix #73: Typo in config documentation. 2015.4.14 ========= ---- * Feature #59: Write image tags with height and width attrs as raw html to retain dimensions 2015.4.13 ========= ---- * Feature #56: Treat '-' file parameter as stdin. * Feature #57: Retain escaping of html except within code or pre tags. 2015.2.18 ========= ---- * Fix #38: Anchor tags with empty text or with ```` tags inside are no longer stripped. 2014.12.29 ========== ---- * Feature #51: Add single line break option. This feature is useful for ensuring that lots of extra line breaks do not end up in the resulting Markdown file in situations like Evernote .enex exports. Note that this only works properly if ``body-width`` is set to ``0``. 2014.12.24 ========== ---- * Feature #49: Added an images_to_alt option to discard images and keep only their alt. * Feature #50: Protect links, surrounding them with angle brackets to avoid breaking... * Feature: Add ``setup.cfg`` file. 2014.12.5 ========= ---- * Feature: Update ``README.md`` with usage examples. * Fix #35: Remove ``py_modules`` from ``setup.py``. * Fix #36: Excludes tests from being installed as a separate module. * Fix #37: Don't hardcode the path to the installed binary. * Fix: Readme typo in running cli. * Feature #40: Extract cli part to ``cli`` module. * Feature #42: Bring python version compatibility to ``compat.py`` module. * Feature #41: Extract utility/helper methods to ``utils`` module. * Fix #45: Does not accept standard input when running under Python 3. * Feature: Clean up ``ChangeLog.rst`` for version and date numbers. 2014.9.25 ========= ---- * Feature #29, #27: Add simple table support with bypass option. * Fix #20: Replace project website with: https://alir3z4.github.io/html2text/ . 2014.9.8 ======== ---- * Fix #28: missing ``html2text`` package in installation. 2014.9.7 ======== ---- * Fix ``unicode``/``type`` error in memory leak unit-test. * Feature #16: Remove ``install_deps.py``. * Feature #17: Add status badges via pypin. * Feature #18: Add ``Python`` ``3.4`` to travis config file. * Feature #19: Bring ``html2text`` to a separate module and take out the ``conf``/``constant`` variables. * Feature #21: Remove meta vars from ``html2text.py`` file header. * Fix: Fix TypeError when parsing tags like . Fixed in #25. 2014.7.3 ======== ---- * Fix #8: Remove ``How to do a release`` section from README.md. * Fix #11: Include test directory markdown, html files. * Fix #13: memory leak in using ``handle`` while keeping the old instance of ``html2text``. 2014.4.5 ======== ---- * Fix #1: Add ``ChangeLog.rst`` file. * Fix #2: Add ``AUTHORS.rst`` file. html2text-2020.1.16/MANIFEST.in0000664000175000017500000000020413435524347015122 0ustar jonjon00000000000000include COPYING include README.md include ChangeLog.rst include AUTHORS.rst include tox.ini recursive-include test *.html *.md *.py html2text-2020.1.16/PKG-INFO0000664000175000017500000001156413610070526014462 0ustar jonjon00000000000000Metadata-Version: 2.1 Name: html2text Version: 2020.1.16 Summary: Turn HTML into equivalent Markdown-structured text. Home-page: https://github.com/Alir3z4/html2text/ Author: Aaron Swartz Author-email: me@aaronsw.com Maintainer: Alireza Savand Maintainer-email: alireza.savand@gmail.com License: GNU GPL 3 Description: # html2text [![Build Status](https://secure.travis-ci.org/Alir3z4/html2text.png)](https://travis-ci.org/Alir3z4/html2text) [![Coverage Status](https://coveralls.io/repos/Alir3z4/html2text/badge.png)](https://coveralls.io/r/Alir3z4/html2text) [![Downloads](http://badge.kloud51.com/pypi/d/html2text.png)](https://pypi.org/project/html2text/) [![Version](http://badge.kloud51.com/pypi/v/html2text.png)](https://pypi.org/project/html2text/) [![Wheel?](http://badge.kloud51.com/pypi/wheel/html2text.png)](https://pypi.org/project/html2text/) [![Format](http://badge.kloud51.com/pypi/format/html2text.png)](https://pypi.org/project/html2text/) [![License](http://badge.kloud51.com/pypi/license/html2text.png)](https://pypi.org/project/html2text/) html2text is a Python script that converts a page of HTML into clean, easy-to-read plain ASCII text. Better yet, that ASCII also happens to be valid Markdown (a text-to-HTML format). Usage: `html2text [filename [encoding]]` | Option | Description |--------------------------------------------------------|--------------------------------------------------- | `--version` | Show program's version number and exit | `-h`, `--help` | Show this help message and exit | `--ignore-links` | Don't include any formatting for links |`--escape-all` | Escape all special characters. Output is less readable, but avoids corner case formatting issues. | `--reference-links` | Use reference links instead of links to create markdown | `--mark-code` | Mark preformatted and code blocks with [code]...[/code] For a complete list of options see the [docs](https://github.com/Alir3z4/html2text/blob/master/docs/usage.md) Or you can use it from within `Python`: ``` >>> import html2text >>> >>> print(html2text.html2text("

Zed's dead baby, Zed's dead.

")) **Zed's** dead baby, _Zed's_ dead. ``` Or with some configuration options: ``` >>> import html2text >>> >>> h = html2text.HTML2Text() >>> # Ignore converting links from HTML >>> h.ignore_links = True >>> print h.handle("

Hello, world!") Hello, world! >>> print(h.handle("

Hello, world!")) Hello, world! >>> # Don't Ignore links anymore, I like links >>> h.ignore_links = False >>> print(h.handle("

Hello, world!")) Hello, [world](https://www.google.com/earth/)! ``` *Originally written by Aaron Swartz. This code is distributed under the GPLv3.* ## How to install `html2text` is available on pypi https://pypi.org/project/html2text/ ``` $ pip install html2text ``` ## How to run unit tests tox To see the coverage results: coverage html then open the `./htmlcov/index.html` file in your browser. ## Documentation Documentation lives [here](https://github.com/Alir3z4/html2text/blob/master/docs/usage.md) Platform: OS Independent Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=3.5 Description-Content-Type: text/markdown html2text-2020.1.16/README.md0000664000175000017500000000615113435524347014652 0ustar jonjon00000000000000# html2text [![Build Status](https://secure.travis-ci.org/Alir3z4/html2text.png)](https://travis-ci.org/Alir3z4/html2text) [![Coverage Status](https://coveralls.io/repos/Alir3z4/html2text/badge.png)](https://coveralls.io/r/Alir3z4/html2text) [![Downloads](http://badge.kloud51.com/pypi/d/html2text.png)](https://pypi.org/project/html2text/) [![Version](http://badge.kloud51.com/pypi/v/html2text.png)](https://pypi.org/project/html2text/) [![Wheel?](http://badge.kloud51.com/pypi/wheel/html2text.png)](https://pypi.org/project/html2text/) [![Format](http://badge.kloud51.com/pypi/format/html2text.png)](https://pypi.org/project/html2text/) [![License](http://badge.kloud51.com/pypi/license/html2text.png)](https://pypi.org/project/html2text/) html2text is a Python script that converts a page of HTML into clean, easy-to-read plain ASCII text. Better yet, that ASCII also happens to be valid Markdown (a text-to-HTML format). Usage: `html2text [filename [encoding]]` | Option | Description |--------------------------------------------------------|--------------------------------------------------- | `--version` | Show program's version number and exit | `-h`, `--help` | Show this help message and exit | `--ignore-links` | Don't include any formatting for links |`--escape-all` | Escape all special characters. Output is less readable, but avoids corner case formatting issues. | `--reference-links` | Use reference links instead of links to create markdown | `--mark-code` | Mark preformatted and code blocks with [code]...[/code] For a complete list of options see the [docs](https://github.com/Alir3z4/html2text/blob/master/docs/usage.md) Or you can use it from within `Python`: ``` >>> import html2text >>> >>> print(html2text.html2text("

Zed's dead baby, Zed's dead.

")) **Zed's** dead baby, _Zed's_ dead. ``` Or with some configuration options: ``` >>> import html2text >>> >>> h = html2text.HTML2Text() >>> # Ignore converting links from HTML >>> h.ignore_links = True >>> print h.handle("

Hello, world!") Hello, world! >>> print(h.handle("

Hello, world!")) Hello, world! >>> # Don't Ignore links anymore, I like links >>> h.ignore_links = False >>> print(h.handle("

Hello, world!")) Hello, [world](https://www.google.com/earth/)! ``` *Originally written by Aaron Swartz. This code is distributed under the GPLv3.* ## How to install `html2text` is available on pypi https://pypi.org/project/html2text/ ``` $ pip install html2text ``` ## How to run unit tests tox To see the coverage results: coverage html then open the `./htmlcov/index.html` file in your browser. ## Documentation Documentation lives [here](https://github.com/Alir3z4/html2text/blob/master/docs/usage.md) html2text-2020.1.16/html2text/0000775000175000017500000000000013610070526015311 5ustar jonjon00000000000000html2text-2020.1.16/html2text/__init__.py0000664000175000017500000010214113610070441017415 0ustar jonjon00000000000000"""html2text: Turn HTML into equivalent Markdown-structured text.""" import html.entities import html.parser import re import urllib.parse as urlparse from textwrap import wrap from typing import Dict, List, Optional, Tuple, Union from . import config from .elements import AnchorElement, ListElement from .typing import OutCallback from .utils import ( dumb_css_parser, element_style, escape_md, escape_md_section, google_fixed_width_font, google_has_height, google_list_style, google_text_emphasis, hn, list_numbering_start, pad_tables_in_text, skipwrap, unifiable_n, ) __version__ = (2020, 1, 16) # TODO: # Support decoded entities with UNIFIABLE. class HTML2Text(html.parser.HTMLParser): def __init__( self, out: Optional[OutCallback] = None, baseurl: str = "", bodywidth: int = config.BODY_WIDTH, ) -> None: """ Input parameters: out: possible custom replacement for self.outtextf (which appends lines of text). baseurl: base URL of the document we process """ super().__init__(convert_charrefs=False) # Config options self.split_next_td = False self.td_count = 0 self.table_start = False self.unicode_snob = config.UNICODE_SNOB # covered in cli self.escape_snob = config.ESCAPE_SNOB # covered in cli self.links_each_paragraph = config.LINKS_EACH_PARAGRAPH self.body_width = bodywidth # covered in cli self.skip_internal_links = config.SKIP_INTERNAL_LINKS # covered in cli self.inline_links = config.INLINE_LINKS # covered in cli self.protect_links = config.PROTECT_LINKS # covered in cli self.google_list_indent = config.GOOGLE_LIST_INDENT # covered in cli self.ignore_links = config.IGNORE_ANCHORS # covered in cli self.ignore_images = config.IGNORE_IMAGES # covered in cli self.images_as_html = config.IMAGES_AS_HTML # covered in cli self.images_to_alt = config.IMAGES_TO_ALT # covered in cli self.images_with_size = config.IMAGES_WITH_SIZE # covered in cli self.ignore_emphasis = config.IGNORE_EMPHASIS # covered in cli self.bypass_tables = config.BYPASS_TABLES # covered in cli self.ignore_tables = config.IGNORE_TABLES # covered in cli self.google_doc = False # covered in cli self.ul_item_mark = "*" # covered in cli self.emphasis_mark = "_" # covered in cli self.strong_mark = "**" self.single_line_break = config.SINGLE_LINE_BREAK # covered in cli self.use_automatic_links = config.USE_AUTOMATIC_LINKS # covered in cli self.hide_strikethrough = False # covered in cli self.mark_code = config.MARK_CODE self.wrap_list_items = config.WRAP_LIST_ITEMS # covered in cli self.wrap_links = config.WRAP_LINKS # covered in cli self.pad_tables = config.PAD_TABLES # covered in cli self.default_image_alt = config.DEFAULT_IMAGE_ALT # covered in cli self.tag_callback = None self.open_quote = config.OPEN_QUOTE # covered in cli self.close_quote = config.CLOSE_QUOTE # covered in cli if out is None: self.out = self.outtextf else: self.out = out # empty list to store output characters before they are "joined" self.outtextlist = [] # type: List[str] self.quiet = 0 self.p_p = 0 # number of newline character to print before next output self.outcount = 0 self.start = True self.space = False self.a = [] # type: List[AnchorElement] self.astack = [] # type: List[Optional[Dict[str, Optional[str]]]] self.maybe_automatic_link = None # type: Optional[str] self.empty_link = False self.absolute_url_matcher = re.compile(r"^[a-zA-Z+]+://") self.acount = 0 self.list = [] # type: List[ListElement] self.blockquote = 0 self.pre = False self.startpre = False self.code = False self.quote = False self.br_toggle = "" self.lastWasNL = False self.lastWasList = False self.style = 0 self.style_def = {} # type: Dict[str, Dict[str, str]] self.tag_stack = ( [] ) # type: List[Tuple[str, Dict[str, Optional[str]], Dict[str, str]]] self.emphasis = 0 self.drop_white_space = 0 self.inheader = False # Current abbreviation definition self.abbr_title = None # type: Optional[str] # Last inner HTML (for abbr being defined) self.abbr_data = None # type: Optional[str] # Stack of abbreviations to write later self.abbr_list = {} # type: Dict[str, str] self.baseurl = baseurl self.stressed = False self.preceding_stressed = False self.preceding_data = "" self.current_tag = "" config.UNIFIABLE["nbsp"] = " _place_holder;" def feed(self, data: str) -> None: data = data.replace("", "") super().feed(data) def handle(self, data: str) -> str: self.feed(data) self.feed("") markdown = self.optwrap(self.finish()) if self.pad_tables: return pad_tables_in_text(markdown) else: return markdown def outtextf(self, s: str) -> None: self.outtextlist.append(s) if s: self.lastWasNL = s[-1] == "\n" def finish(self) -> str: self.close() self.pbr() self.o("", force="end") outtext = "".join(self.outtextlist) if self.unicode_snob: nbsp = html.entities.html5["nbsp;"] else: nbsp = " " outtext = outtext.replace(" _place_holder;", nbsp) # Clear self.outtextlist to avoid memory leak of its content to # the next handling. self.outtextlist = [] return outtext def handle_charref(self, c: str) -> None: self.handle_data(self.charref(c), True) def handle_entityref(self, c: str) -> None: ref = self.entityref(c) # ref may be an empty string (e.g. for ‎/‏ markers that should # not contribute to the final output). # self.handle_data cannot handle a zero-length string right after a # stressed tag or mid-text within a stressed tag (text get split and # self.stressed/self.preceding_stressed gets switched after the first # part of that text). if ref: self.handle_data(ref, True) def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None: self.handle_tag(tag, dict(attrs), start=True) def handle_endtag(self, tag: str) -> None: self.handle_tag(tag, {}, start=False) def previousIndex(self, attrs: Dict[str, Optional[str]]) -> Optional[int]: """ :type attrs: dict :returns: The index of certain set of attributes (of a link) in the self.a list. If the set of attributes is not found, returns None :rtype: int """ if "href" not in attrs: return None match = False for i, a in enumerate(self.a): if "href" in a.attrs and a.attrs["href"] == attrs["href"]: if "title" in a.attrs or "title" in attrs: if ( "title" in a.attrs and "title" in attrs and a.attrs["title"] == attrs["title"] ): match = True else: match = True if match: return i return None def handle_emphasis( self, start: bool, tag_style: Dict[str, str], parent_style: Dict[str, str] ) -> None: """ Handles various text emphases """ tag_emphasis = google_text_emphasis(tag_style) parent_emphasis = google_text_emphasis(parent_style) # handle Google's text emphasis strikethrough = "line-through" in tag_emphasis and self.hide_strikethrough # google and others may mark a font's weight as `bold` or `700` bold = False for bold_marker in config.BOLD_TEXT_STYLE_VALUES: bold = bold_marker in tag_emphasis and bold_marker not in parent_emphasis if bold: break italic = "italic" in tag_emphasis and "italic" not in parent_emphasis fixed = ( google_fixed_width_font(tag_style) and not google_fixed_width_font(parent_style) and not self.pre ) if start: # crossed-out text must be handled before other attributes # in order not to output qualifiers unnecessarily if bold or italic or fixed: self.emphasis += 1 if strikethrough: self.quiet += 1 if italic: self.o(self.emphasis_mark) self.drop_white_space += 1 if bold: self.o(self.strong_mark) self.drop_white_space += 1 if fixed: self.o("`") self.drop_white_space += 1 self.code = True else: if bold or italic or fixed: # there must not be whitespace before closing emphasis mark self.emphasis -= 1 self.space = False if fixed: if self.drop_white_space: # empty emphasis, drop it self.drop_white_space -= 1 else: self.o("`") self.code = False if bold: if self.drop_white_space: # empty emphasis, drop it self.drop_white_space -= 1 else: self.o(self.strong_mark) if italic: if self.drop_white_space: # empty emphasis, drop it self.drop_white_space -= 1 else: self.o(self.emphasis_mark) # space is only allowed after *all* emphasis marks if (bold or italic) and not self.emphasis: self.o(" ") if strikethrough: self.quiet -= 1 def handle_tag( self, tag: str, attrs: Dict[str, Optional[str]], start: bool ) -> None: self.current_tag = tag if self.tag_callback is not None: if self.tag_callback(self, tag, attrs, start) is True: return # first thing inside the anchor tag is another tag # that produces some output if ( start and self.maybe_automatic_link is not None and tag not in ["p", "div", "style", "dl", "dt"] and (tag != "img" or self.ignore_images) ): self.o("[") self.maybe_automatic_link = None self.empty_link = False if self.google_doc: # the attrs parameter is empty for a closing tag. in addition, we # need the attributes of the parent nodes in order to get a # complete style description for the current element. we assume # that google docs export well formed html. parent_style = {} # type: Dict[str, str] if start: if self.tag_stack: parent_style = self.tag_stack[-1][2] tag_style = element_style(attrs, self.style_def, parent_style) self.tag_stack.append((tag, attrs, tag_style)) else: dummy, attrs, tag_style = ( self.tag_stack.pop() if self.tag_stack else (None, {}, {}) ) if self.tag_stack: parent_style = self.tag_stack[-1][2] if hn(tag): self.p() if start: self.inheader = True self.o(hn(tag) * "#" + " ") else: self.inheader = False return # prevent redundant emphasis marks on headers if tag in ["p", "div"]: if self.google_doc: if start and google_has_height(tag_style): self.p() else: self.soft_br() elif self.astack and tag == "div": pass else: self.p() if tag == "br" and start: if self.blockquote > 0: self.o(" \n> ") else: self.o(" \n") if tag == "hr" and start: self.p() self.o("* * *") self.p() if tag in ["head", "style", "script"]: if start: self.quiet += 1 else: self.quiet -= 1 if tag == "style": if start: self.style += 1 else: self.style -= 1 if tag in ["body"]: self.quiet = 0 # sites like 9rules.com never close if tag == "blockquote": if start: self.p() self.o("> ", force=True) self.start = True self.blockquote += 1 else: self.blockquote -= 1 self.p() def no_preceding_space(self: HTML2Text) -> bool: return bool( self.preceding_data and re.match(r"[^\s]", self.preceding_data[-1]) ) if tag in ["em", "i", "u"] and not self.ignore_emphasis: if start and no_preceding_space(self): emphasis = " " + self.emphasis_mark else: emphasis = self.emphasis_mark self.o(emphasis) if start: self.stressed = True if tag in ["strong", "b"] and not self.ignore_emphasis: if start and no_preceding_space(self): strong = " " + self.strong_mark else: strong = self.strong_mark self.o(strong) if start: self.stressed = True if tag in ["del", "strike", "s"]: if start and no_preceding_space(self): strike = " ~~" else: strike = "~~" self.o(strike) if start: self.stressed = True if self.google_doc: if not self.inheader: # handle some font attributes, but leave headers clean self.handle_emphasis(start, tag_style, parent_style) if tag in ["kbd", "code", "tt"] and not self.pre: self.o("`") # TODO: `` `this` `` self.code = not self.code if tag == "abbr": if start: self.abbr_title = None self.abbr_data = "" if "title" in attrs: self.abbr_title = attrs["title"] else: if self.abbr_title is not None: assert self.abbr_data is not None self.abbr_list[self.abbr_data] = self.abbr_title self.abbr_title = None self.abbr_data = None if tag == "q": if not self.quote: self.o(self.open_quote) else: self.o(self.close_quote) self.quote = not self.quote def link_url(self: HTML2Text, link: str, title: str = "") -> None: url = urlparse.urljoin(self.baseurl, link) title = ' "{}"'.format(title) if title.strip() else "" self.o("]({url}{title})".format(url=escape_md(url), title=title)) if tag == "a" and not self.ignore_links: if start: if ( "href" in attrs and attrs["href"] is not None and not (self.skip_internal_links and attrs["href"].startswith("#")) ): self.astack.append(attrs) self.maybe_automatic_link = attrs["href"] self.empty_link = True if self.protect_links: attrs["href"] = "<" + attrs["href"] + ">" else: self.astack.append(None) else: if self.astack: a = self.astack.pop() if self.maybe_automatic_link and not self.empty_link: self.maybe_automatic_link = None elif a: assert a["href"] is not None if self.empty_link: self.o("[") self.empty_link = False self.maybe_automatic_link = None if self.inline_links: title = a.get("title") or "" title = escape_md(title) link_url(self, a["href"], title) else: i = self.previousIndex(a) if i is not None: a_props = self.a[i] else: self.acount += 1 a_props = AnchorElement(a, self.acount, self.outcount) self.a.append(a_props) self.o("][" + str(a_props.count) + "]") if tag == "img" and start and not self.ignore_images: if "src" in attrs: assert attrs["src"] is not None if not self.images_to_alt: attrs["href"] = attrs["src"] alt = attrs.get("alt") or self.default_image_alt # If we have images_with_size, write raw html including width, # height, and alt attributes if self.images_as_html or ( self.images_with_size and ("width" in attrs or "height" in attrs) ): self.o("") return # If we have a link to create, output the start if self.maybe_automatic_link is not None: href = self.maybe_automatic_link if ( self.images_to_alt and escape_md(alt) == href and self.absolute_url_matcher.match(href) ): self.o("<" + escape_md(alt) + ">") self.empty_link = False return else: self.o("[") self.maybe_automatic_link = None self.empty_link = False # If we have images_to_alt, we discard the image itself, # considering only the alt text. if self.images_to_alt: self.o(escape_md(alt)) else: self.o("![" + escape_md(alt) + "]") if self.inline_links: href = attrs.get("href") or "" self.o( "(" + escape_md(urlparse.urljoin(self.baseurl, href)) + ")" ) else: i = self.previousIndex(attrs) if i is not None: a_props = self.a[i] else: self.acount += 1 a_props = AnchorElement(attrs, self.acount, self.outcount) self.a.append(a_props) self.o("[" + str(a_props.count) + "]") if tag == "dl" and start: self.p() if tag == "dt" and not start: self.pbr() if tag == "dd" and start: self.o(" ") if tag == "dd" and not start: self.pbr() if tag in ["ol", "ul"]: # Google Docs create sub lists as top level lists if not self.list and not self.lastWasList: self.p() if start: if self.google_doc: list_style = google_list_style(tag_style) else: list_style = tag numbering_start = list_numbering_start(attrs) self.list.append(ListElement(list_style, numbering_start)) else: if self.list: self.list.pop() if not self.google_doc and not self.list: self.o("\n") self.lastWasList = True else: self.lastWasList = False if tag == "li": self.pbr() if start: if self.list: li = self.list[-1] else: li = ListElement("ul", 0) if self.google_doc: nest_count = self.google_nest_count(tag_style) else: nest_count = len(self.list) # TODO: line up

  1. s > 9 correctly. self.o(" " * nest_count) if li.name == "ul": self.o(self.ul_item_mark + " ") elif li.name == "ol": li.num += 1 self.o(str(li.num) + ". ") self.start = True if tag in ["table", "tr", "td", "th"]: if self.ignore_tables: if tag == "tr": if start: pass else: self.soft_br() else: pass elif self.bypass_tables: if start: self.soft_br() if tag in ["td", "th"]: if start: self.o("<{}>\n\n".format(tag)) else: self.o("\n".format(tag)) else: if start: self.o("<{}>".format(tag)) else: self.o("".format(tag)) else: if tag == "table": if start: self.table_start = True if self.pad_tables: self.o("<" + config.TABLE_MARKER_FOR_PAD + ">") self.o(" \n") else: if self.pad_tables: self.o("") self.o(" \n") if tag in ["td", "th"] and start: if self.split_next_td: self.o("| ") self.split_next_td = True if tag == "tr" and start: self.td_count = 0 if tag == "tr" and not start: self.split_next_td = False self.soft_br() if tag == "tr" and not start and self.table_start: # Underline table header self.o("|".join(["---"] * self.td_count)) self.soft_br() self.table_start = False if tag in ["td", "th"] and start: self.td_count += 1 if tag == "pre": if start: self.startpre = True self.pre = True else: self.pre = False if self.mark_code: self.out("\n[/code]") self.p() # TODO: Add docstring for these one letter functions def pbr(self) -> None: "Pretty print has a line break" if self.p_p == 0: self.p_p = 1 def p(self) -> None: "Set pretty print to 1 or 2 lines" self.p_p = 1 if self.single_line_break else 2 def soft_br(self) -> None: "Soft breaks" self.pbr() self.br_toggle = " " def o( self, data: str, puredata: bool = False, force: Union[bool, str] = False ) -> None: """ Deal with indentation and whitespace """ if self.abbr_data is not None: self.abbr_data += data if not self.quiet: if self.google_doc: # prevent white space immediately after 'begin emphasis' # marks ('**' and '_') lstripped_data = data.lstrip() if self.drop_white_space and not (self.pre or self.code): data = lstripped_data if lstripped_data != "": self.drop_white_space = 0 if puredata and not self.pre: # This is a very dangerous call ... it could mess up # all handling of   when not handled properly # (see entityref) data = re.sub(r"\s+", r" ", data) if data and data[0] == " ": self.space = True data = data[1:] if not data and not force: return if self.startpre: # self.out(" :") #TODO: not output when already one there if not data.startswith("\n") and not data.startswith("\r\n"): #
    stuff...
                        data = "\n" + data
                    if self.mark_code:
                        self.out("\n[code]")
                        self.p_p = 0
    
                bq = ">" * self.blockquote
                if not (force and data and data[0] == ">") and self.blockquote:
                    bq += " "
    
                if self.pre:
                    if not self.list:
                        bq += "    "
                    # else: list content is already partially indented
                    bq += "    " * len(self.list)
                    data = data.replace("\n", "\n" + bq)
    
                if self.startpre:
                    self.startpre = False
                    if self.list:
                        # use existing initial indentation
                        data = data.lstrip("\n")
    
                if self.start:
                    self.space = False
                    self.p_p = 0
                    self.start = False
    
                if force == "end":
                    # It's the end.
                    self.p_p = 0
                    self.out("\n")
                    self.space = False
    
                if self.p_p:
                    self.out((self.br_toggle + "\n" + bq) * self.p_p)
                    self.space = False
                    self.br_toggle = ""
    
                if self.space:
                    if not self.lastWasNL:
                        self.out(" ")
                    self.space = False
    
                if self.a and (
                    (self.p_p == 2 and self.links_each_paragraph) or force == "end"
                ):
                    if force == "end":
                        self.out("\n")
    
                    newa = []
                    for link in self.a:
                        if self.outcount > link.outcount:
                            self.out(
                                "   ["
                                + str(link.count)
                                + "]: "
                                + urlparse.urljoin(self.baseurl, link.attrs["href"])
                            )
                            if "title" in link.attrs:
                                assert link.attrs["title"] is not None
                                self.out(" (" + link.attrs["title"] + ")")
                            self.out("\n")
                        else:
                            newa.append(link)
    
                    # Don't need an extra line when nothing was done.
                    if self.a != newa:
                        self.out("\n")
    
                    self.a = newa
    
                if self.abbr_list and force == "end":
                    for abbr, definition in self.abbr_list.items():
                        self.out("  *[" + abbr + "]: " + definition + "\n")
    
                self.p_p = 0
                self.out(data)
                self.outcount += 1
    
        def handle_data(self, data: str, entity_char: bool = False) -> None:
            if not data:
                # Data may be empty for some HTML entities. For example,
                # LEFT-TO-RIGHT MARK.
                return
    
            if self.stressed:
                data = data.strip()
                self.stressed = False
                self.preceding_stressed = True
            elif self.preceding_stressed:
                if (
                    re.match(r"[^\s.!?]", data[0])
                    and not hn(self.current_tag)
                    and self.current_tag not in ["a", "code", "pre"]
                ):
                    # should match a letter or common punctuation
                    data = " " + data
                self.preceding_stressed = False
    
            if self.style:
                self.style_def.update(dumb_css_parser(data))
    
            if self.maybe_automatic_link is not None:
                href = self.maybe_automatic_link
                if (
                    href == data
                    and self.absolute_url_matcher.match(href)
                    and self.use_automatic_links
                ):
                    self.o("<" + data + ">")
                    self.empty_link = False
                    return
                else:
                    self.o("[")
                    self.maybe_automatic_link = None
                    self.empty_link = False
    
            if not self.code and not self.pre and not entity_char:
                data = escape_md_section(data, snob=self.escape_snob)
            self.preceding_data = data
            self.o(data, puredata=True)
    
        def charref(self, name: str) -> str:
            if name[0] in ["x", "X"]:
                c = int(name[1:], 16)
            else:
                c = int(name)
    
            if not self.unicode_snob and c in unifiable_n:
                return unifiable_n[c]
            else:
                try:
                    return chr(c)
                except ValueError:  # invalid unicode
                    return ""
    
        def entityref(self, c: str) -> str:
            if not self.unicode_snob and c in config.UNIFIABLE:
                return config.UNIFIABLE[c]
            try:
                ch = html.entities.html5[c + ";"]
            except KeyError:
                return "&" + c + ";"
            return config.UNIFIABLE[c] if c == "nbsp" else ch
    
        def google_nest_count(self, style: Dict[str, str]) -> int:
            """
            Calculate the nesting count of google doc lists
    
            :type style: dict
    
            :rtype: int
            """
            nest_count = 0
            if "margin-left" in style:
                nest_count = int(style["margin-left"][:-2]) // self.google_list_indent
    
            return nest_count
    
        def optwrap(self, text: str) -> str:
            """
            Wrap all paragraphs in the provided text.
    
            :type text: str
    
            :rtype: str
            """
            if not self.body_width:
                return text
    
            result = ""
            newlines = 0
            # I cannot think of a better solution for now.
            # To avoid the non-wrap behaviour for entire paras
            # because of the presence of a link in it
            if not self.wrap_links:
                self.inline_links = False
            for para in text.split("\n"):
                if len(para) > 0:
                    if not skipwrap(para, self.wrap_links, self.wrap_list_items):
                        indent = ""
                        if para.startswith("  " + self.ul_item_mark):
                            # list item continuation: add a double indent to the
                            # new lines
                            indent = "    "
                        elif para.startswith("> "):
                            # blockquote continuation: add the greater than symbol
                            # to the new lines
                            indent = "> "
                        wrapped = wrap(
                            para,
                            self.body_width,
                            break_long_words=False,
                            subsequent_indent=indent,
                        )
                        result += "\n".join(wrapped)
                        if para.endswith("  "):
                            result += "  \n"
                            newlines = 1
                        elif indent:
                            result += "\n"
                            newlines = 1
                        else:
                            result += "\n\n"
                            newlines = 2
                    else:
                        # Warning for the tempted!!!
                        # Be aware that obvious replacement of this with
                        # line.isspace()
                        # DOES NOT work! Explanations are welcome.
                        if not config.RE_SPACE.match(para):
                            result += para + "\n"
                            newlines = 1
                else:
                    if newlines < 2:
                        result += "\n"
                        newlines += 1
            return result
    
    
    def html2text(html: str, baseurl: str = "", bodywidth: Optional[int] = None) -> str:
        if bodywidth is None:
            bodywidth = config.BODY_WIDTH
        h = HTML2Text(baseurl=baseurl, bodywidth=bodywidth)
    
        return h.handle(html)
    html2text-2020.1.16/html2text/__main__.py0000664000175000017500000000003613550373562017413 0ustar  jonjon00000000000000from .cli import main
    
    main()
    html2text-2020.1.16/html2text/cli.py0000664000175000017500000002204013550376531016440 0ustar  jonjon00000000000000import argparse
    import sys
    
    from . import HTML2Text, __version__, config
    
    
    def main() -> None:
        baseurl = ""
    
        class bcolors:
            HEADER = "\033[95m"
            OKBLUE = "\033[94m"
            OKGREEN = "\033[92m"
            WARNING = "\033[93m"
            FAIL = "\033[91m"
            ENDC = "\033[0m"
            BOLD = "\033[1m"
            UNDERLINE = "\033[4m"
    
        p = argparse.ArgumentParser()
        p.add_argument(
            "--default-image-alt",
            dest="default_image_alt",
            default=config.DEFAULT_IMAGE_ALT,
            help="The default alt string for images with missing ones",
        )
        p.add_argument(
            "--pad-tables",
            dest="pad_tables",
            action="store_true",
            default=config.PAD_TABLES,
            help="pad the cells to equal column width in tables",
        )
        p.add_argument(
            "--no-wrap-links",
            dest="wrap_links",
            action="store_false",
            default=config.WRAP_LINKS,
            help="don't wrap links during conversion",
        )
        p.add_argument(
            "--wrap-list-items",
            dest="wrap_list_items",
            action="store_true",
            default=config.WRAP_LIST_ITEMS,
            help="wrap list items during conversion",
        )
        p.add_argument(
            "--ignore-emphasis",
            dest="ignore_emphasis",
            action="store_true",
            default=config.IGNORE_EMPHASIS,
            help="don't include any formatting for emphasis",
        )
        p.add_argument(
            "--reference-links",
            dest="inline_links",
            action="store_false",
            default=config.INLINE_LINKS,
            help="use reference style links instead of inline links",
        )
        p.add_argument(
            "--ignore-links",
            dest="ignore_links",
            action="store_true",
            default=config.IGNORE_ANCHORS,
            help="don't include any formatting for links",
        )
        p.add_argument(
            "--protect-links",
            dest="protect_links",
            action="store_true",
            default=config.PROTECT_LINKS,
            help="protect links from line breaks surrounding them with angle brackets",
        )
        p.add_argument(
            "--ignore-images",
            dest="ignore_images",
            action="store_true",
            default=config.IGNORE_IMAGES,
            help="don't include any formatting for images",
        )
        p.add_argument(
            "--images-as-html",
            dest="images_as_html",
            action="store_true",
            default=config.IMAGES_AS_HTML,
            help=(
                "Always write image tags as raw html; preserves `height`, `width` and "
                "`alt` if possible."
            ),
        )
        p.add_argument(
            "--images-to-alt",
            dest="images_to_alt",
            action="store_true",
            default=config.IMAGES_TO_ALT,
            help="Discard image data, only keep alt text",
        )
        p.add_argument(
            "--images-with-size",
            dest="images_with_size",
            action="store_true",
            default=config.IMAGES_WITH_SIZE,
            help=(
                "Write image tags with height and width attrs as raw html to retain "
                "dimensions"
            ),
        )
        p.add_argument(
            "-g",
            "--google-doc",
            action="store_true",
            dest="google_doc",
            default=False,
            help="convert an html-exported Google Document",
        )
        p.add_argument(
            "-d",
            "--dash-unordered-list",
            action="store_true",
            dest="ul_style_dash",
            default=False,
            help="use a dash rather than a star for unordered list items",
        )
        p.add_argument(
            "-e",
            "--asterisk-emphasis",
            action="store_true",
            dest="em_style_asterisk",
            default=False,
            help="use an asterisk rather than an underscore for emphasized text",
        )
        p.add_argument(
            "-b",
            "--body-width",
            dest="body_width",
            type=int,
            default=config.BODY_WIDTH,
            help="number of characters per output line, 0 for no wrap",
        )
        p.add_argument(
            "-i",
            "--google-list-indent",
            dest="list_indent",
            type=int,
            default=config.GOOGLE_LIST_INDENT,
            help="number of pixels Google indents nested lists",
        )
        p.add_argument(
            "-s",
            "--hide-strikethrough",
            action="store_true",
            dest="hide_strikethrough",
            default=False,
            help="hide strike-through text. only relevant when -g is " "specified as well",
        )
        p.add_argument(
            "--escape-all",
            action="store_true",
            dest="escape_snob",
            default=False,
            help=(
                "Escape all special characters.  Output is less readable, but avoids "
                "corner case formatting issues."
            ),
        )
        p.add_argument(
            "--bypass-tables",
            action="store_true",
            dest="bypass_tables",
            default=config.BYPASS_TABLES,
            help="Format tables in HTML rather than Markdown syntax.",
        )
        p.add_argument(
            "--ignore-tables",
            action="store_true",
            dest="ignore_tables",
            default=config.IGNORE_TABLES,
            help="Ignore table-related tags (table, th, td, tr) " "while keeping rows.",
        )
        p.add_argument(
            "--single-line-break",
            action="store_true",
            dest="single_line_break",
            default=config.SINGLE_LINE_BREAK,
            help=(
                "Use a single line break after a block element rather than two line "
                "breaks. NOTE: Requires --body-width=0"
            ),
        )
        p.add_argument(
            "--unicode-snob",
            action="store_true",
            dest="unicode_snob",
            default=config.UNICODE_SNOB,
            help="Use unicode throughout document",
        )
        p.add_argument(
            "--no-automatic-links",
            action="store_false",
            dest="use_automatic_links",
            default=config.USE_AUTOMATIC_LINKS,
            help="Do not use automatic links wherever applicable",
        )
        p.add_argument(
            "--no-skip-internal-links",
            action="store_false",
            dest="skip_internal_links",
            default=config.SKIP_INTERNAL_LINKS,
            help="Do not skip internal links",
        )
        p.add_argument(
            "--links-after-para",
            action="store_true",
            dest="links_each_paragraph",
            default=config.LINKS_EACH_PARAGRAPH,
            help="Put links after each paragraph instead of document",
        )
        p.add_argument(
            "--mark-code",
            action="store_true",
            dest="mark_code",
            default=config.MARK_CODE,
            help="Mark program code blocks with [code]...[/code]",
        )
        p.add_argument(
            "--decode-errors",
            dest="decode_errors",
            default=config.DECODE_ERRORS,
            help=(
                "What to do in case of decode errors.'ignore', 'strict' and 'replace' are "
                "acceptable values"
            ),
        )
        p.add_argument(
            "--open-quote",
            dest="open_quote",
            default=config.OPEN_QUOTE,
            help="The character used to open quotes",
        )
        p.add_argument(
            "--close-quote",
            dest="close_quote",
            default=config.CLOSE_QUOTE,
            help="The character used to close quotes",
        )
        p.add_argument(
            "--version", action="version", version=".".join(map(str, __version__))
        )
        p.add_argument("filename", nargs="?")
        p.add_argument("encoding", nargs="?", default="utf-8")
        args = p.parse_args()
    
        if args.filename and args.filename != "-":
            with open(args.filename, "rb") as fp:
                data = fp.read()
        else:
            data = sys.stdin.buffer.read()
    
        try:
            html = data.decode(args.encoding, args.decode_errors)
        except UnicodeDecodeError as err:
            warning = bcolors.WARNING + "Warning:" + bcolors.ENDC
            warning += " Use the " + bcolors.OKGREEN
            warning += "--decode-errors=ignore" + bcolors.ENDC + " flag."
            print(warning)
            raise err
    
        h = HTML2Text(baseurl=baseurl)
        # handle options
        if args.ul_style_dash:
            h.ul_item_mark = "-"
        if args.em_style_asterisk:
            h.emphasis_mark = "*"
            h.strong_mark = "__"
    
        h.body_width = args.body_width
        h.google_list_indent = args.list_indent
        h.ignore_emphasis = args.ignore_emphasis
        h.ignore_links = args.ignore_links
        h.protect_links = args.protect_links
        h.ignore_images = args.ignore_images
        h.images_as_html = args.images_as_html
        h.images_to_alt = args.images_to_alt
        h.images_with_size = args.images_with_size
        h.google_doc = args.google_doc
        h.hide_strikethrough = args.hide_strikethrough
        h.escape_snob = args.escape_snob
        h.bypass_tables = args.bypass_tables
        h.ignore_tables = args.ignore_tables
        h.single_line_break = args.single_line_break
        h.inline_links = args.inline_links
        h.unicode_snob = args.unicode_snob
        h.use_automatic_links = args.use_automatic_links
        h.skip_internal_links = args.skip_internal_links
        h.links_each_paragraph = args.links_each_paragraph
        h.mark_code = args.mark_code
        h.wrap_links = args.wrap_links
        h.wrap_list_items = args.wrap_list_items
        h.pad_tables = args.pad_tables
        h.default_image_alt = args.default_image_alt
        h.open_quote = args.open_quote
        h.close_quote = args.close_quote
    
        sys.stdout.write(h.handle(html))
    html2text-2020.1.16/html2text/config.py0000664000175000017500000000740113525235166017142 0ustar  jonjon00000000000000import re
    
    # Use Unicode characters instead of their ascii pseudo-replacements
    UNICODE_SNOB = False
    
    # Marker to use for marking tables for padding post processing
    TABLE_MARKER_FOR_PAD = "special_marker_for_table_padding"
    # Escape all special characters.  Output is less readable, but avoids
    # corner case formatting issues.
    ESCAPE_SNOB = False
    
    # Put the links after each paragraph instead of at the end.
    LINKS_EACH_PARAGRAPH = False
    
    # Wrap long lines at position. 0 for no wrapping.
    BODY_WIDTH = 78
    
    # Don't show internal links (href="#local-anchor") -- corresponding link
    # targets won't be visible in the plain text file anyway.
    SKIP_INTERNAL_LINKS = True
    
    # Use inline, rather than reference, formatting for images and links
    INLINE_LINKS = True
    
    # Protect links from line breaks surrounding them with angle brackets (in
    # addition to their square brackets)
    PROTECT_LINKS = False
    # WRAP_LINKS = True
    WRAP_LINKS = True
    
    # Wrap list items.
    WRAP_LIST_ITEMS = False
    
    # Number of pixels Google indents nested lists
    GOOGLE_LIST_INDENT = 36
    
    # Values Google and others may use to indicate bold text
    BOLD_TEXT_STYLE_VALUES = ("bold", "700", "800", "900")
    
    IGNORE_ANCHORS = False
    IGNORE_IMAGES = False
    IMAGES_AS_HTML = False
    IMAGES_TO_ALT = False
    IMAGES_WITH_SIZE = False
    IGNORE_EMPHASIS = False
    MARK_CODE = False
    DECODE_ERRORS = "strict"
    DEFAULT_IMAGE_ALT = ""
    PAD_TABLES = False
    
    # Convert links with same href and text to  format
    # if they are absolute links
    USE_AUTOMATIC_LINKS = True
    
    # For checking space-only lines on line 771
    RE_SPACE = re.compile(r"\s\+")
    
    RE_ORDERED_LIST_MATCHER = re.compile(r"\d+\.\s")
    RE_UNORDERED_LIST_MATCHER = re.compile(r"[-\*\+]\s")
    RE_MD_CHARS_MATCHER = re.compile(r"([\\\[\]\(\)])")
    RE_MD_CHARS_MATCHER_ALL = re.compile(r"([`\*_{}\[\]\(\)#!])")
    
    # to find links in the text
    RE_LINK = re.compile(r"(\[.*?\] ?\(.*?\))|(\[.*?\]:.*?)")
    
    RE_MD_DOT_MATCHER = re.compile(
        r"""
        ^             # start of line
        (\s*\d+)      # optional whitespace and a number
        (\.)          # dot
        (?=\s)        # lookahead assert whitespace
        """,
        re.MULTILINE | re.VERBOSE,
    )
    RE_MD_PLUS_MATCHER = re.compile(
        r"""
        ^
        (\s*)
        (\+)
        (?=\s)
        """,
        flags=re.MULTILINE | re.VERBOSE,
    )
    RE_MD_DASH_MATCHER = re.compile(
        r"""
        ^
        (\s*)
        (-)
        (?=\s|\-)     # followed by whitespace (bullet list, or spaced out hr)
                      # or another dash (header or hr)
        """,
        flags=re.MULTILINE | re.VERBOSE,
    )
    RE_SLASH_CHARS = r"\`*_{}[]()#+-.!"
    RE_MD_BACKSLASH_MATCHER = re.compile(
        r"""
        (\\)          # match one slash
        (?=[%s])      # followed by a char that requires escaping
        """
        % re.escape(RE_SLASH_CHARS),
        flags=re.VERBOSE,
    )
    
    UNIFIABLE = {
        "rsquo": "'",
        "lsquo": "'",
        "rdquo": '"',
        "ldquo": '"',
        "copy": "(C)",
        "mdash": "--",
        "nbsp": " ",
        "rarr": "->",
        "larr": "<-",
        "middot": "*",
        "ndash": "-",
        "oelig": "oe",
        "aelig": "ae",
        "agrave": "a",
        "aacute": "a",
        "acirc": "a",
        "atilde": "a",
        "auml": "a",
        "aring": "a",
        "egrave": "e",
        "eacute": "e",
        "ecirc": "e",
        "euml": "e",
        "igrave": "i",
        "iacute": "i",
        "icirc": "i",
        "iuml": "i",
        "ograve": "o",
        "oacute": "o",
        "ocirc": "o",
        "otilde": "o",
        "ouml": "o",
        "ugrave": "u",
        "uacute": "u",
        "ucirc": "u",
        "uuml": "u",
        "lrm": "",
        "rlm": "",
    }
    
    # Format tables in HTML rather than Markdown syntax
    BYPASS_TABLES = False
    # Ignore table-related tags (table, th, td, tr) while keeping rows
    IGNORE_TABLES = False
    
    
    # Use a single line break after a block element rather than two line breaks.
    # NOTE: Requires body width setting to be 0.
    SINGLE_LINE_BREAK = False
    
    
    # Use double quotation marks when converting the  tag.
    OPEN_QUOTE = '"'
    CLOSE_QUOTE = '"'
    html2text-2020.1.16/html2text/elements.py0000664000175000017500000000064713550376531017516 0ustar  jonjon00000000000000from typing import Dict, Optional
    
    
    class AnchorElement:
        __slots__ = ["attrs", "count", "outcount"]
    
        def __init__(self, attrs: Dict[str, Optional[str]], count: int, outcount: int):
            self.attrs = attrs
            self.count = count
            self.outcount = outcount
    
    
    class ListElement:
        __slots__ = ["name", "num"]
    
        def __init__(self, name: str, num: int):
            self.name = name
            self.num = num
    html2text-2020.1.16/html2text/py.typed0000664000175000017500000000000013550376531017006 0ustar  jonjon00000000000000html2text-2020.1.16/html2text/typing.py0000664000175000017500000000010713550376531017203 0ustar  jonjon00000000000000class OutCallback:
        def __call__(self, s: str) -> None:
            ...
    html2text-2020.1.16/html2text/utils.py0000664000175000017500000001754413610067134017037 0ustar  jonjon00000000000000import html.entities
    from typing import Dict, List, Optional
    
    from . import config
    
    unifiable_n = {
        html.entities.name2codepoint[k]: v
        for k, v in config.UNIFIABLE.items()
        if k != "nbsp"
    }
    
    
    def hn(tag: str) -> int:
        if tag[0] == "h" and len(tag) == 2:
            n = tag[1]
            if "0" < n <= "9":
                return int(n)
        return 0
    
    
    def dumb_property_dict(style: str) -> Dict[str, str]:
        """
        :returns: A hash of css attributes
        """
        return {
            x.strip().lower(): y.strip().lower()
            for x, y in [z.split(":", 1) for z in style.split(";") if ":" in z]
        }
    
    
    def dumb_css_parser(data: str) -> Dict[str, Dict[str, str]]:
        """
        :type data: str
    
        :returns: A hash of css selectors, each of which contains a hash of
        css attributes.
        :rtype: dict
        """
        # remove @import sentences
        data += ";"
        importIndex = data.find("@import")
        while importIndex != -1:
            data = data[0:importIndex] + data[data.find(";", importIndex) + 1 :]
            importIndex = data.find("@import")
    
        # parse the css. reverted from dictionary comprehension in order to
        # support older pythons
        pairs = [x.split("{") for x in data.split("}") if "{" in x.strip()]
        try:
            elements = {a.strip(): dumb_property_dict(b) for a, b in pairs}
        except ValueError:
            elements = {}  # not that important
    
        return elements
    
    
    def element_style(
        attrs: Dict[str, Optional[str]],
        style_def: Dict[str, Dict[str, str]],
        parent_style: Dict[str, str],
    ) -> Dict[str, str]:
        """
        :type attrs: dict
        :type style_def: dict
        :type style_def: dict
    
        :returns: A hash of the 'final' style attributes of the element
        :rtype: dict
        """
        style = parent_style.copy()
        if "class" in attrs:
            assert attrs["class"] is not None
            for css_class in attrs["class"].split():
                css_style = style_def.get("." + css_class, {})
                style.update(css_style)
        if "style" in attrs:
            assert attrs["style"] is not None
            immediate_style = dumb_property_dict(attrs["style"])
            style.update(immediate_style)
    
        return style
    
    
    def google_list_style(style: Dict[str, str]) -> str:
        """
        Finds out whether this is an ordered or unordered list
    
        :type style: dict
    
        :rtype: str
        """
        if "list-style-type" in style:
            list_style = style["list-style-type"]
            if list_style in ["disc", "circle", "square", "none"]:
                return "ul"
    
        return "ol"
    
    
    def google_has_height(style: Dict[str, str]) -> bool:
        """
        Check if the style of the element has the 'height' attribute
        explicitly defined
    
        :type style: dict
    
        :rtype: bool
        """
        return "height" in style
    
    
    def google_text_emphasis(style: Dict[str, str]) -> List[str]:
        """
        :type style: dict
    
        :returns: A list of all emphasis modifiers of the element
        :rtype: list
        """
        emphasis = []
        if "text-decoration" in style:
            emphasis.append(style["text-decoration"])
        if "font-style" in style:
            emphasis.append(style["font-style"])
        if "font-weight" in style:
            emphasis.append(style["font-weight"])
    
        return emphasis
    
    
    def google_fixed_width_font(style: Dict[str, str]) -> bool:
        """
        Check if the css of the current element defines a fixed width font
    
        :type style: dict
    
        :rtype: bool
        """
        font_family = ""
        if "font-family" in style:
            font_family = style["font-family"]
        return "courier new" == font_family or "consolas" == font_family
    
    
    def list_numbering_start(attrs: Dict[str, Optional[str]]) -> int:
        """
        Extract numbering from list element attributes
    
        :type attrs: dict
    
        :rtype: int or None
        """
        if "start" in attrs:
            assert attrs["start"] is not None
            try:
                return int(attrs["start"]) - 1
            except ValueError:
                pass
    
        return 0
    
    
    def skipwrap(para: str, wrap_links: bool, wrap_list_items: bool) -> bool:
        # If it appears to contain a link
        # don't wrap
        if not wrap_links and config.RE_LINK.search(para):
            return True
        # If the text begins with four spaces or one tab, it's a code block;
        # don't wrap
        if para[0:4] == "    " or para[0] == "\t":
            return True
    
        # If the text begins with only two "--", possibly preceded by
        # whitespace, that's an emdash; so wrap.
        stripped = para.lstrip()
        if stripped[0:2] == "--" and len(stripped) > 2 and stripped[2] != "-":
            return False
    
        # I'm not sure what this is for; I thought it was to detect lists,
        # but there's a 
    -inside- case in one of the tests that # also depends upon it. if stripped[0:1] in ("-", "*") and not stripped[0:2] == "**": return not wrap_list_items # If the text begins with a single -, *, or +, followed by a space, # or an integer, followed by a ., followed by a space (in either # case optionally proceeded by whitespace), it's a list; don't wrap. return bool( config.RE_ORDERED_LIST_MATCHER.match(stripped) or config.RE_UNORDERED_LIST_MATCHER.match(stripped) ) def escape_md(text: str) -> str: """ Escapes markdown-sensitive characters within other markdown constructs. """ return config.RE_MD_CHARS_MATCHER.sub(r"\\\1", text) def escape_md_section(text: str, snob: bool = False) -> str: """ Escapes markdown-sensitive characters across whole document sections. """ text = config.RE_MD_BACKSLASH_MATCHER.sub(r"\\\1", text) if snob: text = config.RE_MD_CHARS_MATCHER_ALL.sub(r"\\\1", text) text = config.RE_MD_DOT_MATCHER.sub(r"\1\\\2", text) text = config.RE_MD_PLUS_MATCHER.sub(r"\1\\\2", text) text = config.RE_MD_DASH_MATCHER.sub(r"\1\\\2", text) return text def reformat_table(lines: List[str], right_margin: int) -> List[str]: """ Given the lines of a table padds the cells and returns the new lines """ # find the maximum width of the columns max_width = [len(x.rstrip()) + right_margin for x in lines[0].split("|")] max_cols = len(max_width) for line in lines: cols = [x.rstrip() for x in line.split("|")] num_cols = len(cols) # don't drop any data if colspan attributes result in unequal lengths if num_cols < max_cols: cols += [""] * (max_cols - num_cols) elif max_cols < num_cols: max_width += [len(x) + right_margin for x in cols[-(num_cols - max_cols) :]] max_cols = num_cols max_width = [ max(len(x) + right_margin, old_len) for x, old_len in zip(cols, max_width) ] # reformat new_lines = [] for line in lines: cols = [x.rstrip() for x in line.split("|")] if set(line.strip()) == set("-|"): filler = "-" new_cols = [ x.rstrip() + (filler * (M - len(x.rstrip()))) for x, M in zip(cols, max_width) ] else: filler = " " new_cols = [ x.rstrip() + (filler * (M - len(x.rstrip()))) for x, M in zip(cols, max_width) ] new_lines.append("|".join(new_cols)) return new_lines def pad_tables_in_text(text: str, right_margin: int = 1) -> str: """ Provide padding for tables in the text """ lines = text.split("\n") table_buffer = [] # type: List[str] table_started = False new_lines = [] for line in lines: # Toggle table started if config.TABLE_MARKER_FOR_PAD in line: table_started = not table_started if not table_started: table = reformat_table(table_buffer, right_margin) new_lines.extend(table) table_buffer = [] new_lines.append("") continue # Process lines if table_started: table_buffer.append(line) else: new_lines.append(line) return "\n".join(new_lines) html2text-2020.1.16/html2text.egg-info/0000775000175000017500000000000013610070526017003 5ustar jonjon00000000000000html2text-2020.1.16/html2text.egg-info/PKG-INFO0000664000175000017500000001156413610070526020107 0ustar jonjon00000000000000Metadata-Version: 2.1 Name: html2text Version: 2020.1.16 Summary: Turn HTML into equivalent Markdown-structured text. Home-page: https://github.com/Alir3z4/html2text/ Author: Aaron Swartz Author-email: me@aaronsw.com Maintainer: Alireza Savand Maintainer-email: alireza.savand@gmail.com License: GNU GPL 3 Description: # html2text [![Build Status](https://secure.travis-ci.org/Alir3z4/html2text.png)](https://travis-ci.org/Alir3z4/html2text) [![Coverage Status](https://coveralls.io/repos/Alir3z4/html2text/badge.png)](https://coveralls.io/r/Alir3z4/html2text) [![Downloads](http://badge.kloud51.com/pypi/d/html2text.png)](https://pypi.org/project/html2text/) [![Version](http://badge.kloud51.com/pypi/v/html2text.png)](https://pypi.org/project/html2text/) [![Wheel?](http://badge.kloud51.com/pypi/wheel/html2text.png)](https://pypi.org/project/html2text/) [![Format](http://badge.kloud51.com/pypi/format/html2text.png)](https://pypi.org/project/html2text/) [![License](http://badge.kloud51.com/pypi/license/html2text.png)](https://pypi.org/project/html2text/) html2text is a Python script that converts a page of HTML into clean, easy-to-read plain ASCII text. Better yet, that ASCII also happens to be valid Markdown (a text-to-HTML format). Usage: `html2text [filename [encoding]]` | Option | Description |--------------------------------------------------------|--------------------------------------------------- | `--version` | Show program's version number and exit | `-h`, `--help` | Show this help message and exit | `--ignore-links` | Don't include any formatting for links |`--escape-all` | Escape all special characters. Output is less readable, but avoids corner case formatting issues. | `--reference-links` | Use reference links instead of links to create markdown | `--mark-code` | Mark preformatted and code blocks with [code]...[/code] For a complete list of options see the [docs](https://github.com/Alir3z4/html2text/blob/master/docs/usage.md) Or you can use it from within `Python`: ``` >>> import html2text >>> >>> print(html2text.html2text("

    Zed's dead baby, Zed's dead.

    ")) **Zed's** dead baby, _Zed's_ dead. ``` Or with some configuration options: ``` >>> import html2text >>> >>> h = html2text.HTML2Text() >>> # Ignore converting links from HTML >>> h.ignore_links = True >>> print h.handle("

    Hello, world!") Hello, world! >>> print(h.handle("

    Hello, world!")) Hello, world! >>> # Don't Ignore links anymore, I like links >>> h.ignore_links = False >>> print(h.handle("

    Hello, world!")) Hello, [world](https://www.google.com/earth/)! ``` *Originally written by Aaron Swartz. This code is distributed under the GPLv3.* ## How to install `html2text` is available on pypi https://pypi.org/project/html2text/ ``` $ pip install html2text ``` ## How to run unit tests tox To see the coverage results: coverage html then open the `./htmlcov/index.html` file in your browser. ## Documentation Documentation lives [here](https://github.com/Alir3z4/html2text/blob/master/docs/usage.md) Platform: OS Independent Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=3.5 Description-Content-Type: text/markdown html2text-2020.1.16/html2text.egg-info/SOURCES.txt0000664000175000017500000000722213610070526020672 0ustar jonjon00000000000000AUTHORS.rst COPYING ChangeLog.rst MANIFEST.in README.md setup.cfg setup.py tox.ini html2text/__init__.py html2text/__main__.py html2text/cli.py html2text/config.py html2text/elements.py html2text/py.typed html2text/typing.py html2text/utils.py html2text.egg-info/PKG-INFO html2text.egg-info/SOURCES.txt html2text.egg-info/dependency_links.txt html2text.egg-info/entry_points.txt html2text.egg-info/not-zip-safe html2text.egg-info/top_level.txt test/GoogleDocMassDownload.html test/GoogleDocMassDownload.md test/GoogleDocSaved.html test/GoogleDocSaved.md test/GoogleDocSaved_two.html test/GoogleDocSaved_two.md test/__init__.py test/abbr_tag.html test/abbr_tag.md test/anchors.html test/anchors.md test/apos_element.html test/apos_element.md test/blockquote_example.html test/blockquote_example.md test/bodywidth_newline.html test/bodywidth_newline.md test/bold_inside_link.html test/bold_inside_link.md test/bold_long_line.html test/bold_long_line.md test/break_preserved_in_blockquote.html test/break_preserved_in_blockquote.md test/css_import_no_semicolon.html test/css_import_no_semicolon.md test/decript_tage.html test/decript_tage.md test/default_image_alt.html test/default_image_alt.md test/doc_with_table.html test/doc_with_table.md test/doc_with_table_bypass.html test/doc_with_table_bypass.md test/emdash-para.html test/emdash-para.md test/emphasis_preserved_whitespace.html test/emphasis_preserved_whitespace.md test/empty-link.html test/empty-link.md test/empty-title-tag.html test/empty-title-tag.md test/flip_emphasis.html test/flip_emphasis.md test/google-like_font-properties.html test/google-like_font-properties.md test/header_tags.html test/header_tags.md test/horizontal_rule.html test/horizontal_rule.md test/html-escaping.html test/html-escaping.md test/html_entities_out_of_text.html test/html_entities_out_of_text.md test/images_as_html.html test/images_as_html.md test/images_to_alt.html test/images_to_alt.md test/images_with_div_wrap.html test/images_with_div_wrap.md test/images_with_size.html test/images_with_size.md test/img-tag-with-link.html test/img-tag-with-link.md test/inplace_baseurl_substitution.html test/inplace_baseurl_substitution.md test/invalid_start.html test/invalid_start.md test/invalid_unicode.html test/invalid_unicode.md test/kbd_tag.html test/kbd_tag.md test/link_titles.html test/link_titles.md test/list_tags_example.html test/list_tags_example.md test/long_lines.html test/long_lines.md test/lrm_after_b.html test/lrm_after_b.md test/lrm_after_i.html test/lrm_after_i.md test/lrm_inside_i.html test/lrm_inside_i.md test/mark_code.html test/mark_code.md test/nbsp.html test/nbsp.md test/nbsp_unicode.html test/nbsp_unicode.md test/no_inline_links_example.html test/no_inline_links_example.md test/no_inline_links_images_to_alt.html test/no_inline_links_images_to_alt.md test/no_inline_links_nested.html test/no_inline_links_nested.md test/no_wrap_links.html test/no_wrap_links.md test/no_wrap_links_no_inline_links.html test/no_wrap_links_no_inline_links.md test/normal.html test/normal.md test/normal_escape_snob.html test/normal_escape_snob.md test/pad_table.html test/pad_table.md test/pre.html test/pre.md test/preformatted_in_list.html test/preformatted_in_list.md test/protect_links.html test/protect_links.md test/q_tag.html test/q_tag.md test/rlm_inside_strong.html test/rlm_inside_strong.md test/single_line_break.html test/single_line_break.md test/stressed_with_html_entities.html test/stressed_with_html_entities.md test/table_ignore.html test/table_ignore.md test/test_html2text.py test/test_memleak.py test/text_after_list.html test/text_after_list.md test/url-escaping.html test/url-escaping.md test/wrap_list_items_example.html test/wrap_list_items_example.mdhtml2text-2020.1.16/html2text.egg-info/dependency_links.txt0000664000175000017500000000000113610070526023051 0ustar jonjon00000000000000 html2text-2020.1.16/html2text.egg-info/entry_points.txt0000664000175000017500000000006213610070526022277 0ustar jonjon00000000000000[console_scripts] html2text = html2text.cli:main html2text-2020.1.16/html2text.egg-info/not-zip-safe0000664000175000017500000000000113610070526021231 0ustar jonjon00000000000000 html2text-2020.1.16/html2text.egg-info/top_level.txt0000664000175000017500000000001213610070526021526 0ustar jonjon00000000000000html2text html2text-2020.1.16/setup.cfg0000664000175000017500000000262013610070526015177 0ustar jonjon00000000000000[metadata] name = html2text version = attr: html2text.__version__ description = Turn HTML into equivalent Markdown-structured text. long_description = file: README.md long_description_content_type = text/markdown url = https://github.com/Alir3z4/html2text/ author = Aaron Swartz author_email = me@aaronsw.com maintainer = Alireza Savand maintainer_email = alireza.savand@gmail.com license = GNU GPL 3 classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: GNU General Public License (GPL) Operating System :: OS Independent Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3 :: Only Programming Language :: Python :: Implementation :: CPython Programming Language :: Python :: Implementation :: PyPy platform = OS Independent [options] zip_safe = False packages = html2text python_requires = >=3.5 [options.entry_points] console_scripts = html2text = html2text.cli:main [options.package_data] html2text = py.typed [flake8] max_line_length = 88 ignore = E203 W503 [isort] combine_as_imports = True include_trailing_comma = True line_length = 88 multi_line_output = 3 [mypy] python_version = 3.5 [egg_info] tag_build = tag_date = 0 html2text-2020.1.16/setup.py0000664000175000017500000000004613556624753015110 0ustar jonjon00000000000000from setuptools import setup setup() html2text-2020.1.16/test/0000775000175000017500000000000013610070526014335 5ustar jonjon00000000000000html2text-2020.1.16/test/GoogleDocMassDownload.html0000664000175000017500000001352113542620133021402 0ustar jonjon00000000000000 Sandbox

    test doc

    first issue

    1. bit
    2. bold italic
    1. orange
    2. apple
    1. final

    text to separate lists

    1. now with numbers
    2. the prisoner
    1. not an italic number
    2. a bold human  being
    1. end

    bold

    italic

    def func(x):

      if x < 1:

        return 'a'

      return 'b'

    Some fixed width text  here

    italic fixed width text

    html2text-2020.1.16/test/GoogleDocMassDownload.md0000664000175000017500000000064313542620133021037 0ustar jonjon00000000000000# test doc first issue - bit - _**bold italic**_ - orange - apple - final text to separate lists 1. now with numbers 2. the prisoner 1. not an _italic number_ 2. a **bold human** being 3. end **bold** _italic_ ` def func(x):` ` if x < 1:` ` return 'a'` ` return 'b'` Some ` fixed width text` here _` italic fixed width text`_ html2text-2020.1.16/test/GoogleDocSaved.html0000664000175000017500000000743013542620133020053 0ustar jonjon00000000000000 Sandbox

    test doc

    first issue

    1. bit
    2. bold italic
    1. orange
    2. apple
    1. final

    text to separate lists

    1. now with numbers
    2. the prisoner
    1. not an italic number
    2. a bold human  being
    1. end

    bold

    italic

    def func(x):

      if x < 1:

        return 'a'

      return 'b'

    Some fixed width text  here

    italic fixed width text

    html2text-2020.1.16/test/GoogleDocSaved.md0000664000175000017500000000064313542620133017506 0ustar jonjon00000000000000# test doc first issue - bit - _**bold italic**_ - orange - apple - final text to separate lists 1. now with numbers 2. the prisoner 1. not an _italic number_ 2. a **bold human** being 3. end **bold** _italic_ ` def func(x):` ` if x < 1:` ` return 'a'` ` return 'b'` Some ` fixed width text` here _` italic fixed width text`_ html2text-2020.1.16/test/GoogleDocSaved_two.html0000664000175000017500000000746513542620133020754 0ustar jonjon00000000000000 Sandbox

    test doc

    first issue

    1. bit
    2. bold italic
    1. orange
    2. apple
    1. final

    text to separate lists

    1. now with numbers
    2. the prisoner
    1. not an italic number
    2. a bold human  being
    1. end

    bold

    italic

    def func(x):

      if x < 1:

        return 'a'

      return 'b'

    Some fixed width text  here

    italic fixed width text

    html2text-2020.1.16/test/GoogleDocSaved_two.md0000664000175000017500000000000013434106424020364 0ustar jonjon00000000000000html2text-2020.1.16/test/__init__.py0000664000175000017500000000000013434106424016435 0ustar jonjon00000000000000html2text-2020.1.16/test/abbr_tag.html0000664000175000017500000000007713434106424016771 0ustar jonjon00000000000000TLA xyz html2text-2020.1.16/test/abbr_tag.md0000664000175000017500000000005113542620133016413 0ustar jonjon00000000000000TLA xyz *[TLA]: Three Letter Acronym html2text-2020.1.16/test/anchors.html0000664000175000017500000000042713434106424016664 0ustar jonjon00000000000000

    Processing hyperlinks

    Additional hyperlink tests!

    Bold Link filename.py The source code is called magic.py html2text-2020.1.16/test/anchors.md0000664000175000017500000000032013542620133016306 0ustar jonjon00000000000000# Processing hyperlinks Additional hyperlink tests! [**Bold Link**](http://some.link) [`filename.py`](http://some.link/filename.py) [The source code is called `magic.py`](http://some.link/magicsources.py) html2text-2020.1.16/test/apos_element.html0000664000175000017500000000006513434106424017700 0ustar jonjon00000000000000 ' html2text-2020.1.16/test/apos_element.md0000664000175000017500000000000313542620133017322 0ustar jonjon00000000000000' html2text-2020.1.16/test/blockquote_example.html0000664000175000017500000000033313525235166021115 0ustar jonjon00000000000000
    "The time has come", the Walrus said, "To talk of many things: Of shoes - and ships - and sealing wax - Of cabbages - and kings- And why the sea is boiling hot - And whether pigs have wings."
    html2text-2020.1.16/test/blockquote_example.md0000664000175000017500000000030713542620133020541 0ustar jonjon00000000000000> "The time has come", the Walrus said, "To talk of many things: Of shoes - > and ships - and sealing wax - Of cabbages - and kings- And why the sea is > boiling hot - And whether pigs have wings." html2text-2020.1.16/test/bodywidth_newline.html0000664000175000017500000000055713434106424020751 0ustar jonjon00000000000000

    Another theory is that magician and occultist Aliester Crowley created the beast while attempting to summon evil spirits at his house on the edge of the lake in the early 1900′s. I met a local woman who prefers this explanation.

    html2text-2020.1.16/test/bodywidth_newline.md0000664000175000017500000000043413434106424020377 0ustar jonjon00000000000000Another theory is that magician and occultist [Aliester Crowley](http://en.wikipedia.org/wiki/Aleister_Crowley) created the beast while attempting to summon evil spirits at his house on the edge of the lake in the early 1900′s. **I met a local woman who prefers this explanation.** html2text-2020.1.16/test/bold_inside_link.html0000664000175000017500000000011113434106424020505 0ustar jonjon00000000000000Text sample html2text-2020.1.16/test/bold_inside_link.md0000664000175000017500000000005613542620133020147 0ustar jonjon00000000000000[**Text**](link.htm) [**sample**](/nothing/) html2text-2020.1.16/test/bold_long_line.html0000664000175000017500000000021113434106424020164 0ustar jonjon00000000000000

    text and a very long long long long long long long long long long long long long long long long long long long long line

    html2text-2020.1.16/test/bold_long_line.md0000664000175000017500000000017613542620133017630 0ustar jonjon00000000000000**text** and a very long long long long long long long long long long long long long long long long long long long long line html2text-2020.1.16/test/break_preserved_in_blockquote.html0000664000175000017500000000004113434106424023300 0ustar jonjon00000000000000a
    b
    c
    html2text-2020.1.16/test/break_preserved_in_blockquote.md0000664000175000017500000000001613542620133022734 0ustar jonjon00000000000000a > b > c html2text-2020.1.16/test/css_import_no_semicolon.html0000664000175000017500000000066213542620133022154 0ustar jonjon00000000000000 NBSP handling test #1

    CSS @import statement without semicolon handling test

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    html2text-2020.1.16/test/css_import_no_semicolon.md0000664000175000017500000000026713542620133021611 0ustar jonjon00000000000000# CSS @import statement without semicolon handling test Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. html2text-2020.1.16/test/decript_tage.html0000664000175000017500000000010113434106424017646 0ustar jonjon00000000000000something something something html2text-2020.1.16/test/decript_tage.md0000664000175000017500000000005313542620133017306 0ustar jonjon00000000000000~~something~~ ~~something~~ ~~something~~ html2text-2020.1.16/test/default_image_alt.html0000664000175000017500000000007613434106424020655 0ustar jonjon00000000000000 html2text-2020.1.16/test/default_image_alt.md0000664000175000017500000000006213542620133020302 0ustar jonjon00000000000000[![Image](images/google.png)](http://google.com) html2text-2020.1.16/test/doc_with_table.html0000664000175000017500000000131313434106424020171 0ustar jonjon00000000000000

    This is a test document

    With some text, code, bolds and italics.

    This is second header

    Displaynone text

    Header 1 Header 2 Header 3
    Content 1 Content 2 200 Image!
    Content 1 Content 2 200 Image!
    html2text-2020.1.16/test/doc_with_table.md0000664000175000017500000000046513542620133017632 0ustar jonjon00000000000000# This is a test document With some text, `code`, **bolds** and _italics_. ## This is second header Displaynone text Header 1 | Header 2 | Header 3 ---|---|--- Content 1 | Content 2 | ![200](http://lorempixel.com/200/200) Image! Content 1 | Content 2 | ![200](http://lorempixel.com/200/200) Image! html2text-2020.1.16/test/doc_with_table_bypass.html0000664000175000017500000000106613434106424021557 0ustar jonjon00000000000000

    This is a test document

    With some text, code, bolds and italics.

    This is second header

    Displaynone text

    Header 1 Header 2 Header 3
    Content 1 Content 2 200 Image!
    html2text-2020.1.16/test/doc_with_table_bypass.md0000664000175000017500000000053713542620133021213 0ustar jonjon00000000000000# This is a test document With some text, `code`, **bolds** and _italics_. ## This is second header Displaynone text
    Header 1 Header 2 Header 3
    Content 1 Content 2 ![200](http://lorempixel.com/200/200) Image!
    html2text-2020.1.16/test/emdash-para.html0000664000175000017500000000143713434106424017413 0ustar jonjon00000000000000

    Bacon ipsum dolor sit amet pork chop id pork belly ham hock, sed meatloaf eu exercitation flank quis veniam officia. Chuck dolor esse, occaecat est elit drumstick ground round tri-tip nisi. Eu fugiat drumstick leberkas magna. Turducken frankfurter nisi aute shank—

    —irure ex esse id, ham commodo meatloaf pig pariatur ut cow. Officia salami in fatback voluptate boudin ullamco beef ribs shank. Duis spare ribs pork chop, ad leberkas reprehenderit id voluptate salami ham ut in ut cillum turducken. Nisi ribeye tail capicola dolore andouille. Short ribs id beef ribs, et nulla ground round do sunt dolore. Dolore nisi ullamco veniam sunt. Duis brisket drumstick, dolor fatback filet mignon meatloaf laboris tri-tip speck chuck ball tip voluptate ullamco laborum.

    --

    html2text-2020.1.16/test/emdash-para.md0000664000175000017500000000140313542620133017036 0ustar jonjon00000000000000Bacon ipsum dolor sit amet pork chop id pork belly ham hock, sed meatloaf eu exercitation flank quis veniam officia. Chuck dolor esse, occaecat est elit drumstick ground round tri-tip nisi. Eu fugiat drumstick leberkas magna. Turducken frankfurter nisi aute shank-- --irure ex esse id, ham commodo meatloaf pig pariatur ut cow. Officia salami in fatback voluptate boudin ullamco beef ribs shank. Duis spare ribs pork chop, ad leberkas reprehenderit id voluptate salami ham ut in ut cillum turducken. Nisi ribeye tail capicola dolore andouille. Short ribs id beef ribs, et nulla ground round do sunt dolore. Dolore nisi ullamco veniam sunt. Duis brisket drumstick, dolor fatback filet mignon meatloaf laboris tri-tip speck chuck ball tip voluptate ullamco laborum. \-- html2text-2020.1.16/test/emphasis_preserved_whitespace.html0000664000175000017500000000075413434106424023336 0ustar jonjon00000000000000

    emphasis

    emphasis: some text

    repeat: again

    bold

    bold: some text

    repeat: again

    strike

    strike: some text

    strike: again

    separate emphasis some more text

    emphasis.

    emphasis?

    emphasis!

    em1em2

    html2text-2020.1.16/test/emphasis_preserved_whitespace.md0000664000175000017500000000036413542620133022765 0ustar jonjon00000000000000_emphasis_ _emphasis:_ some text _repeat:_ again **bold** **bold:** some text **repeat:** again ~~strike~~ ~~strike:~~ some text ~~strike:~~ again separate _emphasis_ some more text _emphasis_. _emphasis_? _emphasis_! _em1_ _em2_ html2text-2020.1.16/test/empty-link.html0000664000175000017500000000030313434106424017311 0ustar jonjon00000000000000

    Processing empty hyperlinks

    This test checks whether empty hyperlinks still appear in the markdown result.

    html2text-2020.1.16/test/empty-link.md0000664000175000017500000000023313542620133016745 0ustar jonjon00000000000000# Processing empty hyperlinks This test checks whether empty hyperlinks still appear in the markdown result. [](http://some.link) [](http://some.link) html2text-2020.1.16/test/empty-title-tag.html0000664000175000017500000000011313434106424020245 0ustar jonjon00000000000000This is an A tag with an empty title propertyhtml2text-2020.1.16/test/empty-title-tag.md0000664000175000017500000000007413542620133017705 0ustar jonjon00000000000000[This is an A tag with an empty title property](test.html) html2text-2020.1.16/test/flip_emphasis.html0000664000175000017500000000003513434106424020045 0ustar jonjon00000000000000Something else html2text-2020.1.16/test/flip_emphasis.md0000664000175000017500000000002613542620133017477 0ustar jonjon00000000000000*Something* __else__ html2text-2020.1.16/test/google-like_font-properties.html0000664000175000017500000000173113434106424022644 0ustar jonjon00000000000000 CAPS-LOCK TEST

    font-weight: bold

    FONT-WEIGHT: BOLD

    font-weight: 700

    FONT-WEIGHT: 700

    font-weight: 800

    FONT-WEIGHT: 800

    font-weight: 900

    FONT-WEIGHT: 900

    font-style: italic

    FONT-STYLE: ITALIC

    font-weight: bold;font-style: italic

    FONT-WEIGHT: BOLD;FONT-STYLE: ITALIC

    html2text-2020.1.16/test/google-like_font-properties.md0000664000175000017500000000051413542620133022274 0ustar jonjon00000000000000**font-weight: bold** **FONT-WEIGHT: BOLD** **font-weight: 700** **FONT-WEIGHT: 700** **font-weight: 800** **FONT-WEIGHT: 800** **font-weight: 900** **FONT-WEIGHT: 900** _font-style: italic_ _FONT-STYLE: ITALIC_ _**font-weight: bold;font-style: italic**_ _**FONT-WEIGHT: BOLD;FONT-STYLE: ITALIC**_ html2text-2020.1.16/test/header_tags.html0000664000175000017500000000040413434106424017470 0ustar jonjon00000000000000

    H1

    H2

    H3

    H4

    H5
    H6
    H7 H8 H9 H10 H11 H12 NO number html2text-2020.1.16/test/header_tags.md0000664000175000017500000000016113542620133017122 0ustar jonjon00000000000000# H1 ## H2 ### H3 #### H4 ##### H5 ###### H6 ####### H7 ######## H8 ######### H9 H10 H11 H12 NO number html2text-2020.1.16/test/horizontal_rule.html0000664000175000017500000000005713434106424020446 0ustar jonjon00000000000000
    html2text-2020.1.16/test/horizontal_rule.md0000664000175000017500000000000713542620133020073 0ustar jonjon00000000000000* * * html2text-2020.1.16/test/html-escaping.html0000664000175000017500000000027113434106424017757 0ustar jonjon00000000000000

    Escaped HTML like <div> or & should NOT remain escaped on output

    ...even when that escaped HTML is in a <pre> tag
    ...or a <code> taghtml2text-2020.1.16/test/html-escaping.md0000664000175000017500000000023013542620133017404 0ustar jonjon00000000000000Escaped HTML like
    or & should NOT remain escaped on output ...even when that escaped HTML is in a
     tag
    
    `...or a  tag`
    
    html2text-2020.1.16/test/html_entities_out_of_text.html0000664000175000017500000000007313434106424022513 0ustar  jonjon00000000000000állás: Country Manager
    html2text-2020.1.16/test/html_entities_out_of_text.md0000664000175000017500000000004713542620133022146 0ustar  jonjon00000000000000[allas: Country Manager](http://thth)
    
    html2text-2020.1.16/test/images_as_html.html0000664000175000017500000000115713434106424020204 0ustar  jonjon00000000000000
    
    An image with a width attr
    
    An image with a height attr
    
    An image with width and height
    
    
    
    html2text-2020.1.16/test/images_as_html.md0000664000175000017500000000065713542620133017642 0ustar  jonjon00000000000000 An image with a width attr An image with a height attr
    An
    image with width and height  
    
    html2text-2020.1.16/test/images_to_alt.html0000664000175000017500000000044013434106424020031 0ustar  jonjon00000000000000
    ALT TEXT
    
    
    ALT TEXT
    http://example.comhtml2text-2020.1.16/test/images_to_alt.md0000664000175000017500000000013213542620133017461 0ustar jonjon00000000000000[ ALT TEXT ](http://example.com) [ALT TEXT](http://example.com) html2text-2020.1.16/test/images_with_div_wrap.html0000664000175000017500000000012413434106424021414 0ustar jonjon00000000000000
    html2text-2020.1.16/test/images_with_div_wrap.md0000664000175000017500000000006713542620133021054 0ustar jonjon00000000000000[![](http://example.com/img.png)](http://example.com) html2text-2020.1.16/test/images_with_size.html0000664000175000017500000000115113434106424020554 0ustar jonjon00000000000000An image without dimensions An image with a width attr An image with a height attr An image with width and height html2text-2020.1.16/test/images_with_size.md0000664000175000017500000000067013542620133020213 0ustar jonjon00000000000000![An image without dimensions](image_without_dimensions.jpg) An image with a width attr An image with a height attr An
image with width and height ![](image_with_width_and_height.jpg) html2text-2020.1.16/test/img-tag-with-link.html0000664000175000017500000000124413434106424020456 0ustar jonjon00000000000000

    Processing images with links

    This test checks images with associated links.

    (banana) [banana] {banana} ([{}]) html2text-2020.1.16/test/img-tag-with-link.md0000664000175000017500000000066513542620133020116 0ustar jonjon00000000000000# Processing images with links This test checks images with associated links. [![\(banana\)](http://placehold.it/350x150#\(banana\))](http://some.link) [![\[banana\]](http://placehold.it/350x150#\[banana\])](http://some.link) [![{banana}](http://placehold.it/350x150#{banana})](http://some.link) [![\(\[{}\]\)](http://placehold.it/350x150#\(\[{}\]\))](http://some.link) [![](http://placehold.it/350x150#\(\[{}\]\))](http://some.link) html2text-2020.1.16/test/inplace_baseurl_substitution.html0000664000175000017500000000032113434106424023204 0ustar jonjon00000000000000

    read2text header image

    BrettTerpstra.com

    html2text-2020.1.16/test/inplace_baseurl_substitution.md0000664000175000017500000000021013434106424022635 0ustar jonjon00000000000000![read2text header image](http://brettterpstra.com/uploads/2012/01/read2textheader.jpg) [BrettTerpstra.com](http://brettterpstra.com/) html2text-2020.1.16/test/invalid_start.html0000664000175000017500000000025013434106424020064 0ustar jonjon00000000000000
    1. The ol has an invalid start
    2. This should just be ignored
    html2text-2020.1.16/test/invalid_start.md0000664000175000017500000000010513542620133017515 0ustar jonjon00000000000000 1. The ol has an invalid start 2. This should just be ignored html2text-2020.1.16/test/invalid_unicode.html0000664000175000017500000000001513434106424020354 0ustar jonjon00000000000000B�r html2text-2020.1.16/test/invalid_unicode.md0000664000175000017500000000000413542620133020004 0ustar jonjon00000000000000Br html2text-2020.1.16/test/kbd_tag.html0000664000175000017500000000004313434106424016614 0ustar jonjon00000000000000Press [CTRL]+c to copy. html2text-2020.1.16/test/kbd_tag.md0000664000175000017500000000003313542620133016245 0ustar jonjon00000000000000Press `[CTRL]+c` to copy. html2text-2020.1.16/test/link_titles.html0000664000175000017500000000016713434106424017551 0ustar jonjon00000000000000 first example
    second example html2text-2020.1.16/test/link_titles.md0000664000175000017500000000013013542620133017171 0ustar jonjon00000000000000[ first example](http://example.com "MyTitle") [ second example](http://example.com) html2text-2020.1.16/test/list_tags_example.html0000664000175000017500000000123313434106424020727 0ustar jonjon00000000000000
    Definition List
    A list of terms and their definitions/descriptions.
    Ordered List
    A numbered list.
    Unordered List
    An unnumbered list.

    Example 2

    Vocals
    Bruce Dickinson
    Guitar
    Adrian Smith
    Dave Murray
    Janick Gers
    Bass
    Steve Harris
    Drums
    Nicko McBrain
    • some item
    • Some other item
    • some item
    1. Some other item
    2. some item
    3. some item
    • something else here
    • some item
    html2text-2020.1.16/test/list_tags_example.md0000664000175000017500000000066713542620133020373 0ustar jonjon00000000000000Definition List A list of terms and their definitions/descriptions. Ordered List A numbered list. Unordered List An unnumbered list. #### Example 2 Vocals Bruce Dickinson Guitar Adrian Smith Dave Murray Janick Gers Bass Steve Harris Drums Nicko McBrain * some item * Some other item * some item 1. Some other item 2. some item 3. some item * something else here * some item html2text-2020.1.16/test/long_lines.html0000664000175000017500000000165313434106424017362 0ustar jonjon00000000000000asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd html2text-2020.1.16/test/long_lines.md0000664000175000017500000000164513542620133017015 0ustar jonjon00000000000000asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd ![](http://www.foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.com) asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd html2text-2020.1.16/test/lrm_after_b.html0000664000175000017500000000002013442727054017477 0ustar jonjon00000000000000b‎ html2text-2020.1.16/test/lrm_after_b.md0000664000175000017500000000000713542620133017127 0ustar jonjon00000000000000**b** html2text-2020.1.16/test/lrm_after_i.html0000664000175000017500000000001713434106424017505 0ustar jonjon00000000000000Foo‎html2text-2020.1.16/test/lrm_after_i.md0000664000175000017500000000000713542620133017136 0ustar jonjon00000000000000_Foo_ html2text-2020.1.16/test/lrm_inside_i.html0000664000175000017500000000002213434106424017653 0ustar jonjon00000000000000Foo‎barhtml2text-2020.1.16/test/lrm_inside_i.md0000664000175000017500000000001313542620133017305 0ustar jonjon00000000000000_Foo bar_ html2text-2020.1.16/test/mark_code.html0000664000175000017500000000023213434106424017145 0ustar jonjon00000000000000

    Normal text with 'pre' code block.

    import os
    
    def function():
        a = 1
    

    Normal text continues.

    html2text-2020.1.16/test/mark_code.md0000664000175000017500000000020713542620133016601 0ustar jonjon00000000000000Normal text with 'pre' code block. [code] import os def function(): a = 1 [/code] Normal text continues. html2text-2020.1.16/test/nbsp.html0000664000175000017500000000141213542620133016162 0ustar jonjon00000000000000 NBSP handling test #1

    NBSP handling test #1

    In this test all NBSPs will be replaced with ordinary spaces (unicode_snob = False).

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    html2text-2020.1.16/test/nbsp.md0000664000175000017500000000106013542620133015615 0ustar jonjon00000000000000# NBSP handling test #1 In this test all NBSPs will be replaced with ordinary spaces (unicode_snob = False). Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. html2text-2020.1.16/test/nbsp_unicode.html0000664000175000017500000000142413434106424017675 0ustar jonjon00000000000000 NBSP handling test #2

    NBSP handling test #2

    In this test all NBSPs will be replaced with unicode non-breaking spaces (unicode_snob = True).

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    html2text-2020.1.16/test/nbsp_unicode.md0000664000175000017500000000110713542620133017325 0ustar jonjon00000000000000# NBSP handling test #2 In this test all NBSPs will be replaced with unicode non-breaking spaces (unicode_snob = True). Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. html2text-2020.1.16/test/no_inline_links_example.html0000664000175000017500000000050413434106424022110 0ustar jonjon00000000000000Googler No href No href but title available Example link text html2text-2020.1.16/test/no_inline_links_example.md0000664000175000017500000000030613542620133021542 0ustar jonjon00000000000000[Googler][1] No href No href but title available [ Example][2] [ [ [ link text ][3]][3]][3] [1]: http://google.com [2]: http://example.com (Example title) [3]: http://example.com (abc) html2text-2020.1.16/test/no_inline_links_images_to_alt.html0000664000175000017500000000044113434106424023264 0ustar jonjon00000000000000 ALT TEXT
    ALT TEXT
    http://example.com html2text-2020.1.16/test/no_inline_links_images_to_alt.md0000664000175000017500000000021513542620133022715 0ustar jonjon00000000000000[ ![ALT TEXT][1] ][2] [![ALT TEXT][1]][2] [![http://example.com][1]][2] [1]: http://example.com/img.png [2]: http://example.com html2text-2020.1.16/test/no_inline_links_nested.html0000664000175000017500000000007713434106424021744 0ustar jonjon00000000000000thisthat html2text-2020.1.16/test/no_inline_links_nested.md0000664000175000017500000000010013542620133021361 0ustar jonjon00000000000000[[this][1]that][2] [1]: /test2/ [2]: http://google.com html2text-2020.1.16/test/no_wrap_links.html0000664000175000017500000000022713434106424020072 0ustar jonjon00000000000000And here is a long link I had at hand.

    html2text-2020.1.16/test/no_wrap_links.md0000664000175000017500000000021113542620133017515 0ustar jonjon00000000000000And [here](http://bugs.debian.org/cgi-bin/pkgreport.cgi?tag=multiarch;users=debian-dpkg@lists.debian.org) is a long link I had at hand. html2text-2020.1.16/test/no_wrap_links_no_inline_links.html0000664000175000017500000000022313434106424023320 0ustar jonjon00000000000000And here is a long link I had at hand. html2text-2020.1.16/test/no_wrap_links_no_inline_links.md0000664000175000017500000000021213542620133022750 0ustar jonjon00000000000000And [here](http://bugs.debian.org/cgi-bin/pkgreport.cgi?tag=multiarch;users=debian-dpkg@lists.debian.org) is a long link I had at hand. html2text-2020.1.16/test/normal.html0000664000175000017500000000433513434106424016521 0ustar jonjon00000000000000 Normal

    test doc

    first issue

    • bit
    • bold italic
      • orange
      • apple
    • final

    text to separate lists

    1. now with numbers
    2. the prisoner
      1. not an italic number
      2. a bold human being
    3. end

    bold
    italic

    def func(x):
      if x < 1:
        return 'a'
      return 'b'
          

    Some fixed width text here
    italic fixed width text

    2012. Now that was a good year. So was 2011. That's all.

    3.14159 is an approximation of pi.

    + not + a list item

    +foo

    - foo - bar

    -foo

    not a header
    --

    not a hr

    ---
    - - -

    c:\tmp, \\server\path, \_/, foo\bar, #\#, \\#

    html2text-2020.1.16/test/normal.md0000664000175000017500000000120513542620133016144 0ustar jonjon00000000000000# test doc first issue * bit * _**bold italic**_ * orange * apple * final text to separate lists 1. now with numbers 2. the prisoner 1. not an _italic number_ 2. a **bold human** being 3. end **bold** _italic_ def func(x): if x < 1: return 'a' return 'b' Some `fixed width text` here _`italic fixed width text`_ 2012\. Now that was a good year. So was 2011. That's all. 3.14159 is an approximation of pi. \+ not + a list item +foo \- foo - bar -foo not a header \-- not a hr \--- \- - - c:\tmp, \\\server\path, \\_/, foo\bar, #\\#, \\\\# html2text-2020.1.16/test/normal_escape_snob.html0000664000175000017500000000443013542620133021054 0ustar jonjon00000000000000 Normal

    test doc

    first issue

    • bit
    • bold italic
      • orange
      • apple
    • final

    text to separate lists

    1. now with numbers
    2. the prisoner
      1. not an italic number
      2. a bold human being
    3. end

    bold
    italic
    text with _underscore but not _italicized

    def func(x):
      if x < 1:
        return 'a'
      return 'b'
          

    Some fixed width text here
    italic fixed width text

    2012. Now that was a good year. So was 2011. That's all.

    3.14159 is an approximation of pi.

    + not + a list item

    +foo

    - foo - bar

    -foo

    not a header
    --

    not a hr

    ---
    - - -

    c:\tmp, \\server\path, \_/, foo\bar, #\#, \\#

    html2text-2020.1.16/test/normal_escape_snob.md0000664000175000017500000000126713542620133020515 0ustar jonjon00000000000000# test doc first issue * bit * _**bold italic**_ * orange * apple * final text to separate lists 1. now with numbers 2. the prisoner 1. not an _italic number_ 2. a **bold human** being 3. end **bold** _italic_ text with \_underscore but not \_italicized def func(x): if x < 1: return 'a' return 'b' Some `fixed width text` here _`italic fixed width text`_ 2012\. Now that was a good year. So was 2011. That's all. 3.14159 is an approximation of pi. \+ not + a list item +foo \- foo - bar -foo not a header \-- not a hr \--- \- - - c:\tmp, \\\server\path, \\\_/, foo\bar, \#\\\#, \\\\\# html2text-2020.1.16/test/pad_table.html0000664000175000017500000000375513542620133017147 0ustar jonjon00000000000000

    This is a test document

    With some text, code, bolds and italics.

    This is second header

    Displaynone text

    Header 1 Header 2 Header 3
    Content 1 2 200 Image!
    Content 1 longer Content 2 blah
    Content Content 2 blah
    t Content 2 blah blah blah
    H1 H2 H3
    C1 Content 2 x
    C123 Content 2 xyz
    some content between the tables
    Header 1 Header 2 Header 3
    Content 1 Content 2 200 Image!
    Content 1 Content 2 longer 200 Image!
    something else entirely
    OneTwoThree
    ABC
    AB+C
    A+BC
    A+B+C
    One+TwoThree
    ABC
    AB+C
    A+BC
    A+B+C
    html2text-2020.1.16/test/pad_table.md0000664000175000017500000000233713542620133016576 0ustar jonjon00000000000000# This is a test document With some text, `code`, **bolds** and _italics_. ## This is second header Displaynone text Header 1 | Header 2 | Header 3 -----------------|-----------|---------------------------------------------- Content 1 | 2 | ![200](http://lorempixel.com/200/200) Image! Content 1 longer | Content 2 | blah Content | Content 2 | blah t | Content 2 | blah blah blah H1 | H2 | H3 -----|-----------|----- C1 | Content 2 | x C123 | Content 2 | xyz some content between the tables Header 1 | Header 2 | Header 3 ----------|------------------|---------------------------------------------- Content 1 | Content 2 | ![200](http://lorempixel.com/200/200) Image! Content 1 | Content 2 longer | ![200](http://lorempixel.com/200/200) Image! something else entirely One | Two | Three ------|-----|------- A | B | C A | B+C A+B | C A+B+C One+Two | Three --------|------- A | B | C A | B+C A+B | C A+B+C html2text-2020.1.16/test/pre.html0000664000175000017500000000037013434106424016012 0ustar jonjon00000000000000 initial crowded pre handling test #1
    a
    b
    c

    Ensure that HTML that starts with a crowded <pre> is converted to reasonable Markdown.

    html2text-2020.1.16/test/pre.md0000664000175000017500000000015613542620133015446 0ustar jonjon00000000000000 a b c Ensure that HTML that starts with a crowded `
    ` is converted to reasonable
    Markdown.
    
    html2text-2020.1.16/test/preformatted_in_list.html0000664000175000017500000000017013434106424021437 0ustar  jonjon00000000000000
    
    
    • Run this command:
      ls -l *.html
    • ?
    • Profit!
    html2text-2020.1.16/test/preformatted_in_list.md0000664000175000017500000000010513542620133021067 0ustar jonjon00000000000000 * Run this command: ls -l *.html * ? * Profit! html2text-2020.1.16/test/protect_links.html0000664000175000017500000000013613434106424020104 0ustar jonjon00000000000000foohtml2text-2020.1.16/test/protect_links.md0000664000175000017500000000013013542620133017530 0ustar jonjon00000000000000[foo]() html2text-2020.1.16/test/q_tag.html0000664000175000017500000000007713434106424016323 0ustar jonjon00000000000000If this is a test, he said, then it should pass. html2text-2020.1.16/test/q_tag.md0000664000175000017500000000006613542620133015753 0ustar jonjon00000000000000"If this is a test," he said, "then it should pass". html2text-2020.1.16/test/rlm_inside_strong.html0000664000175000017500000000003413434106424020742 0ustar jonjon00000000000000Foo‏barhtml2text-2020.1.16/test/rlm_inside_strong.md0000664000175000017500000000001513542620133020373 0ustar jonjon00000000000000**Foo bar** html2text-2020.1.16/test/single_line_break.html0000664000175000017500000000030613434106424020657 0ustar jonjon00000000000000
    Hello world.
    And hello html2text.
    html2text-2020.1.16/test/single_line_break.md0000664000175000017500000000004213434106424020310 0ustar jonjon00000000000000Hello world. And hello html2text. html2text-2020.1.16/test/stressed_with_html_entities.html0000664000175000017500000000005513435524347023054 0ustar jonjon00000000000000

    hello world ><

    html2text-2020.1.16/test/stressed_with_html_entities.md0000664000175000017500000000002413542620133022471 0ustar jonjon00000000000000**hello** world >< html2text-2020.1.16/test/table_ignore.html0000664000175000017500000000250413542620133017655 0ustar jonjon00000000000000

    This is a test document

    With some text, code, bolds and italics.

    This is second header

    Displaynone text

    Header 1 Header 2 Header 3
    Content 1 2 200 Image!
    Content 1 longer Content 2 blah
    Content Content 2 blah
    t Content 2 blah blah blah
    H1 H2 H3
    C1 Content 2 x
    C123 Content 2 xyz
    some content between the tables
    Header 1 Header 2 Header 3
    Content 1 Content 2 200 Image!
    Content 1 Content 2 longer 200 Image!
    something else entirely html2text-2020.1.16/test/table_ignore.md0000664000175000017500000000110113542620133017301 0ustar jonjon00000000000000# This is a test document With some text, `code`, **bolds** and _italics_. ## This is second header Displaynone text Header 1 Header 2 Header 3 Content 1 2 ![200](http://lorempixel.com/200/200) Image! Content 1 longer Content 2 blah Content Content 2 blah t Content 2 blah blah blah H1 H2 H3 C1 Content 2 x C123 Content 2 xyz some content between the tables Header 1 Header 2 Header 3 Content 1 Content 2 ![200](http://lorempixel.com/200/200) Image! Content 1 Content 2 longer ![200](http://lorempixel.com/200/200) Image! something else entirely html2text-2020.1.16/test/test_html2text.py0000664000175000017500000001534413610067134017711 0ustar jonjon00000000000000import glob import os import re import subprocess import sys import html2text import pytest skip = object() def cleanup_eol(clean_str): if os.name == "nt" or sys.platform == "cygwin": # Fix the unwanted CR to CRCRLF replacement # during text pipelining on Windows/cygwin # on cygwin, os.name == 'posix', not nt clean_str = re.sub(r"\r+", "\r", clean_str) clean_str = clean_str.replace("\r\n", "\n") return clean_str def generate_testdata(): test_dir_name = os.path.dirname(os.path.realpath(__file__)) for fn in glob.glob("%s/*.html" % test_dir_name): module_args = {} cmdline_args = [] func_args = {} base_fn = os.path.basename(fn).lower() if base_fn.startswith("default_image_alt"): module_args["default_image_alt"] = "Image" cmdline_args.append("--default-image-alt=Image") func_args = skip if base_fn.startswith("google"): module_args["google_doc"] = True cmdline_args.append("--googledoc") func_args = skip if base_fn.find("unicode") >= 0: module_args["unicode_snob"] = True cmdline_args.append("--unicode-snob") func_args = skip if base_fn.find("flip_emphasis") >= 0: module_args["emphasis_mark"] = "*" module_args["strong_mark"] = "__" cmdline_args.append("-e") func_args = skip if base_fn.find("escape_snob") >= 0: module_args["escape_snob"] = True cmdline_args.append("--escape-all") func_args = skip if base_fn.find("table_bypass") >= 0: module_args["bypass_tables"] = True cmdline_args.append("--bypass-tables") func_args = skip if base_fn.startswith("table_ignore"): module_args["ignore_tables"] = True cmdline_args.append("--ignore-tables") func_args = skip if base_fn.startswith("bodywidth"): module_args["body_width"] = 0 cmdline_args.append("--body-width=0") func_args["bodywidth"] = 0 if base_fn.startswith("protect_links"): module_args["protect_links"] = True cmdline_args.append("--protect-links") func_args = skip if base_fn.startswith("images_as_html"): module_args["images_as_html"] = True cmdline_args.append("--images-as-html") func_args = skip if base_fn.startswith("images_to_alt"): module_args["images_to_alt"] = True cmdline_args.append("--images-to-alt") func_args = skip if base_fn.startswith("images_with_size"): module_args["images_with_size"] = True cmdline_args.append("--images-with-size") func_args = skip if base_fn.startswith("single_line_break"): module_args["body_width"] = 0 cmdline_args.append("--body-width=0") module_args["single_line_break"] = True cmdline_args.append("--single-line-break") func_args = skip if base_fn.startswith("no_inline_links"): module_args["inline_links"] = False cmdline_args.append("--reference-links") func_args = skip if base_fn.startswith("no_wrap_links"): module_args["wrap_links"] = False cmdline_args.append("--no-wrap-links") func_args = skip if base_fn.startswith("mark_code"): module_args["mark_code"] = True cmdline_args.append("--mark-code") func_args = skip if base_fn.startswith("pad_table"): module_args["pad_tables"] = True cmdline_args.append("--pad-tables") func_args = skip if base_fn.startswith("wrap_list_items"): module_args["wrap_list_items"] = True cmdline_args.append("--wrap-list-items") func_args = skip if base_fn == "inplace_baseurl_substitution.html": module_args["baseurl"] = "http://brettterpstra.com" module_args["body_width"] = 0 func_args["baseurl"] = "http://brettterpstra.com" func_args["bodywidth"] = 0 # CLI doesn't support baseurl. cmdline_args = skip yield fn, module_args, cmdline_args, func_args def generate_module_testdata(): for fn, module_args, cmdline_args, func_args in generate_testdata(): yield fn, module_args def generate_command_testdata(): for fn, module_args, cmdline_args, func_args in generate_testdata(): if cmdline_args is not skip: yield fn, cmdline_args def generate_function_testdata(): for fn, module_args, cmdline_args, func_args in generate_testdata(): if func_args is not skip: yield fn, func_args @pytest.mark.parametrize("fn,module_args", generate_module_testdata()) def test_module(fn, module_args): h = html2text.HTML2Text() h.fn = fn if module_args.pop("google_doc", False): h.google_doc = True h.ul_item_mark = "-" h.body_width = 0 h.hide_strikethrough = True for k, v in module_args.items(): setattr(h, k, v) result = get_baseline(fn) with open(fn) as inf: actual = cleanup_eol(inf.read()) actual = h.handle(actual) assert result == actual @pytest.mark.parametrize("fn,cmdline_args", generate_command_testdata()) def test_command(fn, cmdline_args): args = list(cmdline_args) cmd = [sys.executable, "-m", "html2text"] if "--googledoc" in args: args.remove("--googledoc") cmd += ["-g", "-d", "-b", "0", "-s"] if args: cmd.extend(args) cmd += [fn] result = get_baseline(fn) out = subprocess.check_output(cmd) actual = out.decode() actual = cleanup_eol(actual) assert result == actual @pytest.mark.parametrize("fn,func_args", generate_function_testdata()) def test_function(fn, func_args): with open(fn) as inf: actual = html2text.html2text(inf.read(), **func_args) result = get_baseline(fn) assert result == actual def get_baseline_name(fn): return os.path.splitext(fn)[0] + ".md" def get_baseline(fn): name = get_baseline_name(fn) with open(name, encoding="utf-8") as f: out = f.read() return cleanup_eol(out) def test_tag_callback(): def _skip_certain_tags(h2t, tag, attrs, start): if tag == "b": return True h = html2text.HTML2Text() h.tag_callback = _skip_certain_tags ret = h.handle( 'this is a txt and this is a with text and ' "some italics too." ) assert ret == ("this is a txt and this is a with text and some _italics_ too.\n\n") html2text-2020.1.16/test/test_memleak.py0000664000175000017500000000131713542615105017365 0ustar jonjon00000000000000import html2text # See https://github.com/Alir3z4/html2text/issues/13 for more information. INSTR = "miow " def test_same_string(): h2t = html2text.HTML2Text() result = h2t.handle(INSTR) # Now, we shouldn't get leak of the previous run to the new one. assert h2t.handle(INSTR) == result def test_empty_string(): h2t = html2text.HTML2Text() h2t.handle(INSTR) # And even less when the input is empty. assert h2t.handle("") == "\n\n" def test_abbr_data(): h2t = html2text.HTML2Text() result = h2t.handle('

    foo TLA bar

    ') assert result == "foo TLA bar\n\n *[TLA]: Three Letter Acronym\n\n" assert h2t.abbr_data is None html2text-2020.1.16/test/text_after_list.html0000664000175000017500000000003413434106424020421 0ustar jonjon00000000000000
    • item
    text html2text-2020.1.16/test/text_after_list.md0000664000175000017500000000002013542620133020046 0ustar jonjon00000000000000 * item text html2text-2020.1.16/test/url-escaping.html0000664000175000017500000000253113434106424017616 0ustar jonjon00000000000000

    Markdown-sensible characters processing

    This test checks special characters processing inside URLs: parenthesis and brackets should be escaped to keep markdown image and anchor syntax safe and sound.

    And here are images with tricky attribute values:

    (banana)
    [banana]
    {banana}
    ([{}]) html2text-2020.1.16/test/url-escaping.md0000664000175000017500000000203013542620133017242 0ustar jonjon00000000000000# Markdown-sensible characters processing This test checks special characters processing inside URLs: parenthesis and brackets should be escaped to keep markdown image and anchor syntax safe and sound. * [Some MSDN link using parenthesis](http://msdn.microsoft.com/en-us/library/system.drawing.drawing2d\(v=vs.110\)) * [Google search result URL with unescaped brackets](https://www.google.ru/search?q=\[brackets are cool\]) * [Yet another test for [brackets], {curly braces} and (parenthesis) processing inside the anchor](https://www.google.ru/search?q='\[\({}\)\]') * Use automatic links like when the URL is the label * Exempt [non-absolute_URIs](non-absolute_URIs) from automatic link detection And here are images with tricky attribute values: ![\(banana\)](http://placehold.it/350x150#\(banana\)) ![\[banana\]](http://placehold.it/350x150#\[banana\]) ![{banana}](http://placehold.it/350x150#{banana}) ![\(\[{}\]\)](http://placehold.it/350x150#\(\[{}\]\)) ![](http://placehold.it/350x150#\(\[{}\]\)) html2text-2020.1.16/test/wrap_list_items_example.html0000664000175000017500000000116613434106424022150 0ustar jonjon00000000000000
    • One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty.
    • One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty.
    Text between lists.
    • One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty.
    • One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty.
    Text after list. html2text-2020.1.16/test/wrap_list_items_example.md0000664000175000017500000000113513542620133021576 0ustar jonjon00000000000000 * One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty. * One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty. Text between lists. * One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty. * One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty. Text after list. html2text-2020.1.16/tox.ini0000664000175000017500000000115613556624753014714 0ustar jonjon00000000000000[tox] envlist = black flake8 isort mypy py{35,36,37,38,py3} minversion = 1.9 [testenv] commands = pytest --cov=html2text {posargs} deps = pytest pytest-cov [testenv:black] basepython = python3 commands = black --target-version py35 --check --diff . deps = black skip_install = true [testenv:flake8] basepython = python3 commands = flake8 deps = flake8 skip_install = true [testenv:isort] basepython = python3 commands = isort --check-only --diff deps = isort skip_install = true [testenv:mypy] commands = mypy --strict html2text deps = mypy skip_install = true