blob: 408079b8038f4f38959dc2405a0e21a3f81b3f28 [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
79 >>> print round(s.ratio(), 3)
80 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():
87 ... print "a[%d] and b[%d] match for %d elements" % block
88 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():
100 ... print "%6s a[%d:%d] b[%d:%d]" % opcode
101 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():
548 ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
549 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
550 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
835 >>> print ''.join(result),
836 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
892 >>> print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
893 ... 'ore\ntree\nemu\n'.splitlines(1))),
894 - one
895 ? ^
896 + ore
897 ? ^
898 - two
899 - three
900 ? -
901 + tree
902 + emu
903 """
904
905 cruncher = SequenceMatcher(self.linejunk, a, b)
906 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
907 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000908 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000909 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000910 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000911 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000912 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000913 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000914 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000915 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000916 raise ValueError, 'unknown tag %r' % (tag,)
Tim Peters8a9c2842001-09-22 21:30:22 +0000917
918 for line in g:
919 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000920
921 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000922 """Generate comparison results for a same-tagged range."""
Tim Peters5e824c32001-08-12 22:25:01 +0000923 for i in xrange(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000924 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000925
926 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
927 assert alo < ahi and blo < bhi
928 # dump the shorter block first -- reduces the burden on short-term
929 # memory if the blocks are of very different sizes
930 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000931 first = self._dump('+', b, blo, bhi)
932 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000933 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000934 first = self._dump('-', a, alo, ahi)
935 second = self._dump('+', b, blo, bhi)
936
937 for g in first, second:
938 for line in g:
939 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000940
941 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
942 r"""
943 When replacing one block of lines with another, search the blocks
944 for *similar* lines; the best-matching pair (if any) is used as a
945 synch point, and intraline difference marking is done on the
946 similar pair. Lots of work, but often worth it.
947
948 Example:
949
950 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000951 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
952 ... ['abcdefGhijkl\n'], 0, 1)
953 >>> print ''.join(results),
Tim Peters5e824c32001-08-12 22:25:01 +0000954 - abcDefghiJkl
955 ? ^ ^ ^
956 + abcdefGhijkl
957 ? ^ ^ ^
958 """
959
Tim Peters5e824c32001-08-12 22:25:01 +0000960 # don't synch up unless the lines have a similarity score of at
961 # least cutoff; best_ratio tracks the best score seen so far
962 best_ratio, cutoff = 0.74, 0.75
963 cruncher = SequenceMatcher(self.charjunk)
964 eqi, eqj = None, None # 1st indices of equal lines (if any)
965
966 # search for the pair that matches best without being identical
967 # (identical lines must be junk lines, & we don't want to synch up
968 # on junk -- unless we have to)
969 for j in xrange(blo, bhi):
970 bj = b[j]
971 cruncher.set_seq2(bj)
972 for i in xrange(alo, ahi):
973 ai = a[i]
974 if ai == bj:
975 if eqi is None:
976 eqi, eqj = i, j
977 continue
978 cruncher.set_seq1(ai)
979 # computing similarity is expensive, so use the quick
980 # upper bounds first -- have seen this speed up messy
981 # compares by a factor of 3.
982 # note that ratio() is only expensive to compute the first
983 # time it's called on a sequence pair; the expensive part
984 # of the computation is cached by cruncher
985 if cruncher.real_quick_ratio() > best_ratio and \
986 cruncher.quick_ratio() > best_ratio and \
987 cruncher.ratio() > best_ratio:
988 best_ratio, best_i, best_j = cruncher.ratio(), i, j
989 if best_ratio < cutoff:
990 # no non-identical "pretty close" pair
991 if eqi is None:
992 # no identical pair either -- treat it as a straight replace
Tim Peters8a9c2842001-09-22 21:30:22 +0000993 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
994 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000995 return
996 # no close pair, but an identical pair -- synch up on that
997 best_i, best_j, best_ratio = eqi, eqj, 1.0
998 else:
999 # there's a close pair, so forget the identical pair (if any)
1000 eqi = None
1001
1002 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
1003 # identical
Tim Peters5e824c32001-08-12 22:25:01 +00001004
1005 # pump out diffs from before the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001006 for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
1007 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001008
1009 # do intraline marking on the synch pair
1010 aelt, belt = a[best_i], b[best_j]
1011 if eqi is None:
1012 # pump out a '-', '?', '+', '?' quad for the synched lines
1013 atags = btags = ""
1014 cruncher.set_seqs(aelt, belt)
1015 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1016 la, lb = ai2 - ai1, bj2 - bj1
1017 if tag == 'replace':
1018 atags += '^' * la
1019 btags += '^' * lb
1020 elif tag == 'delete':
1021 atags += '-' * la
1022 elif tag == 'insert':
1023 btags += '+' * lb
1024 elif tag == 'equal':
1025 atags += ' ' * la
1026 btags += ' ' * lb
1027 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001028 raise ValueError, 'unknown tag %r' % (tag,)
Tim Peters8a9c2842001-09-22 21:30:22 +00001029 for line in self._qformat(aelt, belt, atags, btags):
1030 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001031 else:
1032 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001033 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001034
1035 # pump out diffs from after the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001036 for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
1037 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001038
1039 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001040 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001041 if alo < ahi:
1042 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001043 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001044 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001045 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001046 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001047 g = self._dump('+', b, blo, bhi)
1048
1049 for line in g:
1050 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001051
1052 def _qformat(self, aline, bline, atags, btags):
1053 r"""
1054 Format "?" output and deal with leading tabs.
1055
1056 Example:
1057
1058 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +00001059 >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n',
1060 ... ' ^ ^ ^ ', '+ ^ ^ ^ ')
1061 >>> for line in results: print repr(line)
Tim Peters5e824c32001-08-12 22:25:01 +00001062 ...
1063 '- \tabcDefghiJkl\n'
1064 '? \t ^ ^ ^\n'
1065 '+ \t\tabcdefGhijkl\n'
1066 '? \t ^ ^ ^\n'
1067 """
1068
1069 # Can hurt, but will probably help most of the time.
1070 common = min(_count_leading(aline, "\t"),
1071 _count_leading(bline, "\t"))
1072 common = min(common, _count_leading(atags[:common], " "))
1073 atags = atags[common:].rstrip()
1074 btags = btags[common:].rstrip()
1075
Tim Peters8a9c2842001-09-22 21:30:22 +00001076 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001077 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001078 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001079
Tim Peters8a9c2842001-09-22 21:30:22 +00001080 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001081 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001082 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001083
1084# With respect to junk, an earlier version of ndiff simply refused to
1085# *start* a match with a junk element. The result was cases like this:
1086# before: private Thread currentThread;
1087# after: private volatile Thread currentThread;
1088# If you consider whitespace to be junk, the longest contiguous match
1089# not starting with junk is "e Thread currentThread". So ndiff reported
1090# that "e volatil" was inserted between the 't' and the 'e' in "private".
1091# While an accurate view, to people that's absurd. The current version
1092# looks for matching blocks that are entirely junk-free, then extends the
1093# longest one of those as far as possible but only with matching junk.
1094# So now "currentThread" is matched, then extended to suck up the
1095# preceding blank; then "private" is matched, and extended to suck up the
1096# following blank; then "Thread" is matched; and finally ndiff reports
1097# that "volatile " was inserted before "Thread". The only quibble
1098# remaining is that perhaps it was really the case that " volatile"
1099# was inserted after "private". I can live with that <wink>.
1100
1101import re
1102
1103def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1104 r"""
1105 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1106
1107 Examples:
1108
1109 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001110 True
Tim Peters5e824c32001-08-12 22:25:01 +00001111 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001112 True
Tim Peters5e824c32001-08-12 22:25:01 +00001113 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001114 False
Tim Peters5e824c32001-08-12 22:25:01 +00001115 """
1116
1117 return pat(line) is not None
1118
1119def IS_CHARACTER_JUNK(ch, ws=" \t"):
1120 r"""
1121 Return 1 for ignorable character: iff `ch` is a space or tab.
1122
1123 Examples:
1124
1125 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001126 True
Tim Peters5e824c32001-08-12 22:25:01 +00001127 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001128 True
Tim Peters5e824c32001-08-12 22:25:01 +00001129 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001130 False
Tim Peters5e824c32001-08-12 22:25:01 +00001131 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001132 False
Tim Peters5e824c32001-08-12 22:25:01 +00001133 """
1134
1135 return ch in ws
1136
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001137
1138def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1139 tofiledate='', n=3, lineterm='\n'):
1140 r"""
1141 Compare two sequences of lines; generate the delta as a unified diff.
1142
1143 Unified diffs are a compact way of showing line changes and a few
1144 lines of context. The number of context lines is set by 'n' which
1145 defaults to three.
1146
Raymond Hettinger0887c732003-06-17 16:53:25 +00001147 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001148 created with a trailing newline. This is helpful so that inputs
1149 created from file.readlines() result in diffs that are suitable for
1150 file.writelines() since both the inputs and outputs have trailing
1151 newlines.
1152
1153 For inputs that do not have trailing newlines, set the lineterm
1154 argument to "" so that the output will be uniformly newline free.
1155
1156 The unidiff format normally has a header for filenames and modification
1157 times. Any or all of these may be specified using strings for
1158 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification
1159 times are normally expressed in the format returned by time.ctime().
1160
1161 Example:
1162
1163 >>> for line in unified_diff('one two three four'.split(),
1164 ... 'zero one tree four'.split(), 'Original', 'Current',
1165 ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003',
1166 ... lineterm=''):
1167 ... print line
1168 --- Original Sat Jan 26 23:30:50 1991
1169 +++ Current Fri Jun 06 10:20:52 2003
1170 @@ -1,4 +1,4 @@
1171 +zero
1172 one
1173 -two
1174 -three
1175 +tree
1176 four
1177 """
1178
1179 started = False
1180 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1181 if not started:
1182 yield '--- %s %s%s' % (fromfile, fromfiledate, lineterm)
1183 yield '+++ %s %s%s' % (tofile, tofiledate, lineterm)
1184 started = True
1185 i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
1186 yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
1187 for tag, i1, i2, j1, j2 in group:
1188 if tag == 'equal':
1189 for line in a[i1:i2]:
1190 yield ' ' + line
1191 continue
1192 if tag == 'replace' or tag == 'delete':
1193 for line in a[i1:i2]:
1194 yield '-' + line
1195 if tag == 'replace' or tag == 'insert':
1196 for line in b[j1:j2]:
1197 yield '+' + line
1198
1199# See http://www.unix.org/single_unix_specification/
1200def context_diff(a, b, fromfile='', tofile='',
1201 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1202 r"""
1203 Compare two sequences of lines; generate the delta as a context diff.
1204
1205 Context diffs are a compact way of showing line changes and a few
1206 lines of context. The number of context lines is set by 'n' which
1207 defaults to three.
1208
1209 By default, the diff control lines (those with *** or ---) are
1210 created with a trailing newline. This is helpful so that inputs
1211 created from file.readlines() result in diffs that are suitable for
1212 file.writelines() since both the inputs and outputs have trailing
1213 newlines.
1214
1215 For inputs that do not have trailing newlines, set the lineterm
1216 argument to "" so that the output will be uniformly newline free.
1217
1218 The context diff format normally has a header for filenames and
1219 modification times. Any or all of these may be specified using
1220 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1221 The modification times are normally expressed in the format returned
1222 by time.ctime(). If not specified, the strings default to blanks.
1223
1224 Example:
1225
1226 >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
1227 ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current',
1228 ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')),
1229 *** Original Sat Jan 26 23:30:50 1991
1230 --- Current Fri Jun 06 10:22:46 2003
1231 ***************
1232 *** 1,4 ****
1233 one
1234 ! two
1235 ! three
1236 four
1237 --- 1,4 ----
1238 + zero
1239 one
1240 ! tree
1241 four
1242 """
1243
1244 started = False
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001245 prefixmap = {'insert':'+ ', 'delete':'- ', 'replace':'! ', 'equal':' '}
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001246 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1247 if not started:
1248 yield '*** %s %s%s' % (fromfile, fromfiledate, lineterm)
1249 yield '--- %s %s%s' % (tofile, tofiledate, lineterm)
1250 started = True
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001251
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001252 yield '***************%s' % (lineterm,)
1253 if group[-1][2] - group[0][1] >= 2:
1254 yield '*** %d,%d ****%s' % (group[0][1]+1, group[-1][2], lineterm)
1255 else:
1256 yield '*** %d ****%s' % (group[-1][2], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001257 visiblechanges = [e for e in group if e[0] in ('replace', 'delete')]
1258 if visiblechanges:
1259 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001260 if tag != 'insert':
1261 for line in a[i1:i2]:
1262 yield prefixmap[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001263
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001264 if group[-1][4] - group[0][3] >= 2:
1265 yield '--- %d,%d ----%s' % (group[0][3]+1, group[-1][4], lineterm)
1266 else:
1267 yield '--- %d ----%s' % (group[-1][4], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001268 visiblechanges = [e for e in group if e[0] in ('replace', 'insert')]
1269 if visiblechanges:
1270 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001271 if tag != 'delete':
1272 for line in b[j1:j2]:
1273 yield prefixmap[tag] + line
1274
Tim Peters81b92512002-04-29 01:37:32 +00001275def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001276 r"""
1277 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1278
1279 Optional keyword parameters `linejunk` and `charjunk` are for filter
1280 functions (or None):
1281
1282 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001283 return true iff the string is junk. The default is None, and is
1284 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1285 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001286
1287 - charjunk: A function that should accept a string of length 1. The
1288 default is module-level function IS_CHARACTER_JUNK, which filters out
1289 whitespace characters (a blank or tab; note: bad idea to include newline
1290 in this!).
1291
1292 Tools/scripts/ndiff.py is a command-line front-end to this function.
1293
1294 Example:
1295
1296 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1297 ... 'ore\ntree\nemu\n'.splitlines(1))
1298 >>> print ''.join(diff),
1299 - one
1300 ? ^
1301 + ore
1302 ? ^
1303 - two
1304 - three
1305 ? -
1306 + tree
1307 + emu
1308 """
1309 return Differ(linejunk, charjunk).compare(a, b)
1310
Martin v. Löwise064b412004-08-29 16:34:40 +00001311def _mdiff(fromlines, tolines, context=None, linejunk=None,
1312 charjunk=IS_CHARACTER_JUNK):
1313 """Returns generator yielding marked up from/to side by side differences.
1314
1315 Arguments:
1316 fromlines -- list of text lines to compared to tolines
1317 tolines -- list of text lines to be compared to fromlines
1318 context -- number of context lines to display on each side of difference,
1319 if None, all from/to text lines will be generated.
1320 linejunk -- passed on to ndiff (see ndiff documentation)
1321 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001322
Martin v. Löwise064b412004-08-29 16:34:40 +00001323 This function returns an interator which returns a tuple:
1324 (from line tuple, to line tuple, boolean flag)
1325
1326 from/to line tuple -- (line num, line text)
1327 line num -- integer or None (to indicate a context seperation)
1328 line text -- original line text with following markers inserted:
1329 '\0+' -- marks start of added text
1330 '\0-' -- marks start of deleted text
1331 '\0^' -- marks start of changed text
1332 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001333
Martin v. Löwise064b412004-08-29 16:34:40 +00001334 boolean flag -- None indicates context separation, True indicates
1335 either "from" or "to" line contains a change, otherwise False.
1336
1337 This function/iterator was originally developed to generate side by side
1338 file difference for making HTML pages (see HtmlDiff class for example
1339 usage).
1340
1341 Note, this function utilizes the ndiff function to generate the side by
1342 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001343 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001344 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001345 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001346
1347 # regular expression for finding intraline change indices
1348 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001349
Martin v. Löwise064b412004-08-29 16:34:40 +00001350 # create the difference iterator to generate the differences
1351 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1352
1353 def _make_line(lines, format_key, side, num_lines=[0,0]):
1354 """Returns line of text with user's change markup and line formatting.
1355
1356 lines -- list of lines from the ndiff generator to produce a line of
1357 text from. When producing the line of text to return, the
1358 lines used are removed from this list.
1359 format_key -- '+' return first line in list with "add" markup around
1360 the entire line.
1361 '-' return first line in list with "delete" markup around
1362 the entire line.
1363 '?' return first line in list with add/delete/change
1364 intraline markup (indices obtained from second line)
1365 None return first line in list with no markup
1366 side -- indice into the num_lines list (0=from,1=to)
1367 num_lines -- from/to current line number. This is NOT intended to be a
1368 passed parameter. It is present as a keyword argument to
1369 maintain memory of the current line numbers between calls
1370 of this function.
1371
1372 Note, this function is purposefully not defined at the module scope so
1373 that data it needs from its parent function (within whose context it
1374 is defined) does not need to be of module scope.
1375 """
1376 num_lines[side] += 1
1377 # Handle case where no user markup is to be added, just return line of
1378 # text with user's line format to allow for usage of the line number.
1379 if format_key is None:
1380 return (num_lines[side],lines.pop(0)[2:])
1381 # Handle case of intraline changes
1382 if format_key == '?':
1383 text, markers = lines.pop(0), lines.pop(0)
1384 # find intraline changes (store change type and indices in tuples)
1385 sub_info = []
1386 def record_sub_info(match_object,sub_info=sub_info):
1387 sub_info.append([match_object.group(1)[0],match_object.span()])
1388 return match_object.group(1)
1389 change_re.sub(record_sub_info,markers)
1390 # process each tuple inserting our special marks that won't be
1391 # noticed by an xml/html escaper.
1392 for key,(begin,end) in sub_info[::-1]:
1393 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1394 text = text[2:]
1395 # Handle case of add/delete entire line
1396 else:
1397 text = lines.pop(0)[2:]
1398 # if line of text is just a newline, insert a space so there is
1399 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001400 if not text:
1401 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001402 # insert marks that won't be noticed by an xml/html escaper.
1403 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001404 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001405 # thing (such as adding the line number) then replace the special
1406 # marks with what the user's change markup.
1407 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001408
Martin v. Löwise064b412004-08-29 16:34:40 +00001409 def _line_iterator():
1410 """Yields from/to lines of text with a change indication.
1411
1412 This function is an iterator. It itself pulls lines from a
1413 differencing iterator, processes them and yields them. When it can
1414 it yields both a "from" and a "to" line, otherwise it will yield one
1415 or the other. In addition to yielding the lines of from/to text, a
1416 boolean flag is yielded to indicate if the text line(s) have
1417 differences in them.
1418
1419 Note, this function is purposefully not defined at the module scope so
1420 that data it needs from its parent function (within whose context it
1421 is defined) does not need to be of module scope.
1422 """
1423 lines = []
1424 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001425 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001426 # Load up next 4 lines so we can look ahead, create strings which
1427 # are a concatenation of the first character of each of the 4 lines
1428 # so we can do some very readable comparisons.
1429 while len(lines) < 4:
1430 try:
1431 lines.append(diff_lines_iterator.next())
1432 except StopIteration:
1433 lines.append('X')
1434 s = ''.join([line[0] for line in lines])
1435 if s.startswith('X'):
1436 # When no more lines, pump out any remaining blank lines so the
1437 # corresponding add/delete lines get a matching blank line so
1438 # all line pairs get yielded at the next level.
1439 num_blanks_to_yield = num_blanks_pending
1440 elif s.startswith('-?+?'):
1441 # simple intraline change
1442 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1443 continue
1444 elif s.startswith('--++'):
1445 # in delete block, add block coming: we do NOT want to get
1446 # caught up on blank lines yet, just process the delete line
1447 num_blanks_pending -= 1
1448 yield _make_line(lines,'-',0), None, True
1449 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001450 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001451 # in delete block and see a intraline change or unchanged line
1452 # coming: yield the delete line and then blanks
1453 from_line,to_line = _make_line(lines,'-',0), None
1454 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1455 elif s.startswith('-+?'):
1456 # intraline change
1457 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1458 continue
1459 elif s.startswith('-?+'):
1460 # intraline change
1461 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1462 continue
1463 elif s.startswith('-'):
1464 # delete FROM line
1465 num_blanks_pending -= 1
1466 yield _make_line(lines,'-',0), None, True
1467 continue
1468 elif s.startswith('+--'):
1469 # in add block, delete block coming: we do NOT want to get
1470 # caught up on blank lines yet, just process the add line
1471 num_blanks_pending += 1
1472 yield None, _make_line(lines,'+',1), True
1473 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001474 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001475 # will be leaving an add block: yield blanks then add line
1476 from_line, to_line = None, _make_line(lines,'+',1)
1477 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1478 elif s.startswith('+'):
1479 # inside an add block, yield the add line
1480 num_blanks_pending += 1
1481 yield None, _make_line(lines,'+',1), True
1482 continue
1483 elif s.startswith(' '):
1484 # unchanged text, yield it to both sides
1485 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1486 continue
1487 # Catch up on the blank lines so when we yield the next from/to
1488 # pair, they are lined up.
1489 while(num_blanks_to_yield < 0):
1490 num_blanks_to_yield += 1
1491 yield None,('','\n'),True
1492 while(num_blanks_to_yield > 0):
1493 num_blanks_to_yield -= 1
1494 yield ('','\n'),None,True
1495 if s.startswith('X'):
1496 raise StopIteration
1497 else:
1498 yield from_line,to_line,True
1499
1500 def _line_pair_iterator():
1501 """Yields from/to lines of text with a change indication.
1502
1503 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001504 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001505 always yields a pair of from/to text lines (with the change
1506 indication). If necessary it will collect single from/to lines
1507 until it has a matching pair from/to pair to yield.
1508
1509 Note, this function is purposefully not defined at the module scope so
1510 that data it needs from its parent function (within whose context it
1511 is defined) does not need to be of module scope.
1512 """
1513 line_iterator = _line_iterator()
1514 fromlines,tolines=[],[]
1515 while True:
1516 # Collecting lines of text until we have a from/to pair
1517 while (len(fromlines)==0 or len(tolines)==0):
1518 from_line, to_line, found_diff =line_iterator.next()
1519 if from_line is not None:
1520 fromlines.append((from_line,found_diff))
1521 if to_line is not None:
1522 tolines.append((to_line,found_diff))
1523 # Once we have a pair, remove them from the collection and yield it
1524 from_line, fromDiff = fromlines.pop(0)
1525 to_line, to_diff = tolines.pop(0)
1526 yield (from_line,to_line,fromDiff or to_diff)
1527
1528 # Handle case where user does not want context differencing, just yield
1529 # them up without doing anything else with them.
1530 line_pair_iterator = _line_pair_iterator()
1531 if context is None:
1532 while True:
1533 yield line_pair_iterator.next()
1534 # Handle case where user wants context differencing. We must do some
1535 # storage of lines until we know for sure that they are to be yielded.
1536 else:
1537 context += 1
1538 lines_to_write = 0
1539 while True:
1540 # Store lines up until we find a difference, note use of a
1541 # circular queue because we only need to keep around what
1542 # we need for context.
1543 index, contextLines = 0, [None]*(context)
1544 found_diff = False
1545 while(found_diff is False):
1546 from_line, to_line, found_diff = line_pair_iterator.next()
1547 i = index % context
1548 contextLines[i] = (from_line, to_line, found_diff)
1549 index += 1
1550 # Yield lines that we have collected so far, but first yield
1551 # the user's separator.
1552 if index > context:
1553 yield None, None, None
1554 lines_to_write = context
1555 else:
1556 lines_to_write = index
1557 index = 0
1558 while(lines_to_write):
1559 i = index % context
1560 index += 1
1561 yield contextLines[i]
1562 lines_to_write -= 1
1563 # Now yield the context lines after the change
1564 lines_to_write = context-1
1565 while(lines_to_write):
1566 from_line, to_line, found_diff = line_pair_iterator.next()
1567 # If another change within the context, extend the context
1568 if found_diff:
1569 lines_to_write = context-1
1570 else:
1571 lines_to_write -= 1
1572 yield from_line, to_line, found_diff
1573
1574
1575_file_template = """
1576<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1577 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1578
1579<html>
1580
1581<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001582 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001583 content="text/html; charset=ISO-8859-1" />
1584 <title></title>
1585 <style type="text/css">%(styles)s
1586 </style>
1587</head>
1588
1589<body>
1590 %(table)s%(legend)s
1591</body>
1592
1593</html>"""
1594
1595_styles = """
1596 table.diff {font-family:Courier; border:medium;}
1597 .diff_header {background-color:#e0e0e0}
1598 td.diff_header {text-align:right}
1599 .diff_next {background-color:#c0c0c0}
1600 .diff_add {background-color:#aaffaa}
1601 .diff_chg {background-color:#ffff77}
1602 .diff_sub {background-color:#ffaaaa}"""
1603
1604_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001605 <table class="diff" id="difflib_chg_%(prefix)s_top"
1606 cellspacing="0" cellpadding="0" rules="groups" >
1607 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001608 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1609 %(header_row)s
1610 <tbody>
1611%(data_rows)s </tbody>
1612 </table>"""
1613
1614_legend = """
1615 <table class="diff" summary="Legends">
1616 <tr> <th colspan="2"> Legends </th> </tr>
1617 <tr> <td> <table border="" summary="Colors">
1618 <tr><th> Colors </th> </tr>
1619 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1620 <tr><td class="diff_chg">Changed</td> </tr>
1621 <tr><td class="diff_sub">Deleted</td> </tr>
1622 </table></td>
1623 <td> <table border="" summary="Links">
1624 <tr><th colspan="2"> Links </th> </tr>
1625 <tr><td>(f)irst change</td> </tr>
1626 <tr><td>(n)ext change</td> </tr>
1627 <tr><td>(t)op</td> </tr>
1628 </table></td> </tr>
1629 </table>"""
1630
1631class HtmlDiff(object):
1632 """For producing HTML side by side comparison with change highlights.
1633
1634 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001635 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001636 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001637 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001638
Martin v. Löwise064b412004-08-29 16:34:40 +00001639 The following methods are provided for HTML generation:
1640
1641 make_table -- generates HTML for a single side by side table
1642 make_file -- generates complete HTML file with a single side by side table
1643
Tim Peters48bd7f32004-08-29 22:38:38 +00001644 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001645 """
1646
1647 _file_template = _file_template
1648 _styles = _styles
1649 _table_template = _table_template
1650 _legend = _legend
1651 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001652
Martin v. Löwise064b412004-08-29 16:34:40 +00001653 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1654 charjunk=IS_CHARACTER_JUNK):
1655 """HtmlDiff instance initializer
1656
1657 Arguments:
1658 tabsize -- tab stop spacing, defaults to 8.
1659 wrapcolumn -- column number where lines are broken and wrapped,
1660 defaults to None where lines are not wrapped.
1661 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001662 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001663 ndiff() documentation for argument default values and descriptions.
1664 """
1665 self._tabsize = tabsize
1666 self._wrapcolumn = wrapcolumn
1667 self._linejunk = linejunk
1668 self._charjunk = charjunk
1669
1670 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1671 numlines=5):
1672 """Returns HTML file of side by side comparison with change highlights
1673
1674 Arguments:
1675 fromlines -- list of "from" lines
1676 tolines -- list of "to" lines
1677 fromdesc -- "from" file column header string
1678 todesc -- "to" file column header string
1679 context -- set to True for contextual differences (defaults to False
1680 which shows full differences).
1681 numlines -- number of context lines. When context is set True,
1682 controls number of lines displayed before and after the change.
1683 When context is False, controls the number of lines to place
1684 the "next" link anchors before the next change (so click of
1685 "next" link jumps to just before the change).
1686 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001687
Martin v. Löwise064b412004-08-29 16:34:40 +00001688 return self._file_template % dict(
1689 styles = self._styles,
1690 legend = self._legend,
1691 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1692 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001693
Martin v. Löwise064b412004-08-29 16:34:40 +00001694 def _tab_newline_replace(self,fromlines,tolines):
1695 """Returns from/to line lists with tabs expanded and newlines removed.
1696
1697 Instead of tab characters being replaced by the number of spaces
1698 needed to fill in to the next tab stop, this function will fill
1699 the space with tab characters. This is done so that the difference
1700 algorithms can identify changes in a file when tabs are replaced by
1701 spaces and vice versa. At the end of the HTML generation, the tab
1702 characters will be replaced with a nonbreakable space.
1703 """
1704 def expand_tabs(line):
1705 # hide real spaces
1706 line = line.replace(' ','\0')
1707 # expand tabs into spaces
1708 line = line.expandtabs(self._tabsize)
1709 # relace spaces from expanded tabs back into tab characters
1710 # (we'll replace them with markup after we do differencing)
1711 line = line.replace(' ','\t')
1712 return line.replace('\0',' ').rstrip('\n')
1713 fromlines = [expand_tabs(line) for line in fromlines]
1714 tolines = [expand_tabs(line) for line in tolines]
1715 return fromlines,tolines
1716
1717 def _split_line(self,data_list,line_num,text):
1718 """Builds list of text lines by splitting text lines at wrap point
1719
1720 This function will determine if the input text line needs to be
1721 wrapped (split) into separate lines. If so, the first wrap point
1722 will be determined and the first line appended to the output
1723 text line list. This function is used recursively to handle
1724 the second part of the split line to further split it.
1725 """
1726 # if blank line or context separator, just add it to the output list
1727 if not line_num:
1728 data_list.append((line_num,text))
1729 return
1730
1731 # if line text doesn't need wrapping, just add it to the output list
1732 size = len(text)
1733 max = self._wrapcolumn
1734 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1735 data_list.append((line_num,text))
1736 return
1737
1738 # scan text looking for the wrap point, keeping track if the wrap
1739 # point is inside markers
1740 i = 0
1741 n = 0
1742 mark = ''
1743 while n < max and i < size:
1744 if text[i] == '\0':
1745 i += 1
1746 mark = text[i]
1747 i += 1
1748 elif text[i] == '\1':
1749 i += 1
1750 mark = ''
1751 else:
1752 i += 1
1753 n += 1
1754
1755 # wrap point is inside text, break it up into separate lines
1756 line1 = text[:i]
1757 line2 = text[i:]
1758
1759 # if wrap point is inside markers, place end marker at end of first
1760 # line and start marker at beginning of second line because each
1761 # line will have its own table tag markup around it.
1762 if mark:
1763 line1 = line1 + '\1'
1764 line2 = '\0' + mark + line2
1765
Tim Peters48bd7f32004-08-29 22:38:38 +00001766 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001767 data_list.append((line_num,line1))
1768
Tim Peters48bd7f32004-08-29 22:38:38 +00001769 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001770 self._split_line(data_list,'>',line2)
1771
1772 def _line_wrapper(self,diffs):
1773 """Returns iterator that splits (wraps) mdiff text lines"""
1774
1775 # pull from/to data and flags from mdiff iterator
1776 for fromdata,todata,flag in diffs:
1777 # check for context separators and pass them through
1778 if flag is None:
1779 yield fromdata,todata,flag
1780 continue
1781 (fromline,fromtext),(toline,totext) = fromdata,todata
1782 # for each from/to line split it at the wrap column to form
1783 # list of text lines.
1784 fromlist,tolist = [],[]
1785 self._split_line(fromlist,fromline,fromtext)
1786 self._split_line(tolist,toline,totext)
1787 # yield from/to line in pairs inserting blank lines as
1788 # necessary when one side has more wrapped lines
1789 while fromlist or tolist:
1790 if fromlist:
1791 fromdata = fromlist.pop(0)
1792 else:
1793 fromdata = ('',' ')
1794 if tolist:
1795 todata = tolist.pop(0)
1796 else:
1797 todata = ('',' ')
1798 yield fromdata,todata,flag
1799
1800 def _collect_lines(self,diffs):
1801 """Collects mdiff output into separate lists
1802
1803 Before storing the mdiff from/to data into a list, it is converted
1804 into a single line of text with HTML markup.
1805 """
1806
1807 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001808 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001809 for fromdata,todata,flag in diffs:
1810 try:
1811 # store HTML markup of the lines into the lists
1812 fromlist.append(self._format_line(0,flag,*fromdata))
1813 tolist.append(self._format_line(1,flag,*todata))
1814 except TypeError:
1815 # exceptions occur for lines where context separators go
1816 fromlist.append(None)
1817 tolist.append(None)
1818 flaglist.append(flag)
1819 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001820
Martin v. Löwise064b412004-08-29 16:34:40 +00001821 def _format_line(self,side,flag,linenum,text):
1822 """Returns HTML markup of "from" / "to" text lines
1823
1824 side -- 0 or 1 indicating "from" or "to" text
1825 flag -- indicates if difference on line
1826 linenum -- line number (used for line number column)
1827 text -- line text to be marked up
1828 """
1829 try:
1830 linenum = '%d' % linenum
1831 id = ' id="%s%s"' % (self._prefix[side],linenum)
1832 except TypeError:
1833 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001834 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001835 # replace those things that would get confused with HTML symbols
1836 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1837
1838 # make space non-breakable so they don't get compressed or line wrapped
1839 text = text.replace(' ','&nbsp;').rstrip()
1840
1841 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1842 % (id,linenum,text)
1843
1844 def _make_prefix(self):
1845 """Create unique anchor prefixes"""
1846
1847 # Generate a unique anchor prefix so multiple tables
1848 # can exist on the same HTML page without conflicts.
1849 fromprefix = "from%d_" % HtmlDiff._default_prefix
1850 toprefix = "to%d_" % HtmlDiff._default_prefix
1851 HtmlDiff._default_prefix += 1
1852 # store prefixes so line format method has access
1853 self._prefix = [fromprefix,toprefix]
1854
1855 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1856 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001857
Martin v. Löwise064b412004-08-29 16:34:40 +00001858 # all anchor names will be generated using the unique "to" prefix
1859 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001860
Martin v. Löwise064b412004-08-29 16:34:40 +00001861 # process change flags, generating middle column of next anchors/links
1862 next_id = ['']*len(flaglist)
1863 next_href = ['']*len(flaglist)
1864 num_chg, in_change = 0, False
1865 last = 0
1866 for i,flag in enumerate(flaglist):
1867 if flag:
1868 if not in_change:
1869 in_change = True
1870 last = i
1871 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001872 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001873 # link
1874 i = max([0,i-numlines])
1875 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001876 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001877 # change
1878 num_chg += 1
1879 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1880 toprefix,num_chg)
1881 else:
1882 in_change = False
1883 # check for cases where there is no content to avoid exceptions
1884 if not flaglist:
1885 flaglist = [False]
1886 next_id = ['']
1887 next_href = ['']
1888 last = 0
1889 if context:
1890 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1891 tolist = fromlist
1892 else:
1893 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1894 # if not a change on first line, drop a link
1895 if not flaglist[0]:
1896 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1897 # redo the last link to link to the top
1898 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1899
1900 return fromlist,tolist,flaglist,next_href,next_id
1901
1902 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1903 numlines=5):
1904 """Returns HTML table of side by side comparison with change highlights
1905
1906 Arguments:
1907 fromlines -- list of "from" lines
1908 tolines -- list of "to" lines
1909 fromdesc -- "from" file column header string
1910 todesc -- "to" file column header string
1911 context -- set to True for contextual differences (defaults to False
1912 which shows full differences).
1913 numlines -- number of context lines. When context is set True,
1914 controls number of lines displayed before and after the change.
1915 When context is False, controls the number of lines to place
1916 the "next" link anchors before the next change (so click of
1917 "next" link jumps to just before the change).
1918 """
1919
1920 # make unique anchor prefixes so that multiple tables may exist
1921 # on the same page without conflict.
1922 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001923
Martin v. Löwise064b412004-08-29 16:34:40 +00001924 # change tabs to spaces before it gets more difficult after we insert
1925 # markkup
1926 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001927
Martin v. Löwise064b412004-08-29 16:34:40 +00001928 # create diffs iterator which generates side by side from/to data
1929 if context:
1930 context_lines = numlines
1931 else:
1932 context_lines = None
1933 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1934 charjunk=self._charjunk)
1935
1936 # set up iterator to wrap lines that exceed desired width
1937 if self._wrapcolumn:
1938 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001939
Martin v. Löwise064b412004-08-29 16:34:40 +00001940 # collect up from/to lines and flags into lists (also format the lines)
1941 fromlist,tolist,flaglist = self._collect_lines(diffs)
1942
1943 # process change flags, generating middle column of next anchors/links
1944 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1945 fromlist,tolist,flaglist,context,numlines)
1946
1947 import cStringIO
1948 s = cStringIO.StringIO()
1949 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1950 '<td class="diff_next">%s</td>%s</tr>\n'
1951 for i in range(len(flaglist)):
1952 if flaglist[i] is None:
1953 # mdiff yields None on separator lines skip the bogus ones
1954 # generated for the first line
1955 if i > 0:
1956 s.write(' </tbody> \n <tbody>\n')
1957 else:
1958 s.write( fmt % (next_id[i],next_href[i],fromlist[i],
1959 next_href[i],tolist[i]))
1960 if fromdesc or todesc:
1961 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
1962 '<th class="diff_next"><br /></th>',
1963 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
1964 '<th class="diff_next"><br /></th>',
1965 '<th colspan="2" class="diff_header">%s</th>' % todesc)
1966 else:
1967 header_row = ''
1968
1969 table = self._table_template % dict(
1970 data_rows=s.getvalue(),
1971 header_row=header_row,
1972 prefix=self._prefix[1])
1973
1974 return table.replace('\0+','<span class="diff_add">'). \
1975 replace('\0-','<span class="diff_sub">'). \
1976 replace('\0^','<span class="diff_chg">'). \
1977 replace('\1','</span>'). \
1978 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00001979
Martin v. Löwise064b412004-08-29 16:34:40 +00001980del re
1981
Tim Peters5e824c32001-08-12 22:25:01 +00001982def restore(delta, which):
1983 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00001984 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00001985
1986 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
1987 lines originating from file 1 or 2 (parameter `which`), stripping off line
1988 prefixes.
1989
1990 Examples:
1991
1992 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1993 ... 'ore\ntree\nemu\n'.splitlines(1))
Tim Peters8a9c2842001-09-22 21:30:22 +00001994 >>> diff = list(diff)
Tim Peters5e824c32001-08-12 22:25:01 +00001995 >>> print ''.join(restore(diff, 1)),
1996 one
1997 two
1998 three
1999 >>> print ''.join(restore(diff, 2)),
2000 ore
2001 tree
2002 emu
2003 """
2004 try:
2005 tag = {1: "- ", 2: "+ "}[int(which)]
2006 except KeyError:
2007 raise ValueError, ('unknown delta choice (must be 1 or 2): %r'
2008 % which)
2009 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002010 for line in delta:
2011 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002012 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002013
Tim Peters9ae21482001-02-10 08:00:53 +00002014def _test():
2015 import doctest, difflib
2016 return doctest.testmod(difflib)
2017
2018if __name__ == "__main__":
2019 _test()