blob: 809774489fb44c7eedc1b37b8d56bae396490d59 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Tim Peters9ae21482001-02-10 08:00:53 +00002
3"""
4Module difflib -- helpers for computing deltas between objects.
5
6Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
Tim Peters9ae21482001-02-10 08:00:53 +00007 Use SequenceMatcher to return list of the best "good enough" matches.
8
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00009Function context_diff(a, b):
10 For two lists of strings, return a delta in context diff format.
11
Tim Peters5e824c32001-08-12 22:25:01 +000012Function ndiff(a, b):
13 Return a delta: the difference between `a` and `b` (lists of strings).
Tim Peters9ae21482001-02-10 08:00:53 +000014
Tim Peters5e824c32001-08-12 22:25:01 +000015Function restore(delta, which):
16 Return one of the two sequences that generated an ndiff delta.
Tim Peters9ae21482001-02-10 08:00:53 +000017
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000018Function unified_diff(a, b):
19 For two lists of strings, return a delta in unified diff format.
20
Tim Peters5e824c32001-08-12 22:25:01 +000021Class SequenceMatcher:
22 A flexible class for comparing pairs of sequences of any type.
Tim Peters9ae21482001-02-10 08:00:53 +000023
Tim Peters5e824c32001-08-12 22:25:01 +000024Class Differ:
25 For producing human-readable deltas from sequences of lines of text.
Martin v. Löwise064b412004-08-29 16:34:40 +000026
27Class HtmlDiff:
28 For producing HTML side by side comparison with change highlights.
Tim Peters9ae21482001-02-10 08:00:53 +000029"""
30
Tim Peters5e824c32001-08-12 22:25:01 +000031__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000032 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
Christian Heimes25bb7832008-01-11 16:17:00 +000033 'unified_diff', 'HtmlDiff', 'Match']
Tim Peters5e824c32001-08-12 22:25:01 +000034
Terry Reedybcd89882010-12-03 22:29:40 +000035import warnings
Raymond Hettingerbb6b7342004-06-13 09:57:33 +000036import heapq
Christian Heimes25bb7832008-01-11 16:17:00 +000037from collections import namedtuple as _namedtuple
38
39Match = _namedtuple('Match', 'a b size')
Raymond Hettingerbb6b7342004-06-13 09:57:33 +000040
Neal Norwitze7dfe212003-07-01 14:59:46 +000041def _calculate_ratio(matches, length):
42 if length:
43 return 2.0 * matches / length
44 return 1.0
45
Tim Peters9ae21482001-02-10 08:00:53 +000046class SequenceMatcher:
Tim Peters5e824c32001-08-12 22:25:01 +000047
48 """
49 SequenceMatcher is a flexible class for comparing pairs of sequences of
50 any type, so long as the sequence elements are hashable. The basic
51 algorithm predates, and is a little fancier than, an algorithm
52 published in the late 1980's by Ratcliff and Obershelp under the
53 hyperbolic name "gestalt pattern matching". The basic idea is to find
54 the longest contiguous matching subsequence that contains no "junk"
55 elements (R-O doesn't address junk). The same idea is then applied
56 recursively to the pieces of the sequences to the left and to the right
57 of the matching subsequence. This does not yield minimal edit
58 sequences, but does tend to yield matches that "look right" to people.
59
60 SequenceMatcher tries to compute a "human-friendly diff" between two
61 sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
62 longest *contiguous* & junk-free matching subsequence. That's what
63 catches peoples' eyes. The Windows(tm) windiff has another interesting
64 notion, pairing up elements that appear uniquely in each sequence.
65 That, and the method here, appear to yield more intuitive difference
66 reports than does diff. This method appears to be the least vulnerable
67 to synching up on blocks of "junk lines", though (like blank lines in
68 ordinary text files, or maybe "<P>" lines in HTML files). That may be
69 because this is the only method of the 3 that has a *concept* of
70 "junk" <wink>.
71
72 Example, comparing two strings, and considering blanks to be "junk":
73
74 >>> s = SequenceMatcher(lambda x: x == " ",
75 ... "private Thread currentThread;",
76 ... "private volatile Thread currentThread;")
77 >>>
78
79 .ratio() returns a float in [0, 1], measuring the "similarity" of the
80 sequences. As a rule of thumb, a .ratio() value over 0.6 means the
81 sequences are close matches:
82
Guido van Rossumfff80df2007-02-09 20:33:44 +000083 >>> print(round(s.ratio(), 3))
Tim Peters5e824c32001-08-12 22:25:01 +000084 0.866
85 >>>
86
87 If you're only interested in where the sequences match,
88 .get_matching_blocks() is handy:
89
90 >>> for block in s.get_matching_blocks():
Guido van Rossumfff80df2007-02-09 20:33:44 +000091 ... print("a[%d] and b[%d] match for %d elements" % block)
Tim Peters5e824c32001-08-12 22:25:01 +000092 a[0] and b[0] match for 8 elements
Thomas Wouters0e3f5912006-08-11 14:57:12 +000093 a[8] and b[17] match for 21 elements
Tim Peters5e824c32001-08-12 22:25:01 +000094 a[29] and b[38] match for 0 elements
95
96 Note that the last tuple returned by .get_matching_blocks() is always a
97 dummy, (len(a), len(b), 0), and this is the only case in which the last
98 tuple element (number of elements matched) is 0.
99
100 If you want to know how to change the first sequence into the second,
101 use .get_opcodes():
102
103 >>> for opcode in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000104 ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
Tim Peters5e824c32001-08-12 22:25:01 +0000105 equal a[0:8] b[0:8]
106 insert a[8:8] b[8:17]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107 equal a[8:29] b[17:38]
Tim Peters5e824c32001-08-12 22:25:01 +0000108
109 See the Differ class for a fancy human-friendly file differencer, which
110 uses SequenceMatcher both to compare sequences of lines, and to compare
111 sequences of characters within similar (near-matching) lines.
112
113 See also function get_close_matches() in this module, which shows how
114 simple code building on SequenceMatcher can be used to do useful work.
115
116 Timing: Basic R-O is cubic time worst case and quadratic time expected
117 case. SequenceMatcher is quadratic time for the worst case and has
118 expected-case behavior dependent in a complicated way on how many
119 elements the sequences have in common; best case time is linear.
120
121 Methods:
122
123 __init__(isjunk=None, a='', b='')
124 Construct a SequenceMatcher.
125
126 set_seqs(a, b)
127 Set the two sequences to be compared.
128
129 set_seq1(a)
130 Set the first sequence to be compared.
131
132 set_seq2(b)
133 Set the second sequence to be compared.
134
135 find_longest_match(alo, ahi, blo, bhi)
136 Find longest matching block in a[alo:ahi] and b[blo:bhi].
137
138 get_matching_blocks()
139 Return list of triples describing matching subsequences.
140
141 get_opcodes()
142 Return list of 5-tuples describing how to turn a into b.
143
144 ratio()
145 Return a measure of the sequences' similarity (float in [0,1]).
146
147 quick_ratio()
148 Return an upper bound on .ratio() relatively quickly.
149
150 real_quick_ratio()
151 Return an upper bound on ratio() very quickly.
152 """
153
Terry Reedy99f96372010-11-25 06:12:34 +0000154 def __init__(self, isjunk=None, a='', b='', autojunk=True):
Tim Peters9ae21482001-02-10 08:00:53 +0000155 """Construct a SequenceMatcher.
156
157 Optional arg isjunk is None (the default), or a one-argument
158 function that takes a sequence element and returns true iff the
Tim Peters5e824c32001-08-12 22:25:01 +0000159 element is junk. None is equivalent to passing "lambda x: 0", i.e.
Fred Drakef1da6282001-02-19 19:30:05 +0000160 no elements are considered to be junk. For example, pass
Tim Peters9ae21482001-02-10 08:00:53 +0000161 lambda x: x in " \\t"
162 if you're comparing lines as sequences of characters, and don't
163 want to synch up on blanks or hard tabs.
164
165 Optional arg a is the first of two sequences to be compared. By
166 default, an empty string. The elements of a must be hashable. See
167 also .set_seqs() and .set_seq1().
168
169 Optional arg b is the second of two sequences to be compared. By
Fred Drakef1da6282001-02-19 19:30:05 +0000170 default, an empty string. The elements of b must be hashable. See
Tim Peters9ae21482001-02-10 08:00:53 +0000171 also .set_seqs() and .set_seq2().
Terry Reedy99f96372010-11-25 06:12:34 +0000172
173 Optional arg autojunk should be set to False to disable the
174 "automatic junk heuristic" that treats popular elements as junk
175 (see module documentation for more information).
Tim Peters9ae21482001-02-10 08:00:53 +0000176 """
177
178 # Members:
179 # a
180 # first sequence
181 # b
182 # second sequence; differences are computed as "what do
183 # we need to do to 'a' to change it into 'b'?"
184 # b2j
185 # for x in b, b2j[x] is a list of the indices (into b)
Terry Reedybcd89882010-12-03 22:29:40 +0000186 # at which x appears; junk and popular elements do not appear
Tim Peters9ae21482001-02-10 08:00:53 +0000187 # fullbcount
188 # for x in b, fullbcount[x] == the number of times x
189 # appears in b; only materialized if really needed (used
190 # only for computing quick_ratio())
191 # matching_blocks
192 # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
193 # ascending & non-overlapping in i and in j; terminated by
194 # a dummy (len(a), len(b), 0) sentinel
195 # opcodes
196 # a list of (tag, i1, i2, j1, j2) tuples, where tag is
197 # one of
198 # 'replace' a[i1:i2] should be replaced by b[j1:j2]
199 # 'delete' a[i1:i2] should be deleted
200 # 'insert' b[j1:j2] should be inserted
201 # 'equal' a[i1:i2] == b[j1:j2]
202 # isjunk
203 # a user-supplied function taking a sequence element and
204 # returning true iff the element is "junk" -- this has
205 # subtle but helpful effects on the algorithm, which I'll
206 # get around to writing up someday <0.9 wink>.
Florent Xicluna7f1c15b2011-12-10 13:02:17 +0100207 # DON'T USE! Only __chain_b uses this. Use "in self.bjunk".
Terry Reedy74a7c672010-12-03 18:57:42 +0000208 # bjunk
209 # the items in b for which isjunk is True.
210 # bpopular
211 # nonjunk items in b treated as junk by the heuristic (if used).
Tim Peters9ae21482001-02-10 08:00:53 +0000212
213 self.isjunk = isjunk
214 self.a = self.b = None
Terry Reedy99f96372010-11-25 06:12:34 +0000215 self.autojunk = autojunk
Tim Peters9ae21482001-02-10 08:00:53 +0000216 self.set_seqs(a, b)
217
218 def set_seqs(self, a, b):
219 """Set the two sequences to be compared.
220
221 >>> s = SequenceMatcher()
222 >>> s.set_seqs("abcd", "bcde")
223 >>> s.ratio()
224 0.75
225 """
226
227 self.set_seq1(a)
228 self.set_seq2(b)
229
230 def set_seq1(self, a):
231 """Set the first sequence to be compared.
232
233 The second sequence to be compared is not changed.
234
235 >>> s = SequenceMatcher(None, "abcd", "bcde")
236 >>> s.ratio()
237 0.75
238 >>> s.set_seq1("bcde")
239 >>> s.ratio()
240 1.0
241 >>>
242
243 SequenceMatcher computes and caches detailed information about the
244 second sequence, so if you want to compare one sequence S against
245 many sequences, use .set_seq2(S) once and call .set_seq1(x)
246 repeatedly for each of the other sequences.
247
248 See also set_seqs() and set_seq2().
249 """
250
251 if a is self.a:
252 return
253 self.a = a
254 self.matching_blocks = self.opcodes = None
255
256 def set_seq2(self, b):
257 """Set the second sequence to be compared.
258
259 The first sequence to be compared is not changed.
260
261 >>> s = SequenceMatcher(None, "abcd", "bcde")
262 >>> s.ratio()
263 0.75
264 >>> s.set_seq2("abcd")
265 >>> s.ratio()
266 1.0
267 >>>
268
269 SequenceMatcher computes and caches detailed information about the
270 second sequence, so if you want to compare one sequence S against
271 many sequences, use .set_seq2(S) once and call .set_seq1(x)
272 repeatedly for each of the other sequences.
273
274 See also set_seqs() and set_seq1().
275 """
276
277 if b is self.b:
278 return
279 self.b = b
280 self.matching_blocks = self.opcodes = None
281 self.fullbcount = None
282 self.__chain_b()
283
284 # For each element x in b, set b2j[x] to a list of the indices in
285 # b where x appears; the indices are in increasing order; note that
286 # the number of times x appears in b is len(b2j[x]) ...
287 # when self.isjunk is defined, junk elements don't show up in this
288 # map at all, which stops the central find_longest_match method
289 # from starting any matching block at a junk element ...
Tim Peters81b92512002-04-29 01:37:32 +0000290 # b2j also does not contain entries for "popular" elements, meaning
Terry Reedy99f96372010-11-25 06:12:34 +0000291 # elements that account for more than 1 + 1% of the total elements, and
Tim Peters81b92512002-04-29 01:37:32 +0000292 # when the sequence is reasonably large (>= 200 elements); this can
293 # be viewed as an adaptive notion of semi-junk, and yields an enormous
294 # speedup when, e.g., comparing program files with hundreds of
295 # instances of "return NULL;" ...
Tim Peters9ae21482001-02-10 08:00:53 +0000296 # note that this is only called when b changes; so for cross-product
297 # kinds of matches, it's best to call set_seq2 once, then set_seq1
298 # repeatedly
299
300 def __chain_b(self):
301 # Because isjunk is a user-defined (not C) function, and we test
302 # for junk a LOT, it's important to minimize the number of calls.
303 # Before the tricks described here, __chain_b was by far the most
304 # time-consuming routine in the whole module! If anyone sees
305 # Jim Roskind, thank him again for profile.py -- I never would
306 # have guessed that.
307 # The first trick is to build b2j ignoring the possibility
308 # of junk. I.e., we don't call isjunk at all yet. Throwing
309 # out the junk later is much cheaper than building b2j "right"
310 # from the start.
311 b = self.b
312 self.b2j = b2j = {}
Terry Reedy99f96372010-11-25 06:12:34 +0000313
Tim Peters81b92512002-04-29 01:37:32 +0000314 for i, elt in enumerate(b):
Terry Reedy99f96372010-11-25 06:12:34 +0000315 indices = b2j.setdefault(elt, [])
316 indices.append(i)
Tim Peters9ae21482001-02-10 08:00:53 +0000317
Terry Reedy99f96372010-11-25 06:12:34 +0000318 # Purge junk elements
Terry Reedy74a7c672010-12-03 18:57:42 +0000319 self.bjunk = junk = set()
Tim Peters81b92512002-04-29 01:37:32 +0000320 isjunk = self.isjunk
Tim Peters9ae21482001-02-10 08:00:53 +0000321 if isjunk:
Terry Reedy17a59252010-12-15 20:18:10 +0000322 for elt in b2j.keys():
Terry Reedy99f96372010-11-25 06:12:34 +0000323 if isjunk(elt):
324 junk.add(elt)
Terry Reedy17a59252010-12-15 20:18:10 +0000325 for elt in junk: # separate loop avoids separate list of keys
326 del b2j[elt]
Tim Peters9ae21482001-02-10 08:00:53 +0000327
Terry Reedy99f96372010-11-25 06:12:34 +0000328 # Purge popular elements that are not junk
Terry Reedy74a7c672010-12-03 18:57:42 +0000329 self.bpopular = popular = set()
Terry Reedy99f96372010-11-25 06:12:34 +0000330 n = len(b)
331 if self.autojunk and n >= 200:
332 ntest = n // 100 + 1
Terry Reedy17a59252010-12-15 20:18:10 +0000333 for elt, idxs in b2j.items():
Terry Reedy99f96372010-11-25 06:12:34 +0000334 if len(idxs) > ntest:
335 popular.add(elt)
Terry Reedy17a59252010-12-15 20:18:10 +0000336 for elt in popular: # ditto; as fast for 1% deletion
337 del b2j[elt]
Terry Reedy99f96372010-11-25 06:12:34 +0000338
Tim Peters9ae21482001-02-10 08:00:53 +0000339 def find_longest_match(self, alo, ahi, blo, bhi):
340 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
341
342 If isjunk is not defined:
343
344 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
345 alo <= i <= i+k <= ahi
346 blo <= j <= j+k <= bhi
347 and for all (i',j',k') meeting those conditions,
348 k >= k'
349 i <= i'
350 and if i == i', j <= j'
351
352 In other words, of all maximal matching blocks, return one that
353 starts earliest in a, and of all those maximal matching blocks that
354 start earliest in a, return the one that starts earliest in b.
355
356 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
357 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000358 Match(a=0, b=4, size=5)
Tim Peters9ae21482001-02-10 08:00:53 +0000359
360 If isjunk is defined, first the longest matching block is
361 determined as above, but with the additional restriction that no
362 junk element appears in the block. Then that block is extended as
363 far as possible by matching (only) junk elements on both sides. So
364 the resulting block never matches on junk except as identical junk
365 happens to be adjacent to an "interesting" match.
366
367 Here's the same example as before, but considering blanks to be
368 junk. That prevents " abcd" from matching the " abcd" at the tail
369 end of the second sequence directly. Instead only the "abcd" can
370 match, and matches the leftmost "abcd" in the second sequence:
371
372 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
373 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000374 Match(a=1, b=0, size=4)
Tim Peters9ae21482001-02-10 08:00:53 +0000375
376 If no blocks match, return (alo, blo, 0).
377
378 >>> s = SequenceMatcher(None, "ab", "c")
379 >>> s.find_longest_match(0, 2, 0, 1)
Christian Heimes25bb7832008-01-11 16:17:00 +0000380 Match(a=0, b=0, size=0)
Tim Peters9ae21482001-02-10 08:00:53 +0000381 """
382
383 # CAUTION: stripping common prefix or suffix would be incorrect.
384 # E.g.,
385 # ab
386 # acab
387 # Longest matching block is "ab", but if common prefix is
388 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
389 # strip, so ends up claiming that ab is changed to acab by
390 # inserting "ca" in the middle. That's minimal but unintuitive:
391 # "it's obvious" that someone inserted "ac" at the front.
392 # Windiff ends up at the same place as diff, but by pairing up
393 # the unique 'b's and then matching the first two 'a's.
394
Terry Reedybcd89882010-12-03 22:29:40 +0000395 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000396 besti, bestj, bestsize = alo, blo, 0
397 # find longest junk-free match
398 # during an iteration of the loop, j2len[j] = length of longest
399 # junk-free match ending with a[i-1] and b[j]
400 j2len = {}
401 nothing = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000402 for i in range(alo, ahi):
Tim Peters9ae21482001-02-10 08:00:53 +0000403 # look at all instances of a[i] in b; note that because
404 # b2j has no junk keys, the loop is skipped if a[i] is junk
405 j2lenget = j2len.get
406 newj2len = {}
407 for j in b2j.get(a[i], nothing):
408 # a[i] matches b[j]
409 if j < blo:
410 continue
411 if j >= bhi:
412 break
413 k = newj2len[j] = j2lenget(j-1, 0) + 1
414 if k > bestsize:
415 besti, bestj, bestsize = i-k+1, j-k+1, k
416 j2len = newj2len
417
Tim Peters81b92512002-04-29 01:37:32 +0000418 # Extend the best by non-junk elements on each end. In particular,
419 # "popular" non-junk elements aren't in b2j, which greatly speeds
420 # the inner loop above, but also means "the best" match so far
421 # doesn't contain any junk *or* popular non-junk elements.
422 while besti > alo and bestj > blo and \
423 not isbjunk(b[bestj-1]) and \
424 a[besti-1] == b[bestj-1]:
425 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
426 while besti+bestsize < ahi and bestj+bestsize < bhi and \
427 not isbjunk(b[bestj+bestsize]) and \
428 a[besti+bestsize] == b[bestj+bestsize]:
429 bestsize += 1
430
Tim Peters9ae21482001-02-10 08:00:53 +0000431 # Now that we have a wholly interesting match (albeit possibly
432 # empty!), we may as well suck up the matching junk on each
433 # side of it too. Can't think of a good reason not to, and it
434 # saves post-processing the (possibly considerable) expense of
435 # figuring out what to do with it. In the case of an empty
436 # interesting match, this is clearly the right thing to do,
437 # because no other kind of match is possible in the regions.
438 while besti > alo and bestj > blo and \
439 isbjunk(b[bestj-1]) and \
440 a[besti-1] == b[bestj-1]:
441 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
442 while besti+bestsize < ahi and bestj+bestsize < bhi and \
443 isbjunk(b[bestj+bestsize]) and \
444 a[besti+bestsize] == b[bestj+bestsize]:
445 bestsize = bestsize + 1
446
Christian Heimes25bb7832008-01-11 16:17:00 +0000447 return Match(besti, bestj, bestsize)
Tim Peters9ae21482001-02-10 08:00:53 +0000448
449 def get_matching_blocks(self):
450 """Return list of triples describing matching subsequences.
451
452 Each triple is of the form (i, j, n), and means that
453 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000454 i and in j. New in Python 2.5, it's also guaranteed that if
455 (i, j, n) and (i', j', n') are adjacent triples in the list, and
456 the second is not the last triple in the list, then i+n != i' or
457 j+n != j'. IOW, adjacent triples never describe adjacent equal
458 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000459
460 The last triple is a dummy, (len(a), len(b), 0), and is the only
461 triple with n==0.
462
463 >>> s = SequenceMatcher(None, "abxcd", "abcd")
Christian Heimes25bb7832008-01-11 16:17:00 +0000464 >>> list(s.get_matching_blocks())
465 [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 +0000466 """
467
468 if self.matching_blocks is not None:
469 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000470 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000471
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000472 # This is most naturally expressed as a recursive algorithm, but
473 # at least one user bumped into extreme use cases that exceeded
474 # the recursion limit on their box. So, now we maintain a list
475 # ('queue`) of blocks we still need to look at, and append partial
476 # results to `matching_blocks` in a loop; the matches are sorted
477 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000478 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000479 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000480 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000481 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000482 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000483 # a[alo:i] vs b[blo:j] unknown
484 # a[i:i+k] same as b[j:j+k]
485 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000486 if k: # if k is 0, there was no matching block
487 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000488 if alo < i and blo < j:
489 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000490 if i+k < ahi and j+k < bhi:
491 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000492 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000493
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000494 # It's possible that we have adjacent equal blocks in the
495 # matching_blocks list now. Starting with 2.5, this code was added
496 # to collapse them.
497 i1 = j1 = k1 = 0
498 non_adjacent = []
499 for i2, j2, k2 in matching_blocks:
500 # Is this block adjacent to i1, j1, k1?
501 if i1 + k1 == i2 and j1 + k1 == j2:
502 # Yes, so collapse them -- this just increases the length of
503 # the first block by the length of the second, and the first
504 # block so lengthened remains the block to compare against.
505 k1 += k2
506 else:
507 # Not adjacent. Remember the first block (k1==0 means it's
508 # the dummy we started with), and make the second block the
509 # new block to compare against.
510 if k1:
511 non_adjacent.append((i1, j1, k1))
512 i1, j1, k1 = i2, j2, k2
513 if k1:
514 non_adjacent.append((i1, j1, k1))
515
516 non_adjacent.append( (la, lb, 0) )
517 self.matching_blocks = non_adjacent
Christian Heimes25bb7832008-01-11 16:17:00 +0000518 return map(Match._make, self.matching_blocks)
Tim Peters9ae21482001-02-10 08:00:53 +0000519
Tim Peters9ae21482001-02-10 08:00:53 +0000520 def get_opcodes(self):
521 """Return list of 5-tuples describing how to turn a into b.
522
523 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
524 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
525 tuple preceding it, and likewise for j1 == the previous j2.
526
527 The tags are strings, with these meanings:
528
529 'replace': a[i1:i2] should be replaced by b[j1:j2]
530 'delete': a[i1:i2] should be deleted.
531 Note that j1==j2 in this case.
532 'insert': b[j1:j2] should be inserted at a[i1:i1].
533 Note that i1==i2 in this case.
534 'equal': a[i1:i2] == b[j1:j2]
535
536 >>> a = "qabxcd"
537 >>> b = "abycdf"
538 >>> s = SequenceMatcher(None, a, b)
539 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000540 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
541 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000542 delete a[0:1] (q) b[0:0] ()
543 equal a[1:3] (ab) b[0:2] (ab)
544 replace a[3:4] (x) b[2:3] (y)
545 equal a[4:6] (cd) b[3:5] (cd)
546 insert a[6:6] () b[5:6] (f)
547 """
548
549 if self.opcodes is not None:
550 return self.opcodes
551 i = j = 0
552 self.opcodes = answer = []
553 for ai, bj, size in self.get_matching_blocks():
554 # invariant: we've pumped out correct diffs to change
555 # a[:i] into b[:j], and the next matching block is
556 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
557 # out a diff to change a[i:ai] into b[j:bj], pump out
558 # the matching block, and move (i,j) beyond the match
559 tag = ''
560 if i < ai and j < bj:
561 tag = 'replace'
562 elif i < ai:
563 tag = 'delete'
564 elif j < bj:
565 tag = 'insert'
566 if tag:
567 answer.append( (tag, i, ai, j, bj) )
568 i, j = ai+size, bj+size
569 # the list of matching blocks is terminated by a
570 # sentinel with size 0
571 if size:
572 answer.append( ('equal', ai, i, bj, j) )
573 return answer
574
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000575 def get_grouped_opcodes(self, n=3):
576 """ Isolate change clusters by eliminating ranges with no changes.
577
578 Return a generator of groups with upto n lines of context.
579 Each group is in the same format as returned by get_opcodes().
580
581 >>> from pprint import pprint
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000582 >>> a = list(map(str, range(1,40)))
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000583 >>> b = a[:]
584 >>> b[8:8] = ['i'] # Make an insertion
585 >>> b[20] += 'x' # Make a replacement
586 >>> b[23:28] = [] # Make a deletion
587 >>> b[30] += 'y' # Make another replacement
588 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
589 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
590 [('equal', 16, 19, 17, 20),
591 ('replace', 19, 20, 20, 21),
592 ('equal', 20, 22, 21, 23),
593 ('delete', 22, 27, 23, 23),
594 ('equal', 27, 30, 23, 26)],
595 [('equal', 31, 34, 27, 30),
596 ('replace', 34, 35, 30, 31),
597 ('equal', 35, 38, 31, 34)]]
598 """
599
600 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000601 if not codes:
602 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000603 # Fixup leading and trailing groups if they show no changes.
604 if codes[0][0] == 'equal':
605 tag, i1, i2, j1, j2 = codes[0]
606 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
607 if codes[-1][0] == 'equal':
608 tag, i1, i2, j1, j2 = codes[-1]
609 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
610
611 nn = n + n
612 group = []
613 for tag, i1, i2, j1, j2 in codes:
614 # End the current group and start a new one whenever
615 # there is a large range with no changes.
616 if tag == 'equal' and i2-i1 > nn:
617 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
618 yield group
619 group = []
620 i1, j1 = max(i1, i2-n), max(j1, j2-n)
621 group.append((tag, i1, i2, j1 ,j2))
622 if group and not (len(group)==1 and group[0][0] == 'equal'):
623 yield group
624
Tim Peters9ae21482001-02-10 08:00:53 +0000625 def ratio(self):
626 """Return a measure of the sequences' similarity (float in [0,1]).
627
628 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000629 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000630 Note that this is 1 if the sequences are identical, and 0 if
631 they have nothing in common.
632
633 .ratio() is expensive to compute if you haven't already computed
634 .get_matching_blocks() or .get_opcodes(), in which case you may
635 want to try .quick_ratio() or .real_quick_ratio() first to get an
636 upper bound.
637
638 >>> s = SequenceMatcher(None, "abcd", "bcde")
639 >>> s.ratio()
640 0.75
641 >>> s.quick_ratio()
642 0.75
643 >>> s.real_quick_ratio()
644 1.0
645 """
646
Guido van Rossum89da5d72006-08-22 00:21:25 +0000647 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000648 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000649
650 def quick_ratio(self):
651 """Return an upper bound on ratio() relatively quickly.
652
653 This isn't defined beyond that it is an upper bound on .ratio(), and
654 is faster to compute.
655 """
656
657 # viewing a and b as multisets, set matches to the cardinality
658 # of their intersection; this counts the number of matches
659 # without regard to order, so is clearly an upper bound
660 if self.fullbcount is None:
661 self.fullbcount = fullbcount = {}
662 for elt in self.b:
663 fullbcount[elt] = fullbcount.get(elt, 0) + 1
664 fullbcount = self.fullbcount
665 # avail[x] is the number of times x appears in 'b' less the
666 # number of times we've seen it in 'a' so far ... kinda
667 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000668 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000669 for elt in self.a:
670 if availhas(elt):
671 numb = avail[elt]
672 else:
673 numb = fullbcount.get(elt, 0)
674 avail[elt] = numb - 1
675 if numb > 0:
676 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000677 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000678
679 def real_quick_ratio(self):
680 """Return an upper bound on ratio() very quickly.
681
682 This isn't defined beyond that it is an upper bound on .ratio(), and
683 is faster to compute than either .ratio() or .quick_ratio().
684 """
685
686 la, lb = len(self.a), len(self.b)
687 # can't have more matches than the number of elements in the
688 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000689 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000690
691def get_close_matches(word, possibilities, n=3, cutoff=0.6):
692 """Use SequenceMatcher to return list of the best "good enough" matches.
693
694 word is a sequence for which close matches are desired (typically a
695 string).
696
697 possibilities is a list of sequences against which to match word
698 (typically a list of strings).
699
700 Optional arg n (default 3) is the maximum number of close matches to
701 return. n must be > 0.
702
703 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
704 that don't score at least that similar to word are ignored.
705
706 The best (no more than n) matches among the possibilities are returned
707 in a list, sorted by similarity score, most similar first.
708
709 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
710 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000711 >>> import keyword as _keyword
712 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000713 ['while']
Guido van Rossum486364b2007-06-30 05:01:58 +0000714 >>> get_close_matches("Apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000715 []
Tim Peters5e824c32001-08-12 22:25:01 +0000716 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000717 ['except']
718 """
719
720 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000721 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000722 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000723 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000724 result = []
725 s = SequenceMatcher()
726 s.set_seq2(word)
727 for x in possibilities:
728 s.set_seq1(x)
729 if s.real_quick_ratio() >= cutoff and \
730 s.quick_ratio() >= cutoff and \
731 s.ratio() >= cutoff:
732 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000733
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000734 # Move the best scorers to head of list
Raymond Hettingeraefde432004-06-15 23:53:35 +0000735 result = heapq.nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000736 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000737 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000738
739def _count_leading(line, ch):
740 """
741 Return number of `ch` characters at the start of `line`.
742
743 Example:
744
745 >>> _count_leading(' abc', ' ')
746 3
747 """
748
749 i, n = 0, len(line)
750 while i < n and line[i] == ch:
751 i += 1
752 return i
753
754class Differ:
755 r"""
756 Differ is a class for comparing sequences of lines of text, and
757 producing human-readable differences or deltas. Differ uses
758 SequenceMatcher both to compare sequences of lines, and to compare
759 sequences of characters within similar (near-matching) lines.
760
761 Each line of a Differ delta begins with a two-letter code:
762
763 '- ' line unique to sequence 1
764 '+ ' line unique to sequence 2
765 ' ' line common to both sequences
766 '? ' line not present in either input sequence
767
768 Lines beginning with '? ' attempt to guide the eye to intraline
769 differences, and were not present in either input sequence. These lines
770 can be confusing if the sequences contain tab characters.
771
772 Note that Differ makes no claim to produce a *minimal* diff. To the
773 contrary, minimal diffs are often counter-intuitive, because they synch
774 up anywhere possible, sometimes accidental matches 100 pages apart.
775 Restricting synch points to contiguous matches preserves some notion of
776 locality, at the occasional cost of producing a longer diff.
777
778 Example: Comparing two texts.
779
780 First we set up the texts, sequences of individual single-line strings
781 ending with newlines (such sequences can also be obtained from the
782 `readlines()` method of file-like objects):
783
784 >>> text1 = ''' 1. Beautiful is better than ugly.
785 ... 2. Explicit is better than implicit.
786 ... 3. Simple is better than complex.
787 ... 4. Complex is better than complicated.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300788 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000789 >>> len(text1)
790 4
791 >>> text1[0][-1]
792 '\n'
793 >>> text2 = ''' 1. Beautiful is better than ugly.
794 ... 3. Simple is better than complex.
795 ... 4. Complicated is better than complex.
796 ... 5. Flat is better than nested.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300797 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000798
799 Next we instantiate a Differ object:
800
801 >>> d = Differ()
802
803 Note that when instantiating a Differ object we may pass functions to
804 filter out line and character 'junk'. See Differ.__init__ for details.
805
806 Finally, we compare the two:
807
Tim Peters8a9c2842001-09-22 21:30:22 +0000808 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000809
810 'result' is a list of strings, so let's pretty-print it:
811
812 >>> from pprint import pprint as _pprint
813 >>> _pprint(result)
814 [' 1. Beautiful is better than ugly.\n',
815 '- 2. Explicit is better than implicit.\n',
816 '- 3. Simple is better than complex.\n',
817 '+ 3. Simple is better than complex.\n',
818 '? ++\n',
819 '- 4. Complex is better than complicated.\n',
820 '? ^ ---- ^\n',
821 '+ 4. Complicated is better than complex.\n',
822 '? ++++ ^ ^\n',
823 '+ 5. Flat is better than nested.\n']
824
825 As a single multi-line string it looks like this:
826
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000827 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000828 1. Beautiful is better than ugly.
829 - 2. Explicit is better than implicit.
830 - 3. Simple is better than complex.
831 + 3. Simple is better than complex.
832 ? ++
833 - 4. Complex is better than complicated.
834 ? ^ ---- ^
835 + 4. Complicated is better than complex.
836 ? ++++ ^ ^
837 + 5. Flat is better than nested.
838
839 Methods:
840
841 __init__(linejunk=None, charjunk=None)
842 Construct a text differencer, with optional filters.
843
844 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000845 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000846 """
847
848 def __init__(self, linejunk=None, charjunk=None):
849 """
850 Construct a text differencer, with optional filters.
851
852 The two optional keyword parameters are for filter functions:
853
854 - `linejunk`: A function that should accept a single string argument,
855 and return true iff the string is junk. The module-level function
856 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000857 characters, except for at most one splat ('#'). It is recommended
858 to leave linejunk None; as of Python 2.3, the underlying
859 SequenceMatcher class has grown an adaptive notion of "noise" lines
860 that's better than any static definition the author has ever been
861 able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000862
863 - `charjunk`: A function that should accept a string of length 1. The
864 module-level function `IS_CHARACTER_JUNK` may be used to filter out
865 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000866 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000867 """
868
869 self.linejunk = linejunk
870 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000871
872 def compare(self, a, b):
873 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000874 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000875
876 Each sequence must contain individual single-line strings ending with
877 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000878 of file-like objects. The delta generated also consists of newline-
879 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000880 method of a file-like object.
881
882 Example:
883
Ezio Melottid8b509b2011-09-28 17:37:55 +0300884 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(True),
885 ... 'ore\ntree\nemu\n'.splitlines(True))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000886 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000887 - one
888 ? ^
889 + ore
890 ? ^
891 - two
892 - three
893 ? -
894 + tree
895 + emu
896 """
897
898 cruncher = SequenceMatcher(self.linejunk, a, b)
899 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
900 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000901 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000902 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000903 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000904 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000905 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000906 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000907 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000908 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000909 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +0000910
Philip Jenvey4993cc02012-10-01 12:53:43 -0700911 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +0000912
913 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000914 """Generate comparison results for a same-tagged range."""
Guido van Rossum805365e2007-05-07 22:24:25 +0000915 for i in range(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000916 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000917
918 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
919 assert alo < ahi and blo < bhi
920 # dump the shorter block first -- reduces the burden on short-term
921 # memory if the blocks are of very different sizes
922 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000923 first = self._dump('+', b, blo, bhi)
924 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000925 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000926 first = self._dump('-', a, alo, ahi)
927 second = self._dump('+', b, blo, bhi)
928
929 for g in first, second:
Philip Jenvey4993cc02012-10-01 12:53:43 -0700930 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +0000931
932 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
933 r"""
934 When replacing one block of lines with another, search the blocks
935 for *similar* lines; the best-matching pair (if any) is used as a
936 synch point, and intraline difference marking is done on the
937 similar pair. Lots of work, but often worth it.
938
939 Example:
940
941 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000942 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
943 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000944 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000945 - abcDefghiJkl
946 ? ^ ^ ^
947 + abcdefGhijkl
948 ? ^ ^ ^
949 """
950
Tim Peters5e824c32001-08-12 22:25:01 +0000951 # don't synch up unless the lines have a similarity score of at
952 # least cutoff; best_ratio tracks the best score seen so far
953 best_ratio, cutoff = 0.74, 0.75
954 cruncher = SequenceMatcher(self.charjunk)
955 eqi, eqj = None, None # 1st indices of equal lines (if any)
956
957 # search for the pair that matches best without being identical
958 # (identical lines must be junk lines, & we don't want to synch up
959 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000960 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000961 bj = b[j]
962 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000963 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000964 ai = a[i]
965 if ai == bj:
966 if eqi is None:
967 eqi, eqj = i, j
968 continue
969 cruncher.set_seq1(ai)
970 # computing similarity is expensive, so use the quick
971 # upper bounds first -- have seen this speed up messy
972 # compares by a factor of 3.
973 # note that ratio() is only expensive to compute the first
974 # time it's called on a sequence pair; the expensive part
975 # of the computation is cached by cruncher
976 if cruncher.real_quick_ratio() > best_ratio and \
977 cruncher.quick_ratio() > best_ratio and \
978 cruncher.ratio() > best_ratio:
979 best_ratio, best_i, best_j = cruncher.ratio(), i, j
980 if best_ratio < cutoff:
981 # no non-identical "pretty close" pair
982 if eqi is None:
983 # no identical pair either -- treat it as a straight replace
Philip Jenvey4993cc02012-10-01 12:53:43 -0700984 yield from self._plain_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000985 return
986 # no close pair, but an identical pair -- synch up on that
987 best_i, best_j, best_ratio = eqi, eqj, 1.0
988 else:
989 # there's a close pair, so forget the identical pair (if any)
990 eqi = None
991
992 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
993 # identical
Tim Peters5e824c32001-08-12 22:25:01 +0000994
995 # pump out diffs from before the synch point
Philip Jenvey4993cc02012-10-01 12:53:43 -0700996 yield from self._fancy_helper(a, alo, best_i, b, blo, best_j)
Tim Peters5e824c32001-08-12 22:25:01 +0000997
998 # do intraline marking on the synch pair
999 aelt, belt = a[best_i], b[best_j]
1000 if eqi is None:
1001 # pump out a '-', '?', '+', '?' quad for the synched lines
1002 atags = btags = ""
1003 cruncher.set_seqs(aelt, belt)
1004 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1005 la, lb = ai2 - ai1, bj2 - bj1
1006 if tag == 'replace':
1007 atags += '^' * la
1008 btags += '^' * lb
1009 elif tag == 'delete':
1010 atags += '-' * la
1011 elif tag == 'insert':
1012 btags += '+' * lb
1013 elif tag == 'equal':
1014 atags += ' ' * la
1015 btags += ' ' * lb
1016 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001017 raise ValueError('unknown tag %r' % (tag,))
Philip Jenvey4993cc02012-10-01 12:53:43 -07001018 yield from self._qformat(aelt, belt, atags, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001019 else:
1020 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001021 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001022
1023 # pump out diffs from after the synch point
Philip Jenvey4993cc02012-10-01 12:53:43 -07001024 yield from self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001025
1026 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001027 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001028 if alo < ahi:
1029 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001030 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001031 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001032 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001033 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001034 g = self._dump('+', b, blo, bhi)
1035
Philip Jenvey4993cc02012-10-01 12:53:43 -07001036 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +00001037
1038 def _qformat(self, aline, bline, atags, btags):
1039 r"""
1040 Format "?" output and deal with leading tabs.
1041
1042 Example:
1043
1044 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001045 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1046 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001047 >>> for line in results: print(repr(line))
1048 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001049 '- \tabcDefghiJkl\n'
1050 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001051 '+ \tabcdefGhijkl\n'
1052 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001053 """
1054
1055 # Can hurt, but will probably help most of the time.
1056 common = min(_count_leading(aline, "\t"),
1057 _count_leading(bline, "\t"))
1058 common = min(common, _count_leading(atags[:common], " "))
Senthil Kumaran758025c2009-11-23 19:02:52 +00001059 common = min(common, _count_leading(btags[:common], " "))
Tim Peters5e824c32001-08-12 22:25:01 +00001060 atags = atags[common:].rstrip()
1061 btags = btags[common:].rstrip()
1062
Tim Peters8a9c2842001-09-22 21:30:22 +00001063 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001064 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001065 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001066
Tim Peters8a9c2842001-09-22 21:30:22 +00001067 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001068 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001069 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001070
1071# With respect to junk, an earlier version of ndiff simply refused to
1072# *start* a match with a junk element. The result was cases like this:
1073# before: private Thread currentThread;
1074# after: private volatile Thread currentThread;
1075# If you consider whitespace to be junk, the longest contiguous match
1076# not starting with junk is "e Thread currentThread". So ndiff reported
1077# that "e volatil" was inserted between the 't' and the 'e' in "private".
1078# While an accurate view, to people that's absurd. The current version
1079# looks for matching blocks that are entirely junk-free, then extends the
1080# longest one of those as far as possible but only with matching junk.
1081# So now "currentThread" is matched, then extended to suck up the
1082# preceding blank; then "private" is matched, and extended to suck up the
1083# following blank; then "Thread" is matched; and finally ndiff reports
1084# that "volatile " was inserted before "Thread". The only quibble
1085# remaining is that perhaps it was really the case that " volatile"
1086# was inserted after "private". I can live with that <wink>.
1087
1088import re
1089
1090def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1091 r"""
1092 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1093
1094 Examples:
1095
1096 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001097 True
Tim Peters5e824c32001-08-12 22:25:01 +00001098 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001099 True
Tim Peters5e824c32001-08-12 22:25:01 +00001100 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001101 False
Tim Peters5e824c32001-08-12 22:25:01 +00001102 """
1103
1104 return pat(line) is not None
1105
1106def IS_CHARACTER_JUNK(ch, ws=" \t"):
1107 r"""
1108 Return 1 for ignorable character: iff `ch` is a space or tab.
1109
1110 Examples:
1111
1112 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001113 True
Tim Peters5e824c32001-08-12 22:25:01 +00001114 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001115 True
Tim Peters5e824c32001-08-12 22:25:01 +00001116 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001117 False
Tim Peters5e824c32001-08-12 22:25:01 +00001118 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001119 False
Tim Peters5e824c32001-08-12 22:25:01 +00001120 """
1121
1122 return ch in ws
1123
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001124
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001125########################################################################
1126### Unified Diff
1127########################################################################
1128
1129def _format_range_unified(start, stop):
Raymond Hettinger49353d02011-04-11 12:40:58 -07001130 'Convert range to the "ed" format'
1131 # Per the diff spec at http://www.unix.org/single_unix_specification/
1132 beginning = start + 1 # lines start numbering with one
1133 length = stop - start
1134 if length == 1:
1135 return '{}'.format(beginning)
1136 if not length:
1137 beginning -= 1 # empty ranges begin at line just before the range
1138 return '{},{}'.format(beginning, length)
1139
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001140def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1141 tofiledate='', n=3, lineterm='\n'):
1142 r"""
1143 Compare two sequences of lines; generate the delta as a unified diff.
1144
1145 Unified diffs are a compact way of showing line changes and a few
1146 lines of context. The number of context lines is set by 'n' which
1147 defaults to three.
1148
Raymond Hettinger0887c732003-06-17 16:53:25 +00001149 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001150 created with a trailing newline. This is helpful so that inputs
1151 created from file.readlines() result in diffs that are suitable for
1152 file.writelines() since both the inputs and outputs have trailing
1153 newlines.
1154
1155 For inputs that do not have trailing newlines, set the lineterm
1156 argument to "" so that the output will be uniformly newline free.
1157
1158 The unidiff format normally has a header for filenames and modification
1159 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001160 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1161 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001162
1163 Example:
1164
1165 >>> for line in unified_diff('one two three four'.split(),
1166 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001167 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001168 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001169 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1170 --- Original 2005-01-26 23:30:50
1171 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001172 @@ -1,4 +1,4 @@
1173 +zero
1174 one
1175 -two
1176 -three
1177 +tree
1178 four
1179 """
1180
1181 started = False
1182 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1183 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001184 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001185 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1186 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1187 yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
1188 yield '+++ {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger49353d02011-04-11 12:40:58 -07001189
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001190 first, last = group[0], group[-1]
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001191 file1_range = _format_range_unified(first[1], last[2])
1192 file2_range = _format_range_unified(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001193 yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
1194
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001195 for tag, i1, i2, j1, j2 in group:
1196 if tag == 'equal':
1197 for line in a[i1:i2]:
1198 yield ' ' + line
1199 continue
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001200 if tag in {'replace', 'delete'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001201 for line in a[i1:i2]:
1202 yield '-' + line
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001203 if tag in {'replace', 'insert'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001204 for line in b[j1:j2]:
1205 yield '+' + line
1206
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001207
1208########################################################################
1209### Context Diff
1210########################################################################
1211
1212def _format_range_context(start, stop):
1213 'Convert range to the "ed" format'
1214 # Per the diff spec at http://www.unix.org/single_unix_specification/
1215 beginning = start + 1 # lines start numbering with one
1216 length = stop - start
1217 if not length:
1218 beginning -= 1 # empty ranges begin at line just before the range
1219 if length <= 1:
1220 return '{}'.format(beginning)
1221 return '{},{}'.format(beginning, beginning + length - 1)
1222
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001223# See http://www.unix.org/single_unix_specification/
1224def context_diff(a, b, fromfile='', tofile='',
1225 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1226 r"""
1227 Compare two sequences of lines; generate the delta as a context diff.
1228
1229 Context diffs are a compact way of showing line changes and a few
1230 lines of context. The number of context lines is set by 'n' which
1231 defaults to three.
1232
1233 By default, the diff control lines (those with *** or ---) are
1234 created with a trailing newline. This is helpful so that inputs
1235 created from file.readlines() result in diffs that are suitable for
1236 file.writelines() since both the inputs and outputs have trailing
1237 newlines.
1238
1239 For inputs that do not have trailing newlines, set the lineterm
1240 argument to "" so that the output will be uniformly newline free.
1241
1242 The context diff format normally has a header for filenames and
1243 modification times. Any or all of these may be specified using
1244 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001245 The modification times are normally expressed in the ISO 8601 format.
1246 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001247
1248 Example:
1249
Ezio Melottid8b509b2011-09-28 17:37:55 +03001250 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
1251 ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001252 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001253 *** Original
1254 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001255 ***************
1256 *** 1,4 ****
1257 one
1258 ! two
1259 ! three
1260 four
1261 --- 1,4 ----
1262 + zero
1263 one
1264 ! tree
1265 four
1266 """
1267
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001268 prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001269 started = False
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001270 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1271 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001272 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001273 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1274 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1275 yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
1276 yield '--- {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001277
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001278 first, last = group[0], group[-1]
Raymond Hettinger49353d02011-04-11 12:40:58 -07001279 yield '***************' + lineterm
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001280
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001281 file1_range = _format_range_context(first[1], last[2])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001282 yield '*** {} ****{}'.format(file1_range, lineterm)
1283
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001284 if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001285 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001286 if tag != 'insert':
1287 for line in a[i1:i2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001288 yield prefix[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001289
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001290 file2_range = _format_range_context(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001291 yield '--- {} ----{}'.format(file2_range, lineterm)
1292
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001293 if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001294 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001295 if tag != 'delete':
1296 for line in b[j1:j2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001297 yield prefix[tag] + line
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001298
Tim Peters81b92512002-04-29 01:37:32 +00001299def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001300 r"""
1301 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1302
1303 Optional keyword parameters `linejunk` and `charjunk` are for filter
1304 functions (or None):
1305
1306 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001307 return true iff the string is junk. The default is None, and is
1308 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1309 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001310
1311 - charjunk: A function that should accept a string of length 1. The
1312 default is module-level function IS_CHARACTER_JUNK, which filters out
1313 whitespace characters (a blank or tab; note: bad idea to include newline
1314 in this!).
1315
1316 Tools/scripts/ndiff.py is a command-line front-end to this function.
1317
1318 Example:
1319
Ezio Melottid8b509b2011-09-28 17:37:55 +03001320 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
1321 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001322 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001323 - one
1324 ? ^
1325 + ore
1326 ? ^
1327 - two
1328 - three
1329 ? -
1330 + tree
1331 + emu
1332 """
1333 return Differ(linejunk, charjunk).compare(a, b)
1334
Martin v. Löwise064b412004-08-29 16:34:40 +00001335def _mdiff(fromlines, tolines, context=None, linejunk=None,
1336 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001337 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001338
1339 Arguments:
1340 fromlines -- list of text lines to compared to tolines
1341 tolines -- list of text lines to be compared to fromlines
1342 context -- number of context lines to display on each side of difference,
1343 if None, all from/to text lines will be generated.
1344 linejunk -- passed on to ndiff (see ndiff documentation)
1345 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001346
Martin v. Löwise064b412004-08-29 16:34:40 +00001347 This function returns an interator which returns a tuple:
1348 (from line tuple, to line tuple, boolean flag)
1349
1350 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001351 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001352 line text -- original line text with following markers inserted:
1353 '\0+' -- marks start of added text
1354 '\0-' -- marks start of deleted text
1355 '\0^' -- marks start of changed text
1356 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001357
Martin v. Löwise064b412004-08-29 16:34:40 +00001358 boolean flag -- None indicates context separation, True indicates
1359 either "from" or "to" line contains a change, otherwise False.
1360
1361 This function/iterator was originally developed to generate side by side
1362 file difference for making HTML pages (see HtmlDiff class for example
1363 usage).
1364
1365 Note, this function utilizes the ndiff function to generate the side by
1366 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001367 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001368 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001369 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001370
1371 # regular expression for finding intraline change indices
1372 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001373
Martin v. Löwise064b412004-08-29 16:34:40 +00001374 # create the difference iterator to generate the differences
1375 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1376
1377 def _make_line(lines, format_key, side, num_lines=[0,0]):
1378 """Returns line of text with user's change markup and line formatting.
1379
1380 lines -- list of lines from the ndiff generator to produce a line of
1381 text from. When producing the line of text to return, the
1382 lines used are removed from this list.
1383 format_key -- '+' return first line in list with "add" markup around
1384 the entire line.
1385 '-' return first line in list with "delete" markup around
1386 the entire line.
1387 '?' return first line in list with add/delete/change
1388 intraline markup (indices obtained from second line)
1389 None return first line in list with no markup
1390 side -- indice into the num_lines list (0=from,1=to)
1391 num_lines -- from/to current line number. This is NOT intended to be a
1392 passed parameter. It is present as a keyword argument to
1393 maintain memory of the current line numbers between calls
1394 of this function.
1395
1396 Note, this function is purposefully not defined at the module scope so
1397 that data it needs from its parent function (within whose context it
1398 is defined) does not need to be of module scope.
1399 """
1400 num_lines[side] += 1
1401 # Handle case where no user markup is to be added, just return line of
1402 # text with user's line format to allow for usage of the line number.
1403 if format_key is None:
1404 return (num_lines[side],lines.pop(0)[2:])
1405 # Handle case of intraline changes
1406 if format_key == '?':
1407 text, markers = lines.pop(0), lines.pop(0)
1408 # find intraline changes (store change type and indices in tuples)
1409 sub_info = []
1410 def record_sub_info(match_object,sub_info=sub_info):
1411 sub_info.append([match_object.group(1)[0],match_object.span()])
1412 return match_object.group(1)
1413 change_re.sub(record_sub_info,markers)
1414 # process each tuple inserting our special marks that won't be
1415 # noticed by an xml/html escaper.
1416 for key,(begin,end) in sub_info[::-1]:
1417 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1418 text = text[2:]
1419 # Handle case of add/delete entire line
1420 else:
1421 text = lines.pop(0)[2:]
1422 # if line of text is just a newline, insert a space so there is
1423 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001424 if not text:
1425 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001426 # insert marks that won't be noticed by an xml/html escaper.
1427 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001428 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001429 # thing (such as adding the line number) then replace the special
1430 # marks with what the user's change markup.
1431 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001432
Martin v. Löwise064b412004-08-29 16:34:40 +00001433 def _line_iterator():
1434 """Yields from/to lines of text with a change indication.
1435
1436 This function is an iterator. It itself pulls lines from a
1437 differencing iterator, processes them and yields them. When it can
1438 it yields both a "from" and a "to" line, otherwise it will yield one
1439 or the other. In addition to yielding the lines of from/to text, a
1440 boolean flag is yielded to indicate if the text line(s) have
1441 differences in them.
1442
1443 Note, this function is purposefully not defined at the module scope so
1444 that data it needs from its parent function (within whose context it
1445 is defined) does not need to be of module scope.
1446 """
1447 lines = []
1448 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001449 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001450 # Load up next 4 lines so we can look ahead, create strings which
1451 # are a concatenation of the first character of each of the 4 lines
1452 # so we can do some very readable comparisons.
1453 while len(lines) < 4:
1454 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001455 lines.append(next(diff_lines_iterator))
Martin v. Löwise064b412004-08-29 16:34:40 +00001456 except StopIteration:
1457 lines.append('X')
1458 s = ''.join([line[0] for line in lines])
1459 if s.startswith('X'):
1460 # When no more lines, pump out any remaining blank lines so the
1461 # corresponding add/delete lines get a matching blank line so
1462 # all line pairs get yielded at the next level.
1463 num_blanks_to_yield = num_blanks_pending
1464 elif s.startswith('-?+?'):
1465 # simple intraline change
1466 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1467 continue
1468 elif s.startswith('--++'):
1469 # in delete block, add block coming: we do NOT want to get
1470 # caught up on blank lines yet, just process the delete line
1471 num_blanks_pending -= 1
1472 yield _make_line(lines,'-',0), None, True
1473 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001474 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001475 # in delete block and see a intraline change or unchanged line
1476 # coming: yield the delete line and then blanks
1477 from_line,to_line = _make_line(lines,'-',0), None
1478 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1479 elif s.startswith('-+?'):
1480 # intraline change
1481 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1482 continue
1483 elif s.startswith('-?+'):
1484 # intraline change
1485 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1486 continue
1487 elif s.startswith('-'):
1488 # delete FROM line
1489 num_blanks_pending -= 1
1490 yield _make_line(lines,'-',0), None, True
1491 continue
1492 elif s.startswith('+--'):
1493 # in add block, delete block coming: we do NOT want to get
1494 # caught up on blank lines yet, just process the add line
1495 num_blanks_pending += 1
1496 yield None, _make_line(lines,'+',1), True
1497 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001498 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001499 # will be leaving an add block: yield blanks then add line
1500 from_line, to_line = None, _make_line(lines,'+',1)
1501 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1502 elif s.startswith('+'):
1503 # inside an add block, yield the add line
1504 num_blanks_pending += 1
1505 yield None, _make_line(lines,'+',1), True
1506 continue
1507 elif s.startswith(' '):
1508 # unchanged text, yield it to both sides
1509 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1510 continue
1511 # Catch up on the blank lines so when we yield the next from/to
1512 # pair, they are lined up.
1513 while(num_blanks_to_yield < 0):
1514 num_blanks_to_yield += 1
1515 yield None,('','\n'),True
1516 while(num_blanks_to_yield > 0):
1517 num_blanks_to_yield -= 1
1518 yield ('','\n'),None,True
1519 if s.startswith('X'):
1520 raise StopIteration
1521 else:
1522 yield from_line,to_line,True
1523
1524 def _line_pair_iterator():
1525 """Yields from/to lines of text with a change indication.
1526
1527 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001528 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001529 always yields a pair of from/to text lines (with the change
1530 indication). If necessary it will collect single from/to lines
1531 until it has a matching pair from/to pair to yield.
1532
1533 Note, this function is purposefully not defined at the module scope so
1534 that data it needs from its parent function (within whose context it
1535 is defined) does not need to be of module scope.
1536 """
1537 line_iterator = _line_iterator()
1538 fromlines,tolines=[],[]
1539 while True:
1540 # Collecting lines of text until we have a from/to pair
1541 while (len(fromlines)==0 or len(tolines)==0):
Georg Brandla18af4e2007-04-21 15:47:16 +00001542 from_line, to_line, found_diff = next(line_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001543 if from_line is not None:
1544 fromlines.append((from_line,found_diff))
1545 if to_line is not None:
1546 tolines.append((to_line,found_diff))
1547 # Once we have a pair, remove them from the collection and yield it
1548 from_line, fromDiff = fromlines.pop(0)
1549 to_line, to_diff = tolines.pop(0)
1550 yield (from_line,to_line,fromDiff or to_diff)
1551
1552 # Handle case where user does not want context differencing, just yield
1553 # them up without doing anything else with them.
1554 line_pair_iterator = _line_pair_iterator()
1555 if context is None:
1556 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +00001557 yield next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001558 # Handle case where user wants context differencing. We must do some
1559 # storage of lines until we know for sure that they are to be yielded.
1560 else:
1561 context += 1
1562 lines_to_write = 0
1563 while True:
1564 # Store lines up until we find a difference, note use of a
1565 # circular queue because we only need to keep around what
1566 # we need for context.
1567 index, contextLines = 0, [None]*(context)
1568 found_diff = False
1569 while(found_diff is False):
Georg Brandla18af4e2007-04-21 15:47:16 +00001570 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001571 i = index % context
1572 contextLines[i] = (from_line, to_line, found_diff)
1573 index += 1
1574 # Yield lines that we have collected so far, but first yield
1575 # the user's separator.
1576 if index > context:
1577 yield None, None, None
1578 lines_to_write = context
1579 else:
1580 lines_to_write = index
1581 index = 0
1582 while(lines_to_write):
1583 i = index % context
1584 index += 1
1585 yield contextLines[i]
1586 lines_to_write -= 1
1587 # Now yield the context lines after the change
1588 lines_to_write = context-1
1589 while(lines_to_write):
Georg Brandla18af4e2007-04-21 15:47:16 +00001590 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001591 # If another change within the context, extend the context
1592 if found_diff:
1593 lines_to_write = context-1
1594 else:
1595 lines_to_write -= 1
1596 yield from_line, to_line, found_diff
1597
1598
1599_file_template = """
1600<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1601 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1602
1603<html>
1604
1605<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001606 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001607 content="text/html; charset=ISO-8859-1" />
1608 <title></title>
1609 <style type="text/css">%(styles)s
1610 </style>
1611</head>
1612
1613<body>
1614 %(table)s%(legend)s
1615</body>
1616
1617</html>"""
1618
1619_styles = """
1620 table.diff {font-family:Courier; border:medium;}
1621 .diff_header {background-color:#e0e0e0}
1622 td.diff_header {text-align:right}
1623 .diff_next {background-color:#c0c0c0}
1624 .diff_add {background-color:#aaffaa}
1625 .diff_chg {background-color:#ffff77}
1626 .diff_sub {background-color:#ffaaaa}"""
1627
1628_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001629 <table class="diff" id="difflib_chg_%(prefix)s_top"
1630 cellspacing="0" cellpadding="0" rules="groups" >
1631 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001632 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1633 %(header_row)s
1634 <tbody>
1635%(data_rows)s </tbody>
1636 </table>"""
1637
1638_legend = """
1639 <table class="diff" summary="Legends">
1640 <tr> <th colspan="2"> Legends </th> </tr>
1641 <tr> <td> <table border="" summary="Colors">
1642 <tr><th> Colors </th> </tr>
1643 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1644 <tr><td class="diff_chg">Changed</td> </tr>
1645 <tr><td class="diff_sub">Deleted</td> </tr>
1646 </table></td>
1647 <td> <table border="" summary="Links">
1648 <tr><th colspan="2"> Links </th> </tr>
1649 <tr><td>(f)irst change</td> </tr>
1650 <tr><td>(n)ext change</td> </tr>
1651 <tr><td>(t)op</td> </tr>
1652 </table></td> </tr>
1653 </table>"""
1654
1655class HtmlDiff(object):
1656 """For producing HTML side by side comparison with change highlights.
1657
1658 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001659 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001660 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001661 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001662
Martin v. Löwise064b412004-08-29 16:34:40 +00001663 The following methods are provided for HTML generation:
1664
1665 make_table -- generates HTML for a single side by side table
1666 make_file -- generates complete HTML file with a single side by side table
1667
Tim Peters48bd7f32004-08-29 22:38:38 +00001668 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001669 """
1670
1671 _file_template = _file_template
1672 _styles = _styles
1673 _table_template = _table_template
1674 _legend = _legend
1675 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001676
Martin v. Löwise064b412004-08-29 16:34:40 +00001677 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1678 charjunk=IS_CHARACTER_JUNK):
1679 """HtmlDiff instance initializer
1680
1681 Arguments:
1682 tabsize -- tab stop spacing, defaults to 8.
1683 wrapcolumn -- column number where lines are broken and wrapped,
1684 defaults to None where lines are not wrapped.
1685 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001686 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001687 ndiff() documentation for argument default values and descriptions.
1688 """
1689 self._tabsize = tabsize
1690 self._wrapcolumn = wrapcolumn
1691 self._linejunk = linejunk
1692 self._charjunk = charjunk
1693
1694 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1695 numlines=5):
1696 """Returns HTML file of side by side comparison with change highlights
1697
1698 Arguments:
1699 fromlines -- list of "from" lines
1700 tolines -- list of "to" lines
1701 fromdesc -- "from" file column header string
1702 todesc -- "to" file column header string
1703 context -- set to True for contextual differences (defaults to False
1704 which shows full differences).
1705 numlines -- number of context lines. When context is set True,
1706 controls number of lines displayed before and after the change.
1707 When context is False, controls the number of lines to place
1708 the "next" link anchors before the next change (so click of
1709 "next" link jumps to just before the change).
1710 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001711
Martin v. Löwise064b412004-08-29 16:34:40 +00001712 return self._file_template % dict(
1713 styles = self._styles,
1714 legend = self._legend,
1715 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1716 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001717
Martin v. Löwise064b412004-08-29 16:34:40 +00001718 def _tab_newline_replace(self,fromlines,tolines):
1719 """Returns from/to line lists with tabs expanded and newlines removed.
1720
1721 Instead of tab characters being replaced by the number of spaces
1722 needed to fill in to the next tab stop, this function will fill
1723 the space with tab characters. This is done so that the difference
1724 algorithms can identify changes in a file when tabs are replaced by
1725 spaces and vice versa. At the end of the HTML generation, the tab
1726 characters will be replaced with a nonbreakable space.
1727 """
1728 def expand_tabs(line):
1729 # hide real spaces
1730 line = line.replace(' ','\0')
1731 # expand tabs into spaces
1732 line = line.expandtabs(self._tabsize)
Ezio Melotti13925002011-03-16 11:05:33 +02001733 # replace spaces from expanded tabs back into tab characters
Martin v. Löwise064b412004-08-29 16:34:40 +00001734 # (we'll replace them with markup after we do differencing)
1735 line = line.replace(' ','\t')
1736 return line.replace('\0',' ').rstrip('\n')
1737 fromlines = [expand_tabs(line) for line in fromlines]
1738 tolines = [expand_tabs(line) for line in tolines]
1739 return fromlines,tolines
1740
1741 def _split_line(self,data_list,line_num,text):
1742 """Builds list of text lines by splitting text lines at wrap point
1743
1744 This function will determine if the input text line needs to be
1745 wrapped (split) into separate lines. If so, the first wrap point
1746 will be determined and the first line appended to the output
1747 text line list. This function is used recursively to handle
1748 the second part of the split line to further split it.
1749 """
1750 # if blank line or context separator, just add it to the output list
1751 if not line_num:
1752 data_list.append((line_num,text))
1753 return
1754
1755 # if line text doesn't need wrapping, just add it to the output list
1756 size = len(text)
1757 max = self._wrapcolumn
1758 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1759 data_list.append((line_num,text))
1760 return
1761
1762 # scan text looking for the wrap point, keeping track if the wrap
1763 # point is inside markers
1764 i = 0
1765 n = 0
1766 mark = ''
1767 while n < max and i < size:
1768 if text[i] == '\0':
1769 i += 1
1770 mark = text[i]
1771 i += 1
1772 elif text[i] == '\1':
1773 i += 1
1774 mark = ''
1775 else:
1776 i += 1
1777 n += 1
1778
1779 # wrap point is inside text, break it up into separate lines
1780 line1 = text[:i]
1781 line2 = text[i:]
1782
1783 # if wrap point is inside markers, place end marker at end of first
1784 # line and start marker at beginning of second line because each
1785 # line will have its own table tag markup around it.
1786 if mark:
1787 line1 = line1 + '\1'
1788 line2 = '\0' + mark + line2
1789
Tim Peters48bd7f32004-08-29 22:38:38 +00001790 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001791 data_list.append((line_num,line1))
1792
Tim Peters48bd7f32004-08-29 22:38:38 +00001793 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001794 self._split_line(data_list,'>',line2)
1795
1796 def _line_wrapper(self,diffs):
1797 """Returns iterator that splits (wraps) mdiff text lines"""
1798
1799 # pull from/to data and flags from mdiff iterator
1800 for fromdata,todata,flag in diffs:
1801 # check for context separators and pass them through
1802 if flag is None:
1803 yield fromdata,todata,flag
1804 continue
1805 (fromline,fromtext),(toline,totext) = fromdata,todata
1806 # for each from/to line split it at the wrap column to form
1807 # list of text lines.
1808 fromlist,tolist = [],[]
1809 self._split_line(fromlist,fromline,fromtext)
1810 self._split_line(tolist,toline,totext)
1811 # yield from/to line in pairs inserting blank lines as
1812 # necessary when one side has more wrapped lines
1813 while fromlist or tolist:
1814 if fromlist:
1815 fromdata = fromlist.pop(0)
1816 else:
1817 fromdata = ('',' ')
1818 if tolist:
1819 todata = tolist.pop(0)
1820 else:
1821 todata = ('',' ')
1822 yield fromdata,todata,flag
1823
1824 def _collect_lines(self,diffs):
1825 """Collects mdiff output into separate lists
1826
1827 Before storing the mdiff from/to data into a list, it is converted
1828 into a single line of text with HTML markup.
1829 """
1830
1831 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001832 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001833 for fromdata,todata,flag in diffs:
1834 try:
1835 # store HTML markup of the lines into the lists
1836 fromlist.append(self._format_line(0,flag,*fromdata))
1837 tolist.append(self._format_line(1,flag,*todata))
1838 except TypeError:
1839 # exceptions occur for lines where context separators go
1840 fromlist.append(None)
1841 tolist.append(None)
1842 flaglist.append(flag)
1843 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001844
Martin v. Löwise064b412004-08-29 16:34:40 +00001845 def _format_line(self,side,flag,linenum,text):
1846 """Returns HTML markup of "from" / "to" text lines
1847
1848 side -- 0 or 1 indicating "from" or "to" text
1849 flag -- indicates if difference on line
1850 linenum -- line number (used for line number column)
1851 text -- line text to be marked up
1852 """
1853 try:
1854 linenum = '%d' % linenum
1855 id = ' id="%s%s"' % (self._prefix[side],linenum)
1856 except TypeError:
1857 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001858 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001859 # replace those things that would get confused with HTML symbols
1860 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1861
1862 # make space non-breakable so they don't get compressed or line wrapped
1863 text = text.replace(' ','&nbsp;').rstrip()
1864
1865 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1866 % (id,linenum,text)
1867
1868 def _make_prefix(self):
1869 """Create unique anchor prefixes"""
1870
1871 # Generate a unique anchor prefix so multiple tables
1872 # can exist on the same HTML page without conflicts.
1873 fromprefix = "from%d_" % HtmlDiff._default_prefix
1874 toprefix = "to%d_" % HtmlDiff._default_prefix
1875 HtmlDiff._default_prefix += 1
1876 # store prefixes so line format method has access
1877 self._prefix = [fromprefix,toprefix]
1878
1879 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1880 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001881
Martin v. Löwise064b412004-08-29 16:34:40 +00001882 # all anchor names will be generated using the unique "to" prefix
1883 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001884
Martin v. Löwise064b412004-08-29 16:34:40 +00001885 # process change flags, generating middle column of next anchors/links
1886 next_id = ['']*len(flaglist)
1887 next_href = ['']*len(flaglist)
1888 num_chg, in_change = 0, False
1889 last = 0
1890 for i,flag in enumerate(flaglist):
1891 if flag:
1892 if not in_change:
1893 in_change = True
1894 last = i
1895 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001896 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001897 # link
1898 i = max([0,i-numlines])
1899 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001900 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001901 # change
1902 num_chg += 1
1903 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1904 toprefix,num_chg)
1905 else:
1906 in_change = False
1907 # check for cases where there is no content to avoid exceptions
1908 if not flaglist:
1909 flaglist = [False]
1910 next_id = ['']
1911 next_href = ['']
1912 last = 0
1913 if context:
1914 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1915 tolist = fromlist
1916 else:
1917 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1918 # if not a change on first line, drop a link
1919 if not flaglist[0]:
1920 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1921 # redo the last link to link to the top
1922 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1923
1924 return fromlist,tolist,flaglist,next_href,next_id
1925
1926 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1927 numlines=5):
1928 """Returns HTML table of side by side comparison with change highlights
1929
1930 Arguments:
1931 fromlines -- list of "from" lines
1932 tolines -- list of "to" lines
1933 fromdesc -- "from" file column header string
1934 todesc -- "to" file column header string
1935 context -- set to True for contextual differences (defaults to False
1936 which shows full differences).
1937 numlines -- number of context lines. When context is set True,
1938 controls number of lines displayed before and after the change.
1939 When context is False, controls the number of lines to place
1940 the "next" link anchors before the next change (so click of
1941 "next" link jumps to just before the change).
1942 """
1943
1944 # make unique anchor prefixes so that multiple tables may exist
1945 # on the same page without conflict.
1946 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001947
Martin v. Löwise064b412004-08-29 16:34:40 +00001948 # change tabs to spaces before it gets more difficult after we insert
1949 # markkup
1950 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001951
Martin v. Löwise064b412004-08-29 16:34:40 +00001952 # create diffs iterator which generates side by side from/to data
1953 if context:
1954 context_lines = numlines
1955 else:
1956 context_lines = None
1957 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1958 charjunk=self._charjunk)
1959
1960 # set up iterator to wrap lines that exceed desired width
1961 if self._wrapcolumn:
1962 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001963
Martin v. Löwise064b412004-08-29 16:34:40 +00001964 # collect up from/to lines and flags into lists (also format the lines)
1965 fromlist,tolist,flaglist = self._collect_lines(diffs)
1966
1967 # process change flags, generating middle column of next anchors/links
1968 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1969 fromlist,tolist,flaglist,context,numlines)
1970
Guido van Rossumd8faa362007-04-27 19:54:29 +00001971 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00001972 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1973 '<td class="diff_next">%s</td>%s</tr>\n'
1974 for i in range(len(flaglist)):
1975 if flaglist[i] is None:
1976 # mdiff yields None on separator lines skip the bogus ones
1977 # generated for the first line
1978 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001979 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00001980 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001981 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00001982 next_href[i],tolist[i]))
1983 if fromdesc or todesc:
1984 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
1985 '<th class="diff_next"><br /></th>',
1986 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
1987 '<th class="diff_next"><br /></th>',
1988 '<th colspan="2" class="diff_header">%s</th>' % todesc)
1989 else:
1990 header_row = ''
1991
1992 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00001993 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00001994 header_row=header_row,
1995 prefix=self._prefix[1])
1996
1997 return table.replace('\0+','<span class="diff_add">'). \
1998 replace('\0-','<span class="diff_sub">'). \
1999 replace('\0^','<span class="diff_chg">'). \
2000 replace('\1','</span>'). \
2001 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00002002
Martin v. Löwise064b412004-08-29 16:34:40 +00002003del re
2004
Tim Peters5e824c32001-08-12 22:25:01 +00002005def restore(delta, which):
2006 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00002007 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00002008
2009 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
2010 lines originating from file 1 or 2 (parameter `which`), stripping off line
2011 prefixes.
2012
2013 Examples:
2014
Ezio Melottid8b509b2011-09-28 17:37:55 +03002015 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
2016 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Tim Peters8a9c2842001-09-22 21:30:22 +00002017 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002018 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002019 one
2020 two
2021 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002022 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002023 ore
2024 tree
2025 emu
2026 """
2027 try:
2028 tag = {1: "- ", 2: "+ "}[int(which)]
2029 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002030 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Tim Peters5e824c32001-08-12 22:25:01 +00002031 % which)
2032 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002033 for line in delta:
2034 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002035 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002036
Tim Peters9ae21482001-02-10 08:00:53 +00002037def _test():
2038 import doctest, difflib
2039 return doctest.testmod(difflib)
2040
2041if __name__ == "__main__":
2042 _test()