Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

787 Zeilen
28 KiB

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