Skip to content

Commit b589863

Browse files
committed
add escaping of asterisks and option to disable it
closes #62
1 parent 423b7e9 commit b589863

File tree

3 files changed

+20
-9
lines changed

3 files changed

+20
-9
lines changed

README.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,10 @@ code_language
102102
should be annotated with `````python`` or similar.
103103
Defaults to ``''`` (empty string) and can be any string.
104104

105+
escape_asterisks
106+
If set to ``False``, do not escape ``*`` to ``\*`` in text.
107+
Defaults to ``True``.
108+
105109
escape_underscores
106110
If set to ``False``, do not escape ``_`` to ``\_`` in text.
107111
Defaults to ``True``.

markdownify/__init__.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,6 @@
2525
UNDERSCORE = '_'
2626

2727

28-
def escape(text, escape_underscores):
29-
if not text:
30-
return ''
31-
if escape_underscores:
32-
return text.replace('_', r'\_')
33-
return text
34-
35-
3628
def chomp(text):
3729
"""
3830
If the text in an inline tag like b, a, or em contains a leading or trailing
@@ -73,6 +65,7 @@ class DefaultOptions:
7365
code_language = ''
7466
convert = None
7567
default_title = False
68+
escape_asterisks = True
7669
escape_underscores = True
7770
heading_style = UNDERLINED
7871
keep_inline_images_in = []
@@ -162,7 +155,7 @@ def process_text(self, el):
162155
text = whitespace_re.sub(' ', text)
163156

164157
if el.parent.name != 'code':
165-
text = escape(text, self.options['escape_underscores'])
158+
text = self.escape(text)
166159

167160
# remove trailing whitespaces if any of the following condition is true:
168161
# - current text node is the last node in li
@@ -200,6 +193,15 @@ def should_convert_tag(self, tag):
200193
else:
201194
return True
202195

196+
def escape(self, text):
197+
if not text:
198+
return ''
199+
if self.options['escape_asterisks']:
200+
text = text.replace('*', r'\*')
201+
if self.options['escape_underscores']:
202+
text = text.replace('_', r'\_')
203+
return text
204+
203205
def indent(self, text, level):
204206
return line_beginning_re.sub('\t' * level, text) if text else ''
205207

tests/test_escaping.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
from markdownify import markdownify as md
22

33

4+
def test_asterisks():
5+
assert md('*hey*dude*') == r'\*hey\*dude\*'
6+
assert md('*hey*dude*', escape_asterisks=False) == r'*hey*dude*'
7+
8+
49
def test_underscore():
510
assert md('_hey_dude_') == r'\_hey\_dude\_'
611
assert md('_hey_dude_', escape_underscores=False) == r'_hey_dude_'

0 commit comments

Comments
 (0)