blob: f2d13436b14310eb061962740d5817e5bed5da95 [file] [log] [blame]
Tim Peters9ae21482001-02-10 08:00:53 +00001#! /usr/bin/env python
2
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',
Martin v. Löwise064b412004-08-29 16:34:40 +000033 'unified_diff', 'HtmlDiff']
Tim Peters5e824c32001-08-12 22:25:01 +000034
Raymond Hettingerbb6b7342004-06-13 09:57:33 +000035import heapq
36
Neal Norwitze7dfe212003-07-01 14:59:46 +000037def _calculate_ratio(matches, length):
38 if length:
39 return 2.0 * matches / length
40 return 1.0
41
Tim Peters9ae21482001-02-10 08:00:53 +000042class SequenceMatcher:
Tim Peters5e824c32001-08-12 22:25:01 +000043
44 """
45 SequenceMatcher is a flexible class for comparing pairs of sequences of
46 any type, so long as the sequence elements are hashable. The basic
47 algorithm predates, and is a little fancier than, an algorithm
48 published in the late 1980's by Ratcliff and Obershelp under the
49 hyperbolic name "gestalt pattern matching". The basic idea is to find
50 the longest contiguous matching subsequence that contains no "junk"
51 elements (R-O doesn't address junk). The same idea is then applied
52 recursively to the pieces of the sequences to the left and to the right
53 of the matching subsequence. This does not yield minimal edit
54 sequences, but does tend to yield matches that "look right" to people.
55
56 SequenceMatcher tries to compute a "human-friendly diff" between two
57 sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
58 longest *contiguous* & junk-free matching subsequence. That's what
59 catches peoples' eyes. The Windows(tm) windiff has another interesting
60 notion, pairing up elements that appear uniquely in each sequence.
61 That, and the method here, appear to yield more intuitive difference
62 reports than does diff. This method appears to be the least vulnerable
63 to synching up on blocks of "junk lines", though (like blank lines in
64 ordinary text files, or maybe "<P>" lines in HTML files). That may be
65 because this is the only method of the 3 that has a *concept* of
66 "junk" <wink>.
67
68 Example, comparing two strings, and considering blanks to be "junk":
69
70 >>> s = SequenceMatcher(lambda x: x == " ",
71 ... "private Thread currentThread;",
72 ... "private volatile Thread currentThread;")
73 >>>
74
75 .ratio() returns a float in [0, 1], measuring the "similarity" of the
76 sequences. As a rule of thumb, a .ratio() value over 0.6 means the
77 sequences are close matches:
78
Guido van Rossumfff80df2007-02-09 20:33:44 +000079 >>> print(round(s.ratio(), 3))
Tim Peters5e824c32001-08-12 22:25:01 +000080 0.866
81 >>>
82
83 If you're only interested in where the sequences match,
84 .get_matching_blocks() is handy:
85
86 >>> for block in s.get_matching_blocks():
Guido van Rossumfff80df2007-02-09 20:33:44 +000087 ... print("a[%d] and b[%d] match for %d elements" % block)
Tim Peters5e824c32001-08-12 22:25:01 +000088 a[0] and b[0] match for 8 elements
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089 a[8] and b[17] match for 21 elements
Tim Peters5e824c32001-08-12 22:25:01 +000090 a[29] and b[38] match for 0 elements
91
92 Note that the last tuple returned by .get_matching_blocks() is always a
93 dummy, (len(a), len(b), 0), and this is the only case in which the last
94 tuple element (number of elements matched) is 0.
95
96 If you want to know how to change the first sequence into the second,
97 use .get_opcodes():
98
99 >>> for opcode in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000100 ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
Tim Peters5e824c32001-08-12 22:25:01 +0000101 equal a[0:8] b[0:8]
102 insert a[8:8] b[8:17]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000103 equal a[8:29] b[17:38]
Tim Peters5e824c32001-08-12 22:25:01 +0000104
105 See the Differ class for a fancy human-friendly file differencer, which
106 uses SequenceMatcher both to compare sequences of lines, and to compare
107 sequences of characters within similar (near-matching) lines.
108
109 See also function get_close_matches() in this module, which shows how
110 simple code building on SequenceMatcher can be used to do useful work.
111
112 Timing: Basic R-O is cubic time worst case and quadratic time expected
113 case. SequenceMatcher is quadratic time for the worst case and has
114 expected-case behavior dependent in a complicated way on how many
115 elements the sequences have in common; best case time is linear.
116
117 Methods:
118
119 __init__(isjunk=None, a='', b='')
120 Construct a SequenceMatcher.
121
122 set_seqs(a, b)
123 Set the two sequences to be compared.
124
125 set_seq1(a)
126 Set the first sequence to be compared.
127
128 set_seq2(b)
129 Set the second sequence to be compared.
130
131 find_longest_match(alo, ahi, blo, bhi)
132 Find longest matching block in a[alo:ahi] and b[blo:bhi].
133
134 get_matching_blocks()
135 Return list of triples describing matching subsequences.
136
137 get_opcodes()
138 Return list of 5-tuples describing how to turn a into b.
139
140 ratio()
141 Return a measure of the sequences' similarity (float in [0,1]).
142
143 quick_ratio()
144 Return an upper bound on .ratio() relatively quickly.
145
146 real_quick_ratio()
147 Return an upper bound on ratio() very quickly.
148 """
149
Tim Peters9ae21482001-02-10 08:00:53 +0000150 def __init__(self, isjunk=None, a='', b=''):
151 """Construct a SequenceMatcher.
152
153 Optional arg isjunk is None (the default), or a one-argument
154 function that takes a sequence element and returns true iff the
Tim Peters5e824c32001-08-12 22:25:01 +0000155 element is junk. None is equivalent to passing "lambda x: 0", i.e.
Fred Drakef1da6282001-02-19 19:30:05 +0000156 no elements are considered to be junk. For example, pass
Tim Peters9ae21482001-02-10 08:00:53 +0000157 lambda x: x in " \\t"
158 if you're comparing lines as sequences of characters, and don't
159 want to synch up on blanks or hard tabs.
160
161 Optional arg a is the first of two sequences to be compared. By
162 default, an empty string. The elements of a must be hashable. See
163 also .set_seqs() and .set_seq1().
164
165 Optional arg b is the second of two sequences to be compared. By
Fred Drakef1da6282001-02-19 19:30:05 +0000166 default, an empty string. The elements of b must be hashable. See
Tim Peters9ae21482001-02-10 08:00:53 +0000167 also .set_seqs() and .set_seq2().
168 """
169
170 # Members:
171 # a
172 # first sequence
173 # b
174 # second sequence; differences are computed as "what do
175 # we need to do to 'a' to change it into 'b'?"
176 # b2j
177 # for x in b, b2j[x] is a list of the indices (into b)
178 # at which x appears; junk elements do not appear
Tim Peters9ae21482001-02-10 08:00:53 +0000179 # fullbcount
180 # for x in b, fullbcount[x] == the number of times x
181 # appears in b; only materialized if really needed (used
182 # only for computing quick_ratio())
183 # matching_blocks
184 # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
185 # ascending & non-overlapping in i and in j; terminated by
186 # a dummy (len(a), len(b), 0) sentinel
187 # opcodes
188 # a list of (tag, i1, i2, j1, j2) tuples, where tag is
189 # one of
190 # 'replace' a[i1:i2] should be replaced by b[j1:j2]
191 # 'delete' a[i1:i2] should be deleted
192 # 'insert' b[j1:j2] should be inserted
193 # 'equal' a[i1:i2] == b[j1:j2]
194 # isjunk
195 # a user-supplied function taking a sequence element and
196 # returning true iff the element is "junk" -- this has
197 # subtle but helpful effects on the algorithm, which I'll
198 # get around to writing up someday <0.9 wink>.
199 # DON'T USE! Only __chain_b uses this. Use isbjunk.
200 # isbjunk
201 # for x in b, isbjunk(x) == isjunk(x) but much faster;
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000202 # it's really the __contains__ method of a hidden dict.
Tim Peters9ae21482001-02-10 08:00:53 +0000203 # DOES NOT WORK for x in a!
Tim Peters81b92512002-04-29 01:37:32 +0000204 # isbpopular
205 # for x in b, isbpopular(x) is true iff b is reasonably long
206 # (at least 200 elements) and x accounts for more than 1% of
207 # its elements. DOES NOT WORK for x in a!
Tim Peters9ae21482001-02-10 08:00:53 +0000208
209 self.isjunk = isjunk
210 self.a = self.b = None
211 self.set_seqs(a, b)
212
213 def set_seqs(self, a, b):
214 """Set the two sequences to be compared.
215
216 >>> s = SequenceMatcher()
217 >>> s.set_seqs("abcd", "bcde")
218 >>> s.ratio()
219 0.75
220 """
221
222 self.set_seq1(a)
223 self.set_seq2(b)
224
225 def set_seq1(self, a):
226 """Set the first sequence to be compared.
227
228 The second sequence to be compared is not changed.
229
230 >>> s = SequenceMatcher(None, "abcd", "bcde")
231 >>> s.ratio()
232 0.75
233 >>> s.set_seq1("bcde")
234 >>> s.ratio()
235 1.0
236 >>>
237
238 SequenceMatcher computes and caches detailed information about the
239 second sequence, so if you want to compare one sequence S against
240 many sequences, use .set_seq2(S) once and call .set_seq1(x)
241 repeatedly for each of the other sequences.
242
243 See also set_seqs() and set_seq2().
244 """
245
246 if a is self.a:
247 return
248 self.a = a
249 self.matching_blocks = self.opcodes = None
250
251 def set_seq2(self, b):
252 """Set the second sequence to be compared.
253
254 The first sequence to be compared is not changed.
255
256 >>> s = SequenceMatcher(None, "abcd", "bcde")
257 >>> s.ratio()
258 0.75
259 >>> s.set_seq2("abcd")
260 >>> s.ratio()
261 1.0
262 >>>
263
264 SequenceMatcher computes and caches detailed information about the
265 second sequence, so if you want to compare one sequence S against
266 many sequences, use .set_seq2(S) once and call .set_seq1(x)
267 repeatedly for each of the other sequences.
268
269 See also set_seqs() and set_seq1().
270 """
271
272 if b is self.b:
273 return
274 self.b = b
275 self.matching_blocks = self.opcodes = None
276 self.fullbcount = None
277 self.__chain_b()
278
279 # For each element x in b, set b2j[x] to a list of the indices in
280 # b where x appears; the indices are in increasing order; note that
281 # the number of times x appears in b is len(b2j[x]) ...
282 # when self.isjunk is defined, junk elements don't show up in this
283 # map at all, which stops the central find_longest_match method
284 # from starting any matching block at a junk element ...
285 # also creates the fast isbjunk function ...
Tim Peters81b92512002-04-29 01:37:32 +0000286 # b2j also does not contain entries for "popular" elements, meaning
287 # elements that account for more than 1% of the total elements, and
288 # when the sequence is reasonably large (>= 200 elements); this can
289 # be viewed as an adaptive notion of semi-junk, and yields an enormous
290 # speedup when, e.g., comparing program files with hundreds of
291 # instances of "return NULL;" ...
Tim Peters9ae21482001-02-10 08:00:53 +0000292 # note that this is only called when b changes; so for cross-product
293 # kinds of matches, it's best to call set_seq2 once, then set_seq1
294 # repeatedly
295
296 def __chain_b(self):
297 # Because isjunk is a user-defined (not C) function, and we test
298 # for junk a LOT, it's important to minimize the number of calls.
299 # Before the tricks described here, __chain_b was by far the most
300 # time-consuming routine in the whole module! If anyone sees
301 # Jim Roskind, thank him again for profile.py -- I never would
302 # have guessed that.
303 # The first trick is to build b2j ignoring the possibility
304 # of junk. I.e., we don't call isjunk at all yet. Throwing
305 # out the junk later is much cheaper than building b2j "right"
306 # from the start.
307 b = self.b
Tim Peters81b92512002-04-29 01:37:32 +0000308 n = len(b)
Tim Peters9ae21482001-02-10 08:00:53 +0000309 self.b2j = b2j = {}
Tim Peters81b92512002-04-29 01:37:32 +0000310 populardict = {}
311 for i, elt in enumerate(b):
312 if elt in b2j:
313 indices = b2j[elt]
314 if n >= 200 and len(indices) * 100 > n:
315 populardict[elt] = 1
316 del indices[:]
317 else:
318 indices.append(i)
Tim Peters9ae21482001-02-10 08:00:53 +0000319 else:
320 b2j[elt] = [i]
321
Tim Peters81b92512002-04-29 01:37:32 +0000322 # Purge leftover indices for popular elements.
323 for elt in populardict:
324 del b2j[elt]
325
Tim Peters9ae21482001-02-10 08:00:53 +0000326 # Now b2j.keys() contains elements uniquely, and especially when
327 # the sequence is a string, that's usually a good deal smaller
328 # than len(string). The difference is the number of isjunk calls
329 # saved.
Tim Peters81b92512002-04-29 01:37:32 +0000330 isjunk = self.isjunk
331 junkdict = {}
Tim Peters9ae21482001-02-10 08:00:53 +0000332 if isjunk:
Tim Peters81b92512002-04-29 01:37:32 +0000333 for d in populardict, b2j:
334 for elt in d.keys():
335 if isjunk(elt):
336 junkdict[elt] = 1
337 del d[elt]
Tim Peters9ae21482001-02-10 08:00:53 +0000338
Raymond Hettinger54f02222002-06-01 14:18:47 +0000339 # Now for x in b, isjunk(x) == x in junkdict, but the
Tim Peters9ae21482001-02-10 08:00:53 +0000340 # latter is much faster. Note too that while there may be a
341 # lot of junk in the sequence, the number of *unique* junk
342 # elements is probably small. So the memory burden of keeping
343 # this dict alive is likely trivial compared to the size of b2j.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000344 self.isbjunk = junkdict.__contains__
345 self.isbpopular = populardict.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000346
347 def find_longest_match(self, alo, ahi, blo, bhi):
348 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
349
350 If isjunk is not defined:
351
352 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
353 alo <= i <= i+k <= ahi
354 blo <= j <= j+k <= bhi
355 and for all (i',j',k') meeting those conditions,
356 k >= k'
357 i <= i'
358 and if i == i', j <= j'
359
360 In other words, of all maximal matching blocks, return one that
361 starts earliest in a, and of all those maximal matching blocks that
362 start earliest in a, return the one that starts earliest in b.
363
364 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
365 >>> s.find_longest_match(0, 5, 0, 9)
366 (0, 4, 5)
367
368 If isjunk is defined, first the longest matching block is
369 determined as above, but with the additional restriction that no
370 junk element appears in the block. Then that block is extended as
371 far as possible by matching (only) junk elements on both sides. So
372 the resulting block never matches on junk except as identical junk
373 happens to be adjacent to an "interesting" match.
374
375 Here's the same example as before, but considering blanks to be
376 junk. That prevents " abcd" from matching the " abcd" at the tail
377 end of the second sequence directly. Instead only the "abcd" can
378 match, and matches the leftmost "abcd" in the second sequence:
379
380 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
381 >>> s.find_longest_match(0, 5, 0, 9)
382 (1, 0, 4)
383
384 If no blocks match, return (alo, blo, 0).
385
386 >>> s = SequenceMatcher(None, "ab", "c")
387 >>> s.find_longest_match(0, 2, 0, 1)
388 (0, 0, 0)
389 """
390
391 # CAUTION: stripping common prefix or suffix would be incorrect.
392 # E.g.,
393 # ab
394 # acab
395 # Longest matching block is "ab", but if common prefix is
396 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
397 # strip, so ends up claiming that ab is changed to acab by
398 # inserting "ca" in the middle. That's minimal but unintuitive:
399 # "it's obvious" that someone inserted "ac" at the front.
400 # Windiff ends up at the same place as diff, but by pairing up
401 # the unique 'b's and then matching the first two 'a's.
402
403 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
404 besti, bestj, bestsize = alo, blo, 0
405 # find longest junk-free match
406 # during an iteration of the loop, j2len[j] = length of longest
407 # junk-free match ending with a[i-1] and b[j]
408 j2len = {}
409 nothing = []
410 for i in xrange(alo, ahi):
411 # look at all instances of a[i] in b; note that because
412 # b2j has no junk keys, the loop is skipped if a[i] is junk
413 j2lenget = j2len.get
414 newj2len = {}
415 for j in b2j.get(a[i], nothing):
416 # a[i] matches b[j]
417 if j < blo:
418 continue
419 if j >= bhi:
420 break
421 k = newj2len[j] = j2lenget(j-1, 0) + 1
422 if k > bestsize:
423 besti, bestj, bestsize = i-k+1, j-k+1, k
424 j2len = newj2len
425
Tim Peters81b92512002-04-29 01:37:32 +0000426 # Extend the best by non-junk elements on each end. In particular,
427 # "popular" non-junk elements aren't in b2j, which greatly speeds
428 # the inner loop above, but also means "the best" match so far
429 # doesn't contain any junk *or* popular non-junk elements.
430 while besti > alo and bestj > blo and \
431 not isbjunk(b[bestj-1]) and \
432 a[besti-1] == b[bestj-1]:
433 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
434 while besti+bestsize < ahi and bestj+bestsize < bhi and \
435 not isbjunk(b[bestj+bestsize]) and \
436 a[besti+bestsize] == b[bestj+bestsize]:
437 bestsize += 1
438
Tim Peters9ae21482001-02-10 08:00:53 +0000439 # Now that we have a wholly interesting match (albeit possibly
440 # empty!), we may as well suck up the matching junk on each
441 # side of it too. Can't think of a good reason not to, and it
442 # saves post-processing the (possibly considerable) expense of
443 # figuring out what to do with it. In the case of an empty
444 # interesting match, this is clearly the right thing to do,
445 # because no other kind of match is possible in the regions.
446 while besti > alo and bestj > blo and \
447 isbjunk(b[bestj-1]) and \
448 a[besti-1] == b[bestj-1]:
449 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
450 while besti+bestsize < ahi and bestj+bestsize < bhi and \
451 isbjunk(b[bestj+bestsize]) and \
452 a[besti+bestsize] == b[bestj+bestsize]:
453 bestsize = bestsize + 1
454
Tim Peters9ae21482001-02-10 08:00:53 +0000455 return besti, bestj, bestsize
456
457 def get_matching_blocks(self):
458 """Return list of triples describing matching subsequences.
459
460 Each triple is of the form (i, j, n), and means that
461 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000462 i and in j. New in Python 2.5, it's also guaranteed that if
463 (i, j, n) and (i', j', n') are adjacent triples in the list, and
464 the second is not the last triple in the list, then i+n != i' or
465 j+n != j'. IOW, adjacent triples never describe adjacent equal
466 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000467
468 The last triple is a dummy, (len(a), len(b), 0), and is the only
469 triple with n==0.
470
471 >>> s = SequenceMatcher(None, "abxcd", "abcd")
472 >>> s.get_matching_blocks()
473 [(0, 0, 2), (3, 2, 2), (5, 4, 0)]
474 """
475
476 if self.matching_blocks is not None:
477 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000478 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000479
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000480 # This is most naturally expressed as a recursive algorithm, but
481 # at least one user bumped into extreme use cases that exceeded
482 # the recursion limit on their box. So, now we maintain a list
483 # ('queue`) of blocks we still need to look at, and append partial
484 # results to `matching_blocks` in a loop; the matches are sorted
485 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000486 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000487 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000488 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000489 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000490 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000491 # a[alo:i] vs b[blo:j] unknown
492 # a[i:i+k] same as b[j:j+k]
493 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000494 if k: # if k is 0, there was no matching block
495 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000496 if alo < i and blo < j:
497 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000498 if i+k < ahi and j+k < bhi:
499 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000500 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000501
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000502 # It's possible that we have adjacent equal blocks in the
503 # matching_blocks list now. Starting with 2.5, this code was added
504 # to collapse them.
505 i1 = j1 = k1 = 0
506 non_adjacent = []
507 for i2, j2, k2 in matching_blocks:
508 # Is this block adjacent to i1, j1, k1?
509 if i1 + k1 == i2 and j1 + k1 == j2:
510 # Yes, so collapse them -- this just increases the length of
511 # the first block by the length of the second, and the first
512 # block so lengthened remains the block to compare against.
513 k1 += k2
514 else:
515 # Not adjacent. Remember the first block (k1==0 means it's
516 # the dummy we started with), and make the second block the
517 # new block to compare against.
518 if k1:
519 non_adjacent.append((i1, j1, k1))
520 i1, j1, k1 = i2, j2, k2
521 if k1:
522 non_adjacent.append((i1, j1, k1))
523
524 non_adjacent.append( (la, lb, 0) )
525 self.matching_blocks = non_adjacent
Tim Peters9ae21482001-02-10 08:00:53 +0000526 return self.matching_blocks
527
Tim Peters9ae21482001-02-10 08:00:53 +0000528 def get_opcodes(self):
529 """Return list of 5-tuples describing how to turn a into b.
530
531 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
532 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
533 tuple preceding it, and likewise for j1 == the previous j2.
534
535 The tags are strings, with these meanings:
536
537 'replace': a[i1:i2] should be replaced by b[j1:j2]
538 'delete': a[i1:i2] should be deleted.
539 Note that j1==j2 in this case.
540 'insert': b[j1:j2] should be inserted at a[i1:i1].
541 Note that i1==i2 in this case.
542 'equal': a[i1:i2] == b[j1:j2]
543
544 >>> a = "qabxcd"
545 >>> b = "abycdf"
546 >>> s = SequenceMatcher(None, a, b)
547 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000548 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
549 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000550 delete a[0:1] (q) b[0:0] ()
551 equal a[1:3] (ab) b[0:2] (ab)
552 replace a[3:4] (x) b[2:3] (y)
553 equal a[4:6] (cd) b[3:5] (cd)
554 insert a[6:6] () b[5:6] (f)
555 """
556
557 if self.opcodes is not None:
558 return self.opcodes
559 i = j = 0
560 self.opcodes = answer = []
561 for ai, bj, size in self.get_matching_blocks():
562 # invariant: we've pumped out correct diffs to change
563 # a[:i] into b[:j], and the next matching block is
564 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
565 # out a diff to change a[i:ai] into b[j:bj], pump out
566 # the matching block, and move (i,j) beyond the match
567 tag = ''
568 if i < ai and j < bj:
569 tag = 'replace'
570 elif i < ai:
571 tag = 'delete'
572 elif j < bj:
573 tag = 'insert'
574 if tag:
575 answer.append( (tag, i, ai, j, bj) )
576 i, j = ai+size, bj+size
577 # the list of matching blocks is terminated by a
578 # sentinel with size 0
579 if size:
580 answer.append( ('equal', ai, i, bj, j) )
581 return answer
582
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000583 def get_grouped_opcodes(self, n=3):
584 """ Isolate change clusters by eliminating ranges with no changes.
585
586 Return a generator of groups with upto n lines of context.
587 Each group is in the same format as returned by get_opcodes().
588
589 >>> from pprint import pprint
590 >>> a = map(str, range(1,40))
591 >>> b = a[:]
592 >>> b[8:8] = ['i'] # Make an insertion
593 >>> b[20] += 'x' # Make a replacement
594 >>> b[23:28] = [] # Make a deletion
595 >>> b[30] += 'y' # Make another replacement
596 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
597 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
598 [('equal', 16, 19, 17, 20),
599 ('replace', 19, 20, 20, 21),
600 ('equal', 20, 22, 21, 23),
601 ('delete', 22, 27, 23, 23),
602 ('equal', 27, 30, 23, 26)],
603 [('equal', 31, 34, 27, 30),
604 ('replace', 34, 35, 30, 31),
605 ('equal', 35, 38, 31, 34)]]
606 """
607
608 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000609 if not codes:
610 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000611 # Fixup leading and trailing groups if they show no changes.
612 if codes[0][0] == 'equal':
613 tag, i1, i2, j1, j2 = codes[0]
614 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
615 if codes[-1][0] == 'equal':
616 tag, i1, i2, j1, j2 = codes[-1]
617 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
618
619 nn = n + n
620 group = []
621 for tag, i1, i2, j1, j2 in codes:
622 # End the current group and start a new one whenever
623 # there is a large range with no changes.
624 if tag == 'equal' and i2-i1 > nn:
625 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
626 yield group
627 group = []
628 i1, j1 = max(i1, i2-n), max(j1, j2-n)
629 group.append((tag, i1, i2, j1 ,j2))
630 if group and not (len(group)==1 and group[0][0] == 'equal'):
631 yield group
632
Tim Peters9ae21482001-02-10 08:00:53 +0000633 def ratio(self):
634 """Return a measure of the sequences' similarity (float in [0,1]).
635
636 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000637 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000638 Note that this is 1 if the sequences are identical, and 0 if
639 they have nothing in common.
640
641 .ratio() is expensive to compute if you haven't already computed
642 .get_matching_blocks() or .get_opcodes(), in which case you may
643 want to try .quick_ratio() or .real_quick_ratio() first to get an
644 upper bound.
645
646 >>> s = SequenceMatcher(None, "abcd", "bcde")
647 >>> s.ratio()
648 0.75
649 >>> s.quick_ratio()
650 0.75
651 >>> s.real_quick_ratio()
652 1.0
653 """
654
Guido van Rossum89da5d72006-08-22 00:21:25 +0000655 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000656 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000657
658 def quick_ratio(self):
659 """Return an upper bound on ratio() relatively quickly.
660
661 This isn't defined beyond that it is an upper bound on .ratio(), and
662 is faster to compute.
663 """
664
665 # viewing a and b as multisets, set matches to the cardinality
666 # of their intersection; this counts the number of matches
667 # without regard to order, so is clearly an upper bound
668 if self.fullbcount is None:
669 self.fullbcount = fullbcount = {}
670 for elt in self.b:
671 fullbcount[elt] = fullbcount.get(elt, 0) + 1
672 fullbcount = self.fullbcount
673 # avail[x] is the number of times x appears in 'b' less the
674 # number of times we've seen it in 'a' so far ... kinda
675 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000676 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000677 for elt in self.a:
678 if availhas(elt):
679 numb = avail[elt]
680 else:
681 numb = fullbcount.get(elt, 0)
682 avail[elt] = numb - 1
683 if numb > 0:
684 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000685 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000686
687 def real_quick_ratio(self):
688 """Return an upper bound on ratio() very quickly.
689
690 This isn't defined beyond that it is an upper bound on .ratio(), and
691 is faster to compute than either .ratio() or .quick_ratio().
692 """
693
694 la, lb = len(self.a), len(self.b)
695 # can't have more matches than the number of elements in the
696 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000697 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000698
699def get_close_matches(word, possibilities, n=3, cutoff=0.6):
700 """Use SequenceMatcher to return list of the best "good enough" matches.
701
702 word is a sequence for which close matches are desired (typically a
703 string).
704
705 possibilities is a list of sequences against which to match word
706 (typically a list of strings).
707
708 Optional arg n (default 3) is the maximum number of close matches to
709 return. n must be > 0.
710
711 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
712 that don't score at least that similar to word are ignored.
713
714 The best (no more than n) matches among the possibilities are returned
715 in a list, sorted by similarity score, most similar first.
716
717 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
718 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000719 >>> import keyword as _keyword
720 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000721 ['while']
Tim Peters5e824c32001-08-12 22:25:01 +0000722 >>> get_close_matches("apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000723 []
Tim Peters5e824c32001-08-12 22:25:01 +0000724 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000725 ['except']
726 """
727
728 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000729 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000730 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000731 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000732 result = []
733 s = SequenceMatcher()
734 s.set_seq2(word)
735 for x in possibilities:
736 s.set_seq1(x)
737 if s.real_quick_ratio() >= cutoff and \
738 s.quick_ratio() >= cutoff and \
739 s.ratio() >= cutoff:
740 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000741
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000742 # Move the best scorers to head of list
Raymond Hettingeraefde432004-06-15 23:53:35 +0000743 result = heapq.nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000744 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000745 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000746
747def _count_leading(line, ch):
748 """
749 Return number of `ch` characters at the start of `line`.
750
751 Example:
752
753 >>> _count_leading(' abc', ' ')
754 3
755 """
756
757 i, n = 0, len(line)
758 while i < n and line[i] == ch:
759 i += 1
760 return i
761
762class Differ:
763 r"""
764 Differ is a class for comparing sequences of lines of text, and
765 producing human-readable differences or deltas. Differ uses
766 SequenceMatcher both to compare sequences of lines, and to compare
767 sequences of characters within similar (near-matching) lines.
768
769 Each line of a Differ delta begins with a two-letter code:
770
771 '- ' line unique to sequence 1
772 '+ ' line unique to sequence 2
773 ' ' line common to both sequences
774 '? ' line not present in either input sequence
775
776 Lines beginning with '? ' attempt to guide the eye to intraline
777 differences, and were not present in either input sequence. These lines
778 can be confusing if the sequences contain tab characters.
779
780 Note that Differ makes no claim to produce a *minimal* diff. To the
781 contrary, minimal diffs are often counter-intuitive, because they synch
782 up anywhere possible, sometimes accidental matches 100 pages apart.
783 Restricting synch points to contiguous matches preserves some notion of
784 locality, at the occasional cost of producing a longer diff.
785
786 Example: Comparing two texts.
787
788 First we set up the texts, sequences of individual single-line strings
789 ending with newlines (such sequences can also be obtained from the
790 `readlines()` method of file-like objects):
791
792 >>> text1 = ''' 1. Beautiful is better than ugly.
793 ... 2. Explicit is better than implicit.
794 ... 3. Simple is better than complex.
795 ... 4. Complex is better than complicated.
796 ... '''.splitlines(1)
797 >>> len(text1)
798 4
799 >>> text1[0][-1]
800 '\n'
801 >>> text2 = ''' 1. Beautiful is better than ugly.
802 ... 3. Simple is better than complex.
803 ... 4. Complicated is better than complex.
804 ... 5. Flat is better than nested.
805 ... '''.splitlines(1)
806
807 Next we instantiate a Differ object:
808
809 >>> d = Differ()
810
811 Note that when instantiating a Differ object we may pass functions to
812 filter out line and character 'junk'. See Differ.__init__ for details.
813
814 Finally, we compare the two:
815
Tim Peters8a9c2842001-09-22 21:30:22 +0000816 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000817
818 'result' is a list of strings, so let's pretty-print it:
819
820 >>> from pprint import pprint as _pprint
821 >>> _pprint(result)
822 [' 1. Beautiful is better than ugly.\n',
823 '- 2. Explicit is better than implicit.\n',
824 '- 3. Simple is better than complex.\n',
825 '+ 3. Simple is better than complex.\n',
826 '? ++\n',
827 '- 4. Complex is better than complicated.\n',
828 '? ^ ---- ^\n',
829 '+ 4. Complicated is better than complex.\n',
830 '? ++++ ^ ^\n',
831 '+ 5. Flat is better than nested.\n']
832
833 As a single multi-line string it looks like this:
834
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000835 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000836 1. Beautiful is better than ugly.
837 - 2. Explicit is better than implicit.
838 - 3. Simple is better than complex.
839 + 3. Simple is better than complex.
840 ? ++
841 - 4. Complex is better than complicated.
842 ? ^ ---- ^
843 + 4. Complicated is better than complex.
844 ? ++++ ^ ^
845 + 5. Flat is better than nested.
846
847 Methods:
848
849 __init__(linejunk=None, charjunk=None)
850 Construct a text differencer, with optional filters.
851
852 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000853 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000854 """
855
856 def __init__(self, linejunk=None, charjunk=None):
857 """
858 Construct a text differencer, with optional filters.
859
860 The two optional keyword parameters are for filter functions:
861
862 - `linejunk`: A function that should accept a single string argument,
863 and return true iff the string is junk. The module-level function
864 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000865 characters, except for at most one splat ('#'). It is recommended
866 to leave linejunk None; as of Python 2.3, the underlying
867 SequenceMatcher class has grown an adaptive notion of "noise" lines
868 that's better than any static definition the author has ever been
869 able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000870
871 - `charjunk`: A function that should accept a string of length 1. The
872 module-level function `IS_CHARACTER_JUNK` may be used to filter out
873 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000874 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000875 """
876
877 self.linejunk = linejunk
878 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000879
880 def compare(self, a, b):
881 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000882 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000883
884 Each sequence must contain individual single-line strings ending with
885 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000886 of file-like objects. The delta generated also consists of newline-
887 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000888 method of a file-like object.
889
890 Example:
891
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000892 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
Tim Peters5e824c32001-08-12 22:25:01 +0000893 ... 'ore\ntree\nemu\n'.splitlines(1))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000894 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000895 - one
896 ? ^
897 + ore
898 ? ^
899 - two
900 - three
901 ? -
902 + tree
903 + emu
904 """
905
906 cruncher = SequenceMatcher(self.linejunk, a, b)
907 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
908 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000909 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000910 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000911 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000912 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000913 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000914 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000915 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000916 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000917 raise ValueError, 'unknown tag %r' % (tag,)
Tim Peters8a9c2842001-09-22 21:30:22 +0000918
919 for line in g:
920 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000921
922 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000923 """Generate comparison results for a same-tagged range."""
Tim Peters5e824c32001-08-12 22:25:01 +0000924 for i in xrange(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000925 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000926
927 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
928 assert alo < ahi and blo < bhi
929 # dump the shorter block first -- reduces the burden on short-term
930 # memory if the blocks are of very different sizes
931 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000932 first = self._dump('+', b, blo, bhi)
933 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000934 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000935 first = self._dump('-', a, alo, ahi)
936 second = self._dump('+', b, blo, bhi)
937
938 for g in first, second:
939 for line in g:
940 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000941
942 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
943 r"""
944 When replacing one block of lines with another, search the blocks
945 for *similar* lines; the best-matching pair (if any) is used as a
946 synch point, and intraline difference marking is done on the
947 similar pair. Lots of work, but often worth it.
948
949 Example:
950
951 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000952 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
953 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000954 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000955 - abcDefghiJkl
956 ? ^ ^ ^
957 + abcdefGhijkl
958 ? ^ ^ ^
959 """
960
Tim Peters5e824c32001-08-12 22:25:01 +0000961 # don't synch up unless the lines have a similarity score of at
962 # least cutoff; best_ratio tracks the best score seen so far
963 best_ratio, cutoff = 0.74, 0.75
964 cruncher = SequenceMatcher(self.charjunk)
965 eqi, eqj = None, None # 1st indices of equal lines (if any)
966
967 # search for the pair that matches best without being identical
968 # (identical lines must be junk lines, & we don't want to synch up
969 # on junk -- unless we have to)
970 for j in xrange(blo, bhi):
971 bj = b[j]
972 cruncher.set_seq2(bj)
973 for i in xrange(alo, ahi):
974 ai = a[i]
975 if ai == bj:
976 if eqi is None:
977 eqi, eqj = i, j
978 continue
979 cruncher.set_seq1(ai)
980 # computing similarity is expensive, so use the quick
981 # upper bounds first -- have seen this speed up messy
982 # compares by a factor of 3.
983 # note that ratio() is only expensive to compute the first
984 # time it's called on a sequence pair; the expensive part
985 # of the computation is cached by cruncher
986 if cruncher.real_quick_ratio() > best_ratio and \
987 cruncher.quick_ratio() > best_ratio and \
988 cruncher.ratio() > best_ratio:
989 best_ratio, best_i, best_j = cruncher.ratio(), i, j
990 if best_ratio < cutoff:
991 # no non-identical "pretty close" pair
992 if eqi is None:
993 # no identical pair either -- treat it as a straight replace
Tim Peters8a9c2842001-09-22 21:30:22 +0000994 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
995 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000996 return
997 # no close pair, but an identical pair -- synch up on that
998 best_i, best_j, best_ratio = eqi, eqj, 1.0
999 else:
1000 # there's a close pair, so forget the identical pair (if any)
1001 eqi = None
1002
1003 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
1004 # identical
Tim Peters5e824c32001-08-12 22:25:01 +00001005
1006 # pump out diffs from before the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001007 for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
1008 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001009
1010 # do intraline marking on the synch pair
1011 aelt, belt = a[best_i], b[best_j]
1012 if eqi is None:
1013 # pump out a '-', '?', '+', '?' quad for the synched lines
1014 atags = btags = ""
1015 cruncher.set_seqs(aelt, belt)
1016 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1017 la, lb = ai2 - ai1, bj2 - bj1
1018 if tag == 'replace':
1019 atags += '^' * la
1020 btags += '^' * lb
1021 elif tag == 'delete':
1022 atags += '-' * la
1023 elif tag == 'insert':
1024 btags += '+' * lb
1025 elif tag == 'equal':
1026 atags += ' ' * la
1027 btags += ' ' * lb
1028 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001029 raise ValueError, 'unknown tag %r' % (tag,)
Tim Peters8a9c2842001-09-22 21:30:22 +00001030 for line in self._qformat(aelt, belt, atags, btags):
1031 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001032 else:
1033 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001034 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001035
1036 # pump out diffs from after the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001037 for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
1038 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001039
1040 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001041 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001042 if alo < ahi:
1043 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001044 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001045 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001046 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001047 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001048 g = self._dump('+', b, blo, bhi)
1049
1050 for line in g:
1051 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001052
1053 def _qformat(self, aline, bline, atags, btags):
1054 r"""
1055 Format "?" output and deal with leading tabs.
1056
1057 Example:
1058
1059 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +00001060 >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n',
1061 ... ' ^ ^ ^ ', '+ ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001062 >>> for line in results: print(repr(line))
1063 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001064 '- \tabcDefghiJkl\n'
1065 '? \t ^ ^ ^\n'
1066 '+ \t\tabcdefGhijkl\n'
1067 '? \t ^ ^ ^\n'
1068 """
1069
1070 # Can hurt, but will probably help most of the time.
1071 common = min(_count_leading(aline, "\t"),
1072 _count_leading(bline, "\t"))
1073 common = min(common, _count_leading(atags[:common], " "))
1074 atags = atags[common:].rstrip()
1075 btags = btags[common:].rstrip()
1076
Tim Peters8a9c2842001-09-22 21:30:22 +00001077 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001078 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001079 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001080
Tim Peters8a9c2842001-09-22 21:30:22 +00001081 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001082 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001083 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001084
1085# With respect to junk, an earlier version of ndiff simply refused to
1086# *start* a match with a junk element. The result was cases like this:
1087# before: private Thread currentThread;
1088# after: private volatile Thread currentThread;
1089# If you consider whitespace to be junk, the longest contiguous match
1090# not starting with junk is "e Thread currentThread". So ndiff reported
1091# that "e volatil" was inserted between the 't' and the 'e' in "private".
1092# While an accurate view, to people that's absurd. The current version
1093# looks for matching blocks that are entirely junk-free, then extends the
1094# longest one of those as far as possible but only with matching junk.
1095# So now "currentThread" is matched, then extended to suck up the
1096# preceding blank; then "private" is matched, and extended to suck up the
1097# following blank; then "Thread" is matched; and finally ndiff reports
1098# that "volatile " was inserted before "Thread". The only quibble
1099# remaining is that perhaps it was really the case that " volatile"
1100# was inserted after "private". I can live with that <wink>.
1101
1102import re
1103
1104def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1105 r"""
1106 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1107
1108 Examples:
1109
1110 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001111 True
Tim Peters5e824c32001-08-12 22:25:01 +00001112 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001113 True
Tim Peters5e824c32001-08-12 22:25:01 +00001114 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001115 False
Tim Peters5e824c32001-08-12 22:25:01 +00001116 """
1117
1118 return pat(line) is not None
1119
1120def IS_CHARACTER_JUNK(ch, ws=" \t"):
1121 r"""
1122 Return 1 for ignorable character: iff `ch` is a space or tab.
1123
1124 Examples:
1125
1126 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001127 True
Tim Peters5e824c32001-08-12 22:25:01 +00001128 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001129 True
Tim Peters5e824c32001-08-12 22:25:01 +00001130 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001131 False
Tim Peters5e824c32001-08-12 22:25:01 +00001132 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001133 False
Tim Peters5e824c32001-08-12 22:25:01 +00001134 """
1135
1136 return ch in ws
1137
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001138
1139def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1140 tofiledate='', n=3, lineterm='\n'):
1141 r"""
1142 Compare two sequences of lines; generate the delta as a unified diff.
1143
1144 Unified diffs are a compact way of showing line changes and a few
1145 lines of context. The number of context lines is set by 'n' which
1146 defaults to three.
1147
Raymond Hettinger0887c732003-06-17 16:53:25 +00001148 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001149 created with a trailing newline. This is helpful so that inputs
1150 created from file.readlines() result in diffs that are suitable for
1151 file.writelines() since both the inputs and outputs have trailing
1152 newlines.
1153
1154 For inputs that do not have trailing newlines, set the lineterm
1155 argument to "" so that the output will be uniformly newline free.
1156
1157 The unidiff format normally has a header for filenames and modification
1158 times. Any or all of these may be specified using strings for
1159 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification
1160 times are normally expressed in the format returned by time.ctime().
1161
1162 Example:
1163
1164 >>> for line in unified_diff('one two three four'.split(),
1165 ... 'zero one tree four'.split(), 'Original', 'Current',
1166 ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003',
1167 ... lineterm=''):
Guido van Rossumfff80df2007-02-09 20:33:44 +00001168 ... print(line)
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001169 --- Original Sat Jan 26 23:30:50 1991
1170 +++ Current Fri Jun 06 10:20:52 2003
1171 @@ -1,4 +1,4 @@
1172 +zero
1173 one
1174 -two
1175 -three
1176 +tree
1177 four
1178 """
1179
1180 started = False
1181 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1182 if not started:
1183 yield '--- %s %s%s' % (fromfile, fromfiledate, lineterm)
1184 yield '+++ %s %s%s' % (tofile, tofiledate, lineterm)
1185 started = True
1186 i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
1187 yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
1188 for tag, i1, i2, j1, j2 in group:
1189 if tag == 'equal':
1190 for line in a[i1:i2]:
1191 yield ' ' + line
1192 continue
1193 if tag == 'replace' or tag == 'delete':
1194 for line in a[i1:i2]:
1195 yield '-' + line
1196 if tag == 'replace' or tag == 'insert':
1197 for line in b[j1:j2]:
1198 yield '+' + line
1199
1200# See http://www.unix.org/single_unix_specification/
1201def context_diff(a, b, fromfile='', tofile='',
1202 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1203 r"""
1204 Compare two sequences of lines; generate the delta as a context diff.
1205
1206 Context diffs are a compact way of showing line changes and a few
1207 lines of context. The number of context lines is set by 'n' which
1208 defaults to three.
1209
1210 By default, the diff control lines (those with *** or ---) are
1211 created with a trailing newline. This is helpful so that inputs
1212 created from file.readlines() result in diffs that are suitable for
1213 file.writelines() since both the inputs and outputs have trailing
1214 newlines.
1215
1216 For inputs that do not have trailing newlines, set the lineterm
1217 argument to "" so that the output will be uniformly newline free.
1218
1219 The context diff format normally has a header for filenames and
1220 modification times. Any or all of these may be specified using
1221 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1222 The modification times are normally expressed in the format returned
1223 by time.ctime(). If not specified, the strings default to blanks.
1224
1225 Example:
1226
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001227 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001228 ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current',
1229 ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001230 ... end="")
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001231 *** Original Sat Jan 26 23:30:50 1991
1232 --- Current Fri Jun 06 10:22:46 2003
1233 ***************
1234 *** 1,4 ****
1235 one
1236 ! two
1237 ! three
1238 four
1239 --- 1,4 ----
1240 + zero
1241 one
1242 ! tree
1243 four
1244 """
1245
1246 started = False
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001247 prefixmap = {'insert':'+ ', 'delete':'- ', 'replace':'! ', 'equal':' '}
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001248 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1249 if not started:
1250 yield '*** %s %s%s' % (fromfile, fromfiledate, lineterm)
1251 yield '--- %s %s%s' % (tofile, tofiledate, lineterm)
1252 started = True
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001253
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001254 yield '***************%s' % (lineterm,)
1255 if group[-1][2] - group[0][1] >= 2:
1256 yield '*** %d,%d ****%s' % (group[0][1]+1, group[-1][2], lineterm)
1257 else:
1258 yield '*** %d ****%s' % (group[-1][2], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001259 visiblechanges = [e for e in group if e[0] in ('replace', 'delete')]
1260 if visiblechanges:
1261 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001262 if tag != 'insert':
1263 for line in a[i1:i2]:
1264 yield prefixmap[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001265
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001266 if group[-1][4] - group[0][3] >= 2:
1267 yield '--- %d,%d ----%s' % (group[0][3]+1, group[-1][4], lineterm)
1268 else:
1269 yield '--- %d ----%s' % (group[-1][4], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001270 visiblechanges = [e for e in group if e[0] in ('replace', 'insert')]
1271 if visiblechanges:
1272 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001273 if tag != 'delete':
1274 for line in b[j1:j2]:
1275 yield prefixmap[tag] + line
1276
Tim Peters81b92512002-04-29 01:37:32 +00001277def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001278 r"""
1279 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1280
1281 Optional keyword parameters `linejunk` and `charjunk` are for filter
1282 functions (or None):
1283
1284 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001285 return true iff the string is junk. The default is None, and is
1286 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1287 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001288
1289 - charjunk: A function that should accept a string of length 1. The
1290 default is module-level function IS_CHARACTER_JUNK, which filters out
1291 whitespace characters (a blank or tab; note: bad idea to include newline
1292 in this!).
1293
1294 Tools/scripts/ndiff.py is a command-line front-end to this function.
1295
1296 Example:
1297
1298 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1299 ... 'ore\ntree\nemu\n'.splitlines(1))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001300 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001301 - one
1302 ? ^
1303 + ore
1304 ? ^
1305 - two
1306 - three
1307 ? -
1308 + tree
1309 + emu
1310 """
1311 return Differ(linejunk, charjunk).compare(a, b)
1312
Martin v. Löwise064b412004-08-29 16:34:40 +00001313def _mdiff(fromlines, tolines, context=None, linejunk=None,
1314 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001315 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001316
1317 Arguments:
1318 fromlines -- list of text lines to compared to tolines
1319 tolines -- list of text lines to be compared to fromlines
1320 context -- number of context lines to display on each side of difference,
1321 if None, all from/to text lines will be generated.
1322 linejunk -- passed on to ndiff (see ndiff documentation)
1323 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001324
Martin v. Löwise064b412004-08-29 16:34:40 +00001325 This function returns an interator which returns a tuple:
1326 (from line tuple, to line tuple, boolean flag)
1327
1328 from/to line tuple -- (line num, line text)
1329 line num -- integer or None (to indicate a context seperation)
1330 line text -- original line text with following markers inserted:
1331 '\0+' -- marks start of added text
1332 '\0-' -- marks start of deleted text
1333 '\0^' -- marks start of changed text
1334 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001335
Martin v. Löwise064b412004-08-29 16:34:40 +00001336 boolean flag -- None indicates context separation, True indicates
1337 either "from" or "to" line contains a change, otherwise False.
1338
1339 This function/iterator was originally developed to generate side by side
1340 file difference for making HTML pages (see HtmlDiff class for example
1341 usage).
1342
1343 Note, this function utilizes the ndiff function to generate the side by
1344 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001345 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001346 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001347 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001348
1349 # regular expression for finding intraline change indices
1350 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001351
Martin v. Löwise064b412004-08-29 16:34:40 +00001352 # create the difference iterator to generate the differences
1353 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1354
1355 def _make_line(lines, format_key, side, num_lines=[0,0]):
1356 """Returns line of text with user's change markup and line formatting.
1357
1358 lines -- list of lines from the ndiff generator to produce a line of
1359 text from. When producing the line of text to return, the
1360 lines used are removed from this list.
1361 format_key -- '+' return first line in list with "add" markup around
1362 the entire line.
1363 '-' return first line in list with "delete" markup around
1364 the entire line.
1365 '?' return first line in list with add/delete/change
1366 intraline markup (indices obtained from second line)
1367 None return first line in list with no markup
1368 side -- indice into the num_lines list (0=from,1=to)
1369 num_lines -- from/to current line number. This is NOT intended to be a
1370 passed parameter. It is present as a keyword argument to
1371 maintain memory of the current line numbers between calls
1372 of this function.
1373
1374 Note, this function is purposefully not defined at the module scope so
1375 that data it needs from its parent function (within whose context it
1376 is defined) does not need to be of module scope.
1377 """
1378 num_lines[side] += 1
1379 # Handle case where no user markup is to be added, just return line of
1380 # text with user's line format to allow for usage of the line number.
1381 if format_key is None:
1382 return (num_lines[side],lines.pop(0)[2:])
1383 # Handle case of intraline changes
1384 if format_key == '?':
1385 text, markers = lines.pop(0), lines.pop(0)
1386 # find intraline changes (store change type and indices in tuples)
1387 sub_info = []
1388 def record_sub_info(match_object,sub_info=sub_info):
1389 sub_info.append([match_object.group(1)[0],match_object.span()])
1390 return match_object.group(1)
1391 change_re.sub(record_sub_info,markers)
1392 # process each tuple inserting our special marks that won't be
1393 # noticed by an xml/html escaper.
1394 for key,(begin,end) in sub_info[::-1]:
1395 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1396 text = text[2:]
1397 # Handle case of add/delete entire line
1398 else:
1399 text = lines.pop(0)[2:]
1400 # if line of text is just a newline, insert a space so there is
1401 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001402 if not text:
1403 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001404 # insert marks that won't be noticed by an xml/html escaper.
1405 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001406 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001407 # thing (such as adding the line number) then replace the special
1408 # marks with what the user's change markup.
1409 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001410
Martin v. Löwise064b412004-08-29 16:34:40 +00001411 def _line_iterator():
1412 """Yields from/to lines of text with a change indication.
1413
1414 This function is an iterator. It itself pulls lines from a
1415 differencing iterator, processes them and yields them. When it can
1416 it yields both a "from" and a "to" line, otherwise it will yield one
1417 or the other. In addition to yielding the lines of from/to text, a
1418 boolean flag is yielded to indicate if the text line(s) have
1419 differences in them.
1420
1421 Note, this function is purposefully not defined at the module scope so
1422 that data it needs from its parent function (within whose context it
1423 is defined) does not need to be of module scope.
1424 """
1425 lines = []
1426 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001427 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001428 # Load up next 4 lines so we can look ahead, create strings which
1429 # are a concatenation of the first character of each of the 4 lines
1430 # so we can do some very readable comparisons.
1431 while len(lines) < 4:
1432 try:
1433 lines.append(diff_lines_iterator.next())
1434 except StopIteration:
1435 lines.append('X')
1436 s = ''.join([line[0] for line in lines])
1437 if s.startswith('X'):
1438 # When no more lines, pump out any remaining blank lines so the
1439 # corresponding add/delete lines get a matching blank line so
1440 # all line pairs get yielded at the next level.
1441 num_blanks_to_yield = num_blanks_pending
1442 elif s.startswith('-?+?'):
1443 # simple intraline change
1444 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1445 continue
1446 elif s.startswith('--++'):
1447 # in delete block, add block coming: we do NOT want to get
1448 # caught up on blank lines yet, just process the delete line
1449 num_blanks_pending -= 1
1450 yield _make_line(lines,'-',0), None, True
1451 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001452 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001453 # in delete block and see a intraline change or unchanged line
1454 # coming: yield the delete line and then blanks
1455 from_line,to_line = _make_line(lines,'-',0), None
1456 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1457 elif s.startswith('-+?'):
1458 # intraline change
1459 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1460 continue
1461 elif s.startswith('-?+'):
1462 # intraline change
1463 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1464 continue
1465 elif s.startswith('-'):
1466 # delete FROM line
1467 num_blanks_pending -= 1
1468 yield _make_line(lines,'-',0), None, True
1469 continue
1470 elif s.startswith('+--'):
1471 # in add block, delete block coming: we do NOT want to get
1472 # caught up on blank lines yet, just process the add line
1473 num_blanks_pending += 1
1474 yield None, _make_line(lines,'+',1), True
1475 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001476 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001477 # will be leaving an add block: yield blanks then add line
1478 from_line, to_line = None, _make_line(lines,'+',1)
1479 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1480 elif s.startswith('+'):
1481 # inside an add block, yield the add line
1482 num_blanks_pending += 1
1483 yield None, _make_line(lines,'+',1), True
1484 continue
1485 elif s.startswith(' '):
1486 # unchanged text, yield it to both sides
1487 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1488 continue
1489 # Catch up on the blank lines so when we yield the next from/to
1490 # pair, they are lined up.
1491 while(num_blanks_to_yield < 0):
1492 num_blanks_to_yield += 1
1493 yield None,('','\n'),True
1494 while(num_blanks_to_yield > 0):
1495 num_blanks_to_yield -= 1
1496 yield ('','\n'),None,True
1497 if s.startswith('X'):
1498 raise StopIteration
1499 else:
1500 yield from_line,to_line,True
1501
1502 def _line_pair_iterator():
1503 """Yields from/to lines of text with a change indication.
1504
1505 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001506 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001507 always yields a pair of from/to text lines (with the change
1508 indication). If necessary it will collect single from/to lines
1509 until it has a matching pair from/to pair to yield.
1510
1511 Note, this function is purposefully not defined at the module scope so
1512 that data it needs from its parent function (within whose context it
1513 is defined) does not need to be of module scope.
1514 """
1515 line_iterator = _line_iterator()
1516 fromlines,tolines=[],[]
1517 while True:
1518 # Collecting lines of text until we have a from/to pair
1519 while (len(fromlines)==0 or len(tolines)==0):
1520 from_line, to_line, found_diff =line_iterator.next()
1521 if from_line is not None:
1522 fromlines.append((from_line,found_diff))
1523 if to_line is not None:
1524 tolines.append((to_line,found_diff))
1525 # Once we have a pair, remove them from the collection and yield it
1526 from_line, fromDiff = fromlines.pop(0)
1527 to_line, to_diff = tolines.pop(0)
1528 yield (from_line,to_line,fromDiff or to_diff)
1529
1530 # Handle case where user does not want context differencing, just yield
1531 # them up without doing anything else with them.
1532 line_pair_iterator = _line_pair_iterator()
1533 if context is None:
1534 while True:
1535 yield line_pair_iterator.next()
1536 # Handle case where user wants context differencing. We must do some
1537 # storage of lines until we know for sure that they are to be yielded.
1538 else:
1539 context += 1
1540 lines_to_write = 0
1541 while True:
1542 # Store lines up until we find a difference, note use of a
1543 # circular queue because we only need to keep around what
1544 # we need for context.
1545 index, contextLines = 0, [None]*(context)
1546 found_diff = False
1547 while(found_diff is False):
1548 from_line, to_line, found_diff = line_pair_iterator.next()
1549 i = index % context
1550 contextLines[i] = (from_line, to_line, found_diff)
1551 index += 1
1552 # Yield lines that we have collected so far, but first yield
1553 # the user's separator.
1554 if index > context:
1555 yield None, None, None
1556 lines_to_write = context
1557 else:
1558 lines_to_write = index
1559 index = 0
1560 while(lines_to_write):
1561 i = index % context
1562 index += 1
1563 yield contextLines[i]
1564 lines_to_write -= 1
1565 # Now yield the context lines after the change
1566 lines_to_write = context-1
1567 while(lines_to_write):
1568 from_line, to_line, found_diff = line_pair_iterator.next()
1569 # If another change within the context, extend the context
1570 if found_diff:
1571 lines_to_write = context-1
1572 else:
1573 lines_to_write -= 1
1574 yield from_line, to_line, found_diff
1575
1576
1577_file_template = """
1578<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1579 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1580
1581<html>
1582
1583<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001584 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001585 content="text/html; charset=ISO-8859-1" />
1586 <title></title>
1587 <style type="text/css">%(styles)s
1588 </style>
1589</head>
1590
1591<body>
1592 %(table)s%(legend)s
1593</body>
1594
1595</html>"""
1596
1597_styles = """
1598 table.diff {font-family:Courier; border:medium;}
1599 .diff_header {background-color:#e0e0e0}
1600 td.diff_header {text-align:right}
1601 .diff_next {background-color:#c0c0c0}
1602 .diff_add {background-color:#aaffaa}
1603 .diff_chg {background-color:#ffff77}
1604 .diff_sub {background-color:#ffaaaa}"""
1605
1606_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001607 <table class="diff" id="difflib_chg_%(prefix)s_top"
1608 cellspacing="0" cellpadding="0" rules="groups" >
1609 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001610 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1611 %(header_row)s
1612 <tbody>
1613%(data_rows)s </tbody>
1614 </table>"""
1615
1616_legend = """
1617 <table class="diff" summary="Legends">
1618 <tr> <th colspan="2"> Legends </th> </tr>
1619 <tr> <td> <table border="" summary="Colors">
1620 <tr><th> Colors </th> </tr>
1621 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1622 <tr><td class="diff_chg">Changed</td> </tr>
1623 <tr><td class="diff_sub">Deleted</td> </tr>
1624 </table></td>
1625 <td> <table border="" summary="Links">
1626 <tr><th colspan="2"> Links </th> </tr>
1627 <tr><td>(f)irst change</td> </tr>
1628 <tr><td>(n)ext change</td> </tr>
1629 <tr><td>(t)op</td> </tr>
1630 </table></td> </tr>
1631 </table>"""
1632
1633class HtmlDiff(object):
1634 """For producing HTML side by side comparison with change highlights.
1635
1636 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001637 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001638 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001639 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001640
Martin v. Löwise064b412004-08-29 16:34:40 +00001641 The following methods are provided for HTML generation:
1642
1643 make_table -- generates HTML for a single side by side table
1644 make_file -- generates complete HTML file with a single side by side table
1645
Tim Peters48bd7f32004-08-29 22:38:38 +00001646 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001647 """
1648
1649 _file_template = _file_template
1650 _styles = _styles
1651 _table_template = _table_template
1652 _legend = _legend
1653 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001654
Martin v. Löwise064b412004-08-29 16:34:40 +00001655 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1656 charjunk=IS_CHARACTER_JUNK):
1657 """HtmlDiff instance initializer
1658
1659 Arguments:
1660 tabsize -- tab stop spacing, defaults to 8.
1661 wrapcolumn -- column number where lines are broken and wrapped,
1662 defaults to None where lines are not wrapped.
1663 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001664 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001665 ndiff() documentation for argument default values and descriptions.
1666 """
1667 self._tabsize = tabsize
1668 self._wrapcolumn = wrapcolumn
1669 self._linejunk = linejunk
1670 self._charjunk = charjunk
1671
1672 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1673 numlines=5):
1674 """Returns HTML file of side by side comparison with change highlights
1675
1676 Arguments:
1677 fromlines -- list of "from" lines
1678 tolines -- list of "to" lines
1679 fromdesc -- "from" file column header string
1680 todesc -- "to" file column header string
1681 context -- set to True for contextual differences (defaults to False
1682 which shows full differences).
1683 numlines -- number of context lines. When context is set True,
1684 controls number of lines displayed before and after the change.
1685 When context is False, controls the number of lines to place
1686 the "next" link anchors before the next change (so click of
1687 "next" link jumps to just before the change).
1688 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001689
Martin v. Löwise064b412004-08-29 16:34:40 +00001690 return self._file_template % dict(
1691 styles = self._styles,
1692 legend = self._legend,
1693 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1694 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001695
Martin v. Löwise064b412004-08-29 16:34:40 +00001696 def _tab_newline_replace(self,fromlines,tolines):
1697 """Returns from/to line lists with tabs expanded and newlines removed.
1698
1699 Instead of tab characters being replaced by the number of spaces
1700 needed to fill in to the next tab stop, this function will fill
1701 the space with tab characters. This is done so that the difference
1702 algorithms can identify changes in a file when tabs are replaced by
1703 spaces and vice versa. At the end of the HTML generation, the tab
1704 characters will be replaced with a nonbreakable space.
1705 """
1706 def expand_tabs(line):
1707 # hide real spaces
1708 line = line.replace(' ','\0')
1709 # expand tabs into spaces
1710 line = line.expandtabs(self._tabsize)
1711 # relace spaces from expanded tabs back into tab characters
1712 # (we'll replace them with markup after we do differencing)
1713 line = line.replace(' ','\t')
1714 return line.replace('\0',' ').rstrip('\n')
1715 fromlines = [expand_tabs(line) for line in fromlines]
1716 tolines = [expand_tabs(line) for line in tolines]
1717 return fromlines,tolines
1718
1719 def _split_line(self,data_list,line_num,text):
1720 """Builds list of text lines by splitting text lines at wrap point
1721
1722 This function will determine if the input text line needs to be
1723 wrapped (split) into separate lines. If so, the first wrap point
1724 will be determined and the first line appended to the output
1725 text line list. This function is used recursively to handle
1726 the second part of the split line to further split it.
1727 """
1728 # if blank line or context separator, just add it to the output list
1729 if not line_num:
1730 data_list.append((line_num,text))
1731 return
1732
1733 # if line text doesn't need wrapping, just add it to the output list
1734 size = len(text)
1735 max = self._wrapcolumn
1736 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1737 data_list.append((line_num,text))
1738 return
1739
1740 # scan text looking for the wrap point, keeping track if the wrap
1741 # point is inside markers
1742 i = 0
1743 n = 0
1744 mark = ''
1745 while n < max and i < size:
1746 if text[i] == '\0':
1747 i += 1
1748 mark = text[i]
1749 i += 1
1750 elif text[i] == '\1':
1751 i += 1
1752 mark = ''
1753 else:
1754 i += 1
1755 n += 1
1756
1757 # wrap point is inside text, break it up into separate lines
1758 line1 = text[:i]
1759 line2 = text[i:]
1760
1761 # if wrap point is inside markers, place end marker at end of first
1762 # line and start marker at beginning of second line because each
1763 # line will have its own table tag markup around it.
1764 if mark:
1765 line1 = line1 + '\1'
1766 line2 = '\0' + mark + line2
1767
Tim Peters48bd7f32004-08-29 22:38:38 +00001768 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001769 data_list.append((line_num,line1))
1770
Tim Peters48bd7f32004-08-29 22:38:38 +00001771 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001772 self._split_line(data_list,'>',line2)
1773
1774 def _line_wrapper(self,diffs):
1775 """Returns iterator that splits (wraps) mdiff text lines"""
1776
1777 # pull from/to data and flags from mdiff iterator
1778 for fromdata,todata,flag in diffs:
1779 # check for context separators and pass them through
1780 if flag is None:
1781 yield fromdata,todata,flag
1782 continue
1783 (fromline,fromtext),(toline,totext) = fromdata,todata
1784 # for each from/to line split it at the wrap column to form
1785 # list of text lines.
1786 fromlist,tolist = [],[]
1787 self._split_line(fromlist,fromline,fromtext)
1788 self._split_line(tolist,toline,totext)
1789 # yield from/to line in pairs inserting blank lines as
1790 # necessary when one side has more wrapped lines
1791 while fromlist or tolist:
1792 if fromlist:
1793 fromdata = fromlist.pop(0)
1794 else:
1795 fromdata = ('',' ')
1796 if tolist:
1797 todata = tolist.pop(0)
1798 else:
1799 todata = ('',' ')
1800 yield fromdata,todata,flag
1801
1802 def _collect_lines(self,diffs):
1803 """Collects mdiff output into separate lists
1804
1805 Before storing the mdiff from/to data into a list, it is converted
1806 into a single line of text with HTML markup.
1807 """
1808
1809 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001810 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001811 for fromdata,todata,flag in diffs:
1812 try:
1813 # store HTML markup of the lines into the lists
1814 fromlist.append(self._format_line(0,flag,*fromdata))
1815 tolist.append(self._format_line(1,flag,*todata))
1816 except TypeError:
1817 # exceptions occur for lines where context separators go
1818 fromlist.append(None)
1819 tolist.append(None)
1820 flaglist.append(flag)
1821 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001822
Martin v. Löwise064b412004-08-29 16:34:40 +00001823 def _format_line(self,side,flag,linenum,text):
1824 """Returns HTML markup of "from" / "to" text lines
1825
1826 side -- 0 or 1 indicating "from" or "to" text
1827 flag -- indicates if difference on line
1828 linenum -- line number (used for line number column)
1829 text -- line text to be marked up
1830 """
1831 try:
1832 linenum = '%d' % linenum
1833 id = ' id="%s%s"' % (self._prefix[side],linenum)
1834 except TypeError:
1835 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001836 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001837 # replace those things that would get confused with HTML symbols
1838 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1839
1840 # make space non-breakable so they don't get compressed or line wrapped
1841 text = text.replace(' ','&nbsp;').rstrip()
1842
1843 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1844 % (id,linenum,text)
1845
1846 def _make_prefix(self):
1847 """Create unique anchor prefixes"""
1848
1849 # Generate a unique anchor prefix so multiple tables
1850 # can exist on the same HTML page without conflicts.
1851 fromprefix = "from%d_" % HtmlDiff._default_prefix
1852 toprefix = "to%d_" % HtmlDiff._default_prefix
1853 HtmlDiff._default_prefix += 1
1854 # store prefixes so line format method has access
1855 self._prefix = [fromprefix,toprefix]
1856
1857 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1858 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001859
Martin v. Löwise064b412004-08-29 16:34:40 +00001860 # all anchor names will be generated using the unique "to" prefix
1861 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001862
Martin v. Löwise064b412004-08-29 16:34:40 +00001863 # process change flags, generating middle column of next anchors/links
1864 next_id = ['']*len(flaglist)
1865 next_href = ['']*len(flaglist)
1866 num_chg, in_change = 0, False
1867 last = 0
1868 for i,flag in enumerate(flaglist):
1869 if flag:
1870 if not in_change:
1871 in_change = True
1872 last = i
1873 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001874 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001875 # link
1876 i = max([0,i-numlines])
1877 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001878 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001879 # change
1880 num_chg += 1
1881 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1882 toprefix,num_chg)
1883 else:
1884 in_change = False
1885 # check for cases where there is no content to avoid exceptions
1886 if not flaglist:
1887 flaglist = [False]
1888 next_id = ['']
1889 next_href = ['']
1890 last = 0
1891 if context:
1892 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1893 tolist = fromlist
1894 else:
1895 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1896 # if not a change on first line, drop a link
1897 if not flaglist[0]:
1898 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1899 # redo the last link to link to the top
1900 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1901
1902 return fromlist,tolist,flaglist,next_href,next_id
1903
1904 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1905 numlines=5):
1906 """Returns HTML table of side by side comparison with change highlights
1907
1908 Arguments:
1909 fromlines -- list of "from" lines
1910 tolines -- list of "to" lines
1911 fromdesc -- "from" file column header string
1912 todesc -- "to" file column header string
1913 context -- set to True for contextual differences (defaults to False
1914 which shows full differences).
1915 numlines -- number of context lines. When context is set True,
1916 controls number of lines displayed before and after the change.
1917 When context is False, controls the number of lines to place
1918 the "next" link anchors before the next change (so click of
1919 "next" link jumps to just before the change).
1920 """
1921
1922 # make unique anchor prefixes so that multiple tables may exist
1923 # on the same page without conflict.
1924 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001925
Martin v. Löwise064b412004-08-29 16:34:40 +00001926 # change tabs to spaces before it gets more difficult after we insert
1927 # markkup
1928 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001929
Martin v. Löwise064b412004-08-29 16:34:40 +00001930 # create diffs iterator which generates side by side from/to data
1931 if context:
1932 context_lines = numlines
1933 else:
1934 context_lines = None
1935 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1936 charjunk=self._charjunk)
1937
1938 # set up iterator to wrap lines that exceed desired width
1939 if self._wrapcolumn:
1940 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001941
Martin v. Löwise064b412004-08-29 16:34:40 +00001942 # collect up from/to lines and flags into lists (also format the lines)
1943 fromlist,tolist,flaglist = self._collect_lines(diffs)
1944
1945 # process change flags, generating middle column of next anchors/links
1946 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1947 fromlist,tolist,flaglist,context,numlines)
1948
1949 import cStringIO
1950 s = cStringIO.StringIO()
1951 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1952 '<td class="diff_next">%s</td>%s</tr>\n'
1953 for i in range(len(flaglist)):
1954 if flaglist[i] is None:
1955 # mdiff yields None on separator lines skip the bogus ones
1956 # generated for the first line
1957 if i > 0:
1958 s.write(' </tbody> \n <tbody>\n')
1959 else:
1960 s.write( fmt % (next_id[i],next_href[i],fromlist[i],
1961 next_href[i],tolist[i]))
1962 if fromdesc or todesc:
1963 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
1964 '<th class="diff_next"><br /></th>',
1965 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
1966 '<th class="diff_next"><br /></th>',
1967 '<th colspan="2" class="diff_header">%s</th>' % todesc)
1968 else:
1969 header_row = ''
1970
1971 table = self._table_template % dict(
1972 data_rows=s.getvalue(),
1973 header_row=header_row,
1974 prefix=self._prefix[1])
1975
1976 return table.replace('\0+','<span class="diff_add">'). \
1977 replace('\0-','<span class="diff_sub">'). \
1978 replace('\0^','<span class="diff_chg">'). \
1979 replace('\1','</span>'). \
1980 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00001981
Martin v. Löwise064b412004-08-29 16:34:40 +00001982del re
1983
Tim Peters5e824c32001-08-12 22:25:01 +00001984def restore(delta, which):
1985 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00001986 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00001987
1988 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
1989 lines originating from file 1 or 2 (parameter `which`), stripping off line
1990 prefixes.
1991
1992 Examples:
1993
1994 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1995 ... 'ore\ntree\nemu\n'.splitlines(1))
Tim Peters8a9c2842001-09-22 21:30:22 +00001996 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001997 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001998 one
1999 two
2000 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002001 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002002 ore
2003 tree
2004 emu
2005 """
2006 try:
2007 tag = {1: "- ", 2: "+ "}[int(which)]
2008 except KeyError:
2009 raise ValueError, ('unknown delta choice (must be 1 or 2): %r'
2010 % which)
2011 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002012 for line in delta:
2013 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002014 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002015
Tim Peters9ae21482001-02-10 08:00:53 +00002016def _test():
2017 import doctest, difflib
2018 return doctest.testmod(difflib)
2019
2020if __name__ == "__main__":
2021 _test()