clean.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. """A cleanup tool for HTML.
  2. Removes unwanted tags and content. See the `Cleaner` class for
  3. details.
  4. """
  5. import re
  6. import copy
  7. try:
  8. from urlparse import urlsplit
  9. except ImportError:
  10. # Python 3
  11. from urllib.parse import urlsplit
  12. from lxml import etree
  13. from lxml.html import defs
  14. from lxml.html import fromstring, XHTML_NAMESPACE
  15. from lxml.html import xhtml_to_html, _transform_result
  16. try:
  17. unichr
  18. except NameError:
  19. # Python 3
  20. unichr = chr
  21. try:
  22. unicode
  23. except NameError:
  24. # Python 3
  25. unicode = str
  26. try:
  27. bytes
  28. except NameError:
  29. # Python < 2.6
  30. bytes = str
  31. try:
  32. basestring
  33. except NameError:
  34. basestring = (str, bytes)
  35. __all__ = ['clean_html', 'clean', 'Cleaner', 'autolink', 'autolink_html',
  36. 'word_break', 'word_break_html']
  37. # Look at http://code.sixapart.com/trac/livejournal/browser/trunk/cgi-bin/cleanhtml.pl
  38. # Particularly the CSS cleaning; most of the tag cleaning is integrated now
  39. # I have multiple kinds of schemes searched; but should schemes be
  40. # whitelisted instead?
  41. # max height?
  42. # remove images? Also in CSS? background attribute?
  43. # Some way to whitelist object, iframe, etc (e.g., if you want to
  44. # allow *just* embedded YouTube movies)
  45. # Log what was deleted and why?
  46. # style="behavior: ..." might be bad in IE?
  47. # Should we have something for just <meta http-equiv>? That's the worst of the
  48. # metas.
  49. # UTF-7 detections? Example:
  50. # <HEAD><META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=UTF-7"> </HEAD>+ADw-SCRIPT+AD4-alert('XSS');+ADw-/SCRIPT+AD4-
  51. # you don't always have to have the charset set, if the page has no charset
  52. # and there's UTF7-like code in it.
  53. # Look at these tests: http://htmlpurifier.org/live/smoketests/xssAttacks.php
  54. # This is an IE-specific construct you can have in a stylesheet to
  55. # run some Javascript:
  56. _css_javascript_re = re.compile(
  57. r'expression\s*\(.*?\)', re.S|re.I)
  58. # Do I have to worry about @\nimport?
  59. _css_import_re = re.compile(
  60. r'@\s*import', re.I)
  61. # All kinds of schemes besides just javascript: that can cause
  62. # execution:
  63. _is_image_dataurl = re.compile(
  64. r'^data:image/.+;base64', re.I).search
  65. _is_possibly_malicious_scheme = re.compile(
  66. r'(?:javascript|jscript|livescript|vbscript|data|about|mocha):',
  67. re.I).search
  68. def _is_javascript_scheme(s):
  69. if _is_image_dataurl(s):
  70. return None
  71. return _is_possibly_malicious_scheme(s)
  72. _substitute_whitespace = re.compile(r'[\s\x00-\x08\x0B\x0C\x0E-\x19]+').sub
  73. # FIXME: should data: be blocked?
  74. # FIXME: check against: http://msdn2.microsoft.com/en-us/library/ms537512.aspx
  75. _conditional_comment_re = re.compile(
  76. r'\[if[\s\n\r]+.*?][\s\n\r]*>', re.I|re.S)
  77. _find_styled_elements = etree.XPath(
  78. "descendant-or-self::*[@style]")
  79. _find_external_links = etree.XPath(
  80. ("descendant-or-self::a [normalize-space(@href) and substring(normalize-space(@href),1,1) != '#'] |"
  81. "descendant-or-self::x:a[normalize-space(@href) and substring(normalize-space(@href),1,1) != '#']"),
  82. namespaces={'x':XHTML_NAMESPACE})
  83. class Cleaner(object):
  84. """
  85. Instances cleans the document of each of the possible offending
  86. elements. The cleaning is controlled by attributes; you can
  87. override attributes in a subclass, or set them in the constructor.
  88. ``scripts``:
  89. Removes any ``<script>`` tags.
  90. ``javascript``:
  91. Removes any Javascript, like an ``onclick`` attribute. Also removes stylesheets
  92. as they could contain Javascript.
  93. ``comments``:
  94. Removes any comments.
  95. ``style``:
  96. Removes any style tags.
  97. ``inline_style``
  98. Removes any style attributes. Defaults to the value of the ``style`` option.
  99. ``links``:
  100. Removes any ``<link>`` tags
  101. ``meta``:
  102. Removes any ``<meta>`` tags
  103. ``page_structure``:
  104. Structural parts of a page: ``<head>``, ``<html>``, ``<title>``.
  105. ``processing_instructions``:
  106. Removes any processing instructions.
  107. ``embedded``:
  108. Removes any embedded objects (flash, iframes)
  109. ``frames``:
  110. Removes any frame-related tags
  111. ``forms``:
  112. Removes any form tags
  113. ``annoying_tags``:
  114. Tags that aren't *wrong*, but are annoying. ``<blink>`` and ``<marquee>``
  115. ``remove_tags``:
  116. A list of tags to remove. Only the tags will be removed,
  117. their content will get pulled up into the parent tag.
  118. ``kill_tags``:
  119. A list of tags to kill. Killing also removes the tag's content,
  120. i.e. the whole subtree, not just the tag itself.
  121. ``allow_tags``:
  122. A list of tags to include (default include all).
  123. ``remove_unknown_tags``:
  124. Remove any tags that aren't standard parts of HTML.
  125. ``safe_attrs_only``:
  126. If true, only include 'safe' attributes (specifically the list
  127. from the feedparser HTML sanitisation web site).
  128. ``safe_attrs``:
  129. A set of attribute names to override the default list of attributes
  130. considered 'safe' (when safe_attrs_only=True).
  131. ``add_nofollow``:
  132. If true, then any <a> tags will have ``rel="nofollow"`` added to them.
  133. ``host_whitelist``:
  134. A list or set of hosts that you can use for embedded content
  135. (for content like ``<object>``, ``<link rel="stylesheet">``, etc).
  136. You can also implement/override the method
  137. ``allow_embedded_url(el, url)`` or ``allow_element(el)`` to
  138. implement more complex rules for what can be embedded.
  139. Anything that passes this test will be shown, regardless of
  140. the value of (for instance) ``embedded``.
  141. Note that this parameter might not work as intended if you do not
  142. make the links absolute before doing the cleaning.
  143. Note that you may also need to set ``whitelist_tags``.
  144. ``whitelist_tags``:
  145. A set of tags that can be included with ``host_whitelist``.
  146. The default is ``iframe`` and ``embed``; you may wish to
  147. include other tags like ``script``, or you may want to
  148. implement ``allow_embedded_url`` for more control. Set to None to
  149. include all tags.
  150. This modifies the document *in place*.
  151. """
  152. scripts = True
  153. javascript = True
  154. comments = True
  155. style = False
  156. inline_style = None
  157. links = True
  158. meta = True
  159. page_structure = True
  160. processing_instructions = True
  161. embedded = True
  162. frames = True
  163. forms = True
  164. annoying_tags = True
  165. remove_tags = None
  166. allow_tags = None
  167. kill_tags = None
  168. remove_unknown_tags = True
  169. safe_attrs_only = True
  170. safe_attrs = defs.safe_attrs
  171. add_nofollow = False
  172. host_whitelist = ()
  173. whitelist_tags = set(['iframe', 'embed'])
  174. def __init__(self, **kw):
  175. for name, value in kw.items():
  176. if not hasattr(self, name):
  177. raise TypeError(
  178. "Unknown parameter: %s=%r" % (name, value))
  179. setattr(self, name, value)
  180. if self.inline_style is None and 'inline_style' not in kw:
  181. self.inline_style = self.style
  182. # Used to lookup the primary URL for a given tag that is up for
  183. # removal:
  184. _tag_link_attrs = dict(
  185. script='src',
  186. link='href',
  187. # From: http://java.sun.com/j2se/1.4.2/docs/guide/misc/applet.html
  188. # From what I can tell, both attributes can contain a link:
  189. applet=['code', 'object'],
  190. iframe='src',
  191. embed='src',
  192. layer='src',
  193. # FIXME: there doesn't really seem like a general way to figure out what
  194. # links an <object> tag uses; links often go in <param> tags with values
  195. # that we don't really know. You'd have to have knowledge about specific
  196. # kinds of plugins (probably keyed off classid), and match against those.
  197. ##object=?,
  198. # FIXME: not looking at the action currently, because it is more complex
  199. # than than -- if you keep the form, you should keep the form controls.
  200. ##form='action',
  201. a='href',
  202. )
  203. def __call__(self, doc):
  204. """
  205. Cleans the document.
  206. """
  207. if hasattr(doc, 'getroot'):
  208. # ElementTree instance, instead of an element
  209. doc = doc.getroot()
  210. # convert XHTML to HTML
  211. xhtml_to_html(doc)
  212. # Normalize a case that IE treats <image> like <img>, and that
  213. # can confuse either this step or later steps.
  214. for el in doc.iter('image'):
  215. el.tag = 'img'
  216. if not self.comments:
  217. # Of course, if we were going to kill comments anyway, we don't
  218. # need to worry about this
  219. self.kill_conditional_comments(doc)
  220. kill_tags = set(self.kill_tags or ())
  221. remove_tags = set(self.remove_tags or ())
  222. allow_tags = set(self.allow_tags or ())
  223. if self.scripts:
  224. kill_tags.add('script')
  225. if self.safe_attrs_only:
  226. safe_attrs = set(self.safe_attrs)
  227. for el in doc.iter(etree.Element):
  228. attrib = el.attrib
  229. for aname in attrib.keys():
  230. if aname not in safe_attrs:
  231. del attrib[aname]
  232. if self.javascript:
  233. if not (self.safe_attrs_only and
  234. self.safe_attrs == defs.safe_attrs):
  235. # safe_attrs handles events attributes itself
  236. for el in doc.iter(etree.Element):
  237. attrib = el.attrib
  238. for aname in attrib.keys():
  239. if aname.startswith('on'):
  240. del attrib[aname]
  241. doc.rewrite_links(self._remove_javascript_link,
  242. resolve_base_href=False)
  243. # If we're deleting style then we don't have to remove JS links
  244. # from styles, otherwise...
  245. if not self.inline_style:
  246. for el in _find_styled_elements(doc):
  247. old = el.get('style')
  248. new = _css_javascript_re.sub('', old)
  249. new = _css_import_re.sub('', new)
  250. if self._has_sneaky_javascript(new):
  251. # Something tricky is going on...
  252. del el.attrib['style']
  253. elif new != old:
  254. el.set('style', new)
  255. if not self.style:
  256. for el in list(doc.iter('style')):
  257. if el.get('type', '').lower().strip() == 'text/javascript':
  258. el.drop_tree()
  259. continue
  260. old = el.text or ''
  261. new = _css_javascript_re.sub('', old)
  262. # The imported CSS can do anything; we just can't allow:
  263. new = _css_import_re.sub('', old)
  264. if self._has_sneaky_javascript(new):
  265. # Something tricky is going on...
  266. el.text = '/* deleted */'
  267. elif new != old:
  268. el.text = new
  269. if self.comments or self.processing_instructions:
  270. # FIXME: why either? I feel like there's some obscure reason
  271. # because you can put PIs in comments...? But I've already
  272. # forgotten it
  273. kill_tags.add(etree.Comment)
  274. if self.processing_instructions:
  275. kill_tags.add(etree.ProcessingInstruction)
  276. if self.style:
  277. kill_tags.add('style')
  278. if self.inline_style:
  279. etree.strip_attributes(doc, 'style')
  280. if self.links:
  281. kill_tags.add('link')
  282. elif self.style or self.javascript:
  283. # We must get rid of included stylesheets if Javascript is not
  284. # allowed, as you can put Javascript in them
  285. for el in list(doc.iter('link')):
  286. if 'stylesheet' in el.get('rel', '').lower():
  287. # Note this kills alternate stylesheets as well
  288. if not self.allow_element(el):
  289. el.drop_tree()
  290. if self.meta:
  291. kill_tags.add('meta')
  292. if self.page_structure:
  293. remove_tags.update(('head', 'html', 'title'))
  294. if self.embedded:
  295. # FIXME: is <layer> really embedded?
  296. # We should get rid of any <param> tags not inside <applet>;
  297. # These are not really valid anyway.
  298. for el in list(doc.iter('param')):
  299. found_parent = False
  300. parent = el.getparent()
  301. while parent is not None and parent.tag not in ('applet', 'object'):
  302. parent = parent.getparent()
  303. if parent is None:
  304. el.drop_tree()
  305. kill_tags.update(('applet',))
  306. # The alternate contents that are in an iframe are a good fallback:
  307. remove_tags.update(('iframe', 'embed', 'layer', 'object', 'param'))
  308. if self.frames:
  309. # FIXME: ideally we should look at the frame links, but
  310. # generally frames don't mix properly with an HTML
  311. # fragment anyway.
  312. kill_tags.update(defs.frame_tags)
  313. if self.forms:
  314. remove_tags.add('form')
  315. kill_tags.update(('button', 'input', 'select', 'textarea'))
  316. if self.annoying_tags:
  317. remove_tags.update(('blink', 'marquee'))
  318. _remove = []
  319. _kill = []
  320. for el in doc.iter():
  321. if el.tag in kill_tags:
  322. if self.allow_element(el):
  323. continue
  324. _kill.append(el)
  325. elif el.tag in remove_tags:
  326. if self.allow_element(el):
  327. continue
  328. _remove.append(el)
  329. if _remove and _remove[0] == doc:
  330. # We have to drop the parent-most tag, which we can't
  331. # do. Instead we'll rewrite it:
  332. el = _remove.pop(0)
  333. el.tag = 'div'
  334. el.attrib.clear()
  335. elif _kill and _kill[0] == doc:
  336. # We have to drop the parent-most element, which we can't
  337. # do. Instead we'll clear it:
  338. el = _kill.pop(0)
  339. if el.tag != 'html':
  340. el.tag = 'div'
  341. el.clear()
  342. _kill.reverse() # start with innermost tags
  343. for el in _kill:
  344. el.drop_tree()
  345. for el in _remove:
  346. el.drop_tag()
  347. if self.remove_unknown_tags:
  348. if allow_tags:
  349. raise ValueError(
  350. "It does not make sense to pass in both allow_tags and remove_unknown_tags")
  351. allow_tags = set(defs.tags)
  352. if allow_tags:
  353. bad = []
  354. for el in doc.iter():
  355. if el.tag not in allow_tags:
  356. bad.append(el)
  357. if bad:
  358. if bad[0] is doc:
  359. el = bad.pop(0)
  360. el.tag = 'div'
  361. el.attrib.clear()
  362. for el in bad:
  363. el.drop_tag()
  364. if self.add_nofollow:
  365. for el in _find_external_links(doc):
  366. if not self.allow_follow(el):
  367. rel = el.get('rel')
  368. if rel:
  369. if ('nofollow' in rel
  370. and ' nofollow ' in (' %s ' % rel)):
  371. continue
  372. rel = '%s nofollow' % rel
  373. else:
  374. rel = 'nofollow'
  375. el.set('rel', rel)
  376. def allow_follow(self, anchor):
  377. """
  378. Override to suppress rel="nofollow" on some anchors.
  379. """
  380. return False
  381. def allow_element(self, el):
  382. if el.tag not in self._tag_link_attrs:
  383. return False
  384. attr = self._tag_link_attrs[el.tag]
  385. if isinstance(attr, (list, tuple)):
  386. for one_attr in attr:
  387. url = el.get(one_attr)
  388. if not url:
  389. return False
  390. if not self.allow_embedded_url(el, url):
  391. return False
  392. return True
  393. else:
  394. url = el.get(attr)
  395. if not url:
  396. return False
  397. return self.allow_embedded_url(el, url)
  398. def allow_embedded_url(self, el, url):
  399. if (self.whitelist_tags is not None
  400. and el.tag not in self.whitelist_tags):
  401. return False
  402. scheme, netloc, path, query, fragment = urlsplit(url)
  403. netloc = netloc.lower().split(':', 1)[0]
  404. if scheme not in ('http', 'https'):
  405. return False
  406. if netloc in self.host_whitelist:
  407. return True
  408. return False
  409. def kill_conditional_comments(self, doc):
  410. """
  411. IE conditional comments basically embed HTML that the parser
  412. doesn't normally see. We can't allow anything like that, so
  413. we'll kill any comments that could be conditional.
  414. """
  415. bad = []
  416. self._kill_elements(
  417. doc, lambda el: _conditional_comment_re.search(el.text),
  418. etree.Comment)
  419. def _kill_elements(self, doc, condition, iterate=None):
  420. bad = []
  421. for el in doc.iter(iterate):
  422. if condition(el):
  423. bad.append(el)
  424. for el in bad:
  425. el.drop_tree()
  426. def _remove_javascript_link(self, link):
  427. # links like "j a v a s c r i p t:" might be interpreted in IE
  428. new = _substitute_whitespace('', link)
  429. if _is_javascript_scheme(new):
  430. # FIXME: should this be None to delete?
  431. return ''
  432. return link
  433. _substitute_comments = re.compile(r'/\*.*?\*/', re.S).sub
  434. def _has_sneaky_javascript(self, style):
  435. """
  436. Depending on the browser, stuff like ``e x p r e s s i o n(...)``
  437. can get interpreted, or ``expre/* stuff */ssion(...)``. This
  438. checks for attempt to do stuff like this.
  439. Typically the response will be to kill the entire style; if you
  440. have just a bit of Javascript in the style another rule will catch
  441. that and remove only the Javascript from the style; this catches
  442. more sneaky attempts.
  443. """
  444. style = self._substitute_comments('', style)
  445. style = style.replace('\\', '')
  446. style = _substitute_whitespace('', style)
  447. style = style.lower()
  448. if 'javascript:' in style:
  449. return True
  450. if 'expression(' in style:
  451. return True
  452. return False
  453. def clean_html(self, html):
  454. result_type = type(html)
  455. if isinstance(html, basestring):
  456. doc = fromstring(html)
  457. else:
  458. doc = copy.deepcopy(html)
  459. self(doc)
  460. return _transform_result(result_type, doc)
  461. clean = Cleaner()
  462. clean_html = clean.clean_html
  463. ############################################################
  464. ## Autolinking
  465. ############################################################
  466. _link_regexes = [
  467. re.compile(r'(?P<body>https?://(?P<host>[a-z0-9._-]+)(?:/[/\-_.,a-z0-9%&?;=~]*)?(?:\([/\-_.,a-z0-9%&?;=~]*\))?)', re.I),
  468. # This is conservative, but autolinking can be a bit conservative:
  469. re.compile(r'mailto:(?P<body>[a-z0-9._-]+@(?P<host>[a-z0-9_.-]+[a-z]))', re.I),
  470. ]
  471. _avoid_elements = ['textarea', 'pre', 'code', 'head', 'select', 'a']
  472. _avoid_hosts = [
  473. re.compile(r'^localhost', re.I),
  474. re.compile(r'\bexample\.(?:com|org|net)$', re.I),
  475. re.compile(r'^127\.0\.0\.1$'),
  476. ]
  477. _avoid_classes = ['nolink']
  478. def autolink(el, link_regexes=_link_regexes,
  479. avoid_elements=_avoid_elements,
  480. avoid_hosts=_avoid_hosts,
  481. avoid_classes=_avoid_classes):
  482. """
  483. Turn any URLs into links.
  484. It will search for links identified by the given regular
  485. expressions (by default mailto and http(s) links).
  486. It won't link text in an element in avoid_elements, or an element
  487. with a class in avoid_classes. It won't link to anything with a
  488. host that matches one of the regular expressions in avoid_hosts
  489. (default localhost and 127.0.0.1).
  490. If you pass in an element, the element's tail will not be
  491. substituted, only the contents of the element.
  492. """
  493. if el.tag in avoid_elements:
  494. return
  495. class_name = el.get('class')
  496. if class_name:
  497. class_name = class_name.split()
  498. for match_class in avoid_classes:
  499. if match_class in class_name:
  500. return
  501. for child in list(el):
  502. autolink(child, link_regexes=link_regexes,
  503. avoid_elements=avoid_elements,
  504. avoid_hosts=avoid_hosts,
  505. avoid_classes=avoid_classes)
  506. if child.tail:
  507. text, tail_children = _link_text(
  508. child.tail, link_regexes, avoid_hosts, factory=el.makeelement)
  509. if tail_children:
  510. child.tail = text
  511. index = el.index(child)
  512. el[index+1:index+1] = tail_children
  513. if el.text:
  514. text, pre_children = _link_text(
  515. el.text, link_regexes, avoid_hosts, factory=el.makeelement)
  516. if pre_children:
  517. el.text = text
  518. el[:0] = pre_children
  519. def _link_text(text, link_regexes, avoid_hosts, factory):
  520. leading_text = ''
  521. links = []
  522. last_pos = 0
  523. while 1:
  524. best_match, best_pos = None, None
  525. for regex in link_regexes:
  526. regex_pos = last_pos
  527. while 1:
  528. match = regex.search(text, pos=regex_pos)
  529. if match is None:
  530. break
  531. host = match.group('host')
  532. for host_regex in avoid_hosts:
  533. if host_regex.search(host):
  534. regex_pos = match.end()
  535. break
  536. else:
  537. break
  538. if match is None:
  539. continue
  540. if best_pos is None or match.start() < best_pos:
  541. best_match = match
  542. best_pos = match.start()
  543. if best_match is None:
  544. # No more matches
  545. if links:
  546. assert not links[-1].tail
  547. links[-1].tail = text
  548. else:
  549. assert not leading_text
  550. leading_text = text
  551. break
  552. link = best_match.group(0)
  553. end = best_match.end()
  554. if link.endswith('.') or link.endswith(','):
  555. # These punctuation marks shouldn't end a link
  556. end -= 1
  557. link = link[:-1]
  558. prev_text = text[:best_match.start()]
  559. if links:
  560. assert not links[-1].tail
  561. links[-1].tail = prev_text
  562. else:
  563. assert not leading_text
  564. leading_text = prev_text
  565. anchor = factory('a')
  566. anchor.set('href', link)
  567. body = best_match.group('body')
  568. if not body:
  569. body = link
  570. if body.endswith('.') or body.endswith(','):
  571. body = body[:-1]
  572. anchor.text = body
  573. links.append(anchor)
  574. text = text[end:]
  575. return leading_text, links
  576. def autolink_html(html, *args, **kw):
  577. result_type = type(html)
  578. if isinstance(html, basestring):
  579. doc = fromstring(html)
  580. else:
  581. doc = copy.deepcopy(html)
  582. autolink(doc, *args, **kw)
  583. return _transform_result(result_type, doc)
  584. autolink_html.__doc__ = autolink.__doc__
  585. ############################################################
  586. ## Word wrapping
  587. ############################################################
  588. _avoid_word_break_elements = ['pre', 'textarea', 'code']
  589. _avoid_word_break_classes = ['nobreak']
  590. def word_break(el, max_width=40,
  591. avoid_elements=_avoid_word_break_elements,
  592. avoid_classes=_avoid_word_break_classes,
  593. break_character=unichr(0x200b)):
  594. """
  595. Breaks any long words found in the body of the text (not attributes).
  596. Doesn't effect any of the tags in avoid_elements, by default
  597. ``<textarea>`` and ``<pre>``
  598. Breaks words by inserting &#8203;, which is a unicode character
  599. for Zero Width Space character. This generally takes up no space
  600. in rendering, but does copy as a space, and in monospace contexts
  601. usually takes up space.
  602. See http://www.cs.tut.fi/~jkorpela/html/nobr.html for a discussion
  603. """
  604. # Character suggestion of &#8203 comes from:
  605. # http://www.cs.tut.fi/~jkorpela/html/nobr.html
  606. if el.tag in _avoid_word_break_elements:
  607. return
  608. class_name = el.get('class')
  609. if class_name:
  610. dont_break = False
  611. class_name = class_name.split()
  612. for avoid in avoid_classes:
  613. if avoid in class_name:
  614. dont_break = True
  615. break
  616. if dont_break:
  617. return
  618. if el.text:
  619. el.text = _break_text(el.text, max_width, break_character)
  620. for child in el:
  621. word_break(child, max_width=max_width,
  622. avoid_elements=avoid_elements,
  623. avoid_classes=avoid_classes,
  624. break_character=break_character)
  625. if child.tail:
  626. child.tail = _break_text(child.tail, max_width, break_character)
  627. def word_break_html(html, *args, **kw):
  628. result_type = type(html)
  629. doc = fromstring(html)
  630. word_break(doc, *args, **kw)
  631. return _transform_result(result_type, doc)
  632. def _break_text(text, max_width, break_character):
  633. words = text.split()
  634. for word in words:
  635. if len(word) > max_width:
  636. replacement = _insert_break(word, max_width, break_character)
  637. text = text.replace(word, replacement)
  638. return text
  639. _break_prefer_re = re.compile(r'[^a-z]', re.I)
  640. def _insert_break(word, width, break_character):
  641. orig_word = word
  642. result = ''
  643. while len(word) > width:
  644. start = word[:width]
  645. breaks = list(_break_prefer_re.finditer(start))
  646. if breaks:
  647. last_break = breaks[-1]
  648. # Only walk back up to 10 characters to find a nice break:
  649. if last_break.end() > width-10:
  650. # FIXME: should the break character be at the end of the
  651. # chunk, or the beginning of the next chunk?
  652. start = word[:last_break.end()]
  653. result += start + break_character
  654. word = word[len(start):]
  655. result += word
  656. return result