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.

881 lines
30 KiB

4 years ago
  1. import difflib
  2. from lxml import etree
  3. from lxml.html import fragment_fromstring
  4. import re
  5. __all__ = ['html_annotate', 'htmldiff']
  6. try:
  7. from html import escape as html_escape
  8. except ImportError:
  9. from cgi import escape as html_escape
  10. try:
  11. _unicode = unicode
  12. except NameError:
  13. # Python 3
  14. _unicode = str
  15. try:
  16. basestring
  17. except NameError:
  18. # Python 3
  19. basestring = str
  20. ############################################################
  21. ## Annotation
  22. ############################################################
  23. def default_markup(text, version):
  24. return '<span title="%s">%s</span>' % (
  25. html_escape(_unicode(version), 1), text)
  26. def html_annotate(doclist, markup=default_markup):
  27. """
  28. doclist should be ordered from oldest to newest, like::
  29. >>> version1 = 'Hello World'
  30. >>> version2 = 'Goodbye World'
  31. >>> print(html_annotate([(version1, 'version 1'),
  32. ... (version2, 'version 2')]))
  33. <span title="version 2">Goodbye</span> <span title="version 1">World</span>
  34. The documents must be *fragments* (str/UTF8 or unicode), not
  35. complete documents
  36. The markup argument is a function to markup the spans of words.
  37. This function is called like markup('Hello', 'version 2'), and
  38. returns HTML. The first argument is text and never includes any
  39. markup. The default uses a span with a title:
  40. >>> print(default_markup('Some Text', 'by Joe'))
  41. <span title="by Joe">Some Text</span>
  42. """
  43. # The basic strategy we have is to split the documents up into
  44. # logical tokens (which are words with attached markup). We then
  45. # do diffs of each of the versions to track when a token first
  46. # appeared in the document; the annotation attached to the token
  47. # is the version where it first appeared.
  48. tokenlist = [tokenize_annotated(doc, version)
  49. for doc, version in doclist]
  50. cur_tokens = tokenlist[0]
  51. for tokens in tokenlist[1:]:
  52. html_annotate_merge_annotations(cur_tokens, tokens)
  53. cur_tokens = tokens
  54. # After we've tracked all the tokens, we can combine spans of text
  55. # that are adjacent and have the same annotation
  56. cur_tokens = compress_tokens(cur_tokens)
  57. # And finally add markup
  58. result = markup_serialize_tokens(cur_tokens, markup)
  59. return ''.join(result).strip()
  60. def tokenize_annotated(doc, annotation):
  61. """Tokenize a document and add an annotation attribute to each token
  62. """
  63. tokens = tokenize(doc, include_hrefs=False)
  64. for tok in tokens:
  65. tok.annotation = annotation
  66. return tokens
  67. def html_annotate_merge_annotations(tokens_old, tokens_new):
  68. """Merge the annotations from tokens_old into tokens_new, when the
  69. tokens in the new document already existed in the old document.
  70. """
  71. s = InsensitiveSequenceMatcher(a=tokens_old, b=tokens_new)
  72. commands = s.get_opcodes()
  73. for command, i1, i2, j1, j2 in commands:
  74. if command == 'equal':
  75. eq_old = tokens_old[i1:i2]
  76. eq_new = tokens_new[j1:j2]
  77. copy_annotations(eq_old, eq_new)
  78. def copy_annotations(src, dest):
  79. """
  80. Copy annotations from the tokens listed in src to the tokens in dest
  81. """
  82. assert len(src) == len(dest)
  83. for src_tok, dest_tok in zip(src, dest):
  84. dest_tok.annotation = src_tok.annotation
  85. def compress_tokens(tokens):
  86. """
  87. Combine adjacent tokens when there is no HTML between the tokens,
  88. and they share an annotation
  89. """
  90. result = [tokens[0]]
  91. for tok in tokens[1:]:
  92. if (not result[-1].post_tags and
  93. not tok.pre_tags and
  94. result[-1].annotation == tok.annotation):
  95. compress_merge_back(result, tok)
  96. else:
  97. result.append(tok)
  98. return result
  99. def compress_merge_back(tokens, tok):
  100. """ Merge tok into the last element of tokens (modifying the list of
  101. tokens in-place). """
  102. last = tokens[-1]
  103. if type(last) is not token or type(tok) is not token:
  104. tokens.append(tok)
  105. else:
  106. text = _unicode(last)
  107. if last.trailing_whitespace:
  108. text += last.trailing_whitespace
  109. text += tok
  110. merged = token(text,
  111. pre_tags=last.pre_tags,
  112. post_tags=tok.post_tags,
  113. trailing_whitespace=tok.trailing_whitespace)
  114. merged.annotation = last.annotation
  115. tokens[-1] = merged
  116. def markup_serialize_tokens(tokens, markup_func):
  117. """
  118. Serialize the list of tokens into a list of text chunks, calling
  119. markup_func around text to add annotations.
  120. """
  121. for token in tokens:
  122. for pre in token.pre_tags:
  123. yield pre
  124. html = token.html()
  125. html = markup_func(html, token.annotation)
  126. if token.trailing_whitespace:
  127. html += token.trailing_whitespace
  128. yield html
  129. for post in token.post_tags:
  130. yield post
  131. ############################################################
  132. ## HTML Diffs
  133. ############################################################
  134. def htmldiff(old_html, new_html):
  135. ## FIXME: this should take parsed documents too, and use their body
  136. ## or other content.
  137. """ Do a diff of the old and new document. The documents are HTML
  138. *fragments* (str/UTF8 or unicode), they are not complete documents
  139. (i.e., no <html> tag).
  140. Returns HTML with <ins> and <del> tags added around the
  141. appropriate text.
  142. Markup is generally ignored, with the markup from new_html
  143. preserved, and possibly some markup from old_html (though it is
  144. considered acceptable to lose some of the old markup). Only the
  145. words in the HTML are diffed. The exception is <img> tags, which
  146. are treated like words, and the href attribute of <a> tags, which
  147. are noted inside the tag itself when there are changes.
  148. """
  149. old_html_tokens = tokenize(old_html)
  150. new_html_tokens = tokenize(new_html)
  151. result = htmldiff_tokens(old_html_tokens, new_html_tokens)
  152. result = ''.join(result).strip()
  153. return fixup_ins_del_tags(result)
  154. def htmldiff_tokens(html1_tokens, html2_tokens):
  155. """ Does a diff on the tokens themselves, returning a list of text
  156. chunks (not tokens).
  157. """
  158. # There are several passes as we do the differences. The tokens
  159. # isolate the portion of the content we care to diff; difflib does
  160. # all the actual hard work at that point.
  161. #
  162. # Then we must create a valid document from pieces of both the old
  163. # document and the new document. We generally prefer to take
  164. # markup from the new document, and only do a best effort attempt
  165. # to keep markup from the old document; anything that we can't
  166. # resolve we throw away. Also we try to put the deletes as close
  167. # to the location where we think they would have been -- because
  168. # we are only keeping the markup from the new document, it can be
  169. # fuzzy where in the new document the old text would have gone.
  170. # Again we just do a best effort attempt.
  171. s = InsensitiveSequenceMatcher(a=html1_tokens, b=html2_tokens)
  172. commands = s.get_opcodes()
  173. result = []
  174. for command, i1, i2, j1, j2 in commands:
  175. if command == 'equal':
  176. result.extend(expand_tokens(html2_tokens[j1:j2], equal=True))
  177. continue
  178. if command == 'insert' or command == 'replace':
  179. ins_tokens = expand_tokens(html2_tokens[j1:j2])
  180. merge_insert(ins_tokens, result)
  181. if command == 'delete' or command == 'replace':
  182. del_tokens = expand_tokens(html1_tokens[i1:i2])
  183. merge_delete(del_tokens, result)
  184. # If deletes were inserted directly as <del> then we'd have an
  185. # invalid document at this point. Instead we put in special
  186. # markers, and when the complete diffed document has been created
  187. # we try to move the deletes around and resolve any problems.
  188. result = cleanup_delete(result)
  189. return result
  190. def expand_tokens(tokens, equal=False):
  191. """Given a list of tokens, return a generator of the chunks of
  192. text for the data in the tokens.
  193. """
  194. for token in tokens:
  195. for pre in token.pre_tags:
  196. yield pre
  197. if not equal or not token.hide_when_equal:
  198. if token.trailing_whitespace:
  199. yield token.html() + token.trailing_whitespace
  200. else:
  201. yield token.html()
  202. for post in token.post_tags:
  203. yield post
  204. def merge_insert(ins_chunks, doc):
  205. """ doc is the already-handled document (as a list of text chunks);
  206. here we add <ins>ins_chunks</ins> to the end of that. """
  207. # Though we don't throw away unbalanced_start or unbalanced_end
  208. # (we assume there is accompanying markup later or earlier in the
  209. # document), we only put <ins> around the balanced portion.
  210. unbalanced_start, balanced, unbalanced_end = split_unbalanced(ins_chunks)
  211. doc.extend(unbalanced_start)
  212. if doc and not doc[-1].endswith(' '):
  213. # Fix up the case where the word before the insert didn't end with
  214. # a space
  215. doc[-1] += ' '
  216. doc.append('<ins>')
  217. if balanced and balanced[-1].endswith(' '):
  218. # We move space outside of </ins>
  219. balanced[-1] = balanced[-1][:-1]
  220. doc.extend(balanced)
  221. doc.append('</ins> ')
  222. doc.extend(unbalanced_end)
  223. # These are sentinals to represent the start and end of a <del>
  224. # segment, until we do the cleanup phase to turn them into proper
  225. # markup:
  226. class DEL_START:
  227. pass
  228. class DEL_END:
  229. pass
  230. class NoDeletes(Exception):
  231. """ Raised when the document no longer contains any pending deletes
  232. (DEL_START/DEL_END) """
  233. def merge_delete(del_chunks, doc):
  234. """ Adds the text chunks in del_chunks to the document doc (another
  235. list of text chunks) with marker to show it is a delete.
  236. cleanup_delete later resolves these markers into <del> tags."""
  237. doc.append(DEL_START)
  238. doc.extend(del_chunks)
  239. doc.append(DEL_END)
  240. def cleanup_delete(chunks):
  241. """ Cleans up any DEL_START/DEL_END markers in the document, replacing
  242. them with <del></del>. To do this while keeping the document
  243. valid, it may need to drop some tags (either start or end tags).
  244. It may also move the del into adjacent tags to try to move it to a
  245. similar location where it was originally located (e.g., moving a
  246. delete into preceding <div> tag, if the del looks like (DEL_START,
  247. 'Text</div>', DEL_END)"""
  248. while 1:
  249. # Find a pending DEL_START/DEL_END, splitting the document
  250. # into stuff-preceding-DEL_START, stuff-inside, and
  251. # stuff-following-DEL_END
  252. try:
  253. pre_delete, delete, post_delete = split_delete(chunks)
  254. except NoDeletes:
  255. # Nothing found, we've cleaned up the entire doc
  256. break
  257. # The stuff-inside-DEL_START/END may not be well balanced
  258. # markup. First we figure out what unbalanced portions there are:
  259. unbalanced_start, balanced, unbalanced_end = split_unbalanced(delete)
  260. # Then we move the span forward and/or backward based on these
  261. # unbalanced portions:
  262. locate_unbalanced_start(unbalanced_start, pre_delete, post_delete)
  263. locate_unbalanced_end(unbalanced_end, pre_delete, post_delete)
  264. doc = pre_delete
  265. if doc and not doc[-1].endswith(' '):
  266. # Fix up case where the word before us didn't have a trailing space
  267. doc[-1] += ' '
  268. doc.append('<del>')
  269. if balanced and balanced[-1].endswith(' '):
  270. # We move space outside of </del>
  271. balanced[-1] = balanced[-1][:-1]
  272. doc.extend(balanced)
  273. doc.append('</del> ')
  274. doc.extend(post_delete)
  275. chunks = doc
  276. return chunks
  277. def split_unbalanced(chunks):
  278. """Return (unbalanced_start, balanced, unbalanced_end), where each is
  279. a list of text and tag chunks.
  280. unbalanced_start is a list of all the tags that are opened, but
  281. not closed in this span. Similarly, unbalanced_end is a list of
  282. tags that are closed but were not opened. Extracting these might
  283. mean some reordering of the chunks."""
  284. start = []
  285. end = []
  286. tag_stack = []
  287. balanced = []
  288. for chunk in chunks:
  289. if not chunk.startswith('<'):
  290. balanced.append(chunk)
  291. continue
  292. endtag = chunk[1] == '/'
  293. name = chunk.split()[0].strip('<>/')
  294. if name in empty_tags:
  295. balanced.append(chunk)
  296. continue
  297. if endtag:
  298. if tag_stack and tag_stack[-1][0] == name:
  299. balanced.append(chunk)
  300. name, pos, tag = tag_stack.pop()
  301. balanced[pos] = tag
  302. elif tag_stack:
  303. start.extend([tag for name, pos, tag in tag_stack])
  304. tag_stack = []
  305. end.append(chunk)
  306. else:
  307. end.append(chunk)
  308. else:
  309. tag_stack.append((name, len(balanced), chunk))
  310. balanced.append(None)
  311. start.extend(
  312. [chunk for name, pos, chunk in tag_stack])
  313. balanced = [chunk for chunk in balanced if chunk is not None]
  314. return start, balanced, end
  315. def split_delete(chunks):
  316. """ Returns (stuff_before_DEL_START, stuff_inside_DEL_START_END,
  317. stuff_after_DEL_END). Returns the first case found (there may be
  318. more DEL_STARTs in stuff_after_DEL_END). Raises NoDeletes if
  319. there's no DEL_START found. """
  320. try:
  321. pos = chunks.index(DEL_START)
  322. except ValueError:
  323. raise NoDeletes
  324. pos2 = chunks.index(DEL_END)
  325. return chunks[:pos], chunks[pos+1:pos2], chunks[pos2+1:]
  326. def locate_unbalanced_start(unbalanced_start, pre_delete, post_delete):
  327. """ pre_delete and post_delete implicitly point to a place in the
  328. document (where the two were split). This moves that point (by
  329. popping items from one and pushing them onto the other). It moves
  330. the point to try to find a place where unbalanced_start applies.
  331. As an example::
  332. >>> unbalanced_start = ['<div>']
  333. >>> doc = ['<p>', 'Text', '</p>', '<div>', 'More Text', '</div>']
  334. >>> pre, post = doc[:3], doc[3:]
  335. >>> pre, post
  336. (['<p>', 'Text', '</p>'], ['<div>', 'More Text', '</div>'])
  337. >>> locate_unbalanced_start(unbalanced_start, pre, post)
  338. >>> pre, post
  339. (['<p>', 'Text', '</p>', '<div>'], ['More Text', '</div>'])
  340. As you can see, we moved the point so that the dangling <div> that
  341. we found will be effectively replaced by the div in the original
  342. document. If this doesn't work out, we just throw away
  343. unbalanced_start without doing anything.
  344. """
  345. while 1:
  346. if not unbalanced_start:
  347. # We have totally succeeded in finding the position
  348. break
  349. finding = unbalanced_start[0]
  350. finding_name = finding.split()[0].strip('<>')
  351. if not post_delete:
  352. break
  353. next = post_delete[0]
  354. if next is DEL_START or not next.startswith('<'):
  355. # Reached a word, we can't move the delete text forward
  356. break
  357. if next[1] == '/':
  358. # Reached a closing tag, can we go further? Maybe not...
  359. break
  360. name = next.split()[0].strip('<>')
  361. if name == 'ins':
  362. # Can't move into an insert
  363. break
  364. assert name != 'del', (
  365. "Unexpected delete tag: %r" % next)
  366. if name == finding_name:
  367. unbalanced_start.pop(0)
  368. pre_delete.append(post_delete.pop(0))
  369. else:
  370. # Found a tag that doesn't match
  371. break
  372. def locate_unbalanced_end(unbalanced_end, pre_delete, post_delete):
  373. """ like locate_unbalanced_start, except handling end tags and
  374. possibly moving the point earlier in the document. """
  375. while 1:
  376. if not unbalanced_end:
  377. # Success
  378. break
  379. finding = unbalanced_end[-1]
  380. finding_name = finding.split()[0].strip('<>/')
  381. if not pre_delete:
  382. break
  383. next = pre_delete[-1]
  384. if next is DEL_END or not next.startswith('</'):
  385. # A word or a start tag
  386. break
  387. name = next.split()[0].strip('<>/')
  388. if name == 'ins' or name == 'del':
  389. # Can't move into an insert or delete
  390. break
  391. if name == finding_name:
  392. unbalanced_end.pop()
  393. post_delete.insert(0, pre_delete.pop())
  394. else:
  395. # Found a tag that doesn't match
  396. break
  397. class token(_unicode):
  398. """ Represents a diffable token, generally a word that is displayed to
  399. the user. Opening tags are attached to this token when they are
  400. adjacent (pre_tags) and closing tags that follow the word
  401. (post_tags). Some exceptions occur when there are empty tags
  402. adjacent to a word, so there may be close tags in pre_tags, or
  403. open tags in post_tags.
  404. We also keep track of whether the word was originally followed by
  405. whitespace, even though we do not want to treat the word as
  406. equivalent to a similar word that does not have a trailing
  407. space."""
  408. # When this is true, the token will be eliminated from the
  409. # displayed diff if no change has occurred:
  410. hide_when_equal = False
  411. def __new__(cls, text, pre_tags=None, post_tags=None, trailing_whitespace=""):
  412. obj = _unicode.__new__(cls, text)
  413. if pre_tags is not None:
  414. obj.pre_tags = pre_tags
  415. else:
  416. obj.pre_tags = []
  417. if post_tags is not None:
  418. obj.post_tags = post_tags
  419. else:
  420. obj.post_tags = []
  421. obj.trailing_whitespace = trailing_whitespace
  422. return obj
  423. def __repr__(self):
  424. return 'token(%s, %r, %r, %r)' % (_unicode.__repr__(self), self.pre_tags,
  425. self.post_tags, self.trailing_whitespace)
  426. def html(self):
  427. return _unicode(self)
  428. class tag_token(token):
  429. """ Represents a token that is actually a tag. Currently this is just
  430. the <img> tag, which takes up visible space just like a word but
  431. is only represented in a document by a tag. """
  432. def __new__(cls, tag, data, html_repr, pre_tags=None,
  433. post_tags=None, trailing_whitespace=""):
  434. obj = token.__new__(cls, "%s: %s" % (type, data),
  435. pre_tags=pre_tags,
  436. post_tags=post_tags,
  437. trailing_whitespace=trailing_whitespace)
  438. obj.tag = tag
  439. obj.data = data
  440. obj.html_repr = html_repr
  441. return obj
  442. def __repr__(self):
  443. return 'tag_token(%s, %s, html_repr=%s, post_tags=%r, pre_tags=%r, trailing_whitespace=%r)' % (
  444. self.tag,
  445. self.data,
  446. self.html_repr,
  447. self.pre_tags,
  448. self.post_tags,
  449. self.trailing_whitespace)
  450. def html(self):
  451. return self.html_repr
  452. class href_token(token):
  453. """ Represents the href in an anchor tag. Unlike other words, we only
  454. show the href when it changes. """
  455. hide_when_equal = True
  456. def html(self):
  457. return ' Link: %s' % self
  458. def tokenize(html, include_hrefs=True):
  459. """
  460. Parse the given HTML and returns token objects (words with attached tags).
  461. This parses only the content of a page; anything in the head is
  462. ignored, and the <head> and <body> elements are themselves
  463. optional. The content is then parsed by lxml, which ensures the
  464. validity of the resulting parsed document (though lxml may make
  465. incorrect guesses when the markup is particular bad).
  466. <ins> and <del> tags are also eliminated from the document, as
  467. that gets confusing.
  468. If include_hrefs is true, then the href attribute of <a> tags is
  469. included as a special kind of diffable token."""
  470. if etree.iselement(html):
  471. body_el = html
  472. else:
  473. body_el = parse_html(html, cleanup=True)
  474. # Then we split the document into text chunks for each tag, word, and end tag:
  475. chunks = flatten_el(body_el, skip_tag=True, include_hrefs=include_hrefs)
  476. # Finally re-joining them into token objects:
  477. return fixup_chunks(chunks)
  478. def parse_html(html, cleanup=True):
  479. """
  480. Parses an HTML fragment, returning an lxml element. Note that the HTML will be
  481. wrapped in a <div> tag that was not in the original document.
  482. If cleanup is true, make sure there's no <head> or <body>, and get
  483. rid of any <ins> and <del> tags.
  484. """
  485. if cleanup:
  486. # This removes any extra markup or structure like <head>:
  487. html = cleanup_html(html)
  488. return fragment_fromstring(html, create_parent=True)
  489. _body_re = re.compile(r'<body.*?>', re.I|re.S)
  490. _end_body_re = re.compile(r'</body.*?>', re.I|re.S)
  491. _ins_del_re = re.compile(r'</?(ins|del).*?>', re.I|re.S)
  492. def cleanup_html(html):
  493. """ This 'cleans' the HTML, meaning that any page structure is removed
  494. (only the contents of <body> are used, if there is any <body).
  495. Also <ins> and <del> tags are removed. """
  496. match = _body_re.search(html)
  497. if match:
  498. html = html[match.end():]
  499. match = _end_body_re.search(html)
  500. if match:
  501. html = html[:match.start()]
  502. html = _ins_del_re.sub('', html)
  503. return html
  504. end_whitespace_re = re.compile(r'[ \t\n\r]$')
  505. def split_trailing_whitespace(word):
  506. """
  507. This function takes a word, such as 'test\n\n' and returns ('test','\n\n')
  508. """
  509. stripped_length = len(word.rstrip())
  510. return word[0:stripped_length], word[stripped_length:]
  511. def fixup_chunks(chunks):
  512. """
  513. This function takes a list of chunks and produces a list of tokens.
  514. """
  515. tag_accum = []
  516. cur_word = None
  517. result = []
  518. for chunk in chunks:
  519. if isinstance(chunk, tuple):
  520. if chunk[0] == 'img':
  521. src = chunk[1]
  522. tag, trailing_whitespace = split_trailing_whitespace(chunk[2])
  523. cur_word = tag_token('img', src, html_repr=tag,
  524. pre_tags=tag_accum,
  525. trailing_whitespace=trailing_whitespace)
  526. tag_accum = []
  527. result.append(cur_word)
  528. elif chunk[0] == 'href':
  529. href = chunk[1]
  530. cur_word = href_token(href, pre_tags=tag_accum, trailing_whitespace=" ")
  531. tag_accum = []
  532. result.append(cur_word)
  533. continue
  534. if is_word(chunk):
  535. chunk, trailing_whitespace = split_trailing_whitespace(chunk)
  536. cur_word = token(chunk, pre_tags=tag_accum, trailing_whitespace=trailing_whitespace)
  537. tag_accum = []
  538. result.append(cur_word)
  539. elif is_start_tag(chunk):
  540. tag_accum.append(chunk)
  541. elif is_end_tag(chunk):
  542. if tag_accum:
  543. tag_accum.append(chunk)
  544. else:
  545. assert cur_word, (
  546. "Weird state, cur_word=%r, result=%r, chunks=%r of %r"
  547. % (cur_word, result, chunk, chunks))
  548. cur_word.post_tags.append(chunk)
  549. else:
  550. assert(0)
  551. if not result:
  552. return [token('', pre_tags=tag_accum)]
  553. else:
  554. result[-1].post_tags.extend(tag_accum)
  555. return result
  556. # All the tags in HTML that don't require end tags:
  557. empty_tags = (
  558. 'param', 'img', 'area', 'br', 'basefont', 'input',
  559. 'base', 'meta', 'link', 'col')
  560. block_level_tags = (
  561. 'address',
  562. 'blockquote',
  563. 'center',
  564. 'dir',
  565. 'div',
  566. 'dl',
  567. 'fieldset',
  568. 'form',
  569. 'h1',
  570. 'h2',
  571. 'h3',
  572. 'h4',
  573. 'h5',
  574. 'h6',
  575. 'hr',
  576. 'isindex',
  577. 'menu',
  578. 'noframes',
  579. 'noscript',
  580. 'ol',
  581. 'p',
  582. 'pre',
  583. 'table',
  584. 'ul',
  585. )
  586. block_level_container_tags = (
  587. 'dd',
  588. 'dt',
  589. 'frameset',
  590. 'li',
  591. 'tbody',
  592. 'td',
  593. 'tfoot',
  594. 'th',
  595. 'thead',
  596. 'tr',
  597. )
  598. def flatten_el(el, include_hrefs, skip_tag=False):
  599. """ Takes an lxml element el, and generates all the text chunks for
  600. that tag. Each start tag is a chunk, each word is a chunk, and each
  601. end tag is a chunk.
  602. If skip_tag is true, then the outermost container tag is
  603. not returned (just its contents)."""
  604. if not skip_tag:
  605. if el.tag == 'img':
  606. yield ('img', el.get('src'), start_tag(el))
  607. else:
  608. yield start_tag(el)
  609. if el.tag in empty_tags and not el.text and not len(el) and not el.tail:
  610. return
  611. start_words = split_words(el.text)
  612. for word in start_words:
  613. yield html_escape(word)
  614. for child in el:
  615. for item in flatten_el(child, include_hrefs=include_hrefs):
  616. yield item
  617. if el.tag == 'a' and el.get('href') and include_hrefs:
  618. yield ('href', el.get('href'))
  619. if not skip_tag:
  620. yield end_tag(el)
  621. end_words = split_words(el.tail)
  622. for word in end_words:
  623. yield html_escape(word)
  624. split_words_re = re.compile(r'\S+(?:\s+|$)', re.U)
  625. def split_words(text):
  626. """ Splits some text into words. Includes trailing whitespace
  627. on each word when appropriate. """
  628. if not text or not text.strip():
  629. return []
  630. words = split_words_re.findall(text)
  631. return words
  632. start_whitespace_re = re.compile(r'^[ \t\n\r]')
  633. def start_tag(el):
  634. """
  635. The text representation of the start tag for a tag.
  636. """
  637. return '<%s%s>' % (
  638. el.tag, ''.join([' %s="%s"' % (name, html_escape(value, True))
  639. for name, value in el.attrib.items()]))
  640. def end_tag(el):
  641. """ The text representation of an end tag for a tag. Includes
  642. trailing whitespace when appropriate. """
  643. if el.tail and start_whitespace_re.search(el.tail):
  644. extra = ' '
  645. else:
  646. extra = ''
  647. return '</%s>%s' % (el.tag, extra)
  648. def is_word(tok):
  649. return not tok.startswith('<')
  650. def is_end_tag(tok):
  651. return tok.startswith('</')
  652. def is_start_tag(tok):
  653. return tok.startswith('<') and not tok.startswith('</')
  654. def fixup_ins_del_tags(html):
  655. """ Given an html string, move any <ins> or <del> tags inside of any
  656. block-level elements, e.g. transform <ins><p>word</p></ins> to
  657. <p><ins>word</ins></p> """
  658. doc = parse_html(html, cleanup=False)
  659. _fixup_ins_del_tags(doc)
  660. html = serialize_html_fragment(doc, skip_outer=True)
  661. return html
  662. def serialize_html_fragment(el, skip_outer=False):
  663. """ Serialize a single lxml element as HTML. The serialized form
  664. includes the elements tail.
  665. If skip_outer is true, then don't serialize the outermost tag
  666. """
  667. assert not isinstance(el, basestring), (
  668. "You should pass in an element, not a string like %r" % el)
  669. html = etree.tostring(el, method="html", encoding=_unicode)
  670. if skip_outer:
  671. # Get rid of the extra starting tag:
  672. html = html[html.find('>')+1:]
  673. # Get rid of the extra end tag:
  674. html = html[:html.rfind('<')]
  675. return html.strip()
  676. else:
  677. return html
  678. def _fixup_ins_del_tags(doc):
  679. """fixup_ins_del_tags that works on an lxml document in-place
  680. """
  681. for tag in ['ins', 'del']:
  682. for el in doc.xpath('descendant-or-self::%s' % tag):
  683. if not _contains_block_level_tag(el):
  684. continue
  685. _move_el_inside_block(el, tag=tag)
  686. el.drop_tag()
  687. #_merge_element_contents(el)
  688. def _contains_block_level_tag(el):
  689. """True if the element contains any block-level elements, like <p>, <td>, etc.
  690. """
  691. if el.tag in block_level_tags or el.tag in block_level_container_tags:
  692. return True
  693. for child in el:
  694. if _contains_block_level_tag(child):
  695. return True
  696. return False
  697. def _move_el_inside_block(el, tag):
  698. """ helper for _fixup_ins_del_tags; actually takes the <ins> etc tags
  699. and moves them inside any block-level tags. """
  700. for child in el:
  701. if _contains_block_level_tag(child):
  702. break
  703. else:
  704. import sys
  705. # No block-level tags in any child
  706. children_tag = etree.Element(tag)
  707. children_tag.text = el.text
  708. el.text = None
  709. children_tag.extend(list(el))
  710. el[:] = [children_tag]
  711. return
  712. for child in list(el):
  713. if _contains_block_level_tag(child):
  714. _move_el_inside_block(child, tag)
  715. if child.tail:
  716. tail_tag = etree.Element(tag)
  717. tail_tag.text = child.tail
  718. child.tail = None
  719. el.insert(el.index(child)+1, tail_tag)
  720. else:
  721. child_tag = etree.Element(tag)
  722. el.replace(child, child_tag)
  723. child_tag.append(child)
  724. if el.text:
  725. text_tag = etree.Element(tag)
  726. text_tag.text = el.text
  727. el.text = None
  728. el.insert(0, text_tag)
  729. def _merge_element_contents(el):
  730. """
  731. Removes an element, but merges its contents into its place, e.g.,
  732. given <p>Hi <i>there!</i></p>, if you remove the <i> element you get
  733. <p>Hi there!</p>
  734. """
  735. parent = el.getparent()
  736. text = el.text or ''
  737. if el.tail:
  738. if not len(el):
  739. text += el.tail
  740. else:
  741. if el[-1].tail:
  742. el[-1].tail += el.tail
  743. else:
  744. el[-1].tail = el.tail
  745. index = parent.index(el)
  746. if text:
  747. if index == 0:
  748. previous = None
  749. else:
  750. previous = parent[index-1]
  751. if previous is None:
  752. if parent.text:
  753. parent.text += text
  754. else:
  755. parent.text = text
  756. else:
  757. if previous.tail:
  758. previous.tail += text
  759. else:
  760. previous.tail = text
  761. parent[index:index+1] = el.getchildren()
  762. class InsensitiveSequenceMatcher(difflib.SequenceMatcher):
  763. """
  764. Acts like SequenceMatcher, but tries not to find very small equal
  765. blocks amidst large spans of changes
  766. """
  767. threshold = 2
  768. def get_matching_blocks(self):
  769. size = min(len(self.b), len(self.b))
  770. threshold = min(self.threshold, size / 4)
  771. actual = difflib.SequenceMatcher.get_matching_blocks(self)
  772. return [item for item in actual
  773. if item[2] > threshold
  774. or not item[2]]
  775. if __name__ == '__main__':
  776. from lxml.html import _diffcommand
  777. _diffcommand.main()