diff --git a/README.rst b/README.rst index b64318a..f961257 100644 --- a/README.rst +++ b/README.rst @@ -102,6 +102,10 @@ code_language should be annotated with `````python`` or similar. Defaults to ``''`` (empty string) and can be any string. +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``. diff --git a/markdownify/__init__.py b/markdownify/__init__.py index 8cf56eb..4ef539b 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -25,14 +25,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 @@ -73,6 +65,7 @@ class MarkdownConverter(object): code_language = '' convert = None default_title = False + escape_asterisks = True escape_underscores = True heading_style = UNDERLINED keep_inline_images_in = [] @@ -162,7 +155,7 @@ class MarkdownConverter(object): text = whitespace_re.sub(' ', text) if el.parent.name != 'code': - text = escape(text, self.options['escape_underscores']) + text = self.escape(text) # remove trailing whitespaces if any of the following condition is true: # - current text node is the last node in li @@ -200,6 +193,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 '' diff --git a/tests/test_escaping.py b/tests/test_escaping.py index 3388b7e..2f3a83e 100644 --- a/tests/test_escaping.py +++ b/tests/test_escaping.py @@ -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_'