blob: fa8c287d4714cf1b093560f55c52cbc34a729471 [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!
Tim Peters9ae21482001-02-10 08:00:53 +0000216
217 self.isjunk = isjunk
218 self.a = self.b = None
Terry Reedy99f96372010-11-25 06:12:34 +0000219 self.autojunk = autojunk
Tim Peters9ae21482001-02-10 08:00:53 +0000220 self.set_seqs(a, b)
221
222 def set_seqs(self, a, b):
223 """Set the two sequences to be compared.
224
225 >>> s = SequenceMatcher()
226 >>> s.set_seqs("abcd", "bcde")
227 >>> s.ratio()
228 0.75
229 """
230
231 self.set_seq1(a)
232 self.set_seq2(b)
233
234 def set_seq1(self, a):
235 """Set the first sequence to be compared.
236
237 The second sequence to be compared is not changed.
238
239 >>> s = SequenceMatcher(None, "abcd", "bcde")
240 >>> s.ratio()
241 0.75
242 >>> s.set_seq1("bcde")
243 >>> s.ratio()
244 1.0
245 >>>
246
247 SequenceMatcher computes and caches detailed information about the
248 second sequence, so if you want to compare one sequence S against
249 many sequences, use .set_seq2(S) once and call .set_seq1(x)
250 repeatedly for each of the other sequences.
251
252 See also set_seqs() and set_seq2().
253 """
254
255 if a is self.a:
256 return
257 self.a = a
258 self.matching_blocks = self.opcodes = None
259
260 def set_seq2(self, b):
261 """Set the second sequence to be compared.
262
263 The first sequence to be compared is not changed.
264
265 >>> s = SequenceMatcher(None, "abcd", "bcde")
266 >>> s.ratio()
267 0.75
268 >>> s.set_seq2("abcd")
269 >>> s.ratio()
270 1.0
271 >>>
272
273 SequenceMatcher computes and caches detailed information about the
274 second sequence, so if you want to compare one sequence S against
275 many sequences, use .set_seq2(S) once and call .set_seq1(x)
276 repeatedly for each of the other sequences.
277
278 See also set_seqs() and set_seq1().
279 """
280
281 if b is self.b:
282 return
283 self.b = b
284 self.matching_blocks = self.opcodes = None
285 self.fullbcount = None
286 self.__chain_b()
287
288 # For each element x in b, set b2j[x] to a list of the indices in
289 # b where x appears; the indices are in increasing order; note that
290 # the number of times x appears in b is len(b2j[x]) ...
291 # when self.isjunk is defined, junk elements don't show up in this
292 # map at all, which stops the central find_longest_match method
293 # from starting any matching block at a junk element ...
294 # also creates the fast isbjunk function ...
Tim Peters81b92512002-04-29 01:37:32 +0000295 # b2j also does not contain entries for "popular" elements, meaning
Terry Reedy99f96372010-11-25 06:12:34 +0000296 # elements that account for more than 1 + 1% of the total elements, and
Tim Peters81b92512002-04-29 01:37:32 +0000297 # when the sequence is reasonably large (>= 200 elements); this can
298 # be viewed as an adaptive notion of semi-junk, and yields an enormous
299 # speedup when, e.g., comparing program files with hundreds of
300 # instances of "return NULL;" ...
Tim Peters9ae21482001-02-10 08:00:53 +0000301 # note that this is only called when b changes; so for cross-product
302 # kinds of matches, it's best to call set_seq2 once, then set_seq1
303 # repeatedly
304
305 def __chain_b(self):
306 # Because isjunk is a user-defined (not C) function, and we test
307 # for junk a LOT, it's important to minimize the number of calls.
308 # Before the tricks described here, __chain_b was by far the most
309 # time-consuming routine in the whole module! If anyone sees
310 # Jim Roskind, thank him again for profile.py -- I never would
311 # have guessed that.
312 # The first trick is to build b2j ignoring the possibility
313 # of junk. I.e., we don't call isjunk at all yet. Throwing
314 # out the junk later is much cheaper than building b2j "right"
315 # from the start.
316 b = self.b
317 self.b2j = b2j = {}
Terry Reedy99f96372010-11-25 06:12:34 +0000318
Tim Peters81b92512002-04-29 01:37:32 +0000319 for i, elt in enumerate(b):
Terry Reedy99f96372010-11-25 06:12:34 +0000320 indices = b2j.setdefault(elt, [])
321 indices.append(i)
Tim Peters9ae21482001-02-10 08:00:53 +0000322
Terry Reedy99f96372010-11-25 06:12:34 +0000323 # Purge junk elements
324 junk = set()
Tim Peters81b92512002-04-29 01:37:32 +0000325 isjunk = self.isjunk
Tim Peters9ae21482001-02-10 08:00:53 +0000326 if isjunk:
Terry Reedy99f96372010-11-25 06:12:34 +0000327 for elt in list(b2j.keys()): # using list() since b2j is modified
328 if isjunk(elt):
329 junk.add(elt)
330 del b2j[elt]
Tim Peters9ae21482001-02-10 08:00:53 +0000331
Terry Reedy99f96372010-11-25 06:12:34 +0000332 # Purge popular elements that are not junk
333 popular = set()
334 n = len(b)
335 if self.autojunk and n >= 200:
336 ntest = n // 100 + 1
337 for elt, idxs in list(b2j.items()):
338 if len(idxs) > ntest:
339 popular.add(elt)
340 del b2j[elt]
341
342 # Now for x in b, isjunk(x) == x in junk, but the latter is much faster.
343 # Since the number of *unique* junk elements is probably small, the
344 # memory burden of keeping this set alive is likely trivial compared to
345 # the size of b2j.
346 self.isbjunk = junk.__contains__
347 self.isbpopular = popular.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000348
349 def find_longest_match(self, alo, ahi, blo, bhi):
350 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
351
352 If isjunk is not defined:
353
354 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
355 alo <= i <= i+k <= ahi
356 blo <= j <= j+k <= bhi
357 and for all (i',j',k') meeting those conditions,
358 k >= k'
359 i <= i'
360 and if i == i', j <= j'
361
362 In other words, of all maximal matching blocks, return one that
363 starts earliest in a, and of all those maximal matching blocks that
364 start earliest in a, return the one that starts earliest in b.
365
366 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
367 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000368 Match(a=0, b=4, size=5)
Tim Peters9ae21482001-02-10 08:00:53 +0000369
370 If isjunk is defined, first the longest matching block is
371 determined as above, but with the additional restriction that no
372 junk element appears in the block. Then that block is extended as
373 far as possible by matching (only) junk elements on both sides. So
374 the resulting block never matches on junk except as identical junk
375 happens to be adjacent to an "interesting" match.
376
377 Here's the same example as before, but considering blanks to be
378 junk. That prevents " abcd" from matching the " abcd" at the tail
379 end of the second sequence directly. Instead only the "abcd" can
380 match, and matches the leftmost "abcd" in the second sequence:
381
382 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
383 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000384 Match(a=1, b=0, size=4)
Tim Peters9ae21482001-02-10 08:00:53 +0000385
386 If no blocks match, return (alo, blo, 0).
387
388 >>> s = SequenceMatcher(None, "ab", "c")
389 >>> s.find_longest_match(0, 2, 0, 1)
Christian Heimes25bb7832008-01-11 16:17:00 +0000390 Match(a=0, b=0, size=0)
Tim Peters9ae21482001-02-10 08:00:53 +0000391 """
392
393 # CAUTION: stripping common prefix or suffix would be incorrect.
394 # E.g.,
395 # ab
396 # acab
397 # Longest matching block is "ab", but if common prefix is
398 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
399 # strip, so ends up claiming that ab is changed to acab by
400 # inserting "ca" in the middle. That's minimal but unintuitive:
401 # "it's obvious" that someone inserted "ac" at the front.
402 # Windiff ends up at the same place as diff, but by pairing up
403 # the unique 'b's and then matching the first two 'a's.
404
405 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
406 besti, bestj, bestsize = alo, blo, 0
407 # find longest junk-free match
408 # during an iteration of the loop, j2len[j] = length of longest
409 # junk-free match ending with a[i-1] and b[j]
410 j2len = {}
411 nothing = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000412 for i in range(alo, ahi):
Tim Peters9ae21482001-02-10 08:00:53 +0000413 # look at all instances of a[i] in b; note that because
414 # b2j has no junk keys, the loop is skipped if a[i] is junk
415 j2lenget = j2len.get
416 newj2len = {}
417 for j in b2j.get(a[i], nothing):
418 # a[i] matches b[j]
419 if j < blo:
420 continue
421 if j >= bhi:
422 break
423 k = newj2len[j] = j2lenget(j-1, 0) + 1
424 if k > bestsize:
425 besti, bestj, bestsize = i-k+1, j-k+1, k
426 j2len = newj2len
427
Tim Peters81b92512002-04-29 01:37:32 +0000428 # Extend the best by non-junk elements on each end. In particular,
429 # "popular" non-junk elements aren't in b2j, which greatly speeds
430 # the inner loop above, but also means "the best" match so far
431 # doesn't contain any junk *or* popular non-junk elements.
432 while besti > alo and bestj > blo and \
433 not isbjunk(b[bestj-1]) and \
434 a[besti-1] == b[bestj-1]:
435 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
436 while besti+bestsize < ahi and bestj+bestsize < bhi and \
437 not isbjunk(b[bestj+bestsize]) and \
438 a[besti+bestsize] == b[bestj+bestsize]:
439 bestsize += 1
440
Tim Peters9ae21482001-02-10 08:00:53 +0000441 # Now that we have a wholly interesting match (albeit possibly
442 # empty!), we may as well suck up the matching junk on each
443 # side of it too. Can't think of a good reason not to, and it
444 # saves post-processing the (possibly considerable) expense of
445 # figuring out what to do with it. In the case of an empty
446 # interesting match, this is clearly the right thing to do,
447 # because no other kind of match is possible in the regions.
448 while besti > alo and bestj > blo and \
449 isbjunk(b[bestj-1]) and \
450 a[besti-1] == b[bestj-1]:
451 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
452 while besti+bestsize < ahi and bestj+bestsize < bhi and \
453 isbjunk(b[bestj+bestsize]) and \
454 a[besti+bestsize] == b[bestj+bestsize]:
455 bestsize = bestsize + 1
456
Christian Heimes25bb7832008-01-11 16:17:00 +0000457 return Match(besti, bestj, bestsize)
Tim Peters9ae21482001-02-10 08:00:53 +0000458
459 def get_matching_blocks(self):
460 """Return list of triples describing matching subsequences.
461
462 Each triple is of the form (i, j, n), and means that
463 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000464 i and in j. New in Python 2.5, it's also guaranteed that if
465 (i, j, n) and (i', j', n') are adjacent triples in the list, and
466 the second is not the last triple in the list, then i+n != i' or
467 j+n != j'. IOW, adjacent triples never describe adjacent equal
468 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000469
470 The last triple is a dummy, (len(a), len(b), 0), and is the only
471 triple with n==0.
472
473 >>> s = SequenceMatcher(None, "abxcd", "abcd")
Christian Heimes25bb7832008-01-11 16:17:00 +0000474 >>> list(s.get_matching_blocks())
475 [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 +0000476 """
477
478 if self.matching_blocks is not None:
479 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000480 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000481
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000482 # This is most naturally expressed as a recursive algorithm, but
483 # at least one user bumped into extreme use cases that exceeded
484 # the recursion limit on their box. So, now we maintain a list
485 # ('queue`) of blocks we still need to look at, and append partial
486 # results to `matching_blocks` in a loop; the matches are sorted
487 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000488 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000489 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000490 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000491 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000492 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000493 # a[alo:i] vs b[blo:j] unknown
494 # a[i:i+k] same as b[j:j+k]
495 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000496 if k: # if k is 0, there was no matching block
497 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000498 if alo < i and blo < j:
499 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000500 if i+k < ahi and j+k < bhi:
501 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000502 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000503
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000504 # It's possible that we have adjacent equal blocks in the
505 # matching_blocks list now. Starting with 2.5, this code was added
506 # to collapse them.
507 i1 = j1 = k1 = 0
508 non_adjacent = []
509 for i2, j2, k2 in matching_blocks:
510 # Is this block adjacent to i1, j1, k1?
511 if i1 + k1 == i2 and j1 + k1 == j2:
512 # Yes, so collapse them -- this just increases the length of
513 # the first block by the length of the second, and the first
514 # block so lengthened remains the block to compare against.
515 k1 += k2
516 else:
517 # Not adjacent. Remember the first block (k1==0 means it's
518 # the dummy we started with), and make the second block the
519 # new block to compare against.
520 if k1:
521 non_adjacent.append((i1, j1, k1))
522 i1, j1, k1 = i2, j2, k2
523 if k1:
524 non_adjacent.append((i1, j1, k1))
525
526 non_adjacent.append( (la, lb, 0) )
527 self.matching_blocks = non_adjacent
Christian Heimes25bb7832008-01-11 16:17:00 +0000528 return map(Match._make, self.matching_blocks)
Tim Peters9ae21482001-02-10 08:00:53 +0000529
Tim Peters9ae21482001-02-10 08:00:53 +0000530 def get_opcodes(self):
531 """Return list of 5-tuples describing how to turn a into b.
532
533 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
534 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
535 tuple preceding it, and likewise for j1 == the previous j2.
536
537 The tags are strings, with these meanings:
538
539 'replace': a[i1:i2] should be replaced by b[j1:j2]
540 'delete': a[i1:i2] should be deleted.
541 Note that j1==j2 in this case.
542 'insert': b[j1:j2] should be inserted at a[i1:i1].
543 Note that i1==i2 in this case.
544 'equal': a[i1:i2] == b[j1:j2]
545
546 >>> a = "qabxcd"
547 >>> b = "abycdf"
548 >>> s = SequenceMatcher(None, a, b)
549 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000550 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
551 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000552 delete a[0:1] (q) b[0:0] ()
553 equal a[1:3] (ab) b[0:2] (ab)
554 replace a[3:4] (x) b[2:3] (y)
555 equal a[4:6] (cd) b[3:5] (cd)
556 insert a[6:6] () b[5:6] (f)
557 """
558
559 if self.opcodes is not None:
560 return self.opcodes
561 i = j = 0
562 self.opcodes = answer = []
563 for ai, bj, size in self.get_matching_blocks():
564 # invariant: we've pumped out correct diffs to change
565 # a[:i] into b[:j], and the next matching block is
566 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
567 # out a diff to change a[i:ai] into b[j:bj], pump out
568 # the matching block, and move (i,j) beyond the match
569 tag = ''
570 if i < ai and j < bj:
571 tag = 'replace'
572 elif i < ai:
573 tag = 'delete'
574 elif j < bj:
575 tag = 'insert'
576 if tag:
577 answer.append( (tag, i, ai, j, bj) )
578 i, j = ai+size, bj+size
579 # the list of matching blocks is terminated by a
580 # sentinel with size 0
581 if size:
582 answer.append( ('equal', ai, i, bj, j) )
583 return answer
584
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000585 def get_grouped_opcodes(self, n=3):
586 """ Isolate change clusters by eliminating ranges with no changes.
587
588 Return a generator of groups with upto n lines of context.
589 Each group is in the same format as returned by get_opcodes().
590
591 >>> from pprint import pprint
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000592 >>> a = list(map(str, range(1,40)))
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000593 >>> b = a[:]
594 >>> b[8:8] = ['i'] # Make an insertion
595 >>> b[20] += 'x' # Make a replacement
596 >>> b[23:28] = [] # Make a deletion
597 >>> b[30] += 'y' # Make another replacement
598 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
599 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
600 [('equal', 16, 19, 17, 20),
601 ('replace', 19, 20, 20, 21),
602 ('equal', 20, 22, 21, 23),
603 ('delete', 22, 27, 23, 23),
604 ('equal', 27, 30, 23, 26)],
605 [('equal', 31, 34, 27, 30),
606 ('replace', 34, 35, 30, 31),
607 ('equal', 35, 38, 31, 34)]]
608 """
609
610 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000611 if not codes:
612 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000613 # Fixup leading and trailing groups if they show no changes.
614 if codes[0][0] == 'equal':
615 tag, i1, i2, j1, j2 = codes[0]
616 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
617 if codes[-1][0] == 'equal':
618 tag, i1, i2, j1, j2 = codes[-1]
619 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
620
621 nn = n + n
622 group = []
623 for tag, i1, i2, j1, j2 in codes:
624 # End the current group and start a new one whenever
625 # there is a large range with no changes.
626 if tag == 'equal' and i2-i1 > nn:
627 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
628 yield group
629 group = []
630 i1, j1 = max(i1, i2-n), max(j1, j2-n)
631 group.append((tag, i1, i2, j1 ,j2))
632 if group and not (len(group)==1 and group[0][0] == 'equal'):
633 yield group
634
Tim Peters9ae21482001-02-10 08:00:53 +0000635 def ratio(self):
636 """Return a measure of the sequences' similarity (float in [0,1]).
637
638 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000639 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000640 Note that this is 1 if the sequences are identical, and 0 if
641 they have nothing in common.
642
643 .ratio() is expensive to compute if you haven't already computed
644 .get_matching_blocks() or .get_opcodes(), in which case you may
645 want to try .quick_ratio() or .real_quick_ratio() first to get an
646 upper bound.
647
648 >>> s = SequenceMatcher(None, "abcd", "bcde")
649 >>> s.ratio()
650 0.75
651 >>> s.quick_ratio()
652 0.75
653 >>> s.real_quick_ratio()
654 1.0
655 """
656
Guido van Rossum89da5d72006-08-22 00:21:25 +0000657 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000658 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000659
660 def quick_ratio(self):
661 """Return an upper bound on ratio() relatively quickly.
662
663 This isn't defined beyond that it is an upper bound on .ratio(), and
664 is faster to compute.
665 """
666
667 # viewing a and b as multisets, set matches to the cardinality
668 # of their intersection; this counts the number of matches
669 # without regard to order, so is clearly an upper bound
670 if self.fullbcount is None:
671 self.fullbcount = fullbcount = {}
672 for elt in self.b:
673 fullbcount[elt] = fullbcount.get(elt, 0) + 1
674 fullbcount = self.fullbcount
675 # avail[x] is the number of times x appears in 'b' less the
676 # number of times we've seen it in 'a' so far ... kinda
677 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000678 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000679 for elt in self.a:
680 if availhas(elt):
681 numb = avail[elt]
682 else:
683 numb = fullbcount.get(elt, 0)
684 avail[elt] = numb - 1
685 if numb > 0:
686 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000687 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000688
689 def real_quick_ratio(self):
690 """Return an upper bound on ratio() very quickly.
691
692 This isn't defined beyond that it is an upper bound on .ratio(), and
693 is faster to compute than either .ratio() or .quick_ratio().
694 """
695
696 la, lb = len(self.a), len(self.b)
697 # can't have more matches than the number of elements in the
698 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000699 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000700
701def get_close_matches(word, possibilities, n=3, cutoff=0.6):
702 """Use SequenceMatcher to return list of the best "good enough" matches.
703
704 word is a sequence for which close matches are desired (typically a
705 string).
706
707 possibilities is a list of sequences against which to match word
708 (typically a list of strings).
709
710 Optional arg n (default 3) is the maximum number of close matches to
711 return. n must be > 0.
712
713 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
714 that don't score at least that similar to word are ignored.
715
716 The best (no more than n) matches among the possibilities are returned
717 in a list, sorted by similarity score, most similar first.
718
719 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
720 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000721 >>> import keyword as _keyword
722 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000723 ['while']
Guido van Rossum486364b2007-06-30 05:01:58 +0000724 >>> get_close_matches("Apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000725 []
Tim Peters5e824c32001-08-12 22:25:01 +0000726 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000727 ['except']
728 """
729
730 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000731 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000732 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000733 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000734 result = []
735 s = SequenceMatcher()
736 s.set_seq2(word)
737 for x in possibilities:
738 s.set_seq1(x)
739 if s.real_quick_ratio() >= cutoff and \
740 s.quick_ratio() >= cutoff and \
741 s.ratio() >= cutoff:
742 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000743
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000744 # Move the best scorers to head of list
Raymond Hettingeraefde432004-06-15 23:53:35 +0000745 result = heapq.nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000746 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000747 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000748
749def _count_leading(line, ch):
750 """
751 Return number of `ch` characters at the start of `line`.
752
753 Example:
754
755 >>> _count_leading(' abc', ' ')
756 3
757 """
758
759 i, n = 0, len(line)
760 while i < n and line[i] == ch:
761 i += 1
762 return i
763
764class Differ:
765 r"""
766 Differ is a class for comparing sequences of lines of text, and
767 producing human-readable differences or deltas. Differ uses
768 SequenceMatcher both to compare sequences of lines, and to compare
769 sequences of characters within similar (near-matching) lines.
770
771 Each line of a Differ delta begins with a two-letter code:
772
773 '- ' line unique to sequence 1
774 '+ ' line unique to sequence 2
775 ' ' line common to both sequences
776 '? ' line not present in either input sequence
777
778 Lines beginning with '? ' attempt to guide the eye to intraline
779 differences, and were not present in either input sequence. These lines
780 can be confusing if the sequences contain tab characters.
781
782 Note that Differ makes no claim to produce a *minimal* diff. To the
783 contrary, minimal diffs are often counter-intuitive, because they synch
784 up anywhere possible, sometimes accidental matches 100 pages apart.
785 Restricting synch points to contiguous matches preserves some notion of
786 locality, at the occasional cost of producing a longer diff.
787
788 Example: Comparing two texts.
789
790 First we set up the texts, sequences of individual single-line strings
791 ending with newlines (such sequences can also be obtained from the
792 `readlines()` method of file-like objects):
793
794 >>> text1 = ''' 1. Beautiful is better than ugly.
795 ... 2. Explicit is better than implicit.
796 ... 3. Simple is better than complex.
797 ... 4. Complex is better than complicated.
798 ... '''.splitlines(1)
799 >>> len(text1)
800 4
801 >>> text1[0][-1]
802 '\n'
803 >>> text2 = ''' 1. Beautiful is better than ugly.
804 ... 3. Simple is better than complex.
805 ... 4. Complicated is better than complex.
806 ... 5. Flat is better than nested.
807 ... '''.splitlines(1)
808
809 Next we instantiate a Differ object:
810
811 >>> d = Differ()
812
813 Note that when instantiating a Differ object we may pass functions to
814 filter out line and character 'junk'. See Differ.__init__ for details.
815
816 Finally, we compare the two:
817
Tim Peters8a9c2842001-09-22 21:30:22 +0000818 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000819
820 'result' is a list of strings, so let's pretty-print it:
821
822 >>> from pprint import pprint as _pprint
823 >>> _pprint(result)
824 [' 1. Beautiful is better than ugly.\n',
825 '- 2. Explicit is better than implicit.\n',
826 '- 3. Simple is better than complex.\n',
827 '+ 3. Simple is better than complex.\n',
828 '? ++\n',
829 '- 4. Complex is better than complicated.\n',
830 '? ^ ---- ^\n',
831 '+ 4. Complicated is better than complex.\n',
832 '? ++++ ^ ^\n',
833 '+ 5. Flat is better than nested.\n']
834
835 As a single multi-line string it looks like this:
836
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000837 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000838 1. Beautiful is better than ugly.
839 - 2. Explicit is better than implicit.
840 - 3. Simple is better than complex.
841 + 3. Simple is better than complex.
842 ? ++
843 - 4. Complex is better than complicated.
844 ? ^ ---- ^
845 + 4. Complicated is better than complex.
846 ? ++++ ^ ^
847 + 5. Flat is better than nested.
848
849 Methods:
850
851 __init__(linejunk=None, charjunk=None)
852 Construct a text differencer, with optional filters.
853
854 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000855 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000856 """
857
858 def __init__(self, linejunk=None, charjunk=None):
859 """
860 Construct a text differencer, with optional filters.
861
862 The two optional keyword parameters are for filter functions:
863
864 - `linejunk`: A function that should accept a single string argument,
865 and return true iff the string is junk. The module-level function
866 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000867 characters, except for at most one splat ('#'). It is recommended
868 to leave linejunk None; as of Python 2.3, the underlying
869 SequenceMatcher class has grown an adaptive notion of "noise" lines
870 that's better than any static definition the author has ever been
871 able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000872
873 - `charjunk`: A function that should accept a string of length 1. The
874 module-level function `IS_CHARACTER_JUNK` may be used to filter out
875 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000876 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000877 """
878
879 self.linejunk = linejunk
880 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000881
882 def compare(self, a, b):
883 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000884 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000885
886 Each sequence must contain individual single-line strings ending with
887 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000888 of file-like objects. The delta generated also consists of newline-
889 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000890 method of a file-like object.
891
892 Example:
893
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000894 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
Tim Peters5e824c32001-08-12 22:25:01 +0000895 ... 'ore\ntree\nemu\n'.splitlines(1))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000896 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000897 - one
898 ? ^
899 + ore
900 ? ^
901 - two
902 - three
903 ? -
904 + tree
905 + emu
906 """
907
908 cruncher = SequenceMatcher(self.linejunk, a, b)
909 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
910 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000911 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000912 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000913 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000914 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000915 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000916 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000917 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000918 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000919 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +0000920
921 for line in g:
922 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000923
924 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000925 """Generate comparison results for a same-tagged range."""
Guido van Rossum805365e2007-05-07 22:24:25 +0000926 for i in range(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000927 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000928
929 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
930 assert alo < ahi and blo < bhi
931 # dump the shorter block first -- reduces the burden on short-term
932 # memory if the blocks are of very different sizes
933 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000934 first = self._dump('+', b, blo, bhi)
935 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000936 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000937 first = self._dump('-', a, alo, ahi)
938 second = self._dump('+', b, blo, bhi)
939
940 for g in first, second:
941 for line in g:
942 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000943
944 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
945 r"""
946 When replacing one block of lines with another, search the blocks
947 for *similar* lines; the best-matching pair (if any) is used as a
948 synch point, and intraline difference marking is done on the
949 similar pair. Lots of work, but often worth it.
950
951 Example:
952
953 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000954 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
955 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000956 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000957 - abcDefghiJkl
958 ? ^ ^ ^
959 + abcdefGhijkl
960 ? ^ ^ ^
961 """
962
Tim Peters5e824c32001-08-12 22:25:01 +0000963 # don't synch up unless the lines have a similarity score of at
964 # least cutoff; best_ratio tracks the best score seen so far
965 best_ratio, cutoff = 0.74, 0.75
966 cruncher = SequenceMatcher(self.charjunk)
967 eqi, eqj = None, None # 1st indices of equal lines (if any)
968
969 # search for the pair that matches best without being identical
970 # (identical lines must be junk lines, & we don't want to synch up
971 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000972 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000973 bj = b[j]
974 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000975 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000976 ai = a[i]
977 if ai == bj:
978 if eqi is None:
979 eqi, eqj = i, j
980 continue
981 cruncher.set_seq1(ai)
982 # computing similarity is expensive, so use the quick
983 # upper bounds first -- have seen this speed up messy
984 # compares by a factor of 3.
985 # note that ratio() is only expensive to compute the first
986 # time it's called on a sequence pair; the expensive part
987 # of the computation is cached by cruncher
988 if cruncher.real_quick_ratio() > best_ratio and \
989 cruncher.quick_ratio() > best_ratio and \
990 cruncher.ratio() > best_ratio:
991 best_ratio, best_i, best_j = cruncher.ratio(), i, j
992 if best_ratio < cutoff:
993 # no non-identical "pretty close" pair
994 if eqi is None:
995 # no identical pair either -- treat it as a straight replace
Tim Peters8a9c2842001-09-22 21:30:22 +0000996 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
997 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000998 return
999 # no close pair, but an identical pair -- synch up on that
1000 best_i, best_j, best_ratio = eqi, eqj, 1.0
1001 else:
1002 # there's a close pair, so forget the identical pair (if any)
1003 eqi = None
1004
1005 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
1006 # identical
Tim Peters5e824c32001-08-12 22:25:01 +00001007
1008 # pump out diffs from before the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001009 for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
1010 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001011
1012 # do intraline marking on the synch pair
1013 aelt, belt = a[best_i], b[best_j]
1014 if eqi is None:
1015 # pump out a '-', '?', '+', '?' quad for the synched lines
1016 atags = btags = ""
1017 cruncher.set_seqs(aelt, belt)
1018 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1019 la, lb = ai2 - ai1, bj2 - bj1
1020 if tag == 'replace':
1021 atags += '^' * la
1022 btags += '^' * lb
1023 elif tag == 'delete':
1024 atags += '-' * la
1025 elif tag == 'insert':
1026 btags += '+' * lb
1027 elif tag == 'equal':
1028 atags += ' ' * la
1029 btags += ' ' * lb
1030 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001031 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +00001032 for line in self._qformat(aelt, belt, atags, btags):
1033 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001034 else:
1035 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001036 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001037
1038 # pump out diffs from after the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001039 for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
1040 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001041
1042 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001043 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001044 if alo < ahi:
1045 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001046 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001047 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001048 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001049 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001050 g = self._dump('+', b, blo, bhi)
1051
1052 for line in g:
1053 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001054
1055 def _qformat(self, aline, bline, atags, btags):
1056 r"""
1057 Format "?" output and deal with leading tabs.
1058
1059 Example:
1060
1061 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001062 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1063 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001064 >>> for line in results: print(repr(line))
1065 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001066 '- \tabcDefghiJkl\n'
1067 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001068 '+ \tabcdefGhijkl\n'
1069 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001070 """
1071
1072 # Can hurt, but will probably help most of the time.
1073 common = min(_count_leading(aline, "\t"),
1074 _count_leading(bline, "\t"))
1075 common = min(common, _count_leading(atags[:common], " "))
Senthil Kumaran758025c2009-11-23 19:02:52 +00001076 common = min(common, _count_leading(btags[:common], " "))
Tim Peters5e824c32001-08-12 22:25:01 +00001077 atags = atags[common:].rstrip()
1078 btags = btags[common:].rstrip()
1079
Tim Peters8a9c2842001-09-22 21:30:22 +00001080 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001081 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001082 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001083
Tim Peters8a9c2842001-09-22 21:30:22 +00001084 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001085 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001086 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001087
1088# With respect to junk, an earlier version of ndiff simply refused to
1089# *start* a match with a junk element. The result was cases like this:
1090# before: private Thread currentThread;
1091# after: private volatile Thread currentThread;
1092# If you consider whitespace to be junk, the longest contiguous match
1093# not starting with junk is "e Thread currentThread". So ndiff reported
1094# that "e volatil" was inserted between the 't' and the 'e' in "private".
1095# While an accurate view, to people that's absurd. The current version
1096# looks for matching blocks that are entirely junk-free, then extends the
1097# longest one of those as far as possible but only with matching junk.
1098# So now "currentThread" is matched, then extended to suck up the
1099# preceding blank; then "private" is matched, and extended to suck up the
1100# following blank; then "Thread" is matched; and finally ndiff reports
1101# that "volatile " was inserted before "Thread". The only quibble
1102# remaining is that perhaps it was really the case that " volatile"
1103# was inserted after "private". I can live with that <wink>.
1104
1105import re
1106
1107def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1108 r"""
1109 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1110
1111 Examples:
1112
1113 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001114 True
Tim Peters5e824c32001-08-12 22:25:01 +00001115 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001116 True
Tim Peters5e824c32001-08-12 22:25:01 +00001117 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001118 False
Tim Peters5e824c32001-08-12 22:25:01 +00001119 """
1120
1121 return pat(line) is not None
1122
1123def IS_CHARACTER_JUNK(ch, ws=" \t"):
1124 r"""
1125 Return 1 for ignorable character: iff `ch` is a space or tab.
1126
1127 Examples:
1128
1129 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001130 True
Tim Peters5e824c32001-08-12 22:25:01 +00001131 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001132 True
Tim Peters5e824c32001-08-12 22:25:01 +00001133 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001134 False
Tim Peters5e824c32001-08-12 22:25:01 +00001135 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001136 False
Tim Peters5e824c32001-08-12 22:25:01 +00001137 """
1138
1139 return ch in ws
1140
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001141
1142def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1143 tofiledate='', n=3, lineterm='\n'):
1144 r"""
1145 Compare two sequences of lines; generate the delta as a unified diff.
1146
1147 Unified diffs are a compact way of showing line changes and a few
1148 lines of context. The number of context lines is set by 'n' which
1149 defaults to three.
1150
Raymond Hettinger0887c732003-06-17 16:53:25 +00001151 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001152 created with a trailing newline. This is helpful so that inputs
1153 created from file.readlines() result in diffs that are suitable for
1154 file.writelines() since both the inputs and outputs have trailing
1155 newlines.
1156
1157 For inputs that do not have trailing newlines, set the lineterm
1158 argument to "" so that the output will be uniformly newline free.
1159
1160 The unidiff format normally has a header for filenames and modification
1161 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001162 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1163 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001164
1165 Example:
1166
1167 >>> for line in unified_diff('one two three four'.split(),
1168 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001169 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001170 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001171 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1172 --- Original 2005-01-26 23:30:50
1173 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001174 @@ -1,4 +1,4 @@
1175 +zero
1176 one
1177 -two
1178 -three
1179 +tree
1180 four
1181 """
1182
1183 started = False
1184 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1185 if not started:
R. David Murrayb2416e52010-04-12 16:58:02 +00001186 fromdate = '\t%s' % fromfiledate if fromfiledate else ''
1187 todate = '\t%s' % tofiledate if tofiledate else ''
1188 yield '--- %s%s%s' % (fromfile, fromdate, lineterm)
1189 yield '+++ %s%s%s' % (tofile, todate, lineterm)
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001190 started = True
1191 i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
1192 yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
1193 for tag, i1, i2, j1, j2 in group:
1194 if tag == 'equal':
1195 for line in a[i1:i2]:
1196 yield ' ' + line
1197 continue
1198 if tag == 'replace' or tag == 'delete':
1199 for line in a[i1:i2]:
1200 yield '-' + line
1201 if tag == 'replace' or tag == 'insert':
1202 for line in b[j1:j2]:
1203 yield '+' + line
1204
1205# See http://www.unix.org/single_unix_specification/
1206def context_diff(a, b, fromfile='', tofile='',
1207 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1208 r"""
1209 Compare two sequences of lines; generate the delta as a context diff.
1210
1211 Context diffs are a compact way of showing line changes and a few
1212 lines of context. The number of context lines is set by 'n' which
1213 defaults to three.
1214
1215 By default, the diff control lines (those with *** or ---) are
1216 created with a trailing newline. This is helpful so that inputs
1217 created from file.readlines() result in diffs that are suitable for
1218 file.writelines() since both the inputs and outputs have trailing
1219 newlines.
1220
1221 For inputs that do not have trailing newlines, set the lineterm
1222 argument to "" so that the output will be uniformly newline free.
1223
1224 The context diff format normally has a header for filenames and
1225 modification times. Any or all of these may be specified using
1226 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001227 The modification times are normally expressed in the ISO 8601 format.
1228 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001229
1230 Example:
1231
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001232 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
R. David Murrayb2416e52010-04-12 16:58:02 +00001233 ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001234 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001235 *** Original
1236 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001237 ***************
1238 *** 1,4 ****
1239 one
1240 ! two
1241 ! three
1242 four
1243 --- 1,4 ----
1244 + zero
1245 one
1246 ! tree
1247 four
1248 """
1249
1250 started = False
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001251 prefixmap = {'insert':'+ ', 'delete':'- ', 'replace':'! ', 'equal':' '}
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001252 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1253 if not started:
R. David Murrayb2416e52010-04-12 16:58:02 +00001254 fromdate = '\t%s' % fromfiledate if fromfiledate else ''
1255 todate = '\t%s' % tofiledate if tofiledate else ''
1256 yield '*** %s%s%s' % (fromfile, fromdate, lineterm)
1257 yield '--- %s%s%s' % (tofile, todate, lineterm)
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001258 started = True
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001259
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001260 yield '***************%s' % (lineterm,)
1261 if group[-1][2] - group[0][1] >= 2:
1262 yield '*** %d,%d ****%s' % (group[0][1]+1, group[-1][2], lineterm)
1263 else:
1264 yield '*** %d ****%s' % (group[-1][2], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001265 visiblechanges = [e for e in group if e[0] in ('replace', 'delete')]
1266 if visiblechanges:
1267 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001268 if tag != 'insert':
1269 for line in a[i1:i2]:
1270 yield prefixmap[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001271
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001272 if group[-1][4] - group[0][3] >= 2:
1273 yield '--- %d,%d ----%s' % (group[0][3]+1, group[-1][4], lineterm)
1274 else:
1275 yield '--- %d ----%s' % (group[-1][4], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001276 visiblechanges = [e for e in group if e[0] in ('replace', 'insert')]
1277 if visiblechanges:
1278 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001279 if tag != 'delete':
1280 for line in b[j1:j2]:
1281 yield prefixmap[tag] + line
1282
Tim Peters81b92512002-04-29 01:37:32 +00001283def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001284 r"""
1285 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1286
1287 Optional keyword parameters `linejunk` and `charjunk` are for filter
1288 functions (or None):
1289
1290 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001291 return true iff the string is junk. The default is None, and is
1292 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1293 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001294
1295 - charjunk: A function that should accept a string of length 1. The
1296 default is module-level function IS_CHARACTER_JUNK, which filters out
1297 whitespace characters (a blank or tab; note: bad idea to include newline
1298 in this!).
1299
1300 Tools/scripts/ndiff.py is a command-line front-end to this function.
1301
1302 Example:
1303
1304 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1305 ... 'ore\ntree\nemu\n'.splitlines(1))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001306 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001307 - one
1308 ? ^
1309 + ore
1310 ? ^
1311 - two
1312 - three
1313 ? -
1314 + tree
1315 + emu
1316 """
1317 return Differ(linejunk, charjunk).compare(a, b)
1318
Martin v. Löwise064b412004-08-29 16:34:40 +00001319def _mdiff(fromlines, tolines, context=None, linejunk=None,
1320 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001321 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001322
1323 Arguments:
1324 fromlines -- list of text lines to compared to tolines
1325 tolines -- list of text lines to be compared to fromlines
1326 context -- number of context lines to display on each side of difference,
1327 if None, all from/to text lines will be generated.
1328 linejunk -- passed on to ndiff (see ndiff documentation)
1329 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001330
Martin v. Löwise064b412004-08-29 16:34:40 +00001331 This function returns an interator which returns a tuple:
1332 (from line tuple, to line tuple, boolean flag)
1333
1334 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001335 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001336 line text -- original line text with following markers inserted:
1337 '\0+' -- marks start of added text
1338 '\0-' -- marks start of deleted text
1339 '\0^' -- marks start of changed text
1340 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001341
Martin v. Löwise064b412004-08-29 16:34:40 +00001342 boolean flag -- None indicates context separation, True indicates
1343 either "from" or "to" line contains a change, otherwise False.
1344
1345 This function/iterator was originally developed to generate side by side
1346 file difference for making HTML pages (see HtmlDiff class for example
1347 usage).
1348
1349 Note, this function utilizes the ndiff function to generate the side by
1350 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001351 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001352 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001353 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001354
1355 # regular expression for finding intraline change indices
1356 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001357
Martin v. Löwise064b412004-08-29 16:34:40 +00001358 # create the difference iterator to generate the differences
1359 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1360
1361 def _make_line(lines, format_key, side, num_lines=[0,0]):
1362 """Returns line of text with user's change markup and line formatting.
1363
1364 lines -- list of lines from the ndiff generator to produce a line of
1365 text from. When producing the line of text to return, the
1366 lines used are removed from this list.
1367 format_key -- '+' return first line in list with "add" markup around
1368 the entire line.
1369 '-' return first line in list with "delete" markup around
1370 the entire line.
1371 '?' return first line in list with add/delete/change
1372 intraline markup (indices obtained from second line)
1373 None return first line in list with no markup
1374 side -- indice into the num_lines list (0=from,1=to)
1375 num_lines -- from/to current line number. This is NOT intended to be a
1376 passed parameter. It is present as a keyword argument to
1377 maintain memory of the current line numbers between calls
1378 of this function.
1379
1380 Note, this function is purposefully not defined at the module scope so
1381 that data it needs from its parent function (within whose context it
1382 is defined) does not need to be of module scope.
1383 """
1384 num_lines[side] += 1
1385 # Handle case where no user markup is to be added, just return line of
1386 # text with user's line format to allow for usage of the line number.
1387 if format_key is None:
1388 return (num_lines[side],lines.pop(0)[2:])
1389 # Handle case of intraline changes
1390 if format_key == '?':
1391 text, markers = lines.pop(0), lines.pop(0)
1392 # find intraline changes (store change type and indices in tuples)
1393 sub_info = []
1394 def record_sub_info(match_object,sub_info=sub_info):
1395 sub_info.append([match_object.group(1)[0],match_object.span()])
1396 return match_object.group(1)
1397 change_re.sub(record_sub_info,markers)
1398 # process each tuple inserting our special marks that won't be
1399 # noticed by an xml/html escaper.
1400 for key,(begin,end) in sub_info[::-1]:
1401 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1402 text = text[2:]
1403 # Handle case of add/delete entire line
1404 else:
1405 text = lines.pop(0)[2:]
1406 # if line of text is just a newline, insert a space so there is
1407 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001408 if not text:
1409 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001410 # insert marks that won't be noticed by an xml/html escaper.
1411 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001412 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001413 # thing (such as adding the line number) then replace the special
1414 # marks with what the user's change markup.
1415 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001416
Martin v. Löwise064b412004-08-29 16:34:40 +00001417 def _line_iterator():
1418 """Yields from/to lines of text with a change indication.
1419
1420 This function is an iterator. It itself pulls lines from a
1421 differencing iterator, processes them and yields them. When it can
1422 it yields both a "from" and a "to" line, otherwise it will yield one
1423 or the other. In addition to yielding the lines of from/to text, a
1424 boolean flag is yielded to indicate if the text line(s) have
1425 differences in them.
1426
1427 Note, this function is purposefully not defined at the module scope so
1428 that data it needs from its parent function (within whose context it
1429 is defined) does not need to be of module scope.
1430 """
1431 lines = []
1432 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001433 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001434 # Load up next 4 lines so we can look ahead, create strings which
1435 # are a concatenation of the first character of each of the 4 lines
1436 # so we can do some very readable comparisons.
1437 while len(lines) < 4:
1438 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001439 lines.append(next(diff_lines_iterator))
Martin v. Löwise064b412004-08-29 16:34:40 +00001440 except StopIteration:
1441 lines.append('X')
1442 s = ''.join([line[0] for line in lines])
1443 if s.startswith('X'):
1444 # When no more lines, pump out any remaining blank lines so the
1445 # corresponding add/delete lines get a matching blank line so
1446 # all line pairs get yielded at the next level.
1447 num_blanks_to_yield = num_blanks_pending
1448 elif s.startswith('-?+?'):
1449 # simple intraline change
1450 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1451 continue
1452 elif s.startswith('--++'):
1453 # in delete block, add block coming: we do NOT want to get
1454 # caught up on blank lines yet, just process the delete line
1455 num_blanks_pending -= 1
1456 yield _make_line(lines,'-',0), None, True
1457 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001458 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001459 # in delete block and see a intraline change or unchanged line
1460 # coming: yield the delete line and then blanks
1461 from_line,to_line = _make_line(lines,'-',0), None
1462 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1463 elif s.startswith('-+?'):
1464 # intraline change
1465 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1466 continue
1467 elif s.startswith('-?+'):
1468 # intraline change
1469 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1470 continue
1471 elif s.startswith('-'):
1472 # delete FROM line
1473 num_blanks_pending -= 1
1474 yield _make_line(lines,'-',0), None, True
1475 continue
1476 elif s.startswith('+--'):
1477 # in add block, delete block coming: we do NOT want to get
1478 # caught up on blank lines yet, just process the add line
1479 num_blanks_pending += 1
1480 yield None, _make_line(lines,'+',1), True
1481 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001482 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001483 # will be leaving an add block: yield blanks then add line
1484 from_line, to_line = None, _make_line(lines,'+',1)
1485 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1486 elif s.startswith('+'):
1487 # inside an add block, yield the add line
1488 num_blanks_pending += 1
1489 yield None, _make_line(lines,'+',1), True
1490 continue
1491 elif s.startswith(' '):
1492 # unchanged text, yield it to both sides
1493 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1494 continue
1495 # Catch up on the blank lines so when we yield the next from/to
1496 # pair, they are lined up.
1497 while(num_blanks_to_yield < 0):
1498 num_blanks_to_yield += 1
1499 yield None,('','\n'),True
1500 while(num_blanks_to_yield > 0):
1501 num_blanks_to_yield -= 1
1502 yield ('','\n'),None,True
1503 if s.startswith('X'):
1504 raise StopIteration
1505 else:
1506 yield from_line,to_line,True
1507
1508 def _line_pair_iterator():
1509 """Yields from/to lines of text with a change indication.
1510
1511 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001512 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001513 always yields a pair of from/to text lines (with the change
1514 indication). If necessary it will collect single from/to lines
1515 until it has a matching pair from/to pair to yield.
1516
1517 Note, this function is purposefully not defined at the module scope so
1518 that data it needs from its parent function (within whose context it
1519 is defined) does not need to be of module scope.
1520 """
1521 line_iterator = _line_iterator()
1522 fromlines,tolines=[],[]
1523 while True:
1524 # Collecting lines of text until we have a from/to pair
1525 while (len(fromlines)==0 or len(tolines)==0):
Georg Brandla18af4e2007-04-21 15:47:16 +00001526 from_line, to_line, found_diff = next(line_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001527 if from_line is not None:
1528 fromlines.append((from_line,found_diff))
1529 if to_line is not None:
1530 tolines.append((to_line,found_diff))
1531 # Once we have a pair, remove them from the collection and yield it
1532 from_line, fromDiff = fromlines.pop(0)
1533 to_line, to_diff = tolines.pop(0)
1534 yield (from_line,to_line,fromDiff or to_diff)
1535
1536 # Handle case where user does not want context differencing, just yield
1537 # them up without doing anything else with them.
1538 line_pair_iterator = _line_pair_iterator()
1539 if context is None:
1540 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +00001541 yield next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001542 # Handle case where user wants context differencing. We must do some
1543 # storage of lines until we know for sure that they are to be yielded.
1544 else:
1545 context += 1
1546 lines_to_write = 0
1547 while True:
1548 # Store lines up until we find a difference, note use of a
1549 # circular queue because we only need to keep around what
1550 # we need for context.
1551 index, contextLines = 0, [None]*(context)
1552 found_diff = False
1553 while(found_diff is False):
Georg Brandla18af4e2007-04-21 15:47:16 +00001554 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001555 i = index % context
1556 contextLines[i] = (from_line, to_line, found_diff)
1557 index += 1
1558 # Yield lines that we have collected so far, but first yield
1559 # the user's separator.
1560 if index > context:
1561 yield None, None, None
1562 lines_to_write = context
1563 else:
1564 lines_to_write = index
1565 index = 0
1566 while(lines_to_write):
1567 i = index % context
1568 index += 1
1569 yield contextLines[i]
1570 lines_to_write -= 1
1571 # Now yield the context lines after the change
1572 lines_to_write = context-1
1573 while(lines_to_write):
Georg Brandla18af4e2007-04-21 15:47:16 +00001574 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001575 # If another change within the context, extend the context
1576 if found_diff:
1577 lines_to_write = context-1
1578 else:
1579 lines_to_write -= 1
1580 yield from_line, to_line, found_diff
1581
1582
1583_file_template = """
1584<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1585 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1586
1587<html>
1588
1589<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001590 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001591 content="text/html; charset=ISO-8859-1" />
1592 <title></title>
1593 <style type="text/css">%(styles)s
1594 </style>
1595</head>
1596
1597<body>
1598 %(table)s%(legend)s
1599</body>
1600
1601</html>"""
1602
1603_styles = """
1604 table.diff {font-family:Courier; border:medium;}
1605 .diff_header {background-color:#e0e0e0}
1606 td.diff_header {text-align:right}
1607 .diff_next {background-color:#c0c0c0}
1608 .diff_add {background-color:#aaffaa}
1609 .diff_chg {background-color:#ffff77}
1610 .diff_sub {background-color:#ffaaaa}"""
1611
1612_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001613 <table class="diff" id="difflib_chg_%(prefix)s_top"
1614 cellspacing="0" cellpadding="0" rules="groups" >
1615 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001616 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1617 %(header_row)s
1618 <tbody>
1619%(data_rows)s </tbody>
1620 </table>"""
1621
1622_legend = """
1623 <table class="diff" summary="Legends">
1624 <tr> <th colspan="2"> Legends </th> </tr>
1625 <tr> <td> <table border="" summary="Colors">
1626 <tr><th> Colors </th> </tr>
1627 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1628 <tr><td class="diff_chg">Changed</td> </tr>
1629 <tr><td class="diff_sub">Deleted</td> </tr>
1630 </table></td>
1631 <td> <table border="" summary="Links">
1632 <tr><th colspan="2"> Links </th> </tr>
1633 <tr><td>(f)irst change</td> </tr>
1634 <tr><td>(n)ext change</td> </tr>
1635 <tr><td>(t)op</td> </tr>
1636 </table></td> </tr>
1637 </table>"""
1638
1639class HtmlDiff(object):
1640 """For producing HTML side by side comparison with change highlights.
1641
1642 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001643 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001644 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001645 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001646
Martin v. Löwise064b412004-08-29 16:34:40 +00001647 The following methods are provided for HTML generation:
1648
1649 make_table -- generates HTML for a single side by side table
1650 make_file -- generates complete HTML file with a single side by side table
1651
Tim Peters48bd7f32004-08-29 22:38:38 +00001652 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001653 """
1654
1655 _file_template = _file_template
1656 _styles = _styles
1657 _table_template = _table_template
1658 _legend = _legend
1659 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001660
Martin v. Löwise064b412004-08-29 16:34:40 +00001661 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1662 charjunk=IS_CHARACTER_JUNK):
1663 """HtmlDiff instance initializer
1664
1665 Arguments:
1666 tabsize -- tab stop spacing, defaults to 8.
1667 wrapcolumn -- column number where lines are broken and wrapped,
1668 defaults to None where lines are not wrapped.
1669 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001670 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001671 ndiff() documentation for argument default values and descriptions.
1672 """
1673 self._tabsize = tabsize
1674 self._wrapcolumn = wrapcolumn
1675 self._linejunk = linejunk
1676 self._charjunk = charjunk
1677
1678 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1679 numlines=5):
1680 """Returns HTML file of side by side comparison with change highlights
1681
1682 Arguments:
1683 fromlines -- list of "from" lines
1684 tolines -- list of "to" lines
1685 fromdesc -- "from" file column header string
1686 todesc -- "to" file column header string
1687 context -- set to True for contextual differences (defaults to False
1688 which shows full differences).
1689 numlines -- number of context lines. When context is set True,
1690 controls number of lines displayed before and after the change.
1691 When context is False, controls the number of lines to place
1692 the "next" link anchors before the next change (so click of
1693 "next" link jumps to just before the change).
1694 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001695
Martin v. Löwise064b412004-08-29 16:34:40 +00001696 return self._file_template % dict(
1697 styles = self._styles,
1698 legend = self._legend,
1699 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1700 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001701
Martin v. Löwise064b412004-08-29 16:34:40 +00001702 def _tab_newline_replace(self,fromlines,tolines):
1703 """Returns from/to line lists with tabs expanded and newlines removed.
1704
1705 Instead of tab characters being replaced by the number of spaces
1706 needed to fill in to the next tab stop, this function will fill
1707 the space with tab characters. This is done so that the difference
1708 algorithms can identify changes in a file when tabs are replaced by
1709 spaces and vice versa. At the end of the HTML generation, the tab
1710 characters will be replaced with a nonbreakable space.
1711 """
1712 def expand_tabs(line):
1713 # hide real spaces
1714 line = line.replace(' ','\0')
1715 # expand tabs into spaces
1716 line = line.expandtabs(self._tabsize)
1717 # relace spaces from expanded tabs back into tab characters
1718 # (we'll replace them with markup after we do differencing)
1719 line = line.replace(' ','\t')
1720 return line.replace('\0',' ').rstrip('\n')
1721 fromlines = [expand_tabs(line) for line in fromlines]
1722 tolines = [expand_tabs(line) for line in tolines]
1723 return fromlines,tolines
1724
1725 def _split_line(self,data_list,line_num,text):
1726 """Builds list of text lines by splitting text lines at wrap point
1727
1728 This function will determine if the input text line needs to be
1729 wrapped (split) into separate lines. If so, the first wrap point
1730 will be determined and the first line appended to the output
1731 text line list. This function is used recursively to handle
1732 the second part of the split line to further split it.
1733 """
1734 # if blank line or context separator, just add it to the output list
1735 if not line_num:
1736 data_list.append((line_num,text))
1737 return
1738
1739 # if line text doesn't need wrapping, just add it to the output list
1740 size = len(text)
1741 max = self._wrapcolumn
1742 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1743 data_list.append((line_num,text))
1744 return
1745
1746 # scan text looking for the wrap point, keeping track if the wrap
1747 # point is inside markers
1748 i = 0
1749 n = 0
1750 mark = ''
1751 while n < max and i < size:
1752 if text[i] == '\0':
1753 i += 1
1754 mark = text[i]
1755 i += 1
1756 elif text[i] == '\1':
1757 i += 1
1758 mark = ''
1759 else:
1760 i += 1
1761 n += 1
1762
1763 # wrap point is inside text, break it up into separate lines
1764 line1 = text[:i]
1765 line2 = text[i:]
1766
1767 # if wrap point is inside markers, place end marker at end of first
1768 # line and start marker at beginning of second line because each
1769 # line will have its own table tag markup around it.
1770 if mark:
1771 line1 = line1 + '\1'
1772 line2 = '\0' + mark + line2
1773
Tim Peters48bd7f32004-08-29 22:38:38 +00001774 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001775 data_list.append((line_num,line1))
1776
Tim Peters48bd7f32004-08-29 22:38:38 +00001777 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001778 self._split_line(data_list,'>',line2)
1779
1780 def _line_wrapper(self,diffs):
1781 """Returns iterator that splits (wraps) mdiff text lines"""
1782
1783 # pull from/to data and flags from mdiff iterator
1784 for fromdata,todata,flag in diffs:
1785 # check for context separators and pass them through
1786 if flag is None:
1787 yield fromdata,todata,flag
1788 continue
1789 (fromline,fromtext),(toline,totext) = fromdata,todata
1790 # for each from/to line split it at the wrap column to form
1791 # list of text lines.
1792 fromlist,tolist = [],[]
1793 self._split_line(fromlist,fromline,fromtext)
1794 self._split_line(tolist,toline,totext)
1795 # yield from/to line in pairs inserting blank lines as
1796 # necessary when one side has more wrapped lines
1797 while fromlist or tolist:
1798 if fromlist:
1799 fromdata = fromlist.pop(0)
1800 else:
1801 fromdata = ('',' ')
1802 if tolist:
1803 todata = tolist.pop(0)
1804 else:
1805 todata = ('',' ')
1806 yield fromdata,todata,flag
1807
1808 def _collect_lines(self,diffs):
1809 """Collects mdiff output into separate lists
1810
1811 Before storing the mdiff from/to data into a list, it is converted
1812 into a single line of text with HTML markup.
1813 """
1814
1815 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001816 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001817 for fromdata,todata,flag in diffs:
1818 try:
1819 # store HTML markup of the lines into the lists
1820 fromlist.append(self._format_line(0,flag,*fromdata))
1821 tolist.append(self._format_line(1,flag,*todata))
1822 except TypeError:
1823 # exceptions occur for lines where context separators go
1824 fromlist.append(None)
1825 tolist.append(None)
1826 flaglist.append(flag)
1827 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001828
Martin v. Löwise064b412004-08-29 16:34:40 +00001829 def _format_line(self,side,flag,linenum,text):
1830 """Returns HTML markup of "from" / "to" text lines
1831
1832 side -- 0 or 1 indicating "from" or "to" text
1833 flag -- indicates if difference on line
1834 linenum -- line number (used for line number column)
1835 text -- line text to be marked up
1836 """
1837 try:
1838 linenum = '%d' % linenum
1839 id = ' id="%s%s"' % (self._prefix[side],linenum)
1840 except TypeError:
1841 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001842 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001843 # replace those things that would get confused with HTML symbols
1844 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1845
1846 # make space non-breakable so they don't get compressed or line wrapped
1847 text = text.replace(' ','&nbsp;').rstrip()
1848
1849 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1850 % (id,linenum,text)
1851
1852 def _make_prefix(self):
1853 """Create unique anchor prefixes"""
1854
1855 # Generate a unique anchor prefix so multiple tables
1856 # can exist on the same HTML page without conflicts.
1857 fromprefix = "from%d_" % HtmlDiff._default_prefix
1858 toprefix = "to%d_" % HtmlDiff._default_prefix
1859 HtmlDiff._default_prefix += 1
1860 # store prefixes so line format method has access
1861 self._prefix = [fromprefix,toprefix]
1862
1863 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1864 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001865
Martin v. Löwise064b412004-08-29 16:34:40 +00001866 # all anchor names will be generated using the unique "to" prefix
1867 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001868
Martin v. Löwise064b412004-08-29 16:34:40 +00001869 # process change flags, generating middle column of next anchors/links
1870 next_id = ['']*len(flaglist)
1871 next_href = ['']*len(flaglist)
1872 num_chg, in_change = 0, False
1873 last = 0
1874 for i,flag in enumerate(flaglist):
1875 if flag:
1876 if not in_change:
1877 in_change = True
1878 last = i
1879 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001880 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001881 # link
1882 i = max([0,i-numlines])
1883 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001884 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001885 # change
1886 num_chg += 1
1887 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1888 toprefix,num_chg)
1889 else:
1890 in_change = False
1891 # check for cases where there is no content to avoid exceptions
1892 if not flaglist:
1893 flaglist = [False]
1894 next_id = ['']
1895 next_href = ['']
1896 last = 0
1897 if context:
1898 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1899 tolist = fromlist
1900 else:
1901 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1902 # if not a change on first line, drop a link
1903 if not flaglist[0]:
1904 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1905 # redo the last link to link to the top
1906 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1907
1908 return fromlist,tolist,flaglist,next_href,next_id
1909
1910 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1911 numlines=5):
1912 """Returns HTML table of side by side comparison with change highlights
1913
1914 Arguments:
1915 fromlines -- list of "from" lines
1916 tolines -- list of "to" lines
1917 fromdesc -- "from" file column header string
1918 todesc -- "to" file column header string
1919 context -- set to True for contextual differences (defaults to False
1920 which shows full differences).
1921 numlines -- number of context lines. When context is set True,
1922 controls number of lines displayed before and after the change.
1923 When context is False, controls the number of lines to place
1924 the "next" link anchors before the next change (so click of
1925 "next" link jumps to just before the change).
1926 """
1927
1928 # make unique anchor prefixes so that multiple tables may exist
1929 # on the same page without conflict.
1930 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001931
Martin v. Löwise064b412004-08-29 16:34:40 +00001932 # change tabs to spaces before it gets more difficult after we insert
1933 # markkup
1934 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001935
Martin v. Löwise064b412004-08-29 16:34:40 +00001936 # create diffs iterator which generates side by side from/to data
1937 if context:
1938 context_lines = numlines
1939 else:
1940 context_lines = None
1941 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1942 charjunk=self._charjunk)
1943
1944 # set up iterator to wrap lines that exceed desired width
1945 if self._wrapcolumn:
1946 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001947
Martin v. Löwise064b412004-08-29 16:34:40 +00001948 # collect up from/to lines and flags into lists (also format the lines)
1949 fromlist,tolist,flaglist = self._collect_lines(diffs)
1950
1951 # process change flags, generating middle column of next anchors/links
1952 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1953 fromlist,tolist,flaglist,context,numlines)
1954
Guido van Rossumd8faa362007-04-27 19:54:29 +00001955 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00001956 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1957 '<td class="diff_next">%s</td>%s</tr>\n'
1958 for i in range(len(flaglist)):
1959 if flaglist[i] is None:
1960 # mdiff yields None on separator lines skip the bogus ones
1961 # generated for the first line
1962 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001963 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00001964 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001965 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00001966 next_href[i],tolist[i]))
1967 if fromdesc or todesc:
1968 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
1969 '<th class="diff_next"><br /></th>',
1970 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
1971 '<th class="diff_next"><br /></th>',
1972 '<th colspan="2" class="diff_header">%s</th>' % todesc)
1973 else:
1974 header_row = ''
1975
1976 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00001977 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00001978 header_row=header_row,
1979 prefix=self._prefix[1])
1980
1981 return table.replace('\0+','<span class="diff_add">'). \
1982 replace('\0-','<span class="diff_sub">'). \
1983 replace('\0^','<span class="diff_chg">'). \
1984 replace('\1','</span>'). \
1985 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00001986
Martin v. Löwise064b412004-08-29 16:34:40 +00001987del re
1988
Tim Peters5e824c32001-08-12 22:25:01 +00001989def restore(delta, which):
1990 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00001991 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00001992
1993 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
1994 lines originating from file 1 or 2 (parameter `which`), stripping off line
1995 prefixes.
1996
1997 Examples:
1998
1999 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
2000 ... 'ore\ntree\nemu\n'.splitlines(1))
Tim Peters8a9c2842001-09-22 21:30:22 +00002001 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002002 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002003 one
2004 two
2005 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002006 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002007 ore
2008 tree
2009 emu
2010 """
2011 try:
2012 tag = {1: "- ", 2: "+ "}[int(which)]
2013 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002014 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Tim Peters5e824c32001-08-12 22:25:01 +00002015 % which)
2016 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002017 for line in delta:
2018 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002019 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002020
Tim Peters9ae21482001-02-10 08:00:53 +00002021def _test():
2022 import doctest, difflib
2023 return doctest.testmod(difflib)
2024
2025if __name__ == "__main__":
2026 _test()