blob: f0bfcc507027e67cb4a513075dd0c558e3559fc6 [file] [log] [blame]
Tim Peters9ae21482001-02-10 08:00:53 +00001"""
2Module difflib -- helpers for computing deltas between objects.
3
4Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
Tim Peters9ae21482001-02-10 08:00:53 +00005 Use SequenceMatcher to return list of the best "good enough" matches.
6
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00007Function context_diff(a, b):
8 For two lists of strings, return a delta in context diff format.
9
Tim Peters5e824c32001-08-12 22:25:01 +000010Function ndiff(a, b):
11 Return a delta: the difference between `a` and `b` (lists of strings).
Tim Peters9ae21482001-02-10 08:00:53 +000012
Tim Peters5e824c32001-08-12 22:25:01 +000013Function restore(delta, which):
14 Return one of the two sequences that generated an ndiff delta.
Tim Peters9ae21482001-02-10 08:00:53 +000015
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000016Function unified_diff(a, b):
17 For two lists of strings, return a delta in unified diff format.
18
Tim Peters5e824c32001-08-12 22:25:01 +000019Class SequenceMatcher:
20 A flexible class for comparing pairs of sequences of any type.
Tim Peters9ae21482001-02-10 08:00:53 +000021
Tim Peters5e824c32001-08-12 22:25:01 +000022Class Differ:
23 For producing human-readable deltas from sequences of lines of text.
Martin v. Löwise064b412004-08-29 16:34:40 +000024
25Class HtmlDiff:
26 For producing HTML side by side comparison with change highlights.
Tim Peters9ae21482001-02-10 08:00:53 +000027"""
28
Tim Peters5e824c32001-08-12 22:25:01 +000029__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000030 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
Christian Heimes25bb7832008-01-11 16:17:00 +000031 'unified_diff', 'HtmlDiff', 'Match']
Tim Peters5e824c32001-08-12 22:25:01 +000032
Terry Reedybcd89882010-12-03 22:29:40 +000033import warnings
Raymond Hettingerbb6b7342004-06-13 09:57:33 +000034import heapq
Christian Heimes25bb7832008-01-11 16:17:00 +000035from collections import namedtuple as _namedtuple
36
37Match = _namedtuple('Match', 'a b size')
Raymond Hettingerbb6b7342004-06-13 09:57:33 +000038
Neal Norwitze7dfe212003-07-01 14:59:46 +000039def _calculate_ratio(matches, length):
40 if length:
41 return 2.0 * matches / length
42 return 1.0
43
Tim Peters9ae21482001-02-10 08:00:53 +000044class SequenceMatcher:
Tim Peters5e824c32001-08-12 22:25:01 +000045
46 """
47 SequenceMatcher is a flexible class for comparing pairs of sequences of
48 any type, so long as the sequence elements are hashable. The basic
49 algorithm predates, and is a little fancier than, an algorithm
50 published in the late 1980's by Ratcliff and Obershelp under the
51 hyperbolic name "gestalt pattern matching". The basic idea is to find
52 the longest contiguous matching subsequence that contains no "junk"
53 elements (R-O doesn't address junk). The same idea is then applied
54 recursively to the pieces of the sequences to the left and to the right
55 of the matching subsequence. This does not yield minimal edit
56 sequences, but does tend to yield matches that "look right" to people.
57
58 SequenceMatcher tries to compute a "human-friendly diff" between two
59 sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
60 longest *contiguous* & junk-free matching subsequence. That's what
61 catches peoples' eyes. The Windows(tm) windiff has another interesting
62 notion, pairing up elements that appear uniquely in each sequence.
63 That, and the method here, appear to yield more intuitive difference
64 reports than does diff. This method appears to be the least vulnerable
65 to synching up on blocks of "junk lines", though (like blank lines in
66 ordinary text files, or maybe "<P>" lines in HTML files). That may be
67 because this is the only method of the 3 that has a *concept* of
68 "junk" <wink>.
69
70 Example, comparing two strings, and considering blanks to be "junk":
71
72 >>> s = SequenceMatcher(lambda x: x == " ",
73 ... "private Thread currentThread;",
74 ... "private volatile Thread currentThread;")
75 >>>
76
77 .ratio() returns a float in [0, 1], measuring the "similarity" of the
78 sequences. As a rule of thumb, a .ratio() value over 0.6 means the
79 sequences are close matches:
80
Guido van Rossumfff80df2007-02-09 20:33:44 +000081 >>> print(round(s.ratio(), 3))
Tim Peters5e824c32001-08-12 22:25:01 +000082 0.866
83 >>>
84
85 If you're only interested in where the sequences match,
86 .get_matching_blocks() is handy:
87
88 >>> for block in s.get_matching_blocks():
Guido van Rossumfff80df2007-02-09 20:33:44 +000089 ... print("a[%d] and b[%d] match for %d elements" % block)
Tim Peters5e824c32001-08-12 22:25:01 +000090 a[0] and b[0] match for 8 elements
Thomas Wouters0e3f5912006-08-11 14:57:12 +000091 a[8] and b[17] match for 21 elements
Tim Peters5e824c32001-08-12 22:25:01 +000092 a[29] and b[38] match for 0 elements
93
94 Note that the last tuple returned by .get_matching_blocks() is always a
95 dummy, (len(a), len(b), 0), and this is the only case in which the last
96 tuple element (number of elements matched) is 0.
97
98 If you want to know how to change the first sequence into the second,
99 use .get_opcodes():
100
101 >>> for opcode in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000102 ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
Tim Peters5e824c32001-08-12 22:25:01 +0000103 equal a[0:8] b[0:8]
104 insert a[8:8] b[8:17]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105 equal a[8:29] b[17:38]
Tim Peters5e824c32001-08-12 22:25:01 +0000106
107 See the Differ class for a fancy human-friendly file differencer, which
108 uses SequenceMatcher both to compare sequences of lines, and to compare
109 sequences of characters within similar (near-matching) lines.
110
111 See also function get_close_matches() in this module, which shows how
112 simple code building on SequenceMatcher can be used to do useful work.
113
114 Timing: Basic R-O is cubic time worst case and quadratic time expected
115 case. SequenceMatcher is quadratic time for the worst case and has
116 expected-case behavior dependent in a complicated way on how many
117 elements the sequences have in common; best case time is linear.
118
119 Methods:
120
121 __init__(isjunk=None, a='', b='')
122 Construct a SequenceMatcher.
123
124 set_seqs(a, b)
125 Set the two sequences to be compared.
126
127 set_seq1(a)
128 Set the first sequence to be compared.
129
130 set_seq2(b)
131 Set the second sequence to be compared.
132
133 find_longest_match(alo, ahi, blo, bhi)
134 Find longest matching block in a[alo:ahi] and b[blo:bhi].
135
136 get_matching_blocks()
137 Return list of triples describing matching subsequences.
138
139 get_opcodes()
140 Return list of 5-tuples describing how to turn a into b.
141
142 ratio()
143 Return a measure of the sequences' similarity (float in [0,1]).
144
145 quick_ratio()
146 Return an upper bound on .ratio() relatively quickly.
147
148 real_quick_ratio()
149 Return an upper bound on ratio() very quickly.
150 """
151
Terry Reedy99f96372010-11-25 06:12:34 +0000152 def __init__(self, isjunk=None, a='', b='', autojunk=True):
Tim Peters9ae21482001-02-10 08:00:53 +0000153 """Construct a SequenceMatcher.
154
155 Optional arg isjunk is None (the default), or a one-argument
156 function that takes a sequence element and returns true iff the
Tim Peters5e824c32001-08-12 22:25:01 +0000157 element is junk. None is equivalent to passing "lambda x: 0", i.e.
Fred Drakef1da6282001-02-19 19:30:05 +0000158 no elements are considered to be junk. For example, pass
Tim Peters9ae21482001-02-10 08:00:53 +0000159 lambda x: x in " \\t"
160 if you're comparing lines as sequences of characters, and don't
161 want to synch up on blanks or hard tabs.
162
163 Optional arg a is the first of two sequences to be compared. By
164 default, an empty string. The elements of a must be hashable. See
165 also .set_seqs() and .set_seq1().
166
167 Optional arg b is the second of two sequences to be compared. By
Fred Drakef1da6282001-02-19 19:30:05 +0000168 default, an empty string. The elements of b must be hashable. See
Tim Peters9ae21482001-02-10 08:00:53 +0000169 also .set_seqs() and .set_seq2().
Terry Reedy99f96372010-11-25 06:12:34 +0000170
171 Optional arg autojunk should be set to False to disable the
172 "automatic junk heuristic" that treats popular elements as junk
173 (see module documentation for more information).
Tim Peters9ae21482001-02-10 08:00:53 +0000174 """
175
176 # Members:
177 # a
178 # first sequence
179 # b
180 # second sequence; differences are computed as "what do
181 # we need to do to 'a' to change it into 'b'?"
182 # b2j
183 # for x in b, b2j[x] is a list of the indices (into b)
Terry Reedybcd89882010-12-03 22:29:40 +0000184 # at which x appears; junk and popular elements do not appear
Tim Peters9ae21482001-02-10 08:00:53 +0000185 # fullbcount
186 # for x in b, fullbcount[x] == the number of times x
187 # appears in b; only materialized if really needed (used
188 # only for computing quick_ratio())
189 # matching_blocks
190 # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
191 # ascending & non-overlapping in i and in j; terminated by
192 # a dummy (len(a), len(b), 0) sentinel
193 # opcodes
194 # a list of (tag, i1, i2, j1, j2) tuples, where tag is
195 # one of
196 # 'replace' a[i1:i2] should be replaced by b[j1:j2]
197 # 'delete' a[i1:i2] should be deleted
198 # 'insert' b[j1:j2] should be inserted
199 # 'equal' a[i1:i2] == b[j1:j2]
200 # isjunk
201 # a user-supplied function taking a sequence element and
202 # returning true iff the element is "junk" -- this has
203 # subtle but helpful effects on the algorithm, which I'll
204 # get around to writing up someday <0.9 wink>.
Florent Xicluna7f1c15b2011-12-10 13:02:17 +0100205 # DON'T USE! Only __chain_b uses this. Use "in self.bjunk".
Terry Reedy74a7c672010-12-03 18:57:42 +0000206 # bjunk
207 # the items in b for which isjunk is True.
208 # bpopular
209 # nonjunk items in b treated as junk by the heuristic (if used).
Tim Peters9ae21482001-02-10 08:00:53 +0000210
211 self.isjunk = isjunk
212 self.a = self.b = None
Terry Reedy99f96372010-11-25 06:12:34 +0000213 self.autojunk = autojunk
Tim Peters9ae21482001-02-10 08:00:53 +0000214 self.set_seqs(a, b)
215
216 def set_seqs(self, a, b):
217 """Set the two sequences to be compared.
218
219 >>> s = SequenceMatcher()
220 >>> s.set_seqs("abcd", "bcde")
221 >>> s.ratio()
222 0.75
223 """
224
225 self.set_seq1(a)
226 self.set_seq2(b)
227
228 def set_seq1(self, a):
229 """Set the first sequence to be compared.
230
231 The second sequence to be compared is not changed.
232
233 >>> s = SequenceMatcher(None, "abcd", "bcde")
234 >>> s.ratio()
235 0.75
236 >>> s.set_seq1("bcde")
237 >>> s.ratio()
238 1.0
239 >>>
240
241 SequenceMatcher computes and caches detailed information about the
242 second sequence, so if you want to compare one sequence S against
243 many sequences, use .set_seq2(S) once and call .set_seq1(x)
244 repeatedly for each of the other sequences.
245
246 See also set_seqs() and set_seq2().
247 """
248
249 if a is self.a:
250 return
251 self.a = a
252 self.matching_blocks = self.opcodes = None
253
254 def set_seq2(self, b):
255 """Set the second sequence to be compared.
256
257 The first sequence to be compared is not changed.
258
259 >>> s = SequenceMatcher(None, "abcd", "bcde")
260 >>> s.ratio()
261 0.75
262 >>> s.set_seq2("abcd")
263 >>> s.ratio()
264 1.0
265 >>>
266
267 SequenceMatcher computes and caches detailed information about the
268 second sequence, so if you want to compare one sequence S against
269 many sequences, use .set_seq2(S) once and call .set_seq1(x)
270 repeatedly for each of the other sequences.
271
272 See also set_seqs() and set_seq1().
273 """
274
275 if b is self.b:
276 return
277 self.b = b
278 self.matching_blocks = self.opcodes = None
279 self.fullbcount = None
280 self.__chain_b()
281
282 # For each element x in b, set b2j[x] to a list of the indices in
283 # b where x appears; the indices are in increasing order; note that
284 # the number of times x appears in b is len(b2j[x]) ...
285 # when self.isjunk is defined, junk elements don't show up in this
286 # map at all, which stops the central find_longest_match method
287 # from starting any matching block at a junk element ...
Tim Peters81b92512002-04-29 01:37:32 +0000288 # b2j also does not contain entries for "popular" elements, meaning
Terry Reedy99f96372010-11-25 06:12:34 +0000289 # elements that account for more than 1 + 1% of the total elements, and
Tim Peters81b92512002-04-29 01:37:32 +0000290 # when the sequence is reasonably large (>= 200 elements); this can
291 # be viewed as an adaptive notion of semi-junk, and yields an enormous
292 # speedup when, e.g., comparing program files with hundreds of
293 # instances of "return NULL;" ...
Tim Peters9ae21482001-02-10 08:00:53 +0000294 # note that this is only called when b changes; so for cross-product
295 # kinds of matches, it's best to call set_seq2 once, then set_seq1
296 # repeatedly
297
298 def __chain_b(self):
299 # Because isjunk is a user-defined (not C) function, and we test
300 # for junk a LOT, it's important to minimize the number of calls.
301 # Before the tricks described here, __chain_b was by far the most
302 # time-consuming routine in the whole module! If anyone sees
303 # Jim Roskind, thank him again for profile.py -- I never would
304 # have guessed that.
305 # The first trick is to build b2j ignoring the possibility
306 # of junk. I.e., we don't call isjunk at all yet. Throwing
307 # out the junk later is much cheaper than building b2j "right"
308 # from the start.
309 b = self.b
310 self.b2j = b2j = {}
Terry Reedy99f96372010-11-25 06:12:34 +0000311
Tim Peters81b92512002-04-29 01:37:32 +0000312 for i, elt in enumerate(b):
Terry Reedy99f96372010-11-25 06:12:34 +0000313 indices = b2j.setdefault(elt, [])
314 indices.append(i)
Tim Peters9ae21482001-02-10 08:00:53 +0000315
Terry Reedy99f96372010-11-25 06:12:34 +0000316 # Purge junk elements
Terry Reedy74a7c672010-12-03 18:57:42 +0000317 self.bjunk = junk = set()
Tim Peters81b92512002-04-29 01:37:32 +0000318 isjunk = self.isjunk
Tim Peters9ae21482001-02-10 08:00:53 +0000319 if isjunk:
Terry Reedy17a59252010-12-15 20:18:10 +0000320 for elt in b2j.keys():
Terry Reedy99f96372010-11-25 06:12:34 +0000321 if isjunk(elt):
322 junk.add(elt)
Terry Reedy17a59252010-12-15 20:18:10 +0000323 for elt in junk: # separate loop avoids separate list of keys
324 del b2j[elt]
Tim Peters9ae21482001-02-10 08:00:53 +0000325
Terry Reedy99f96372010-11-25 06:12:34 +0000326 # Purge popular elements that are not junk
Terry Reedy74a7c672010-12-03 18:57:42 +0000327 self.bpopular = popular = set()
Terry Reedy99f96372010-11-25 06:12:34 +0000328 n = len(b)
329 if self.autojunk and n >= 200:
330 ntest = n // 100 + 1
Terry Reedy17a59252010-12-15 20:18:10 +0000331 for elt, idxs in b2j.items():
Terry Reedy99f96372010-11-25 06:12:34 +0000332 if len(idxs) > ntest:
333 popular.add(elt)
Terry Reedy17a59252010-12-15 20:18:10 +0000334 for elt in popular: # ditto; as fast for 1% deletion
335 del b2j[elt]
Terry Reedy99f96372010-11-25 06:12:34 +0000336
Terry Reedybcd89882010-12-03 22:29:40 +0000337 def isbjunk(self, item):
338 "Deprecated; use 'item in SequenceMatcher().bjunk'."
339 warnings.warn("'SequenceMatcher().isbjunk(item)' is deprecated;\n"
340 "use 'item in SMinstance.bjunk' instead.",
341 DeprecationWarning, 2)
342 return item in self.bjunk
343
344 def isbpopular(self, item):
345 "Deprecated; use 'item in SequenceMatcher().bpopular'."
346 warnings.warn("'SequenceMatcher().isbpopular(item)' is deprecated;\n"
347 "use 'item in SMinstance.bpopular' instead.",
348 DeprecationWarning, 2)
349 return item in self.bpopular
Tim Peters9ae21482001-02-10 08:00:53 +0000350
351 def find_longest_match(self, alo, ahi, blo, bhi):
352 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
353
354 If isjunk is not defined:
355
356 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
357 alo <= i <= i+k <= ahi
358 blo <= j <= j+k <= bhi
359 and for all (i',j',k') meeting those conditions,
360 k >= k'
361 i <= i'
362 and if i == i', j <= j'
363
364 In other words, of all maximal matching blocks, return one that
365 starts earliest in a, and of all those maximal matching blocks that
366 start earliest in a, return the one that starts earliest in b.
367
368 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
369 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000370 Match(a=0, b=4, size=5)
Tim Peters9ae21482001-02-10 08:00:53 +0000371
372 If isjunk is defined, first the longest matching block is
373 determined as above, but with the additional restriction that no
374 junk element appears in the block. Then that block is extended as
375 far as possible by matching (only) junk elements on both sides. So
376 the resulting block never matches on junk except as identical junk
377 happens to be adjacent to an "interesting" match.
378
379 Here's the same example as before, but considering blanks to be
380 junk. That prevents " abcd" from matching the " abcd" at the tail
381 end of the second sequence directly. Instead only the "abcd" can
382 match, and matches the leftmost "abcd" in the second sequence:
383
384 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
385 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000386 Match(a=1, b=0, size=4)
Tim Peters9ae21482001-02-10 08:00:53 +0000387
388 If no blocks match, return (alo, blo, 0).
389
390 >>> s = SequenceMatcher(None, "ab", "c")
391 >>> s.find_longest_match(0, 2, 0, 1)
Christian Heimes25bb7832008-01-11 16:17:00 +0000392 Match(a=0, b=0, size=0)
Tim Peters9ae21482001-02-10 08:00:53 +0000393 """
394
395 # CAUTION: stripping common prefix or suffix would be incorrect.
396 # E.g.,
397 # ab
398 # acab
399 # Longest matching block is "ab", but if common prefix is
400 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
401 # strip, so ends up claiming that ab is changed to acab by
402 # inserting "ca" in the middle. That's minimal but unintuitive:
403 # "it's obvious" that someone inserted "ac" at the front.
404 # Windiff ends up at the same place as diff, but by pairing up
405 # the unique 'b's and then matching the first two 'a's.
406
Terry Reedybcd89882010-12-03 22:29:40 +0000407 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000408 besti, bestj, bestsize = alo, blo, 0
409 # find longest junk-free match
410 # during an iteration of the loop, j2len[j] = length of longest
411 # junk-free match ending with a[i-1] and b[j]
412 j2len = {}
413 nothing = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000414 for i in range(alo, ahi):
Tim Peters9ae21482001-02-10 08:00:53 +0000415 # look at all instances of a[i] in b; note that because
416 # b2j has no junk keys, the loop is skipped if a[i] is junk
417 j2lenget = j2len.get
418 newj2len = {}
419 for j in b2j.get(a[i], nothing):
420 # a[i] matches b[j]
421 if j < blo:
422 continue
423 if j >= bhi:
424 break
425 k = newj2len[j] = j2lenget(j-1, 0) + 1
426 if k > bestsize:
427 besti, bestj, bestsize = i-k+1, j-k+1, k
428 j2len = newj2len
429
Tim Peters81b92512002-04-29 01:37:32 +0000430 # Extend the best by non-junk elements on each end. In particular,
431 # "popular" non-junk elements aren't in b2j, which greatly speeds
432 # the inner loop above, but also means "the best" match so far
433 # doesn't contain any junk *or* popular non-junk elements.
434 while besti > alo and bestj > blo and \
435 not isbjunk(b[bestj-1]) and \
436 a[besti-1] == b[bestj-1]:
437 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
438 while besti+bestsize < ahi and bestj+bestsize < bhi and \
439 not isbjunk(b[bestj+bestsize]) and \
440 a[besti+bestsize] == b[bestj+bestsize]:
441 bestsize += 1
442
Tim Peters9ae21482001-02-10 08:00:53 +0000443 # Now that we have a wholly interesting match (albeit possibly
444 # empty!), we may as well suck up the matching junk on each
445 # side of it too. Can't think of a good reason not to, and it
446 # saves post-processing the (possibly considerable) expense of
447 # figuring out what to do with it. In the case of an empty
448 # interesting match, this is clearly the right thing to do,
449 # because no other kind of match is possible in the regions.
450 while besti > alo and bestj > blo and \
451 isbjunk(b[bestj-1]) and \
452 a[besti-1] == b[bestj-1]:
453 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
454 while besti+bestsize < ahi and bestj+bestsize < bhi and \
455 isbjunk(b[bestj+bestsize]) and \
456 a[besti+bestsize] == b[bestj+bestsize]:
457 bestsize = bestsize + 1
458
Christian Heimes25bb7832008-01-11 16:17:00 +0000459 return Match(besti, bestj, bestsize)
Tim Peters9ae21482001-02-10 08:00:53 +0000460
461 def get_matching_blocks(self):
462 """Return list of triples describing matching subsequences.
463
464 Each triple is of the form (i, j, n), and means that
465 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000466 i and in j. New in Python 2.5, it's also guaranteed that if
467 (i, j, n) and (i', j', n') are adjacent triples in the list, and
468 the second is not the last triple in the list, then i+n != i' or
469 j+n != j'. IOW, adjacent triples never describe adjacent equal
470 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000471
472 The last triple is a dummy, (len(a), len(b), 0), and is the only
473 triple with n==0.
474
475 >>> s = SequenceMatcher(None, "abxcd", "abcd")
Christian Heimes25bb7832008-01-11 16:17:00 +0000476 >>> list(s.get_matching_blocks())
477 [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
Tim Peters9ae21482001-02-10 08:00:53 +0000478 """
479
480 if self.matching_blocks is not None:
481 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000482 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000483
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000484 # This is most naturally expressed as a recursive algorithm, but
485 # at least one user bumped into extreme use cases that exceeded
486 # the recursion limit on their box. So, now we maintain a list
487 # ('queue`) of blocks we still need to look at, and append partial
488 # results to `matching_blocks` in a loop; the matches are sorted
489 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000490 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000491 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000492 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000493 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000494 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000495 # a[alo:i] vs b[blo:j] unknown
496 # a[i:i+k] same as b[j:j+k]
497 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000498 if k: # if k is 0, there was no matching block
499 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000500 if alo < i and blo < j:
501 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000502 if i+k < ahi and j+k < bhi:
503 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000504 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000505
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 # It's possible that we have adjacent equal blocks in the
507 # matching_blocks list now. Starting with 2.5, this code was added
508 # to collapse them.
509 i1 = j1 = k1 = 0
510 non_adjacent = []
511 for i2, j2, k2 in matching_blocks:
512 # Is this block adjacent to i1, j1, k1?
513 if i1 + k1 == i2 and j1 + k1 == j2:
514 # Yes, so collapse them -- this just increases the length of
515 # the first block by the length of the second, and the first
516 # block so lengthened remains the block to compare against.
517 k1 += k2
518 else:
519 # Not adjacent. Remember the first block (k1==0 means it's
520 # the dummy we started with), and make the second block the
521 # new block to compare against.
522 if k1:
523 non_adjacent.append((i1, j1, k1))
524 i1, j1, k1 = i2, j2, k2
525 if k1:
526 non_adjacent.append((i1, j1, k1))
527
528 non_adjacent.append( (la, lb, 0) )
529 self.matching_blocks = non_adjacent
Christian Heimes25bb7832008-01-11 16:17:00 +0000530 return map(Match._make, self.matching_blocks)
Tim Peters9ae21482001-02-10 08:00:53 +0000531
Tim Peters9ae21482001-02-10 08:00:53 +0000532 def get_opcodes(self):
533 """Return list of 5-tuples describing how to turn a into b.
534
535 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
536 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
537 tuple preceding it, and likewise for j1 == the previous j2.
538
539 The tags are strings, with these meanings:
540
541 'replace': a[i1:i2] should be replaced by b[j1:j2]
542 'delete': a[i1:i2] should be deleted.
543 Note that j1==j2 in this case.
544 'insert': b[j1:j2] should be inserted at a[i1:i1].
545 Note that i1==i2 in this case.
546 'equal': a[i1:i2] == b[j1:j2]
547
548 >>> a = "qabxcd"
549 >>> b = "abycdf"
550 >>> s = SequenceMatcher(None, a, b)
551 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000552 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
553 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000554 delete a[0:1] (q) b[0:0] ()
555 equal a[1:3] (ab) b[0:2] (ab)
556 replace a[3:4] (x) b[2:3] (y)
557 equal a[4:6] (cd) b[3:5] (cd)
558 insert a[6:6] () b[5:6] (f)
559 """
560
561 if self.opcodes is not None:
562 return self.opcodes
563 i = j = 0
564 self.opcodes = answer = []
565 for ai, bj, size in self.get_matching_blocks():
566 # invariant: we've pumped out correct diffs to change
567 # a[:i] into b[:j], and the next matching block is
568 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
569 # out a diff to change a[i:ai] into b[j:bj], pump out
570 # the matching block, and move (i,j) beyond the match
571 tag = ''
572 if i < ai and j < bj:
573 tag = 'replace'
574 elif i < ai:
575 tag = 'delete'
576 elif j < bj:
577 tag = 'insert'
578 if tag:
579 answer.append( (tag, i, ai, j, bj) )
580 i, j = ai+size, bj+size
581 # the list of matching blocks is terminated by a
582 # sentinel with size 0
583 if size:
584 answer.append( ('equal', ai, i, bj, j) )
585 return answer
586
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000587 def get_grouped_opcodes(self, n=3):
588 """ Isolate change clusters by eliminating ranges with no changes.
589
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300590 Return a generator of groups with up to n lines of context.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000591 Each group is in the same format as returned by get_opcodes().
592
593 >>> from pprint import pprint
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000594 >>> a = list(map(str, range(1,40)))
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000595 >>> b = a[:]
596 >>> b[8:8] = ['i'] # Make an insertion
597 >>> b[20] += 'x' # Make a replacement
598 >>> b[23:28] = [] # Make a deletion
599 >>> b[30] += 'y' # Make another replacement
600 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
601 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
602 [('equal', 16, 19, 17, 20),
603 ('replace', 19, 20, 20, 21),
604 ('equal', 20, 22, 21, 23),
605 ('delete', 22, 27, 23, 23),
606 ('equal', 27, 30, 23, 26)],
607 [('equal', 31, 34, 27, 30),
608 ('replace', 34, 35, 30, 31),
609 ('equal', 35, 38, 31, 34)]]
610 """
611
612 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000613 if not codes:
614 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000615 # Fixup leading and trailing groups if they show no changes.
616 if codes[0][0] == 'equal':
617 tag, i1, i2, j1, j2 = codes[0]
618 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
619 if codes[-1][0] == 'equal':
620 tag, i1, i2, j1, j2 = codes[-1]
621 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
622
623 nn = n + n
624 group = []
625 for tag, i1, i2, j1, j2 in codes:
626 # End the current group and start a new one whenever
627 # there is a large range with no changes.
628 if tag == 'equal' and i2-i1 > nn:
629 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
630 yield group
631 group = []
632 i1, j1 = max(i1, i2-n), max(j1, j2-n)
633 group.append((tag, i1, i2, j1 ,j2))
634 if group and not (len(group)==1 and group[0][0] == 'equal'):
635 yield group
636
Tim Peters9ae21482001-02-10 08:00:53 +0000637 def ratio(self):
638 """Return a measure of the sequences' similarity (float in [0,1]).
639
640 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000641 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000642 Note that this is 1 if the sequences are identical, and 0 if
643 they have nothing in common.
644
645 .ratio() is expensive to compute if you haven't already computed
646 .get_matching_blocks() or .get_opcodes(), in which case you may
647 want to try .quick_ratio() or .real_quick_ratio() first to get an
648 upper bound.
649
650 >>> s = SequenceMatcher(None, "abcd", "bcde")
651 >>> s.ratio()
652 0.75
653 >>> s.quick_ratio()
654 0.75
655 >>> s.real_quick_ratio()
656 1.0
657 """
658
Guido van Rossum89da5d72006-08-22 00:21:25 +0000659 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000660 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000661
662 def quick_ratio(self):
663 """Return an upper bound on ratio() relatively quickly.
664
665 This isn't defined beyond that it is an upper bound on .ratio(), and
666 is faster to compute.
667 """
668
669 # viewing a and b as multisets, set matches to the cardinality
670 # of their intersection; this counts the number of matches
671 # without regard to order, so is clearly an upper bound
672 if self.fullbcount is None:
673 self.fullbcount = fullbcount = {}
674 for elt in self.b:
675 fullbcount[elt] = fullbcount.get(elt, 0) + 1
676 fullbcount = self.fullbcount
677 # avail[x] is the number of times x appears in 'b' less the
678 # number of times we've seen it in 'a' so far ... kinda
679 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000680 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000681 for elt in self.a:
682 if availhas(elt):
683 numb = avail[elt]
684 else:
685 numb = fullbcount.get(elt, 0)
686 avail[elt] = numb - 1
687 if numb > 0:
688 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000689 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000690
691 def real_quick_ratio(self):
692 """Return an upper bound on ratio() very quickly.
693
694 This isn't defined beyond that it is an upper bound on .ratio(), and
695 is faster to compute than either .ratio() or .quick_ratio().
696 """
697
698 la, lb = len(self.a), len(self.b)
699 # can't have more matches than the number of elements in the
700 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000701 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000702
703def get_close_matches(word, possibilities, n=3, cutoff=0.6):
704 """Use SequenceMatcher to return list of the best "good enough" matches.
705
706 word is a sequence for which close matches are desired (typically a
707 string).
708
709 possibilities is a list of sequences against which to match word
710 (typically a list of strings).
711
712 Optional arg n (default 3) is the maximum number of close matches to
713 return. n must be > 0.
714
715 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
716 that don't score at least that similar to word are ignored.
717
718 The best (no more than n) matches among the possibilities are returned
719 in a list, sorted by similarity score, most similar first.
720
721 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
722 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000723 >>> import keyword as _keyword
724 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000725 ['while']
Guido van Rossum486364b2007-06-30 05:01:58 +0000726 >>> get_close_matches("Apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000727 []
Tim Peters5e824c32001-08-12 22:25:01 +0000728 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000729 ['except']
730 """
731
732 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000733 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000734 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000735 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000736 result = []
737 s = SequenceMatcher()
738 s.set_seq2(word)
739 for x in possibilities:
740 s.set_seq1(x)
741 if s.real_quick_ratio() >= cutoff and \
742 s.quick_ratio() >= cutoff and \
743 s.ratio() >= cutoff:
744 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000745
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000746 # Move the best scorers to head of list
Raymond Hettingeraefde432004-06-15 23:53:35 +0000747 result = heapq.nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000748 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000749 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000750
751def _count_leading(line, ch):
752 """
753 Return number of `ch` characters at the start of `line`.
754
755 Example:
756
757 >>> _count_leading(' abc', ' ')
758 3
759 """
760
761 i, n = 0, len(line)
762 while i < n and line[i] == ch:
763 i += 1
764 return i
765
766class Differ:
767 r"""
768 Differ is a class for comparing sequences of lines of text, and
769 producing human-readable differences or deltas. Differ uses
770 SequenceMatcher both to compare sequences of lines, and to compare
771 sequences of characters within similar (near-matching) lines.
772
773 Each line of a Differ delta begins with a two-letter code:
774
775 '- ' line unique to sequence 1
776 '+ ' line unique to sequence 2
777 ' ' line common to both sequences
778 '? ' line not present in either input sequence
779
780 Lines beginning with '? ' attempt to guide the eye to intraline
781 differences, and were not present in either input sequence. These lines
782 can be confusing if the sequences contain tab characters.
783
784 Note that Differ makes no claim to produce a *minimal* diff. To the
785 contrary, minimal diffs are often counter-intuitive, because they synch
786 up anywhere possible, sometimes accidental matches 100 pages apart.
787 Restricting synch points to contiguous matches preserves some notion of
788 locality, at the occasional cost of producing a longer diff.
789
790 Example: Comparing two texts.
791
792 First we set up the texts, sequences of individual single-line strings
793 ending with newlines (such sequences can also be obtained from the
794 `readlines()` method of file-like objects):
795
796 >>> text1 = ''' 1. Beautiful is better than ugly.
797 ... 2. Explicit is better than implicit.
798 ... 3. Simple is better than complex.
799 ... 4. Complex is better than complicated.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300800 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000801 >>> len(text1)
802 4
803 >>> text1[0][-1]
804 '\n'
805 >>> text2 = ''' 1. Beautiful is better than ugly.
806 ... 3. Simple is better than complex.
807 ... 4. Complicated is better than complex.
808 ... 5. Flat is better than nested.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300809 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000810
811 Next we instantiate a Differ object:
812
813 >>> d = Differ()
814
815 Note that when instantiating a Differ object we may pass functions to
816 filter out line and character 'junk'. See Differ.__init__ for details.
817
818 Finally, we compare the two:
819
Tim Peters8a9c2842001-09-22 21:30:22 +0000820 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000821
822 'result' is a list of strings, so let's pretty-print it:
823
824 >>> from pprint import pprint as _pprint
825 >>> _pprint(result)
826 [' 1. Beautiful is better than ugly.\n',
827 '- 2. Explicit is better than implicit.\n',
828 '- 3. Simple is better than complex.\n',
829 '+ 3. Simple is better than complex.\n',
830 '? ++\n',
831 '- 4. Complex is better than complicated.\n',
832 '? ^ ---- ^\n',
833 '+ 4. Complicated is better than complex.\n',
834 '? ++++ ^ ^\n',
835 '+ 5. Flat is better than nested.\n']
836
837 As a single multi-line string it looks like this:
838
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000839 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000840 1. Beautiful is better than ugly.
841 - 2. Explicit is better than implicit.
842 - 3. Simple is better than complex.
843 + 3. Simple is better than complex.
844 ? ++
845 - 4. Complex is better than complicated.
846 ? ^ ---- ^
847 + 4. Complicated is better than complex.
848 ? ++++ ^ ^
849 + 5. Flat is better than nested.
850
851 Methods:
852
853 __init__(linejunk=None, charjunk=None)
854 Construct a text differencer, with optional filters.
855
856 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000857 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000858 """
859
860 def __init__(self, linejunk=None, charjunk=None):
861 """
862 Construct a text differencer, with optional filters.
863
864 The two optional keyword parameters are for filter functions:
865
866 - `linejunk`: A function that should accept a single string argument,
867 and return true iff the string is junk. The module-level function
868 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000869 characters, except for at most one splat ('#'). It is recommended
870 to leave linejunk None; as of Python 2.3, the underlying
871 SequenceMatcher class has grown an adaptive notion of "noise" lines
872 that's better than any static definition the author has ever been
873 able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000874
875 - `charjunk`: A function that should accept a string of length 1. The
876 module-level function `IS_CHARACTER_JUNK` may be used to filter out
877 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000878 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000879 """
880
881 self.linejunk = linejunk
882 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000883
884 def compare(self, a, b):
885 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000886 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000887
888 Each sequence must contain individual single-line strings ending with
889 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000890 of file-like objects. The delta generated also consists of newline-
891 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000892 method of a file-like object.
893
894 Example:
895
Ezio Melottid8b509b2011-09-28 17:37:55 +0300896 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(True),
897 ... 'ore\ntree\nemu\n'.splitlines(True))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000898 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000899 - one
900 ? ^
901 + ore
902 ? ^
903 - two
904 - three
905 ? -
906 + tree
907 + emu
908 """
909
910 cruncher = SequenceMatcher(self.linejunk, a, b)
911 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
912 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000913 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000914 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000915 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000916 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000917 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000918 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000919 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000920 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000921 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +0000922
923 for line in g:
924 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000925
926 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000927 """Generate comparison results for a same-tagged range."""
Guido van Rossum805365e2007-05-07 22:24:25 +0000928 for i in range(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000929 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000930
931 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
932 assert alo < ahi and blo < bhi
933 # dump the shorter block first -- reduces the burden on short-term
934 # memory if the blocks are of very different sizes
935 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000936 first = self._dump('+', b, blo, bhi)
937 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000938 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000939 first = self._dump('-', a, alo, ahi)
940 second = self._dump('+', b, blo, bhi)
941
942 for g in first, second:
943 for line in g:
944 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000945
946 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
947 r"""
948 When replacing one block of lines with another, search the blocks
949 for *similar* lines; the best-matching pair (if any) is used as a
950 synch point, and intraline difference marking is done on the
951 similar pair. Lots of work, but often worth it.
952
953 Example:
954
955 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000956 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
957 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000958 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000959 - abcDefghiJkl
960 ? ^ ^ ^
961 + abcdefGhijkl
962 ? ^ ^ ^
963 """
964
Tim Peters5e824c32001-08-12 22:25:01 +0000965 # don't synch up unless the lines have a similarity score of at
966 # least cutoff; best_ratio tracks the best score seen so far
967 best_ratio, cutoff = 0.74, 0.75
968 cruncher = SequenceMatcher(self.charjunk)
969 eqi, eqj = None, None # 1st indices of equal lines (if any)
970
971 # search for the pair that matches best without being identical
972 # (identical lines must be junk lines, & we don't want to synch up
973 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000974 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000975 bj = b[j]
976 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000977 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000978 ai = a[i]
979 if ai == bj:
980 if eqi is None:
981 eqi, eqj = i, j
982 continue
983 cruncher.set_seq1(ai)
984 # computing similarity is expensive, so use the quick
985 # upper bounds first -- have seen this speed up messy
986 # compares by a factor of 3.
987 # note that ratio() is only expensive to compute the first
988 # time it's called on a sequence pair; the expensive part
989 # of the computation is cached by cruncher
990 if cruncher.real_quick_ratio() > best_ratio and \
991 cruncher.quick_ratio() > best_ratio and \
992 cruncher.ratio() > best_ratio:
993 best_ratio, best_i, best_j = cruncher.ratio(), i, j
994 if best_ratio < cutoff:
995 # no non-identical "pretty close" pair
996 if eqi is None:
997 # no identical pair either -- treat it as a straight replace
Tim Peters8a9c2842001-09-22 21:30:22 +0000998 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
999 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001000 return
1001 # no close pair, but an identical pair -- synch up on that
1002 best_i, best_j, best_ratio = eqi, eqj, 1.0
1003 else:
1004 # there's a close pair, so forget the identical pair (if any)
1005 eqi = None
1006
1007 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
1008 # identical
Tim Peters5e824c32001-08-12 22:25:01 +00001009
1010 # pump out diffs from before the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001011 for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
1012 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001013
1014 # do intraline marking on the synch pair
1015 aelt, belt = a[best_i], b[best_j]
1016 if eqi is None:
1017 # pump out a '-', '?', '+', '?' quad for the synched lines
1018 atags = btags = ""
1019 cruncher.set_seqs(aelt, belt)
1020 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1021 la, lb = ai2 - ai1, bj2 - bj1
1022 if tag == 'replace':
1023 atags += '^' * la
1024 btags += '^' * lb
1025 elif tag == 'delete':
1026 atags += '-' * la
1027 elif tag == 'insert':
1028 btags += '+' * lb
1029 elif tag == 'equal':
1030 atags += ' ' * la
1031 btags += ' ' * lb
1032 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001033 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +00001034 for line in self._qformat(aelt, belt, atags, btags):
1035 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001036 else:
1037 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001038 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001039
1040 # pump out diffs from after the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001041 for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
1042 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001043
1044 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001045 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001046 if alo < ahi:
1047 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001048 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001049 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001050 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001051 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001052 g = self._dump('+', b, blo, bhi)
1053
1054 for line in g:
1055 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001056
1057 def _qformat(self, aline, bline, atags, btags):
1058 r"""
1059 Format "?" output and deal with leading tabs.
1060
1061 Example:
1062
1063 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001064 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1065 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001066 >>> for line in results: print(repr(line))
1067 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001068 '- \tabcDefghiJkl\n'
1069 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001070 '+ \tabcdefGhijkl\n'
1071 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001072 """
1073
1074 # Can hurt, but will probably help most of the time.
1075 common = min(_count_leading(aline, "\t"),
1076 _count_leading(bline, "\t"))
1077 common = min(common, _count_leading(atags[:common], " "))
Senthil Kumaran758025c2009-11-23 19:02:52 +00001078 common = min(common, _count_leading(btags[:common], " "))
Tim Peters5e824c32001-08-12 22:25:01 +00001079 atags = atags[common:].rstrip()
1080 btags = btags[common:].rstrip()
1081
Tim Peters8a9c2842001-09-22 21:30:22 +00001082 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001083 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001084 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001085
Tim Peters8a9c2842001-09-22 21:30:22 +00001086 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001087 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001088 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001089
1090# With respect to junk, an earlier version of ndiff simply refused to
1091# *start* a match with a junk element. The result was cases like this:
1092# before: private Thread currentThread;
1093# after: private volatile Thread currentThread;
1094# If you consider whitespace to be junk, the longest contiguous match
1095# not starting with junk is "e Thread currentThread". So ndiff reported
1096# that "e volatil" was inserted between the 't' and the 'e' in "private".
1097# While an accurate view, to people that's absurd. The current version
1098# looks for matching blocks that are entirely junk-free, then extends the
1099# longest one of those as far as possible but only with matching junk.
1100# So now "currentThread" is matched, then extended to suck up the
1101# preceding blank; then "private" is matched, and extended to suck up the
1102# following blank; then "Thread" is matched; and finally ndiff reports
1103# that "volatile " was inserted before "Thread". The only quibble
1104# remaining is that perhaps it was really the case that " volatile"
1105# was inserted after "private". I can live with that <wink>.
1106
1107import re
1108
1109def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1110 r"""
1111 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1112
1113 Examples:
1114
1115 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001116 True
Tim Peters5e824c32001-08-12 22:25:01 +00001117 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001118 True
Tim Peters5e824c32001-08-12 22:25:01 +00001119 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001120 False
Tim Peters5e824c32001-08-12 22:25:01 +00001121 """
1122
1123 return pat(line) is not None
1124
1125def IS_CHARACTER_JUNK(ch, ws=" \t"):
1126 r"""
1127 Return 1 for ignorable character: iff `ch` is a space or tab.
1128
1129 Examples:
1130
1131 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001132 True
Tim Peters5e824c32001-08-12 22:25:01 +00001133 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001134 True
Tim Peters5e824c32001-08-12 22:25:01 +00001135 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001136 False
Tim Peters5e824c32001-08-12 22:25:01 +00001137 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001138 False
Tim Peters5e824c32001-08-12 22:25:01 +00001139 """
1140
1141 return ch in ws
1142
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001143
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001144########################################################################
1145### Unified Diff
1146########################################################################
1147
1148def _format_range_unified(start, stop):
Raymond Hettinger49353d02011-04-11 12:40:58 -07001149 'Convert range to the "ed" format'
1150 # Per the diff spec at http://www.unix.org/single_unix_specification/
1151 beginning = start + 1 # lines start numbering with one
1152 length = stop - start
1153 if length == 1:
1154 return '{}'.format(beginning)
1155 if not length:
1156 beginning -= 1 # empty ranges begin at line just before the range
1157 return '{},{}'.format(beginning, length)
1158
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001159def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1160 tofiledate='', n=3, lineterm='\n'):
1161 r"""
1162 Compare two sequences of lines; generate the delta as a unified diff.
1163
1164 Unified diffs are a compact way of showing line changes and a few
1165 lines of context. The number of context lines is set by 'n' which
1166 defaults to three.
1167
Raymond Hettinger0887c732003-06-17 16:53:25 +00001168 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001169 created with a trailing newline. This is helpful so that inputs
1170 created from file.readlines() result in diffs that are suitable for
1171 file.writelines() since both the inputs and outputs have trailing
1172 newlines.
1173
1174 For inputs that do not have trailing newlines, set the lineterm
1175 argument to "" so that the output will be uniformly newline free.
1176
1177 The unidiff format normally has a header for filenames and modification
1178 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001179 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1180 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001181
1182 Example:
1183
1184 >>> for line in unified_diff('one two three four'.split(),
1185 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001186 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001187 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001188 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1189 --- Original 2005-01-26 23:30:50
1190 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001191 @@ -1,4 +1,4 @@
1192 +zero
1193 one
1194 -two
1195 -three
1196 +tree
1197 four
1198 """
1199
1200 started = False
1201 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1202 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001203 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001204 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1205 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1206 yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
1207 yield '+++ {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger49353d02011-04-11 12:40:58 -07001208
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001209 first, last = group[0], group[-1]
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001210 file1_range = _format_range_unified(first[1], last[2])
1211 file2_range = _format_range_unified(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001212 yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
1213
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001214 for tag, i1, i2, j1, j2 in group:
1215 if tag == 'equal':
1216 for line in a[i1:i2]:
1217 yield ' ' + line
1218 continue
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001219 if tag in {'replace', 'delete'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001220 for line in a[i1:i2]:
1221 yield '-' + line
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001222 if tag in {'replace', 'insert'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001223 for line in b[j1:j2]:
1224 yield '+' + line
1225
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001226
1227########################################################################
1228### Context Diff
1229########################################################################
1230
1231def _format_range_context(start, stop):
1232 'Convert range to the "ed" format'
1233 # Per the diff spec at http://www.unix.org/single_unix_specification/
1234 beginning = start + 1 # lines start numbering with one
1235 length = stop - start
1236 if not length:
1237 beginning -= 1 # empty ranges begin at line just before the range
1238 if length <= 1:
1239 return '{}'.format(beginning)
1240 return '{},{}'.format(beginning, beginning + length - 1)
1241
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001242# See http://www.unix.org/single_unix_specification/
1243def context_diff(a, b, fromfile='', tofile='',
1244 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1245 r"""
1246 Compare two sequences of lines; generate the delta as a context diff.
1247
1248 Context diffs are a compact way of showing line changes and a few
1249 lines of context. The number of context lines is set by 'n' which
1250 defaults to three.
1251
1252 By default, the diff control lines (those with *** or ---) are
1253 created with a trailing newline. This is helpful so that inputs
1254 created from file.readlines() result in diffs that are suitable for
1255 file.writelines() since both the inputs and outputs have trailing
1256 newlines.
1257
1258 For inputs that do not have trailing newlines, set the lineterm
1259 argument to "" so that the output will be uniformly newline free.
1260
1261 The context diff format normally has a header for filenames and
1262 modification times. Any or all of these may be specified using
1263 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001264 The modification times are normally expressed in the ISO 8601 format.
1265 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001266
1267 Example:
1268
Ezio Melottid8b509b2011-09-28 17:37:55 +03001269 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
1270 ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001271 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001272 *** Original
1273 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001274 ***************
1275 *** 1,4 ****
1276 one
1277 ! two
1278 ! three
1279 four
1280 --- 1,4 ----
1281 + zero
1282 one
1283 ! tree
1284 four
1285 """
1286
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001287 prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001288 started = False
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001289 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1290 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001291 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001292 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1293 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1294 yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
1295 yield '--- {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001296
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001297 first, last = group[0], group[-1]
Raymond Hettinger49353d02011-04-11 12:40:58 -07001298 yield '***************' + lineterm
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001299
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001300 file1_range = _format_range_context(first[1], last[2])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001301 yield '*** {} ****{}'.format(file1_range, lineterm)
1302
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001303 if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001304 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001305 if tag != 'insert':
1306 for line in a[i1:i2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001307 yield prefix[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001308
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001309 file2_range = _format_range_context(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001310 yield '--- {} ----{}'.format(file2_range, lineterm)
1311
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001312 if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001313 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001314 if tag != 'delete':
1315 for line in b[j1:j2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001316 yield prefix[tag] + line
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001317
Tim Peters81b92512002-04-29 01:37:32 +00001318def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001319 r"""
1320 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1321
1322 Optional keyword parameters `linejunk` and `charjunk` are for filter
1323 functions (or None):
1324
1325 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001326 return true iff the string is junk. The default is None, and is
1327 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1328 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001329
1330 - charjunk: A function that should accept a string of length 1. The
1331 default is module-level function IS_CHARACTER_JUNK, which filters out
1332 whitespace characters (a blank or tab; note: bad idea to include newline
1333 in this!).
1334
1335 Tools/scripts/ndiff.py is a command-line front-end to this function.
1336
1337 Example:
1338
Ezio Melottid8b509b2011-09-28 17:37:55 +03001339 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
1340 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001341 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001342 - one
1343 ? ^
1344 + ore
1345 ? ^
1346 - two
1347 - three
1348 ? -
1349 + tree
1350 + emu
1351 """
1352 return Differ(linejunk, charjunk).compare(a, b)
1353
Martin v. Löwise064b412004-08-29 16:34:40 +00001354def _mdiff(fromlines, tolines, context=None, linejunk=None,
1355 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001356 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001357
1358 Arguments:
1359 fromlines -- list of text lines to compared to tolines
1360 tolines -- list of text lines to be compared to fromlines
1361 context -- number of context lines to display on each side of difference,
1362 if None, all from/to text lines will be generated.
1363 linejunk -- passed on to ndiff (see ndiff documentation)
1364 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001365
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001366 This function returns an iterator which returns a tuple:
Martin v. Löwise064b412004-08-29 16:34:40 +00001367 (from line tuple, to line tuple, boolean flag)
1368
1369 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001370 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001371 line text -- original line text with following markers inserted:
1372 '\0+' -- marks start of added text
1373 '\0-' -- marks start of deleted text
1374 '\0^' -- marks start of changed text
1375 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001376
Martin v. Löwise064b412004-08-29 16:34:40 +00001377 boolean flag -- None indicates context separation, True indicates
1378 either "from" or "to" line contains a change, otherwise False.
1379
1380 This function/iterator was originally developed to generate side by side
1381 file difference for making HTML pages (see HtmlDiff class for example
1382 usage).
1383
1384 Note, this function utilizes the ndiff function to generate the side by
1385 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001386 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001387 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001388 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001389
1390 # regular expression for finding intraline change indices
1391 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001392
Martin v. Löwise064b412004-08-29 16:34:40 +00001393 # create the difference iterator to generate the differences
1394 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1395
1396 def _make_line(lines, format_key, side, num_lines=[0,0]):
1397 """Returns line of text with user's change markup and line formatting.
1398
1399 lines -- list of lines from the ndiff generator to produce a line of
1400 text from. When producing the line of text to return, the
1401 lines used are removed from this list.
1402 format_key -- '+' return first line in list with "add" markup around
1403 the entire line.
1404 '-' return first line in list with "delete" markup around
1405 the entire line.
1406 '?' return first line in list with add/delete/change
1407 intraline markup (indices obtained from second line)
1408 None return first line in list with no markup
1409 side -- indice into the num_lines list (0=from,1=to)
1410 num_lines -- from/to current line number. This is NOT intended to be a
1411 passed parameter. It is present as a keyword argument to
1412 maintain memory of the current line numbers between calls
1413 of this function.
1414
1415 Note, this function is purposefully not defined at the module scope so
1416 that data it needs from its parent function (within whose context it
1417 is defined) does not need to be of module scope.
1418 """
1419 num_lines[side] += 1
1420 # Handle case where no user markup is to be added, just return line of
1421 # text with user's line format to allow for usage of the line number.
1422 if format_key is None:
1423 return (num_lines[side],lines.pop(0)[2:])
1424 # Handle case of intraline changes
1425 if format_key == '?':
1426 text, markers = lines.pop(0), lines.pop(0)
1427 # find intraline changes (store change type and indices in tuples)
1428 sub_info = []
1429 def record_sub_info(match_object,sub_info=sub_info):
1430 sub_info.append([match_object.group(1)[0],match_object.span()])
1431 return match_object.group(1)
1432 change_re.sub(record_sub_info,markers)
1433 # process each tuple inserting our special marks that won't be
1434 # noticed by an xml/html escaper.
1435 for key,(begin,end) in sub_info[::-1]:
1436 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1437 text = text[2:]
1438 # Handle case of add/delete entire line
1439 else:
1440 text = lines.pop(0)[2:]
1441 # if line of text is just a newline, insert a space so there is
1442 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001443 if not text:
1444 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001445 # insert marks that won't be noticed by an xml/html escaper.
1446 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001447 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001448 # thing (such as adding the line number) then replace the special
1449 # marks with what the user's change markup.
1450 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001451
Martin v. Löwise064b412004-08-29 16:34:40 +00001452 def _line_iterator():
1453 """Yields from/to lines of text with a change indication.
1454
1455 This function is an iterator. It itself pulls lines from a
1456 differencing iterator, processes them and yields them. When it can
1457 it yields both a "from" and a "to" line, otherwise it will yield one
1458 or the other. In addition to yielding the lines of from/to text, a
1459 boolean flag is yielded to indicate if the text line(s) have
1460 differences in them.
1461
1462 Note, this function is purposefully not defined at the module scope so
1463 that data it needs from its parent function (within whose context it
1464 is defined) does not need to be of module scope.
1465 """
1466 lines = []
1467 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001468 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001469 # Load up next 4 lines so we can look ahead, create strings which
1470 # are a concatenation of the first character of each of the 4 lines
1471 # so we can do some very readable comparisons.
1472 while len(lines) < 4:
1473 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001474 lines.append(next(diff_lines_iterator))
Martin v. Löwise064b412004-08-29 16:34:40 +00001475 except StopIteration:
1476 lines.append('X')
1477 s = ''.join([line[0] for line in lines])
1478 if s.startswith('X'):
1479 # When no more lines, pump out any remaining blank lines so the
1480 # corresponding add/delete lines get a matching blank line so
1481 # all line pairs get yielded at the next level.
1482 num_blanks_to_yield = num_blanks_pending
1483 elif s.startswith('-?+?'):
1484 # simple intraline change
1485 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1486 continue
1487 elif s.startswith('--++'):
1488 # in delete block, add block coming: we do NOT want to get
1489 # caught up on blank lines yet, just process the delete line
1490 num_blanks_pending -= 1
1491 yield _make_line(lines,'-',0), None, True
1492 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001493 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001494 # in delete block and see a intraline change or unchanged line
1495 # coming: yield the delete line and then blanks
1496 from_line,to_line = _make_line(lines,'-',0), None
1497 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1498 elif s.startswith('-+?'):
1499 # intraline change
1500 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1501 continue
1502 elif s.startswith('-?+'):
1503 # intraline change
1504 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1505 continue
1506 elif s.startswith('-'):
1507 # delete FROM line
1508 num_blanks_pending -= 1
1509 yield _make_line(lines,'-',0), None, True
1510 continue
1511 elif s.startswith('+--'):
1512 # in add block, delete block coming: we do NOT want to get
1513 # caught up on blank lines yet, just process the add line
1514 num_blanks_pending += 1
1515 yield None, _make_line(lines,'+',1), True
1516 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001517 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001518 # will be leaving an add block: yield blanks then add line
1519 from_line, to_line = None, _make_line(lines,'+',1)
1520 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1521 elif s.startswith('+'):
1522 # inside an add block, yield the add line
1523 num_blanks_pending += 1
1524 yield None, _make_line(lines,'+',1), True
1525 continue
1526 elif s.startswith(' '):
1527 # unchanged text, yield it to both sides
1528 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1529 continue
1530 # Catch up on the blank lines so when we yield the next from/to
1531 # pair, they are lined up.
1532 while(num_blanks_to_yield < 0):
1533 num_blanks_to_yield += 1
1534 yield None,('','\n'),True
1535 while(num_blanks_to_yield > 0):
1536 num_blanks_to_yield -= 1
1537 yield ('','\n'),None,True
1538 if s.startswith('X'):
1539 raise StopIteration
1540 else:
1541 yield from_line,to_line,True
1542
1543 def _line_pair_iterator():
1544 """Yields from/to lines of text with a change indication.
1545
1546 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001547 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001548 always yields a pair of from/to text lines (with the change
1549 indication). If necessary it will collect single from/to lines
1550 until it has a matching pair from/to pair to yield.
1551
1552 Note, this function is purposefully not defined at the module scope so
1553 that data it needs from its parent function (within whose context it
1554 is defined) does not need to be of module scope.
1555 """
1556 line_iterator = _line_iterator()
1557 fromlines,tolines=[],[]
1558 while True:
1559 # Collecting lines of text until we have a from/to pair
1560 while (len(fromlines)==0 or len(tolines)==0):
Georg Brandla18af4e2007-04-21 15:47:16 +00001561 from_line, to_line, found_diff = next(line_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001562 if from_line is not None:
1563 fromlines.append((from_line,found_diff))
1564 if to_line is not None:
1565 tolines.append((to_line,found_diff))
1566 # Once we have a pair, remove them from the collection and yield it
1567 from_line, fromDiff = fromlines.pop(0)
1568 to_line, to_diff = tolines.pop(0)
1569 yield (from_line,to_line,fromDiff or to_diff)
1570
1571 # Handle case where user does not want context differencing, just yield
1572 # them up without doing anything else with them.
1573 line_pair_iterator = _line_pair_iterator()
1574 if context is None:
1575 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +00001576 yield next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001577 # Handle case where user wants context differencing. We must do some
1578 # storage of lines until we know for sure that they are to be yielded.
1579 else:
1580 context += 1
1581 lines_to_write = 0
1582 while True:
1583 # Store lines up until we find a difference, note use of a
1584 # circular queue because we only need to keep around what
1585 # we need for context.
1586 index, contextLines = 0, [None]*(context)
1587 found_diff = False
1588 while(found_diff is False):
Georg Brandla18af4e2007-04-21 15:47:16 +00001589 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001590 i = index % context
1591 contextLines[i] = (from_line, to_line, found_diff)
1592 index += 1
1593 # Yield lines that we have collected so far, but first yield
1594 # the user's separator.
1595 if index > context:
1596 yield None, None, None
1597 lines_to_write = context
1598 else:
1599 lines_to_write = index
1600 index = 0
1601 while(lines_to_write):
1602 i = index % context
1603 index += 1
1604 yield contextLines[i]
1605 lines_to_write -= 1
1606 # Now yield the context lines after the change
1607 lines_to_write = context-1
1608 while(lines_to_write):
Georg Brandla18af4e2007-04-21 15:47:16 +00001609 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001610 # If another change within the context, extend the context
1611 if found_diff:
1612 lines_to_write = context-1
1613 else:
1614 lines_to_write -= 1
1615 yield from_line, to_line, found_diff
1616
1617
1618_file_template = """
1619<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1620 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1621
1622<html>
1623
1624<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001625 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001626 content="text/html; charset=ISO-8859-1" />
1627 <title></title>
1628 <style type="text/css">%(styles)s
1629 </style>
1630</head>
1631
1632<body>
1633 %(table)s%(legend)s
1634</body>
1635
1636</html>"""
1637
1638_styles = """
1639 table.diff {font-family:Courier; border:medium;}
1640 .diff_header {background-color:#e0e0e0}
1641 td.diff_header {text-align:right}
1642 .diff_next {background-color:#c0c0c0}
1643 .diff_add {background-color:#aaffaa}
1644 .diff_chg {background-color:#ffff77}
1645 .diff_sub {background-color:#ffaaaa}"""
1646
1647_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001648 <table class="diff" id="difflib_chg_%(prefix)s_top"
1649 cellspacing="0" cellpadding="0" rules="groups" >
1650 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001651 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1652 %(header_row)s
1653 <tbody>
1654%(data_rows)s </tbody>
1655 </table>"""
1656
1657_legend = """
1658 <table class="diff" summary="Legends">
1659 <tr> <th colspan="2"> Legends </th> </tr>
1660 <tr> <td> <table border="" summary="Colors">
1661 <tr><th> Colors </th> </tr>
1662 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1663 <tr><td class="diff_chg">Changed</td> </tr>
1664 <tr><td class="diff_sub">Deleted</td> </tr>
1665 </table></td>
1666 <td> <table border="" summary="Links">
1667 <tr><th colspan="2"> Links </th> </tr>
1668 <tr><td>(f)irst change</td> </tr>
1669 <tr><td>(n)ext change</td> </tr>
1670 <tr><td>(t)op</td> </tr>
1671 </table></td> </tr>
1672 </table>"""
1673
1674class HtmlDiff(object):
1675 """For producing HTML side by side comparison with change highlights.
1676
1677 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001678 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001679 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001680 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001681
Martin v. Löwise064b412004-08-29 16:34:40 +00001682 The following methods are provided for HTML generation:
1683
1684 make_table -- generates HTML for a single side by side table
1685 make_file -- generates complete HTML file with a single side by side table
1686
Tim Peters48bd7f32004-08-29 22:38:38 +00001687 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001688 """
1689
1690 _file_template = _file_template
1691 _styles = _styles
1692 _table_template = _table_template
1693 _legend = _legend
1694 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001695
Martin v. Löwise064b412004-08-29 16:34:40 +00001696 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1697 charjunk=IS_CHARACTER_JUNK):
1698 """HtmlDiff instance initializer
1699
1700 Arguments:
1701 tabsize -- tab stop spacing, defaults to 8.
1702 wrapcolumn -- column number where lines are broken and wrapped,
1703 defaults to None where lines are not wrapped.
1704 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001705 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001706 ndiff() documentation for argument default values and descriptions.
1707 """
1708 self._tabsize = tabsize
1709 self._wrapcolumn = wrapcolumn
1710 self._linejunk = linejunk
1711 self._charjunk = charjunk
1712
1713 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1714 numlines=5):
1715 """Returns HTML file of side by side comparison with change highlights
1716
1717 Arguments:
1718 fromlines -- list of "from" lines
1719 tolines -- list of "to" lines
1720 fromdesc -- "from" file column header string
1721 todesc -- "to" file column header string
1722 context -- set to True for contextual differences (defaults to False
1723 which shows full differences).
1724 numlines -- number of context lines. When context is set True,
1725 controls number of lines displayed before and after the change.
1726 When context is False, controls the number of lines to place
1727 the "next" link anchors before the next change (so click of
1728 "next" link jumps to just before the change).
1729 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001730
Martin v. Löwise064b412004-08-29 16:34:40 +00001731 return self._file_template % dict(
1732 styles = self._styles,
1733 legend = self._legend,
1734 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1735 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001736
Martin v. Löwise064b412004-08-29 16:34:40 +00001737 def _tab_newline_replace(self,fromlines,tolines):
1738 """Returns from/to line lists with tabs expanded and newlines removed.
1739
1740 Instead of tab characters being replaced by the number of spaces
1741 needed to fill in to the next tab stop, this function will fill
1742 the space with tab characters. This is done so that the difference
1743 algorithms can identify changes in a file when tabs are replaced by
1744 spaces and vice versa. At the end of the HTML generation, the tab
1745 characters will be replaced with a nonbreakable space.
1746 """
1747 def expand_tabs(line):
1748 # hide real spaces
1749 line = line.replace(' ','\0')
1750 # expand tabs into spaces
1751 line = line.expandtabs(self._tabsize)
Ezio Melotti13925002011-03-16 11:05:33 +02001752 # replace spaces from expanded tabs back into tab characters
Martin v. Löwise064b412004-08-29 16:34:40 +00001753 # (we'll replace them with markup after we do differencing)
1754 line = line.replace(' ','\t')
1755 return line.replace('\0',' ').rstrip('\n')
1756 fromlines = [expand_tabs(line) for line in fromlines]
1757 tolines = [expand_tabs(line) for line in tolines]
1758 return fromlines,tolines
1759
1760 def _split_line(self,data_list,line_num,text):
1761 """Builds list of text lines by splitting text lines at wrap point
1762
1763 This function will determine if the input text line needs to be
1764 wrapped (split) into separate lines. If so, the first wrap point
1765 will be determined and the first line appended to the output
1766 text line list. This function is used recursively to handle
1767 the second part of the split line to further split it.
1768 """
1769 # if blank line or context separator, just add it to the output list
1770 if not line_num:
1771 data_list.append((line_num,text))
1772 return
1773
1774 # if line text doesn't need wrapping, just add it to the output list
1775 size = len(text)
1776 max = self._wrapcolumn
1777 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1778 data_list.append((line_num,text))
1779 return
1780
1781 # scan text looking for the wrap point, keeping track if the wrap
1782 # point is inside markers
1783 i = 0
1784 n = 0
1785 mark = ''
1786 while n < max and i < size:
1787 if text[i] == '\0':
1788 i += 1
1789 mark = text[i]
1790 i += 1
1791 elif text[i] == '\1':
1792 i += 1
1793 mark = ''
1794 else:
1795 i += 1
1796 n += 1
1797
1798 # wrap point is inside text, break it up into separate lines
1799 line1 = text[:i]
1800 line2 = text[i:]
1801
1802 # if wrap point is inside markers, place end marker at end of first
1803 # line and start marker at beginning of second line because each
1804 # line will have its own table tag markup around it.
1805 if mark:
1806 line1 = line1 + '\1'
1807 line2 = '\0' + mark + line2
1808
Tim Peters48bd7f32004-08-29 22:38:38 +00001809 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001810 data_list.append((line_num,line1))
1811
Tim Peters48bd7f32004-08-29 22:38:38 +00001812 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001813 self._split_line(data_list,'>',line2)
1814
1815 def _line_wrapper(self,diffs):
1816 """Returns iterator that splits (wraps) mdiff text lines"""
1817
1818 # pull from/to data and flags from mdiff iterator
1819 for fromdata,todata,flag in diffs:
1820 # check for context separators and pass them through
1821 if flag is None:
1822 yield fromdata,todata,flag
1823 continue
1824 (fromline,fromtext),(toline,totext) = fromdata,todata
1825 # for each from/to line split it at the wrap column to form
1826 # list of text lines.
1827 fromlist,tolist = [],[]
1828 self._split_line(fromlist,fromline,fromtext)
1829 self._split_line(tolist,toline,totext)
1830 # yield from/to line in pairs inserting blank lines as
1831 # necessary when one side has more wrapped lines
1832 while fromlist or tolist:
1833 if fromlist:
1834 fromdata = fromlist.pop(0)
1835 else:
1836 fromdata = ('',' ')
1837 if tolist:
1838 todata = tolist.pop(0)
1839 else:
1840 todata = ('',' ')
1841 yield fromdata,todata,flag
1842
1843 def _collect_lines(self,diffs):
1844 """Collects mdiff output into separate lists
1845
1846 Before storing the mdiff from/to data into a list, it is converted
1847 into a single line of text with HTML markup.
1848 """
1849
1850 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001851 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001852 for fromdata,todata,flag in diffs:
1853 try:
1854 # store HTML markup of the lines into the lists
1855 fromlist.append(self._format_line(0,flag,*fromdata))
1856 tolist.append(self._format_line(1,flag,*todata))
1857 except TypeError:
1858 # exceptions occur for lines where context separators go
1859 fromlist.append(None)
1860 tolist.append(None)
1861 flaglist.append(flag)
1862 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001863
Martin v. Löwise064b412004-08-29 16:34:40 +00001864 def _format_line(self,side,flag,linenum,text):
1865 """Returns HTML markup of "from" / "to" text lines
1866
1867 side -- 0 or 1 indicating "from" or "to" text
1868 flag -- indicates if difference on line
1869 linenum -- line number (used for line number column)
1870 text -- line text to be marked up
1871 """
1872 try:
1873 linenum = '%d' % linenum
1874 id = ' id="%s%s"' % (self._prefix[side],linenum)
1875 except TypeError:
1876 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001877 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001878 # replace those things that would get confused with HTML symbols
1879 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1880
1881 # make space non-breakable so they don't get compressed or line wrapped
1882 text = text.replace(' ','&nbsp;').rstrip()
1883
1884 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1885 % (id,linenum,text)
1886
1887 def _make_prefix(self):
1888 """Create unique anchor prefixes"""
1889
1890 # Generate a unique anchor prefix so multiple tables
1891 # can exist on the same HTML page without conflicts.
1892 fromprefix = "from%d_" % HtmlDiff._default_prefix
1893 toprefix = "to%d_" % HtmlDiff._default_prefix
1894 HtmlDiff._default_prefix += 1
1895 # store prefixes so line format method has access
1896 self._prefix = [fromprefix,toprefix]
1897
1898 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1899 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001900
Martin v. Löwise064b412004-08-29 16:34:40 +00001901 # all anchor names will be generated using the unique "to" prefix
1902 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001903
Martin v. Löwise064b412004-08-29 16:34:40 +00001904 # process change flags, generating middle column of next anchors/links
1905 next_id = ['']*len(flaglist)
1906 next_href = ['']*len(flaglist)
1907 num_chg, in_change = 0, False
1908 last = 0
1909 for i,flag in enumerate(flaglist):
1910 if flag:
1911 if not in_change:
1912 in_change = True
1913 last = i
1914 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001915 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001916 # link
1917 i = max([0,i-numlines])
1918 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001919 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001920 # change
1921 num_chg += 1
1922 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1923 toprefix,num_chg)
1924 else:
1925 in_change = False
1926 # check for cases where there is no content to avoid exceptions
1927 if not flaglist:
1928 flaglist = [False]
1929 next_id = ['']
1930 next_href = ['']
1931 last = 0
1932 if context:
1933 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1934 tolist = fromlist
1935 else:
1936 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1937 # if not a change on first line, drop a link
1938 if not flaglist[0]:
1939 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1940 # redo the last link to link to the top
1941 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1942
1943 return fromlist,tolist,flaglist,next_href,next_id
1944
1945 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1946 numlines=5):
1947 """Returns HTML table of side by side comparison with change highlights
1948
1949 Arguments:
1950 fromlines -- list of "from" lines
1951 tolines -- list of "to" lines
1952 fromdesc -- "from" file column header string
1953 todesc -- "to" file column header string
1954 context -- set to True for contextual differences (defaults to False
1955 which shows full differences).
1956 numlines -- number of context lines. When context is set True,
1957 controls number of lines displayed before and after the change.
1958 When context is False, controls the number of lines to place
1959 the "next" link anchors before the next change (so click of
1960 "next" link jumps to just before the change).
1961 """
1962
1963 # make unique anchor prefixes so that multiple tables may exist
1964 # on the same page without conflict.
1965 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001966
Martin v. Löwise064b412004-08-29 16:34:40 +00001967 # change tabs to spaces before it gets more difficult after we insert
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001968 # markup
Martin v. Löwise064b412004-08-29 16:34:40 +00001969 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001970
Martin v. Löwise064b412004-08-29 16:34:40 +00001971 # create diffs iterator which generates side by side from/to data
1972 if context:
1973 context_lines = numlines
1974 else:
1975 context_lines = None
1976 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1977 charjunk=self._charjunk)
1978
1979 # set up iterator to wrap lines that exceed desired width
1980 if self._wrapcolumn:
1981 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001982
Martin v. Löwise064b412004-08-29 16:34:40 +00001983 # collect up from/to lines and flags into lists (also format the lines)
1984 fromlist,tolist,flaglist = self._collect_lines(diffs)
1985
1986 # process change flags, generating middle column of next anchors/links
1987 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1988 fromlist,tolist,flaglist,context,numlines)
1989
Guido van Rossumd8faa362007-04-27 19:54:29 +00001990 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00001991 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1992 '<td class="diff_next">%s</td>%s</tr>\n'
1993 for i in range(len(flaglist)):
1994 if flaglist[i] is None:
1995 # mdiff yields None on separator lines skip the bogus ones
1996 # generated for the first line
1997 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001998 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00001999 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002000 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00002001 next_href[i],tolist[i]))
2002 if fromdesc or todesc:
2003 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
2004 '<th class="diff_next"><br /></th>',
2005 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
2006 '<th class="diff_next"><br /></th>',
2007 '<th colspan="2" class="diff_header">%s</th>' % todesc)
2008 else:
2009 header_row = ''
2010
2011 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002012 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00002013 header_row=header_row,
2014 prefix=self._prefix[1])
2015
2016 return table.replace('\0+','<span class="diff_add">'). \
2017 replace('\0-','<span class="diff_sub">'). \
2018 replace('\0^','<span class="diff_chg">'). \
2019 replace('\1','</span>'). \
2020 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00002021
Martin v. Löwise064b412004-08-29 16:34:40 +00002022del re
2023
Tim Peters5e824c32001-08-12 22:25:01 +00002024def restore(delta, which):
2025 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00002026 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00002027
2028 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
2029 lines originating from file 1 or 2 (parameter `which`), stripping off line
2030 prefixes.
2031
2032 Examples:
2033
Ezio Melottid8b509b2011-09-28 17:37:55 +03002034 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
2035 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Tim Peters8a9c2842001-09-22 21:30:22 +00002036 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002037 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002038 one
2039 two
2040 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002041 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002042 ore
2043 tree
2044 emu
2045 """
2046 try:
2047 tag = {1: "- ", 2: "+ "}[int(which)]
2048 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002049 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Tim Peters5e824c32001-08-12 22:25:01 +00002050 % which)
2051 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002052 for line in delta:
2053 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002054 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002055
Tim Peters9ae21482001-02-10 08:00:53 +00002056def _test():
2057 import doctest, difflib
2058 return doctest.testmod(difflib)
2059
2060if __name__ == "__main__":
2061 _test()