You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

742 lines
26 KiB

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