Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions html2text/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""html2text: Turn HTML into equivalent Markdown-structured text."""
from __future__ import division
import re
import cgi

try:
from textwrap import wrap
Expand Down Expand Up @@ -160,10 +161,16 @@ def close(self):
return outtext

def handle_charref(self, c):
self.o(self.charref(c), 1)
charref = self.charref(c)
if not self.code and not self.pre:
charref = cgi.escape(charref)
self.o(charref, 1)

def handle_entityref(self, c):
self.o(self.entityref(c), 1)
entityref = self.entityref(c)
if not self.code and not self.pre and entityref != '&nbsp_place_holder;':
entityref = cgi.escape(entityref)
self.o(entityref, 1)

def handle_starttag(self, tag, attrs):
self.handle_tag(tag, attrs, 1)
Expand Down Expand Up @@ -351,6 +358,7 @@ def handle_tag(self, tag, attrs, start):

if tag in ["code", "tt"] and not self.pre:
self.o('`') # TODO: `` `this` ``
self.code = not self.code
if tag == "abbr":
if start:
self.abbr_title = None
Expand Down Expand Up @@ -416,7 +424,7 @@ def handle_tag(self, tag, attrs, start):
else:
self.o("[")
self.maybe_automatic_link = None
self.empty_link = False
self.empty_link = False

# If we have images_to_alt, we discard the image itself,
# considering only the alt text.
Expand Down
3 changes: 3 additions & 0 deletions test/html-escaping.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<p>Escaped HTML like &lt;div&gt; or &amp; should remain escaped on output</p>
<pre>...unless that escaped HTML is in a &lt;pre&gt; tag</pre>
<code>...or a &lt;code&gt; tag</code>
8 changes: 8 additions & 0 deletions test/html-escaping.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Escaped HTML like &lt;div&gt; or &amp; should remain escaped on output



...unless that escaped HTML is in a <pre> tag

`...or a <code> tag`