blob: cc573f982779db678d2443216ea4b685b330c0c3 [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
Tim Peters9ae21482001-02-10 08:00:53 +0000337 def find_longest_match(self, alo, ahi, blo, bhi):
338 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
339
340 If isjunk is not defined:
341
342 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
343 alo <= i <= i+k <= ahi
344 blo <= j <= j+k <= bhi
345 and for all (i',j',k') meeting those conditions,
346 k >= k'
347 i <= i'
348 and if i == i', j <= j'
349
350 In other words, of all maximal matching blocks, return one that
351 starts earliest in a, and of all those maximal matching blocks that
352 start earliest in a, return the one that starts earliest in b.
353
354 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
355 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000356 Match(a=0, b=4, size=5)
Tim Peters9ae21482001-02-10 08:00:53 +0000357
358 If isjunk is defined, first the longest matching block is
359 determined as above, but with the additional restriction that no
360 junk element appears in the block. Then that block is extended as
361 far as possible by matching (only) junk elements on both sides. So
362 the resulting block never matches on junk except as identical junk
363 happens to be adjacent to an "interesting" match.
364
365 Here's the same example as before, but considering blanks to be
366 junk. That prevents " abcd" from matching the " abcd" at the tail
367 end of the second sequence directly. Instead only the "abcd" can
368 match, and matches the leftmost "abcd" in the second sequence:
369
370 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
371 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000372 Match(a=1, b=0, size=4)
Tim Peters9ae21482001-02-10 08:00:53 +0000373
374 If no blocks match, return (alo, blo, 0).
375
376 >>> s = SequenceMatcher(None, "ab", "c")
377 >>> s.find_longest_match(0, 2, 0, 1)
Christian Heimes25bb7832008-01-11 16:17:00 +0000378 Match(a=0, b=0, size=0)
Tim Peters9ae21482001-02-10 08:00:53 +0000379 """
380
381 # CAUTION: stripping common prefix or suffix would be incorrect.
382 # E.g.,
383 # ab
384 # acab
385 # Longest matching block is "ab", but if common prefix is
386 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
387 # strip, so ends up claiming that ab is changed to acab by
388 # inserting "ca" in the middle. That's minimal but unintuitive:
389 # "it's obvious" that someone inserted "ac" at the front.
390 # Windiff ends up at the same place as diff, but by pairing up
391 # the unique 'b's and then matching the first two 'a's.
392
Terry Reedybcd89882010-12-03 22:29:40 +0000393 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000394 besti, bestj, bestsize = alo, blo, 0
395 # find longest junk-free match
396 # during an iteration of the loop, j2len[j] = length of longest
397 # junk-free match ending with a[i-1] and b[j]
398 j2len = {}
399 nothing = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000400 for i in range(alo, ahi):
Tim Peters9ae21482001-02-10 08:00:53 +0000401 # look at all instances of a[i] in b; note that because
402 # b2j has no junk keys, the loop is skipped if a[i] is junk
403 j2lenget = j2len.get
404 newj2len = {}
405 for j in b2j.get(a[i], nothing):
406 # a[i] matches b[j]
407 if j < blo:
408 continue
409 if j >= bhi:
410 break
411 k = newj2len[j] = j2lenget(j-1, 0) + 1
412 if k > bestsize:
413 besti, bestj, bestsize = i-k+1, j-k+1, k
414 j2len = newj2len
415
Tim Peters81b92512002-04-29 01:37:32 +0000416 # Extend the best by non-junk elements on each end. In particular,
417 # "popular" non-junk elements aren't in b2j, which greatly speeds
418 # the inner loop above, but also means "the best" match so far
419 # doesn't contain any junk *or* popular non-junk elements.
420 while besti > alo and bestj > blo and \
421 not isbjunk(b[bestj-1]) and \
422 a[besti-1] == b[bestj-1]:
423 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
424 while besti+bestsize < ahi and bestj+bestsize < bhi and \
425 not isbjunk(b[bestj+bestsize]) and \
426 a[besti+bestsize] == b[bestj+bestsize]:
427 bestsize += 1
428
Tim Peters9ae21482001-02-10 08:00:53 +0000429 # Now that we have a wholly interesting match (albeit possibly
430 # empty!), we may as well suck up the matching junk on each
431 # side of it too. Can't think of a good reason not to, and it
432 # saves post-processing the (possibly considerable) expense of
433 # figuring out what to do with it. In the case of an empty
434 # interesting match, this is clearly the right thing to do,
435 # because no other kind of match is possible in the regions.
436 while besti > alo and bestj > blo and \
437 isbjunk(b[bestj-1]) and \
438 a[besti-1] == b[bestj-1]:
439 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
440 while besti+bestsize < ahi and bestj+bestsize < bhi and \
441 isbjunk(b[bestj+bestsize]) and \
442 a[besti+bestsize] == b[bestj+bestsize]:
443 bestsize = bestsize + 1
444
Christian Heimes25bb7832008-01-11 16:17:00 +0000445 return Match(besti, bestj, bestsize)
Tim Peters9ae21482001-02-10 08:00:53 +0000446
447 def get_matching_blocks(self):
448 """Return list of triples describing matching subsequences.
449
450 Each triple is of the form (i, j, n), and means that
451 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000452 i and in j. New in Python 2.5, it's also guaranteed that if
453 (i, j, n) and (i', j', n') are adjacent triples in the list, and
454 the second is not the last triple in the list, then i+n != i' or
455 j+n != j'. IOW, adjacent triples never describe adjacent equal
456 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000457
458 The last triple is a dummy, (len(a), len(b), 0), and is the only
459 triple with n==0.
460
461 >>> s = SequenceMatcher(None, "abxcd", "abcd")
Christian Heimes25bb7832008-01-11 16:17:00 +0000462 >>> list(s.get_matching_blocks())
463 [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 +0000464 """
465
466 if self.matching_blocks is not None:
467 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000468 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000469
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000470 # This is most naturally expressed as a recursive algorithm, but
471 # at least one user bumped into extreme use cases that exceeded
472 # the recursion limit on their box. So, now we maintain a list
473 # ('queue`) of blocks we still need to look at, and append partial
474 # results to `matching_blocks` in a loop; the matches are sorted
475 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000476 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000477 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000478 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000479 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000480 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000481 # a[alo:i] vs b[blo:j] unknown
482 # a[i:i+k] same as b[j:j+k]
483 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000484 if k: # if k is 0, there was no matching block
485 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000486 if alo < i and blo < j:
487 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000488 if i+k < ahi and j+k < bhi:
489 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000490 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000491
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000492 # It's possible that we have adjacent equal blocks in the
493 # matching_blocks list now. Starting with 2.5, this code was added
494 # to collapse them.
495 i1 = j1 = k1 = 0
496 non_adjacent = []
497 for i2, j2, k2 in matching_blocks:
498 # Is this block adjacent to i1, j1, k1?
499 if i1 + k1 == i2 and j1 + k1 == j2:
500 # Yes, so collapse them -- this just increases the length of
501 # the first block by the length of the second, and the first
502 # block so lengthened remains the block to compare against.
503 k1 += k2
504 else:
505 # Not adjacent. Remember the first block (k1==0 means it's
506 # the dummy we started with), and make the second block the
507 # new block to compare against.
508 if k1:
509 non_adjacent.append((i1, j1, k1))
510 i1, j1, k1 = i2, j2, k2
511 if k1:
512 non_adjacent.append((i1, j1, k1))
513
514 non_adjacent.append( (la, lb, 0) )
515 self.matching_blocks = non_adjacent
Christian Heimes25bb7832008-01-11 16:17:00 +0000516 return map(Match._make, self.matching_blocks)
Tim Peters9ae21482001-02-10 08:00:53 +0000517
Tim Peters9ae21482001-02-10 08:00:53 +0000518 def get_opcodes(self):
519 """Return list of 5-tuples describing how to turn a into b.
520
521 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
522 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
523 tuple preceding it, and likewise for j1 == the previous j2.
524
525 The tags are strings, with these meanings:
526
527 'replace': a[i1:i2] should be replaced by b[j1:j2]
528 'delete': a[i1:i2] should be deleted.
529 Note that j1==j2 in this case.
530 'insert': b[j1:j2] should be inserted at a[i1:i1].
531 Note that i1==i2 in this case.
532 'equal': a[i1:i2] == b[j1:j2]
533
534 >>> a = "qabxcd"
535 >>> b = "abycdf"
536 >>> s = SequenceMatcher(None, a, b)
537 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000538 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
539 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000540 delete a[0:1] (q) b[0:0] ()
541 equal a[1:3] (ab) b[0:2] (ab)
542 replace a[3:4] (x) b[2:3] (y)
543 equal a[4:6] (cd) b[3:5] (cd)
544 insert a[6:6] () b[5:6] (f)
545 """
546
547 if self.opcodes is not None:
548 return self.opcodes
549 i = j = 0
550 self.opcodes = answer = []
551 for ai, bj, size in self.get_matching_blocks():
552 # invariant: we've pumped out correct diffs to change
553 # a[:i] into b[:j], and the next matching block is
554 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
555 # out a diff to change a[i:ai] into b[j:bj], pump out
556 # the matching block, and move (i,j) beyond the match
557 tag = ''
558 if i < ai and j < bj:
559 tag = 'replace'
560 elif i < ai:
561 tag = 'delete'
562 elif j < bj:
563 tag = 'insert'
564 if tag:
565 answer.append( (tag, i, ai, j, bj) )
566 i, j = ai+size, bj+size
567 # the list of matching blocks is terminated by a
568 # sentinel with size 0
569 if size:
570 answer.append( ('equal', ai, i, bj, j) )
571 return answer
572
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000573 def get_grouped_opcodes(self, n=3):
574 """ Isolate change clusters by eliminating ranges with no changes.
575
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300576 Return a generator of groups with up to n lines of context.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000577 Each group is in the same format as returned by get_opcodes().
578
579 >>> from pprint import pprint
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000580 >>> a = list(map(str, range(1,40)))
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000581 >>> b = a[:]
582 >>> b[8:8] = ['i'] # Make an insertion
583 >>> b[20] += 'x' # Make a replacement
584 >>> b[23:28] = [] # Make a deletion
585 >>> b[30] += 'y' # Make another replacement
586 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
587 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
588 [('equal', 16, 19, 17, 20),
589 ('replace', 19, 20, 20, 21),
590 ('equal', 20, 22, 21, 23),
591 ('delete', 22, 27, 23, 23),
592 ('equal', 27, 30, 23, 26)],
593 [('equal', 31, 34, 27, 30),
594 ('replace', 34, 35, 30, 31),
595 ('equal', 35, 38, 31, 34)]]
596 """
597
598 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000599 if not codes:
600 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000601 # Fixup leading and trailing groups if they show no changes.
602 if codes[0][0] == 'equal':
603 tag, i1, i2, j1, j2 = codes[0]
604 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
605 if codes[-1][0] == 'equal':
606 tag, i1, i2, j1, j2 = codes[-1]
607 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
608
609 nn = n + n
610 group = []
611 for tag, i1, i2, j1, j2 in codes:
612 # End the current group and start a new one whenever
613 # there is a large range with no changes.
614 if tag == 'equal' and i2-i1 > nn:
615 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
616 yield group
617 group = []
618 i1, j1 = max(i1, i2-n), max(j1, j2-n)
619 group.append((tag, i1, i2, j1 ,j2))
620 if group and not (len(group)==1 and group[0][0] == 'equal'):
621 yield group
622
Tim Peters9ae21482001-02-10 08:00:53 +0000623 def ratio(self):
624 """Return a measure of the sequences' similarity (float in [0,1]).
625
626 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000627 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000628 Note that this is 1 if the sequences are identical, and 0 if
629 they have nothing in common.
630
631 .ratio() is expensive to compute if you haven't already computed
632 .get_matching_blocks() or .get_opcodes(), in which case you may
633 want to try .quick_ratio() or .real_quick_ratio() first to get an
634 upper bound.
635
636 >>> s = SequenceMatcher(None, "abcd", "bcde")
637 >>> s.ratio()
638 0.75
639 >>> s.quick_ratio()
640 0.75
641 >>> s.real_quick_ratio()
642 1.0
643 """
644
Guido van Rossum89da5d72006-08-22 00:21:25 +0000645 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000646 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000647
648 def quick_ratio(self):
649 """Return an upper bound on ratio() relatively quickly.
650
651 This isn't defined beyond that it is an upper bound on .ratio(), and
652 is faster to compute.
653 """
654
655 # viewing a and b as multisets, set matches to the cardinality
656 # of their intersection; this counts the number of matches
657 # without regard to order, so is clearly an upper bound
658 if self.fullbcount is None:
659 self.fullbcount = fullbcount = {}
660 for elt in self.b:
661 fullbcount[elt] = fullbcount.get(elt, 0) + 1
662 fullbcount = self.fullbcount
663 # avail[x] is the number of times x appears in 'b' less the
664 # number of times we've seen it in 'a' so far ... kinda
665 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000666 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000667 for elt in self.a:
668 if availhas(elt):
669 numb = avail[elt]
670 else:
671 numb = fullbcount.get(elt, 0)
672 avail[elt] = numb - 1
673 if numb > 0:
674 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000675 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000676
677 def real_quick_ratio(self):
678 """Return an upper bound on ratio() very quickly.
679
680 This isn't defined beyond that it is an upper bound on .ratio(), and
681 is faster to compute than either .ratio() or .quick_ratio().
682 """
683
684 la, lb = len(self.a), len(self.b)
685 # can't have more matches than the number of elements in the
686 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000687 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000688
689def get_close_matches(word, possibilities, n=3, cutoff=0.6):
690 """Use SequenceMatcher to return list of the best "good enough" matches.
691
692 word is a sequence for which close matches are desired (typically a
693 string).
694
695 possibilities is a list of sequences against which to match word
696 (typically a list of strings).
697
698 Optional arg n (default 3) is the maximum number of close matches to
699 return. n must be > 0.
700
701 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
702 that don't score at least that similar to word are ignored.
703
704 The best (no more than n) matches among the possibilities are returned
705 in a list, sorted by similarity score, most similar first.
706
707 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
708 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000709 >>> import keyword as _keyword
710 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000711 ['while']
Guido van Rossum486364b2007-06-30 05:01:58 +0000712 >>> get_close_matches("Apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000713 []
Tim Peters5e824c32001-08-12 22:25:01 +0000714 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000715 ['except']
716 """
717
718 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000719 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000720 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000721 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000722 result = []
723 s = SequenceMatcher()
724 s.set_seq2(word)
725 for x in possibilities:
726 s.set_seq1(x)
727 if s.real_quick_ratio() >= cutoff and \
728 s.quick_ratio() >= cutoff and \
729 s.ratio() >= cutoff:
730 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000731
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000732 # Move the best scorers to head of list
Raymond Hettingeraefde432004-06-15 23:53:35 +0000733 result = heapq.nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000734 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000735 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000736
737def _count_leading(line, ch):
738 """
739 Return number of `ch` characters at the start of `line`.
740
741 Example:
742
743 >>> _count_leading(' abc', ' ')
744 3
745 """
746
747 i, n = 0, len(line)
748 while i < n and line[i] == ch:
749 i += 1
750 return i
751
752class Differ:
753 r"""
754 Differ is a class for comparing sequences of lines of text, and
755 producing human-readable differences or deltas. Differ uses
756 SequenceMatcher both to compare sequences of lines, and to compare
757 sequences of characters within similar (near-matching) lines.
758
759 Each line of a Differ delta begins with a two-letter code:
760
761 '- ' line unique to sequence 1
762 '+ ' line unique to sequence 2
763 ' ' line common to both sequences
764 '? ' line not present in either input sequence
765
766 Lines beginning with '? ' attempt to guide the eye to intraline
767 differences, and were not present in either input sequence. These lines
768 can be confusing if the sequences contain tab characters.
769
770 Note that Differ makes no claim to produce a *minimal* diff. To the
771 contrary, minimal diffs are often counter-intuitive, because they synch
772 up anywhere possible, sometimes accidental matches 100 pages apart.
773 Restricting synch points to contiguous matches preserves some notion of
774 locality, at the occasional cost of producing a longer diff.
775
776 Example: Comparing two texts.
777
778 First we set up the texts, sequences of individual single-line strings
779 ending with newlines (such sequences can also be obtained from the
780 `readlines()` method of file-like objects):
781
782 >>> text1 = ''' 1. Beautiful is better than ugly.
783 ... 2. Explicit is better than implicit.
784 ... 3. Simple is better than complex.
785 ... 4. Complex is better than complicated.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300786 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000787 >>> len(text1)
788 4
789 >>> text1[0][-1]
790 '\n'
791 >>> text2 = ''' 1. Beautiful is better than ugly.
792 ... 3. Simple is better than complex.
793 ... 4. Complicated is better than complex.
794 ... 5. Flat is better than nested.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300795 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000796
797 Next we instantiate a Differ object:
798
799 >>> d = Differ()
800
801 Note that when instantiating a Differ object we may pass functions to
802 filter out line and character 'junk'. See Differ.__init__ for details.
803
804 Finally, we compare the two:
805
Tim Peters8a9c2842001-09-22 21:30:22 +0000806 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000807
808 'result' is a list of strings, so let's pretty-print it:
809
810 >>> from pprint import pprint as _pprint
811 >>> _pprint(result)
812 [' 1. Beautiful is better than ugly.\n',
813 '- 2. Explicit is better than implicit.\n',
814 '- 3. Simple is better than complex.\n',
815 '+ 3. Simple is better than complex.\n',
816 '? ++\n',
817 '- 4. Complex is better than complicated.\n',
818 '? ^ ---- ^\n',
819 '+ 4. Complicated is better than complex.\n',
820 '? ++++ ^ ^\n',
821 '+ 5. Flat is better than nested.\n']
822
823 As a single multi-line string it looks like this:
824
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000825 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000826 1. Beautiful is better than ugly.
827 - 2. Explicit is better than implicit.
828 - 3. Simple is better than complex.
829 + 3. Simple is better than complex.
830 ? ++
831 - 4. Complex is better than complicated.
832 ? ^ ---- ^
833 + 4. Complicated is better than complex.
834 ? ++++ ^ ^
835 + 5. Flat is better than nested.
836
837 Methods:
838
839 __init__(linejunk=None, charjunk=None)
840 Construct a text differencer, with optional filters.
841
842 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000843 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000844 """
845
846 def __init__(self, linejunk=None, charjunk=None):
847 """
848 Construct a text differencer, with optional filters.
849
850 The two optional keyword parameters are for filter functions:
851
852 - `linejunk`: A function that should accept a single string argument,
853 and return true iff the string is junk. The module-level function
854 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000855 characters, except for at most one splat ('#'). It is recommended
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -0400856 to leave linejunk None; the underlying SequenceMatcher class has
857 an adaptive notion of "noise" lines that's better than any static
858 definition the author has ever been able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000859
860 - `charjunk`: A function that should accept a string of length 1. The
861 module-level function `IS_CHARACTER_JUNK` may be used to filter out
862 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000863 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000864 """
865
866 self.linejunk = linejunk
867 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000868
869 def compare(self, a, b):
870 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000871 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000872
873 Each sequence must contain individual single-line strings ending with
874 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000875 of file-like objects. The delta generated also consists of newline-
876 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000877 method of a file-like object.
878
879 Example:
880
Ezio Melottid8b509b2011-09-28 17:37:55 +0300881 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(True),
882 ... 'ore\ntree\nemu\n'.splitlines(True))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000883 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000884 - one
885 ? ^
886 + ore
887 ? ^
888 - two
889 - three
890 ? -
891 + tree
892 + emu
893 """
894
895 cruncher = SequenceMatcher(self.linejunk, a, b)
896 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
897 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000898 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000899 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000900 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000901 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000902 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000903 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000904 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000905 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000906 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +0000907
Philip Jenvey4993cc02012-10-01 12:53:43 -0700908 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +0000909
910 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000911 """Generate comparison results for a same-tagged range."""
Guido van Rossum805365e2007-05-07 22:24:25 +0000912 for i in range(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000913 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000914
915 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
916 assert alo < ahi and blo < bhi
917 # dump the shorter block first -- reduces the burden on short-term
918 # memory if the blocks are of very different sizes
919 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000920 first = self._dump('+', b, blo, bhi)
921 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000922 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000923 first = self._dump('-', a, alo, ahi)
924 second = self._dump('+', b, blo, bhi)
925
926 for g in first, second:
Philip Jenvey4993cc02012-10-01 12:53:43 -0700927 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +0000928
929 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
930 r"""
931 When replacing one block of lines with another, search the blocks
932 for *similar* lines; the best-matching pair (if any) is used as a
933 synch point, and intraline difference marking is done on the
934 similar pair. Lots of work, but often worth it.
935
936 Example:
937
938 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000939 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
940 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000941 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000942 - abcDefghiJkl
943 ? ^ ^ ^
944 + abcdefGhijkl
945 ? ^ ^ ^
946 """
947
Tim Peters5e824c32001-08-12 22:25:01 +0000948 # don't synch up unless the lines have a similarity score of at
949 # least cutoff; best_ratio tracks the best score seen so far
950 best_ratio, cutoff = 0.74, 0.75
951 cruncher = SequenceMatcher(self.charjunk)
952 eqi, eqj = None, None # 1st indices of equal lines (if any)
953
954 # search for the pair that matches best without being identical
955 # (identical lines must be junk lines, & we don't want to synch up
956 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000957 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000958 bj = b[j]
959 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000960 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000961 ai = a[i]
962 if ai == bj:
963 if eqi is None:
964 eqi, eqj = i, j
965 continue
966 cruncher.set_seq1(ai)
967 # computing similarity is expensive, so use the quick
968 # upper bounds first -- have seen this speed up messy
969 # compares by a factor of 3.
970 # note that ratio() is only expensive to compute the first
971 # time it's called on a sequence pair; the expensive part
972 # of the computation is cached by cruncher
973 if cruncher.real_quick_ratio() > best_ratio and \
974 cruncher.quick_ratio() > best_ratio and \
975 cruncher.ratio() > best_ratio:
976 best_ratio, best_i, best_j = cruncher.ratio(), i, j
977 if best_ratio < cutoff:
978 # no non-identical "pretty close" pair
979 if eqi is None:
980 # no identical pair either -- treat it as a straight replace
Philip Jenvey4993cc02012-10-01 12:53:43 -0700981 yield from self._plain_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000982 return
983 # no close pair, but an identical pair -- synch up on that
984 best_i, best_j, best_ratio = eqi, eqj, 1.0
985 else:
986 # there's a close pair, so forget the identical pair (if any)
987 eqi = None
988
989 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
990 # identical
Tim Peters5e824c32001-08-12 22:25:01 +0000991
992 # pump out diffs from before the synch point
Philip Jenvey4993cc02012-10-01 12:53:43 -0700993 yield from self._fancy_helper(a, alo, best_i, b, blo, best_j)
Tim Peters5e824c32001-08-12 22:25:01 +0000994
995 # do intraline marking on the synch pair
996 aelt, belt = a[best_i], b[best_j]
997 if eqi is None:
998 # pump out a '-', '?', '+', '?' quad for the synched lines
999 atags = btags = ""
1000 cruncher.set_seqs(aelt, belt)
1001 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1002 la, lb = ai2 - ai1, bj2 - bj1
1003 if tag == 'replace':
1004 atags += '^' * la
1005 btags += '^' * lb
1006 elif tag == 'delete':
1007 atags += '-' * la
1008 elif tag == 'insert':
1009 btags += '+' * lb
1010 elif tag == 'equal':
1011 atags += ' ' * la
1012 btags += ' ' * lb
1013 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001014 raise ValueError('unknown tag %r' % (tag,))
Philip Jenvey4993cc02012-10-01 12:53:43 -07001015 yield from self._qformat(aelt, belt, atags, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001016 else:
1017 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001018 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001019
1020 # pump out diffs from after the synch point
Philip Jenvey4993cc02012-10-01 12:53:43 -07001021 yield from self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001022
1023 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001024 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001025 if alo < ahi:
1026 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001027 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001028 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001029 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001030 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001031 g = self._dump('+', b, blo, bhi)
1032
Philip Jenvey4993cc02012-10-01 12:53:43 -07001033 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +00001034
1035 def _qformat(self, aline, bline, atags, btags):
1036 r"""
1037 Format "?" output and deal with leading tabs.
1038
1039 Example:
1040
1041 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001042 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1043 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001044 >>> for line in results: print(repr(line))
1045 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001046 '- \tabcDefghiJkl\n'
1047 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001048 '+ \tabcdefGhijkl\n'
1049 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001050 """
1051
1052 # Can hurt, but will probably help most of the time.
1053 common = min(_count_leading(aline, "\t"),
1054 _count_leading(bline, "\t"))
1055 common = min(common, _count_leading(atags[:common], " "))
Senthil Kumaran758025c2009-11-23 19:02:52 +00001056 common = min(common, _count_leading(btags[:common], " "))
Tim Peters5e824c32001-08-12 22:25:01 +00001057 atags = atags[common:].rstrip()
1058 btags = btags[common:].rstrip()
1059
Tim Peters8a9c2842001-09-22 21:30:22 +00001060 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001061 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001062 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001063
Tim Peters8a9c2842001-09-22 21:30:22 +00001064 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001065 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001066 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001067
1068# With respect to junk, an earlier version of ndiff simply refused to
1069# *start* a match with a junk element. The result was cases like this:
1070# before: private Thread currentThread;
1071# after: private volatile Thread currentThread;
1072# If you consider whitespace to be junk, the longest contiguous match
1073# not starting with junk is "e Thread currentThread". So ndiff reported
1074# that "e volatil" was inserted between the 't' and the 'e' in "private".
1075# While an accurate view, to people that's absurd. The current version
1076# looks for matching blocks that are entirely junk-free, then extends the
1077# longest one of those as far as possible but only with matching junk.
1078# So now "currentThread" is matched, then extended to suck up the
1079# preceding blank; then "private" is matched, and extended to suck up the
1080# following blank; then "Thread" is matched; and finally ndiff reports
1081# that "volatile " was inserted before "Thread". The only quibble
1082# remaining is that perhaps it was really the case that " volatile"
1083# was inserted after "private". I can live with that <wink>.
1084
1085import re
1086
1087def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1088 r"""
1089 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1090
1091 Examples:
1092
1093 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001094 True
Tim Peters5e824c32001-08-12 22:25:01 +00001095 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001096 True
Tim Peters5e824c32001-08-12 22:25:01 +00001097 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001098 False
Tim Peters5e824c32001-08-12 22:25:01 +00001099 """
1100
1101 return pat(line) is not None
1102
1103def IS_CHARACTER_JUNK(ch, ws=" \t"):
1104 r"""
1105 Return 1 for ignorable character: iff `ch` is a space or tab.
1106
1107 Examples:
1108
1109 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001110 True
Tim Peters5e824c32001-08-12 22:25:01 +00001111 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001112 True
Tim Peters5e824c32001-08-12 22:25:01 +00001113 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001114 False
Tim Peters5e824c32001-08-12 22:25:01 +00001115 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001116 False
Tim Peters5e824c32001-08-12 22:25:01 +00001117 """
1118
1119 return ch in ws
1120
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001121
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001122########################################################################
1123### Unified Diff
1124########################################################################
1125
1126def _format_range_unified(start, stop):
Raymond Hettinger49353d02011-04-11 12:40:58 -07001127 'Convert range to the "ed" format'
1128 # Per the diff spec at http://www.unix.org/single_unix_specification/
1129 beginning = start + 1 # lines start numbering with one
1130 length = stop - start
1131 if length == 1:
1132 return '{}'.format(beginning)
1133 if not length:
1134 beginning -= 1 # empty ranges begin at line just before the range
1135 return '{},{}'.format(beginning, length)
1136
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001137def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1138 tofiledate='', n=3, lineterm='\n'):
1139 r"""
1140 Compare two sequences of lines; generate the delta as a unified diff.
1141
1142 Unified diffs are a compact way of showing line changes and a few
1143 lines of context. The number of context lines is set by 'n' which
1144 defaults to three.
1145
Raymond Hettinger0887c732003-06-17 16:53:25 +00001146 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001147 created with a trailing newline. This is helpful so that inputs
1148 created from file.readlines() result in diffs that are suitable for
1149 file.writelines() since both the inputs and outputs have trailing
1150 newlines.
1151
1152 For inputs that do not have trailing newlines, set the lineterm
1153 argument to "" so that the output will be uniformly newline free.
1154
1155 The unidiff format normally has a header for filenames and modification
1156 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001157 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1158 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001159
1160 Example:
1161
1162 >>> for line in unified_diff('one two three four'.split(),
1163 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001164 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001165 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001166 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1167 --- Original 2005-01-26 23:30:50
1168 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001169 @@ -1,4 +1,4 @@
1170 +zero
1171 one
1172 -two
1173 -three
1174 +tree
1175 four
1176 """
1177
1178 started = False
1179 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1180 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001181 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001182 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1183 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1184 yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
1185 yield '+++ {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger49353d02011-04-11 12:40:58 -07001186
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001187 first, last = group[0], group[-1]
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001188 file1_range = _format_range_unified(first[1], last[2])
1189 file2_range = _format_range_unified(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001190 yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
1191
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001192 for tag, i1, i2, j1, j2 in group:
1193 if tag == 'equal':
1194 for line in a[i1:i2]:
1195 yield ' ' + line
1196 continue
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001197 if tag in {'replace', 'delete'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001198 for line in a[i1:i2]:
1199 yield '-' + line
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001200 if tag in {'replace', 'insert'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001201 for line in b[j1:j2]:
1202 yield '+' + line
1203
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001204
1205########################################################################
1206### Context Diff
1207########################################################################
1208
1209def _format_range_context(start, stop):
1210 'Convert range to the "ed" format'
1211 # Per the diff spec at http://www.unix.org/single_unix_specification/
1212 beginning = start + 1 # lines start numbering with one
1213 length = stop - start
1214 if not length:
1215 beginning -= 1 # empty ranges begin at line just before the range
1216 if length <= 1:
1217 return '{}'.format(beginning)
1218 return '{},{}'.format(beginning, beginning + length - 1)
1219
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001220# See http://www.unix.org/single_unix_specification/
1221def context_diff(a, b, fromfile='', tofile='',
1222 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1223 r"""
1224 Compare two sequences of lines; generate the delta as a context diff.
1225
1226 Context diffs are a compact way of showing line changes and a few
1227 lines of context. The number of context lines is set by 'n' which
1228 defaults to three.
1229
1230 By default, the diff control lines (those with *** or ---) are
1231 created with a trailing newline. This is helpful so that inputs
1232 created from file.readlines() result in diffs that are suitable for
1233 file.writelines() since both the inputs and outputs have trailing
1234 newlines.
1235
1236 For inputs that do not have trailing newlines, set the lineterm
1237 argument to "" so that the output will be uniformly newline free.
1238
1239 The context diff format normally has a header for filenames and
1240 modification times. Any or all of these may be specified using
1241 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001242 The modification times are normally expressed in the ISO 8601 format.
1243 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001244
1245 Example:
1246
Ezio Melottid8b509b2011-09-28 17:37:55 +03001247 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
1248 ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001249 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001250 *** Original
1251 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001252 ***************
1253 *** 1,4 ****
1254 one
1255 ! two
1256 ! three
1257 four
1258 --- 1,4 ----
1259 + zero
1260 one
1261 ! tree
1262 four
1263 """
1264
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001265 prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001266 started = False
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001267 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1268 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001269 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001270 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1271 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1272 yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
1273 yield '--- {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001274
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001275 first, last = group[0], group[-1]
Raymond Hettinger49353d02011-04-11 12:40:58 -07001276 yield '***************' + lineterm
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001277
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001278 file1_range = _format_range_context(first[1], last[2])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001279 yield '*** {} ****{}'.format(file1_range, lineterm)
1280
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001281 if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001282 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001283 if tag != 'insert':
1284 for line in a[i1:i2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001285 yield prefix[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001286
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001287 file2_range = _format_range_context(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001288 yield '--- {} ----{}'.format(file2_range, lineterm)
1289
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001290 if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001291 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001292 if tag != 'delete':
1293 for line in b[j1:j2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001294 yield prefix[tag] + line
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001295
Tim Peters81b92512002-04-29 01:37:32 +00001296def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001297 r"""
1298 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1299
1300 Optional keyword parameters `linejunk` and `charjunk` are for filter
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001301 functions, or can be None:
Tim Peters5e824c32001-08-12 22:25:01 +00001302
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001303 - linejunk: A function that should accept a single string argument and
Tim Peters81b92512002-04-29 01:37:32 +00001304 return true iff the string is junk. The default is None, and is
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001305 recommended; the underlying SequenceMatcher class has an adaptive
1306 notion of "noise" lines.
Tim Peters5e824c32001-08-12 22:25:01 +00001307
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001308 - charjunk: A function that accepts a character (string of length
1309 1), and returns true iff the character is junk. The default is
1310 the module-level function IS_CHARACTER_JUNK, which filters out
1311 whitespace characters (a blank or tab; note: it's a bad idea to
1312 include newline in this!).
Tim Peters5e824c32001-08-12 22:25:01 +00001313
1314 Tools/scripts/ndiff.py is a command-line front-end to this function.
1315
1316 Example:
1317
Ezio Melottid8b509b2011-09-28 17:37:55 +03001318 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
1319 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001320 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001321 - one
1322 ? ^
1323 + ore
1324 ? ^
1325 - two
1326 - three
1327 ? -
1328 + tree
1329 + emu
1330 """
1331 return Differ(linejunk, charjunk).compare(a, b)
1332
Martin v. Löwise064b412004-08-29 16:34:40 +00001333def _mdiff(fromlines, tolines, context=None, linejunk=None,
1334 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001335 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001336
1337 Arguments:
1338 fromlines -- list of text lines to compared to tolines
1339 tolines -- list of text lines to be compared to fromlines
1340 context -- number of context lines to display on each side of difference,
1341 if None, all from/to text lines will be generated.
1342 linejunk -- passed on to ndiff (see ndiff documentation)
1343 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001344
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001345 This function returns an iterator which returns a tuple:
Martin v. Löwise064b412004-08-29 16:34:40 +00001346 (from line tuple, to line tuple, boolean flag)
1347
1348 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001349 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001350 line text -- original line text with following markers inserted:
1351 '\0+' -- marks start of added text
1352 '\0-' -- marks start of deleted text
1353 '\0^' -- marks start of changed text
1354 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001355
Martin v. Löwise064b412004-08-29 16:34:40 +00001356 boolean flag -- None indicates context separation, True indicates
1357 either "from" or "to" line contains a change, otherwise False.
1358
1359 This function/iterator was originally developed to generate side by side
1360 file difference for making HTML pages (see HtmlDiff class for example
1361 usage).
1362
1363 Note, this function utilizes the ndiff function to generate the side by
1364 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001365 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001366 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001367 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001368
1369 # regular expression for finding intraline change indices
1370 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001371
Martin v. Löwise064b412004-08-29 16:34:40 +00001372 # create the difference iterator to generate the differences
1373 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1374
1375 def _make_line(lines, format_key, side, num_lines=[0,0]):
1376 """Returns line of text with user's change markup and line formatting.
1377
1378 lines -- list of lines from the ndiff generator to produce a line of
1379 text from. When producing the line of text to return, the
1380 lines used are removed from this list.
1381 format_key -- '+' return first line in list with "add" markup around
1382 the entire line.
1383 '-' return first line in list with "delete" markup around
1384 the entire line.
1385 '?' return first line in list with add/delete/change
1386 intraline markup (indices obtained from second line)
1387 None return first line in list with no markup
1388 side -- indice into the num_lines list (0=from,1=to)
1389 num_lines -- from/to current line number. This is NOT intended to be a
1390 passed parameter. It is present as a keyword argument to
1391 maintain memory of the current line numbers between calls
1392 of this function.
1393
1394 Note, this function is purposefully not defined at the module scope so
1395 that data it needs from its parent function (within whose context it
1396 is defined) does not need to be of module scope.
1397 """
1398 num_lines[side] += 1
1399 # Handle case where no user markup is to be added, just return line of
1400 # text with user's line format to allow for usage of the line number.
1401 if format_key is None:
1402 return (num_lines[side],lines.pop(0)[2:])
1403 # Handle case of intraline changes
1404 if format_key == '?':
1405 text, markers = lines.pop(0), lines.pop(0)
1406 # find intraline changes (store change type and indices in tuples)
1407 sub_info = []
1408 def record_sub_info(match_object,sub_info=sub_info):
1409 sub_info.append([match_object.group(1)[0],match_object.span()])
1410 return match_object.group(1)
1411 change_re.sub(record_sub_info,markers)
1412 # process each tuple inserting our special marks that won't be
1413 # noticed by an xml/html escaper.
1414 for key,(begin,end) in sub_info[::-1]:
1415 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1416 text = text[2:]
1417 # Handle case of add/delete entire line
1418 else:
1419 text = lines.pop(0)[2:]
1420 # if line of text is just a newline, insert a space so there is
1421 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001422 if not text:
1423 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001424 # insert marks that won't be noticed by an xml/html escaper.
1425 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001426 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001427 # thing (such as adding the line number) then replace the special
1428 # marks with what the user's change markup.
1429 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001430
Martin v. Löwise064b412004-08-29 16:34:40 +00001431 def _line_iterator():
1432 """Yields from/to lines of text with a change indication.
1433
1434 This function is an iterator. It itself pulls lines from a
1435 differencing iterator, processes them and yields them. When it can
1436 it yields both a "from" and a "to" line, otherwise it will yield one
1437 or the other. In addition to yielding the lines of from/to text, a
1438 boolean flag is yielded to indicate if the text line(s) have
1439 differences in them.
1440
1441 Note, this function is purposefully not defined at the module scope so
1442 that data it needs from its parent function (within whose context it
1443 is defined) does not need to be of module scope.
1444 """
1445 lines = []
1446 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001447 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001448 # Load up next 4 lines so we can look ahead, create strings which
1449 # are a concatenation of the first character of each of the 4 lines
1450 # so we can do some very readable comparisons.
1451 while len(lines) < 4:
1452 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001453 lines.append(next(diff_lines_iterator))
Martin v. Löwise064b412004-08-29 16:34:40 +00001454 except StopIteration:
1455 lines.append('X')
1456 s = ''.join([line[0] for line in lines])
1457 if s.startswith('X'):
1458 # When no more lines, pump out any remaining blank lines so the
1459 # corresponding add/delete lines get a matching blank line so
1460 # all line pairs get yielded at the next level.
1461 num_blanks_to_yield = num_blanks_pending
1462 elif s.startswith('-?+?'):
1463 # simple intraline change
1464 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1465 continue
1466 elif s.startswith('--++'):
1467 # in delete block, add block coming: we do NOT want to get
1468 # caught up on blank lines yet, just process the delete line
1469 num_blanks_pending -= 1
1470 yield _make_line(lines,'-',0), None, True
1471 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001472 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001473 # in delete block and see a intraline change or unchanged line
1474 # coming: yield the delete line and then blanks
1475 from_line,to_line = _make_line(lines,'-',0), None
1476 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1477 elif s.startswith('-+?'):
1478 # intraline change
1479 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1480 continue
1481 elif s.startswith('-?+'):
1482 # intraline change
1483 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1484 continue
1485 elif s.startswith('-'):
1486 # delete FROM line
1487 num_blanks_pending -= 1
1488 yield _make_line(lines,'-',0), None, True
1489 continue
1490 elif s.startswith('+--'):
1491 # in add block, delete block coming: we do NOT want to get
1492 # caught up on blank lines yet, just process the add line
1493 num_blanks_pending += 1
1494 yield None, _make_line(lines,'+',1), True
1495 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001496 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001497 # will be leaving an add block: yield blanks then add line
1498 from_line, to_line = None, _make_line(lines,'+',1)
1499 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1500 elif s.startswith('+'):
1501 # inside an add block, yield the add line
1502 num_blanks_pending += 1
1503 yield None, _make_line(lines,'+',1), True
1504 continue
1505 elif s.startswith(' '):
1506 # unchanged text, yield it to both sides
1507 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1508 continue
1509 # Catch up on the blank lines so when we yield the next from/to
1510 # pair, they are lined up.
1511 while(num_blanks_to_yield < 0):
1512 num_blanks_to_yield += 1
1513 yield None,('','\n'),True
1514 while(num_blanks_to_yield > 0):
1515 num_blanks_to_yield -= 1
1516 yield ('','\n'),None,True
1517 if s.startswith('X'):
1518 raise StopIteration
1519 else:
1520 yield from_line,to_line,True
1521
1522 def _line_pair_iterator():
1523 """Yields from/to lines of text with a change indication.
1524
1525 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001526 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001527 always yields a pair of from/to text lines (with the change
1528 indication). If necessary it will collect single from/to lines
1529 until it has a matching pair from/to pair to yield.
1530
1531 Note, this function is purposefully not defined at the module scope so
1532 that data it needs from its parent function (within whose context it
1533 is defined) does not need to be of module scope.
1534 """
1535 line_iterator = _line_iterator()
1536 fromlines,tolines=[],[]
1537 while True:
1538 # Collecting lines of text until we have a from/to pair
1539 while (len(fromlines)==0 or len(tolines)==0):
Georg Brandla18af4e2007-04-21 15:47:16 +00001540 from_line, to_line, found_diff = next(line_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001541 if from_line is not None:
1542 fromlines.append((from_line,found_diff))
1543 if to_line is not None:
1544 tolines.append((to_line,found_diff))
1545 # Once we have a pair, remove them from the collection and yield it
1546 from_line, fromDiff = fromlines.pop(0)
1547 to_line, to_diff = tolines.pop(0)
1548 yield (from_line,to_line,fromDiff or to_diff)
1549
1550 # Handle case where user does not want context differencing, just yield
1551 # them up without doing anything else with them.
1552 line_pair_iterator = _line_pair_iterator()
1553 if context is None:
1554 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +00001555 yield next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001556 # Handle case where user wants context differencing. We must do some
1557 # storage of lines until we know for sure that they are to be yielded.
1558 else:
1559 context += 1
1560 lines_to_write = 0
1561 while True:
1562 # Store lines up until we find a difference, note use of a
1563 # circular queue because we only need to keep around what
1564 # we need for context.
1565 index, contextLines = 0, [None]*(context)
1566 found_diff = False
1567 while(found_diff is False):
Georg Brandla18af4e2007-04-21 15:47:16 +00001568 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001569 i = index % context
1570 contextLines[i] = (from_line, to_line, found_diff)
1571 index += 1
1572 # Yield lines that we have collected so far, but first yield
1573 # the user's separator.
1574 if index > context:
1575 yield None, None, None
1576 lines_to_write = context
1577 else:
1578 lines_to_write = index
1579 index = 0
1580 while(lines_to_write):
1581 i = index % context
1582 index += 1
1583 yield contextLines[i]
1584 lines_to_write -= 1
1585 # Now yield the context lines after the change
1586 lines_to_write = context-1
1587 while(lines_to_write):
Georg Brandla18af4e2007-04-21 15:47:16 +00001588 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001589 # If another change within the context, extend the context
1590 if found_diff:
1591 lines_to_write = context-1
1592 else:
1593 lines_to_write -= 1
1594 yield from_line, to_line, found_diff
1595
1596
1597_file_template = """
1598<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1599 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1600
1601<html>
1602
1603<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001604 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001605 content="text/html; charset=ISO-8859-1" />
1606 <title></title>
1607 <style type="text/css">%(styles)s
1608 </style>
1609</head>
1610
1611<body>
1612 %(table)s%(legend)s
1613</body>
1614
1615</html>"""
1616
1617_styles = """
1618 table.diff {font-family:Courier; border:medium;}
1619 .diff_header {background-color:#e0e0e0}
1620 td.diff_header {text-align:right}
1621 .diff_next {background-color:#c0c0c0}
1622 .diff_add {background-color:#aaffaa}
1623 .diff_chg {background-color:#ffff77}
1624 .diff_sub {background-color:#ffaaaa}"""
1625
1626_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001627 <table class="diff" id="difflib_chg_%(prefix)s_top"
1628 cellspacing="0" cellpadding="0" rules="groups" >
1629 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001630 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1631 %(header_row)s
1632 <tbody>
1633%(data_rows)s </tbody>
1634 </table>"""
1635
1636_legend = """
1637 <table class="diff" summary="Legends">
1638 <tr> <th colspan="2"> Legends </th> </tr>
1639 <tr> <td> <table border="" summary="Colors">
1640 <tr><th> Colors </th> </tr>
1641 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1642 <tr><td class="diff_chg">Changed</td> </tr>
1643 <tr><td class="diff_sub">Deleted</td> </tr>
1644 </table></td>
1645 <td> <table border="" summary="Links">
1646 <tr><th colspan="2"> Links </th> </tr>
1647 <tr><td>(f)irst change</td> </tr>
1648 <tr><td>(n)ext change</td> </tr>
1649 <tr><td>(t)op</td> </tr>
1650 </table></td> </tr>
1651 </table>"""
1652
1653class HtmlDiff(object):
1654 """For producing HTML side by side comparison with change highlights.
1655
1656 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001657 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001658 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001659 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001660
Martin v. Löwise064b412004-08-29 16:34:40 +00001661 The following methods are provided for HTML generation:
1662
1663 make_table -- generates HTML for a single side by side table
1664 make_file -- generates complete HTML file with a single side by side table
1665
Tim Peters48bd7f32004-08-29 22:38:38 +00001666 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001667 """
1668
1669 _file_template = _file_template
1670 _styles = _styles
1671 _table_template = _table_template
1672 _legend = _legend
1673 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001674
Martin v. Löwise064b412004-08-29 16:34:40 +00001675 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1676 charjunk=IS_CHARACTER_JUNK):
1677 """HtmlDiff instance initializer
1678
1679 Arguments:
1680 tabsize -- tab stop spacing, defaults to 8.
1681 wrapcolumn -- column number where lines are broken and wrapped,
1682 defaults to None where lines are not wrapped.
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001683 linejunk,charjunk -- keyword arguments passed into ndiff() (used by
Tim Peters48bd7f32004-08-29 22:38:38 +00001684 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001685 ndiff() documentation for argument default values and descriptions.
1686 """
1687 self._tabsize = tabsize
1688 self._wrapcolumn = wrapcolumn
1689 self._linejunk = linejunk
1690 self._charjunk = charjunk
1691
1692 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1693 numlines=5):
1694 """Returns HTML file of side by side comparison with change highlights
1695
1696 Arguments:
1697 fromlines -- list of "from" lines
1698 tolines -- list of "to" lines
1699 fromdesc -- "from" file column header string
1700 todesc -- "to" file column header string
1701 context -- set to True for contextual differences (defaults to False
1702 which shows full differences).
1703 numlines -- number of context lines. When context is set True,
1704 controls number of lines displayed before and after the change.
1705 When context is False, controls the number of lines to place
1706 the "next" link anchors before the next change (so click of
1707 "next" link jumps to just before the change).
1708 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001709
Martin v. Löwise064b412004-08-29 16:34:40 +00001710 return self._file_template % dict(
1711 styles = self._styles,
1712 legend = self._legend,
1713 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1714 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001715
Martin v. Löwise064b412004-08-29 16:34:40 +00001716 def _tab_newline_replace(self,fromlines,tolines):
1717 """Returns from/to line lists with tabs expanded and newlines removed.
1718
1719 Instead of tab characters being replaced by the number of spaces
1720 needed to fill in to the next tab stop, this function will fill
1721 the space with tab characters. This is done so that the difference
1722 algorithms can identify changes in a file when tabs are replaced by
1723 spaces and vice versa. At the end of the HTML generation, the tab
1724 characters will be replaced with a nonbreakable space.
1725 """
1726 def expand_tabs(line):
1727 # hide real spaces
1728 line = line.replace(' ','\0')
1729 # expand tabs into spaces
1730 line = line.expandtabs(self._tabsize)
Ezio Melotti13925002011-03-16 11:05:33 +02001731 # replace spaces from expanded tabs back into tab characters
Martin v. Löwise064b412004-08-29 16:34:40 +00001732 # (we'll replace them with markup after we do differencing)
1733 line = line.replace(' ','\t')
1734 return line.replace('\0',' ').rstrip('\n')
1735 fromlines = [expand_tabs(line) for line in fromlines]
1736 tolines = [expand_tabs(line) for line in tolines]
1737 return fromlines,tolines
1738
1739 def _split_line(self,data_list,line_num,text):
1740 """Builds list of text lines by splitting text lines at wrap point
1741
1742 This function will determine if the input text line needs to be
1743 wrapped (split) into separate lines. If so, the first wrap point
1744 will be determined and the first line appended to the output
1745 text line list. This function is used recursively to handle
1746 the second part of the split line to further split it.
1747 """
1748 # if blank line or context separator, just add it to the output list
1749 if not line_num:
1750 data_list.append((line_num,text))
1751 return
1752
1753 # if line text doesn't need wrapping, just add it to the output list
1754 size = len(text)
1755 max = self._wrapcolumn
1756 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1757 data_list.append((line_num,text))
1758 return
1759
1760 # scan text looking for the wrap point, keeping track if the wrap
1761 # point is inside markers
1762 i = 0
1763 n = 0
1764 mark = ''
1765 while n < max and i < size:
1766 if text[i] == '\0':
1767 i += 1
1768 mark = text[i]
1769 i += 1
1770 elif text[i] == '\1':
1771 i += 1
1772 mark = ''
1773 else:
1774 i += 1
1775 n += 1
1776
1777 # wrap point is inside text, break it up into separate lines
1778 line1 = text[:i]
1779 line2 = text[i:]
1780
1781 # if wrap point is inside markers, place end marker at end of first
1782 # line and start marker at beginning of second line because each
1783 # line will have its own table tag markup around it.
1784 if mark:
1785 line1 = line1 + '\1'
1786 line2 = '\0' + mark + line2
1787
Tim Peters48bd7f32004-08-29 22:38:38 +00001788 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001789 data_list.append((line_num,line1))
1790
Tim Peters48bd7f32004-08-29 22:38:38 +00001791 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001792 self._split_line(data_list,'>',line2)
1793
1794 def _line_wrapper(self,diffs):
1795 """Returns iterator that splits (wraps) mdiff text lines"""
1796
1797 # pull from/to data and flags from mdiff iterator
1798 for fromdata,todata,flag in diffs:
1799 # check for context separators and pass them through
1800 if flag is None:
1801 yield fromdata,todata,flag
1802 continue
1803 (fromline,fromtext),(toline,totext) = fromdata,todata
1804 # for each from/to line split it at the wrap column to form
1805 # list of text lines.
1806 fromlist,tolist = [],[]
1807 self._split_line(fromlist,fromline,fromtext)
1808 self._split_line(tolist,toline,totext)
1809 # yield from/to line in pairs inserting blank lines as
1810 # necessary when one side has more wrapped lines
1811 while fromlist or tolist:
1812 if fromlist:
1813 fromdata = fromlist.pop(0)
1814 else:
1815 fromdata = ('',' ')
1816 if tolist:
1817 todata = tolist.pop(0)
1818 else:
1819 todata = ('',' ')
1820 yield fromdata,todata,flag
1821
1822 def _collect_lines(self,diffs):
1823 """Collects mdiff output into separate lists
1824
1825 Before storing the mdiff from/to data into a list, it is converted
1826 into a single line of text with HTML markup.
1827 """
1828
1829 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001830 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001831 for fromdata,todata,flag in diffs:
1832 try:
1833 # store HTML markup of the lines into the lists
1834 fromlist.append(self._format_line(0,flag,*fromdata))
1835 tolist.append(self._format_line(1,flag,*todata))
1836 except TypeError:
1837 # exceptions occur for lines where context separators go
1838 fromlist.append(None)
1839 tolist.append(None)
1840 flaglist.append(flag)
1841 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001842
Martin v. Löwise064b412004-08-29 16:34:40 +00001843 def _format_line(self,side,flag,linenum,text):
1844 """Returns HTML markup of "from" / "to" text lines
1845
1846 side -- 0 or 1 indicating "from" or "to" text
1847 flag -- indicates if difference on line
1848 linenum -- line number (used for line number column)
1849 text -- line text to be marked up
1850 """
1851 try:
1852 linenum = '%d' % linenum
1853 id = ' id="%s%s"' % (self._prefix[side],linenum)
1854 except TypeError:
1855 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001856 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001857 # replace those things that would get confused with HTML symbols
1858 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1859
1860 # make space non-breakable so they don't get compressed or line wrapped
1861 text = text.replace(' ','&nbsp;').rstrip()
1862
1863 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1864 % (id,linenum,text)
1865
1866 def _make_prefix(self):
1867 """Create unique anchor prefixes"""
1868
1869 # Generate a unique anchor prefix so multiple tables
1870 # can exist on the same HTML page without conflicts.
1871 fromprefix = "from%d_" % HtmlDiff._default_prefix
1872 toprefix = "to%d_" % HtmlDiff._default_prefix
1873 HtmlDiff._default_prefix += 1
1874 # store prefixes so line format method has access
1875 self._prefix = [fromprefix,toprefix]
1876
1877 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1878 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001879
Martin v. Löwise064b412004-08-29 16:34:40 +00001880 # all anchor names will be generated using the unique "to" prefix
1881 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001882
Martin v. Löwise064b412004-08-29 16:34:40 +00001883 # process change flags, generating middle column of next anchors/links
1884 next_id = ['']*len(flaglist)
1885 next_href = ['']*len(flaglist)
1886 num_chg, in_change = 0, False
1887 last = 0
1888 for i,flag in enumerate(flaglist):
1889 if flag:
1890 if not in_change:
1891 in_change = True
1892 last = i
1893 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001894 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001895 # link
1896 i = max([0,i-numlines])
1897 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001898 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001899 # change
1900 num_chg += 1
1901 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1902 toprefix,num_chg)
1903 else:
1904 in_change = False
1905 # check for cases where there is no content to avoid exceptions
1906 if not flaglist:
1907 flaglist = [False]
1908 next_id = ['']
1909 next_href = ['']
1910 last = 0
1911 if context:
1912 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1913 tolist = fromlist
1914 else:
1915 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1916 # if not a change on first line, drop a link
1917 if not flaglist[0]:
1918 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1919 # redo the last link to link to the top
1920 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1921
1922 return fromlist,tolist,flaglist,next_href,next_id
1923
1924 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1925 numlines=5):
1926 """Returns HTML table of side by side comparison with change highlights
1927
1928 Arguments:
1929 fromlines -- list of "from" lines
1930 tolines -- list of "to" lines
1931 fromdesc -- "from" file column header string
1932 todesc -- "to" file column header string
1933 context -- set to True for contextual differences (defaults to False
1934 which shows full differences).
1935 numlines -- number of context lines. When context is set True,
1936 controls number of lines displayed before and after the change.
1937 When context is False, controls the number of lines to place
1938 the "next" link anchors before the next change (so click of
1939 "next" link jumps to just before the change).
1940 """
1941
1942 # make unique anchor prefixes so that multiple tables may exist
1943 # on the same page without conflict.
1944 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001945
Martin v. Löwise064b412004-08-29 16:34:40 +00001946 # change tabs to spaces before it gets more difficult after we insert
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001947 # markup
Martin v. Löwise064b412004-08-29 16:34:40 +00001948 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001949
Martin v. Löwise064b412004-08-29 16:34:40 +00001950 # create diffs iterator which generates side by side from/to data
1951 if context:
1952 context_lines = numlines
1953 else:
1954 context_lines = None
1955 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1956 charjunk=self._charjunk)
1957
1958 # set up iterator to wrap lines that exceed desired width
1959 if self._wrapcolumn:
1960 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001961
Martin v. Löwise064b412004-08-29 16:34:40 +00001962 # collect up from/to lines and flags into lists (also format the lines)
1963 fromlist,tolist,flaglist = self._collect_lines(diffs)
1964
1965 # process change flags, generating middle column of next anchors/links
1966 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1967 fromlist,tolist,flaglist,context,numlines)
1968
Guido van Rossumd8faa362007-04-27 19:54:29 +00001969 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00001970 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1971 '<td class="diff_next">%s</td>%s</tr>\n'
1972 for i in range(len(flaglist)):
1973 if flaglist[i] is None:
1974 # mdiff yields None on separator lines skip the bogus ones
1975 # generated for the first line
1976 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001977 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00001978 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001979 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00001980 next_href[i],tolist[i]))
1981 if fromdesc or todesc:
1982 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
1983 '<th class="diff_next"><br /></th>',
1984 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
1985 '<th class="diff_next"><br /></th>',
1986 '<th colspan="2" class="diff_header">%s</th>' % todesc)
1987 else:
1988 header_row = ''
1989
1990 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00001991 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00001992 header_row=header_row,
1993 prefix=self._prefix[1])
1994
1995 return table.replace('\0+','<span class="diff_add">'). \
1996 replace('\0-','<span class="diff_sub">'). \
1997 replace('\0^','<span class="diff_chg">'). \
1998 replace('\1','</span>'). \
1999 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00002000
Martin v. Löwise064b412004-08-29 16:34:40 +00002001del re
2002
Tim Peters5e824c32001-08-12 22:25:01 +00002003def restore(delta, which):
2004 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00002005 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00002006
2007 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
2008 lines originating from file 1 or 2 (parameter `which`), stripping off line
2009 prefixes.
2010
2011 Examples:
2012
Ezio Melottid8b509b2011-09-28 17:37:55 +03002013 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
2014 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Tim Peters8a9c2842001-09-22 21:30:22 +00002015 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002016 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002017 one
2018 two
2019 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002020 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002021 ore
2022 tree
2023 emu
2024 """
2025 try:
2026 tag = {1: "- ", 2: "+ "}[int(which)]
2027 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002028 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Tim Peters5e824c32001-08-12 22:25:01 +00002029 % which)
2030 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002031 for line in delta:
2032 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002033 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002034
Tim Peters9ae21482001-02-10 08:00:53 +00002035def _test():
2036 import doctest, difflib
2037 return doctest.testmod(difflib)
2038
2039if __name__ == "__main__":
2040 _test()