Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
917b01e548 | ||
|
|
e96351b666 | ||
|
|
129c4ef060 | ||
|
|
652714859d | ||
|
|
9cb940cbc0 | ||
|
|
70ef9b6e48 | ||
|
|
91d53ddd5a | ||
|
|
079f32f6cd | ||
|
|
89b577e91e | ||
|
|
4bf2ea44fc | ||
|
|
77797ebb79 | ||
|
|
ea5b22824b | ||
|
|
9f3c4c9fa0 | ||
|
|
967db26b3a | ||
|
|
ea81407b87 | ||
|
|
e6da15c173 | ||
|
|
7dac92e85e | ||
|
|
7685738344 | ||
|
|
92a73c8dfe | ||
|
|
3354f143d8 |
@@ -1,4 +1,4 @@
|
||||
from bs4 import BeautifulSoup, NavigableString, Comment
|
||||
from bs4 import BeautifulSoup, NavigableString, Comment, Doctype
|
||||
import re
|
||||
import six
|
||||
|
||||
@@ -44,6 +44,22 @@ def chomp(text):
|
||||
return (prefix, suffix, text)
|
||||
|
||||
|
||||
def abstract_inline_conversion(markup_fn):
|
||||
"""
|
||||
This abstracts all simple inline tags like b, em, del, ...
|
||||
Returns a function that wraps the chomped text in a pair of the string
|
||||
that is returned by markup_fn. markup_fn is necessary to allow for
|
||||
references to self.strong_em_symbol etc.
|
||||
"""
|
||||
def implementation(self, el, text, convert_as_inline):
|
||||
markup = markup_fn(self)
|
||||
prefix, suffix, text = chomp(text)
|
||||
if not text:
|
||||
return ''
|
||||
return '%s%s%s%s%s' % (prefix, markup, text, markup, suffix)
|
||||
return implementation
|
||||
|
||||
|
||||
def _todict(obj):
|
||||
return dict((k, getattr(obj, k)) for k in dir(obj) if not k.startswith('_'))
|
||||
|
||||
@@ -84,23 +100,31 @@ class MarkdownConverter(object):
|
||||
if not children_only and isHeading:
|
||||
convert_children_as_inline = True
|
||||
|
||||
# Remove whitespace-only textnodes in lists
|
||||
def is_list_node(el):
|
||||
return el and el.name in ['ol', 'ul', 'li']
|
||||
# Remove whitespace-only textnodes in purely nested nodes
|
||||
def is_nested_node(el):
|
||||
return el and el.name in ['ol', 'ul', 'li',
|
||||
'table', 'thead', 'tbody', 'tfoot',
|
||||
'tr', 'td', 'th']
|
||||
|
||||
if is_list_node(node):
|
||||
if is_nested_node(node):
|
||||
for el in node.children:
|
||||
# Only extract (remove) whitespace-only text node if any of the conditions is true:
|
||||
# Only extract (remove) whitespace-only text node if any of the
|
||||
# conditions is true:
|
||||
# - el is the first element in its parent
|
||||
# - el is the last element in its parent
|
||||
# - el is adjacent to an list node
|
||||
can_extract = not el.previous_sibling or not el.next_sibling or is_list_node(el.previous_sibling) or is_list_node(el.next_sibling)
|
||||
if isinstance(el, NavigableString) and six.text_type(el).strip() == '' and can_extract:
|
||||
# - el is adjacent to an nested node
|
||||
can_extract = (not el.previous_sibling
|
||||
or not el.next_sibling
|
||||
or is_nested_node(el.previous_sibling)
|
||||
or is_nested_node(el.next_sibling))
|
||||
if (isinstance(el, NavigableString)
|
||||
and six.text_type(el).strip() == ''
|
||||
and can_extract):
|
||||
el.extract()
|
||||
|
||||
# Convert the children first
|
||||
for el in node.children:
|
||||
if isinstance(el, Comment):
|
||||
if isinstance(el, Comment) or isinstance(el, Doctype):
|
||||
continue
|
||||
elif isinstance(el, NavigableString):
|
||||
text += self.process_text(el)
|
||||
@@ -116,12 +140,21 @@ class MarkdownConverter(object):
|
||||
|
||||
def process_text(self, el):
|
||||
text = six.text_type(el)
|
||||
|
||||
# dont remove any whitespace when handling pre or code in pre
|
||||
if (el.parent.name == 'pre'
|
||||
or (el.parent.name == 'code' and el.parent.parent.name == 'pre')):
|
||||
return escape(text or '')
|
||||
|
||||
cleaned_text = escape(whitespace_re.sub(' ', text or ''))
|
||||
|
||||
# remove trailing whitespaces if any of the following condition is true:
|
||||
# - current text node is the last node in li
|
||||
# - current text node is followed by an embedded list
|
||||
if el.parent.name == 'li' and (not el.next_sibling or el.next_sibling.name in ['ul', 'ol']):
|
||||
return escape(all_whitespace_re.sub(' ', text or '')).rstrip()
|
||||
return escape(whitespace_re.sub(' ', text or ''))
|
||||
return cleaned_text.rstrip()
|
||||
|
||||
return cleaned_text
|
||||
|
||||
def __getattr__(self, attr):
|
||||
# Handle headings
|
||||
@@ -171,8 +204,7 @@ class MarkdownConverter(object):
|
||||
title_part = ' "%s"' % title.replace('"', r'\"') if title else ''
|
||||
return '%s[%s](%s%s)%s' % (prefix, text, href, title_part, suffix) if href else text
|
||||
|
||||
def convert_b(self, el, text, convert_as_inline):
|
||||
return self.convert_strong(el, text, convert_as_inline)
|
||||
convert_b = abstract_inline_conversion(lambda self: 2 * self.options['strong_em_symbol'])
|
||||
|
||||
def convert_blockquote(self, el, text, convert_as_inline):
|
||||
|
||||
@@ -190,12 +222,17 @@ class MarkdownConverter(object):
|
||||
else:
|
||||
return ' \n'
|
||||
|
||||
def convert_em(self, el, text, convert_as_inline):
|
||||
em_tag = self.options['strong_em_symbol']
|
||||
prefix, suffix, text = chomp(text)
|
||||
if not text:
|
||||
return ''
|
||||
return '%s%s%s%s%s' % (prefix, em_tag, text, em_tag, suffix)
|
||||
def convert_code(self, el, text, convert_as_inline):
|
||||
if el.parent.name == 'pre':
|
||||
return text
|
||||
converter = abstract_inline_conversion(lambda self: '`')
|
||||
return converter(self, el, text, convert_as_inline)
|
||||
|
||||
convert_del = abstract_inline_conversion(lambda self: '~~')
|
||||
|
||||
convert_em = abstract_inline_conversion(lambda self: self.options['strong_em_symbol'])
|
||||
|
||||
convert_kbd = convert_code
|
||||
|
||||
def convert_hn(self, n, el, text, convert_as_inline):
|
||||
if convert_as_inline:
|
||||
@@ -211,8 +248,20 @@ class MarkdownConverter(object):
|
||||
return '%s %s %s\n\n' % (hashes, text, hashes)
|
||||
return '%s %s\n\n' % (hashes, text)
|
||||
|
||||
def convert_i(self, el, text, convert_as_inline):
|
||||
return self.convert_em(el, text, convert_as_inline)
|
||||
def convert_hr(self, el, text, convert_as_inline):
|
||||
return '\n\n---\n\n'
|
||||
|
||||
convert_i = convert_em
|
||||
|
||||
def convert_img(self, el, text, convert_as_inline):
|
||||
alt = el.attrs.get('alt', None) or ''
|
||||
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:
|
||||
return alt
|
||||
|
||||
return '' % (alt, src, title_part)
|
||||
|
||||
def convert_list(self, el, text, convert_as_inline):
|
||||
|
||||
@@ -259,42 +308,40 @@ class MarkdownConverter(object):
|
||||
return text
|
||||
return '%s\n\n' % text if text else ''
|
||||
|
||||
def convert_strong(self, el, text, convert_as_inline):
|
||||
strong_tag = 2 * self.options['strong_em_symbol']
|
||||
prefix, suffix, text = chomp(text)
|
||||
def convert_pre(self, el, text, convert_as_inline):
|
||||
if not text:
|
||||
return ''
|
||||
return '%s%s%s%s%s' % (prefix, strong_tag, text, strong_tag, suffix)
|
||||
return '\n```\n%s\n```\n' % text
|
||||
|
||||
def convert_img(self, el, text, convert_as_inline):
|
||||
alt = el.attrs.get('alt', None) or ''
|
||||
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:
|
||||
return alt
|
||||
convert_s = convert_del
|
||||
|
||||
return '' % (alt, src, title_part)
|
||||
convert_strong = convert_b
|
||||
|
||||
convert_samp = convert_code
|
||||
|
||||
def convert_table(self, el, text, convert_as_inline):
|
||||
rows = el.find_all('tr')
|
||||
text_data = []
|
||||
for row in rows:
|
||||
headers = row.find_all('th')
|
||||
columns = row.find_all('td')
|
||||
if len(headers) > 0:
|
||||
headers = [head.text.strip() for head in headers]
|
||||
text_data.append('| ' + ' | '.join(headers) + ' |')
|
||||
text_data.append('| ' + ' | '.join(['---'] * len(headers)) + ' |')
|
||||
elif len(columns) > 0:
|
||||
columns = [colm.text.strip() for colm in columns]
|
||||
text_data.append('| ' + ' | '.join(columns) + ' |')
|
||||
else:
|
||||
continue
|
||||
return '\n'.join(text_data)
|
||||
return '\n\n' + text + '\n'
|
||||
|
||||
def convert_hr(self, el, text, convert_as_inline):
|
||||
return '\n\n---\n\n'
|
||||
def convert_td(self, el, text, convert_as_inline):
|
||||
return ' ' + text + ' |'
|
||||
|
||||
def convert_th(self, el, text, convert_as_inline):
|
||||
return ' ' + text + ' |'
|
||||
|
||||
def convert_tr(self, el, text, convert_as_inline):
|
||||
cells = el.find_all(['td', 'th'])
|
||||
is_headrow = all([cell.name == 'th' for cell in cells])
|
||||
overline = ''
|
||||
underline = ''
|
||||
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:
|
||||
# print empty headline above this row
|
||||
overline += '| ' + ' | '.join([''] * len(cells)) + ' |' + '\n'
|
||||
overline += '| ' + ' | '.join(['---'] * len(cells)) + ' |' + '\n'
|
||||
return overline + '|' + text + '\n' + underline
|
||||
|
||||
|
||||
def markdownify(html, **options):
|
||||
|
||||
2
setup.py
2
setup.py
@@ -10,7 +10,7 @@ read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
||||
pkgmeta = {
|
||||
'__title__': 'markdownify',
|
||||
'__author__': 'Matthew Tretter',
|
||||
'__version__': '0.7.3',
|
||||
'__version__': '0.8.1',
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -14,3 +14,15 @@ def test_ignore_comments():
|
||||
def test_ignore_comments_with_other_tags():
|
||||
text = md("<!-- This is a comment --><a href='http://example.com/'>example link</a>")
|
||||
assert text == "[example link](http://example.com/)"
|
||||
|
||||
|
||||
def test_code_with_tricky_content():
|
||||
assert md('<code>></code>') == "`>`"
|
||||
assert md('<code>/home/</code><b>username</b>') == "`/home/`**username**"
|
||||
assert md('First line <code>blah blah<br />blah blah</code> second line') \
|
||||
== "First line `blah blah \nblah blah` second line"
|
||||
|
||||
|
||||
def test_special_tags():
|
||||
assert md('<!DOCTYPE html>') == ''
|
||||
assert md('<![CDATA[foobar]]>') == 'foobar'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, UNDERSCORE
|
||||
import re
|
||||
|
||||
|
||||
nested_uls = """
|
||||
@@ -41,8 +40,7 @@ nested_ols = """
|
||||
</ul>"""
|
||||
|
||||
|
||||
table = re.sub(r'\s+', '', """
|
||||
<table>
|
||||
table = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
@@ -58,18 +56,54 @@ table = re.sub(r'\s+', '', """
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>
|
||||
""")
|
||||
</table>"""
|
||||
|
||||
|
||||
table_head_body = re.sub(r'\s+', '', """
|
||||
<table>
|
||||
table_with_html_content = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Jill</b></td>
|
||||
<td><i>Smith</i></td>
|
||||
<td><a href="#">50</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
table_with_header_column = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Jill</th>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Eve</th>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
table_head_body = """<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
@@ -83,17 +117,15 @@ table_head_body = re.sub(r'\s+', '', """
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
""")
|
||||
</table>"""
|
||||
|
||||
table_missing_text = re.sub(r'\s+', '', """
|
||||
<table>
|
||||
table_missing_text = """<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
@@ -107,8 +139,25 @@ table_missing_text = re.sub(r'\s+', '', """
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
""")
|
||||
</table>"""
|
||||
|
||||
table_missing_head = """<table>
|
||||
<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>
|
||||
</table>"""
|
||||
|
||||
|
||||
def test_chomp():
|
||||
@@ -191,6 +240,40 @@ def test_em_spaces():
|
||||
assert md('foo <em></em> bar') == 'foo bar'
|
||||
|
||||
|
||||
def inline_tests(tag, markup):
|
||||
# Basically re-use test_em() and test_em_spaces(),
|
||||
assert md(f'<{tag}>Hello</{tag}>') == f'{markup}Hello{markup}'
|
||||
assert md(f'foo <{tag}>Hello</{tag}> bar') == f'foo {markup}Hello{markup} bar'
|
||||
assert md(f'foo<{tag}> Hello</{tag}> bar') == f'foo {markup}Hello{markup} bar'
|
||||
assert md(f'foo <{tag}>Hello </{tag}>bar') == f'foo {markup}Hello{markup} bar'
|
||||
assert md(f'foo <{tag}></{tag}> bar') in ['foo bar', 'foo bar'] # Either is OK
|
||||
|
||||
|
||||
def test_code():
|
||||
inline_tests('code', '`')
|
||||
|
||||
|
||||
def test_samp():
|
||||
inline_tests('samp', '`')
|
||||
|
||||
|
||||
def test_kbd():
|
||||
inline_tests('kbd', '`')
|
||||
|
||||
|
||||
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'
|
||||
|
||||
|
||||
def test_del():
|
||||
inline_tests('del', '~~')
|
||||
|
||||
|
||||
def test_s():
|
||||
inline_tests('s', '~~')
|
||||
|
||||
|
||||
def test_h1():
|
||||
assert md('<h1>Hello</h1>') == 'Hello\n=====\n\n'
|
||||
|
||||
@@ -322,9 +405,12 @@ def test_div():
|
||||
|
||||
|
||||
def test_table():
|
||||
assert md(table) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
|
||||
assert md(table_head_body) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
|
||||
assert md(table_missing_text) == '| | Lastname | Age |\n| --- | --- | --- |\n| Jill | | 50 |\n| Eve | Jackson | 94 |'
|
||||
assert md(table) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_with_html_content) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| **Jill** | *Smith* | [50](#) |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_with_header_column) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
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'
|
||||
|
||||
|
||||
def test_strong_em_symbol():
|
||||
|
||||
Reference in New Issue
Block a user