blob: e31259abf9621d6fd5f3d6b8c1acc8f9c7c0bbd6 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Tim Peters9ae21482001-02-10 08:00:53 +00002
3"""
4Module difflib -- helpers for computing deltas between objects.
5
6Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
Tim Peters9ae21482001-02-10 08:00:53 +00007 Use SequenceMatcher to return list of the best "good enough" matches.
8
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00009Function context_diff(a, b):
10 For two lists of strings, return a delta in context diff format.
11
Tim Peters5e824c32001-08-12 22:25:01 +000012Function ndiff(a, b):
13 Return a delta: the difference between `a` and `b` (lists of strings).
Tim Peters9ae21482001-02-10 08:00:53 +000014
Tim Peters5e824c32001-08-12 22:25:01 +000015Function restore(delta, which):
16 Return one of the two sequences that generated an ndiff delta.
Tim Peters9ae21482001-02-10 08:00:53 +000017
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000018Function unified_diff(a, b):
19 For two lists of strings, return a delta in unified diff format.
20
Tim Peters5e824c32001-08-12 22:25:01 +000021Class SequenceMatcher:
22 A flexible class for comparing pairs of sequences of any type.
Tim Peters9ae21482001-02-10 08:00:53 +000023
Tim Peters5e824c32001-08-12 22:25:01 +000024Class Differ:
25 For producing human-readable deltas from sequences of lines of text.
Martin v. Löwise064b412004-08-29 16:34:40 +000026
27Class HtmlDiff:
28 For producing HTML side by side comparison with change highlights.
Tim Peters9ae21482001-02-10 08:00:53 +000029"""
30
Tim Peters5e824c32001-08-12 22:25:01 +000031__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000032 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
Christian Heimes25bb7832008-01-11 16:17:00 +000033 'unified_diff', 'HtmlDiff', 'Match']
Tim Peters5e824c32001-08-12 22:25:01 +000034
Raymond Hettingerbb6b7342004-06-13 09:57:33 +000035import heapq
Christian Heimes25bb7832008-01-11 16:17:00 +000036from collections import namedtuple as _namedtuple
37
38Match = _namedtuple('Match', 'a b size')
Raymond Hettingerbb6b7342004-06-13 09:57:33 +000039
Neal Norwitze7dfe212003-07-01 14:59:46 +000040def _calculate_ratio(matches, length):
41 if length:
42 return 2.0 * matches / length
43 return 1.0
44
Tim Peters9ae21482001-02-10 08:00:53 +000045class SequenceMatcher:
Tim Peters5e824c32001-08-12 22:25:01 +000046
47 """
48 SequenceMatcher is a flexible class for comparing pairs of sequences of
49 any type, so long as the sequence elements are hashable. The basic
50 algorithm predates, and is a little fancier than, an algorithm
51 published in the late 1980's by Ratcliff and Obershelp under the
52 hyperbolic name "gestalt pattern matching". The basic idea is to find
53 the longest contiguous matching subsequence that contains no "junk"
54 elements (R-O doesn't address junk). The same idea is then applied
55 recursively to the pieces of the sequences to the left and to the right
56 of the matching subsequence. This does not yield minimal edit
57 sequences, but does tend to yield matches that "look right" to people.
58
59 SequenceMatcher tries to compute a "human-friendly diff" between two
60 sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
61 longest *contiguous* & junk-free matching subsequence. That's what
62 catches peoples' eyes. The Windows(tm) windiff has another interesting
63 notion, pairing up elements that appear uniquely in each sequence.
64 That, and the method here, appear to yield more intuitive difference
65 reports than does diff. This method appears to be the least vulnerable
66 to synching up on blocks of "junk lines", though (like blank lines in
67 ordinary text files, or maybe "<P>" lines in HTML files). That may be
68 because this is the only method of the 3 that has a *concept* of
69 "junk" <wink>.
70
71 Example, comparing two strings, and considering blanks to be "junk":
72
73 >>> s = SequenceMatcher(lambda x: x == " ",
74 ... "private Thread currentThread;",
75 ... "private volatile Thread currentThread;")
76 >>>
77
78 .ratio() returns a float in [0, 1], measuring the "similarity" of the
79 sequences. As a rule of thumb, a .ratio() value over 0.6 means the
80 sequences are close matches:
81
Guido van Rossumfff80df2007-02-09 20:33:44 +000082 >>> print(round(s.ratio(), 3))
Tim Peters5e824c32001-08-12 22:25:01 +000083 0.866
84 >>>
85
86 If you're only interested in where the sequences match,
87 .get_matching_blocks() is handy:
88
89 >>> for block in s.get_matching_blocks():
Guido van Rossumfff80df2007-02-09 20:33:44 +000090 ... print("a[%d] and b[%d] match for %d elements" % block)
Tim Peters5e824c32001-08-12 22:25:01 +000091 a[0] and b[0] match for 8 elements
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092 a[8] and b[17] match for 21 elements
Tim Peters5e824c32001-08-12 22:25:01 +000093 a[29] and b[38] match for 0 elements
94
95 Note that the last tuple returned by .get_matching_blocks() is always a
96 dummy, (len(a), len(b), 0), and this is the only case in which the last
97 tuple element (number of elements matched) is 0.
98
99 If you want to know how to change the first sequence into the second,
100 use .get_opcodes():
101
102 >>> for opcode in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000103 ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
Tim Peters5e824c32001-08-12 22:25:01 +0000104 equal a[0:8] b[0:8]
105 insert a[8:8] b[8:17]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106 equal a[8:29] b[17:38]
Tim Peters5e824c32001-08-12 22:25:01 +0000107
108 See the Differ class for a fancy human-friendly file differencer, which
109 uses SequenceMatcher both to compare sequences of lines, and to compare
110 sequences of characters within similar (near-matching) lines.
111
112 See also function get_close_matches() in this module, which shows how
113 simple code building on SequenceMatcher can be used to do useful work.
114
115 Timing: Basic R-O is cubic time worst case and quadratic time expected
116 case. SequenceMatcher is quadratic time for the worst case and has
117 expected-case behavior dependent in a complicated way on how many
118 elements the sequences have in common; best case time is linear.
119
120 Methods:
121
122 __init__(isjunk=None, a='', b='')
123 Construct a SequenceMatcher.
124
125 set_seqs(a, b)
126 Set the two sequences to be compared.
127
128 set_seq1(a)
129 Set the first sequence to be compared.
130
131 set_seq2(b)
132 Set the second sequence to be compared.
133
134 find_longest_match(alo, ahi, blo, bhi)
135 Find longest matching block in a[alo:ahi] and b[blo:bhi].
136
137 get_matching_blocks()
138 Return list of triples describing matching subsequences.
139
140 get_opcodes()
141 Return list of 5-tuples describing how to turn a into b.
142
143 ratio()
144 Return a measure of the sequences' similarity (float in [0,1]).
145
146 quick_ratio()
147 Return an upper bound on .ratio() relatively quickly.
148
149 real_quick_ratio()
150 Return an upper bound on ratio() very quickly.
151 """
152
Terry Reedy99f96372010-11-25 06:12:34 +0000153 def __init__(self, isjunk=None, a='', b='', autojunk=True):
Tim Peters9ae21482001-02-10 08:00:53 +0000154 """Construct a SequenceMatcher.
155
156 Optional arg isjunk is None (the default), or a one-argument
157 function that takes a sequence element and returns true iff the
Tim Peters5e824c32001-08-12 22:25:01 +0000158 element is junk. None is equivalent to passing "lambda x: 0", i.e.
Fred Drakef1da6282001-02-19 19:30:05 +0000159 no elements are considered to be junk. For example, pass
Tim Peters9ae21482001-02-10 08:00:53 +0000160 lambda x: x in " \\t"
161 if you're comparing lines as sequences of characters, and don't
162 want to synch up on blanks or hard tabs.
163
164 Optional arg a is the first of two sequences to be compared. By
165 default, an empty string. The elements of a must be hashable. See
166 also .set_seqs() and .set_seq1().
167
168 Optional arg b is the second of two sequences to be compared. By
Fred Drakef1da6282001-02-19 19:30:05 +0000169 default, an empty string. The elements of b must be hashable. See
Tim Peters9ae21482001-02-10 08:00:53 +0000170 also .set_seqs() and .set_seq2().
Terry Reedy99f96372010-11-25 06:12:34 +0000171
172 Optional arg autojunk should be set to False to disable the
173 "automatic junk heuristic" that treats popular elements as junk
174 (see module documentation for more information).
Tim Peters9ae21482001-02-10 08:00:53 +0000175 """
176
177 # Members:
178 # a
179 # first sequence
180 # b
181 # second sequence; differences are computed as "what do
182 # we need to do to 'a' to change it into 'b'?"
183 # b2j
184 # for x in b, b2j[x] is a list of the indices (into b)
185 # at which x appears; junk elements do not appear
Tim Peters9ae21482001-02-10 08:00:53 +0000186 # fullbcount
187 # for x in b, fullbcount[x] == the number of times x
188 # appears in b; only materialized if really needed (used
189 # only for computing quick_ratio())
190 # matching_blocks
191 # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
192 # ascending & non-overlapping in i and in j; terminated by
193 # a dummy (len(a), len(b), 0) sentinel
194 # opcodes
195 # a list of (tag, i1, i2, j1, j2) tuples, where tag is
196 # one of
197 # 'replace' a[i1:i2] should be replaced by b[j1:j2]
198 # 'delete' a[i1:i2] should be deleted
199 # 'insert' b[j1:j2] should be inserted
200 # 'equal' a[i1:i2] == b[j1:j2]
201 # isjunk
202 # a user-supplied function taking a sequence element and
203 # returning true iff the element is "junk" -- this has
204 # subtle but helpful effects on the algorithm, which I'll
205 # get around to writing up someday <0.9 wink>.
206 # DON'T USE! Only __chain_b uses this. Use isbjunk.
207 # isbjunk
208 # for x in b, isbjunk(x) == isjunk(x) but much faster;
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000209 # it's really the __contains__ method of a hidden dict.
Tim Peters9ae21482001-02-10 08:00:53 +0000210 # DOES NOT WORK for x in a!
Tim Peters81b92512002-04-29 01:37:32 +0000211 # isbpopular
212 # for x in b, isbpopular(x) is true iff b is reasonably long
Terry Reedy99f96372010-11-25 06:12:34 +0000213 # (at least 200 elements) and x accounts for more than 1 + 1% of
214 # its elements (when autojunk is enabled).
215 # DOES NOT WORK for x in a!
Terry Reedy74a7c672010-12-03 18:57:42 +0000216 # bjunk
217 # the items in b for which isjunk is True.
218 # bpopular
219 # nonjunk items in b treated as junk by the heuristic (if used).
Tim Peters9ae21482001-02-10 08:00:53 +0000220
221 self.isjunk = isjunk
222 self.a = self.b = None
Terry Reedy99f96372010-11-25 06:12:34 +0000223 self.autojunk = autojunk
Tim Peters9ae21482001-02-10 08:00:53 +0000224 self.set_seqs(a, b)
225
226 def set_seqs(self, a, b):
227 """Set the two sequences to be compared.
228
229 >>> s = SequenceMatcher()
230 >>> s.set_seqs("abcd", "bcde")
231 >>> s.ratio()
232 0.75
233 """
234
235 self.set_seq1(a)
236 self.set_seq2(b)
237
238 def set_seq1(self, a):
239 """Set the first sequence to be compared.
240
241 The second sequence to be compared is not changed.
242
243 >>> s = SequenceMatcher(None, "abcd", "bcde")
244 >>> s.ratio()
245 0.75
246 >>> s.set_seq1("bcde")
247 >>> s.ratio()
248 1.0
249 >>>
250
251 SequenceMatcher computes and caches detailed information about the
252 second sequence, so if you want to compare one sequence S against
253 many sequences, use .set_seq2(S) once and call .set_seq1(x)
254 repeatedly for each of the other sequences.
255
256 See also set_seqs() and set_seq2().
257 """
258
259 if a is self.a:
260 return
261 self.a = a
262 self.matching_blocks = self.opcodes = None
263
264 def set_seq2(self, b):
265 """Set the second sequence to be compared.
266
267 The first sequence to be compared is not changed.
268
269 >>> s = SequenceMatcher(None, "abcd", "bcde")
270 >>> s.ratio()
271 0.75
272 >>> s.set_seq2("abcd")
273 >>> s.ratio()
274 1.0
275 >>>
276
277 SequenceMatcher computes and caches detailed information about the
278 second sequence, so if you want to compare one sequence S against
279 many sequences, use .set_seq2(S) once and call .set_seq1(x)
280 repeatedly for each of the other sequences.
281
282 See also set_seqs() and set_seq1().
283 """
284
285 if b is self.b:
286 return
287 self.b = b
288 self.matching_blocks = self.opcodes = None
289 self.fullbcount = None
290 self.__chain_b()
291
292 # For each element x in b, set b2j[x] to a list of the indices in
293 # b where x appears; the indices are in increasing order; note that
294 # the number of times x appears in b is len(b2j[x]) ...
295 # when self.isjunk is defined, junk elements don't show up in this
296 # map at all, which stops the central find_longest_match method
297 # from starting any matching block at a junk element ...
298 # also creates the fast isbjunk function ...
Tim Peters81b92512002-04-29 01:37:32 +0000299 # b2j also does not contain entries for "popular" elements, meaning
Terry Reedy99f96372010-11-25 06:12:34 +0000300 # elements that account for more than 1 + 1% of the total elements, and
Tim Peters81b92512002-04-29 01:37:32 +0000301 # when the sequence is reasonably large (>= 200 elements); this can
302 # be viewed as an adaptive notion of semi-junk, and yields an enormous
303 # speedup when, e.g., comparing program files with hundreds of
304 # instances of "return NULL;" ...
Tim Peters9ae21482001-02-10 08:00:53 +0000305 # note that this is only called when b changes; so for cross-product
306 # kinds of matches, it's best to call set_seq2 once, then set_seq1
307 # repeatedly
308
309 def __chain_b(self):
310 # Because isjunk is a user-defined (not C) function, and we test
311 # for junk a LOT, it's important to minimize the number of calls.
312 # Before the tricks described here, __chain_b was by far the most
313 # time-consuming routine in the whole module! If anyone sees
314 # Jim Roskind, thank him again for profile.py -- I never would
315 # have guessed that.
316 # The first trick is to build b2j ignoring the possibility
317 # of junk. I.e., we don't call isjunk at all yet. Throwing
318 # out the junk later is much cheaper than building b2j "right"
319 # from the start.
320 b = self.b
321 self.b2j = b2j = {}
Terry Reedy99f96372010-11-25 06:12:34 +0000322
Tim Peters81b92512002-04-29 01:37:32 +0000323 for i, elt in enumerate(b):
Terry Reedy99f96372010-11-25 06:12:34 +0000324 indices = b2j.setdefault(elt, [])
325 indices.append(i)
Tim Peters9ae21482001-02-10 08:00:53 +0000326
Terry Reedy99f96372010-11-25 06:12:34 +0000327 # Purge junk elements
Terry Reedy74a7c672010-12-03 18:57:42 +0000328 self.bjunk = junk = set()
Tim Peters81b92512002-04-29 01:37:32 +0000329 isjunk = self.isjunk
Tim Peters9ae21482001-02-10 08:00:53 +0000330 if isjunk:
Terry Reedy99f96372010-11-25 06:12:34 +0000331 for elt in list(b2j.keys()): # using list() since b2j is modified
332 if isjunk(elt):
333 junk.add(elt)
334 del b2j[elt]
Tim Peters9ae21482001-02-10 08:00:53 +0000335
Terry Reedy99f96372010-11-25 06:12:34 +0000336 # Purge popular elements that are not junk
Terry Reedy74a7c672010-12-03 18:57:42 +0000337 self.bpopular = popular = set()
Terry Reedy99f96372010-11-25 06:12:34 +0000338 n = len(b)
339 if self.autojunk and n >= 200:
340 ntest = n // 100 + 1
341 for elt, idxs in list(b2j.items()):
342 if len(idxs) > ntest:
343 popular.add(elt)
344 del b2j[elt]
345
346 # Now for x in b, isjunk(x) == x in junk, but the latter is much faster.
347 # Since the number of *unique* junk elements is probably small, the
348 # memory burden of keeping this set alive is likely trivial compared to
349 # the size of b2j.
350 self.isbjunk = junk.__contains__
351 self.isbpopular = popular.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000352
353 def find_longest_match(self, alo, ahi, blo, bhi):
354 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
355
356 If isjunk is not defined:
357
358 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
359 alo <= i <= i+k <= ahi
360 blo <= j <= j+k <= bhi
361 and for all (i',j',k') meeting those conditions,
362 k >= k'
363 i <= i'
364 and if i == i', j <= j'
365
366 In other words, of all maximal matching blocks, return one that
367 starts earliest in a, and of all those maximal matching blocks that
368 start earliest in a, return the one that starts earliest in b.
369
370 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
371 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000372 Match(a=0, b=4, size=5)
Tim Peters9ae21482001-02-10 08:00:53 +0000373
374 If isjunk is defined, first the longest matching block is
375 determined as above, but with the additional restriction that no
376 junk element appears in the block. Then that block is extended as
377 far as possible by matching (only) junk elements on both sides. So
378 the resulting block never matches on junk except as identical junk
379 happens to be adjacent to an "interesting" match.
380
381 Here's the same example as before, but considering blanks to be
382 junk. That prevents " abcd" from matching the " abcd" at the tail
383 end of the second sequence directly. Instead only the "abcd" can
384 match, and matches the leftmost "abcd" in the second sequence:
385
386 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
387 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000388 Match(a=1, b=0, size=4)
Tim Peters9ae21482001-02-10 08:00:53 +0000389
390 If no blocks match, return (alo, blo, 0).
391
392 >>> s = SequenceMatcher(None, "ab", "c")
393 >>> s.find_longest_match(0, 2, 0, 1)
Christian Heimes25bb7832008-01-11 16:17:00 +0000394 Match(a=0, b=0, size=0)
Tim Peters9ae21482001-02-10 08:00:53 +0000395 """
396
397 # CAUTION: stripping common prefix or suffix would be incorrect.
398 # E.g.,
399 # ab
400 # acab
401 # Longest matching block is "ab", but if common prefix is
402 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
403 # strip, so ends up claiming that ab is changed to acab by
404 # inserting "ca" in the middle. That's minimal but unintuitive:
405 # "it's obvious" that someone inserted "ac" at the front.
406 # Windiff ends up at the same place as diff, but by pairing up
407 # the unique 'b's and then matching the first two 'a's.
408
409 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
410 besti, bestj, bestsize = alo, blo, 0
411 # find longest junk-free match
412 # during an iteration of the loop, j2len[j] = length of longest
413 # junk-free match ending with a[i-1] and b[j]
414 j2len = {}
415 nothing = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000416 for i in range(alo, ahi):
Tim Peters9ae21482001-02-10 08:00:53 +0000417 # look at all instances of a[i] in b; note that because
418 # b2j has no junk keys, the loop is skipped if a[i] is junk
419 j2lenget = j2len.get
420 newj2len = {}
421 for j in b2j.get(a[i], nothing):
422 # a[i] matches b[j]
423 if j < blo:
424 continue
425 if j >= bhi:
426 break
427 k = newj2len[j] = j2lenget(j-1, 0) + 1
428 if k > bestsize:
429 besti, bestj, bestsize = i-k+1, j-k+1, k
430 j2len = newj2len
431
Tim Peters81b92512002-04-29 01:37:32 +0000432 # Extend the best by non-junk elements on each end. In particular,
433 # "popular" non-junk elements aren't in b2j, which greatly speeds
434 # the inner loop above, but also means "the best" match so far
435 # doesn't contain any junk *or* popular non-junk elements.
436 while besti > alo and bestj > blo and \
437 not isbjunk(b[bestj-1]) and \
438 a[besti-1] == b[bestj-1]:
439 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
440 while besti+bestsize < ahi and bestj+bestsize < bhi and \
441 not isbjunk(b[bestj+bestsize]) and \
442 a[besti+bestsize] == b[bestj+bestsize]:
443 bestsize += 1
444
Tim Peters9ae21482001-02-10 08:00:53 +0000445 # Now that we have a wholly interesting match (albeit possibly
446 # empty!), we may as well suck up the matching junk on each
447 # side of it too. Can't think of a good reason not to, and it
448 # saves post-processing the (possibly considerable) expense of
449 # figuring out what to do with it. In the case of an empty
450 # interesting match, this is clearly the right thing to do,
451 # because no other kind of match is possible in the regions.
452 while besti > alo and bestj > blo and \
453 isbjunk(b[bestj-1]) and \
454 a[besti-1] == b[bestj-1]:
455 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
456 while besti+bestsize < ahi and bestj+bestsize < bhi and \
457 isbjunk(b[bestj+bestsize]) and \
458 a[besti+bestsize] == b[bestj+bestsize]:
459 bestsize = bestsize + 1
460
Christian Heimes25bb7832008-01-11 16:17:00 +0000461 return Match(besti, bestj, bestsize)
Tim Peters9ae21482001-02-10 08:00:53 +0000462
463 def get_matching_blocks(self):
464 """Return list of triples describing matching subsequences.
465
466 Each triple is of the form (i, j, n), and means that
467 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000468 i and in j. New in Python 2.5, it's also guaranteed that if
469 (i, j, n) and (i', j', n') are adjacent triples in the list, and
470 the second is not the last triple in the list, then i+n != i' or
471 j+n != j'. IOW, adjacent triples never describe adjacent equal
472 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000473
474 The last triple is a dummy, (len(a), len(b), 0), and is the only
475 triple with n==0.
476
477 >>> s = SequenceMatcher(None, "abxcd", "abcd")
Christian Heimes25bb7832008-01-11 16:17:00 +0000478 >>> list(s.get_matching_blocks())
479 [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
Tim Peters9ae21482001-02-10 08:00:53 +0000480 """
481
482 if self.matching_blocks is not None:
483 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000484 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000485
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000486 # This is most naturally expressed as a recursive algorithm, but
487 # at least one user bumped into extreme use cases that exceeded
488 # the recursion limit on their box. So, now we maintain a list
489 # ('queue`) of blocks we still need to look at, and append partial
490 # results to `matching_blocks` in a loop; the matches are sorted
491 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000492 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000493 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000494 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000495 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000496 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000497 # a[alo:i] vs b[blo:j] unknown
498 # a[i:i+k] same as b[j:j+k]
499 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000500 if k: # if k is 0, there was no matching block
501 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000502 if alo < i and blo < j:
503 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000504 if i+k < ahi and j+k < bhi:
505 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000507
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000508 # It's possible that we have adjacent equal blocks in the
509 # matching_blocks list now. Starting with 2.5, this code was added
510 # to collapse them.
511 i1 = j1 = k1 = 0
512 non_adjacent = []
513 for i2, j2, k2 in matching_blocks:
514 # Is this block adjacent to i1, j1, k1?
515 if i1 + k1 == i2 and j1 + k1 == j2:
516 # Yes, so collapse them -- this just increases the length of
517 # the first block by the length of the second, and the first
518 # block so lengthened remains the block to compare against.
519 k1 += k2
520 else:
521 # Not adjacent. Remember the first block (k1==0 means it's
522 # the dummy we started with), and make the second block the
523 # new block to compare against.
524 if k1:
525 non_adjacent.append((i1, j1, k1))
526 i1, j1, k1 = i2, j2, k2
527 if k1:
528 non_adjacent.append((i1, j1, k1))
529
530 non_adjacent.append( (la, lb, 0) )
531 self.matching_blocks = non_adjacent
Christian Heimes25bb7832008-01-11 16:17:00 +0000532 return map(Match._make, self.matching_blocks)
Tim Peters9ae21482001-02-10 08:00:53 +0000533
Tim Peters9ae21482001-02-10 08:00:53 +0000534 def get_opcodes(self):
535 """Return list of 5-tuples describing how to turn a into b.
536
537 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
538 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
539 tuple preceding it, and likewise for j1 == the previous j2.
540
541 The tags are strings, with these meanings:
542
543 'replace': a[i1:i2] should be replaced by b[j1:j2]
544 'delete': a[i1:i2] should be deleted.
545 Note that j1==j2 in this case.
546 'insert': b[j1:j2] should be inserted at a[i1:i1].
547 Note that i1==i2 in this case.
548 'equal': a[i1:i2] == b[j1:j2]
549
550 >>> a = "qabxcd"
551 >>> b = "abycdf"
552 >>> s = SequenceMatcher(None, a, b)
553 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000554 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
555 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000556 delete a[0:1] (q) b[0:0] ()
557 equal a[1:3] (ab) b[0:2] (ab)
558 replace a[3:4] (x) b[2:3] (y)
559 equal a[4:6] (cd) b[3:5] (cd)
560 insert a[6:6] () b[5:6] (f)
561 """
562
563 if self.opcodes is not None:
564 return self.opcodes
565 i = j = 0
566 self.opcodes = answer = []
567 for ai, bj, size in self.get_matching_blocks():
568 # invariant: we've pumped out correct diffs to change
569 # a[:i] into b[:j], and the next matching block is
570 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
571 # out a diff to change a[i:ai] into b[j:bj], pump out
572 # the matching block, and move (i,j) beyond the match
573 tag = ''
574 if i < ai and j < bj:
575 tag = 'replace'
576 elif i < ai:
577 tag = 'delete'
578 elif j < bj:
579 tag = 'insert'
580 if tag:
581 answer.append( (tag, i, ai, j, bj) )
582 i, j = ai+size, bj+size
583 # the list of matching blocks is terminated by a
584 # sentinel with size 0
585 if size:
586 answer.append( ('equal', ai, i, bj, j) )
587 return answer
588
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000589 def get_grouped_opcodes(self, n=3):
590 """ Isolate change clusters by eliminating ranges with no changes.
591
592 Return a generator of groups with upto n lines of context.
593 Each group is in the same format as returned by get_opcodes().
594
595 >>> from pprint import pprint
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000596 >>> a = list(map(str, range(1,40)))
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000597 >>> b = a[:]
598 >>> b[8:8] = ['i'] # Make an insertion
599 >>> b[20] += 'x' # Make a replacement
600 >>> b[23:28] = [] # Make a deletion
601 >>> b[30] += 'y' # Make another replacement
602 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
603 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
604 [('equal', 16, 19, 17, 20),
605 ('replace', 19, 20, 20, 21),
606 ('equal', 20, 22, 21, 23),
607 ('delete', 22, 27, 23, 23),
608 ('equal', 27, 30, 23, 26)],
609 [('equal', 31, 34, 27, 30),
610 ('replace', 34, 35, 30, 31),
611 ('equal', 35, 38, 31, 34)]]
612 """
613
614 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000615 if not codes:
616 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000617 # Fixup leading and trailing groups if they show no changes.
618 if codes[0][0] == 'equal':
619 tag, i1, i2, j1, j2 = codes[0]
620 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
621 if codes[-1][0] == 'equal':
622 tag, i1, i2, j1, j2 = codes[-1]
623 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
624
625 nn = n + n
626 group = []
627 for tag, i1, i2, j1, j2 in codes:
628 # End the current group and start a new one whenever
629 # there is a large range with no changes.
630 if tag == 'equal' and i2-i1 > nn:
631 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
632 yield group
633 group = []
634 i1, j1 = max(i1, i2-n), max(j1, j2-n)
635 group.append((tag, i1, i2, j1 ,j2))
636 if group and not (len(group)==1 and group[0][0] == 'equal'):
637 yield group
638
Tim Peters9ae21482001-02-10 08:00:53 +0000639 def ratio(self):
640 """Return a measure of the sequences' similarity (float in [0,1]).
641
642 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000643 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000644 Note that this is 1 if the sequences are identical, and 0 if
645 they have nothing in common.
646
647 .ratio() is expensive to compute if you haven't already computed
648 .get_matching_blocks() or .get_opcodes(), in which case you may
649 want to try .quick_ratio() or .real_quick_ratio() first to get an
650 upper bound.
651
652 >>> s = SequenceMatcher(None, "abcd", "bcde")
653 >>> s.ratio()
654 0.75
655 >>> s.quick_ratio()
656 0.75
657 >>> s.real_quick_ratio()
658 1.0
659 """
660
Guido van Rossum89da5d72006-08-22 00:21:25 +0000661 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000662 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000663
664 def quick_ratio(self):
665 """Return an upper bound on ratio() relatively quickly.
666
667 This isn't defined beyond that it is an upper bound on .ratio(), and
668 is faster to compute.
669 """
670
671 # viewing a and b as multisets, set matches to the cardinality
672 # of their intersection; this counts the number of matches
673 # without regard to order, so is clearly an upper bound
674 if self.fullbcount is None:
675 self.fullbcount = fullbcount = {}
676 for elt in self.b:
677 fullbcount[elt] = fullbcount.get(elt, 0) + 1
678 fullbcount = self.fullbcount
679 # avail[x] is the number of times x appears in 'b' less the
680 # number of times we've seen it in 'a' so far ... kinda
681 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000682 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000683 for elt in self.a:
684 if availhas(elt):
685 numb = avail[elt]
686 else:
687 numb = fullbcount.get(elt, 0)
688 avail[elt] = numb - 1
689 if numb > 0:
690 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000691 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000692
693 def real_quick_ratio(self):
694 """Return an upper bound on ratio() very quickly.
695
696 This isn't defined beyond that it is an upper bound on .ratio(), and
697 is faster to compute than either .ratio() or .quick_ratio().
698 """
699
700 la, lb = len(self.a), len(self.b)
701 # can't have more matches than the number of elements in the
702 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000703 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000704
705def get_close_matches(word, possibilities, n=3, cutoff=0.6):
706 """Use SequenceMatcher to return list of the best "good enough" matches.
707
708 word is a sequence for which close matches are desired (typically a
709 string).
710
711 possibilities is a list of sequences against which to match word
712 (typically a list of strings).
713
714 Optional arg n (default 3) is the maximum number of close matches to
715 return. n must be > 0.
716
717 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
718 that don't score at least that similar to word are ignored.
719
720 The best (no more than n) matches among the possibilities are returned
721 in a list, sorted by similarity score, most similar first.
722
723 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
724 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000725 >>> import keyword as _keyword
726 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000727 ['while']
Guido van Rossum486364b2007-06-30 05:01:58 +0000728 >>> get_close_matches("Apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000729 []
Tim Peters5e824c32001-08-12 22:25:01 +0000730 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000731 ['except']
732 """
733
734 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000735 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000736 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000737 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000738 result = []
739 s = SequenceMatcher()
740 s.set_seq2(word)
741 for x in possibilities:
742 s.set_seq1(x)
743 if s.real_quick_ratio() >= cutoff and \
744 s.quick_ratio() >= cutoff and \
745 s.ratio() >= cutoff:
746 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000747
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000748 # Move the best scorers to head of list
Raymond Hettingeraefde432004-06-15 23:53:35 +0000749 result = heapq.nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000750 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000751 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000752
753def _count_leading(line, ch):
754 """
755 Return number of `ch` characters at the start of `line`.
756
757 Example:
758
759 >>> _count_leading(' abc', ' ')
760 3
761 """
762
763 i, n = 0, len(line)
764 while i < n and line[i] == ch:
765 i += 1
766 return i
767
768class Differ:
769 r"""
770 Differ is a class for comparing sequences of lines of text, and
771 producing human-readable differences or deltas. Differ uses
772 SequenceMatcher both to compare sequences of lines, and to compare
773 sequences of characters within similar (near-matching) lines.
774
775 Each line of a Differ delta begins with a two-letter code:
776
777 '- ' line unique to sequence 1
778 '+ ' line unique to sequence 2
779 ' ' line common to both sequences
780 '? ' line not present in either input sequence
781
782 Lines beginning with '? ' attempt to guide the eye to intraline
783 differences, and were not present in either input sequence. These lines
784 can be confusing if the sequences contain tab characters.
785
786 Note that Differ makes no claim to produce a *minimal* diff. To the
787 contrary, minimal diffs are often counter-intuitive, because they synch
788 up anywhere possible, sometimes accidental matches 100 pages apart.
789 Restricting synch points to contiguous matches preserves some notion of
790 locality, at the occasional cost of producing a longer diff.
791
792 Example: Comparing two texts.
793
794 First we set up the texts, sequences of individual single-line strings
795 ending with newlines (such sequences can also be obtained from the
796 `readlines()` method of file-like objects):
797
798 >>> text1 = ''' 1. Beautiful is better than ugly.
799 ... 2. Explicit is better than implicit.
800 ... 3. Simple is better than complex.
801 ... 4. Complex is better than complicated.
802 ... '''.splitlines(1)
803 >>> len(text1)
804 4
805 >>> text1[0][-1]
806 '\n'
807 >>> text2 = ''' 1. Beautiful is better than ugly.
808 ... 3. Simple is better than complex.
809 ... 4. Complicated is better than complex.
810 ... 5. Flat is better than nested.
811 ... '''.splitlines(1)
812
813 Next we instantiate a Differ object:
814
815 >>> d = Differ()
816
817 Note that when instantiating a Differ object we may pass functions to
818 filter out line and character 'junk'. See Differ.__init__ for details.
819
820 Finally, we compare the two:
821
Tim Peters8a9c2842001-09-22 21:30:22 +0000822 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000823
824 'result' is a list of strings, so let's pretty-print it:
825
826 >>> from pprint import pprint as _pprint
827 >>> _pprint(result)
828 [' 1. Beautiful is better than ugly.\n',
829 '- 2. Explicit is better than implicit.\n',
830 '- 3. Simple is better than complex.\n',
831 '+ 3. Simple is better than complex.\n',
832 '? ++\n',
833 '- 4. Complex is better than complicated.\n',
834 '? ^ ---- ^\n',
835 '+ 4. Complicated is better than complex.\n',
836 '? ++++ ^ ^\n',
837 '+ 5. Flat is better than nested.\n']
838
839 As a single multi-line string it looks like this:
840
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000841 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000842 1. Beautiful is better than ugly.
843 - 2. Explicit is better than implicit.
844 - 3. Simple is better than complex.
845 + 3. Simple is better than complex.
846 ? ++
847 - 4. Complex is better than complicated.
848 ? ^ ---- ^
849 + 4. Complicated is better than complex.
850 ? ++++ ^ ^
851 + 5. Flat is better than nested.
852
853 Methods:
854
855 __init__(linejunk=None, charjunk=None)
856 Construct a text differencer, with optional filters.
857
858 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000859 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000860 """
861
862 def __init__(self, linejunk=None, charjunk=None):
863 """
864 Construct a text differencer, with optional filters.
865
866 The two optional keyword parameters are for filter functions:
867
868 - `linejunk`: A function that should accept a single string argument,
869 and return true iff the string is junk. The module-level function
870 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000871 characters, except for at most one splat ('#'). It is recommended
872 to leave linejunk None; as of Python 2.3, the underlying
873 SequenceMatcher class has grown an adaptive notion of "noise" lines
874 that's better than any static definition the author has ever been
875 able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000876
877 - `charjunk`: A function that should accept a string of length 1. The
878 module-level function `IS_CHARACTER_JUNK` may be used to filter out
879 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000880 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000881 """
882
883 self.linejunk = linejunk
884 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000885
886 def compare(self, a, b):
887 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000888 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000889
890 Each sequence must contain individual single-line strings ending with
891 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000892 of file-like objects. The delta generated also consists of newline-
893 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000894 method of a file-like object.
895
896 Example:
897
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000898 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
Tim Peters5e824c32001-08-12 22:25:01 +0000899 ... 'ore\ntree\nemu\n'.splitlines(1))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000900 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000901 - one
902 ? ^
903 + ore
904 ? ^
905 - two
906 - three
907 ? -
908 + tree
909 + emu
910 """
911
912 cruncher = SequenceMatcher(self.linejunk, a, b)
913 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
914 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000915 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000916 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000917 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000918 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000919 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000920 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000921 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000922 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000923 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +0000924
925 for line in g:
926 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000927
928 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000929 """Generate comparison results for a same-tagged range."""
Guido van Rossum805365e2007-05-07 22:24:25 +0000930 for i in range(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000931 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000932
933 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
934 assert alo < ahi and blo < bhi
935 # dump the shorter block first -- reduces the burden on short-term
936 # memory if the blocks are of very different sizes
937 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000938 first = self._dump('+', b, blo, bhi)
939 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000940 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000941 first = self._dump('-', a, alo, ahi)
942 second = self._dump('+', b, blo, bhi)
943
944 for g in first, second:
945 for line in g:
946 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000947
948 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
949 r"""
950 When replacing one block of lines with another, search the blocks
951 for *similar* lines; the best-matching pair (if any) is used as a
952 synch point, and intraline difference marking is done on the
953 similar pair. Lots of work, but often worth it.
954
955 Example:
956
957 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000958 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
959 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000960 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000961 - abcDefghiJkl
962 ? ^ ^ ^
963 + abcdefGhijkl
964 ? ^ ^ ^
965 """
966
Tim Peters5e824c32001-08-12 22:25:01 +0000967 # don't synch up unless the lines have a similarity score of at
968 # least cutoff; best_ratio tracks the best score seen so far
969 best_ratio, cutoff = 0.74, 0.75
970 cruncher = SequenceMatcher(self.charjunk)
971 eqi, eqj = None, None # 1st indices of equal lines (if any)
972
973 # search for the pair that matches best without being identical
974 # (identical lines must be junk lines, & we don't want to synch up
975 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000976 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000977 bj = b[j]
978 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000979 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000980 ai = a[i]
981 if ai == bj:
982 if eqi is None:
983 eqi, eqj = i, j
984 continue
985 cruncher.set_seq1(ai)
986 # computing similarity is expensive, so use the quick
987 # upper bounds first -- have seen this speed up messy
988 # compares by a factor of 3.
989 # note that ratio() is only expensive to compute the first
990 # time it's called on a sequence pair; the expensive part
991 # of the computation is cached by cruncher
992 if cruncher.real_quick_ratio() > best_ratio and \
993 cruncher.quick_ratio() > best_ratio and \
994 cruncher.ratio() > best_ratio:
995 best_ratio, best_i, best_j = cruncher.ratio(), i, j
996 if best_ratio < cutoff:
997 # no non-identical "pretty close" pair
998 if eqi is None:
999 # no identical pair either -- treat it as a straight replace
Tim Peters8a9c2842001-09-22 21:30:22 +00001000 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
1001 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001002 return
1003 # no close pair, but an identical pair -- synch up on that
1004 best_i, best_j, best_ratio = eqi, eqj, 1.0
1005 else:
1006 # there's a close pair, so forget the identical pair (if any)
1007 eqi = None
1008
1009 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
1010 # identical
Tim Peters5e824c32001-08-12 22:25:01 +00001011
1012 # pump out diffs from before the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001013 for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
1014 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001015
1016 # do intraline marking on the synch pair
1017 aelt, belt = a[best_i], b[best_j]
1018 if eqi is None:
1019 # pump out a '-', '?', '+', '?' quad for the synched lines
1020 atags = btags = ""
1021 cruncher.set_seqs(aelt, belt)
1022 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1023 la, lb = ai2 - ai1, bj2 - bj1
1024 if tag == 'replace':
1025 atags += '^' * la
1026 btags += '^' * lb
1027 elif tag == 'delete':
1028 atags += '-' * la
1029 elif tag == 'insert':
1030 btags += '+' * lb
1031 elif tag == 'equal':
1032 atags += ' ' * la
1033 btags += ' ' * lb
1034 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001035 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +00001036 for line in self._qformat(aelt, belt, atags, btags):
1037 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001038 else:
1039 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001040 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001041
1042 # pump out diffs from after the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001043 for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
1044 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001045
1046 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001047 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001048 if alo < ahi:
1049 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001050 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001051 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001052 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001053 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001054 g = self._dump('+', b, blo, bhi)
1055
1056 for line in g:
1057 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001058
1059 def _qformat(self, aline, bline, atags, btags):
1060 r"""
1061 Format "?" output and deal with leading tabs.
1062
1063 Example:
1064
1065 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001066 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1067 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001068 >>> for line in results: print(repr(line))
1069 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001070 '- \tabcDefghiJkl\n'
1071 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001072 '+ \tabcdefGhijkl\n'
1073 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001074 """
1075
1076 # Can hurt, but will probably help most of the time.
1077 common = min(_count_leading(aline, "\t"),
1078 _count_leading(bline, "\t"))
1079 common = min(common, _count_leading(atags[:common], " "))
Senthil Kumaran758025c2009-11-23 19:02:52 +00001080 common = min(common, _count_leading(btags[:common], " "))
Tim Peters5e824c32001-08-12 22:25:01 +00001081 atags = atags[common:].rstrip()
1082 btags = btags[common:].rstrip()
1083
Tim Peters8a9c2842001-09-22 21:30:22 +00001084 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001085 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001086 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001087
Tim Peters8a9c2842001-09-22 21:30:22 +00001088 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001089 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001090 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001091
1092# With respect to junk, an earlier version of ndiff simply refused to
1093# *start* a match with a junk element. The result was cases like this:
1094# before: private Thread currentThread;
1095# after: private volatile Thread currentThread;
1096# If you consider whitespace to be junk, the longest contiguous match
1097# not starting with junk is "e Thread currentThread". So ndiff reported
1098# that "e volatil" was inserted between the 't' and the 'e' in "private".
1099# While an accurate view, to people that's absurd. The current version
1100# looks for matching blocks that are entirely junk-free, then extends the
1101# longest one of those as far as possible but only with matching junk.
1102# So now "currentThread" is matched, then extended to suck up the
1103# preceding blank; then "private" is matched, and extended to suck up the
1104# following blank; then "Thread" is matched; and finally ndiff reports
1105# that "volatile " was inserted before "Thread". The only quibble
1106# remaining is that perhaps it was really the case that " volatile"
1107# was inserted after "private". I can live with that <wink>.
1108
1109import re
1110
1111def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1112 r"""
1113 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1114
1115 Examples:
1116
1117 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001118 True
Tim Peters5e824c32001-08-12 22:25:01 +00001119 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001120 True
Tim Peters5e824c32001-08-12 22:25:01 +00001121 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001122 False
Tim Peters5e824c32001-08-12 22:25:01 +00001123 """
1124
1125 return pat(line) is not None
1126
1127def IS_CHARACTER_JUNK(ch, ws=" \t"):
1128 r"""
1129 Return 1 for ignorable character: iff `ch` is a space or tab.
1130
1131 Examples:
1132
1133 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001134 True
Tim Peters5e824c32001-08-12 22:25:01 +00001135 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001136 True
Tim Peters5e824c32001-08-12 22:25:01 +00001137 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001138 False
Tim Peters5e824c32001-08-12 22:25:01 +00001139 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001140 False
Tim Peters5e824c32001-08-12 22:25:01 +00001141 """
1142
1143 return ch in ws
1144
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001145
1146def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1147 tofiledate='', n=3, lineterm='\n'):
1148 r"""
1149 Compare two sequences of lines; generate the delta as a unified diff.
1150
1151 Unified diffs are a compact way of showing line changes and a few
1152 lines of context. The number of context lines is set by 'n' which
1153 defaults to three.
1154
Raymond Hettinger0887c732003-06-17 16:53:25 +00001155 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001156 created with a trailing newline. This is helpful so that inputs
1157 created from file.readlines() result in diffs that are suitable for
1158 file.writelines() since both the inputs and outputs have trailing
1159 newlines.
1160
1161 For inputs that do not have trailing newlines, set the lineterm
1162 argument to "" so that the output will be uniformly newline free.
1163
1164 The unidiff format normally has a header for filenames and modification
1165 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001166 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1167 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001168
1169 Example:
1170
1171 >>> for line in unified_diff('one two three four'.split(),
1172 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001173 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001174 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001175 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1176 --- Original 2005-01-26 23:30:50
1177 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001178 @@ -1,4 +1,4 @@
1179 +zero
1180 one
1181 -two
1182 -three
1183 +tree
1184 four
1185 """
1186
1187 started = False
1188 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1189 if not started:
R. David Murrayb2416e52010-04-12 16:58:02 +00001190 fromdate = '\t%s' % fromfiledate if fromfiledate else ''
1191 todate = '\t%s' % tofiledate if tofiledate else ''
1192 yield '--- %s%s%s' % (fromfile, fromdate, lineterm)
1193 yield '+++ %s%s%s' % (tofile, todate, lineterm)
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001194 started = True
1195 i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
1196 yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
1197 for tag, i1, i2, j1, j2 in group:
1198 if tag == 'equal':
1199 for line in a[i1:i2]:
1200 yield ' ' + line
1201 continue
1202 if tag == 'replace' or tag == 'delete':
1203 for line in a[i1:i2]:
1204 yield '-' + line
1205 if tag == 'replace' or tag == 'insert':
1206 for line in b[j1:j2]:
1207 yield '+' + line
1208
1209# See http://www.unix.org/single_unix_specification/
1210def context_diff(a, b, fromfile='', tofile='',
1211 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1212 r"""
1213 Compare two sequences of lines; generate the delta as a context diff.
1214
1215 Context diffs are a compact way of showing line changes and a few
1216 lines of context. The number of context lines is set by 'n' which
1217 defaults to three.
1218
1219 By default, the diff control lines (those with *** or ---) are
1220 created with a trailing newline. This is helpful so that inputs
1221 created from file.readlines() result in diffs that are suitable for
1222 file.writelines() since both the inputs and outputs have trailing
1223 newlines.
1224
1225 For inputs that do not have trailing newlines, set the lineterm
1226 argument to "" so that the output will be uniformly newline free.
1227
1228 The context diff format normally has a header for filenames and
1229 modification times. Any or all of these may be specified using
1230 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001231 The modification times are normally expressed in the ISO 8601 format.
1232 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001233
1234 Example:
1235
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001236 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
R. David Murrayb2416e52010-04-12 16:58:02 +00001237 ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001238 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001239 *** Original
1240 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001241 ***************
1242 *** 1,4 ****
1243 one
1244 ! two
1245 ! three
1246 four
1247 --- 1,4 ----
1248 + zero
1249 one
1250 ! tree
1251 four
1252 """
1253
1254 started = False
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001255 prefixmap = {'insert':'+ ', 'delete':'- ', 'replace':'! ', 'equal':' '}
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001256 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1257 if not started:
R. David Murrayb2416e52010-04-12 16:58:02 +00001258 fromdate = '\t%s' % fromfiledate if fromfiledate else ''
1259 todate = '\t%s' % tofiledate if tofiledate else ''
1260 yield '*** %s%s%s' % (fromfile, fromdate, lineterm)
1261 yield '--- %s%s%s' % (tofile, todate, lineterm)
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001262 started = True
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001263
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001264 yield '***************%s' % (lineterm,)
1265 if group[-1][2] - group[0][1] >= 2:
1266 yield '*** %d,%d ****%s' % (group[0][1]+1, group[-1][2], lineterm)
1267 else:
1268 yield '*** %d ****%s' % (group[-1][2], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001269 visiblechanges = [e for e in group if e[0] in ('replace', 'delete')]
1270 if visiblechanges:
1271 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001272 if tag != 'insert':
1273 for line in a[i1:i2]:
1274 yield prefixmap[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001275
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001276 if group[-1][4] - group[0][3] >= 2:
1277 yield '--- %d,%d ----%s' % (group[0][3]+1, group[-1][4], lineterm)
1278 else:
1279 yield '--- %d ----%s' % (group[-1][4], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001280 visiblechanges = [e for e in group if e[0] in ('replace', 'insert')]
1281 if visiblechanges:
1282 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001283 if tag != 'delete':
1284 for line in b[j1:j2]:
1285 yield prefixmap[tag] + line
1286
Tim Peters81b92512002-04-29 01:37:32 +00001287def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001288 r"""
1289 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1290
1291 Optional keyword parameters `linejunk` and `charjunk` are for filter
1292 functions (or None):
1293
1294 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001295 return true iff the string is junk. The default is None, and is
1296 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1297 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001298
1299 - charjunk: A function that should accept a string of length 1. The
1300 default is module-level function IS_CHARACTER_JUNK, which filters out
1301 whitespace characters (a blank or tab; note: bad idea to include newline
1302 in this!).
1303
1304 Tools/scripts/ndiff.py is a command-line front-end to this function.
1305
1306 Example:
1307
1308 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1309 ... 'ore\ntree\nemu\n'.splitlines(1))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001310 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001311 - one
1312 ? ^
1313 + ore
1314 ? ^
1315 - two
1316 - three
1317 ? -
1318 + tree
1319 + emu
1320 """
1321 return Differ(linejunk, charjunk).compare(a, b)
1322
Martin v. Löwise064b412004-08-29 16:34:40 +00001323def _mdiff(fromlines, tolines, context=None, linejunk=None,
1324 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001325 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001326
1327 Arguments:
1328 fromlines -- list of text lines to compared to tolines
1329 tolines -- list of text lines to be compared to fromlines
1330 context -- number of context lines to display on each side of difference,
1331 if None, all from/to text lines will be generated.
1332 linejunk -- passed on to ndiff (see ndiff documentation)
1333 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001334
Martin v. Löwise064b412004-08-29 16:34:40 +00001335 This function returns an interator which returns a tuple:
1336 (from line tuple, to line tuple, boolean flag)
1337
1338 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001339 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001340 line text -- original line text with following markers inserted:
1341 '\0+' -- marks start of added text
1342 '\0-' -- marks start of deleted text
1343 '\0^' -- marks start of changed text
1344 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001345
Martin v. Löwise064b412004-08-29 16:34:40 +00001346 boolean flag -- None indicates context separation, True indicates
1347 either "from" or "to" line contains a change, otherwise False.
1348
1349 This function/iterator was originally developed to generate side by side
1350 file difference for making HTML pages (see HtmlDiff class for example
1351 usage).
1352
1353 Note, this function utilizes the ndiff function to generate the side by
1354 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001355 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001356 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001357 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001358
1359 # regular expression for finding intraline change indices
1360 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001361
Martin v. Löwise064b412004-08-29 16:34:40 +00001362 # create the difference iterator to generate the differences
1363 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1364
1365 def _make_line(lines, format_key, side, num_lines=[0,0]):
1366 """Returns line of text with user's change markup and line formatting.
1367
1368 lines -- list of lines from the ndiff generator to produce a line of
1369 text from. When producing the line of text to return, the
1370 lines used are removed from this list.
1371 format_key -- '+' return first line in list with "add" markup around
1372 the entire line.
1373 '-' return first line in list with "delete" markup around
1374 the entire line.
1375 '?' return first line in list with add/delete/change
1376 intraline markup (indices obtained from second line)
1377 None return first line in list with no markup
1378 side -- indice into the num_lines list (0=from,1=to)
1379 num_lines -- from/to current line number. This is NOT intended to be a
1380 passed parameter. It is present as a keyword argument to
1381 maintain memory of the current line numbers between calls
1382 of this function.
1383
1384 Note, this function is purposefully not defined at the module scope so
1385 that data it needs from its parent function (within whose context it
1386 is defined) does not need to be of module scope.
1387 """
1388 num_lines[side] += 1
1389 # Handle case where no user markup is to be added, just return line of
1390 # text with user's line format to allow for usage of the line number.
1391 if format_key is None:
1392 return (num_lines[side],lines.pop(0)[2:])
1393 # Handle case of intraline changes
1394 if format_key == '?':
1395 text, markers = lines.pop(0), lines.pop(0)
1396 # find intraline changes (store change type and indices in tuples)
1397 sub_info = []
1398 def record_sub_info(match_object,sub_info=sub_info):
1399 sub_info.append([match_object.group(1)[0],match_object.span()])
1400 return match_object.group(1)
1401 change_re.sub(record_sub_info,markers)
1402 # process each tuple inserting our special marks that won't be
1403 # noticed by an xml/html escaper.
1404 for key,(begin,end) in sub_info[::-1]:
1405 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1406 text = text[2:]
1407 # Handle case of add/delete entire line
1408 else:
1409 text = lines.pop(0)[2:]
1410 # if line of text is just a newline, insert a space so there is
1411 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001412 if not text:
1413 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001414 # insert marks that won't be noticed by an xml/html escaper.
1415 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001416 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001417 # thing (such as adding the line number) then replace the special
1418 # marks with what the user's change markup.
1419 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001420
Martin v. Löwise064b412004-08-29 16:34:40 +00001421 def _line_iterator():
1422 """Yields from/to lines of text with a change indication.
1423
1424 This function is an iterator. It itself pulls lines from a
1425 differencing iterator, processes them and yields them. When it can
1426 it yields both a "from" and a "to" line, otherwise it will yield one
1427 or the other. In addition to yielding the lines of from/to text, a
1428 boolean flag is yielded to indicate if the text line(s) have
1429 differences in them.
1430
1431 Note, this function is purposefully not defined at the module scope so
1432 that data it needs from its parent function (within whose context it
1433 is defined) does not need to be of module scope.
1434 """
1435 lines = []
1436 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001437 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001438 # Load up next 4 lines so we can look ahead, create strings which
1439 # are a concatenation of the first character of each of the 4 lines
1440 # so we can do some very readable comparisons.
1441 while len(lines) < 4:
1442 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001443 lines.append(next(diff_lines_iterator))
Martin v. Löwise064b412004-08-29 16:34:40 +00001444 except StopIteration:
1445 lines.append('X')
1446 s = ''.join([line[0] for line in lines])
1447 if s.startswith('X'):
1448 # When no more lines, pump out any remaining blank lines so the
1449 # corresponding add/delete lines get a matching blank line so
1450 # all line pairs get yielded at the next level.
1451 num_blanks_to_yield = num_blanks_pending
1452 elif s.startswith('-?+?'):
1453 # simple intraline change
1454 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1455 continue
1456 elif s.startswith('--++'):
1457 # in delete block, add block coming: we do NOT want to get
1458 # caught up on blank lines yet, just process the delete line
1459 num_blanks_pending -= 1
1460 yield _make_line(lines,'-',0), None, True
1461 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001462 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001463 # in delete block and see a intraline change or unchanged line
1464 # coming: yield the delete line and then blanks
1465 from_line,to_line = _make_line(lines,'-',0), None
1466 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1467 elif s.startswith('-+?'):
1468 # intraline change
1469 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1470 continue
1471 elif s.startswith('-?+'):
1472 # intraline change
1473 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1474 continue
1475 elif s.startswith('-'):
1476 # delete FROM line
1477 num_blanks_pending -= 1
1478 yield _make_line(lines,'-',0), None, True
1479 continue
1480 elif s.startswith('+--'):
1481 # in add block, delete block coming: we do NOT want to get
1482 # caught up on blank lines yet, just process the add line
1483 num_blanks_pending += 1
1484 yield None, _make_line(lines,'+',1), True
1485 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001486 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001487 # will be leaving an add block: yield blanks then add line
1488 from_line, to_line = None, _make_line(lines,'+',1)
1489 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1490 elif s.startswith('+'):
1491 # inside an add block, yield the add line
1492 num_blanks_pending += 1
1493 yield None, _make_line(lines,'+',1), True
1494 continue
1495 elif s.startswith(' '):
1496 # unchanged text, yield it to both sides
1497 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1498 continue
1499 # Catch up on the blank lines so when we yield the next from/to
1500 # pair, they are lined up.
1501 while(num_blanks_to_yield < 0):
1502 num_blanks_to_yield += 1
1503 yield None,('','\n'),True
1504 while(num_blanks_to_yield > 0):
1505 num_blanks_to_yield -= 1
1506 yield ('','\n'),None,True
1507 if s.startswith('X'):
1508 raise StopIteration
1509 else:
1510 yield from_line,to_line,True
1511
1512 def _line_pair_iterator():
1513 """Yields from/to lines of text with a change indication.
1514
1515 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001516 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001517 always yields a pair of from/to text lines (with the change
1518 indication). If necessary it will collect single from/to lines
1519 until it has a matching pair from/to pair to yield.
1520
1521 Note, this function is purposefully not defined at the module scope so
1522 that data it needs from its parent function (within whose context it
1523 is defined) does not need to be of module scope.
1524 """
1525 line_iterator = _line_iterator()
1526 fromlines,tolines=[],[]
1527 while True:
1528 # Collecting lines of text until we have a from/to pair
1529 while (len(fromlines)==0 or len(tolines)==0):
Georg Brandla18af4e2007-04-21 15:47:16 +00001530 from_line, to_line, found_diff = next(line_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001531 if from_line is not None:
1532 fromlines.append((from_line,found_diff))
1533 if to_line is not None:
1534 tolines.append((to_line,found_diff))
1535 # Once we have a pair, remove them from the collection and yield it
1536 from_line, fromDiff = fromlines.pop(0)
1537 to_line, to_diff = tolines.pop(0)
1538 yield (from_line,to_line,fromDiff or to_diff)
1539
1540 # Handle case where user does not want context differencing, just yield
1541 # them up without doing anything else with them.
1542 line_pair_iterator = _line_pair_iterator()
1543 if context is None:
1544 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +00001545 yield next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001546 # Handle case where user wants context differencing. We must do some
1547 # storage of lines until we know for sure that they are to be yielded.
1548 else:
1549 context += 1
1550 lines_to_write = 0
1551 while True:
1552 # Store lines up until we find a difference, note use of a
1553 # circular queue because we only need to keep around what
1554 # we need for context.
1555 index, contextLines = 0, [None]*(context)
1556 found_diff = False
1557 while(found_diff is False):
Georg Brandla18af4e2007-04-21 15:47:16 +00001558 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001559 i = index % context
1560 contextLines[i] = (from_line, to_line, found_diff)
1561 index += 1
1562 # Yield lines that we have collected so far, but first yield
1563 # the user's separator.
1564 if index > context:
1565 yield None, None, None
1566 lines_to_write = context
1567 else:
1568 lines_to_write = index
1569 index = 0
1570 while(lines_to_write):
1571 i = index % context
1572 index += 1
1573 yield contextLines[i]
1574 lines_to_write -= 1
1575 # Now yield the context lines after the change
1576 lines_to_write = context-1
1577 while(lines_to_write):
Georg Brandla18af4e2007-04-21 15:47:16 +00001578 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001579 # If another change within the context, extend the context
1580 if found_diff:
1581 lines_to_write = context-1
1582 else:
1583 lines_to_write -= 1
1584 yield from_line, to_line, found_diff
1585
1586
1587_file_template = """
1588<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1589 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1590
1591<html>
1592
1593<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001594 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001595 content="text/html; charset=ISO-8859-1" />
1596 <title></title>
1597 <style type="text/css">%(styles)s
1598 </style>
1599</head>
1600
1601<body>
1602 %(table)s%(legend)s
1603</body>
1604
1605</html>"""
1606
1607_styles = """
1608 table.diff {font-family:Courier; border:medium;}
1609 .diff_header {background-color:#e0e0e0}
1610 td.diff_header {text-align:right}
1611 .diff_next {background-color:#c0c0c0}
1612 .diff_add {background-color:#aaffaa}
1613 .diff_chg {background-color:#ffff77}
1614 .diff_sub {background-color:#ffaaaa}"""
1615
1616_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001617 <table class="diff" id="difflib_chg_%(prefix)s_top"
1618 cellspacing="0" cellpadding="0" rules="groups" >
1619 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001620 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1621 %(header_row)s
1622 <tbody>
1623%(data_rows)s </tbody>
1624 </table>"""
1625
1626_legend = """
1627 <table class="diff" summary="Legends">
1628 <tr> <th colspan="2"> Legends </th> </tr>
1629 <tr> <td> <table border="" summary="Colors">
1630 <tr><th> Colors </th> </tr>
1631 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1632 <tr><td class="diff_chg">Changed</td> </tr>
1633 <tr><td class="diff_sub">Deleted</td> </tr>
1634 </table></td>
1635 <td> <table border="" summary="Links">
1636 <tr><th colspan="2"> Links </th> </tr>
1637 <tr><td>(f)irst change</td> </tr>
1638 <tr><td>(n)ext change</td> </tr>
1639 <tr><td>(t)op</td> </tr>
1640 </table></td> </tr>
1641 </table>"""
1642
1643class HtmlDiff(object):
1644 """For producing HTML side by side comparison with change highlights.
1645
1646 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001647 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001648 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001649 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001650
Martin v. Löwise064b412004-08-29 16:34:40 +00001651 The following methods are provided for HTML generation:
1652
1653 make_table -- generates HTML for a single side by side table
1654 make_file -- generates complete HTML file with a single side by side table
1655
Tim Peters48bd7f32004-08-29 22:38:38 +00001656 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001657 """
1658
1659 _file_template = _file_template
1660 _styles = _styles
1661 _table_template = _table_template
1662 _legend = _legend
1663 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001664
Martin v. Löwise064b412004-08-29 16:34:40 +00001665 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1666 charjunk=IS_CHARACTER_JUNK):
1667 """HtmlDiff instance initializer
1668
1669 Arguments:
1670 tabsize -- tab stop spacing, defaults to 8.
1671 wrapcolumn -- column number where lines are broken and wrapped,
1672 defaults to None where lines are not wrapped.
1673 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001674 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001675 ndiff() documentation for argument default values and descriptions.
1676 """
1677 self._tabsize = tabsize
1678 self._wrapcolumn = wrapcolumn
1679 self._linejunk = linejunk
1680 self._charjunk = charjunk
1681
1682 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1683 numlines=5):
1684 """Returns HTML file of side by side comparison with change highlights
1685
1686 Arguments:
1687 fromlines -- list of "from" lines
1688 tolines -- list of "to" lines
1689 fromdesc -- "from" file column header string
1690 todesc -- "to" file column header string
1691 context -- set to True for contextual differences (defaults to False
1692 which shows full differences).
1693 numlines -- number of context lines. When context is set True,
1694 controls number of lines displayed before and after the change.
1695 When context is False, controls the number of lines to place
1696 the "next" link anchors before the next change (so click of
1697 "next" link jumps to just before the change).
1698 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001699
Martin v. Löwise064b412004-08-29 16:34:40 +00001700 return self._file_template % dict(
1701 styles = self._styles,
1702 legend = self._legend,
1703 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1704 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001705
Martin v. Löwise064b412004-08-29 16:34:40 +00001706 def _tab_newline_replace(self,fromlines,tolines):
1707 """Returns from/to line lists with tabs expanded and newlines removed.
1708
1709 Instead of tab characters being replaced by the number of spaces
1710 needed to fill in to the next tab stop, this function will fill
1711 the space with tab characters. This is done so that the difference
1712 algorithms can identify changes in a file when tabs are replaced by
1713 spaces and vice versa. At the end of the HTML generation, the tab
1714 characters will be replaced with a nonbreakable space.
1715 """
1716 def expand_tabs(line):
1717 # hide real spaces
1718 line = line.replace(' ','\0')
1719 # expand tabs into spaces
1720 line = line.expandtabs(self._tabsize)
1721 # relace spaces from expanded tabs back into tab characters
1722 # (we'll replace them with markup after we do differencing)
1723 line = line.replace(' ','\t')
1724 return line.replace('\0',' ').rstrip('\n')
1725 fromlines = [expand_tabs(line) for line in fromlines]
1726 tolines = [expand_tabs(line) for line in tolines]
1727 return fromlines,tolines
1728
1729 def _split_line(self,data_list,line_num,text):
1730 """Builds list of text lines by splitting text lines at wrap point
1731
1732 This function will determine if the input text line needs to be
1733 wrapped (split) into separate lines. If so, the first wrap point
1734 will be determined and the first line appended to the output
1735 text line list. This function is used recursively to handle
1736 the second part of the split line to further split it.
1737 """
1738 # if blank line or context separator, just add it to the output list
1739 if not line_num:
1740 data_list.append((line_num,text))
1741 return
1742
1743 # if line text doesn't need wrapping, just add it to the output list
1744 size = len(text)
1745 max = self._wrapcolumn
1746 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1747 data_list.append((line_num,text))
1748 return
1749
1750 # scan text looking for the wrap point, keeping track if the wrap
1751 # point is inside markers
1752 i = 0
1753 n = 0
1754 mark = ''
1755 while n < max and i < size:
1756 if text[i] == '\0':
1757 i += 1
1758 mark = text[i]
1759 i += 1
1760 elif text[i] == '\1':
1761 i += 1
1762 mark = ''
1763 else:
1764 i += 1
1765 n += 1
1766
1767 # wrap point is inside text, break it up into separate lines
1768 line1 = text[:i]
1769 line2 = text[i:]
1770
1771 # if wrap point is inside markers, place end marker at end of first
1772 # line and start marker at beginning of second line because each
1773 # line will have its own table tag markup around it.
1774 if mark:
1775 line1 = line1 + '\1'
1776 line2 = '\0' + mark + line2
1777
Tim Peters48bd7f32004-08-29 22:38:38 +00001778 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001779 data_list.append((line_num,line1))
1780
Tim Peters48bd7f32004-08-29 22:38:38 +00001781 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001782 self._split_line(data_list,'>',line2)
1783
1784 def _line_wrapper(self,diffs):
1785 """Returns iterator that splits (wraps) mdiff text lines"""
1786
1787 # pull from/to data and flags from mdiff iterator
1788 for fromdata,todata,flag in diffs:
1789 # check for context separators and pass them through
1790 if flag is None:
1791 yield fromdata,todata,flag
1792 continue
1793 (fromline,fromtext),(toline,totext) = fromdata,todata
1794 # for each from/to line split it at the wrap column to form
1795 # list of text lines.
1796 fromlist,tolist = [],[]
1797 self._split_line(fromlist,fromline,fromtext)
1798 self._split_line(tolist,toline,totext)
1799 # yield from/to line in pairs inserting blank lines as
1800 # necessary when one side has more wrapped lines
1801 while fromlist or tolist:
1802 if fromlist:
1803 fromdata = fromlist.pop(0)
1804 else:
1805 fromdata = ('',' ')
1806 if tolist:
1807 todata = tolist.pop(0)
1808 else:
1809 todata = ('',' ')
1810 yield fromdata,todata,flag
1811
1812 def _collect_lines(self,diffs):
1813 """Collects mdiff output into separate lists
1814
1815 Before storing the mdiff from/to data into a list, it is converted
1816 into a single line of text with HTML markup.
1817 """
1818
1819 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001820 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001821 for fromdata,todata,flag in diffs:
1822 try:
1823 # store HTML markup of the lines into the lists
1824 fromlist.append(self._format_line(0,flag,*fromdata))
1825 tolist.append(self._format_line(1,flag,*todata))
1826 except TypeError:
1827 # exceptions occur for lines where context separators go
1828 fromlist.append(None)
1829 tolist.append(None)
1830 flaglist.append(flag)
1831 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001832
Martin v. Löwise064b412004-08-29 16:34:40 +00001833 def _format_line(self,side,flag,linenum,text):
1834 """Returns HTML markup of "from" / "to" text lines
1835
1836 side -- 0 or 1 indicating "from" or "to" text
1837 flag -- indicates if difference on line
1838 linenum -- line number (used for line number column)
1839 text -- line text to be marked up
1840 """
1841 try:
1842 linenum = '%d' % linenum
1843 id = ' id="%s%s"' % (self._prefix[side],linenum)
1844 except TypeError:
1845 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001846 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001847 # replace those things that would get confused with HTML symbols
1848 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1849
1850 # make space non-breakable so they don't get compressed or line wrapped
1851 text = text.replace(' ','&nbsp;').rstrip()
1852
1853 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1854 % (id,linenum,text)
1855
1856 def _make_prefix(self):
1857 """Create unique anchor prefixes"""
1858
1859 # Generate a unique anchor prefix so multiple tables
1860 # can exist on the same HTML page without conflicts.
1861 fromprefix = "from%d_" % HtmlDiff._default_prefix
1862 toprefix = "to%d_" % HtmlDiff._default_prefix
1863 HtmlDiff._default_prefix += 1
1864 # store prefixes so line format method has access
1865 self._prefix = [fromprefix,toprefix]
1866
1867 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1868 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001869
Martin v. Löwise064b412004-08-29 16:34:40 +00001870 # all anchor names will be generated using the unique "to" prefix
1871 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001872
Martin v. Löwise064b412004-08-29 16:34:40 +00001873 # process change flags, generating middle column of next anchors/links
1874 next_id = ['']*len(flaglist)
1875 next_href = ['']*len(flaglist)
1876 num_chg, in_change = 0, False
1877 last = 0
1878 for i,flag in enumerate(flaglist):
1879 if flag:
1880 if not in_change:
1881 in_change = True
1882 last = i
1883 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001884 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001885 # link
1886 i = max([0,i-numlines])
1887 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001888 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001889 # change
1890 num_chg += 1
1891 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1892 toprefix,num_chg)
1893 else:
1894 in_change = False
1895 # check for cases where there is no content to avoid exceptions
1896 if not flaglist:
1897 flaglist = [False]
1898 next_id = ['']
1899 next_href = ['']
1900 last = 0
1901 if context:
1902 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1903 tolist = fromlist
1904 else:
1905 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1906 # if not a change on first line, drop a link
1907 if not flaglist[0]:
1908 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1909 # redo the last link to link to the top
1910 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1911
1912 return fromlist,tolist,flaglist,next_href,next_id
1913
1914 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1915 numlines=5):
1916 """Returns HTML table of side by side comparison with change highlights
1917
1918 Arguments:
1919 fromlines -- list of "from" lines
1920 tolines -- list of "to" lines
1921 fromdesc -- "from" file column header string
1922 todesc -- "to" file column header string
1923 context -- set to True for contextual differences (defaults to False
1924 which shows full differences).
1925 numlines -- number of context lines. When context is set True,
1926 controls number of lines displayed before and after the change.
1927 When context is False, controls the number of lines to place
1928 the "next" link anchors before the next change (so click of
1929 "next" link jumps to just before the change).
1930 """
1931
1932 # make unique anchor prefixes so that multiple tables may exist
1933 # on the same page without conflict.
1934 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001935
Martin v. Löwise064b412004-08-29 16:34:40 +00001936 # change tabs to spaces before it gets more difficult after we insert
1937 # markkup
1938 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001939
Martin v. Löwise064b412004-08-29 16:34:40 +00001940 # create diffs iterator which generates side by side from/to data
1941 if context:
1942 context_lines = numlines
1943 else:
1944 context_lines = None
1945 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1946 charjunk=self._charjunk)
1947
1948 # set up iterator to wrap lines that exceed desired width
1949 if self._wrapcolumn:
1950 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001951
Martin v. Löwise064b412004-08-29 16:34:40 +00001952 # collect up from/to lines and flags into lists (also format the lines)
1953 fromlist,tolist,flaglist = self._collect_lines(diffs)
1954
1955 # process change flags, generating middle column of next anchors/links
1956 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1957 fromlist,tolist,flaglist,context,numlines)
1958
Guido van Rossumd8faa362007-04-27 19:54:29 +00001959 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00001960 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1961 '<td class="diff_next">%s</td>%s</tr>\n'
1962 for i in range(len(flaglist)):
1963 if flaglist[i] is None:
1964 # mdiff yields None on separator lines skip the bogus ones
1965 # generated for the first line
1966 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001967 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00001968 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001969 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00001970 next_href[i],tolist[i]))
1971 if fromdesc or todesc:
1972 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
1973 '<th class="diff_next"><br /></th>',
1974 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
1975 '<th class="diff_next"><br /></th>',
1976 '<th colspan="2" class="diff_header">%s</th>' % todesc)
1977 else:
1978 header_row = ''
1979
1980 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00001981 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00001982 header_row=header_row,
1983 prefix=self._prefix[1])
1984
1985 return table.replace('\0+','<span class="diff_add">'). \
1986 replace('\0-','<span class="diff_sub">'). \
1987 replace('\0^','<span class="diff_chg">'). \
1988 replace('\1','</span>'). \
1989 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00001990
Martin v. Löwise064b412004-08-29 16:34:40 +00001991del re
1992
Tim Peters5e824c32001-08-12 22:25:01 +00001993def restore(delta, which):
1994 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00001995 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00001996
1997 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
1998 lines originating from file 1 or 2 (parameter `which`), stripping off line
1999 prefixes.
2000
2001 Examples:
2002
2003 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
2004 ... 'ore\ntree\nemu\n'.splitlines(1))
Tim Peters8a9c2842001-09-22 21:30:22 +00002005 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002006 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002007 one
2008 two
2009 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002010 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002011 ore
2012 tree
2013 emu
2014 """
2015 try:
2016 tag = {1: "- ", 2: "+ "}[int(which)]
2017 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002018 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Tim Peters5e824c32001-08-12 22:25:01 +00002019 % which)
2020 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002021 for line in delta:
2022 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002023 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002024
Tim Peters9ae21482001-02-10 08:00:53 +00002025def _test():
2026 import doctest, difflib
2027 return doctest.testmod(difflib)
2028
2029if __name__ == "__main__":
2030 _test()