blob: a1c5ec0421c9f2c4d23e3db888a87786a3483715 [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>.
207 # DON'T USE! Only __chain_b uses this. Use isbjunk.
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 ...
290 # also creates the fast isbjunk function ...
Tim Peters81b92512002-04-29 01:37:32 +0000291 # b2j also does not contain entries for "popular" elements, meaning
Terry Reedy99f96372010-11-25 06:12:34 +0000292 # elements that account for more than 1 + 1% of the total elements, and
Tim Peters81b92512002-04-29 01:37:32 +0000293 # when the sequence is reasonably large (>= 200 elements); this can
294 # be viewed as an adaptive notion of semi-junk, and yields an enormous
295 # speedup when, e.g., comparing program files with hundreds of
296 # instances of "return NULL;" ...
Tim Peters9ae21482001-02-10 08:00:53 +0000297 # note that this is only called when b changes; so for cross-product
298 # kinds of matches, it's best to call set_seq2 once, then set_seq1
299 # repeatedly
300
301 def __chain_b(self):
302 # Because isjunk is a user-defined (not C) function, and we test
303 # for junk a LOT, it's important to minimize the number of calls.
304 # Before the tricks described here, __chain_b was by far the most
305 # time-consuming routine in the whole module! If anyone sees
306 # Jim Roskind, thank him again for profile.py -- I never would
307 # have guessed that.
308 # The first trick is to build b2j ignoring the possibility
309 # of junk. I.e., we don't call isjunk at all yet. Throwing
310 # out the junk later is much cheaper than building b2j "right"
311 # from the start.
312 b = self.b
313 self.b2j = b2j = {}
Terry Reedy99f96372010-11-25 06:12:34 +0000314
Tim Peters81b92512002-04-29 01:37:32 +0000315 for i, elt in enumerate(b):
Terry Reedy99f96372010-11-25 06:12:34 +0000316 indices = b2j.setdefault(elt, [])
317 indices.append(i)
Tim Peters9ae21482001-02-10 08:00:53 +0000318
Terry Reedy99f96372010-11-25 06:12:34 +0000319 # Purge junk elements
Terry Reedy74a7c672010-12-03 18:57:42 +0000320 self.bjunk = junk = set()
Tim Peters81b92512002-04-29 01:37:32 +0000321 isjunk = self.isjunk
Tim Peters9ae21482001-02-10 08:00:53 +0000322 if isjunk:
Terry Reedy99f96372010-11-25 06:12:34 +0000323 for elt in list(b2j.keys()): # using list() since b2j is modified
324 if isjunk(elt):
325 junk.add(elt)
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
333 for elt, idxs in list(b2j.items()):
334 if len(idxs) > ntest:
335 popular.add(elt)
336 del b2j[elt]
337
Terry Reedybcd89882010-12-03 22:29:40 +0000338 def isbjunk(self, item):
339 "Deprecated; use 'item in SequenceMatcher().bjunk'."
340 warnings.warn("'SequenceMatcher().isbjunk(item)' is deprecated;\n"
341 "use 'item in SMinstance.bjunk' instead.",
342 DeprecationWarning, 2)
343 return item in self.bjunk
344
345 def isbpopular(self, item):
346 "Deprecated; use 'item in SequenceMatcher().bpopular'."
347 warnings.warn("'SequenceMatcher().isbpopular(item)' is deprecated;\n"
348 "use 'item in SMinstance.bpopular' instead.",
349 DeprecationWarning, 2)
350 return item in self.bpopular
Tim Peters9ae21482001-02-10 08:00:53 +0000351
352 def find_longest_match(self, alo, ahi, blo, bhi):
353 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
354
355 If isjunk is not defined:
356
357 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
358 alo <= i <= i+k <= ahi
359 blo <= j <= j+k <= bhi
360 and for all (i',j',k') meeting those conditions,
361 k >= k'
362 i <= i'
363 and if i == i', j <= j'
364
365 In other words, of all maximal matching blocks, return one that
366 starts earliest in a, and of all those maximal matching blocks that
367 start earliest in a, return the one that starts earliest in b.
368
369 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
370 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000371 Match(a=0, b=4, size=5)
Tim Peters9ae21482001-02-10 08:00:53 +0000372
373 If isjunk is defined, first the longest matching block is
374 determined as above, but with the additional restriction that no
375 junk element appears in the block. Then that block is extended as
376 far as possible by matching (only) junk elements on both sides. So
377 the resulting block never matches on junk except as identical junk
378 happens to be adjacent to an "interesting" match.
379
380 Here's the same example as before, but considering blanks to be
381 junk. That prevents " abcd" from matching the " abcd" at the tail
382 end of the second sequence directly. Instead only the "abcd" can
383 match, and matches the leftmost "abcd" in the second sequence:
384
385 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
386 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000387 Match(a=1, b=0, size=4)
Tim Peters9ae21482001-02-10 08:00:53 +0000388
389 If no blocks match, return (alo, blo, 0).
390
391 >>> s = SequenceMatcher(None, "ab", "c")
392 >>> s.find_longest_match(0, 2, 0, 1)
Christian Heimes25bb7832008-01-11 16:17:00 +0000393 Match(a=0, b=0, size=0)
Tim Peters9ae21482001-02-10 08:00:53 +0000394 """
395
396 # CAUTION: stripping common prefix or suffix would be incorrect.
397 # E.g.,
398 # ab
399 # acab
400 # Longest matching block is "ab", but if common prefix is
401 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
402 # strip, so ends up claiming that ab is changed to acab by
403 # inserting "ca" in the middle. That's minimal but unintuitive:
404 # "it's obvious" that someone inserted "ac" at the front.
405 # Windiff ends up at the same place as diff, but by pairing up
406 # the unique 'b's and then matching the first two 'a's.
407
Terry Reedybcd89882010-12-03 22:29:40 +0000408 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000409 besti, bestj, bestsize = alo, blo, 0
410 # find longest junk-free match
411 # during an iteration of the loop, j2len[j] = length of longest
412 # junk-free match ending with a[i-1] and b[j]
413 j2len = {}
414 nothing = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000415 for i in range(alo, ahi):
Tim Peters9ae21482001-02-10 08:00:53 +0000416 # look at all instances of a[i] in b; note that because
417 # b2j has no junk keys, the loop is skipped if a[i] is junk
418 j2lenget = j2len.get
419 newj2len = {}
420 for j in b2j.get(a[i], nothing):
421 # a[i] matches b[j]
422 if j < blo:
423 continue
424 if j >= bhi:
425 break
426 k = newj2len[j] = j2lenget(j-1, 0) + 1
427 if k > bestsize:
428 besti, bestj, bestsize = i-k+1, j-k+1, k
429 j2len = newj2len
430
Tim Peters81b92512002-04-29 01:37:32 +0000431 # Extend the best by non-junk elements on each end. In particular,
432 # "popular" non-junk elements aren't in b2j, which greatly speeds
433 # the inner loop above, but also means "the best" match so far
434 # doesn't contain any junk *or* popular non-junk elements.
435 while besti > alo and bestj > blo and \
436 not isbjunk(b[bestj-1]) and \
437 a[besti-1] == b[bestj-1]:
438 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
439 while besti+bestsize < ahi and bestj+bestsize < bhi and \
440 not isbjunk(b[bestj+bestsize]) and \
441 a[besti+bestsize] == b[bestj+bestsize]:
442 bestsize += 1
443
Tim Peters9ae21482001-02-10 08:00:53 +0000444 # Now that we have a wholly interesting match (albeit possibly
445 # empty!), we may as well suck up the matching junk on each
446 # side of it too. Can't think of a good reason not to, and it
447 # saves post-processing the (possibly considerable) expense of
448 # figuring out what to do with it. In the case of an empty
449 # interesting match, this is clearly the right thing to do,
450 # because no other kind of match is possible in the regions.
451 while besti > alo and bestj > blo and \
452 isbjunk(b[bestj-1]) and \
453 a[besti-1] == b[bestj-1]:
454 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
455 while besti+bestsize < ahi and bestj+bestsize < bhi and \
456 isbjunk(b[bestj+bestsize]) and \
457 a[besti+bestsize] == b[bestj+bestsize]:
458 bestsize = bestsize + 1
459
Christian Heimes25bb7832008-01-11 16:17:00 +0000460 return Match(besti, bestj, bestsize)
Tim Peters9ae21482001-02-10 08:00:53 +0000461
462 def get_matching_blocks(self):
463 """Return list of triples describing matching subsequences.
464
465 Each triple is of the form (i, j, n), and means that
466 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000467 i and in j. New in Python 2.5, it's also guaranteed that if
468 (i, j, n) and (i', j', n') are adjacent triples in the list, and
469 the second is not the last triple in the list, then i+n != i' or
470 j+n != j'. IOW, adjacent triples never describe adjacent equal
471 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000472
473 The last triple is a dummy, (len(a), len(b), 0), and is the only
474 triple with n==0.
475
476 >>> s = SequenceMatcher(None, "abxcd", "abcd")
Christian Heimes25bb7832008-01-11 16:17:00 +0000477 >>> list(s.get_matching_blocks())
478 [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 +0000479 """
480
481 if self.matching_blocks is not None:
482 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000483 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000484
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000485 # This is most naturally expressed as a recursive algorithm, but
486 # at least one user bumped into extreme use cases that exceeded
487 # the recursion limit on their box. So, now we maintain a list
488 # ('queue`) of blocks we still need to look at, and append partial
489 # results to `matching_blocks` in a loop; the matches are sorted
490 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000491 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000492 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000493 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000494 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000495 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000496 # a[alo:i] vs b[blo:j] unknown
497 # a[i:i+k] same as b[j:j+k]
498 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000499 if k: # if k is 0, there was no matching block
500 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000501 if alo < i and blo < j:
502 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000503 if i+k < ahi and j+k < bhi:
504 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000505 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000506
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000507 # It's possible that we have adjacent equal blocks in the
508 # matching_blocks list now. Starting with 2.5, this code was added
509 # to collapse them.
510 i1 = j1 = k1 = 0
511 non_adjacent = []
512 for i2, j2, k2 in matching_blocks:
513 # Is this block adjacent to i1, j1, k1?
514 if i1 + k1 == i2 and j1 + k1 == j2:
515 # Yes, so collapse them -- this just increases the length of
516 # the first block by the length of the second, and the first
517 # block so lengthened remains the block to compare against.
518 k1 += k2
519 else:
520 # Not adjacent. Remember the first block (k1==0 means it's
521 # the dummy we started with), and make the second block the
522 # new block to compare against.
523 if k1:
524 non_adjacent.append((i1, j1, k1))
525 i1, j1, k1 = i2, j2, k2
526 if k1:
527 non_adjacent.append((i1, j1, k1))
528
529 non_adjacent.append( (la, lb, 0) )
530 self.matching_blocks = non_adjacent
Christian Heimes25bb7832008-01-11 16:17:00 +0000531 return map(Match._make, self.matching_blocks)
Tim Peters9ae21482001-02-10 08:00:53 +0000532
Tim Peters9ae21482001-02-10 08:00:53 +0000533 def get_opcodes(self):
534 """Return list of 5-tuples describing how to turn a into b.
535
536 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
537 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
538 tuple preceding it, and likewise for j1 == the previous j2.
539
540 The tags are strings, with these meanings:
541
542 'replace': a[i1:i2] should be replaced by b[j1:j2]
543 'delete': a[i1:i2] should be deleted.
544 Note that j1==j2 in this case.
545 'insert': b[j1:j2] should be inserted at a[i1:i1].
546 Note that i1==i2 in this case.
547 'equal': a[i1:i2] == b[j1:j2]
548
549 >>> a = "qabxcd"
550 >>> b = "abycdf"
551 >>> s = SequenceMatcher(None, a, b)
552 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000553 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
554 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000555 delete a[0:1] (q) b[0:0] ()
556 equal a[1:3] (ab) b[0:2] (ab)
557 replace a[3:4] (x) b[2:3] (y)
558 equal a[4:6] (cd) b[3:5] (cd)
559 insert a[6:6] () b[5:6] (f)
560 """
561
562 if self.opcodes is not None:
563 return self.opcodes
564 i = j = 0
565 self.opcodes = answer = []
566 for ai, bj, size in self.get_matching_blocks():
567 # invariant: we've pumped out correct diffs to change
568 # a[:i] into b[:j], and the next matching block is
569 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
570 # out a diff to change a[i:ai] into b[j:bj], pump out
571 # the matching block, and move (i,j) beyond the match
572 tag = ''
573 if i < ai and j < bj:
574 tag = 'replace'
575 elif i < ai:
576 tag = 'delete'
577 elif j < bj:
578 tag = 'insert'
579 if tag:
580 answer.append( (tag, i, ai, j, bj) )
581 i, j = ai+size, bj+size
582 # the list of matching blocks is terminated by a
583 # sentinel with size 0
584 if size:
585 answer.append( ('equal', ai, i, bj, j) )
586 return answer
587
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000588 def get_grouped_opcodes(self, n=3):
589 """ Isolate change clusters by eliminating ranges with no changes.
590
591 Return a generator of groups with upto n lines of context.
592 Each group is in the same format as returned by get_opcodes().
593
594 >>> from pprint import pprint
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000595 >>> a = list(map(str, range(1,40)))
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000596 >>> b = a[:]
597 >>> b[8:8] = ['i'] # Make an insertion
598 >>> b[20] += 'x' # Make a replacement
599 >>> b[23:28] = [] # Make a deletion
600 >>> b[30] += 'y' # Make another replacement
601 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
602 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
603 [('equal', 16, 19, 17, 20),
604 ('replace', 19, 20, 20, 21),
605 ('equal', 20, 22, 21, 23),
606 ('delete', 22, 27, 23, 23),
607 ('equal', 27, 30, 23, 26)],
608 [('equal', 31, 34, 27, 30),
609 ('replace', 34, 35, 30, 31),
610 ('equal', 35, 38, 31, 34)]]
611 """
612
613 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000614 if not codes:
615 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000616 # Fixup leading and trailing groups if they show no changes.
617 if codes[0][0] == 'equal':
618 tag, i1, i2, j1, j2 = codes[0]
619 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
620 if codes[-1][0] == 'equal':
621 tag, i1, i2, j1, j2 = codes[-1]
622 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
623
624 nn = n + n
625 group = []
626 for tag, i1, i2, j1, j2 in codes:
627 # End the current group and start a new one whenever
628 # there is a large range with no changes.
629 if tag == 'equal' and i2-i1 > nn:
630 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
631 yield group
632 group = []
633 i1, j1 = max(i1, i2-n), max(j1, j2-n)
634 group.append((tag, i1, i2, j1 ,j2))
635 if group and not (len(group)==1 and group[0][0] == 'equal'):
636 yield group
637
Tim Peters9ae21482001-02-10 08:00:53 +0000638 def ratio(self):
639 """Return a measure of the sequences' similarity (float in [0,1]).
640
641 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000642 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000643 Note that this is 1 if the sequences are identical, and 0 if
644 they have nothing in common.
645
646 .ratio() is expensive to compute if you haven't already computed
647 .get_matching_blocks() or .get_opcodes(), in which case you may
648 want to try .quick_ratio() or .real_quick_ratio() first to get an
649 upper bound.
650
651 >>> s = SequenceMatcher(None, "abcd", "bcde")
652 >>> s.ratio()
653 0.75
654 >>> s.quick_ratio()
655 0.75
656 >>> s.real_quick_ratio()
657 1.0
658 """
659
Guido van Rossum89da5d72006-08-22 00:21:25 +0000660 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000661 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000662
663 def quick_ratio(self):
664 """Return an upper bound on ratio() relatively quickly.
665
666 This isn't defined beyond that it is an upper bound on .ratio(), and
667 is faster to compute.
668 """
669
670 # viewing a and b as multisets, set matches to the cardinality
671 # of their intersection; this counts the number of matches
672 # without regard to order, so is clearly an upper bound
673 if self.fullbcount is None:
674 self.fullbcount = fullbcount = {}
675 for elt in self.b:
676 fullbcount[elt] = fullbcount.get(elt, 0) + 1
677 fullbcount = self.fullbcount
678 # avail[x] is the number of times x appears in 'b' less the
679 # number of times we've seen it in 'a' so far ... kinda
680 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000681 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000682 for elt in self.a:
683 if availhas(elt):
684 numb = avail[elt]
685 else:
686 numb = fullbcount.get(elt, 0)
687 avail[elt] = numb - 1
688 if numb > 0:
689 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000690 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000691
692 def real_quick_ratio(self):
693 """Return an upper bound on ratio() very quickly.
694
695 This isn't defined beyond that it is an upper bound on .ratio(), and
696 is faster to compute than either .ratio() or .quick_ratio().
697 """
698
699 la, lb = len(self.a), len(self.b)
700 # can't have more matches than the number of elements in the
701 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000702 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000703
704def get_close_matches(word, possibilities, n=3, cutoff=0.6):
705 """Use SequenceMatcher to return list of the best "good enough" matches.
706
707 word is a sequence for which close matches are desired (typically a
708 string).
709
710 possibilities is a list of sequences against which to match word
711 (typically a list of strings).
712
713 Optional arg n (default 3) is the maximum number of close matches to
714 return. n must be > 0.
715
716 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
717 that don't score at least that similar to word are ignored.
718
719 The best (no more than n) matches among the possibilities are returned
720 in a list, sorted by similarity score, most similar first.
721
722 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
723 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000724 >>> import keyword as _keyword
725 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000726 ['while']
Guido van Rossum486364b2007-06-30 05:01:58 +0000727 >>> get_close_matches("Apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000728 []
Tim Peters5e824c32001-08-12 22:25:01 +0000729 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000730 ['except']
731 """
732
733 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000734 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000735 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000736 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000737 result = []
738 s = SequenceMatcher()
739 s.set_seq2(word)
740 for x in possibilities:
741 s.set_seq1(x)
742 if s.real_quick_ratio() >= cutoff and \
743 s.quick_ratio() >= cutoff and \
744 s.ratio() >= cutoff:
745 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000746
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000747 # Move the best scorers to head of list
Raymond Hettingeraefde432004-06-15 23:53:35 +0000748 result = heapq.nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000749 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000750 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000751
752def _count_leading(line, ch):
753 """
754 Return number of `ch` characters at the start of `line`.
755
756 Example:
757
758 >>> _count_leading(' abc', ' ')
759 3
760 """
761
762 i, n = 0, len(line)
763 while i < n and line[i] == ch:
764 i += 1
765 return i
766
767class Differ:
768 r"""
769 Differ is a class for comparing sequences of lines of text, and
770 producing human-readable differences or deltas. Differ uses
771 SequenceMatcher both to compare sequences of lines, and to compare
772 sequences of characters within similar (near-matching) lines.
773
774 Each line of a Differ delta begins with a two-letter code:
775
776 '- ' line unique to sequence 1
777 '+ ' line unique to sequence 2
778 ' ' line common to both sequences
779 '? ' line not present in either input sequence
780
781 Lines beginning with '? ' attempt to guide the eye to intraline
782 differences, and were not present in either input sequence. These lines
783 can be confusing if the sequences contain tab characters.
784
785 Note that Differ makes no claim to produce a *minimal* diff. To the
786 contrary, minimal diffs are often counter-intuitive, because they synch
787 up anywhere possible, sometimes accidental matches 100 pages apart.
788 Restricting synch points to contiguous matches preserves some notion of
789 locality, at the occasional cost of producing a longer diff.
790
791 Example: Comparing two texts.
792
793 First we set up the texts, sequences of individual single-line strings
794 ending with newlines (such sequences can also be obtained from the
795 `readlines()` method of file-like objects):
796
797 >>> text1 = ''' 1. Beautiful is better than ugly.
798 ... 2. Explicit is better than implicit.
799 ... 3. Simple is better than complex.
800 ... 4. Complex is better than complicated.
801 ... '''.splitlines(1)
802 >>> len(text1)
803 4
804 >>> text1[0][-1]
805 '\n'
806 >>> text2 = ''' 1. Beautiful is better than ugly.
807 ... 3. Simple is better than complex.
808 ... 4. Complicated is better than complex.
809 ... 5. Flat is better than nested.
810 ... '''.splitlines(1)
811
812 Next we instantiate a Differ object:
813
814 >>> d = Differ()
815
816 Note that when instantiating a Differ object we may pass functions to
817 filter out line and character 'junk'. See Differ.__init__ for details.
818
819 Finally, we compare the two:
820
Tim Peters8a9c2842001-09-22 21:30:22 +0000821 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000822
823 'result' is a list of strings, so let's pretty-print it:
824
825 >>> from pprint import pprint as _pprint
826 >>> _pprint(result)
827 [' 1. Beautiful is better than ugly.\n',
828 '- 2. Explicit is better than implicit.\n',
829 '- 3. Simple is better than complex.\n',
830 '+ 3. Simple is better than complex.\n',
831 '? ++\n',
832 '- 4. Complex is better than complicated.\n',
833 '? ^ ---- ^\n',
834 '+ 4. Complicated is better than complex.\n',
835 '? ++++ ^ ^\n',
836 '+ 5. Flat is better than nested.\n']
837
838 As a single multi-line string it looks like this:
839
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000840 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000841 1. Beautiful is better than ugly.
842 - 2. Explicit is better than implicit.
843 - 3. Simple is better than complex.
844 + 3. Simple is better than complex.
845 ? ++
846 - 4. Complex is better than complicated.
847 ? ^ ---- ^
848 + 4. Complicated is better than complex.
849 ? ++++ ^ ^
850 + 5. Flat is better than nested.
851
852 Methods:
853
854 __init__(linejunk=None, charjunk=None)
855 Construct a text differencer, with optional filters.
856
857 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000858 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000859 """
860
861 def __init__(self, linejunk=None, charjunk=None):
862 """
863 Construct a text differencer, with optional filters.
864
865 The two optional keyword parameters are for filter functions:
866
867 - `linejunk`: A function that should accept a single string argument,
868 and return true iff the string is junk. The module-level function
869 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000870 characters, except for at most one splat ('#'). It is recommended
871 to leave linejunk None; as of Python 2.3, the underlying
872 SequenceMatcher class has grown an adaptive notion of "noise" lines
873 that's better than any static definition the author has ever been
874 able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000875
876 - `charjunk`: A function that should accept a string of length 1. The
877 module-level function `IS_CHARACTER_JUNK` may be used to filter out
878 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000879 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000880 """
881
882 self.linejunk = linejunk
883 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000884
885 def compare(self, a, b):
886 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000887 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000888
889 Each sequence must contain individual single-line strings ending with
890 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000891 of file-like objects. The delta generated also consists of newline-
892 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000893 method of a file-like object.
894
895 Example:
896
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000897 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
Tim Peters5e824c32001-08-12 22:25:01 +0000898 ... 'ore\ntree\nemu\n'.splitlines(1))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000899 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000900 - one
901 ? ^
902 + ore
903 ? ^
904 - two
905 - three
906 ? -
907 + tree
908 + emu
909 """
910
911 cruncher = SequenceMatcher(self.linejunk, a, b)
912 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
913 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000914 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000915 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000916 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000917 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000918 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000919 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000920 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000921 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000922 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +0000923
924 for line in g:
925 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000926
927 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000928 """Generate comparison results for a same-tagged range."""
Guido van Rossum805365e2007-05-07 22:24:25 +0000929 for i in range(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000930 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000931
932 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
933 assert alo < ahi and blo < bhi
934 # dump the shorter block first -- reduces the burden on short-term
935 # memory if the blocks are of very different sizes
936 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000937 first = self._dump('+', b, blo, bhi)
938 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000939 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000940 first = self._dump('-', a, alo, ahi)
941 second = self._dump('+', b, blo, bhi)
942
943 for g in first, second:
944 for line in g:
945 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000946
947 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
948 r"""
949 When replacing one block of lines with another, search the blocks
950 for *similar* lines; the best-matching pair (if any) is used as a
951 synch point, and intraline difference marking is done on the
952 similar pair. Lots of work, but often worth it.
953
954 Example:
955
956 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000957 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
958 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000959 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000960 - abcDefghiJkl
961 ? ^ ^ ^
962 + abcdefGhijkl
963 ? ^ ^ ^
964 """
965
Tim Peters5e824c32001-08-12 22:25:01 +0000966 # don't synch up unless the lines have a similarity score of at
967 # least cutoff; best_ratio tracks the best score seen so far
968 best_ratio, cutoff = 0.74, 0.75
969 cruncher = SequenceMatcher(self.charjunk)
970 eqi, eqj = None, None # 1st indices of equal lines (if any)
971
972 # search for the pair that matches best without being identical
973 # (identical lines must be junk lines, & we don't want to synch up
974 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000975 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000976 bj = b[j]
977 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000978 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000979 ai = a[i]
980 if ai == bj:
981 if eqi is None:
982 eqi, eqj = i, j
983 continue
984 cruncher.set_seq1(ai)
985 # computing similarity is expensive, so use the quick
986 # upper bounds first -- have seen this speed up messy
987 # compares by a factor of 3.
988 # note that ratio() is only expensive to compute the first
989 # time it's called on a sequence pair; the expensive part
990 # of the computation is cached by cruncher
991 if cruncher.real_quick_ratio() > best_ratio and \
992 cruncher.quick_ratio() > best_ratio and \
993 cruncher.ratio() > best_ratio:
994 best_ratio, best_i, best_j = cruncher.ratio(), i, j
995 if best_ratio < cutoff:
996 # no non-identical "pretty close" pair
997 if eqi is None:
998 # no identical pair either -- treat it as a straight replace
Tim Peters8a9c2842001-09-22 21:30:22 +0000999 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
1000 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001001 return
1002 # no close pair, but an identical pair -- synch up on that
1003 best_i, best_j, best_ratio = eqi, eqj, 1.0
1004 else:
1005 # there's a close pair, so forget the identical pair (if any)
1006 eqi = None
1007
1008 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
1009 # identical
Tim Peters5e824c32001-08-12 22:25:01 +00001010
1011 # pump out diffs from before the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001012 for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
1013 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001014
1015 # do intraline marking on the synch pair
1016 aelt, belt = a[best_i], b[best_j]
1017 if eqi is None:
1018 # pump out a '-', '?', '+', '?' quad for the synched lines
1019 atags = btags = ""
1020 cruncher.set_seqs(aelt, belt)
1021 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1022 la, lb = ai2 - ai1, bj2 - bj1
1023 if tag == 'replace':
1024 atags += '^' * la
1025 btags += '^' * lb
1026 elif tag == 'delete':
1027 atags += '-' * la
1028 elif tag == 'insert':
1029 btags += '+' * lb
1030 elif tag == 'equal':
1031 atags += ' ' * la
1032 btags += ' ' * lb
1033 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001034 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +00001035 for line in self._qformat(aelt, belt, atags, btags):
1036 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001037 else:
1038 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001039 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001040
1041 # pump out diffs from after the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001042 for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
1043 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001044
1045 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001046 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001047 if alo < ahi:
1048 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001049 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001050 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001051 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001052 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001053 g = self._dump('+', b, blo, bhi)
1054
1055 for line in g:
1056 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001057
1058 def _qformat(self, aline, bline, atags, btags):
1059 r"""
1060 Format "?" output and deal with leading tabs.
1061
1062 Example:
1063
1064 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001065 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1066 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001067 >>> for line in results: print(repr(line))
1068 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001069 '- \tabcDefghiJkl\n'
1070 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001071 '+ \tabcdefGhijkl\n'
1072 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001073 """
1074
1075 # Can hurt, but will probably help most of the time.
1076 common = min(_count_leading(aline, "\t"),
1077 _count_leading(bline, "\t"))
1078 common = min(common, _count_leading(atags[:common], " "))
Senthil Kumaran758025c2009-11-23 19:02:52 +00001079 common = min(common, _count_leading(btags[:common], " "))
Tim Peters5e824c32001-08-12 22:25:01 +00001080 atags = atags[common:].rstrip()
1081 btags = btags[common:].rstrip()
1082
Tim Peters8a9c2842001-09-22 21:30:22 +00001083 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001084 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001085 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001086
Tim Peters8a9c2842001-09-22 21:30:22 +00001087 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001088 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001089 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001090
1091# With respect to junk, an earlier version of ndiff simply refused to
1092# *start* a match with a junk element. The result was cases like this:
1093# before: private Thread currentThread;
1094# after: private volatile Thread currentThread;
1095# If you consider whitespace to be junk, the longest contiguous match
1096# not starting with junk is "e Thread currentThread". So ndiff reported
1097# that "e volatil" was inserted between the 't' and the 'e' in "private".
1098# While an accurate view, to people that's absurd. The current version
1099# looks for matching blocks that are entirely junk-free, then extends the
1100# longest one of those as far as possible but only with matching junk.
1101# So now "currentThread" is matched, then extended to suck up the
1102# preceding blank; then "private" is matched, and extended to suck up the
1103# following blank; then "Thread" is matched; and finally ndiff reports
1104# that "volatile " was inserted before "Thread". The only quibble
1105# remaining is that perhaps it was really the case that " volatile"
1106# was inserted after "private". I can live with that <wink>.
1107
1108import re
1109
1110def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1111 r"""
1112 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1113
1114 Examples:
1115
1116 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001117 True
Tim Peters5e824c32001-08-12 22:25:01 +00001118 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001119 True
Tim Peters5e824c32001-08-12 22:25:01 +00001120 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001121 False
Tim Peters5e824c32001-08-12 22:25:01 +00001122 """
1123
1124 return pat(line) is not None
1125
1126def IS_CHARACTER_JUNK(ch, ws=" \t"):
1127 r"""
1128 Return 1 for ignorable character: iff `ch` is a space or tab.
1129
1130 Examples:
1131
1132 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001133 True
Tim Peters5e824c32001-08-12 22:25:01 +00001134 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001135 True
Tim Peters5e824c32001-08-12 22:25:01 +00001136 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001137 False
Tim Peters5e824c32001-08-12 22:25:01 +00001138 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001139 False
Tim Peters5e824c32001-08-12 22:25:01 +00001140 """
1141
1142 return ch in ws
1143
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001144
1145def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1146 tofiledate='', n=3, lineterm='\n'):
1147 r"""
1148 Compare two sequences of lines; generate the delta as a unified diff.
1149
1150 Unified diffs are a compact way of showing line changes and a few
1151 lines of context. The number of context lines is set by 'n' which
1152 defaults to three.
1153
Raymond Hettinger0887c732003-06-17 16:53:25 +00001154 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001155 created with a trailing newline. This is helpful so that inputs
1156 created from file.readlines() result in diffs that are suitable for
1157 file.writelines() since both the inputs and outputs have trailing
1158 newlines.
1159
1160 For inputs that do not have trailing newlines, set the lineterm
1161 argument to "" so that the output will be uniformly newline free.
1162
1163 The unidiff format normally has a header for filenames and modification
1164 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001165 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1166 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001167
1168 Example:
1169
1170 >>> for line in unified_diff('one two three four'.split(),
1171 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001172 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001173 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001174 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1175 --- Original 2005-01-26 23:30:50
1176 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001177 @@ -1,4 +1,4 @@
1178 +zero
1179 one
1180 -two
1181 -three
1182 +tree
1183 four
1184 """
1185
1186 started = False
1187 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1188 if not started:
R. David Murrayb2416e52010-04-12 16:58:02 +00001189 fromdate = '\t%s' % fromfiledate if fromfiledate else ''
1190 todate = '\t%s' % tofiledate if tofiledate else ''
1191 yield '--- %s%s%s' % (fromfile, fromdate, lineterm)
1192 yield '+++ %s%s%s' % (tofile, todate, lineterm)
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001193 started = True
1194 i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
1195 yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
1196 for tag, i1, i2, j1, j2 in group:
1197 if tag == 'equal':
1198 for line in a[i1:i2]:
1199 yield ' ' + line
1200 continue
1201 if tag == 'replace' or tag == 'delete':
1202 for line in a[i1:i2]:
1203 yield '-' + line
1204 if tag == 'replace' or tag == 'insert':
1205 for line in b[j1:j2]:
1206 yield '+' + line
1207
1208# See http://www.unix.org/single_unix_specification/
1209def context_diff(a, b, fromfile='', tofile='',
1210 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1211 r"""
1212 Compare two sequences of lines; generate the delta as a context diff.
1213
1214 Context diffs are a compact way of showing line changes and a few
1215 lines of context. The number of context lines is set by 'n' which
1216 defaults to three.
1217
1218 By default, the diff control lines (those with *** or ---) are
1219 created with a trailing newline. This is helpful so that inputs
1220 created from file.readlines() result in diffs that are suitable for
1221 file.writelines() since both the inputs and outputs have trailing
1222 newlines.
1223
1224 For inputs that do not have trailing newlines, set the lineterm
1225 argument to "" so that the output will be uniformly newline free.
1226
1227 The context diff format normally has a header for filenames and
1228 modification times. Any or all of these may be specified using
1229 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001230 The modification times are normally expressed in the ISO 8601 format.
1231 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001232
1233 Example:
1234
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001235 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
R. David Murrayb2416e52010-04-12 16:58:02 +00001236 ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001237 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001238 *** Original
1239 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001240 ***************
1241 *** 1,4 ****
1242 one
1243 ! two
1244 ! three
1245 four
1246 --- 1,4 ----
1247 + zero
1248 one
1249 ! tree
1250 four
1251 """
1252
1253 started = False
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001254 prefixmap = {'insert':'+ ', 'delete':'- ', 'replace':'! ', 'equal':' '}
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001255 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1256 if not started:
R. David Murrayb2416e52010-04-12 16:58:02 +00001257 fromdate = '\t%s' % fromfiledate if fromfiledate else ''
1258 todate = '\t%s' % tofiledate if tofiledate else ''
1259 yield '*** %s%s%s' % (fromfile, fromdate, lineterm)
1260 yield '--- %s%s%s' % (tofile, todate, lineterm)
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001261 started = True
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001262
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001263 yield '***************%s' % (lineterm,)
1264 if group[-1][2] - group[0][1] >= 2:
1265 yield '*** %d,%d ****%s' % (group[0][1]+1, group[-1][2], lineterm)
1266 else:
1267 yield '*** %d ****%s' % (group[-1][2], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001268 visiblechanges = [e for e in group if e[0] in ('replace', 'delete')]
1269 if visiblechanges:
1270 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001271 if tag != 'insert':
1272 for line in a[i1:i2]:
1273 yield prefixmap[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001274
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001275 if group[-1][4] - group[0][3] >= 2:
1276 yield '--- %d,%d ----%s' % (group[0][3]+1, group[-1][4], lineterm)
1277 else:
1278 yield '--- %d ----%s' % (group[-1][4], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001279 visiblechanges = [e for e in group if e[0] in ('replace', 'insert')]
1280 if visiblechanges:
1281 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001282 if tag != 'delete':
1283 for line in b[j1:j2]:
1284 yield prefixmap[tag] + line
1285
Tim Peters81b92512002-04-29 01:37:32 +00001286def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001287 r"""
1288 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1289
1290 Optional keyword parameters `linejunk` and `charjunk` are for filter
1291 functions (or None):
1292
1293 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001294 return true iff the string is junk. The default is None, and is
1295 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1296 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001297
1298 - charjunk: A function that should accept a string of length 1. The
1299 default is module-level function IS_CHARACTER_JUNK, which filters out
1300 whitespace characters (a blank or tab; note: bad idea to include newline
1301 in this!).
1302
1303 Tools/scripts/ndiff.py is a command-line front-end to this function.
1304
1305 Example:
1306
1307 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1308 ... 'ore\ntree\nemu\n'.splitlines(1))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001309 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001310 - one
1311 ? ^
1312 + ore
1313 ? ^
1314 - two
1315 - three
1316 ? -
1317 + tree
1318 + emu
1319 """
1320 return Differ(linejunk, charjunk).compare(a, b)
1321
Martin v. Löwise064b412004-08-29 16:34:40 +00001322def _mdiff(fromlines, tolines, context=None, linejunk=None,
1323 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001324 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001325
1326 Arguments:
1327 fromlines -- list of text lines to compared to tolines
1328 tolines -- list of text lines to be compared to fromlines
1329 context -- number of context lines to display on each side of difference,
1330 if None, all from/to text lines will be generated.
1331 linejunk -- passed on to ndiff (see ndiff documentation)
1332 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001333
Martin v. Löwise064b412004-08-29 16:34:40 +00001334 This function returns an interator which returns a tuple:
1335 (from line tuple, to line tuple, boolean flag)
1336
1337 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001338 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001339 line text -- original line text with following markers inserted:
1340 '\0+' -- marks start of added text
1341 '\0-' -- marks start of deleted text
1342 '\0^' -- marks start of changed text
1343 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001344
Martin v. Löwise064b412004-08-29 16:34:40 +00001345 boolean flag -- None indicates context separation, True indicates
1346 either "from" or "to" line contains a change, otherwise False.
1347
1348 This function/iterator was originally developed to generate side by side
1349 file difference for making HTML pages (see HtmlDiff class for example
1350 usage).
1351
1352 Note, this function utilizes the ndiff function to generate the side by
1353 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001354 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001355 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001356 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001357
1358 # regular expression for finding intraline change indices
1359 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001360
Martin v. Löwise064b412004-08-29 16:34:40 +00001361 # create the difference iterator to generate the differences
1362 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1363
1364 def _make_line(lines, format_key, side, num_lines=[0,0]):
1365 """Returns line of text with user's change markup and line formatting.
1366
1367 lines -- list of lines from the ndiff generator to produce a line of
1368 text from. When producing the line of text to return, the
1369 lines used are removed from this list.
1370 format_key -- '+' return first line in list with "add" markup around
1371 the entire line.
1372 '-' return first line in list with "delete" markup around
1373 the entire line.
1374 '?' return first line in list with add/delete/change
1375 intraline markup (indices obtained from second line)
1376 None return first line in list with no markup
1377 side -- indice into the num_lines list (0=from,1=to)
1378 num_lines -- from/to current line number. This is NOT intended to be a
1379 passed parameter. It is present as a keyword argument to
1380 maintain memory of the current line numbers between calls
1381 of this function.
1382
1383 Note, this function is purposefully not defined at the module scope so
1384 that data it needs from its parent function (within whose context it
1385 is defined) does not need to be of module scope.
1386 """
1387 num_lines[side] += 1
1388 # Handle case where no user markup is to be added, just return line of
1389 # text with user's line format to allow for usage of the line number.
1390 if format_key is None:
1391 return (num_lines[side],lines.pop(0)[2:])
1392 # Handle case of intraline changes
1393 if format_key == '?':
1394 text, markers = lines.pop(0), lines.pop(0)
1395 # find intraline changes (store change type and indices in tuples)
1396 sub_info = []
1397 def record_sub_info(match_object,sub_info=sub_info):
1398 sub_info.append([match_object.group(1)[0],match_object.span()])
1399 return match_object.group(1)
1400 change_re.sub(record_sub_info,markers)
1401 # process each tuple inserting our special marks that won't be
1402 # noticed by an xml/html escaper.
1403 for key,(begin,end) in sub_info[::-1]:
1404 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1405 text = text[2:]
1406 # Handle case of add/delete entire line
1407 else:
1408 text = lines.pop(0)[2:]
1409 # if line of text is just a newline, insert a space so there is
1410 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001411 if not text:
1412 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001413 # insert marks that won't be noticed by an xml/html escaper.
1414 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001415 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001416 # thing (such as adding the line number) then replace the special
1417 # marks with what the user's change markup.
1418 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001419
Martin v. Löwise064b412004-08-29 16:34:40 +00001420 def _line_iterator():
1421 """Yields from/to lines of text with a change indication.
1422
1423 This function is an iterator. It itself pulls lines from a
1424 differencing iterator, processes them and yields them. When it can
1425 it yields both a "from" and a "to" line, otherwise it will yield one
1426 or the other. In addition to yielding the lines of from/to text, a
1427 boolean flag is yielded to indicate if the text line(s) have
1428 differences in them.
1429
1430 Note, this function is purposefully not defined at the module scope so
1431 that data it needs from its parent function (within whose context it
1432 is defined) does not need to be of module scope.
1433 """
1434 lines = []
1435 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001436 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001437 # Load up next 4 lines so we can look ahead, create strings which
1438 # are a concatenation of the first character of each of the 4 lines
1439 # so we can do some very readable comparisons.
1440 while len(lines) < 4:
1441 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001442 lines.append(next(diff_lines_iterator))
Martin v. Löwise064b412004-08-29 16:34:40 +00001443 except StopIteration:
1444 lines.append('X')
1445 s = ''.join([line[0] for line in lines])
1446 if s.startswith('X'):
1447 # When no more lines, pump out any remaining blank lines so the
1448 # corresponding add/delete lines get a matching blank line so
1449 # all line pairs get yielded at the next level.
1450 num_blanks_to_yield = num_blanks_pending
1451 elif s.startswith('-?+?'):
1452 # simple intraline change
1453 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1454 continue
1455 elif s.startswith('--++'):
1456 # in delete block, add block coming: we do NOT want to get
1457 # caught up on blank lines yet, just process the delete line
1458 num_blanks_pending -= 1
1459 yield _make_line(lines,'-',0), None, True
1460 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001461 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001462 # in delete block and see a intraline change or unchanged line
1463 # coming: yield the delete line and then blanks
1464 from_line,to_line = _make_line(lines,'-',0), None
1465 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1466 elif s.startswith('-+?'):
1467 # intraline change
1468 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1469 continue
1470 elif s.startswith('-?+'):
1471 # intraline change
1472 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1473 continue
1474 elif s.startswith('-'):
1475 # delete FROM line
1476 num_blanks_pending -= 1
1477 yield _make_line(lines,'-',0), None, True
1478 continue
1479 elif s.startswith('+--'):
1480 # in add block, delete block coming: we do NOT want to get
1481 # caught up on blank lines yet, just process the add line
1482 num_blanks_pending += 1
1483 yield None, _make_line(lines,'+',1), True
1484 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001485 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001486 # will be leaving an add block: yield blanks then add line
1487 from_line, to_line = None, _make_line(lines,'+',1)
1488 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1489 elif s.startswith('+'):
1490 # inside an add block, yield the add line
1491 num_blanks_pending += 1
1492 yield None, _make_line(lines,'+',1), True
1493 continue
1494 elif s.startswith(' '):
1495 # unchanged text, yield it to both sides
1496 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1497 continue
1498 # Catch up on the blank lines so when we yield the next from/to
1499 # pair, they are lined up.
1500 while(num_blanks_to_yield < 0):
1501 num_blanks_to_yield += 1
1502 yield None,('','\n'),True
1503 while(num_blanks_to_yield > 0):
1504 num_blanks_to_yield -= 1
1505 yield ('','\n'),None,True
1506 if s.startswith('X'):
1507 raise StopIteration
1508 else:
1509 yield from_line,to_line,True
1510
1511 def _line_pair_iterator():
1512 """Yields from/to lines of text with a change indication.
1513
1514 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001515 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001516 always yields a pair of from/to text lines (with the change
1517 indication). If necessary it will collect single from/to lines
1518 until it has a matching pair from/to pair to yield.
1519
1520 Note, this function is purposefully not defined at the module scope so
1521 that data it needs from its parent function (within whose context it
1522 is defined) does not need to be of module scope.
1523 """
1524 line_iterator = _line_iterator()
1525 fromlines,tolines=[],[]
1526 while True:
1527 # Collecting lines of text until we have a from/to pair
1528 while (len(fromlines)==0 or len(tolines)==0):
Georg Brandla18af4e2007-04-21 15:47:16 +00001529 from_line, to_line, found_diff = next(line_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001530 if from_line is not None:
1531 fromlines.append((from_line,found_diff))
1532 if to_line is not None:
1533 tolines.append((to_line,found_diff))
1534 # Once we have a pair, remove them from the collection and yield it
1535 from_line, fromDiff = fromlines.pop(0)
1536 to_line, to_diff = tolines.pop(0)
1537 yield (from_line,to_line,fromDiff or to_diff)
1538
1539 # Handle case where user does not want context differencing, just yield
1540 # them up without doing anything else with them.
1541 line_pair_iterator = _line_pair_iterator()
1542 if context is None:
1543 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +00001544 yield next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001545 # Handle case where user wants context differencing. We must do some
1546 # storage of lines until we know for sure that they are to be yielded.
1547 else:
1548 context += 1
1549 lines_to_write = 0
1550 while True:
1551 # Store lines up until we find a difference, note use of a
1552 # circular queue because we only need to keep around what
1553 # we need for context.
1554 index, contextLines = 0, [None]*(context)
1555 found_diff = False
1556 while(found_diff is False):
Georg Brandla18af4e2007-04-21 15:47:16 +00001557 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001558 i = index % context
1559 contextLines[i] = (from_line, to_line, found_diff)
1560 index += 1
1561 # Yield lines that we have collected so far, but first yield
1562 # the user's separator.
1563 if index > context:
1564 yield None, None, None
1565 lines_to_write = context
1566 else:
1567 lines_to_write = index
1568 index = 0
1569 while(lines_to_write):
1570 i = index % context
1571 index += 1
1572 yield contextLines[i]
1573 lines_to_write -= 1
1574 # Now yield the context lines after the change
1575 lines_to_write = context-1
1576 while(lines_to_write):
Georg Brandla18af4e2007-04-21 15:47:16 +00001577 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001578 # If another change within the context, extend the context
1579 if found_diff:
1580 lines_to_write = context-1
1581 else:
1582 lines_to_write -= 1
1583 yield from_line, to_line, found_diff
1584
1585
1586_file_template = """
1587<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1588 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1589
1590<html>
1591
1592<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001593 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001594 content="text/html; charset=ISO-8859-1" />
1595 <title></title>
1596 <style type="text/css">%(styles)s
1597 </style>
1598</head>
1599
1600<body>
1601 %(table)s%(legend)s
1602</body>
1603
1604</html>"""
1605
1606_styles = """
1607 table.diff {font-family:Courier; border:medium;}
1608 .diff_header {background-color:#e0e0e0}
1609 td.diff_header {text-align:right}
1610 .diff_next {background-color:#c0c0c0}
1611 .diff_add {background-color:#aaffaa}
1612 .diff_chg {background-color:#ffff77}
1613 .diff_sub {background-color:#ffaaaa}"""
1614
1615_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001616 <table class="diff" id="difflib_chg_%(prefix)s_top"
1617 cellspacing="0" cellpadding="0" rules="groups" >
1618 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001619 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1620 %(header_row)s
1621 <tbody>
1622%(data_rows)s </tbody>
1623 </table>"""
1624
1625_legend = """
1626 <table class="diff" summary="Legends">
1627 <tr> <th colspan="2"> Legends </th> </tr>
1628 <tr> <td> <table border="" summary="Colors">
1629 <tr><th> Colors </th> </tr>
1630 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1631 <tr><td class="diff_chg">Changed</td> </tr>
1632 <tr><td class="diff_sub">Deleted</td> </tr>
1633 </table></td>
1634 <td> <table border="" summary="Links">
1635 <tr><th colspan="2"> Links </th> </tr>
1636 <tr><td>(f)irst change</td> </tr>
1637 <tr><td>(n)ext change</td> </tr>
1638 <tr><td>(t)op</td> </tr>
1639 </table></td> </tr>
1640 </table>"""
1641
1642class HtmlDiff(object):
1643 """For producing HTML side by side comparison with change highlights.
1644
1645 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001646 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001647 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001648 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001649
Martin v. Löwise064b412004-08-29 16:34:40 +00001650 The following methods are provided for HTML generation:
1651
1652 make_table -- generates HTML for a single side by side table
1653 make_file -- generates complete HTML file with a single side by side table
1654
Tim Peters48bd7f32004-08-29 22:38:38 +00001655 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001656 """
1657
1658 _file_template = _file_template
1659 _styles = _styles
1660 _table_template = _table_template
1661 _legend = _legend
1662 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001663
Martin v. Löwise064b412004-08-29 16:34:40 +00001664 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1665 charjunk=IS_CHARACTER_JUNK):
1666 """HtmlDiff instance initializer
1667
1668 Arguments:
1669 tabsize -- tab stop spacing, defaults to 8.
1670 wrapcolumn -- column number where lines are broken and wrapped,
1671 defaults to None where lines are not wrapped.
1672 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001673 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001674 ndiff() documentation for argument default values and descriptions.
1675 """
1676 self._tabsize = tabsize
1677 self._wrapcolumn = wrapcolumn
1678 self._linejunk = linejunk
1679 self._charjunk = charjunk
1680
1681 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1682 numlines=5):
1683 """Returns HTML file of side by side comparison with change highlights
1684
1685 Arguments:
1686 fromlines -- list of "from" lines
1687 tolines -- list of "to" lines
1688 fromdesc -- "from" file column header string
1689 todesc -- "to" file column header string
1690 context -- set to True for contextual differences (defaults to False
1691 which shows full differences).
1692 numlines -- number of context lines. When context is set True,
1693 controls number of lines displayed before and after the change.
1694 When context is False, controls the number of lines to place
1695 the "next" link anchors before the next change (so click of
1696 "next" link jumps to just before the change).
1697 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001698
Martin v. Löwise064b412004-08-29 16:34:40 +00001699 return self._file_template % dict(
1700 styles = self._styles,
1701 legend = self._legend,
1702 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1703 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001704
Martin v. Löwise064b412004-08-29 16:34:40 +00001705 def _tab_newline_replace(self,fromlines,tolines):
1706 """Returns from/to line lists with tabs expanded and newlines removed.
1707
1708 Instead of tab characters being replaced by the number of spaces
1709 needed to fill in to the next tab stop, this function will fill
1710 the space with tab characters. This is done so that the difference
1711 algorithms can identify changes in a file when tabs are replaced by
1712 spaces and vice versa. At the end of the HTML generation, the tab
1713 characters will be replaced with a nonbreakable space.
1714 """
1715 def expand_tabs(line):
1716 # hide real spaces
1717 line = line.replace(' ','\0')
1718 # expand tabs into spaces
1719 line = line.expandtabs(self._tabsize)
1720 # relace spaces from expanded tabs back into tab characters
1721 # (we'll replace them with markup after we do differencing)
1722 line = line.replace(' ','\t')
1723 return line.replace('\0',' ').rstrip('\n')
1724 fromlines = [expand_tabs(line) for line in fromlines]
1725 tolines = [expand_tabs(line) for line in tolines]
1726 return fromlines,tolines
1727
1728 def _split_line(self,data_list,line_num,text):
1729 """Builds list of text lines by splitting text lines at wrap point
1730
1731 This function will determine if the input text line needs to be
1732 wrapped (split) into separate lines. If so, the first wrap point
1733 will be determined and the first line appended to the output
1734 text line list. This function is used recursively to handle
1735 the second part of the split line to further split it.
1736 """
1737 # if blank line or context separator, just add it to the output list
1738 if not line_num:
1739 data_list.append((line_num,text))
1740 return
1741
1742 # if line text doesn't need wrapping, just add it to the output list
1743 size = len(text)
1744 max = self._wrapcolumn
1745 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1746 data_list.append((line_num,text))
1747 return
1748
1749 # scan text looking for the wrap point, keeping track if the wrap
1750 # point is inside markers
1751 i = 0
1752 n = 0
1753 mark = ''
1754 while n < max and i < size:
1755 if text[i] == '\0':
1756 i += 1
1757 mark = text[i]
1758 i += 1
1759 elif text[i] == '\1':
1760 i += 1
1761 mark = ''
1762 else:
1763 i += 1
1764 n += 1
1765
1766 # wrap point is inside text, break it up into separate lines
1767 line1 = text[:i]
1768 line2 = text[i:]
1769
1770 # if wrap point is inside markers, place end marker at end of first
1771 # line and start marker at beginning of second line because each
1772 # line will have its own table tag markup around it.
1773 if mark:
1774 line1 = line1 + '\1'
1775 line2 = '\0' + mark + line2
1776
Tim Peters48bd7f32004-08-29 22:38:38 +00001777 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001778 data_list.append((line_num,line1))
1779
Tim Peters48bd7f32004-08-29 22:38:38 +00001780 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001781 self._split_line(data_list,'>',line2)
1782
1783 def _line_wrapper(self,diffs):
1784 """Returns iterator that splits (wraps) mdiff text lines"""
1785
1786 # pull from/to data and flags from mdiff iterator
1787 for fromdata,todata,flag in diffs:
1788 # check for context separators and pass them through
1789 if flag is None:
1790 yield fromdata,todata,flag
1791 continue
1792 (fromline,fromtext),(toline,totext) = fromdata,todata
1793 # for each from/to line split it at the wrap column to form
1794 # list of text lines.
1795 fromlist,tolist = [],[]
1796 self._split_line(fromlist,fromline,fromtext)
1797 self._split_line(tolist,toline,totext)
1798 # yield from/to line in pairs inserting blank lines as
1799 # necessary when one side has more wrapped lines
1800 while fromlist or tolist:
1801 if fromlist:
1802 fromdata = fromlist.pop(0)
1803 else:
1804 fromdata = ('',' ')
1805 if tolist:
1806 todata = tolist.pop(0)
1807 else:
1808 todata = ('',' ')
1809 yield fromdata,todata,flag
1810
1811 def _collect_lines(self,diffs):
1812 """Collects mdiff output into separate lists
1813
1814 Before storing the mdiff from/to data into a list, it is converted
1815 into a single line of text with HTML markup.
1816 """
1817
1818 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001819 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001820 for fromdata,todata,flag in diffs:
1821 try:
1822 # store HTML markup of the lines into the lists
1823 fromlist.append(self._format_line(0,flag,*fromdata))
1824 tolist.append(self._format_line(1,flag,*todata))
1825 except TypeError:
1826 # exceptions occur for lines where context separators go
1827 fromlist.append(None)
1828 tolist.append(None)
1829 flaglist.append(flag)
1830 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001831
Martin v. Löwise064b412004-08-29 16:34:40 +00001832 def _format_line(self,side,flag,linenum,text):
1833 """Returns HTML markup of "from" / "to" text lines
1834
1835 side -- 0 or 1 indicating "from" or "to" text
1836 flag -- indicates if difference on line
1837 linenum -- line number (used for line number column)
1838 text -- line text to be marked up
1839 """
1840 try:
1841 linenum = '%d' % linenum
1842 id = ' id="%s%s"' % (self._prefix[side],linenum)
1843 except TypeError:
1844 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001845 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001846 # replace those things that would get confused with HTML symbols
1847 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1848
1849 # make space non-breakable so they don't get compressed or line wrapped
1850 text = text.replace(' ','&nbsp;').rstrip()
1851
1852 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1853 % (id,linenum,text)
1854
1855 def _make_prefix(self):
1856 """Create unique anchor prefixes"""
1857
1858 # Generate a unique anchor prefix so multiple tables
1859 # can exist on the same HTML page without conflicts.
1860 fromprefix = "from%d_" % HtmlDiff._default_prefix
1861 toprefix = "to%d_" % HtmlDiff._default_prefix
1862 HtmlDiff._default_prefix += 1
1863 # store prefixes so line format method has access
1864 self._prefix = [fromprefix,toprefix]
1865
1866 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1867 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001868
Martin v. Löwise064b412004-08-29 16:34:40 +00001869 # all anchor names will be generated using the unique "to" prefix
1870 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001871
Martin v. Löwise064b412004-08-29 16:34:40 +00001872 # process change flags, generating middle column of next anchors/links
1873 next_id = ['']*len(flaglist)
1874 next_href = ['']*len(flaglist)
1875 num_chg, in_change = 0, False
1876 last = 0
1877 for i,flag in enumerate(flaglist):
1878 if flag:
1879 if not in_change:
1880 in_change = True
1881 last = i
1882 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001883 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001884 # link
1885 i = max([0,i-numlines])
1886 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001887 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001888 # change
1889 num_chg += 1
1890 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1891 toprefix,num_chg)
1892 else:
1893 in_change = False
1894 # check for cases where there is no content to avoid exceptions
1895 if not flaglist:
1896 flaglist = [False]
1897 next_id = ['']
1898 next_href = ['']
1899 last = 0
1900 if context:
1901 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1902 tolist = fromlist
1903 else:
1904 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1905 # if not a change on first line, drop a link
1906 if not flaglist[0]:
1907 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1908 # redo the last link to link to the top
1909 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1910
1911 return fromlist,tolist,flaglist,next_href,next_id
1912
1913 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1914 numlines=5):
1915 """Returns HTML table of side by side comparison with change highlights
1916
1917 Arguments:
1918 fromlines -- list of "from" lines
1919 tolines -- list of "to" lines
1920 fromdesc -- "from" file column header string
1921 todesc -- "to" file column header string
1922 context -- set to True for contextual differences (defaults to False
1923 which shows full differences).
1924 numlines -- number of context lines. When context is set True,
1925 controls number of lines displayed before and after the change.
1926 When context is False, controls the number of lines to place
1927 the "next" link anchors before the next change (so click of
1928 "next" link jumps to just before the change).
1929 """
1930
1931 # make unique anchor prefixes so that multiple tables may exist
1932 # on the same page without conflict.
1933 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001934
Martin v. Löwise064b412004-08-29 16:34:40 +00001935 # change tabs to spaces before it gets more difficult after we insert
1936 # markkup
1937 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001938
Martin v. Löwise064b412004-08-29 16:34:40 +00001939 # create diffs iterator which generates side by side from/to data
1940 if context:
1941 context_lines = numlines
1942 else:
1943 context_lines = None
1944 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1945 charjunk=self._charjunk)
1946
1947 # set up iterator to wrap lines that exceed desired width
1948 if self._wrapcolumn:
1949 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001950
Martin v. Löwise064b412004-08-29 16:34:40 +00001951 # collect up from/to lines and flags into lists (also format the lines)
1952 fromlist,tolist,flaglist = self._collect_lines(diffs)
1953
1954 # process change flags, generating middle column of next anchors/links
1955 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1956 fromlist,tolist,flaglist,context,numlines)
1957
Guido van Rossumd8faa362007-04-27 19:54:29 +00001958 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00001959 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1960 '<td class="diff_next">%s</td>%s</tr>\n'
1961 for i in range(len(flaglist)):
1962 if flaglist[i] is None:
1963 # mdiff yields None on separator lines skip the bogus ones
1964 # generated for the first line
1965 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001966 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00001967 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001968 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00001969 next_href[i],tolist[i]))
1970 if fromdesc or todesc:
1971 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
1972 '<th class="diff_next"><br /></th>',
1973 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
1974 '<th class="diff_next"><br /></th>',
1975 '<th colspan="2" class="diff_header">%s</th>' % todesc)
1976 else:
1977 header_row = ''
1978
1979 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00001980 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00001981 header_row=header_row,
1982 prefix=self._prefix[1])
1983
1984 return table.replace('\0+','<span class="diff_add">'). \
1985 replace('\0-','<span class="diff_sub">'). \
1986 replace('\0^','<span class="diff_chg">'). \
1987 replace('\1','</span>'). \
1988 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00001989
Martin v. Löwise064b412004-08-29 16:34:40 +00001990del re
1991
Tim Peters5e824c32001-08-12 22:25:01 +00001992def restore(delta, which):
1993 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00001994 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00001995
1996 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
1997 lines originating from file 1 or 2 (parameter `which`), stripping off line
1998 prefixes.
1999
2000 Examples:
2001
2002 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
2003 ... 'ore\ntree\nemu\n'.splitlines(1))
Tim Peters8a9c2842001-09-22 21:30:22 +00002004 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002005 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002006 one
2007 two
2008 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002009 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002010 ore
2011 tree
2012 emu
2013 """
2014 try:
2015 tag = {1: "- ", 2: "+ "}[int(which)]
2016 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002017 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Tim Peters5e824c32001-08-12 22:25:01 +00002018 % which)
2019 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002020 for line in delta:
2021 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002022 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002023
Tim Peters9ae21482001-02-10 08:00:53 +00002024def _test():
2025 import doctest, difflib
2026 return doctest.testmod(difflib)
2027
2028if __name__ == "__main__":
2029 _test()