Skip to content

Commit 5f1b98e

Browse files
committed
added wrap option
closes #66
1 parent 16acd2b commit 5f1b98e

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

README.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,11 @@ keep_inline_images_in
130130
that should be allowed to contain inline images, for example ``['td']``.
131131
Defaults to an empty list.
132132

133+
wrap, wrap_width
134+
If ``wrap`` is set to ``True``, all text paragraphs are wrapped at
135+
``wrap_width`` characters. Defaults to ``False`` and ``80``.
136+
Use with ``newline_style=BACKSLASH`` to keep line breaks in paragraphs.
137+
133138
Options may be specified as kwargs to the ``markdownify`` function, or as a
134139
nested ``Options`` class in ``MarkdownConverter`` subclasses.
135140

markdownify/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from bs4 import BeautifulSoup, NavigableString, Comment, Doctype
2+
from textwrap import fill
23
import re
34
import six
45

@@ -75,6 +76,8 @@ class DefaultOptions:
7576
strong_em_symbol = ASTERISK
7677
sub_symbol = ''
7778
sup_symbol = ''
79+
wrap = False
80+
wrap_width = 80
7881

7982
class Options(DefaultOptions):
8083
pass
@@ -331,6 +334,11 @@ def convert_li(self, el, text, convert_as_inline):
331334
def convert_p(self, el, text, convert_as_inline):
332335
if convert_as_inline:
333336
return text
337+
if self.options['wrap']:
338+
text = fill(text,
339+
width=self.options['wrap_width'],
340+
break_long_words=False,
341+
break_on_hyphens=False)
334342
return '%s\n\n' % text if text else ''
335343

336344
def convert_pre(self, el, text, convert_as_inline):

tests/test_conversions.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,11 @@ def test_kbd():
177177

178178
def test_p():
179179
assert md('<p>hello</p>') == 'hello\n\n'
180+
assert md('<p>123456789 123456789</p>') == '123456789 123456789\n\n'
181+
assert md('<p>123456789 123456789</p>', wrap=True, wrap_width=10) == '123456789\n123456789\n\n'
182+
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'
183+
assert md('<p>12345<br />67890</p>', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '12345\\\n67890\n\n'
184+
assert md('<p>12345678901<br />12345</p>', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '12345678901\\\n12345\n\n'
180185

181186

182187
def test_pre():

0 commit comments

Comments
 (0)