blob: ae377d745dd3efe096bc60fcc27eadbda427afcf [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
925 for line in g:
926 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000927
928 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000929 """Generate comparison results for a same-tagged range."""
Guido van Rossum805365e2007-05-07 22:24:25 +0000930 for i in range(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000931 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000932
933 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
934 assert alo < ahi and blo < bhi
935 # dump the shorter block first -- reduces the burden on short-term
936 # memory if the blocks are of very different sizes
937 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000938 first = self._dump('+', b, blo, bhi)
939 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000940 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000941 first = self._dump('-', a, alo, ahi)
942 second = self._dump('+', b, blo, bhi)
943
944 for g in first, second:
945 for line in g:
946 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000947
948 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
949 r"""
950 When replacing one block of lines with another, search the blocks
951 for *similar* lines; the best-matching pair (if any) is used as a
952 synch point, and intraline difference marking is done on the
953 similar pair. Lots of work, but often worth it.
954
955 Example:
956
957 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000958 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
959 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000960 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000961 - abcDefghiJkl
962 ? ^ ^ ^
963 + abcdefGhijkl
964 ? ^ ^ ^
965 """
966
Tim Peters5e824c32001-08-12 22:25:01 +0000967 # don't synch up unless the lines have a similarity score of at
968 # least cutoff; best_ratio tracks the best score seen so far
969 best_ratio, cutoff = 0.74, 0.75
970 cruncher = SequenceMatcher(self.charjunk)
971 eqi, eqj = None, None # 1st indices of equal lines (if any)
972
973 # search for the pair that matches best without being identical
974 # (identical lines must be junk lines, & we don't want to synch up
975 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000976 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000977 bj = b[j]
978 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000979 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000980 ai = a[i]
981 if ai == bj:
982 if eqi is None:
983 eqi, eqj = i, j
984 continue
985 cruncher.set_seq1(ai)
986 # computing similarity is expensive, so use the quick
987 # upper bounds first -- have seen this speed up messy
988 # compares by a factor of 3.
989 # note that ratio() is only expensive to compute the first
990 # time it's called on a sequence pair; the expensive part
991 # of the computation is cached by cruncher
992 if cruncher.real_quick_ratio() > best_ratio and \
993 cruncher.quick_ratio() > best_ratio and \
994 cruncher.ratio() > best_ratio:
995 best_ratio, best_i, best_j = cruncher.ratio(), i, j
996 if best_ratio < cutoff:
997 # no non-identical "pretty close" pair
998 if eqi is None:
999 # no identical pair either -- treat it as a straight replace
Tim Peters8a9c2842001-09-22 21:30:22 +00001000 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
1001 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001002 return
1003 # no close pair, but an identical pair -- synch up on that
1004 best_i, best_j, best_ratio = eqi, eqj, 1.0
1005 else:
1006 # there's a close pair, so forget the identical pair (if any)
1007 eqi = None
1008
1009 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
1010 # identical
Tim Peters5e824c32001-08-12 22:25:01 +00001011
1012 # pump out diffs from before the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001013 for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
1014 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001015
1016 # do intraline marking on the synch pair
1017 aelt, belt = a[best_i], b[best_j]
1018 if eqi is None:
1019 # pump out a '-', '?', '+', '?' quad for the synched lines
1020 atags = btags = ""
1021 cruncher.set_seqs(aelt, belt)
1022 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1023 la, lb = ai2 - ai1, bj2 - bj1
1024 if tag == 'replace':
1025 atags += '^' * la
1026 btags += '^' * lb
1027 elif tag == 'delete':
1028 atags += '-' * la
1029 elif tag == 'insert':
1030 btags += '+' * lb
1031 elif tag == 'equal':
1032 atags += ' ' * la
1033 btags += ' ' * lb
1034 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001035 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +00001036 for line in self._qformat(aelt, belt, atags, btags):
1037 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001038 else:
1039 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001040 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001041
1042 # pump out diffs from after the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +00001043 for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
1044 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001045
1046 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001047 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001048 if alo < ahi:
1049 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001050 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001051 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001052 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001053 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001054 g = self._dump('+', b, blo, bhi)
1055
1056 for line in g:
1057 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001058
1059 def _qformat(self, aline, bline, atags, btags):
1060 r"""
1061 Format "?" output and deal with leading tabs.
1062
1063 Example:
1064
1065 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001066 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1067 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001068 >>> for line in results: print(repr(line))
1069 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001070 '- \tabcDefghiJkl\n'
1071 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001072 '+ \tabcdefGhijkl\n'
1073 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001074 """
1075
1076 # Can hurt, but will probably help most of the time.
1077 common = min(_count_leading(aline, "\t"),
1078 _count_leading(bline, "\t"))
1079 common = min(common, _count_leading(atags[:common], " "))
Senthil Kumaran758025c2009-11-23 19:02:52 +00001080 common = min(common, _count_leading(btags[:common], " "))
Tim Peters5e824c32001-08-12 22:25:01 +00001081 atags = atags[common:].rstrip()
1082 btags = btags[common:].rstrip()
1083
Tim Peters8a9c2842001-09-22 21:30:22 +00001084 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001085 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001086 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001087
Tim Peters8a9c2842001-09-22 21:30:22 +00001088 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001089 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001090 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001091
1092# With respect to junk, an earlier version of ndiff simply refused to
1093# *start* a match with a junk element. The result was cases like this:
1094# before: private Thread currentThread;
1095# after: private volatile Thread currentThread;
1096# If you consider whitespace to be junk, the longest contiguous match
1097# not starting with junk is "e Thread currentThread". So ndiff reported
1098# that "e volatil" was inserted between the 't' and the 'e' in "private".
1099# While an accurate view, to people that's absurd. The current version
1100# looks for matching blocks that are entirely junk-free, then extends the
1101# longest one of those as far as possible but only with matching junk.
1102# So now "currentThread" is matched, then extended to suck up the
1103# preceding blank; then "private" is matched, and extended to suck up the
1104# following blank; then "Thread" is matched; and finally ndiff reports
1105# that "volatile " was inserted before "Thread". The only quibble
1106# remaining is that perhaps it was really the case that " volatile"
1107# was inserted after "private". I can live with that <wink>.
1108
1109import re
1110
1111def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1112 r"""
1113 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1114
1115 Examples:
1116
1117 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001118 True
Tim Peters5e824c32001-08-12 22:25:01 +00001119 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001120 True
Tim Peters5e824c32001-08-12 22:25:01 +00001121 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001122 False
Tim Peters5e824c32001-08-12 22:25:01 +00001123 """
1124
1125 return pat(line) is not None
1126
1127def IS_CHARACTER_JUNK(ch, ws=" \t"):
1128 r"""
1129 Return 1 for ignorable character: iff `ch` is a space or tab.
1130
1131 Examples:
1132
1133 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001134 True
Tim Peters5e824c32001-08-12 22:25:01 +00001135 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001136 True
Tim Peters5e824c32001-08-12 22:25:01 +00001137 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001138 False
Tim Peters5e824c32001-08-12 22:25:01 +00001139 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001140 False
Tim Peters5e824c32001-08-12 22:25:01 +00001141 """
1142
1143 return ch in ws
1144
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001145
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001146########################################################################
1147### Unified Diff
1148########################################################################
1149
1150def _format_range_unified(start, stop):
Raymond Hettinger49353d02011-04-11 12:40:58 -07001151 'Convert range to the "ed" format'
1152 # Per the diff spec at http://www.unix.org/single_unix_specification/
1153 beginning = start + 1 # lines start numbering with one
1154 length = stop - start
1155 if length == 1:
1156 return '{}'.format(beginning)
1157 if not length:
1158 beginning -= 1 # empty ranges begin at line just before the range
1159 return '{},{}'.format(beginning, length)
1160
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001161def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1162 tofiledate='', n=3, lineterm='\n'):
1163 r"""
1164 Compare two sequences of lines; generate the delta as a unified diff.
1165
1166 Unified diffs are a compact way of showing line changes and a few
1167 lines of context. The number of context lines is set by 'n' which
1168 defaults to three.
1169
Raymond Hettinger0887c732003-06-17 16:53:25 +00001170 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001171 created with a trailing newline. This is helpful so that inputs
1172 created from file.readlines() result in diffs that are suitable for
1173 file.writelines() since both the inputs and outputs have trailing
1174 newlines.
1175
1176 For inputs that do not have trailing newlines, set the lineterm
1177 argument to "" so that the output will be uniformly newline free.
1178
1179 The unidiff format normally has a header for filenames and modification
1180 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001181 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1182 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001183
1184 Example:
1185
1186 >>> for line in unified_diff('one two three four'.split(),
1187 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001188 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001189 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001190 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1191 --- Original 2005-01-26 23:30:50
1192 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001193 @@ -1,4 +1,4 @@
1194 +zero
1195 one
1196 -two
1197 -three
1198 +tree
1199 four
1200 """
1201
1202 started = False
1203 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1204 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001205 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001206 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1207 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1208 yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
1209 yield '+++ {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger49353d02011-04-11 12:40:58 -07001210
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001211 first, last = group[0], group[-1]
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001212 file1_range = _format_range_unified(first[1], last[2])
1213 file2_range = _format_range_unified(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001214 yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
1215
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001216 for tag, i1, i2, j1, j2 in group:
1217 if tag == 'equal':
1218 for line in a[i1:i2]:
1219 yield ' ' + line
1220 continue
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001221 if tag in {'replace', 'delete'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001222 for line in a[i1:i2]:
1223 yield '-' + line
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001224 if tag in {'replace', 'insert'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001225 for line in b[j1:j2]:
1226 yield '+' + line
1227
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001228
1229########################################################################
1230### Context Diff
1231########################################################################
1232
1233def _format_range_context(start, stop):
1234 'Convert range to the "ed" format'
1235 # Per the diff spec at http://www.unix.org/single_unix_specification/
1236 beginning = start + 1 # lines start numbering with one
1237 length = stop - start
1238 if not length:
1239 beginning -= 1 # empty ranges begin at line just before the range
1240 if length <= 1:
1241 return '{}'.format(beginning)
1242 return '{},{}'.format(beginning, beginning + length - 1)
1243
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001244# See http://www.unix.org/single_unix_specification/
1245def context_diff(a, b, fromfile='', tofile='',
1246 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1247 r"""
1248 Compare two sequences of lines; generate the delta as a context diff.
1249
1250 Context diffs are a compact way of showing line changes and a few
1251 lines of context. The number of context lines is set by 'n' which
1252 defaults to three.
1253
1254 By default, the diff control lines (those with *** or ---) are
1255 created with a trailing newline. This is helpful so that inputs
1256 created from file.readlines() result in diffs that are suitable for
1257 file.writelines() since both the inputs and outputs have trailing
1258 newlines.
1259
1260 For inputs that do not have trailing newlines, set the lineterm
1261 argument to "" so that the output will be uniformly newline free.
1262
1263 The context diff format normally has a header for filenames and
1264 modification times. Any or all of these may be specified using
1265 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001266 The modification times are normally expressed in the ISO 8601 format.
1267 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001268
1269 Example:
1270
Ezio Melottid8b509b2011-09-28 17:37:55 +03001271 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
1272 ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001273 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001274 *** Original
1275 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001276 ***************
1277 *** 1,4 ****
1278 one
1279 ! two
1280 ! three
1281 four
1282 --- 1,4 ----
1283 + zero
1284 one
1285 ! tree
1286 four
1287 """
1288
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001289 prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001290 started = False
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001291 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1292 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001293 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001294 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1295 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1296 yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
1297 yield '--- {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001298
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001299 first, last = group[0], group[-1]
Raymond Hettinger49353d02011-04-11 12:40:58 -07001300 yield '***************' + lineterm
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001301
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001302 file1_range = _format_range_context(first[1], last[2])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001303 yield '*** {} ****{}'.format(file1_range, lineterm)
1304
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001305 if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001306 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001307 if tag != 'insert':
1308 for line in a[i1:i2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001309 yield prefix[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001310
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001311 file2_range = _format_range_context(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001312 yield '--- {} ----{}'.format(file2_range, lineterm)
1313
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001314 if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001315 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001316 if tag != 'delete':
1317 for line in b[j1:j2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001318 yield prefix[tag] + line
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001319
Tim Peters81b92512002-04-29 01:37:32 +00001320def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001321 r"""
1322 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1323
1324 Optional keyword parameters `linejunk` and `charjunk` are for filter
1325 functions (or None):
1326
1327 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001328 return true iff the string is junk. The default is None, and is
1329 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1330 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001331
1332 - charjunk: A function that should accept a string of length 1. The
1333 default is module-level function IS_CHARACTER_JUNK, which filters out
1334 whitespace characters (a blank or tab; note: bad idea to include newline
1335 in this!).
1336
1337 Tools/scripts/ndiff.py is a command-line front-end to this function.
1338
1339 Example:
1340
Ezio Melottid8b509b2011-09-28 17:37:55 +03001341 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
1342 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001343 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001344 - one
1345 ? ^
1346 + ore
1347 ? ^
1348 - two
1349 - three
1350 ? -
1351 + tree
1352 + emu
1353 """
1354 return Differ(linejunk, charjunk).compare(a, b)
1355
Martin v. Löwise064b412004-08-29 16:34:40 +00001356def _mdiff(fromlines, tolines, context=None, linejunk=None,
1357 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001358 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001359
1360 Arguments:
1361 fromlines -- list of text lines to compared to tolines
1362 tolines -- list of text lines to be compared to fromlines
1363 context -- number of context lines to display on each side of difference,
1364 if None, all from/to text lines will be generated.
1365 linejunk -- passed on to ndiff (see ndiff documentation)
1366 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001367
Martin v. Löwise064b412004-08-29 16:34:40 +00001368 This function returns an interator which returns a tuple:
1369 (from line tuple, to line tuple, boolean flag)
1370
1371 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001372 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001373 line text -- original line text with following markers inserted:
1374 '\0+' -- marks start of added text
1375 '\0-' -- marks start of deleted text
1376 '\0^' -- marks start of changed text
1377 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001378
Martin v. Löwise064b412004-08-29 16:34:40 +00001379 boolean flag -- None indicates context separation, True indicates
1380 either "from" or "to" line contains a change, otherwise False.
1381
1382 This function/iterator was originally developed to generate side by side
1383 file difference for making HTML pages (see HtmlDiff class for example
1384 usage).
1385
1386 Note, this function utilizes the ndiff function to generate the side by
1387 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001388 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001389 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001390 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001391
1392 # regular expression for finding intraline change indices
1393 change_re = re.compile('(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001394
Martin v. Löwise064b412004-08-29 16:34:40 +00001395 # create the difference iterator to generate the differences
1396 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1397
1398 def _make_line(lines, format_key, side, num_lines=[0,0]):
1399 """Returns line of text with user's change markup and line formatting.
1400
1401 lines -- list of lines from the ndiff generator to produce a line of
1402 text from. When producing the line of text to return, the
1403 lines used are removed from this list.
1404 format_key -- '+' return first line in list with "add" markup around
1405 the entire line.
1406 '-' return first line in list with "delete" markup around
1407 the entire line.
1408 '?' return first line in list with add/delete/change
1409 intraline markup (indices obtained from second line)
1410 None return first line in list with no markup
1411 side -- indice into the num_lines list (0=from,1=to)
1412 num_lines -- from/to current line number. This is NOT intended to be a
1413 passed parameter. It is present as a keyword argument to
1414 maintain memory of the current line numbers between calls
1415 of this function.
1416
1417 Note, this function is purposefully not defined at the module scope so
1418 that data it needs from its parent function (within whose context it
1419 is defined) does not need to be of module scope.
1420 """
1421 num_lines[side] += 1
1422 # Handle case where no user markup is to be added, just return line of
1423 # text with user's line format to allow for usage of the line number.
1424 if format_key is None:
1425 return (num_lines[side],lines.pop(0)[2:])
1426 # Handle case of intraline changes
1427 if format_key == '?':
1428 text, markers = lines.pop(0), lines.pop(0)
1429 # find intraline changes (store change type and indices in tuples)
1430 sub_info = []
1431 def record_sub_info(match_object,sub_info=sub_info):
1432 sub_info.append([match_object.group(1)[0],match_object.span()])
1433 return match_object.group(1)
1434 change_re.sub(record_sub_info,markers)
1435 # process each tuple inserting our special marks that won't be
1436 # noticed by an xml/html escaper.
1437 for key,(begin,end) in sub_info[::-1]:
1438 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1439 text = text[2:]
1440 # Handle case of add/delete entire line
1441 else:
1442 text = lines.pop(0)[2:]
1443 # if line of text is just a newline, insert a space so there is
1444 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001445 if not text:
1446 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001447 # insert marks that won't be noticed by an xml/html escaper.
1448 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001449 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001450 # thing (such as adding the line number) then replace the special
1451 # marks with what the user's change markup.
1452 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001453
Martin v. Löwise064b412004-08-29 16:34:40 +00001454 def _line_iterator():
1455 """Yields from/to lines of text with a change indication.
1456
1457 This function is an iterator. It itself pulls lines from a
1458 differencing iterator, processes them and yields them. When it can
1459 it yields both a "from" and a "to" line, otherwise it will yield one
1460 or the other. In addition to yielding the lines of from/to text, a
1461 boolean flag is yielded to indicate if the text line(s) have
1462 differences in them.
1463
1464 Note, this function is purposefully not defined at the module scope so
1465 that data it needs from its parent function (within whose context it
1466 is defined) does not need to be of module scope.
1467 """
1468 lines = []
1469 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001470 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001471 # Load up next 4 lines so we can look ahead, create strings which
1472 # are a concatenation of the first character of each of the 4 lines
1473 # so we can do some very readable comparisons.
1474 while len(lines) < 4:
1475 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001476 lines.append(next(diff_lines_iterator))
Martin v. Löwise064b412004-08-29 16:34:40 +00001477 except StopIteration:
1478 lines.append('X')
1479 s = ''.join([line[0] for line in lines])
1480 if s.startswith('X'):
1481 # When no more lines, pump out any remaining blank lines so the
1482 # corresponding add/delete lines get a matching blank line so
1483 # all line pairs get yielded at the next level.
1484 num_blanks_to_yield = num_blanks_pending
1485 elif s.startswith('-?+?'):
1486 # simple intraline change
1487 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1488 continue
1489 elif s.startswith('--++'):
1490 # in delete block, add block coming: we do NOT want to get
1491 # caught up on blank lines yet, just process the delete line
1492 num_blanks_pending -= 1
1493 yield _make_line(lines,'-',0), None, True
1494 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001495 elif s.startswith(('--?+', '--+', '- ')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001496 # in delete block and see a intraline change or unchanged line
1497 # coming: yield the delete line and then blanks
1498 from_line,to_line = _make_line(lines,'-',0), None
1499 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1500 elif s.startswith('-+?'):
1501 # intraline change
1502 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1503 continue
1504 elif s.startswith('-?+'):
1505 # intraline change
1506 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1507 continue
1508 elif s.startswith('-'):
1509 # delete FROM line
1510 num_blanks_pending -= 1
1511 yield _make_line(lines,'-',0), None, True
1512 continue
1513 elif s.startswith('+--'):
1514 # in add block, delete block coming: we do NOT want to get
1515 # caught up on blank lines yet, just process the add line
1516 num_blanks_pending += 1
1517 yield None, _make_line(lines,'+',1), True
1518 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001519 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001520 # will be leaving an add block: yield blanks then add line
1521 from_line, to_line = None, _make_line(lines,'+',1)
1522 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1523 elif s.startswith('+'):
1524 # inside an add block, yield the add line
1525 num_blanks_pending += 1
1526 yield None, _make_line(lines,'+',1), True
1527 continue
1528 elif s.startswith(' '):
1529 # unchanged text, yield it to both sides
1530 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1531 continue
1532 # Catch up on the blank lines so when we yield the next from/to
1533 # pair, they are lined up.
1534 while(num_blanks_to_yield < 0):
1535 num_blanks_to_yield += 1
1536 yield None,('','\n'),True
1537 while(num_blanks_to_yield > 0):
1538 num_blanks_to_yield -= 1
1539 yield ('','\n'),None,True
1540 if s.startswith('X'):
1541 raise StopIteration
1542 else:
1543 yield from_line,to_line,True
1544
1545 def _line_pair_iterator():
1546 """Yields from/to lines of text with a change indication.
1547
1548 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001549 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001550 always yields a pair of from/to text lines (with the change
1551 indication). If necessary it will collect single from/to lines
1552 until it has a matching pair from/to pair to yield.
1553
1554 Note, this function is purposefully not defined at the module scope so
1555 that data it needs from its parent function (within whose context it
1556 is defined) does not need to be of module scope.
1557 """
1558 line_iterator = _line_iterator()
1559 fromlines,tolines=[],[]
1560 while True:
1561 # Collecting lines of text until we have a from/to pair
1562 while (len(fromlines)==0 or len(tolines)==0):
Georg Brandla18af4e2007-04-21 15:47:16 +00001563 from_line, to_line, found_diff = next(line_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001564 if from_line is not None:
1565 fromlines.append((from_line,found_diff))
1566 if to_line is not None:
1567 tolines.append((to_line,found_diff))
1568 # Once we have a pair, remove them from the collection and yield it
1569 from_line, fromDiff = fromlines.pop(0)
1570 to_line, to_diff = tolines.pop(0)
1571 yield (from_line,to_line,fromDiff or to_diff)
1572
1573 # Handle case where user does not want context differencing, just yield
1574 # them up without doing anything else with them.
1575 line_pair_iterator = _line_pair_iterator()
1576 if context is None:
1577 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +00001578 yield next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001579 # Handle case where user wants context differencing. We must do some
1580 # storage of lines until we know for sure that they are to be yielded.
1581 else:
1582 context += 1
1583 lines_to_write = 0
1584 while True:
1585 # Store lines up until we find a difference, note use of a
1586 # circular queue because we only need to keep around what
1587 # we need for context.
1588 index, contextLines = 0, [None]*(context)
1589 found_diff = False
1590 while(found_diff is False):
Georg Brandla18af4e2007-04-21 15:47:16 +00001591 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001592 i = index % context
1593 contextLines[i] = (from_line, to_line, found_diff)
1594 index += 1
1595 # Yield lines that we have collected so far, but first yield
1596 # the user's separator.
1597 if index > context:
1598 yield None, None, None
1599 lines_to_write = context
1600 else:
1601 lines_to_write = index
1602 index = 0
1603 while(lines_to_write):
1604 i = index % context
1605 index += 1
1606 yield contextLines[i]
1607 lines_to_write -= 1
1608 # Now yield the context lines after the change
1609 lines_to_write = context-1
1610 while(lines_to_write):
Georg Brandla18af4e2007-04-21 15:47:16 +00001611 from_line, to_line, found_diff = next(line_pair_iterator)
Martin v. Löwise064b412004-08-29 16:34:40 +00001612 # If another change within the context, extend the context
1613 if found_diff:
1614 lines_to_write = context-1
1615 else:
1616 lines_to_write -= 1
1617 yield from_line, to_line, found_diff
1618
1619
1620_file_template = """
1621<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1622 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1623
1624<html>
1625
1626<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001627 <meta http-equiv="Content-Type"
Martin v. Löwise064b412004-08-29 16:34:40 +00001628 content="text/html; charset=ISO-8859-1" />
1629 <title></title>
1630 <style type="text/css">%(styles)s
1631 </style>
1632</head>
1633
1634<body>
1635 %(table)s%(legend)s
1636</body>
1637
1638</html>"""
1639
1640_styles = """
1641 table.diff {font-family:Courier; border:medium;}
1642 .diff_header {background-color:#e0e0e0}
1643 td.diff_header {text-align:right}
1644 .diff_next {background-color:#c0c0c0}
1645 .diff_add {background-color:#aaffaa}
1646 .diff_chg {background-color:#ffff77}
1647 .diff_sub {background-color:#ffaaaa}"""
1648
1649_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001650 <table class="diff" id="difflib_chg_%(prefix)s_top"
1651 cellspacing="0" cellpadding="0" rules="groups" >
1652 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001653 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1654 %(header_row)s
1655 <tbody>
1656%(data_rows)s </tbody>
1657 </table>"""
1658
1659_legend = """
1660 <table class="diff" summary="Legends">
1661 <tr> <th colspan="2"> Legends </th> </tr>
1662 <tr> <td> <table border="" summary="Colors">
1663 <tr><th> Colors </th> </tr>
1664 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1665 <tr><td class="diff_chg">Changed</td> </tr>
1666 <tr><td class="diff_sub">Deleted</td> </tr>
1667 </table></td>
1668 <td> <table border="" summary="Links">
1669 <tr><th colspan="2"> Links </th> </tr>
1670 <tr><td>(f)irst change</td> </tr>
1671 <tr><td>(n)ext change</td> </tr>
1672 <tr><td>(t)op</td> </tr>
1673 </table></td> </tr>
1674 </table>"""
1675
1676class HtmlDiff(object):
1677 """For producing HTML side by side comparison with change highlights.
1678
1679 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001680 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001681 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001682 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001683
Martin v. Löwise064b412004-08-29 16:34:40 +00001684 The following methods are provided for HTML generation:
1685
1686 make_table -- generates HTML for a single side by side table
1687 make_file -- generates complete HTML file with a single side by side table
1688
Tim Peters48bd7f32004-08-29 22:38:38 +00001689 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001690 """
1691
1692 _file_template = _file_template
1693 _styles = _styles
1694 _table_template = _table_template
1695 _legend = _legend
1696 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001697
Martin v. Löwise064b412004-08-29 16:34:40 +00001698 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1699 charjunk=IS_CHARACTER_JUNK):
1700 """HtmlDiff instance initializer
1701
1702 Arguments:
1703 tabsize -- tab stop spacing, defaults to 8.
1704 wrapcolumn -- column number where lines are broken and wrapped,
1705 defaults to None where lines are not wrapped.
1706 linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
Tim Peters48bd7f32004-08-29 22:38:38 +00001707 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001708 ndiff() documentation for argument default values and descriptions.
1709 """
1710 self._tabsize = tabsize
1711 self._wrapcolumn = wrapcolumn
1712 self._linejunk = linejunk
1713 self._charjunk = charjunk
1714
1715 def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1716 numlines=5):
1717 """Returns HTML file of side by side comparison with change highlights
1718
1719 Arguments:
1720 fromlines -- list of "from" lines
1721 tolines -- list of "to" lines
1722 fromdesc -- "from" file column header string
1723 todesc -- "to" file column header string
1724 context -- set to True for contextual differences (defaults to False
1725 which shows full differences).
1726 numlines -- number of context lines. When context is set True,
1727 controls number of lines displayed before and after the change.
1728 When context is False, controls the number of lines to place
1729 the "next" link anchors before the next change (so click of
1730 "next" link jumps to just before the change).
1731 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001732
Martin v. Löwise064b412004-08-29 16:34:40 +00001733 return self._file_template % dict(
1734 styles = self._styles,
1735 legend = self._legend,
1736 table = self.make_table(fromlines,tolines,fromdesc,todesc,
1737 context=context,numlines=numlines))
Tim Peters48bd7f32004-08-29 22:38:38 +00001738
Martin v. Löwise064b412004-08-29 16:34:40 +00001739 def _tab_newline_replace(self,fromlines,tolines):
1740 """Returns from/to line lists with tabs expanded and newlines removed.
1741
1742 Instead of tab characters being replaced by the number of spaces
1743 needed to fill in to the next tab stop, this function will fill
1744 the space with tab characters. This is done so that the difference
1745 algorithms can identify changes in a file when tabs are replaced by
1746 spaces and vice versa. At the end of the HTML generation, the tab
1747 characters will be replaced with a nonbreakable space.
1748 """
1749 def expand_tabs(line):
1750 # hide real spaces
1751 line = line.replace(' ','\0')
1752 # expand tabs into spaces
1753 line = line.expandtabs(self._tabsize)
Ezio Melotti13925002011-03-16 11:05:33 +02001754 # replace spaces from expanded tabs back into tab characters
Martin v. Löwise064b412004-08-29 16:34:40 +00001755 # (we'll replace them with markup after we do differencing)
1756 line = line.replace(' ','\t')
1757 return line.replace('\0',' ').rstrip('\n')
1758 fromlines = [expand_tabs(line) for line in fromlines]
1759 tolines = [expand_tabs(line) for line in tolines]
1760 return fromlines,tolines
1761
1762 def _split_line(self,data_list,line_num,text):
1763 """Builds list of text lines by splitting text lines at wrap point
1764
1765 This function will determine if the input text line needs to be
1766 wrapped (split) into separate lines. If so, the first wrap point
1767 will be determined and the first line appended to the output
1768 text line list. This function is used recursively to handle
1769 the second part of the split line to further split it.
1770 """
1771 # if blank line or context separator, just add it to the output list
1772 if not line_num:
1773 data_list.append((line_num,text))
1774 return
1775
1776 # if line text doesn't need wrapping, just add it to the output list
1777 size = len(text)
1778 max = self._wrapcolumn
1779 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1780 data_list.append((line_num,text))
1781 return
1782
1783 # scan text looking for the wrap point, keeping track if the wrap
1784 # point is inside markers
1785 i = 0
1786 n = 0
1787 mark = ''
1788 while n < max and i < size:
1789 if text[i] == '\0':
1790 i += 1
1791 mark = text[i]
1792 i += 1
1793 elif text[i] == '\1':
1794 i += 1
1795 mark = ''
1796 else:
1797 i += 1
1798 n += 1
1799
1800 # wrap point is inside text, break it up into separate lines
1801 line1 = text[:i]
1802 line2 = text[i:]
1803
1804 # if wrap point is inside markers, place end marker at end of first
1805 # line and start marker at beginning of second line because each
1806 # line will have its own table tag markup around it.
1807 if mark:
1808 line1 = line1 + '\1'
1809 line2 = '\0' + mark + line2
1810
Tim Peters48bd7f32004-08-29 22:38:38 +00001811 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001812 data_list.append((line_num,line1))
1813
Tim Peters48bd7f32004-08-29 22:38:38 +00001814 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001815 self._split_line(data_list,'>',line2)
1816
1817 def _line_wrapper(self,diffs):
1818 """Returns iterator that splits (wraps) mdiff text lines"""
1819
1820 # pull from/to data and flags from mdiff iterator
1821 for fromdata,todata,flag in diffs:
1822 # check for context separators and pass them through
1823 if flag is None:
1824 yield fromdata,todata,flag
1825 continue
1826 (fromline,fromtext),(toline,totext) = fromdata,todata
1827 # for each from/to line split it at the wrap column to form
1828 # list of text lines.
1829 fromlist,tolist = [],[]
1830 self._split_line(fromlist,fromline,fromtext)
1831 self._split_line(tolist,toline,totext)
1832 # yield from/to line in pairs inserting blank lines as
1833 # necessary when one side has more wrapped lines
1834 while fromlist or tolist:
1835 if fromlist:
1836 fromdata = fromlist.pop(0)
1837 else:
1838 fromdata = ('',' ')
1839 if tolist:
1840 todata = tolist.pop(0)
1841 else:
1842 todata = ('',' ')
1843 yield fromdata,todata,flag
1844
1845 def _collect_lines(self,diffs):
1846 """Collects mdiff output into separate lists
1847
1848 Before storing the mdiff from/to data into a list, it is converted
1849 into a single line of text with HTML markup.
1850 """
1851
1852 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001853 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001854 for fromdata,todata,flag in diffs:
1855 try:
1856 # store HTML markup of the lines into the lists
1857 fromlist.append(self._format_line(0,flag,*fromdata))
1858 tolist.append(self._format_line(1,flag,*todata))
1859 except TypeError:
1860 # exceptions occur for lines where context separators go
1861 fromlist.append(None)
1862 tolist.append(None)
1863 flaglist.append(flag)
1864 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001865
Martin v. Löwise064b412004-08-29 16:34:40 +00001866 def _format_line(self,side,flag,linenum,text):
1867 """Returns HTML markup of "from" / "to" text lines
1868
1869 side -- 0 or 1 indicating "from" or "to" text
1870 flag -- indicates if difference on line
1871 linenum -- line number (used for line number column)
1872 text -- line text to be marked up
1873 """
1874 try:
1875 linenum = '%d' % linenum
1876 id = ' id="%s%s"' % (self._prefix[side],linenum)
1877 except TypeError:
1878 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001879 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001880 # replace those things that would get confused with HTML symbols
1881 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1882
1883 # make space non-breakable so they don't get compressed or line wrapped
1884 text = text.replace(' ','&nbsp;').rstrip()
1885
1886 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1887 % (id,linenum,text)
1888
1889 def _make_prefix(self):
1890 """Create unique anchor prefixes"""
1891
1892 # Generate a unique anchor prefix so multiple tables
1893 # can exist on the same HTML page without conflicts.
1894 fromprefix = "from%d_" % HtmlDiff._default_prefix
1895 toprefix = "to%d_" % HtmlDiff._default_prefix
1896 HtmlDiff._default_prefix += 1
1897 # store prefixes so line format method has access
1898 self._prefix = [fromprefix,toprefix]
1899
1900 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1901 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001902
Martin v. Löwise064b412004-08-29 16:34:40 +00001903 # all anchor names will be generated using the unique "to" prefix
1904 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001905
Martin v. Löwise064b412004-08-29 16:34:40 +00001906 # process change flags, generating middle column of next anchors/links
1907 next_id = ['']*len(flaglist)
1908 next_href = ['']*len(flaglist)
1909 num_chg, in_change = 0, False
1910 last = 0
1911 for i,flag in enumerate(flaglist):
1912 if flag:
1913 if not in_change:
1914 in_change = True
1915 last = i
1916 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001917 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001918 # link
1919 i = max([0,i-numlines])
1920 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001921 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001922 # change
1923 num_chg += 1
1924 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1925 toprefix,num_chg)
1926 else:
1927 in_change = False
1928 # check for cases where there is no content to avoid exceptions
1929 if not flaglist:
1930 flaglist = [False]
1931 next_id = ['']
1932 next_href = ['']
1933 last = 0
1934 if context:
1935 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1936 tolist = fromlist
1937 else:
1938 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1939 # if not a change on first line, drop a link
1940 if not flaglist[0]:
1941 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1942 # redo the last link to link to the top
1943 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1944
1945 return fromlist,tolist,flaglist,next_href,next_id
1946
1947 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1948 numlines=5):
1949 """Returns HTML table of side by side comparison with change highlights
1950
1951 Arguments:
1952 fromlines -- list of "from" lines
1953 tolines -- list of "to" lines
1954 fromdesc -- "from" file column header string
1955 todesc -- "to" file column header string
1956 context -- set to True for contextual differences (defaults to False
1957 which shows full differences).
1958 numlines -- number of context lines. When context is set True,
1959 controls number of lines displayed before and after the change.
1960 When context is False, controls the number of lines to place
1961 the "next" link anchors before the next change (so click of
1962 "next" link jumps to just before the change).
1963 """
1964
1965 # make unique anchor prefixes so that multiple tables may exist
1966 # on the same page without conflict.
1967 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001968
Martin v. Löwise064b412004-08-29 16:34:40 +00001969 # change tabs to spaces before it gets more difficult after we insert
1970 # markkup
1971 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001972
Martin v. Löwise064b412004-08-29 16:34:40 +00001973 # create diffs iterator which generates side by side from/to data
1974 if context:
1975 context_lines = numlines
1976 else:
1977 context_lines = None
1978 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
1979 charjunk=self._charjunk)
1980
1981 # set up iterator to wrap lines that exceed desired width
1982 if self._wrapcolumn:
1983 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00001984
Martin v. Löwise064b412004-08-29 16:34:40 +00001985 # collect up from/to lines and flags into lists (also format the lines)
1986 fromlist,tolist,flaglist = self._collect_lines(diffs)
1987
1988 # process change flags, generating middle column of next anchors/links
1989 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
1990 fromlist,tolist,flaglist,context,numlines)
1991
Guido van Rossumd8faa362007-04-27 19:54:29 +00001992 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00001993 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
1994 '<td class="diff_next">%s</td>%s</tr>\n'
1995 for i in range(len(flaglist)):
1996 if flaglist[i] is None:
1997 # mdiff yields None on separator lines skip the bogus ones
1998 # generated for the first line
1999 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002000 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00002001 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002002 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00002003 next_href[i],tolist[i]))
2004 if fromdesc or todesc:
2005 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
2006 '<th class="diff_next"><br /></th>',
2007 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
2008 '<th class="diff_next"><br /></th>',
2009 '<th colspan="2" class="diff_header">%s</th>' % todesc)
2010 else:
2011 header_row = ''
2012
2013 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002014 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00002015 header_row=header_row,
2016 prefix=self._prefix[1])
2017
2018 return table.replace('\0+','<span class="diff_add">'). \
2019 replace('\0-','<span class="diff_sub">'). \
2020 replace('\0^','<span class="diff_chg">'). \
2021 replace('\1','</span>'). \
2022 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00002023
Martin v. Löwise064b412004-08-29 16:34:40 +00002024del re
2025
Tim Peters5e824c32001-08-12 22:25:01 +00002026def restore(delta, which):
2027 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00002028 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00002029
2030 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
2031 lines originating from file 1 or 2 (parameter `which`), stripping off line
2032 prefixes.
2033
2034 Examples:
2035
Ezio Melottid8b509b2011-09-28 17:37:55 +03002036 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
2037 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Tim Peters8a9c2842001-09-22 21:30:22 +00002038 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002039 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002040 one
2041 two
2042 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002043 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002044 ore
2045 tree
2046 emu
2047 """
2048 try:
2049 tag = {1: "- ", 2: "+ "}[int(which)]
2050 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002051 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Tim Peters5e824c32001-08-12 22:25:01 +00002052 % which)
2053 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002054 for line in delta:
2055 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002056 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002057
Tim Peters9ae21482001-02-10 08:00:53 +00002058def _test():
2059 import doctest, difflib
2060 return doctest.testmod(difflib)
2061
2062if __name__ == "__main__":
2063 _test()