html2text-2016.1.8/0000755000175000017500000000000012643763140014600 5ustar ubuntuubuntu00000000000000html2text-2016.1.8/README.md0000644000175000017500000000625012616413406016057 0ustar ubuntuubuntu00000000000000# html2text [![Build Status](https://secure.travis-ci.org/Alir3z4/html2text.png)](http://travis-ci.org/Alir3z4/html2text) [![Coverage Status](https://coveralls.io/repos/Alir3z4/html2text/badge.png)](https://coveralls.io/r/Alir3z4/html2text) [![Downloads](https://pypip.in/d/html2text/badge.png)](https://pypi.python.org/pypi/html2text/) [![Version](https://pypip.in/v/html2text/badge.png)](https://pypi.python.org/pypi/html2text/) [![Egg?](https://pypip.in/egg/html2text/badge.png)](https://pypi.python.org/pypi/html2text/) [![Wheel?](https://pypip.in/wheel/html2text/badge.png)](https://pypi.python.org/pypi/html2text/) [![Format](https://pypip.in/format/html2text/badge.png)](https://pypi.python.org/pypi/html2text/) [![License](https://pypip.in/license/html2text/badge.png)](https://pypi.python.org/pypi/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|url) [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](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](http://earth.google.com/)! ``` *Originally written by Aaron Swartz. This code is distributed under the GPLv3.* ## How to install `html2text` is available on pypi https://pypi.python.org/pypi/html2text ``` $ pip install html2text ``` ## How to run unit tests PYTHONPATH=$PYTHONPATH:. coverage run --source=html2text setup.py test -v To see the coverage results: coverage combine coverage html then open the `./htmlcov/index.html` file in your browser. ## Documentation Documentation lives [here](docs/index.md) html2text-2016.1.8/html2text.egg-info/0000755000175000017500000000000012643763140020225 5ustar ubuntuubuntu00000000000000html2text-2016.1.8/html2text.egg-info/not-zip-safe0000644000175000017500000000000112471110761022445 0ustar ubuntuubuntu00000000000000 html2text-2016.1.8/html2text.egg-info/SOURCES.txt0000644000175000017500000000474712643763140022125 0ustar ubuntuubuntu00000000000000AUTHORS.rst COPYING ChangeLog.rst MANIFEST.in README.md setup.cfg setup.py html2text/__init__.py html2text/cli.py html2text/compat.py html2text/config.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/css_import_no_semicolon.html test/css_import_no_semicolon.md test/decript_tage.html test/decript_tage.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/empty-link.html test/empty-link.md test/flip_emphasis.html test/flip_emphasis.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_to_alt.html test/images_to_alt.md test/images_with_size.html test/images_with_size.md test/img-tag-with-link.html test/img-tag-with-link.md test/invalid_start.html test/invalid_start.md test/invalid_unicode.html test/invalid_unicode.md test/link_titles.html test/link_titles.md test/list_tags_example.html test/list_tags_example.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/pre.html test/pre.md test/preformatted_in_list.html test/preformatted_in_list.md test/protect_links.html test/protect_links.md test/single_line_break.html test/single_line_break.md test/test_html2text.py test/test_memleak.py test/url-escaping.html test/url-escaping.mdhtml2text-2016.1.8/html2text.egg-info/PKG-INFO0000644000175000017500000000211512643763137021327 0ustar ubuntuubuntu00000000000000Metadata-Version: 1.1 Name: html2text Version: 2016.1.8 Summary: Turn HTML into equivalent Markdown-structured text. Home-page: https://github.com/Alir3z4/html2text/ Author: Alireza Savand Author-email: alireza.savand@gmail.com License: GNU GPL 3 Description: UNKNOWN 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 :: 2 Classifier: Programming Language :: Python :: 2.4 Classifier: Programming Language :: Python :: 2.5 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.0 Classifier: Programming Language :: Python :: 3.1 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 html2text-2016.1.8/html2text.egg-info/entry_points.txt0000644000175000017500000000010412643763137023524 0ustar ubuntuubuntu00000000000000 [console_scripts] html2text=html2text.cli:main html2text-2016.1.8/html2text.egg-info/dependency_links.txt0000644000175000017500000000000112643763137024301 0ustar ubuntuubuntu00000000000000 html2text-2016.1.8/html2text.egg-info/top_level.txt0000644000175000017500000000001212643763137022756 0ustar ubuntuubuntu00000000000000html2text html2text-2016.1.8/ChangeLog.rst0000644000175000017500000001007112643762527017170 0ustar ubuntuubuntu000000000000002016.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 a 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: http://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-2016.1.8/test/0000755000175000017500000000000012643763140015557 5ustar ubuntuubuntu00000000000000html2text-2016.1.8/test/html_entities_out_of_text.md0000644000175000017500000000004712616413406023366 0ustar ubuntuubuntu00000000000000[allas: Country Manager](http://thth) html2text-2016.1.8/test/doc_with_table_bypass.html0000664000175000017500000000106612471110237022772 0ustar ubuntuubuntu00000000000000

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-2016.1.8/test/anchors.html0000644000175000017500000000042712534002430020070 0ustar ubuntuubuntu00000000000000

Processing hyperlinks

Additional hyperlink tests!

Bold Link filename.py The source code is called magic.py html2text-2016.1.8/test/no_inline_links_nested.html0000644000175000017500000000007712616413406023162 0ustar ubuntuubuntu00000000000000thisthat html2text-2016.1.8/test/invalid_unicode.md0000644000175000017500000000000412616413406021224 0ustar ubuntuubuntu00000000000000Br html2text-2016.1.8/test/html_entities_out_of_text.html0000644000175000017500000000007312616413406023731 0ustar ubuntuubuntu00000000000000állás: Country Manager html2text-2016.1.8/test/__init__.py0000664000175000017500000000000012471110237017650 0ustar ubuntuubuntu00000000000000html2text-2016.1.8/test/emdash-para.md0000664000175000017500000000140312471110237020253 0ustar ubuntuubuntu00000000000000Bacon 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-2016.1.8/test/css_import_no_semicolon.html0000664000175000017500000000066212471110237023371 0ustar ubuntuubuntu00000000000000 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-2016.1.8/test/blockquote_example.html0000644000175000017500000000013012616413406022317 0ustar ubuntuubuntu00000000000000
The time has come, the Walrus said, to speak of many things.
html2text-2016.1.8/test/test_memleak.py0000664000175000017500000000155712471110237020605 0ustar ubuntuubuntu00000000000000import sys if sys.version_info[:2] < (2, 7): import unittest2 as unittest else: import unittest import logging logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=logging.DEBUG) import html2text class TestMemleak(unittest.TestCase): """ See https://github.com/Alir3z4/html2text/issues/13 for more information on this. """ def setUp(self): self.instr = 'miow ' def test_same_string(self): h2t = html2text.HTML2Text() result = h2t.handle(self.instr) # Now, we shouldn't get leak of the previous run to the new one self.assertEqual(h2t.handle(self.instr), result) def test_empty_string(self): h2t = html2text.HTML2Text() h2t.handle(self.instr) # And even less when the input is empty self.assertEqual(h2t.handle(''), '\n\n') html2text-2016.1.8/test/normal.md0000664000175000017500000000120512471110237017361 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/doc_with_table.md0000664000175000017500000000046512471110237021047 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/no_inline_links_nested.md0000644000175000017500000000010012616413406022601 0ustar ubuntuubuntu00000000000000[[this][1]that][2] [1]: /test2/ [2]: http://google.com html2text-2016.1.8/test/html-escaping.md0000644000175000017500000000023312534002430020615 0ustar ubuntuubuntu00000000000000Escaped HTML like <div> or & should remain escaped on output ...unless that escaped HTML is in a
 tag

`...or a  tag`

html2text-2016.1.8/test/decript_tage.md0000644000175000017500000000005312643762105020531 0ustar  ubuntuubuntu00000000000000~~something~~ ~~something~~ ~~something~~

html2text-2016.1.8/test/bodywidth_newline.html0000664000175000017500000000055712471110237022164 0ustar  ubuntuubuntu00000000000000

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-2016.1.8/test/normal_escape_snob.md0000664000175000017500000000126712471110237021732 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/GoogleDocSaved.html0000644000175000017500000000743012616413406021273 0ustar ubuntuubuntu00000000000000 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-2016.1.8/test/html-escaping.html0000644000175000017500000000026212534002430021163 0ustar ubuntuubuntu00000000000000

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

...unless that escaped HTML is in a <pre> tag
...or a <code> taghtml2text-2016.1.8/test/apos_element.md0000644000175000017500000000000312616413406020542 0ustar ubuntuubuntu00000000000000' html2text-2016.1.8/test/blockquote_example.md0000644000175000017500000000010012616413406021750 0ustar ubuntuubuntu00000000000000> The time has come, the Walrus said, to speak of many things. html2text-2016.1.8/test/flip_emphasis.md0000644000175000017500000000002612616413406020717 0ustar ubuntuubuntu00000000000000*Something* __else__ html2text-2016.1.8/test/url-escaping.md0000664000175000017500000000203012471110237020457 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/list_tags_example.html0000644000175000017500000000123212616413406022144 0ustar ubuntuubuntu00000000000000
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
  • somthing else here
  • some item
html2text-2016.1.8/test/mark_code.html0000644000175000017500000000023212616413406020363 0ustar ubuntuubuntu00000000000000

Normal text with 'pre' code block.

import os

def function():
    a = 1

Normal text continues.

html2text-2016.1.8/test/empty-link.html0000664000175000017500000000030212471110237020523 0ustar ubuntuubuntu00000000000000

Processing empty hyperlinks

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

html2text-2016.1.8/test/bold_inside_link.html0000644000175000017500000000011112616414143021722 0ustar ubuntuubuntu00000000000000Text sample html2text-2016.1.8/test/nbsp.md0000664000175000017500000000106012471110237017032 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/normal_escape_snob.html0000664000175000017500000000443012471110237022271 0ustar ubuntuubuntu00000000000000 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-2016.1.8/test/nbsp_unicode.html0000664000175000017500000000142412471110237021110 0ustar ubuntuubuntu00000000000000 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-2016.1.8/test/abbr_tag.md0000644000175000017500000000005112616413406017633 0ustar ubuntuubuntu00000000000000TLA xyz *[TLA]: Three Letter Acronym html2text-2016.1.8/test/pre.html0000664000175000017500000000037012471110237017225 0ustar ubuntuubuntu00000000000000 initial crowsed pre handling test #1
a
b
c

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

html2text-2016.1.8/test/flip_emphasis.html0000644000175000017500000000003512616413406021263 0ustar ubuntuubuntu00000000000000Something else html2text-2016.1.8/test/images_to_alt.html0000664000175000017500000000044012471110237021244 0ustar ubuntuubuntu00000000000000 ALT TEXT
ALT TEXT
http://example.comhtml2text-2016.1.8/test/link_titles.html0000644000175000017500000000016712616413406020767 0ustar ubuntuubuntu00000000000000 first example
second example html2text-2016.1.8/test/header_tags.md0000644000175000017500000000016112616413406020342 0ustar ubuntuubuntu00000000000000# H1 ## H2 ### H3 #### H4 ##### H5 ###### H6 ####### H7 ######## H8 ######### H9 H10 H11 H12 NO number html2text-2016.1.8/test/doc_with_table_bypass.md0000664000175000017500000000053712471110237022430 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/invalid_unicode.html0000644000175000017500000000001512616413406021572 0ustar ubuntuubuntu00000000000000B�r html2text-2016.1.8/test/protect_links.html0000664000175000017500000000013612471110237021317 0ustar ubuntuubuntu00000000000000foohtml2text-2016.1.8/test/no_wrap_links_no_inline_links.html0000644000175000017500000000022312616413406024536 0ustar ubuntuubuntu00000000000000And here is a long link I had at hand. html2text-2016.1.8/test/doc_with_table.html0000664000175000017500000000131312471110237021404 0ustar ubuntuubuntu00000000000000

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-2016.1.8/test/list_tags_example.md0000644000175000017500000000066412616413406021610 0ustar ubuntuubuntu00000000000000Definition 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 * somthing else here * some item html2text-2016.1.8/test/empty-link.md0000664000175000017500000000023212471110237020161 0ustar ubuntuubuntu00000000000000# Processing empty hyperlinks This test checks wheter empty hyperlinks still appear in the markdown result. [](http://some.link) [](http://some.link) html2text-2016.1.8/test/nbsp_unicode.md0000664000175000017500000000110712471110237020542 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/emdash-para.html0000664000175000017500000000143712471110237020626 0ustar ubuntuubuntu00000000000000

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-2016.1.8/test/normal.html0000664000175000017500000000433512471110237017734 0ustar ubuntuubuntu00000000000000 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-2016.1.8/test/apos_element.html0000644000175000017500000000006512616413406021116 0ustar ubuntuubuntu00000000000000 ' html2text-2016.1.8/test/no_inline_links_example.html0000644000175000017500000000050412616413406023326 0ustar ubuntuubuntu00000000000000Googler No href No href but title available Example link text html2text-2016.1.8/test/pre.md0000664000175000017500000000015612471110237016663 0ustar ubuntuubuntu00000000000000 a b c Ensure that HTML that starts with a crowded `
` is converted to reasonable
Markdown.

html2text-2016.1.8/test/nbsp.html0000664000175000017500000000141212471110237017377 0ustar  ubuntuubuntu00000000000000
  
    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-2016.1.8/test/anchors.md0000644000175000017500000000032012534002430017514 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/images_with_size.html0000644000175000017500000000115112616413406021772 0ustar ubuntuubuntu00000000000000An image without dimensions An image with a width attr An image with a height attr An image with width and height html2text-2016.1.8/test/protect_links.md0000664000175000017500000000013012471110237020745 0ustar ubuntuubuntu00000000000000[foo]() html2text-2016.1.8/test/img-tag-with-link.html0000664000175000017500000000124412471110237021671 0ustar ubuntuubuntu00000000000000

Processing images with links

This test checks images with associated links.

(banana) [banana] {banana} ([{}]) html2text-2016.1.8/test/bodywidth_newline.md0000664000175000017500000000043412471110237021612 0ustar ubuntuubuntu00000000000000Another 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-2016.1.8/test/preformatted_in_list.html0000664000175000017500000000017012471110237022652 0ustar ubuntuubuntu00000000000000
  • Run this command:
    ls -l *.html
  • ?
  • Profit!
html2text-2016.1.8/test/bold_inside_link.md0000644000175000017500000000005612616414204021364 0ustar ubuntuubuntu00000000000000[**Text**](link.htm) [**sample**](/nothing/) html2text-2016.1.8/test/preformatted_in_list.md0000664000175000017500000000010512471110237022304 0ustar ubuntuubuntu00000000000000 * Run this command: ls -l *.html * ? * Profit! html2text-2016.1.8/test/invalid_start.md0000664000175000017500000000010512471110237020732 0ustar ubuntuubuntu00000000000000 1. The ol has an invalid start 2. This should just be ignored html2text-2016.1.8/test/GoogleDocMassDownload.html0000644000175000017500000001352112616413406022622 0ustar ubuntuubuntu00000000000000 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-2016.1.8/test/images_to_alt.md0000664000175000017500000000013212471110237020676 0ustar ubuntuubuntu00000000000000[ ALT TEXT ](http://example.com) [ALT TEXT](http://example.com) html2text-2016.1.8/test/header_tags.html0000644000175000017500000000040412616413406020706 0ustar ubuntuubuntu00000000000000

H1

H2

H3

H4

H5
H6
H7 H8 H9 H10 H11 H12 NO number html2text-2016.1.8/test/single_line_break.md0000664000175000017500000000004212471110237021523 0ustar ubuntuubuntu00000000000000Hello world. And hello html2text. html2text-2016.1.8/test/single_line_break.html0000664000175000017500000000030612471110237022072 0ustar ubuntuubuntu00000000000000
Hello world.
And hello html2text.
html2text-2016.1.8/test/no_wrap_links_no_inline_links.md0000644000175000017500000000021212616413406024170 0ustar ubuntuubuntu00000000000000And [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-2016.1.8/test/img-tag-with-link.md0000664000175000017500000000066512471110237021333 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/invalid_start.html0000664000175000017500000000025012471110237021277 0ustar ubuntuubuntu00000000000000
  1. The ol has an invalid start
  2. This should just be ignored
html2text-2016.1.8/test/no_wrap_links.md0000644000175000017500000000021112616413406020735 0ustar ubuntuubuntu00000000000000And [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-2016.1.8/test/test_html2text.py0000644000175000017500000001224412616413406021123 0ustar ubuntuubuntu00000000000000import codecs import glob import os import re import subprocess import sys if sys.version_info[:2] < (2, 7): import unittest2 as unittest else: import unittest import logging logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=logging.DEBUG) import html2text def test_module(fn, google_doc=False, **kwargs): h = html2text.HTML2Text() h.fn = fn if google_doc: h.google_doc = True h.ul_item_mark = '-' h.body_width = 0 h.hide_strikethrough = True for k, v in kwargs.items(): setattr(h, k, v) result = get_baseline(fn) inf = open(fn) actual = h.handle(inf.read()) inf.close() return result, actual def test_command(fn, *args): args = list(args) cmd = [sys.executable, '-m', 'html2text.__init__'] if '--googledoc' in args: args.remove('--googledoc') cmd += ['-g', '-d', '-b', '0', '-s'] if args: cmd.extend(args) cmd += [fn] result = get_baseline(fn) pid = subprocess.Popen(cmd, stdout=subprocess.PIPE) out, _ = pid.communicate() actual = out.decode('utf8') if os.name == 'nt': # Fix the unwanted CR to CRCRLF replacement # during text pipelining on Windows/cygwin actual = re.sub(r'\r+', '\r', actual) actual = actual.replace('\r\n', '\n') return result, actual def test_function(fn, **kwargs): with open(fn) as inf: actual = html2text.html2text(inf.read(), **kwargs) result = get_baseline(fn) return result, actual def get_dump_name(fn, suffix): return '%s-%s_output.md' % (os.path.splitext(fn)[0], suffix) def get_baseline_name(fn): return os.path.splitext(fn)[0] + '.md' def get_baseline(fn): name = get_baseline_name(fn) f = codecs.open(name, mode='r', encoding='utf8') out = f.read() f.close() return out class TestHTML2Text(unittest.TestCase): pass def generate_test(fn): def test_mod(self): self.maxDiff = None result, actual = test_module(fn, **module_args) self.assertEqual(result, actual) def test_cmd(self): # Because there is no command-line option to control unicode_snob if 'unicode_snob' not in module_args: self.maxDiff = None result, actual = test_command(fn, *cmdline_args) self.assertEqual(result, actual) def test_func(self): result, actual = test_function(fn, **func_args) self.assertEqual(result, actual) module_args = {} cmdline_args = [] func_args = {} base_fn = os.path.basename(fn).lower() if base_fn.startswith('google'): module_args['google_doc'] = True cmdline_args.append('--googledoc') if base_fn.find('unicode') >= 0: module_args['unicode_snob'] = True if base_fn.find('flip_emphasis') >= 0: module_args['emphasis_mark'] = '*' module_args['strong_mark'] = '__' cmdline_args.append('-e') if base_fn.find('escape_snob') >= 0: module_args['escape_snob'] = True cmdline_args.append('--escape-all') if base_fn.find('table_bypass') >= 0: module_args['bypass_tables'] = True cmdline_args.append('--bypass-tables') if base_fn.startswith('bodywidth'): # module_args['unicode_snob'] = True 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') if base_fn.startswith('images_to_alt'): module_args['images_to_alt'] = True cmdline_args.append('--images-to-alt') if base_fn.startswith('images_with_size'): module_args['images_with_size'] = True cmdline_args.append('--images-with-size') 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') if base_fn.startswith('no_inline_links'): module_args['inline_links'] = False cmdline_args.append('--reference-links') if base_fn.startswith('no_wrap_links'): module_args['wrap_links'] = False cmdline_args.append('--no-wrap-links') if base_fn.startswith('mark_code'): module_args['mark_code'] = True cmdline_args.append('--mark-code') if base_fn not in ['bodywidth_newline.html', 'abbr_tag.html']: test_func = None return test_mod, test_cmd, test_func # Originally from http://stackoverflow.com/questions/32899/\ # how-to-generate-dynamic-parametrized-unit-tests-in-python test_dir_name = os.path.dirname(os.path.realpath(__file__)) for fn in glob.glob("%s/*.html" % test_dir_name): test_name = 'test_%s' % os.path.splitext(os.path.basename(fn))[0].lower() test_m, test_c, test_func = generate_test(fn) setattr(TestHTML2Text, test_name + "_mod", test_m) if test_c: setattr(TestHTML2Text, test_name + "_cmd", test_c) if test_func: setattr(TestHTML2Text, test_name + "_func", test_func) if __name__ == "__main__": unittest.main() html2text-2016.1.8/test/url-escaping.html0000664000175000017500000000251112471110237021027 0ustar ubuntuubuntu00000000000000

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-2016.1.8/test/GoogleDocSaved_two.md0000644000175000017500000000000012616413406021602 0ustar ubuntuubuntu00000000000000html2text-2016.1.8/test/GoogleDocMassDownload.md0000664000175000017500000000064312471110237022254 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/css_import_no_semicolon.md0000664000175000017500000000026712471110237023026 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/no_wrap_links.html0000644000175000017500000000022712616413406021310 0ustar ubuntuubuntu00000000000000And here is a long link I had at hand.

html2text-2016.1.8/test/mark_code.md0000644000175000017500000000020712616413406020021 0ustar ubuntuubuntu00000000000000Normal text with 'pre' code block. [code] import os def function(): a = 1 [/code] Normal text continues. html2text-2016.1.8/test/no_inline_links_images_to_alt.md0000644000175000017500000000021512616413406024135 0ustar ubuntuubuntu00000000000000[ ![ALT TEXT][1] ][2] [![ALT TEXT][1]][2] [![http://example.com][1]][2] [1]: http://example.com/img.png [2]: http://example.com html2text-2016.1.8/test/abbr_tag.html0000644000175000017500000000007712616413406020207 0ustar ubuntuubuntu00000000000000TLA xyz html2text-2016.1.8/test/GoogleDocSaved.md0000664000175000017500000000064312471110237020723 0ustar ubuntuubuntu00000000000000# 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-2016.1.8/test/GoogleDocSaved_two.html0000644000175000017500000000746512616413406022174 0ustar ubuntuubuntu00000000000000 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-2016.1.8/test/no_inline_links_example.md0000644000175000017500000000030612616413406022762 0ustar ubuntuubuntu00000000000000[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-2016.1.8/test/images_with_size.md0000644000175000017500000000067012616413406021433 0ustar ubuntuubuntu00000000000000![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-2016.1.8/test/link_titles.md0000644000175000017500000000013112616413406020412 0ustar ubuntuubuntu00000000000000[ first example](http://example.com "MyTitle" ) [ second example](http://example.com) html2text-2016.1.8/test/horizontal_rule.html0000644000175000017500000000005712616413406021664 0ustar ubuntuubuntu00000000000000
html2text-2016.1.8/test/horizontal_rule.md0000644000175000017500000000000712616413406021313 0ustar ubuntuubuntu00000000000000* * * html2text-2016.1.8/test/decript_tage.html0000644000175000017500000000010112616413406021064 0ustar ubuntuubuntu00000000000000something something something html2text-2016.1.8/test/no_inline_links_images_to_alt.html0000644000175000017500000000044112616413406024502 0ustar ubuntuubuntu00000000000000 ALT TEXT
ALT TEXT
http://example.com html2text-2016.1.8/setup.cfg0000664000175000017500000000014412643763140016422 0ustar ubuntuubuntu00000000000000[metadata] description-file = README.md [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 html2text-2016.1.8/PKG-INFO0000644000175000017500000000211512643763140015674 0ustar ubuntuubuntu00000000000000Metadata-Version: 1.1 Name: html2text Version: 2016.1.8 Summary: Turn HTML into equivalent Markdown-structured text. Home-page: https://github.com/Alir3z4/html2text/ Author: Alireza Savand Author-email: alireza.savand@gmail.com License: GNU GPL 3 Description: UNKNOWN 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 :: 2 Classifier: Programming Language :: Python :: 2.4 Classifier: Programming Language :: Python :: 2.5 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.0 Classifier: Programming Language :: Python :: 3.1 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 html2text-2016.1.8/MANIFEST.in0000664000175000017500000000016412471110237016331 0ustar ubuntuubuntu00000000000000include COPYING include README.md include ChangeLog.rst include AUTHORS.rst recursive-include test *.html *.md *.py html2text-2016.1.8/html2text/0000755000175000017500000000000012643763140016533 5ustar ubuntuubuntu00000000000000html2text-2016.1.8/html2text/__init__.py0000644000175000017500000007122712643763075020664 0ustar ubuntuubuntu00000000000000#!/usr/bin/env python # coding: utf-8 """html2text: Turn HTML into equivalent Markdown-structured text.""" from __future__ import division import re import cgi try: from textwrap import wrap except ImportError: # pragma: no cover pass from html2text.compat import urlparse, HTMLParser from html2text import config from html2text.utils import ( name2cp, unifiable_n, google_text_emphasis, google_fixed_width_font, element_style, hn, google_has_height, escape_md, google_list_style, list_numbering_start, dumb_css_parser, escape_md_section, skipwrap ) __version__ = (2016, 1, 8) # TODO: # Support decoded entities with UNIFIABLE. class HTML2Text(HTMLParser.HTMLParser): def __init__(self, out=None, baseurl='', bodywidth=config.BODY_WIDTH): """ Input parameters: out: possible custom replacement for self.outtextf (which appends lines of text). baseurl: base URL of the document we process """ HTMLParser.HTMLParser.__init__(self) # 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_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.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_links = config.WRAP_LINKS # covered in cli self.tag_callback = None if out is None: # pragma: no cover self.out = self.outtextf else: # pragma: no cover self.out = out # empty list to store output characters before they are "joined" self.outtextlist = [] self.quiet = 0 self.p_p = 0 # number of newline character to print before next output self.outcount = 0 self.start = 1 self.space = 0 self.a = [] self.astack = [] self.maybe_automatic_link = None self.empty_link = False self.absolute_url_matcher = re.compile(r'^[a-zA-Z+]+://') self.acount = 0 self.list = [] self.blockquote = 0 self.pre = 0 self.startpre = 0 self.code = False self.br_toggle = '' self.lastWasNL = 0 self.lastWasList = False self.style = 0 self.style_def = {} self.tag_stack = [] self.emphasis = 0 self.drop_white_space = 0 self.inheader = False self.abbr_title = None # current abbreviation definition self.abbr_data = None # last inner HTML (for abbr being defined) self.abbr_list = {} # stack of abbreviations to write later self.baseurl = baseurl try: del unifiable_n[name2cp('nbsp')] except KeyError: pass config.UNIFIABLE['nbsp'] = ' _place_holder;' def feed(self, data): data = data.replace("", "") HTMLParser.HTMLParser.feed(self, data) def handle(self, data): self.feed(data) self.feed("") return self.optwrap(self.close()) def outtextf(self, s): self.outtextlist.append(s) if s: self.lastWasNL = s[-1] == '\n' def close(self): HTMLParser.HTMLParser.close(self) try: nochr = unicode('') except NameError: nochr = str('') self.pbr() self.o('', 0, 'end') outtext = nochr.join(self.outtextlist) if self.unicode_snob: try: nbsp = unichr(name2cp('nbsp')) except NameError: nbsp = chr(name2cp('nbsp')) else: try: nbsp = unichr(32) except NameError: nbsp = chr(32) try: outtext = outtext.replace(unicode(' _place_holder;'), nbsp) except NameError: 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): charref = self.charref(c) if not self.code and not self.pre: charref = cgi.escape(charref) self.handle_data(charref, True) def handle_entityref(self, c): entityref = self.entityref(c) if (not self.code and not self.pre and entityref != ' _place_holder;'): entityref = cgi.escape(entityref) self.handle_data(entityref, True) def handle_starttag(self, tag, attrs): self.handle_tag(tag, attrs, 1) def handle_endtag(self, tag): self.handle_tag(tag, None, 0) def previousIndex(self, attrs): """ :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: # pragma: no cover return None i = -1 for a in self.a: i += 1 match = 0 if ('href' in a) and a['href'] == attrs['href']: if ('title' in a) or ('title' in attrs): if (('title' in a) and ('title' in attrs) and a['title'] == attrs['title']): match = True else: match = True if match: return i def handle_emphasis(self, start, tag_style, parent_style): """ 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 bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis italic = 'italic' in tag_emphasis and not 'italic' 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 = 0 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, attrs, start): # attrs is None for endtags if attrs is None: attrs = {} else: attrs = dict(attrs) 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 not self.maybe_automatic_link is 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 = {} 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() else: self.p() if tag == "br" and start: 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('> ', 0, 1) self.start = 1 self.blockquote += 1 else: self.blockquote -= 1 self.p() if tag in ['em', 'i', 'u'] and not self.ignore_emphasis: self.o(self.emphasis_mark) if tag in ['strong', 'b'] and not self.ignore_emphasis: self.o(self.strong_mark) if tag in ['del', 'strike', 's']: if start: self.o('~~') else: self.o('~~') 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 ["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: self.abbr_list[self.abbr_data] = self.abbr_title self.abbr_title = None self.abbr_data = '' 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: if self.empty_link: self.o("[") self.empty_link = False self.maybe_automatic_link = None if self.inline_links: try: title = escape_md(a['title']) except KeyError: self.o("](" + escape_md(a['href']) + ")") else: self.o("](" + escape_md(a['href']) + ' "' + title + '" )') else: i = self.previousIndex(a) if i is not None: a = self.a[i] else: self.acount += 1 a['count'] = self.acount a['outcount'] = self.outcount self.a.append(a) self.o("][" + str(a['count']) + "]") if tag == "img" and start and not self.ignore_images: if 'src' in attrs: if not self.images_to_alt: attrs['href'] = attrs['src'] alt = attrs.get('alt') or '' # If we have images_with_size, write raw html including width, # height, and alt attributes if 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 not self.maybe_automatic_link is 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(href) + ")") else: i = self.previousIndex(attrs) if i is not None: attrs = self.a[i] else: self.acount += 1 attrs['count'] = self.acount attrs['outcount'] = self.outcount self.a.append(attrs) self.o("[" + str(attrs['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({ 'name': list_style, 'num': numbering_start }) else: if self.list: self.list.pop() self.lastWasList = True else: self.lastWasList = False if tag == 'li': self.pbr() if start: if self.list: li = self.list[-1] else: li = {'name': 'ul', 'num': 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 = 1 if tag in ["table", "tr", "td", "th"]: if self.bypass_tables: if start: self.soft_br() if tag in ["td", "th"]: if start: self.o('<{0}>\n\n'.format(tag)) else: self.o('\n'.format(tag)) else: if start: self.o('<{0}>'.format(tag)) else: self.o(''.format(tag)) else: if tag == "table" and start: self.table_start = True 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 = 1 self.pre = 1 else: self.pre = 0 if self.mark_code: self.out("\n[/code]") self.p() # TODO: Add docstring for these one letter functions def pbr(self): "Pretty print has a line break" if self.p_p == 0: self.p_p = 1 def p(self): "Set pretty print to 1 or 2 lines" self.p_p = 1 if self.single_line_break else 2 def soft_br(self): "Soft breaks" self.pbr() self.br_toggle = ' ' def o(self, data, puredata=0, force=0): """ 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 = 1 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"): #
    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
                    for i in range(len(self.list)):
                        bq += "    "
                    data = data.replace("\n", "\n" + bq)
    
                if self.startpre:
                    self.startpre = 0
                    if self.list:
                        # use existing initial indentation
                        data = data.lstrip("\n")
    
                if self.start:
                    self.space = 0
                    self.p_p = 0
                    self.start = 0
    
                if force == 'end':
                    # It's the end.
                    self.p_p = 0
                    self.out("\n")
                    self.space = 0
    
                if self.p_p:
                    self.out((self.br_toggle + '\n' + bq) * self.p_p)
                    self.space = 0
                    self.br_toggle = ''
    
                if self.space:
                    if not self.lastWasNL:
                        self.out(' ')
                    self.space = 0
    
                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['href']))
                            if 'title' in link:
                                self.out(" (" + link['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, entity_char=False):
            if r'\/script>' in data:
                self.quiet -= 1
    
            if self.style:
                self.style_def.update(dumb_css_parser(data))
    
            if not self.maybe_automatic_link is 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.o(data, 1)
    
        def unknown_decl(self, data):  # pragma: no cover
            # TODO: what is this doing here?
            pass
    
        def charref(self, name):
            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.keys():
                return unifiable_n[c]
            else:
                try:
                    try:
                        return unichr(c)
                    except NameError:  # Python3
                        return chr(c)
                except ValueError:  # invalid unicode
                    return ''
    
        def entityref(self, c):
            if not self.unicode_snob and c in config.UNIFIABLE.keys():
                return config.UNIFIABLE[c]
            else:
                try:
                    name2cp(c)
                except KeyError:
                    return "&" + c + ';'
                else:
                    if c == 'nbsp':
                        return config.UNIFIABLE[c]
                    else:
                        try:
                            return unichr(name2cp(c))
                        except NameError:  # Python3
                            return chr(name2cp(c))
    
        def replaceEntities(self, s):
            s = s.group(1)
            if s[0] == "#":
                return self.charref(s[1:])
            else:
                return self.entityref(s)
    
        def unescape(self, s):
            return config.RE_UNESCAPE.sub(self.replaceEntities, s)
    
        def google_nest_count(self, style):
            """
            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):
            """
            Wrap all paragraphs in the provided text.
    
            :type text: str
    
            :rtype: str
            """
            if not self.body_width:
                return text
    
            assert wrap, "Requires Python 2.3."
            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):
                        result += "\n".join(wrap(para, self.body_width))
                        if para.endswith('  '):
                            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, baseurl='', bodywidth=None):
        if bodywidth is None:
            bodywidth = config.BODY_WIDTH
        h = HTML2Text(baseurl=baseurl, bodywidth=bodywidth)
    
        return h.handle(html)
    
    
    def unescape(s, unicode_snob=False):
        h = HTML2Text()
        h.unicode_snob = unicode_snob
    
        return h.unescape(s)
    
    
    if __name__ == "__main__":
        from html2text.cli import main
    
        main()
    html2text-2016.1.8/html2text/compat.py0000644000175000017500000000043612616413406020370 0ustar  ubuntuubuntu00000000000000import sys
    
    
    if sys.version_info[0] == 2:
        import htmlentitydefs
        import urlparse
        import HTMLParser
        import urllib
    else:
        import urllib.parse as urlparse
        import html.entities as htmlentitydefs
        import html.parser as HTMLParser
        import urllib.request as urllib
    html2text-2016.1.8/html2text/config.py0000644000175000017500000000632712616413406020357 0ustar  ubuntuubuntu00000000000000import re
    
    # Use Unicode characters instead of their ascii psuedo-replacements
    UNICODE_SNOB = 0
    
    # Escape all special characters.  Output is less readable, but avoids
    # corner case formatting issues.
    ESCAPE_SNOB = 0
    
    # Put the links after each paragraph instead of at the end.
    LINKS_EACH_PARAGRAPH = 0
    
    # Wrap long lines at position. 0 for no wrapping. (Requires Python 2.3.)
    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
    
    # Number of pixels Google indents nested lists
    GOOGLE_LIST_INDENT = 36
    
    IGNORE_ANCHORS = False
    IGNORE_IMAGES = False
    IMAGES_TO_ALT = False
    IMAGES_WITH_SIZE = False
    IGNORE_EMPHASIS = False
    MARK_CODE = False
    DECODE_ERRORS = 'strict'
    
    # 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_UNESCAPE = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
    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"([`\*_{}\[\]\(\)#!])")
    RE_LINK = re.compile(r"(\[.*?\] ?\(.*?\))|(\[.*?\]:.*?)")  # to find links in the text
    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': ''
    }
    
    BYPASS_TABLES = False
    
    # Use a single line break after a block element rather an two line breaks.
    # NOTE: Requires body width setting to be 0.
    SINGLE_LINE_BREAK = False
    html2text-2016.1.8/html2text/utils.py0000644000175000017500000001366112643762105020254 0ustar  ubuntuubuntu00000000000000import sys
    
    from html2text import config
    from html2text.compat import htmlentitydefs
    
    
    def name2cp(k):
        """Return sname to codepoint"""
        if k == 'apos':
            return ord("'")
        return htmlentitydefs.name2codepoint[k]
    
    
    unifiable_n = {}
    
    for k in config.UNIFIABLE.keys():
        unifiable_n[name2cp(k)] = config.UNIFIABLE[k]
    
    
    def hn(tag):
        if tag[0] == 'h' and len(tag) == 2:
            try:
                n = int(tag[1])
                if n in range(1, 10):  # pragma: no branch
                    return n
            except ValueError:
                return 0
    
    
    def dumb_property_dict(style):
        """
        :returns: A hash of css attributes
        """
        out = dict([(x.strip(), y.strip()) for x, y in
                    [z.split(':', 1) for z in
                     style.split(';') if ':' in z
                     ]
                    ]
                   )
    
        return out
    
    
    def dumb_css_parser(data):
        """
        :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
        elements = [x.split('{') for x in data.split('}') if '{' in x.strip()]
        try:
            elements = dict([(a.strip(), dumb_property_dict(b))
                             for a, b in elements])
        except ValueError:  # pragma: no cover
            elements = {}  # not that important
    
        return elements
    
    
    def element_style(attrs, style_def, parent_style):
        """
        :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:
            for css_class in attrs['class'].split():
                css_style = style_def.get('.' + css_class, {})
                style.update(css_style)
        if 'style' in attrs:
            immediate_style = dumb_property_dict(attrs['style'])
            style.update(immediate_style)
    
        return style
    
    
    def google_list_style(style):
        """
        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):
        """
        Check if the style of the element has the 'height' attribute
        explicitly defined
    
        :type style: dict
    
        :rtype: bool
        """
        if 'height' in style:
            return True
    
        return False
    
    
    def google_text_emphasis(style):
        """
        :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):
        """
        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']
        if 'Courier New' == font_family or 'Consolas' == font_family:
            return True
    
        return False
    
    
    def list_numbering_start(attrs):
        """
        Extract numbering from list element attributes
    
        :type attrs: dict
    
        :rtype: int or None
        """
        if 'start' in attrs:
            try:
                return int(attrs['start']) - 1
            except ValueError:
                pass
    
        return 0
    
    
    def skipwrap(para, wrap_links):
        # If it appears to contain a link
        # don't wrap
        if (len(config.RE_LINK.findall(para)) > 0) and not wrap_links:
            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] == '-' or stripped[0:1] == '*': return True # 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. if config.RE_ORDERED_LIST_MATCHER.match(stripped) or \ config.RE_UNORDERED_LIST_MATCHER.match(stripped): return True return False def wrapwrite(text): text = text.encode('utf-8') try: # Python3 sys.stdout.buffer.write(text) except AttributeError: sys.stdout.write(text) def wrap_read(): # pragma: no cover """ :rtype: str """ try: return sys.stdin.read() except AttributeError: return sys.stdin.buffer.read() def escape_md(text): """ Escapes markdown-sensitive characters within other markdown constructs. """ return config.RE_MD_CHARS_MATCHER.sub(r"\\\1", text) def escape_md_section(text, snob=False): """ 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 html2text-2016.1.8/html2text/cli.py0000644000175000017500000002070512616413406017655 0ustar ubuntuubuntu00000000000000import optparse from html2text.compat import urllib from html2text import HTML2Text, config, __version__ from html2text.utils import wrapwrite, wrap_read def main(): baseurl = '' class bcolors: # pragma: no cover 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 = optparse.OptionParser( '%prog [(filename|url) [encoding]]', version='%prog ' + ".".join(map(str, __version__)) ) p.add_option( "--no-wrap-links", dest="wrap_links", action="store_false", default=config.WRAP_LINKS, help="wrap links during conversion" ) p.add_option( "--ignore-emphasis", dest="ignore_emphasis", action="store_true", default=config.IGNORE_EMPHASIS, help="don't include any formatting for emphasis" ) p.add_option( "--reference-links", dest="inline_links", action="store_false", default=config.INLINE_LINKS, help="use reference style links instead of inline links" ) p.add_option( "--ignore-links", dest="ignore_links", action="store_true", default=config.IGNORE_ANCHORS, help="don't include any formatting for links") p.add_option( "--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_option( "--ignore-images", dest="ignore_images", action="store_true", default=config.IGNORE_IMAGES, help="don't include any formatting for images" ) p.add_option( "--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_option( "--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_option( "-g", "--google-doc", action="store_true", dest="google_doc", default=False, help="convert an html-exported Google Document" ) p.add_option( "-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_option( "-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_option( "-b", "--body-width", dest="body_width", action="store", type="int", default=config.BODY_WIDTH, help="number of characters per output line, 0 for no wrap" ) p.add_option( "-i", "--google-list-indent", dest="list_indent", action="store", type="int", default=config.GOOGLE_LIST_INDENT, help="number of pixels Google indents nested lists" ) p.add_option( "-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_option( "--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_option( "--bypass-tables", action="store_true", dest="bypass_tables", default=config.BYPASS_TABLES, help="Format tables in HTML rather than Markdown syntax." ) p.add_option( "--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_option( "--unicode-snob", action="store_true", dest="unicode_snob", default=config.UNICODE_SNOB, help="Use unicode throughout document" ) p.add_option( "--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_option( "--no-skip-internal-links", action="store_false", dest="skip_internal_links", default=config.SKIP_INTERNAL_LINKS, help="Do not skip internal links" ) p.add_option( "--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_option( "--mark-code", action="store_true", dest="mark_code", default=config.MARK_CODE, help="Mark program code blocks with [code]...[/code]" ) p.add_option( "--decode-errors", dest="decode_errors", action="store", type="string", default=config.DECODE_ERRORS, help="What to do in case of decode errors.'ignore', 'strict' and 'replace' are acceptable values" ) (options, args) = p.parse_args() # process input encoding = "utf-8" if len(args) > 0 and args[0] != '-': # pragma: no cover file_ = args[0] if len(args) == 2: encoding = args[1] if len(args) > 2: p.error('Too many arguments') if file_.startswith('http://') or file_.startswith('https://'): baseurl = file_ j = urllib.urlopen(baseurl) data = j.read() if encoding is None: try: from feedparser import _getCharacterEncoding as enc except ImportError: enc = lambda x, y: ('utf-8', 1) encoding = enc(j.headers, data)[0] if encoding == 'us-ascii': encoding = 'utf-8' else: data = open(file_, 'rb').read() if encoding is None: try: from chardet import detect except ImportError: detect = lambda x: {'encoding': 'utf-8'} encoding = detect(data)['encoding'] else: data = wrap_read() if hasattr(data, 'decode'): try: try: data = data.decode(encoding, errors=options.decode_errors) except TypeError: # python 2.6.x does not have the errors option data = data.decode(encoding) 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 options.ul_style_dash: h.ul_item_mark = '-' if options.em_style_asterisk: h.emphasis_mark = '*' h.strong_mark = '__' h.body_width = options.body_width h.google_list_indent = options.list_indent h.ignore_emphasis = options.ignore_emphasis h.ignore_links = options.ignore_links h.protect_links = options.protect_links h.ignore_images = options.ignore_images h.images_to_alt = options.images_to_alt h.images_with_size = options.images_with_size h.google_doc = options.google_doc h.hide_strikethrough = options.hide_strikethrough h.escape_snob = options.escape_snob h.bypass_tables = options.bypass_tables h.single_line_break = options.single_line_break h.inline_links = options.inline_links h.unicode_snob = options.unicode_snob h.use_automatic_links = options.use_automatic_links h.skip_internal_links = options.skip_internal_links h.links_each_paragraph = options.links_each_paragraph h.mark_code = options.mark_code h.wrap_links = options.wrap_links wrapwrite(h.handle(data)) html2text-2016.1.8/setup.py0000644000175000017500000000424512616416405016316 0ustar ubuntuubuntu00000000000000# coding: utf-8 import sys from setuptools import setup, Command, find_packages requires_list = [] try: import unittest2 as unittest except ImportError: import unittest else: if sys.version_info <= (2, 6): requires_list.append("unittest2") class RunTests(Command): """New setup.py command to run all tests for the package. """ description = "run all tests for the package" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): tests = unittest.TestLoader().discover('.') runner = unittest.TextTestRunner() results = runner.run(tests) sys.exit(not results.wasSuccessful()) setup( name="html2text", version=".".join(map(str, __import__('html2text').__version__)), description="Turn HTML into equivalent Markdown-structured text.", author="Aaron Swartz", author_email="me@aaronsw.com", maintainer='Alireza Savand', maintainer_email='alireza.savand@gmail.com', url='https://github.com/Alir3z4/html2text/', cmdclass={'test': RunTests}, platforms='OS Independent', 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 :: 2', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], entry_points=""" [console_scripts] html2text=html2text.cli:main """, license='GNU GPL 3', requires=requires_list, packages=find_packages(exclude=['test']), include_package_data=True, zip_safe=False, ) html2text-2016.1.8/COPYING0000664000175000017500000010451312471110237015631 0ustar ubuntuubuntu00000000000000 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-2016.1.8/AUTHORS.rst0000644000175000017500000000123212616413406016452 0ustar ubuntuubuntu00000000000000``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 Maintainer: * Alireza Savand