blob: db5f82ec035055616bc6a6d0aadebd38b393d977 [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
Terry Reedybcd89882010-12-03 22:29:40 +0000339 def isbjunk(self, item):
340 "Deprecated; use 'item in SequenceMatcher().bjunk'."
341 warnings.warn("'SequenceMatcher().isbjunk(item)' is deprecated;\n"
342 "use 'item in SMinstance.bjunk' instead.",
343 DeprecationWarning, 2)
344 return item in self.bjunk
345
346 def isbpopular(self, item):
347 "Deprecated; use 'item in SequenceMatcher().bpopular'."
348 warnings.warn("'SequenceMatcher().isbpopular(item)' is deprecated;\n"
349 "use 'item in SMinstance.bpopular' instead.",
350 DeprecationWarning, 2)
351 return item in self.bpopular
Tim Peters9ae21482001-02-10 08:00:53 +0000352
353 def find_longest_match(self, alo, ahi, blo, bhi):
354 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
355
356 If isjunk is not defined:
357
358 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
359 alo <= i <= i+k <= ahi
360 blo <= j <= j+k <= bhi
361 and for all (i',j',k') meeting those conditions,
362 k >= k'
363 i <= i'
364 and if i == i', j <= j'
365
366 In other words, of all maximal matching blocks, return one that
367 starts earliest in a, and of all those maximal matching blocks that
368 start earliest in a, return the one that starts earliest in b.
369
370 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
371 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000372 Match(a=0, b=4, size=5)
Tim Peters9ae21482001-02-10 08:00:53 +0000373
374 If isjunk is defined, first the longest matching block is
375 determined as above, but with the additional restriction that no
376 junk element appears in the block. Then that block is extended as
377 far as possible by matching (only) junk elements on both sides. So
378 the resulting block never matches on junk except as identical junk
379 happens to be adjacent to an "interesting" match.
380
381 Here's the same example as before, but considering blanks to be
382 junk. That prevents " abcd" from matching the " abcd" at the tail
383 end of the second sequence directly. Instead only the "abcd" can
384 match, and matches the leftmost "abcd" in the second sequence:
385
386 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
387 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000388 Match(a=1, b=0, size=4)
Tim Peters9ae21482001-02-10 08:00:53 +0000389
390 If no blocks match, return (alo, blo, 0).
391
392 >>> s = SequenceMatcher(None, "ab", "c")
393 >>> s.find_longest_match(0, 2, 0, 1)
Christian Heimes25bb7832008-01-11 16:17:00 +0000394 Match(a=0, b=0, size=0)
Tim Peters9ae21482001-02-10 08:00:53 +0000395 """
396
397 # CAUTION: stripping common prefix or suffix would be incorrect.
398 # E.g.,
399 # ab
400 # acab
401 # Longest matching block is "ab", but if common prefix is
402 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
403 # strip, so ends up claiming that ab is changed to acab by
404 # inserting "ca" in the middle. That's minimal but unintuitive:
405 # "it's obvious" that someone inserted "ac" at the front.
406 # Windiff ends up at the same place as diff, but by pairing up
407 # the unique 'b's and then matching the first two 'a's.
408
Terry Reedybcd89882010-12-03 22:29:40 +0000409 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000410 besti, bestj, bestsize = alo, blo, 0
411 # find longest junk-free match
412 # during an iteration of the loop, j2len[j] = length of longest
413 # junk-free match ending with a[i-1] and b[j]
414 j2len = {}
415 nothing = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000416 for i in range(alo, ahi):
Tim Peters9ae21482001-02-10 08:00:53 +0000417 # look at all instances of a[i] in b; note that because
418 # b2j has no junk keys, the loop is skipped if a[i] is junk
419 j2lenget = j2len.get
420 newj2len = {}
421 for j in b2j.get(a[i], nothing):
422 # a[i] matches b[j]
423 if j < blo:
424 continue
425 if j >= bhi:
426 break
427 k = newj2len[j] = j2lenget(j-1, 0) + 1
428 if k > bestsize:
429 besti, bestj, bestsize = i-k+1, j-k+1, k
430 j2len = newj2len
431
Tim Peters81b92512002-04-29 01:37:32 +0000432 # Extend the best by non-junk elements on each end. In particular,
433 # "popular" non-junk elements aren't in b2j, which greatly speeds
434 # the inner loop above, but also means "the best" match so far
435 # doesn't contain any junk *or* popular non-junk elements.
436 while besti > alo and bestj > blo and \
437 not isbjunk(b[bestj-1]) and \
438 a[besti-1] == b[bestj-1]:
439 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
440 while besti+bestsize < ahi and bestj+bestsize < bhi and \
441 not isbjunk(b[bestj+bestsize]) and \
442 a[besti+bestsize] == b[bestj+bestsize]:
443 bestsize += 1
444
Tim Peters9ae21482001-02-10 08:00:53 +0000445 # Now that we have a wholly interesting match (albeit possibly
446 # empty!), we may as well suck up the matching junk on each
447 # side of it too. Can't think of a good reason not to, and it
448 # saves post-processing the (possibly considerable) expense of
449 # figuring out what to do with it. In the case of an empty
450 # interesting match, this is clearly the right thing to do,
451 # because no other kind of match is possible in the regions.
452 while besti > alo and bestj > blo and \
453 isbjunk(b[bestj-1]) and \
454 a[besti-1] == b[bestj-1]:
455 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
456 while besti+bestsize < ahi and bestj+bestsize < bhi and \
457 isbjunk(b[bestj+bestsize]) and \
458 a[besti+bestsize] == b[bestj+bestsize]:
459 bestsize = bestsize + 1
460
Christian Heimes25bb7832008-01-11 16:17:00 +0000461 return Match(besti, bestj, bestsize)
Tim Peters9ae21482001-02-10 08:00:53 +0000462
463 def get_matching_blocks(self):
464 """Return list of triples describing matching subsequences.
465
466 Each triple is of the form (i, j, n), and means that
467 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000468 i and in j. New in Python 2.5, it's also guaranteed that if
469 (i, j, n) and (i', j', n') are adjacent triples in the list, and
470 the second is not the last triple in the list, then i+n != i' or
471 j+n != j'. IOW, adjacent triples never describe adjacent equal
472 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000473
474 The last triple is a dummy, (len(a), len(b), 0), and is the only
475 triple with n==0.
476
477 >>> s = SequenceMatcher(None, "abxcd", "abcd")
Christian Heimes25bb7832008-01-11 16:17:00 +0000478 >>> list(s.get_matching_blocks())
479 [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 +0000480 """
481
482 if self.matching_blocks is not None:
483 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000484 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000485
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000486 # This is most naturally expressed as a recursive algorithm, but
487 # at least one user bumped into extreme use cases that exceeded
488 # the recursion limit on their box. So, now we maintain a list
489 # ('queue`) of blocks we still need to look at, and append partial
490 # results to `matching_blocks` in a loop; the matches are sorted
491 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000492 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000493 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000494 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000495 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000496 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000497 # a[alo:i] vs b[blo:j] unknown
498 # a[i:i+k] same as b[j:j+k]
499 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000500 if k: # if k is 0, there was no matching block
501 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000502 if alo < i and blo < j:
503 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000504 if i+k < ahi and j+k < bhi:
505 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000507
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000508 # It's possible that we have adjacent equal blocks in the
509 # matching_blocks list now. Starting with 2.5, this code was added
510 # to collapse them.
511 i1 = j1 = k1 = 0
512 non_adjacent = []
513 for i2, j2, k2 in matching_blocks:
514 # Is this block adjacent to i1, j1, k1?
515 if i1 + k1 == i2 and j1 + k1 == j2:
516 # Yes, so collapse them -- this just increases the length of
517 # the first block by the length of the second, and the first
518 # block so lengthened remains the block to compare against.
519 k1 += k2
520 else:
521 # Not adjacent. Remember the first block (k1==0 means it's
522 # the dummy we started with), and make the second block the
523 # new block to compare against.
524 if k1:
525 non_adjacent.append((i1, j1, k1))
526 i1, j1, k1 = i2, j2, k2
527 if k1:
528 non_adjacent.append((i1, j1, k1))
529
530 non_adjacent.append( (la, lb, 0) )
531 self.matching_blocks = non_adjacent
Christian Heimes25bb7832008-01-11 16:17:00 +0000532 return map(Match._make, self.matching_blocks)
Tim Peters9ae21482001-02-10 08:00:53 +0000533
Tim Peters9ae21482001-02-10 08:00:53 +0000534 def get_opcodes(self):
535 """Return list of 5-tuples describing how to turn a into b.
536
537 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
538 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
539 tuple preceding it, and likewise for j1 == the previous j2.
540
541 The tags are strings, with these meanings:
542
543 'replace': a[i1:i2] should be replaced by b[j1:j2]
544 'delete': a[i1:i2] should be deleted.
545 Note that j1==j2 in this case.
546 'insert': b[j1:j2] should be inserted at a[i1:i1].
547 Note that i1==i2 in this case.
548 'equal': a[i1:i2] == b[j1:j2]
549
550 >>> a = "qabxcd"
551 >>> b = "abycdf"
552 >>> s = SequenceMatcher(None, a, b)
553 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000554 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
555 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000556 delete a[0:1] (q) b[0:0] ()
557 equal a[1:3] (ab) b[0:2] (ab)
558 replace a[3:4] (x) b[2:3] (y)
559 equal a[4:6] (cd) b[3:5] (cd)
560 insert a[6:6] () b[5:6] (f)
561 """
562
563 if self.opcodes is not None:
564 return self.opcodes
565 i = j = 0
566 self.opcodes = answer = []
567 for ai, bj, size in self.get_matching_blocks():
568 # invariant: we've pumped out correct diffs to change
569 # a[:i] into b[:j], and the next matching block is
570 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
571 # out a diff to change a[i:ai] into b[j:bj], pump out
572 # the matching block, and move (i,j) beyond the match
573 tag = ''
574 if i < ai and j < bj:
575 tag = 'replace'
576 elif i < ai:
577 tag = 'delete'
578 elif j < bj:
579 tag = 'insert'
580 if tag:
581 answer.append( (tag, i, ai, j, bj) )
582 i, j = ai+size, bj+size
583 # the list of matching blocks is terminated by a
584 # sentinel with size 0
585 if size:
586 answer.append( ('equal', ai, i, bj, j) )
587 return answer
588
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000589 def get_grouped_opcodes(self, n=3):
590 """ Isolate change clusters by eliminating ranges with no changes.
591
592 Return a generator of groups with upto n lines of context.
593 Each group is in the same format as returned by get_opcodes().
594
595 >>> from pprint import pprint
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000596 >>> a = list(map(str, range(1,40)))
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000597 >>> b = a[:]
598 >>> b[8:8] = ['i'] # Make an insertion
599 >>> b[20] += 'x' # Make a replacement
600 >>> b[23:28] = [] # Make a deletion
601 >>> b[30] += 'y' # Make another replacement
602 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
603 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
604 [('equal', 16, 19, 17, 20),
605 ('replace', 19, 20, 20, 21),
606 ('equal', 20, 22, 21, 23),
607 ('delete', 22, 27, 23, 23),
608 ('equal', 27, 30, 23, 26)],
609 [('equal', 31, 34, 27, 30),
610 ('replace', 34, 35, 30, 31),
611 ('equal', 35, 38, 31, 34)]]
612 """
613
614 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000615 if not codes:
616 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000617 # Fixup leading and trailing groups if they show no changes.
618 if codes[0][0] == 'equal':
619 tag, i1, i2, j1, j2 = codes[0]
620 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
621 if codes[-1][0] == 'equal':
622 tag, i1, i2, j1, j2 = codes[-1]
623 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
624
625 nn = n + n
626 group = []
627 for tag, i1, i2, j1, j2 in codes:
628 # End the current group and start a new one whenever
629 # there is a large range with no changes.
630 if tag == 'equal' and i2-i1 > nn:
631 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
632 yield group
633 group = []
634 i1, j1 = max(i1, i2-n), max(j1, j2-n)
635 group.append((tag, i1, i2, j1 ,j2))
636 if group and not (len(group)==1 and group[0][0] == 'equal'):
637 yield group
638
Tim Peters9ae21482001-02-10 08:00:53 +0000639 def ratio(self):
640 """Return a measure of the sequences' similarity (float in [0,1]).
641
642 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000643 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000644 Note that this is 1 if the sequences are identical, and 0 if
645 they have nothing in common.
646
647 .ratio() is expensive to compute if you haven't already computed
648 .get_matching_blocks() or .get_opcodes(), in which case you may
649 want to try .quick_ratio() or .real_quick_ratio() first to get an
650 upper bound.
651
652 >>> s = SequenceMatcher(None, "abcd", "bcde")
653 >>> s.ratio()
654 0.75
655 >>> s.quick_ratio()
656 0.75
657 >>> s.real_quick_ratio()
658 1.0
659 """
660
Guido van Rossum89da5d72006-08-22 00:21:25 +0000661 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000662 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000663
664 def quick_ratio(self):
665 """Return an upper bound on ratio() relatively quickly.
666
667 This isn't defined beyond that it is an upper bound on .ratio(), and
668 is faster to compute.
669 """
670
671 # viewing a and b as multisets, set matches to the cardinality
672 # of their intersection; this counts the number of matches
673 # without regard to order, so is clearly an upper bound
674 if self.fullbcount is None:
675 self.fullbcount = fullbcount = {}
676 for elt in self.b:
677 fullbcount[elt] = fullbcount.get(elt, 0) + 1
678 fullbcount = self.fullbcount
679 # avail[x] is the number of times x appears in 'b' less the
680 # number of times we've seen it in 'a' so far ... kinda
681 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000682 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000683 for elt in self.a:
684 if availhas(elt):
685 numb = avail[elt]
686 else:
687 numb = fullbcount.get(elt, 0)
688 avail[elt] = numb - 1
689 if numb > 0:
690 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000691 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000692
693 def real_quick_ratio(self):
694 """Return an upper bound on ratio() very quickly.
695
696 This isn't defined beyond that it is an upper bound on .ratio(), and
697 is faster to compute than either .ratio() or .quick_ratio().
698 """
699
700 la, lb = len(self.a), len(self.b)
701 # can't have more matches than the number of elements in the
702 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000703 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000704
705def get_close_matches(word, possibilities, n=3, cutoff=0.6):
706 """Use SequenceMatcher to return list of the best "good enough" matches.
707
708 word is a sequence for which close matches are desired (typically a
709 string).
710
711 possibilities is a list of sequences against which to match word
712 (typically a list of strings).
713
714 Optional arg n (default 3) is the maximum number of close matches to
715 return. n must be > 0.
716
717 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
718 that don't score at least that similar to word are ignored.
719
720 The best (no more than n) matches among the possibilities are returned
721 in a list, sorted by similarity score, most similar first.
722
723 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
724 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000725 >>> import keyword as _keyword
726 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000727 ['while']
Guido van Rossum486364b2007-06-30 05:01:58 +0000728 >>> get_close_matches("Apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000729 []
Tim Peters5e824c32001-08-12 22:25:01 +0000730 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000731 ['except']
732 """
733
734 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000735 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000736 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000737 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000738 result = []
739 s = SequenceMatcher()
740 s.set_seq2(word)
741 for x in possibilities:
742 s.set_seq1(x)
743 if s.real_quick_ratio() >= cutoff and \
744 s.quick_ratio() >= cutoff and \
745 s.ratio() >= cutoff:
746 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000747
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000748 # Move the best scorers to head of list
Raymond Hettingeraefde432004-06-15 23:53:35 +0000749 result = heapq.nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000750 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000751 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000752
753def _count_leading(line, ch):
754 """
755 Return number of `ch` characters at the start of `line`.
756
757 Example:
758
759 >>> _count_leading(' abc', ' ')
760 3
761 """
762
763 i, n = 0, len(line)
764 while i < n and line[i] == ch:
765 i += 1
766 return i
767
768class Differ:
769 r"""
770 Differ is a class for comparing sequences of lines of text, and
771 producing human-readable differences or deltas. Differ uses
772 SequenceMatcher both to compare sequences of lines, and to compare
773 sequences of characters within similar (near-matching) lines.
774
775 Each line of a Differ delta begins with a two-letter code:
776
777 '- ' line unique to sequence 1
778 '+ ' line unique to sequence 2
779 ' ' line common to both sequences
780 '? ' line not present in either input sequence
781
782 Lines beginning with '? ' attempt to guide the eye to intraline
783 differences, and were not present in either input sequence. These lines
784 can be confusing if the sequences contain tab characters.
785
786 Note that Differ makes no claim to produce a *minimal* diff. To the
787 contrary, minimal diffs are often counter-intuitive, because they synch
788 up anywhere possible, sometimes accidental matches 100 pages apart.
789 Restricting synch points to contiguous matches preserves some notion of
790 locality, at the occasional cost of producing a longer diff.
791
792 Example: Comparing two texts.
793
794 First we set up the texts, sequences of individual single-line strings
795 ending with newlines (such sequences can also be obtained from the
796 `readlines()` method of file-like objects):
797
798 >>> text1 = ''' 1. Beautiful is better than ugly.
799 ... 2. Explicit is better than implicit.
800 ... 3. Simple is better than complex.
801 ... 4. Complex is better than complicated.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300802 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000803 >>> len(text1)
804 4
805 >>> text1[0][-1]
806 '\n'
807 >>> text2 = ''' 1. Beautiful is better than ugly.
808 ... 3. Simple is better than complex.
809 ... 4. Complicated is better than complex.
810 ... 5. Flat is better than nested.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300811 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000812
813 Next we instantiate a Differ object:
814
815 >>> d = Differ()
816
817 Note that when instantiating a Differ object we may pass functions to
818 filter out line and character 'junk'. See Differ.__init__ for details.
819
820 Finally, we compare the two:
821
Tim Peters8a9c2842001-09-22 21:30:22 +0000822 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000823
824 'result' is a list of strings, so let's pretty-print it:
825
826 >>> from pprint import pprint as _pprint
827 >>> _pprint(result)
828 [' 1. Beautiful is better than ugly.\n',
829 '- 2. Explicit is better than implicit.\n',
830 '- 3. Simple is better than complex.\n',
831 '+ 3. Simple is better than complex.\n',
832 '? ++\n',
833 '- 4. Complex is better than complicated.\n',
834 '? ^ ---- ^\n',
835 '+ 4. Complicated is better than complex.\n',
836 '? ++++ ^ ^\n',
837 '+ 5. Flat is better than nested.\n']
838
839 As a single multi-line string it looks like this:
840
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000841 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000842 1. Beautiful is better than ugly.
843 - 2. Explicit is better than implicit.
844 - 3. Simple is better than complex.
845 + 3. Simple is better than complex.
846 ? ++
847 - 4. Complex is better than complicated.
848 ? ^ ---- ^
849 + 4. Complicated is better than complex.
850 ? ++++ ^ ^
851 + 5. Flat is better than nested.
852
853 Methods:
854
855 __init__(linejunk=None, charjunk=None)
856 Construct a text differencer, with optional filters.
857
858 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000859 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000860 """
861
862 def __init__(self, linejunk=None, charjunk=None):
863 """
864 Construct a text differencer, with optional filters.
865
866 The two optional keyword parameters are for filter functions:
867
868 - `linejunk`: A function that should accept a single string argument,
869 and return true iff the string is junk. The module-level function
870 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000871 characters, except for at most one splat ('#'). It is recommended
872 to leave linejunk None; as of Python 2.3, the underlying
873 SequenceMatcher class has grown an adaptive notion of "noise" lines
874 that's better than any static definition the author has ever been
875 able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000876
877 - `charjunk`: A function that should accept a string of length 1. The
878 module-level function `IS_CHARACTER_JUNK` may be used to filter out
879 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000880 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000881 """
882
883 self.linejunk = linejunk
884 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000885
886 def compare(self, a, b):
887 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000888 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000889
890 Each sequence must contain individual single-line strings ending with
891 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000892 of file-like objects. The delta generated also consists of newline-
893 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000894 method of a file-like object.
895
896 Example:
897
Ezio Melottid8b509b2011-09-28 17:37:55 +0300898 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(True),
899 ... 'ore\ntree\nemu\n'.splitlines(True))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000900 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000901 - one
902 ? ^
903 + ore
904 ? ^
905 - two
906 - three
907 ? -
908 + tree
909 + emu
910 """
911
912 cruncher = SequenceMatcher(self.linejunk, a, b)
913 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
914 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000915 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000916 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000917 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000918 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000919 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000920 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000921 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000922 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000923 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +0000924
Philip Jenvey4993cc02012-10-01 12:53:43 -0700925 yield from g
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:
Philip Jenvey4993cc02012-10-01 12:53:43 -0700944 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +0000945
946 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
947 r"""
948 When replacing one block of lines with another, search the blocks
949 for *similar* lines; the best-matching pair (if any) is used as a
950 synch point, and intraline difference marking is done on the
951 similar pair. Lots of work, but often worth it.
952
953 Example:
954
955 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000956 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
957 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000958 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000959 - abcDefghiJkl
960 ? ^ ^ ^
961 + abcdefGhijkl
962 ? ^ ^ ^
963 """
964
Tim Peters5e824c32001-08-12 22:25:01 +0000965 # don't synch up unless the lines have a similarity score of at
966 # least cutoff; best_ratio tracks the best score seen so far
967 best_ratio, cutoff = 0.74, 0.75
968 cruncher = SequenceMatcher(self.charjunk)
969 eqi, eqj = None, None # 1st indices of equal lines (if any)
970
971 # search for the pair that matches best without being identical
972 # (identical lines must be junk lines, & we don't want to synch up
973 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000974 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000975 bj = b[j]
976 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000977 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000978 ai = a[i]
979 if ai == bj:
980 if eqi is None:
981 eqi, eqj = i, j
982 continue
983 cruncher.set_seq1(ai)
984 # computing similarity is expensive, so use the quick
985 # upper bounds first -- have seen this speed up messy
986 # compares by a factor of 3.
987 # note that ratio() is only expensive to compute the first
988 # time it's called on a sequence pair; the expensive part
989 # of the computation is cached by cruncher
990 if cruncher.real_quick_ratio() > best_ratio and \
991 cruncher.quick_ratio() > best_ratio and \
992 cruncher.ratio() > best_ratio:
993 best_ratio, best_i, best_j = cruncher.ratio(), i, j
994 if best_ratio < cutoff:
995 # no non-identical "pretty close" pair
996 if eqi is None:
997 # no identical pair either -- treat it as a straight replace
Philip Jenvey4993cc02012-10-01 12:53:43 -0700998 yield from self._plain_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000999 return
1000 # no close pair, but an identical pair -- synch up on that
1001 best_i, best_j, best_ratio = eqi, eqj, 1.0
1002 else:
1003 # there's a close pair, so forget the identical pair (if any)
1004 eqi = None
1005
1006 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
1007 # identical
Tim Peters5e824c32001-08-12 22:25:01 +00001008
1009 # pump out diffs from before the synch point
Philip Jenvey4993cc02012-10-01 12:53:43 -07001010 yield from self._fancy_helper(a, alo, best_i, b, blo, best_j)
Tim Peters5e824c32001-08-12 22:25:01 +00001011
1012 # do intraline marking on the synch pair
1013 aelt, belt = a[best_i], b[best_j]
1014 if eqi is None:
1015 # pump out a '-', '?', '+', '?' quad for the synched lines
1016 atags = btags = ""
1017 cruncher.set_seqs(aelt, belt)
1018 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1019 la, lb = ai2 - ai1, bj2 - bj1
1020 if tag == 'replace':
1021 atags += '^' * la
1022 btags += '^' * lb
1023 elif tag == 'delete':
1024 atags += '-' * la
1025 elif tag == 'insert':
1026 btags += '+' * lb
1027 elif tag == 'equal':
1028 atags += ' ' * la
1029 btags += ' ' * lb
1030 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001031 raise ValueError('unknown tag %r' % (tag,))
Philip Jenvey4993cc02012-10-01 12:53:43 -07001032 yield from self._qformat(aelt, belt, atags, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001033 else:
1034 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001035 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001036
1037 # pump out diffs from after the synch point
Philip Jenvey4993cc02012-10-01 12:53:43 -07001038 yield from self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001039
1040 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001041 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001042 if alo < ahi:
1043 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001044 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001045 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001046 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001047 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001048 g = self._dump('+', b, blo, bhi)
1049
Philip Jenvey4993cc02012-10-01 12:53:43 -07001050 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +00001051
1052 def _qformat(self, aline, bline, atags, btags):
1053 r"""
1054 Format "?" output and deal with leading tabs.
1055
1056 Example:
1057
1058 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001059 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1060 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001061 >>> for line in results: print(repr(line))
1062 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001063 '- \tabcDefghiJkl\n'
1064 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001065 '+ \tabcdefGhijkl\n'
1066 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001067 """
1068
1069 # Can hurt, but will probably help most of the time.
1070 common = min(_count_leading(aline, "\t"),
1071 _count_leading(bline, "\t"))
1072 common = min(common, _count_leading(atags[:common], " "))
Senthil Kumaran758025c2009-11-23 19:02:52 +00001073 common = min(common, _count_leading(btags[:common], " "))
Tim Peters5e824c32001-08-12 22:25:01 +00001074 atags = atags[common:].rstrip()
1075 btags = btags[common:].rstrip()
1076
Tim Peters8a9c2842001-09-22 21:30:22 +00001077 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001078 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001079 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001080
Tim Peters8a9c2842001-09-22 21:30:22 +00001081 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001082 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001083 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001084
1085# With respect to junk, an earlier version of ndiff simply refused to
1086# *start* a match with a junk element. The result was cases like this:
1087# before: private Thread currentThread;
1088# after: private volatile Thread currentThread;
1089# If you consider whitespace to be junk, the longest contiguous match
1090# not starting with junk is "e Thread currentThread". So ndiff reported
1091# that "e volatil" was inserted between the 't' and the 'e' in "private".
1092# While an accurate view, to people that's absurd. The current version
1093# looks for matching blocks that are entirely junk-free, then extends the
1094# longest one of those as far as possible but only with matching junk.
1095# So now "currentThread" is matched, then extended to suck up the
1096# preceding blank; then "private" is matched, and extended to suck up the
1097# following blank; then "Thread" is matched; and finally ndiff reports
1098# that "volatile " was inserted before "Thread". The only quibble
1099# remaining is that perhaps it was really the case that " volatile"
1100# was inserted after "private". I can live with that <wink>.
1101
1102import re
1103
1104def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1105 r"""
1106 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1107
1108 Examples:
1109
1110 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001111 True
Tim Peters5e824c32001-08-12 22:25:01 +00001112 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001113 True
Tim Peters5e824c32001-08-12 22:25:01 +00001114 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001115 False
Tim Peters5e824c32001-08-12 22:25:01 +00001116 """
1117
1118 return pat(line) is not None
1119
1120def IS_CHARACTER_JUNK(ch, ws=" \t"):
1121 r"""
1122 Return 1 for ignorable character: iff `ch` is a space or tab.
1123
1124 Examples:
1125
1126 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001127 True
Tim Peters5e824c32001-08-12 22:25:01 +00001128 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001129 True
Tim Peters5e824c32001-08-12 22:25:01 +00001130 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001131 False
Tim Peters5e824c32001-08-12 22:25:01 +00001132 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001133 False
Tim Peters5e824c32001-08-12 22:25:01 +00001134 """
1135
1136 return ch in ws
1137
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001138
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001139########################################################################
1140### Unified Diff
1141########################################################################
1142
1143def _format_range_unified(start, stop):
Raymond Hettinger49353d02011-04-11 12:40:58 -07001144 'Convert range to the "ed" format'
1145 # Per the diff spec at http://www.unix.org/single_unix_specification/
1146 beginning = start + 1 # lines start numbering with one
1147 length = stop - start
1148 if length == 1:
1149 return '{}'.format(beginning)
1150 if not length:
1151 beginning -= 1 # empty ranges begin at line just before the range
1152 return '{},{}'.format(beginning, length)
1153
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001154def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1155 tofiledate='', n=3, lineterm='\n'):
1156 r"""
1157 Compare two sequences of lines; generate the delta as a unified diff.
1158
1159 Unified diffs are a compact way of showing line changes and a few
1160 lines of context. The number of context lines is set by 'n' which
1161 defaults to three.
1162
Raymond Hettinger0887c732003-06-17 16:53:25 +00001163 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001164 created with a trailing newline. This is helpful so that inputs
1165 created from file.readlines() result in diffs that are suitable for
1166 file.writelines() since both the inputs and outputs have trailing
1167 newlines.
1168
1169 For inputs that do not have trailing newlines, set the lineterm
1170 argument to "" so that the output will be uniformly newline free.
1171
1172 The unidiff format normally has a header for filenames and modification
1173 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001174 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1175 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001176
1177 Example:
1178
1179 >>> for line in unified_diff('one two three four'.split(),
1180 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001181 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001182 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001183 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1184 --- Original 2005-01-26 23:30:50
1185 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001186 @@ -1,4 +1,4 @@
1187 +zero
1188 one
1189 -two
1190 -three
1191 +tree
1192 four
1193 """
1194
1195 started = False
1196 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1197 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001198 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001199 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1200 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1201 yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
1202 yield '+++ {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger49353d02011-04-11 12:40:58 -07001203
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001204 first, last = group[0], group[-1]
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001205 file1_range = _format_range_unified(first[1], last[2])
1206 file2_range = _format_range_unified(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001207 yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
1208
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001209 for tag, i1, i2, j1, j2 in group:
1210 if tag == 'equal':
1211 for line in a[i1:i2]:
1212 yield ' ' + line
1213 continue
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001214 if tag in {'replace', 'delete'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001215 for line in a[i1:i2]:
1216 yield '-' + line
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001217 if tag in {'replace', 'insert'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001218 for line in b[j1:j2]:
1219 yield '+' + line
1220
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001221
1222########################################################################
1223### Context Diff
1224########################################################################
1225
1226def _format_range_context(start, stop):
1227 'Convert range to the "ed" format'
1228 # Per the diff spec at http://www.unix.org/single_unix_specification/
1229 beginning = start + 1 # lines start numbering with one
1230 length = stop - start
1231 if not length:
1232 beginning -= 1 # empty ranges begin at line just before the range
1233 if length <= 1:
1234 return '{}'.format(beginning)
1235 return '{},{}'.format(beginning, beginning + length - 1)
1236
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001237# See http://www.unix.org/single_unix_specification/
1238def context_diff(a, b, fromfile='', tofile='',
1239 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1240 r"""
1241 Compare two sequences of lines; generate the delta as a context diff.
1242
1243 Context diffs are a compact way of showing line changes and a few
1244 lines of context. The number of context lines is set by 'n' which
1245 defaults to three.
1246
1247 By default, the diff control lines (those with *** or ---) are
1248 created with a trailing newline. This is helpful so that inputs
1249 created from file.readlines() result in diffs that are suitable for
1250 file.writelines() since both the inputs and outputs have trailing
1251 newlines.
1252
1253 For inputs that do not have trailing newlines, set the lineterm
1254 argument to "" so that the output will be uniformly newline free.
1255
1256 The context diff format normally has a header for filenames and
1257 modification times. Any or all of these may be specified using
1258 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001259 The modification times are normally expressed in the ISO 8601 format.
1260 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001261
1262 Example:
1263
Ezio Melottid8b509b2011-09-28 17:37:55 +03001264 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
1265 ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001266 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001267 *** Original
1268 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001269 ***************
1270 *** 1,4 ****
1271 one
1272 ! two
1273 ! three
1274 four
1275 --- 1,4 ----
1276 + zero
1277 one
1278 ! tree
1279 four
1280 """
1281
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001282 prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001283 started = False
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001284 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1285 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001286 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001287 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1288 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1289 yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
1290 yield '--- {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001291
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001292 first, last = group[0], group[-1]
Raymond Hettinger49353d02011-04-11 12:40:58 -07001293 yield '***************' + lineterm
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001294
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001295 file1_range = _format_range_context(first[1], last[2])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001296 yield '*** {} ****{}'.format(file1_range, lineterm)
1297
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001298 if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001299 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001300 if tag != 'insert':
1301 for line in a[i1:i2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001302 yield prefix[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001303
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001304 file2_range = _format_range_context(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001305 yield '--- {} ----{}'.format(file2_range, lineterm)
1306
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001307 if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001308 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001309 if tag != 'delete':
1310 for line in b[j1:j2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001311 yield prefix[tag] + line
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001312
Tim Peters81b92512002-04-29 01:37:32 +00001313def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001314 r"""
1315 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1316
1317 Optional keyword parameters `linejunk` and `charjunk` are for filter
1318 functions (or None):
1319
1320 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001321 return true iff the string is junk. The default is None, and is
1322 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1323 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001324
1325 - charjunk: A function that should accept a string of length 1. The
1326 default is module-level function IS_CHARACTER_JUNK, which filters out
1327 whitespace characters (a blank or tab; note: bad idea to include newline
1328 in this!).
1329
1330 Tools/scripts/ndiff.py is a command-line front-end to this function.
1331
1332 Example:
1333
Ezio Melottid8b509b2011-09-28 17:37:55 +03001334 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
1335 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001336 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001337 - one
1338 ? ^
1339 + ore
1340 ? ^
1341 - two
1342 - three
1343 ? -
1344 + tree
1345 + emu
1346 """
1347 return Differ(linejunk, charjunk).compare(a, b)
1348
Martin v. Löwise064b412004-08-29 16:34:40 +00001349def _mdiff(fromlines, tolines, context=None, linejunk=None,
1350 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001351 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001352
1353 Arguments:
1354 fromlines -- list of text lines to compared to tolines
1355 tolines -- list of text lines to be compared to fromlines
1356 context -- number of context lines to display on each side of difference,
1357 if None, all from/to text lines will be generated.
1358 linejunk -- passed on to ndiff (see ndiff documentation)
1359 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001360
Martin v. Löwise064b412004-08-29 16:34:40 +00001361 This function returns an interator which returns a tuple:
1362 (from line tuple, to line tuple, boolean flag)
1363
1364 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001365 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001366 line text -- original line text with following markers inserted:
1367 '\0+' -- marks start of added text
1368 '\0-' -- marks start of deleted text
1369 '\0^' -- marks start of changed text
1370 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001371
Martin v. Löwise064b412004-08-29 16:34:40 +00001372 boolean flag -- None indicates context separation, True indicates
1373 either "from" or "to" line contains a change, otherwise False.
1374
1375 This function/iterator was originally developed to generate side by side
1376 file difference for making HTML pages (see HtmlDiff class for example
1377 usage).
1378
1379 Note, this function utilizes the ndiff function to generate the side by
1380 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001381 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001382 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001383 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001384
1385 # regular expression for finding intraline change indices
1386 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001387
Martin v. Löwise064b412004-08-29 16:34:40 +00001388 # create the difference iterator to generate the differences
1389 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1390
1391 def _make_line(lines, format_key, side, num_lines=[0,0]):
1392 """Returns line of text with user's change markup and line formatting.
1393
1394 lines -- list of lines from the ndiff generator to produce a line of
1395 text from. When producing the line of text to return, the
1396 lines used are removed from this list.
1397 format_key -- '+' return first line in list with "add" markup around
1398 the entire line.
1399 '-' return first line in list with "delete" markup around
1400 the entire line.
1401 '?' return first line in list with add/delete/change
1402 intraline markup (indices obtained from second line)
1403 None return first line in list with no markup
1404 side -- indice into the num_lines list (0=from,1=to)
1405 num_lines -- from/to current line number. This is NOT intended to be a
1406 passed parameter. It is present as a keyword argument to
1407 maintain memory of the current line numbers between calls
1408 of this function.
1409
1410 Note, this function is purposefully not defined at the module scope so
1411 that data it needs from its parent function (within whose context it
1412 is defined) does not need to be of module scope.
1413 """
1414 num_lines[side] += 1
1415 # Handle case where no user markup is to be added, just return line of
1416 # text with user's line format to allow for usage of the line number.
1417 if format_key is None:
1418 return (num_lines[side],lines.pop(0)[2:])
1419 # Handle case of intraline changes
1420 if format_key == '?':
1421 text, markers = lines.pop(0), lines.pop(0)
1422 # find intraline changes (store change type and indices in tuples)
1423 sub_info = []
1424 def record_sub_info(match_object,sub_info=sub_info):
1425 sub_info.append([match_object.group(1)[0],match_object.span()])
1426 return match_object.group(1)
1427 change_re.sub(record_sub_info,markers)
1428 # process each tuple inserting our special marks that won't be
1429 # noticed by an xml/html escaper.
1430 for key,(begin,end) in sub_info[::-1]:
1431 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1432 text = text[2:]
1433 # Handle case of add/delete entire line
1434 else:
1435 text = lines.pop(0)[2:]
1436 # if line of text is just a newline, insert a space so there is
1437 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001438 if not text:
1439 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001440 # insert marks that won't be noticed by an xml/html escaper.
1441 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001442 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001443 # thing (such as adding the line number) then replace the special
1444 # marks with what the user's change markup.
1445 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001446
Martin v. Löwise064b412004-08-29 16:34:40 +00001447 def _line_iterator():
1448 """Yields from/to lines of text with a change indication.
1449
1450 This function is an iterator. It itself pulls lines from a
1451 differencing iterator, processes them and yields them. When it can
1452 it yields both a "from" and a "to" line, otherwise it will yield one
1453 or the other. In addition to yielding the lines of from/to text, a
1454 boolean flag is yielded to indicate if the text line(s) have
1455 differences in them.
1456
1457 Note, this function is purposefully not defined at the module scope so
1458 that data it needs from its parent function (within whose context it
1459 is defined) does not need to be of module scope.
1460 """
1461 lines = []
1462 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001463 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001464 # Load up next 4 lines so we can look ahead, create strings which
1465 # are a concatenation of the first character of each of the 4 lines
1466 # so we can do some very readable comparisons.
1467 while len(lines) < 4:
1468 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001469 lines.append(next(diff_lines_iterator))
Martin v. Löwise064b412004-08-29 16:34:40 +00001470 except StopIteration:
1471 lines.append('X')
1472 s = ''.join([line[0] for line in lines])
1473 if s.startswith('X'):
1474 # When no more lines, pump out any remaining blank lines so the
1475 # corresponding add/delete lines get a matching blank line so
1476 # all line pairs get yielded at the next level.
1477 num_blanks_to_yield = num_blanks_pending
1478 elif s.startswith('-?+?'):
1479 # simple intraline change
1480 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1481 continue
1482 elif s.startswith('--++'):
1483 # in delete block, add block coming: we do NOT want to get
1484 # caught up on blank lines yet, just process the delete line
1485 num_blanks_pending -= 1
1486 yield _make_line(lines,'-',0), None, True
1487 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001488 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001489 # in delete block and see a intraline change or unchanged line
1490 # coming: yield the delete line and then blanks
1491 from_line,to_line = _make_line(lines,'-',0), None
1492 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1493 elif s.startswith('-+?'):
1494 # intraline change
1495 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1496 continue
1497 elif s.startswith('-?+'):
1498 # intraline change
1499 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1500 continue
1501 elif s.startswith('-'):
1502 # delete FROM line
1503 num_blanks_pending -= 1
1504 yield _make_line(lines,'-',0), None, True
1505 continue
1506 elif s.startswith('+--'):
1507 # in add block, delete block coming: we do NOT want to get
1508 # caught up on blank lines yet, just process the add line
1509 num_blanks_pending += 1
1510 yield None, _make_line(lines,'+',1), True
1511 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001512 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001513 # will be leaving an add block: yield blanks then add line
1514 from_line, to_line = None, _make_line(lines,'+',1)
1515 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1516 elif s.startswith('+'):
1517 # inside an add block, yield the add line
1518 num_blanks_pending += 1
1519 yield None, _make_line(lines,'+',1), True
1520 continue
1521 elif s.startswith(' '):
1522 # unchanged text, yield it to both sides
1523 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1524 continue
1525 # Catch up on the blank lines so when we yield the next from/to
1526 # pair, they are lined up.
1527 while(num_blanks_to_yield < 0):
1528 num_blanks_to_yield += 1
1529 yield None,('','\n'),True
1530 while(num_blanks_to_yield > 0):
1531 num_blanks_to_yield -= 1
1532 yield ('','\n'),None,True
1533 if s.startswith('X'):
1534 raise StopIteration
1535 else:
1536 yield from_line,to_line,True
1537
1538 def _line_pair_iterator():
1539 """Yields from/to lines of text with a change indication.
1540
1541 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001542 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001543 always yields a pair of from/to text lines (with the change
1544 indication). If necessary it will collect single from/to lines
1545 until it has a matching pair from/to pair to yield.
1546
1547 Note, this function is purposefully not defined at the module scope so
1548 that data it needs from its parent function (within whose context it
1549 is defined) does not need to be of module scope.
1550 """
1551 line_iterator = _line_iterator()
1552 fromlines,tolines=[],[]
1553 while True:
1554 # Collecting lines of text until we have a from/to pair
1555 while (len(fromlines)==0 or len(tolines)==0):
Georg Brandla18af4e2007-04-21 15:47:16 +00001556 from_line, to_line, found_diff = next(line_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001557 if from_line is not None:
1558 fromlines.append((from_line,found_diff))
1559 if to_line is not None:
1560 tolines.append((to_line,found_diff))
1561 # Once we have a pair, remove them from the collection and yield it
1562 from_line, fromDiff = fromlines.pop(0)
1563 to_line, to_diff = tolines.pop(0)
1564 yield (from_line,to_line,fromDiff or to_diff)
1565
1566 # Handle case where user does not want context differencing, just yield
1567 # them up without doing anything else with them.
1568 line_pair_iterator = _line_pair_iterator()
1569 if context is None:
1570 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +00001571 yield next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001572 # Handle case where user wants context differencing. We must do some
1573 # storage of lines until we know for sure that they are to be yielded.
1574 else:
1575 context += 1
1576 lines_to_write = 0
1577 while True:
1578 # Store lines up until we find a difference, note use of a
1579 # circular queue because we only need to keep around what
1580 # we need for context.
1581 index, contextLines = 0, [None]*(context)
1582 found_diff = False
1583 while(found_diff is False):
Georg Brandla18af4e2007-04-21 15:47:16 +00001584 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001585 i = index % context
1586 contextLines[i] = (from_line, to_line, found_diff)
1587 index += 1
1588 # Yield lines that we have collected so far, but first yield
1589 # the user's separator.
1590 if index > context:
1591 yield None, None, None
1592 lines_to_write = context
1593 else:
1594 lines_to_write = index
1595 index = 0
1596 while(lines_to_write):
1597 i = index % context
1598 index += 1
1599 yield contextLines[i]
1600 lines_to_write -= 1
1601 # Now yield the context lines after the change
1602 lines_to_write = context-1
1603 while(lines_to_write):
Georg Brandla18af4e2007-04-21 15:47:16 +00001604 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001605 # If another change within the context, extend the context
1606 if found_diff:
1607 lines_to_write = context-1
1608 else:
1609 lines_to_write -= 1
1610 yield from_line, to_line, found_diff
1611
1612
1613_file_template = """
1614<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1615 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1616
1617<html>
1618
1619<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001620 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001621 content="text/html; charset=ISO-8859-1" />
1622 <title></title>
1623 <style type="text/css">%(styles)s
1624 </style>
1625</head>
1626
1627<body>
1628 %(table)s%(legend)s
1629</body>
1630
1631</html>"""
1632
1633_styles = """
1634 table.diff {font-family:Courier; border:medium;}
1635 .diff_header {background-color:#e0e0e0}
1636 td.diff_header {text-align:right}
1637 .diff_next {background-color:#c0c0c0}
1638 .diff_add {background-color:#aaffaa}
1639 .diff_chg {background-color:#ffff77}
1640 .diff_sub {background-color:#ffaaaa}"""
1641
1642_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001643 <table class="diff" id="difflib_chg_%(prefix)s_top"
1644 cellspacing="0" cellpadding="0" rules="groups" >
1645 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001646 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1647 %(header_row)s
1648 <tbody>
1649%(data_rows)s </tbody>
1650 </table>"""
1651
1652_legend = """
1653 <table class="diff" summary="Legends">
1654 <tr> <th colspan="2"> Legends </th> </tr>
1655 <tr> <td> <table border="" summary="Colors">
1656 <tr><th> Colors </th> </tr>
1657 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1658 <tr><td class="diff_chg">Changed</td> </tr>
1659 <tr><td class="diff_sub">Deleted</td> </tr>
1660 </table></td>
1661 <td> <table border="" summary="Links">
1662 <tr><th colspan="2"> Links </th> </tr>
1663 <tr><td>(f)irst change</td> </tr>
1664 <tr><td>(n)ext change</td> </tr>
1665 <tr><td>(t)op</td> </tr>
1666 </table></td> </tr>
1667 </table>"""
1668
1669class HtmlDiff(object):
1670 """For producing HTML side by side comparison with change highlights.
1671
1672 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001673 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001674 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001675 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001676
Martin v. Löwise064b412004-08-29 16:34:40 +00001677 The following methods are provided for HTML generation:
1678
1679 make_table -- generates HTML for a single side by side table
1680 make_file -- generates complete HTML file with a single side by side table
1681
Tim Peters48bd7f32004-08-29 22:38:38 +00001682 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001683 """
1684
1685 _file_template = _file_template
1686 _styles = _styles
1687 _table_template = _table_template
1688 _legend = _legend
1689 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001690
Martin v. Löwise064b412004-08-29 16:34:40 +00001691 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1692 charjunk=IS_CHARACTER_JUNK):
1693 """HtmlDiff instance initializer
1694
1695 Arguments:
1696 tabsize -- tab stop spacing, defaults to 8.
1697 wrapcolumn -- column number where lines are broken and wrapped,
1698 defaults to None where lines are not wrapped.
1699 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001700 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001701 ndiff() documentation for argument default values and descriptions.
1702 """
1703 self._tabsize = tabsize
1704 self._wrapcolumn = wrapcolumn
1705 self._linejunk = linejunk
1706 self._charjunk = charjunk
1707
1708 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1709 numlines=5):
1710 """Returns HTML file of side by side comparison with change highlights
1711
1712 Arguments:
1713 fromlines -- list of "from" lines
1714 tolines -- list of "to" lines
1715 fromdesc -- "from" file column header string
1716 todesc -- "to" file column header string
1717 context -- set to True for contextual differences (defaults to False
1718 which shows full differences).
1719 numlines -- number of context lines. When context is set True,
1720 controls number of lines displayed before and after the change.
1721 When context is False, controls the number of lines to place
1722 the "next" link anchors before the next change (so click of
1723 "next" link jumps to just before the change).
1724 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001725
Martin v. Löwise064b412004-08-29 16:34:40 +00001726 return self._file_template % dict(
1727 styles = self._styles,
1728 legend = self._legend,
1729 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1730 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001731
Martin v. Löwise064b412004-08-29 16:34:40 +00001732 def _tab_newline_replace(self,fromlines,tolines):
1733 """Returns from/to line lists with tabs expanded and newlines removed.
1734
1735 Instead of tab characters being replaced by the number of spaces
1736 needed to fill in to the next tab stop, this function will fill
1737 the space with tab characters. This is done so that the difference
1738 algorithms can identify changes in a file when tabs are replaced by
1739 spaces and vice versa. At the end of the HTML generation, the tab
1740 characters will be replaced with a nonbreakable space.
1741 """
1742 def expand_tabs(line):
1743 # hide real spaces
1744 line = line.replace(' ','\0')
1745 # expand tabs into spaces
1746 line = line.expandtabs(self._tabsize)
Ezio Melotti13925002011-03-16 11:05:33 +02001747 # replace spaces from expanded tabs back into tab characters
Martin v. Löwise064b412004-08-29 16:34:40 +00001748 # (we'll replace them with markup after we do differencing)
1749 line = line.replace(' ','\t')
1750 return line.replace('\0',' ').rstrip('\n')
1751 fromlines = [expand_tabs(line) for line in fromlines]
1752 tolines = [expand_tabs(line) for line in tolines]
1753 return fromlines,tolines
1754
1755 def _split_line(self,data_list,line_num,text):
1756 """Builds list of text lines by splitting text lines at wrap point
1757
1758 This function will determine if the input text line needs to be
1759 wrapped (split) into separate lines. If so, the first wrap point
1760 will be determined and the first line appended to the output
1761 text line list. This function is used recursively to handle
1762 the second part of the split line to further split it.
1763 """
1764 # if blank line or context separator, just add it to the output list
1765 if not line_num:
1766 data_list.append((line_num,text))
1767 return
1768
1769 # if line text doesn't need wrapping, just add it to the output list
1770 size = len(text)
1771 max = self._wrapcolumn
1772 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1773 data_list.append((line_num,text))
1774 return
1775
1776 # scan text looking for the wrap point, keeping track if the wrap
1777 # point is inside markers
1778 i = 0
1779 n = 0
1780 mark = ''
1781 while n < max and i < size:
1782 if text[i] == '\0':
1783 i += 1
1784 mark = text[i]
1785 i += 1
1786 elif text[i] == '\1':
1787 i += 1
1788 mark = ''
1789 else:
1790 i += 1
1791 n += 1
1792
1793 # wrap point is inside text, break it up into separate lines
1794 line1 = text[:i]
1795 line2 = text[i:]
1796
1797 # if wrap point is inside markers, place end marker at end of first
1798 # line and start marker at beginning of second line because each
1799 # line will have its own table tag markup around it.
1800 if mark:
1801 line1 = line1 + '\1'
1802 line2 = '\0' + mark + line2
1803
Tim Peters48bd7f32004-08-29 22:38:38 +00001804 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001805 data_list.append((line_num,line1))
1806
Tim Peters48bd7f32004-08-29 22:38:38 +00001807 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001808 self._split_line(data_list,'>',line2)
1809
1810 def _line_wrapper(self,diffs):
1811 """Returns iterator that splits (wraps) mdiff text lines"""
1812
1813 # pull from/to data and flags from mdiff iterator
1814 for fromdata,todata,flag in diffs:
1815 # check for context separators and pass them through
1816 if flag is None:
1817 yield fromdata,todata,flag
1818 continue
1819 (fromline,fromtext),(toline,totext) = fromdata,todata
1820 # for each from/to line split it at the wrap column to form
1821 # list of text lines.
1822 fromlist,tolist = [],[]
1823 self._split_line(fromlist,fromline,fromtext)
1824 self._split_line(tolist,toline,totext)
1825 # yield from/to line in pairs inserting blank lines as
1826 # necessary when one side has more wrapped lines
1827 while fromlist or tolist:
1828 if fromlist:
1829 fromdata = fromlist.pop(0)
1830 else:
1831 fromdata = ('',' ')
1832 if tolist:
1833 todata = tolist.pop(0)
1834 else:
1835 todata = ('',' ')
1836 yield fromdata,todata,flag
1837
1838 def _collect_lines(self,diffs):
1839 """Collects mdiff output into separate lists
1840
1841 Before storing the mdiff from/to data into a list, it is converted
1842 into a single line of text with HTML markup.
1843 """
1844
1845 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001846 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001847 for fromdata,todata,flag in diffs:
1848 try:
1849 # store HTML markup of the lines into the lists
1850 fromlist.append(self._format_line(0,flag,*fromdata))
1851 tolist.append(self._format_line(1,flag,*todata))
1852 except TypeError:
1853 # exceptions occur for lines where context separators go
1854 fromlist.append(None)
1855 tolist.append(None)
1856 flaglist.append(flag)
1857 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001858
Martin v. Löwise064b412004-08-29 16:34:40 +00001859 def _format_line(self,side,flag,linenum,text):
1860 """Returns HTML markup of "from" / "to" text lines
1861
1862 side -- 0 or 1 indicating "from" or "to" text
1863 flag -- indicates if difference on line
1864 linenum -- line number (used for line number column)
1865 text -- line text to be marked up
1866 """
1867 try:
1868 linenum = '%d' % linenum
1869 id = ' id="%s%s"' % (self._prefix[side],linenum)
1870 except TypeError:
1871 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001872 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001873 # replace those things that would get confused with HTML symbols
1874 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1875
1876 # make space non-breakable so they don't get compressed or line wrapped
1877 text = text.replace(' ','&nbsp;').rstrip()
1878
1879 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1880 % (id,linenum,text)
1881
1882 def _make_prefix(self):
1883 """Create unique anchor prefixes"""
1884
1885 # Generate a unique anchor prefix so multiple tables
1886 # can exist on the same HTML page without conflicts.
1887 fromprefix = "from%d_" % HtmlDiff._default_prefix
1888 toprefix = "to%d_" % HtmlDiff._default_prefix
1889 HtmlDiff._default_prefix += 1
1890 # store prefixes so line format method has access
1891 self._prefix = [fromprefix,toprefix]
1892
1893 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1894 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001895
Martin v. Löwise064b412004-08-29 16:34:40 +00001896 # all anchor names will be generated using the unique "to" prefix
1897 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001898
Martin v. Löwise064b412004-08-29 16:34:40 +00001899 # process change flags, generating middle column of next anchors/links
1900 next_id = ['']*len(flaglist)
1901 next_href = ['']*len(flaglist)
1902 num_chg, in_change = 0, False
1903 last = 0
1904 for i,flag in enumerate(flaglist):
1905 if flag:
1906 if not in_change:
1907 in_change = True
1908 last = i
1909 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001910 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001911 # link
1912 i = max([0,i-numlines])
1913 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001914 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001915 # change
1916 num_chg += 1
1917 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1918 toprefix,num_chg)
1919 else:
1920 in_change = False
1921 # check for cases where there is no content to avoid exceptions
1922 if not flaglist:
1923 flaglist = [False]
1924 next_id = ['']
1925 next_href = ['']
1926 last = 0
1927 if context:
1928 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1929 tolist = fromlist
1930 else:
1931 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1932 # if not a change on first line, drop a link
1933 if not flaglist[0]:
1934 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1935 # redo the last link to link to the top
1936 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1937
1938 return fromlist,tolist,flaglist,next_href,next_id
1939
1940 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1941 numlines=5):
1942 """Returns HTML table of side by side comparison with change highlights
1943
1944 Arguments:
1945 fromlines -- list of "from" lines
1946 tolines -- list of "to" lines
1947 fromdesc -- "from" file column header string
1948 todesc -- "to" file column header string
1949 context -- set to True for contextual differences (defaults to False
1950 which shows full differences).
1951 numlines -- number of context lines. When context is set True,
1952 controls number of lines displayed before and after the change.
1953 When context is False, controls the number of lines to place
1954 the "next" link anchors before the next change (so click of
1955 "next" link jumps to just before the change).
1956 """
1957
1958 # make unique anchor prefixes so that multiple tables may exist
1959 # on the same page without conflict.
1960 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001961
Martin v. Löwise064b412004-08-29 16:34:40 +00001962 # change tabs to spaces before it gets more difficult after we insert
1963 # markkup
1964 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001965
Martin v. Löwise064b412004-08-29 16:34:40 +00001966 # create diffs iterator which generates side by side from/to data
1967 if context:
1968 context_lines = numlines
1969 else:
1970 context_lines = None
1971 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1972 charjunk=self._charjunk)
1973
1974 # set up iterator to wrap lines that exceed desired width
1975 if self._wrapcolumn:
1976 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001977
Martin v. Löwise064b412004-08-29 16:34:40 +00001978 # collect up from/to lines and flags into lists (also format the lines)
1979 fromlist,tolist,flaglist = self._collect_lines(diffs)
1980
1981 # process change flags, generating middle column of next anchors/links
1982 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1983 fromlist,tolist,flaglist,context,numlines)
1984
Guido van Rossumd8faa362007-04-27 19:54:29 +00001985 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00001986 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1987 '<td class="diff_next">%s</td>%s</tr>\n'
1988 for i in range(len(flaglist)):
1989 if flaglist[i] is None:
1990 # mdiff yields None on separator lines skip the bogus ones
1991 # generated for the first line
1992 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001993 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00001994 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001995 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00001996 next_href[i],tolist[i]))
1997 if fromdesc or todesc:
1998 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
1999 '<th class="diff_next"><br /></th>',
2000 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
2001 '<th class="diff_next"><br /></th>',
2002 '<th colspan="2" class="diff_header">%s</th>' % todesc)
2003 else:
2004 header_row = ''
2005
2006 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002007 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00002008 header_row=header_row,
2009 prefix=self._prefix[1])
2010
2011 return table.replace('\0+','<span class="diff_add">'). \
2012 replace('\0-','<span class="diff_sub">'). \
2013 replace('\0^','<span class="diff_chg">'). \
2014 replace('\1','</span>'). \
2015 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00002016
Martin v. Löwise064b412004-08-29 16:34:40 +00002017del re
2018
Tim Peters5e824c32001-08-12 22:25:01 +00002019def restore(delta, which):
2020 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00002021 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00002022
2023 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
2024 lines originating from file 1 or 2 (parameter `which`), stripping off line
2025 prefixes.
2026
2027 Examples:
2028
Ezio Melottid8b509b2011-09-28 17:37:55 +03002029 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
2030 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Tim Peters8a9c2842001-09-22 21:30:22 +00002031 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002032 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002033 one
2034 two
2035 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002036 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002037 ore
2038 tree
2039 emu
2040 """
2041 try:
2042 tag = {1: "- ", 2: "+ "}[int(which)]
2043 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002044 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Tim Peters5e824c32001-08-12 22:25:01 +00002045 % which)
2046 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002047 for line in delta:
2048 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002049 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002050
Tim Peters9ae21482001-02-10 08:00:53 +00002051def _test():
2052 import doctest, difflib
2053 return doctest.testmod(difflib)
2054
2055if __name__ == "__main__":
2056 _test()