Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
194c646a20 | ||
|
|
9914474828 | ||
|
|
6263f0e5f0 | ||
|
|
17d8586843 | ||
|
|
59eb069700 | ||
|
|
e79971a7eb | ||
|
|
2c533339cf | ||
|
|
5adda130b8 | ||
|
|
5f1b98e25d | ||
|
|
16acd2b763 | ||
|
|
2b8cf444f1 | ||
|
|
207d0f4ec6 | ||
|
|
ebb9ea713d | ||
|
|
d375116807 | ||
|
|
87b9f6c88e | ||
|
|
bda367dad9 | ||
|
|
61e8940486 | ||
|
|
35479d2d3b | ||
|
|
b589863715 | ||
|
|
423b7e948c | ||
|
|
0ea95de4d0 | ||
|
|
ed3eee78d2 |
10
.github/workflows/python-app.yml
vendored
10
.github/workflows/python-app.yml
vendored
@@ -23,11 +23,7 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install flake8==3.8.4 pytest
|
||||
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
||||
- name: Lint with flake8
|
||||
pip install tox
|
||||
- name: Lint and test
|
||||
run: |
|
||||
python setup.py lint
|
||||
- name: Test with pytest
|
||||
run: |
|
||||
python setup.py test
|
||||
tox
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -9,3 +9,4 @@
|
||||
/venv
|
||||
build/
|
||||
.vscode/settings.json
|
||||
.tox/
|
||||
|
||||
50
README.rst
50
README.rst
@@ -92,7 +92,7 @@ sub_symbol, sup_symbol
|
||||
newline_style
|
||||
Defines the style of marking linebreaks (``<br>``) in markdown. The default
|
||||
value ``SPACES`` of this option will adopt the usual two spaces and a newline,
|
||||
while ``BACKSLASH`` will convert a linebreak to ``\\n`` (a backslash an a
|
||||
while ``BACKSLASH`` will convert a linebreak to ``\\n`` (a backslash and a
|
||||
newline). While the latter convention is non-standard, it is commonly
|
||||
preferred and supported by a lot of interpreters.
|
||||
|
||||
@@ -102,10 +102,39 @@ code_language
|
||||
should be annotated with `````python`` or similar.
|
||||
Defaults to ``''`` (empty string) and can be any string.
|
||||
|
||||
code_language_callback
|
||||
When the HTML code contains ``pre`` tags that in some way provide the code
|
||||
language, for example as class, this callback can be used to extract the
|
||||
language from the tag and prefix it to the converted ``pre`` tag.
|
||||
The callback gets one single argument, an BeautifylSoup object, and returns
|
||||
a string containing the code language, or ``None``.
|
||||
An example to use the class name as code language could be::
|
||||
|
||||
def callback(el):
|
||||
return el['class'][0] if el.has_attr('class') else None
|
||||
|
||||
Defaults to ``None``.
|
||||
|
||||
escape_asterisks
|
||||
If set to ``False``, do not escape ``*`` to ``\*`` in text.
|
||||
Defaults to ``True``.
|
||||
|
||||
escape_underscores
|
||||
If set to ``False``, do not escape ``_`` to ``\_`` in text.
|
||||
Defaults to ``True``.
|
||||
|
||||
keep_inline_images_in
|
||||
Images are converted to their alt-text when the images are located inside
|
||||
headlines or table cells. If some inline images should be converted to
|
||||
markdown images instead, this option can be set to a list of parent tags
|
||||
that should be allowed to contain inline images, for example ``['td']``.
|
||||
Defaults to an empty list.
|
||||
|
||||
wrap, wrap_width
|
||||
If ``wrap`` is set to ``True``, all text paragraphs are wrapped at
|
||||
``wrap_width`` characters. Defaults to ``False`` and ``80``.
|
||||
Use with ``newline_style=BACKSLASH`` to keep line breaks in paragraphs.
|
||||
|
||||
Options may be specified as kwargs to the ``markdownify`` function, or as a
|
||||
nested ``Options`` class in ``MarkdownConverter`` subclasses.
|
||||
|
||||
@@ -119,7 +148,7 @@ Converting BeautifulSoup objects
|
||||
|
||||
# Create shorthand method for conversion
|
||||
def md(soup, **options):
|
||||
return ImageBlockConverter(**options).convert_soup(soup)
|
||||
return MarkdownConverter(**options).convert_soup(soup)
|
||||
|
||||
|
||||
Creating Custom Converters
|
||||
@@ -145,13 +174,16 @@ change:
|
||||
return ImageBlockConverter(**options).convert(html)
|
||||
|
||||
|
||||
Command Line Interface
|
||||
=====================
|
||||
|
||||
Use ``markdownify example.html > example.md`` or pipe input from stdin
|
||||
(``cat example.html | markdownify > example.md``).
|
||||
Call ``markdownify -h`` to see all available options.
|
||||
They are the same as listed above and take the same arguments.
|
||||
|
||||
|
||||
Development
|
||||
===========
|
||||
|
||||
To run tests:
|
||||
|
||||
``python setup.py test``
|
||||
|
||||
To lint:
|
||||
|
||||
``python setup.py lint``
|
||||
To run tests and the linter run ``pip install tox`` once, then ``tox``.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from bs4 import BeautifulSoup, NavigableString, Comment, Doctype
|
||||
from textwrap import fill
|
||||
import re
|
||||
import six
|
||||
|
||||
@@ -25,14 +26,6 @@ ASTERISK = '*'
|
||||
UNDERSCORE = '_'
|
||||
|
||||
|
||||
def escape(text, escape_underscores):
|
||||
if not text:
|
||||
return ''
|
||||
if escape_underscores:
|
||||
return text.replace('_', r'\_')
|
||||
return text
|
||||
|
||||
|
||||
def chomp(text):
|
||||
"""
|
||||
If the text in an inline tag like b, a, or em contains a leading or trailing
|
||||
@@ -71,15 +64,20 @@ class MarkdownConverter(object):
|
||||
autolinks = True
|
||||
bullets = '*+-' # An iterable of bullet types.
|
||||
code_language = ''
|
||||
code_language_callback = None
|
||||
convert = None
|
||||
default_title = False
|
||||
escape_asterisks = True
|
||||
escape_underscores = True
|
||||
heading_style = UNDERLINED
|
||||
keep_inline_images_in = []
|
||||
newline_style = SPACES
|
||||
strip = None
|
||||
strong_em_symbol = ASTERISK
|
||||
sub_symbol = ''
|
||||
sup_symbol = ''
|
||||
wrap = False
|
||||
wrap_width = 80
|
||||
|
||||
class Options(DefaultOptions):
|
||||
pass
|
||||
@@ -160,8 +158,8 @@ class MarkdownConverter(object):
|
||||
and el.parent.parent.name == 'pre')):
|
||||
text = whitespace_re.sub(' ', text)
|
||||
|
||||
if el.parent.name != 'code':
|
||||
text = escape(text, self.options['escape_underscores'])
|
||||
if el.parent.name != 'code' and el.parent.name != 'pre':
|
||||
text = self.escape(text)
|
||||
|
||||
# remove trailing whitespaces if any of the following condition is true:
|
||||
# - current text node is the last node in li
|
||||
@@ -199,6 +197,15 @@ class MarkdownConverter(object):
|
||||
else:
|
||||
return True
|
||||
|
||||
def escape(self, text):
|
||||
if not text:
|
||||
return ''
|
||||
if self.options['escape_asterisks']:
|
||||
text = text.replace('*', r'\*')
|
||||
if self.options['escape_underscores']:
|
||||
text = text.replace('_', r'\_')
|
||||
return text
|
||||
|
||||
def indent(self, text, level):
|
||||
return line_beginning_re.sub('\t' * level, text) if text else ''
|
||||
|
||||
@@ -278,7 +285,8 @@ class MarkdownConverter(object):
|
||||
src = el.attrs.get('src', None) or ''
|
||||
title = el.attrs.get('title', None) or ''
|
||||
title_part = ' "%s"' % title.replace('"', r'\"') if title else ''
|
||||
if convert_as_inline:
|
||||
if (convert_as_inline
|
||||
and el.parent.name not in self.options['keep_inline_images_in']):
|
||||
return alt
|
||||
|
||||
return '' % (alt, src, title_part)
|
||||
@@ -326,12 +334,22 @@ class MarkdownConverter(object):
|
||||
def convert_p(self, el, text, convert_as_inline):
|
||||
if convert_as_inline:
|
||||
return text
|
||||
if self.options['wrap']:
|
||||
text = fill(text,
|
||||
width=self.options['wrap_width'],
|
||||
break_long_words=False,
|
||||
break_on_hyphens=False)
|
||||
return '%s\n\n' % text if text else ''
|
||||
|
||||
def convert_pre(self, el, text, convert_as_inline):
|
||||
if not text:
|
||||
return ''
|
||||
return '\n```%s\n%s\n```\n' % (self.options['code_language'], text)
|
||||
code_language = self.options['code_language']
|
||||
|
||||
if self.options['code_language_callback']:
|
||||
code_language = self.options['code_language_callback'](el) or code_language
|
||||
|
||||
return '\n```%s\n%s\n```\n' % (code_language, text)
|
||||
|
||||
convert_s = convert_del
|
||||
|
||||
@@ -360,8 +378,13 @@ class MarkdownConverter(object):
|
||||
if is_headrow and not el.previous_sibling:
|
||||
# first row and is headline: print headline underline
|
||||
underline += '| ' + ' | '.join(['---'] * len(cells)) + ' |' + '\n'
|
||||
elif not el.previous_sibling and not el.parent.name != 'table':
|
||||
# first row, not headline, and the parent is sth. like tbody:
|
||||
elif (not el.previous_sibling
|
||||
and (el.parent.name == 'table'
|
||||
or (el.parent.name == 'tbody'
|
||||
and not el.parent.previous_sibling))):
|
||||
# first row, not headline, and:
|
||||
# - the parent is table or
|
||||
# - the parent is tbody at the beginning of a table.
|
||||
# print empty headline above this row
|
||||
overline += '| ' + ' | '.join([''] * len(cells)) + ' |' + '\n'
|
||||
overline += '| ' + ' | '.join(['---'] * len(cells)) + ' |' + '\n'
|
||||
|
||||
65
markdownify/main.py
Normal file
65
markdownify/main.py
Normal file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from markdownify import markdownify
|
||||
|
||||
|
||||
def main(argv=sys.argv[1:]):
|
||||
parser = argparse.ArgumentParser(
|
||||
prog='markdownify',
|
||||
description='Converts html to markdown.',
|
||||
)
|
||||
|
||||
parser.add_argument('html', nargs='?', type=argparse.FileType('r'),
|
||||
default=sys.stdin,
|
||||
help="The html file to convert. Defaults to STDIN if not "
|
||||
"provided.")
|
||||
parser.add_argument('-s', '--strip', nargs='*',
|
||||
help="A list of tags to strip. This option can't be used with "
|
||||
"the --convert option.")
|
||||
parser.add_argument('-c', '--convert', nargs='*',
|
||||
help="A list of tags to convert. This option can't be used with "
|
||||
"the --strip option.")
|
||||
parser.add_argument('-a', '--autolinks', action='store_true',
|
||||
help="A boolean indicating whether the 'automatic link' style "
|
||||
"should be used when a 'a' tag's contents match its href.")
|
||||
parser.add_argument('--default-title', action='store_false',
|
||||
help="A boolean to enable setting the title of a link to its "
|
||||
"href, if no title is given.")
|
||||
parser.add_argument('--heading-style',
|
||||
choices=('ATX', 'ATX_CLOSED', 'SETEXT', 'UNDERLINED'),
|
||||
help="Defines how headings should be converted.")
|
||||
parser.add_argument('-b', '--bullets', default='*+-',
|
||||
help="A string of bullet styles to use; the bullet will "
|
||||
"alternate based on nesting level.")
|
||||
parser.add_argument('--sub-symbol', default='',
|
||||
help="Define the chars that surround '<sub>'.")
|
||||
parser.add_argument('--sup-symbol', default='',
|
||||
help="Define the chars that surround '<sup>'.")
|
||||
parser.add_argument('--code-language', default='',
|
||||
help="Defines the language that should be assumed for all "
|
||||
"'<pre>' sections.")
|
||||
parser.add_argument('--no-escape-asterisks', dest='escape_asterisks',
|
||||
action='store_false',
|
||||
help="Do not escape '*' to '\\*' in text.")
|
||||
parser.add_argument('--no-escape-underscores', dest='escape_underscores',
|
||||
action='store_false',
|
||||
help="Do not escape '_' to '\\_' in text.")
|
||||
parser.add_argument('-i', '--keep-inline-images-in', nargs='*',
|
||||
help="Images are converted to their alt-text when the images are "
|
||||
"located inside headlines or table cells. If some inline images "
|
||||
"should be converted to markdown images instead, this option can "
|
||||
"be set to a list of parent tags that should be allowed to "
|
||||
"contain inline images.")
|
||||
parser.add_argument('-w', '--wrap', action='store_true',
|
||||
help="Wrap all text paragraphs at --wrap-width characters.")
|
||||
parser.add_argument('--wrap-width', type=int, default=80)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
print(markdownify(**vars(args)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
65
setup.py
65
setup.py
@@ -2,7 +2,6 @@
|
||||
import codecs
|
||||
import os
|
||||
from setuptools import setup, find_packages
|
||||
from setuptools.command.test import test as TestCommand, Command
|
||||
|
||||
|
||||
read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
||||
@@ -10,52 +9,10 @@ read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
||||
pkgmeta = {
|
||||
'__title__': 'markdownify',
|
||||
'__author__': 'Matthew Tretter',
|
||||
'__version__': '0.10.3',
|
||||
'__version__': '0.11.3',
|
||||
}
|
||||
|
||||
|
||||
class PyTest(TestCommand):
|
||||
def finalize_options(self):
|
||||
TestCommand.finalize_options(self)
|
||||
self.test_args = ['tests', '-s']
|
||||
self.test_suite = True
|
||||
|
||||
def run_tests(self):
|
||||
import pytest
|
||||
errno = pytest.main(self.test_args)
|
||||
raise SystemExit(errno)
|
||||
|
||||
|
||||
class LintCommand(Command):
|
||||
"""
|
||||
A copy of flake8's Flake8Command
|
||||
|
||||
"""
|
||||
description = "Run flake8 on modules registered in setuptools"
|
||||
user_options = []
|
||||
|
||||
def initialize_options(self):
|
||||
pass
|
||||
|
||||
def finalize_options(self):
|
||||
pass
|
||||
|
||||
def distribution_files(self):
|
||||
if self.distribution.packages:
|
||||
for package in self.distribution.packages:
|
||||
yield package.replace(".", os.path.sep)
|
||||
|
||||
if self.distribution.py_modules:
|
||||
for filename in self.distribution.py_modules:
|
||||
yield "%s.py" % filename
|
||||
|
||||
def run(self):
|
||||
from flake8.api.legacy import get_style_guide
|
||||
flake8_style = get_style_guide(config_file='setup.cfg')
|
||||
paths = self.distribution_files()
|
||||
report = flake8_style.check_files(paths)
|
||||
raise SystemExit(report.total_errors > 0)
|
||||
|
||||
read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
||||
|
||||
setup(
|
||||
name='markdownify',
|
||||
@@ -69,14 +26,9 @@ setup(
|
||||
packages=find_packages(),
|
||||
zip_safe=False,
|
||||
include_package_data=True,
|
||||
setup_requires=[
|
||||
'flake8>=3.8,<5',
|
||||
],
|
||||
tests_require=[
|
||||
'pytest>=6.2,<7',
|
||||
],
|
||||
install_requires=[
|
||||
'beautifulsoup4>=4.9,<5', 'six>=1.15,<2'
|
||||
'beautifulsoup4>=4.9,<5',
|
||||
'six>=1.15,<2',
|
||||
],
|
||||
classifiers=[
|
||||
'Environment :: Web Environment',
|
||||
@@ -92,8 +44,9 @@ setup(
|
||||
'Programming Language :: Python :: 3.8',
|
||||
'Topic :: Utilities'
|
||||
],
|
||||
cmdclass={
|
||||
'test': PyTest,
|
||||
'lint': LintCommand,
|
||||
},
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'markdownify = markdownify.main:main'
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
@@ -133,12 +133,13 @@ def test_hn_nested_simple_tag():
|
||||
|
||||
def test_hn_nested_img():
|
||||
image_attributes_to_markdown = [
|
||||
("", ""),
|
||||
("alt='Alt Text'", "Alt Text"),
|
||||
("alt='Alt Text' title='Optional title'", "Alt Text"),
|
||||
("", "", ""),
|
||||
("alt='Alt Text'", "Alt Text", ""),
|
||||
("alt='Alt Text' title='Optional title'", "Alt Text", " \"Optional title\""),
|
||||
]
|
||||
for image_attributes, markdown in image_attributes_to_markdown:
|
||||
assert md('<h3>A <img src="/path/to/img.jpg " ' + image_attributes + '/> B</h3>') == '### A ' + markdown + ' B\n\n'
|
||||
for image_attributes, markdown, title in image_attributes_to_markdown:
|
||||
assert md('<h3>A <img src="/path/to/img.jpg" ' + image_attributes + '/> B</h3>') == '### A ' + markdown + ' B\n\n'
|
||||
assert md('<h3>A <img src="/path/to/img.jpg" ' + image_attributes + '/> B</h3>', keep_inline_images_in=['h3']) == '### A  B\n\n'
|
||||
|
||||
|
||||
def test_hn_atx_headings():
|
||||
@@ -176,11 +177,17 @@ def test_kbd():
|
||||
|
||||
def test_p():
|
||||
assert md('<p>hello</p>') == 'hello\n\n'
|
||||
assert md('<p>123456789 123456789</p>') == '123456789 123456789\n\n'
|
||||
assert md('<p>123456789 123456789</p>', wrap=True, wrap_width=10) == '123456789\n123456789\n\n'
|
||||
assert md('<p><a href="https://example.com">Some long link</a></p>', wrap=True, wrap_width=10) == '[Some long\nlink](https://example.com)\n\n'
|
||||
assert md('<p>12345<br />67890</p>', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '12345\\\n67890\n\n'
|
||||
assert md('<p>12345678901<br />12345</p>', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '12345678901\\\n12345\n\n'
|
||||
|
||||
|
||||
def test_pre():
|
||||
assert md('<pre>test\n foo\nbar</pre>') == '\n```\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre><code>test\n foo\nbar</code></pre>') == '\n```\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre>this_should_not_escape</pre>') == '\n```\nthis_should_not_escape\n```\n'
|
||||
|
||||
|
||||
def test_s():
|
||||
@@ -215,3 +222,12 @@ def test_sup():
|
||||
def test_lang():
|
||||
assert md('<pre>test\n foo\nbar</pre>', code_language='python') == '\n```python\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre><code>test\n foo\nbar</code></pre>', code_language='javascript') == '\n```javascript\ntest\n foo\nbar\n```\n'
|
||||
|
||||
|
||||
def test_lang_callback():
|
||||
def callback(el):
|
||||
return el['class'][0] if el.has_attr('class') else None
|
||||
|
||||
assert md('<pre class="python">test\n foo\nbar</pre>', code_language_callback=callback) == '\n```python\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre class="javascript"><code>test\n foo\nbar</code></pre>', code_language_callback=callback) == '\n```javascript\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre class="javascript"><code class="javascript">test\n foo\nbar</code></pre>', code_language_callback=callback) == '\n```javascript\ntest\n foo\nbar\n```\n'
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
def test_asterisks():
|
||||
assert md('*hey*dude*') == r'\*hey\*dude\*'
|
||||
assert md('*hey*dude*', escape_asterisks=False) == r'*hey*dude*'
|
||||
|
||||
|
||||
def test_underscore():
|
||||
assert md('_hey_dude_') == r'\_hey\_dude\_'
|
||||
assert md('_hey_dude_', escape_underscores=False) == r'_hey_dude_'
|
||||
|
||||
@@ -139,6 +139,26 @@ table_missing_head = """<table>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
table_body = """<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Firstname</td>
|
||||
<td>Lastname</td>
|
||||
<td>Age</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Jill</td>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>"""
|
||||
|
||||
|
||||
def test_table():
|
||||
assert md(table) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
@@ -148,3 +168,4 @@ def test_table():
|
||||
assert md(table_head_body) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_missing_text) == '\n\n| | Lastname | Age |\n| --- | --- | --- |\n| Jill | | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_missing_head) == '\n\n| | | |\n| --- | --- | --- |\n| Firstname | Lastname | Age |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_body) == '\n\n| | | |\n| --- | --- | --- |\n| Firstname | Lastname | Age |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
|
||||
Reference in New Issue
Block a user