Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python |
| 2 | |
| 3 | """ |
| 4 | Module difflib -- helpers for computing deltas between objects. |
| 5 | |
| 6 | Function get_close_matches(word, possibilities, n=3, cutoff=0.6): |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 7 | Use SequenceMatcher to return list of the best "good enough" matches. |
| 8 | |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 9 | Function context_diff(a, b): |
| 10 | For two lists of strings, return a delta in context diff format. |
| 11 | |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 12 | Function ndiff(a, b): |
| 13 | Return a delta: the difference between `a` and `b` (lists of strings). |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 14 | |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 15 | Function restore(delta, which): |
| 16 | Return one of the two sequences that generated an ndiff delta. |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 17 | |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 18 | Function unified_diff(a, b): |
| 19 | For two lists of strings, return a delta in unified diff format. |
| 20 | |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 21 | Class SequenceMatcher: |
| 22 | A flexible class for comparing pairs of sequences of any type. |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 23 | |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 24 | Class Differ: |
| 25 | For producing human-readable deltas from sequences of lines of text. |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 26 | |
| 27 | Class HtmlDiff: |
| 28 | For producing HTML side by side comparison with change highlights. |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 29 | """ |
| 30 | |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 31 | __all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher', |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 32 | 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff', |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 33 | 'unified_diff', 'HtmlDiff', 'Match'] |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 34 | |
Raymond Hettinger | bb6b734 | 2004-06-13 09:57:33 +0000 | [diff] [blame] | 35 | import heapq |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 36 | from collections import namedtuple as _namedtuple |
| 37 | |
| 38 | Match = _namedtuple('Match', 'a b size') |
Raymond Hettinger | bb6b734 | 2004-06-13 09:57:33 +0000 | [diff] [blame] | 39 | |
Neal Norwitz | e7dfe21 | 2003-07-01 14:59:46 +0000 | [diff] [blame] | 40 | def _calculate_ratio(matches, length): |
| 41 | if length: |
| 42 | return 2.0 * matches / length |
| 43 | return 1.0 |
| 44 | |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 45 | class SequenceMatcher: |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 46 | |
| 47 | """ |
| 48 | SequenceMatcher is a flexible class for comparing pairs of sequences of |
| 49 | any type, so long as the sequence elements are hashable. The basic |
| 50 | algorithm predates, and is a little fancier than, an algorithm |
| 51 | published in the late 1980's by Ratcliff and Obershelp under the |
| 52 | hyperbolic name "gestalt pattern matching". The basic idea is to find |
| 53 | the longest contiguous matching subsequence that contains no "junk" |
| 54 | elements (R-O doesn't address junk). The same idea is then applied |
| 55 | recursively to the pieces of the sequences to the left and to the right |
| 56 | of the matching subsequence. This does not yield minimal edit |
| 57 | sequences, but does tend to yield matches that "look right" to people. |
| 58 | |
| 59 | SequenceMatcher tries to compute a "human-friendly diff" between two |
| 60 | sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the |
| 61 | longest *contiguous* & junk-free matching subsequence. That's what |
| 62 | catches peoples' eyes. The Windows(tm) windiff has another interesting |
| 63 | notion, pairing up elements that appear uniquely in each sequence. |
| 64 | That, and the method here, appear to yield more intuitive difference |
| 65 | reports than does diff. This method appears to be the least vulnerable |
| 66 | to synching up on blocks of "junk lines", though (like blank lines in |
| 67 | ordinary text files, or maybe "<P>" lines in HTML files). That may be |
| 68 | because this is the only method of the 3 that has a *concept* of |
| 69 | "junk" <wink>. |
| 70 | |
| 71 | Example, comparing two strings, and considering blanks to be "junk": |
| 72 | |
| 73 | >>> s = SequenceMatcher(lambda x: x == " ", |
| 74 | ... "private Thread currentThread;", |
| 75 | ... "private volatile Thread currentThread;") |
| 76 | >>> |
| 77 | |
| 78 | .ratio() returns a float in [0, 1], measuring the "similarity" of the |
| 79 | sequences. As a rule of thumb, a .ratio() value over 0.6 means the |
| 80 | sequences are close matches: |
| 81 | |
Guido van Rossum | fff80df | 2007-02-09 20:33:44 +0000 | [diff] [blame] | 82 | >>> print(round(s.ratio(), 3)) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 83 | 0.866 |
| 84 | >>> |
| 85 | |
| 86 | If you're only interested in where the sequences match, |
| 87 | .get_matching_blocks() is handy: |
| 88 | |
| 89 | >>> for block in s.get_matching_blocks(): |
Guido van Rossum | fff80df | 2007-02-09 20:33:44 +0000 | [diff] [blame] | 90 | ... print("a[%d] and b[%d] match for %d elements" % block) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 91 | a[0] and b[0] match for 8 elements |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 92 | a[8] and b[17] match for 21 elements |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 93 | a[29] and b[38] match for 0 elements |
| 94 | |
| 95 | Note that the last tuple returned by .get_matching_blocks() is always a |
| 96 | dummy, (len(a), len(b), 0), and this is the only case in which the last |
| 97 | tuple element (number of elements matched) is 0. |
| 98 | |
| 99 | If you want to know how to change the first sequence into the second, |
| 100 | use .get_opcodes(): |
| 101 | |
| 102 | >>> for opcode in s.get_opcodes(): |
Guido van Rossum | fff80df | 2007-02-09 20:33:44 +0000 | [diff] [blame] | 103 | ... print("%6s a[%d:%d] b[%d:%d]" % opcode) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 104 | equal a[0:8] b[0:8] |
| 105 | insert a[8:8] b[8:17] |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 106 | equal a[8:29] b[17:38] |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 107 | |
| 108 | See the Differ class for a fancy human-friendly file differencer, which |
| 109 | uses SequenceMatcher both to compare sequences of lines, and to compare |
| 110 | sequences of characters within similar (near-matching) lines. |
| 111 | |
| 112 | See also function get_close_matches() in this module, which shows how |
| 113 | simple code building on SequenceMatcher can be used to do useful work. |
| 114 | |
| 115 | Timing: Basic R-O is cubic time worst case and quadratic time expected |
| 116 | case. SequenceMatcher is quadratic time for the worst case and has |
| 117 | expected-case behavior dependent in a complicated way on how many |
| 118 | elements the sequences have in common; best case time is linear. |
| 119 | |
| 120 | Methods: |
| 121 | |
| 122 | __init__(isjunk=None, a='', b='') |
| 123 | Construct a SequenceMatcher. |
| 124 | |
| 125 | set_seqs(a, b) |
| 126 | Set the two sequences to be compared. |
| 127 | |
| 128 | set_seq1(a) |
| 129 | Set the first sequence to be compared. |
| 130 | |
| 131 | set_seq2(b) |
| 132 | Set the second sequence to be compared. |
| 133 | |
| 134 | find_longest_match(alo, ahi, blo, bhi) |
| 135 | Find longest matching block in a[alo:ahi] and b[blo:bhi]. |
| 136 | |
| 137 | get_matching_blocks() |
| 138 | Return list of triples describing matching subsequences. |
| 139 | |
| 140 | get_opcodes() |
| 141 | Return list of 5-tuples describing how to turn a into b. |
| 142 | |
| 143 | ratio() |
| 144 | Return a measure of the sequences' similarity (float in [0,1]). |
| 145 | |
| 146 | quick_ratio() |
| 147 | Return an upper bound on .ratio() relatively quickly. |
| 148 | |
| 149 | real_quick_ratio() |
| 150 | Return an upper bound on ratio() very quickly. |
| 151 | """ |
| 152 | |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 153 | def __init__(self, isjunk=None, a='', b=''): |
| 154 | """Construct a SequenceMatcher. |
| 155 | |
| 156 | Optional arg isjunk is None (the default), or a one-argument |
| 157 | function that takes a sequence element and returns true iff the |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 158 | element is junk. None is equivalent to passing "lambda x: 0", i.e. |
Fred Drake | f1da628 | 2001-02-19 19:30:05 +0000 | [diff] [blame] | 159 | no elements are considered to be junk. For example, pass |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 160 | lambda x: x in " \\t" |
| 161 | if you're comparing lines as sequences of characters, and don't |
| 162 | want to synch up on blanks or hard tabs. |
| 163 | |
| 164 | Optional arg a is the first of two sequences to be compared. By |
| 165 | default, an empty string. The elements of a must be hashable. See |
| 166 | also .set_seqs() and .set_seq1(). |
| 167 | |
| 168 | Optional arg b is the second of two sequences to be compared. By |
Fred Drake | f1da628 | 2001-02-19 19:30:05 +0000 | [diff] [blame] | 169 | default, an empty string. The elements of b must be hashable. See |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 170 | also .set_seqs() and .set_seq2(). |
| 171 | """ |
| 172 | |
| 173 | # Members: |
| 174 | # a |
| 175 | # first sequence |
| 176 | # b |
| 177 | # second sequence; differences are computed as "what do |
| 178 | # we need to do to 'a' to change it into 'b'?" |
| 179 | # b2j |
| 180 | # for x in b, b2j[x] is a list of the indices (into b) |
| 181 | # at which x appears; junk elements do not appear |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 182 | # fullbcount |
| 183 | # for x in b, fullbcount[x] == the number of times x |
| 184 | # appears in b; only materialized if really needed (used |
| 185 | # only for computing quick_ratio()) |
| 186 | # matching_blocks |
| 187 | # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k]; |
| 188 | # ascending & non-overlapping in i and in j; terminated by |
| 189 | # a dummy (len(a), len(b), 0) sentinel |
| 190 | # opcodes |
| 191 | # a list of (tag, i1, i2, j1, j2) tuples, where tag is |
| 192 | # one of |
| 193 | # 'replace' a[i1:i2] should be replaced by b[j1:j2] |
| 194 | # 'delete' a[i1:i2] should be deleted |
| 195 | # 'insert' b[j1:j2] should be inserted |
| 196 | # 'equal' a[i1:i2] == b[j1:j2] |
| 197 | # isjunk |
| 198 | # a user-supplied function taking a sequence element and |
| 199 | # returning true iff the element is "junk" -- this has |
| 200 | # subtle but helpful effects on the algorithm, which I'll |
| 201 | # get around to writing up someday <0.9 wink>. |
| 202 | # DON'T USE! Only __chain_b uses this. Use isbjunk. |
| 203 | # isbjunk |
| 204 | # for x in b, isbjunk(x) == isjunk(x) but much faster; |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 205 | # it's really the __contains__ method of a hidden dict. |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 206 | # DOES NOT WORK for x in a! |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 207 | # isbpopular |
| 208 | # for x in b, isbpopular(x) is true iff b is reasonably long |
| 209 | # (at least 200 elements) and x accounts for more than 1% of |
| 210 | # its elements. DOES NOT WORK for x in a! |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 211 | |
| 212 | self.isjunk = isjunk |
| 213 | self.a = self.b = None |
| 214 | self.set_seqs(a, b) |
| 215 | |
| 216 | def set_seqs(self, a, b): |
| 217 | """Set the two sequences to be compared. |
| 218 | |
| 219 | >>> s = SequenceMatcher() |
| 220 | >>> s.set_seqs("abcd", "bcde") |
| 221 | >>> s.ratio() |
| 222 | 0.75 |
| 223 | """ |
| 224 | |
| 225 | self.set_seq1(a) |
| 226 | self.set_seq2(b) |
| 227 | |
| 228 | def set_seq1(self, a): |
| 229 | """Set the first sequence to be compared. |
| 230 | |
| 231 | The second sequence to be compared is not changed. |
| 232 | |
| 233 | >>> s = SequenceMatcher(None, "abcd", "bcde") |
| 234 | >>> s.ratio() |
| 235 | 0.75 |
| 236 | >>> s.set_seq1("bcde") |
| 237 | >>> s.ratio() |
| 238 | 1.0 |
| 239 | >>> |
| 240 | |
| 241 | SequenceMatcher computes and caches detailed information about the |
| 242 | second sequence, so if you want to compare one sequence S against |
| 243 | many sequences, use .set_seq2(S) once and call .set_seq1(x) |
| 244 | repeatedly for each of the other sequences. |
| 245 | |
| 246 | See also set_seqs() and set_seq2(). |
| 247 | """ |
| 248 | |
| 249 | if a is self.a: |
| 250 | return |
| 251 | self.a = a |
| 252 | self.matching_blocks = self.opcodes = None |
| 253 | |
| 254 | def set_seq2(self, b): |
| 255 | """Set the second sequence to be compared. |
| 256 | |
| 257 | The first sequence to be compared is not changed. |
| 258 | |
| 259 | >>> s = SequenceMatcher(None, "abcd", "bcde") |
| 260 | >>> s.ratio() |
| 261 | 0.75 |
| 262 | >>> s.set_seq2("abcd") |
| 263 | >>> s.ratio() |
| 264 | 1.0 |
| 265 | >>> |
| 266 | |
| 267 | SequenceMatcher computes and caches detailed information about the |
| 268 | second sequence, so if you want to compare one sequence S against |
| 269 | many sequences, use .set_seq2(S) once and call .set_seq1(x) |
| 270 | repeatedly for each of the other sequences. |
| 271 | |
| 272 | See also set_seqs() and set_seq1(). |
| 273 | """ |
| 274 | |
| 275 | if b is self.b: |
| 276 | return |
| 277 | self.b = b |
| 278 | self.matching_blocks = self.opcodes = None |
| 279 | self.fullbcount = None |
| 280 | self.__chain_b() |
| 281 | |
| 282 | # For each element x in b, set b2j[x] to a list of the indices in |
| 283 | # b where x appears; the indices are in increasing order; note that |
| 284 | # the number of times x appears in b is len(b2j[x]) ... |
| 285 | # when self.isjunk is defined, junk elements don't show up in this |
| 286 | # map at all, which stops the central find_longest_match method |
| 287 | # from starting any matching block at a junk element ... |
| 288 | # also creates the fast isbjunk function ... |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 289 | # b2j also does not contain entries for "popular" elements, meaning |
| 290 | # elements that account for more than 1% of the total elements, and |
| 291 | # when the sequence is reasonably large (>= 200 elements); this can |
| 292 | # be viewed as an adaptive notion of semi-junk, and yields an enormous |
| 293 | # speedup when, e.g., comparing program files with hundreds of |
| 294 | # instances of "return NULL;" ... |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 295 | # note that this is only called when b changes; so for cross-product |
| 296 | # kinds of matches, it's best to call set_seq2 once, then set_seq1 |
| 297 | # repeatedly |
| 298 | |
| 299 | def __chain_b(self): |
| 300 | # Because isjunk is a user-defined (not C) function, and we test |
| 301 | # for junk a LOT, it's important to minimize the number of calls. |
| 302 | # Before the tricks described here, __chain_b was by far the most |
| 303 | # time-consuming routine in the whole module! If anyone sees |
| 304 | # Jim Roskind, thank him again for profile.py -- I never would |
| 305 | # have guessed that. |
| 306 | # The first trick is to build b2j ignoring the possibility |
| 307 | # of junk. I.e., we don't call isjunk at all yet. Throwing |
| 308 | # out the junk later is much cheaper than building b2j "right" |
| 309 | # from the start. |
| 310 | b = self.b |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 311 | n = len(b) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 312 | self.b2j = b2j = {} |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 313 | populardict = {} |
| 314 | for i, elt in enumerate(b): |
| 315 | if elt in b2j: |
| 316 | indices = b2j[elt] |
| 317 | if n >= 200 and len(indices) * 100 > n: |
| 318 | populardict[elt] = 1 |
| 319 | del indices[:] |
| 320 | else: |
| 321 | indices.append(i) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 322 | else: |
| 323 | b2j[elt] = [i] |
| 324 | |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 325 | # Purge leftover indices for popular elements. |
| 326 | for elt in populardict: |
| 327 | del b2j[elt] |
| 328 | |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 329 | # Now b2j.keys() contains elements uniquely, and especially when |
| 330 | # the sequence is a string, that's usually a good deal smaller |
| 331 | # than len(string). The difference is the number of isjunk calls |
| 332 | # saved. |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 333 | isjunk = self.isjunk |
| 334 | junkdict = {} |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 335 | if isjunk: |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 336 | for d in populardict, b2j: |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 337 | for elt in list(d.keys()): |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 338 | if isjunk(elt): |
| 339 | junkdict[elt] = 1 |
| 340 | del d[elt] |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 341 | |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 342 | # Now for x in b, isjunk(x) == x in junkdict, but the |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 343 | # latter is much faster. Note too that while there may be a |
| 344 | # lot of junk in the sequence, the number of *unique* junk |
| 345 | # elements is probably small. So the memory burden of keeping |
| 346 | # this dict alive is likely trivial compared to the size of b2j. |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 347 | self.isbjunk = junkdict.__contains__ |
| 348 | self.isbpopular = populardict.__contains__ |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 349 | |
| 350 | def find_longest_match(self, alo, ahi, blo, bhi): |
| 351 | """Find longest matching block in a[alo:ahi] and b[blo:bhi]. |
| 352 | |
| 353 | If isjunk is not defined: |
| 354 | |
| 355 | Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where |
| 356 | alo <= i <= i+k <= ahi |
| 357 | blo <= j <= j+k <= bhi |
| 358 | and for all (i',j',k') meeting those conditions, |
| 359 | k >= k' |
| 360 | i <= i' |
| 361 | and if i == i', j <= j' |
| 362 | |
| 363 | In other words, of all maximal matching blocks, return one that |
| 364 | starts earliest in a, and of all those maximal matching blocks that |
| 365 | start earliest in a, return the one that starts earliest in b. |
| 366 | |
| 367 | >>> s = SequenceMatcher(None, " abcd", "abcd abcd") |
| 368 | >>> s.find_longest_match(0, 5, 0, 9) |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 369 | Match(a=0, b=4, size=5) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 370 | |
| 371 | If isjunk is defined, first the longest matching block is |
| 372 | determined as above, but with the additional restriction that no |
| 373 | junk element appears in the block. Then that block is extended as |
| 374 | far as possible by matching (only) junk elements on both sides. So |
| 375 | the resulting block never matches on junk except as identical junk |
| 376 | happens to be adjacent to an "interesting" match. |
| 377 | |
| 378 | Here's the same example as before, but considering blanks to be |
| 379 | junk. That prevents " abcd" from matching the " abcd" at the tail |
| 380 | end of the second sequence directly. Instead only the "abcd" can |
| 381 | match, and matches the leftmost "abcd" in the second sequence: |
| 382 | |
| 383 | >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") |
| 384 | >>> s.find_longest_match(0, 5, 0, 9) |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 385 | Match(a=1, b=0, size=4) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 386 | |
| 387 | If no blocks match, return (alo, blo, 0). |
| 388 | |
| 389 | >>> s = SequenceMatcher(None, "ab", "c") |
| 390 | >>> s.find_longest_match(0, 2, 0, 1) |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 391 | Match(a=0, b=0, size=0) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 392 | """ |
| 393 | |
| 394 | # CAUTION: stripping common prefix or suffix would be incorrect. |
| 395 | # E.g., |
| 396 | # ab |
| 397 | # acab |
| 398 | # Longest matching block is "ab", but if common prefix is |
| 399 | # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so |
| 400 | # strip, so ends up claiming that ab is changed to acab by |
| 401 | # inserting "ca" in the middle. That's minimal but unintuitive: |
| 402 | # "it's obvious" that someone inserted "ac" at the front. |
| 403 | # Windiff ends up at the same place as diff, but by pairing up |
| 404 | # the unique 'b's and then matching the first two 'a's. |
| 405 | |
| 406 | a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk |
| 407 | besti, bestj, bestsize = alo, blo, 0 |
| 408 | # find longest junk-free match |
| 409 | # during an iteration of the loop, j2len[j] = length of longest |
| 410 | # junk-free match ending with a[i-1] and b[j] |
| 411 | j2len = {} |
| 412 | nothing = [] |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 413 | for i in range(alo, ahi): |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 414 | # look at all instances of a[i] in b; note that because |
| 415 | # b2j has no junk keys, the loop is skipped if a[i] is junk |
| 416 | j2lenget = j2len.get |
| 417 | newj2len = {} |
| 418 | for j in b2j.get(a[i], nothing): |
| 419 | # a[i] matches b[j] |
| 420 | if j < blo: |
| 421 | continue |
| 422 | if j >= bhi: |
| 423 | break |
| 424 | k = newj2len[j] = j2lenget(j-1, 0) + 1 |
| 425 | if k > bestsize: |
| 426 | besti, bestj, bestsize = i-k+1, j-k+1, k |
| 427 | j2len = newj2len |
| 428 | |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 429 | # Extend the best by non-junk elements on each end. In particular, |
| 430 | # "popular" non-junk elements aren't in b2j, which greatly speeds |
| 431 | # the inner loop above, but also means "the best" match so far |
| 432 | # doesn't contain any junk *or* popular non-junk elements. |
| 433 | while besti > alo and bestj > blo and \ |
| 434 | not isbjunk(b[bestj-1]) and \ |
| 435 | a[besti-1] == b[bestj-1]: |
| 436 | besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 |
| 437 | while besti+bestsize < ahi and bestj+bestsize < bhi and \ |
| 438 | not isbjunk(b[bestj+bestsize]) and \ |
| 439 | a[besti+bestsize] == b[bestj+bestsize]: |
| 440 | bestsize += 1 |
| 441 | |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 442 | # Now that we have a wholly interesting match (albeit possibly |
| 443 | # empty!), we may as well suck up the matching junk on each |
| 444 | # side of it too. Can't think of a good reason not to, and it |
| 445 | # saves post-processing the (possibly considerable) expense of |
| 446 | # figuring out what to do with it. In the case of an empty |
| 447 | # interesting match, this is clearly the right thing to do, |
| 448 | # because no other kind of match is possible in the regions. |
| 449 | while besti > alo and bestj > blo and \ |
| 450 | isbjunk(b[bestj-1]) and \ |
| 451 | a[besti-1] == b[bestj-1]: |
| 452 | besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 |
| 453 | while besti+bestsize < ahi and bestj+bestsize < bhi and \ |
| 454 | isbjunk(b[bestj+bestsize]) and \ |
| 455 | a[besti+bestsize] == b[bestj+bestsize]: |
| 456 | bestsize = bestsize + 1 |
| 457 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 458 | return Match(besti, bestj, bestsize) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 459 | |
| 460 | def get_matching_blocks(self): |
| 461 | """Return list of triples describing matching subsequences. |
| 462 | |
| 463 | Each triple is of the form (i, j, n), and means that |
| 464 | a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 465 | i and in j. New in Python 2.5, it's also guaranteed that if |
| 466 | (i, j, n) and (i', j', n') are adjacent triples in the list, and |
| 467 | the second is not the last triple in the list, then i+n != i' or |
| 468 | j+n != j'. IOW, adjacent triples never describe adjacent equal |
| 469 | blocks. |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 470 | |
| 471 | The last triple is a dummy, (len(a), len(b), 0), and is the only |
| 472 | triple with n==0. |
| 473 | |
| 474 | >>> s = SequenceMatcher(None, "abxcd", "abcd") |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 475 | >>> list(s.get_matching_blocks()) |
| 476 | [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 477 | """ |
| 478 | |
| 479 | if self.matching_blocks is not None: |
| 480 | return self.matching_blocks |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 481 | la, lb = len(self.a), len(self.b) |
Gustavo Niemeyer | 54814881 | 2006-01-31 18:34:13 +0000 | [diff] [blame] | 482 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 483 | # This is most naturally expressed as a recursive algorithm, but |
| 484 | # at least one user bumped into extreme use cases that exceeded |
| 485 | # the recursion limit on their box. So, now we maintain a list |
| 486 | # ('queue`) of blocks we still need to look at, and append partial |
| 487 | # results to `matching_blocks` in a loop; the matches are sorted |
| 488 | # at the end. |
Gustavo Niemeyer | 54814881 | 2006-01-31 18:34:13 +0000 | [diff] [blame] | 489 | queue = [(0, la, 0, lb)] |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 490 | matching_blocks = [] |
Gustavo Niemeyer | 54814881 | 2006-01-31 18:34:13 +0000 | [diff] [blame] | 491 | while queue: |
Gustavo Niemeyer | 54814881 | 2006-01-31 18:34:13 +0000 | [diff] [blame] | 492 | alo, ahi, blo, bhi = queue.pop() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 493 | i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi) |
Gustavo Niemeyer | 54814881 | 2006-01-31 18:34:13 +0000 | [diff] [blame] | 494 | # a[alo:i] vs b[blo:j] unknown |
| 495 | # a[i:i+k] same as b[j:j+k] |
| 496 | # a[i+k:ahi] vs b[j+k:bhi] unknown |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 497 | if k: # if k is 0, there was no matching block |
| 498 | matching_blocks.append(x) |
Gustavo Niemeyer | 54814881 | 2006-01-31 18:34:13 +0000 | [diff] [blame] | 499 | if alo < i and blo < j: |
| 500 | queue.append((alo, i, blo, j)) |
Gustavo Niemeyer | 54814881 | 2006-01-31 18:34:13 +0000 | [diff] [blame] | 501 | if i+k < ahi and j+k < bhi: |
| 502 | queue.append((i+k, ahi, j+k, bhi)) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 503 | matching_blocks.sort() |
Gustavo Niemeyer | 54814881 | 2006-01-31 18:34:13 +0000 | [diff] [blame] | 504 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 505 | # It's possible that we have adjacent equal blocks in the |
| 506 | # matching_blocks list now. Starting with 2.5, this code was added |
| 507 | # to collapse them. |
| 508 | i1 = j1 = k1 = 0 |
| 509 | non_adjacent = [] |
| 510 | for i2, j2, k2 in matching_blocks: |
| 511 | # Is this block adjacent to i1, j1, k1? |
| 512 | if i1 + k1 == i2 and j1 + k1 == j2: |
| 513 | # Yes, so collapse them -- this just increases the length of |
| 514 | # the first block by the length of the second, and the first |
| 515 | # block so lengthened remains the block to compare against. |
| 516 | k1 += k2 |
| 517 | else: |
| 518 | # Not adjacent. Remember the first block (k1==0 means it's |
| 519 | # the dummy we started with), and make the second block the |
| 520 | # new block to compare against. |
| 521 | if k1: |
| 522 | non_adjacent.append((i1, j1, k1)) |
| 523 | i1, j1, k1 = i2, j2, k2 |
| 524 | if k1: |
| 525 | non_adjacent.append((i1, j1, k1)) |
| 526 | |
| 527 | non_adjacent.append( (la, lb, 0) ) |
| 528 | self.matching_blocks = non_adjacent |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 529 | return map(Match._make, self.matching_blocks) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 530 | |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 531 | def get_opcodes(self): |
| 532 | """Return list of 5-tuples describing how to turn a into b. |
| 533 | |
| 534 | Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple |
| 535 | has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the |
| 536 | tuple preceding it, and likewise for j1 == the previous j2. |
| 537 | |
| 538 | The tags are strings, with these meanings: |
| 539 | |
| 540 | 'replace': a[i1:i2] should be replaced by b[j1:j2] |
| 541 | 'delete': a[i1:i2] should be deleted. |
| 542 | Note that j1==j2 in this case. |
| 543 | 'insert': b[j1:j2] should be inserted at a[i1:i1]. |
| 544 | Note that i1==i2 in this case. |
| 545 | 'equal': a[i1:i2] == b[j1:j2] |
| 546 | |
| 547 | >>> a = "qabxcd" |
| 548 | >>> b = "abycdf" |
| 549 | >>> s = SequenceMatcher(None, a, b) |
| 550 | >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): |
Guido van Rossum | fff80df | 2007-02-09 20:33:44 +0000 | [diff] [blame] | 551 | ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % |
| 552 | ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 553 | delete a[0:1] (q) b[0:0] () |
| 554 | equal a[1:3] (ab) b[0:2] (ab) |
| 555 | replace a[3:4] (x) b[2:3] (y) |
| 556 | equal a[4:6] (cd) b[3:5] (cd) |
| 557 | insert a[6:6] () b[5:6] (f) |
| 558 | """ |
| 559 | |
| 560 | if self.opcodes is not None: |
| 561 | return self.opcodes |
| 562 | i = j = 0 |
| 563 | self.opcodes = answer = [] |
| 564 | for ai, bj, size in self.get_matching_blocks(): |
| 565 | # invariant: we've pumped out correct diffs to change |
| 566 | # a[:i] into b[:j], and the next matching block is |
| 567 | # a[ai:ai+size] == b[bj:bj+size]. So we need to pump |
| 568 | # out a diff to change a[i:ai] into b[j:bj], pump out |
| 569 | # the matching block, and move (i,j) beyond the match |
| 570 | tag = '' |
| 571 | if i < ai and j < bj: |
| 572 | tag = 'replace' |
| 573 | elif i < ai: |
| 574 | tag = 'delete' |
| 575 | elif j < bj: |
| 576 | tag = 'insert' |
| 577 | if tag: |
| 578 | answer.append( (tag, i, ai, j, bj) ) |
| 579 | i, j = ai+size, bj+size |
| 580 | # the list of matching blocks is terminated by a |
| 581 | # sentinel with size 0 |
| 582 | if size: |
| 583 | answer.append( ('equal', ai, i, bj, j) ) |
| 584 | return answer |
| 585 | |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 586 | def get_grouped_opcodes(self, n=3): |
| 587 | """ Isolate change clusters by eliminating ranges with no changes. |
| 588 | |
| 589 | Return a generator of groups with upto n lines of context. |
| 590 | Each group is in the same format as returned by get_opcodes(). |
| 591 | |
| 592 | >>> from pprint import pprint |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 593 | >>> a = list(map(str, range(1,40))) |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 594 | >>> b = a[:] |
| 595 | >>> b[8:8] = ['i'] # Make an insertion |
| 596 | >>> b[20] += 'x' # Make a replacement |
| 597 | >>> b[23:28] = [] # Make a deletion |
| 598 | >>> b[30] += 'y' # Make another replacement |
| 599 | >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes())) |
| 600 | [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)], |
| 601 | [('equal', 16, 19, 17, 20), |
| 602 | ('replace', 19, 20, 20, 21), |
| 603 | ('equal', 20, 22, 21, 23), |
| 604 | ('delete', 22, 27, 23, 23), |
| 605 | ('equal', 27, 30, 23, 26)], |
| 606 | [('equal', 31, 34, 27, 30), |
| 607 | ('replace', 34, 35, 30, 31), |
| 608 | ('equal', 35, 38, 31, 34)]] |
| 609 | """ |
| 610 | |
| 611 | codes = self.get_opcodes() |
Brett Cannon | d2c5b4b | 2004-07-10 23:54:07 +0000 | [diff] [blame] | 612 | if not codes: |
| 613 | codes = [("equal", 0, 1, 0, 1)] |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 614 | # Fixup leading and trailing groups if they show no changes. |
| 615 | if codes[0][0] == 'equal': |
| 616 | tag, i1, i2, j1, j2 = codes[0] |
| 617 | codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2 |
| 618 | if codes[-1][0] == 'equal': |
| 619 | tag, i1, i2, j1, j2 = codes[-1] |
| 620 | codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n) |
| 621 | |
| 622 | nn = n + n |
| 623 | group = [] |
| 624 | for tag, i1, i2, j1, j2 in codes: |
| 625 | # End the current group and start a new one whenever |
| 626 | # there is a large range with no changes. |
| 627 | if tag == 'equal' and i2-i1 > nn: |
| 628 | group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n))) |
| 629 | yield group |
| 630 | group = [] |
| 631 | i1, j1 = max(i1, i2-n), max(j1, j2-n) |
| 632 | group.append((tag, i1, i2, j1 ,j2)) |
| 633 | if group and not (len(group)==1 and group[0][0] == 'equal'): |
| 634 | yield group |
| 635 | |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 636 | def ratio(self): |
| 637 | """Return a measure of the sequences' similarity (float in [0,1]). |
| 638 | |
| 639 | Where T is the total number of elements in both sequences, and |
Tim Peters | bcc95cb | 2004-07-31 00:19:43 +0000 | [diff] [blame] | 640 | M is the number of matches, this is 2.0*M / T. |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 641 | Note that this is 1 if the sequences are identical, and 0 if |
| 642 | they have nothing in common. |
| 643 | |
| 644 | .ratio() is expensive to compute if you haven't already computed |
| 645 | .get_matching_blocks() or .get_opcodes(), in which case you may |
| 646 | want to try .quick_ratio() or .real_quick_ratio() first to get an |
| 647 | upper bound. |
| 648 | |
| 649 | >>> s = SequenceMatcher(None, "abcd", "bcde") |
| 650 | >>> s.ratio() |
| 651 | 0.75 |
| 652 | >>> s.quick_ratio() |
| 653 | 0.75 |
| 654 | >>> s.real_quick_ratio() |
| 655 | 1.0 |
| 656 | """ |
| 657 | |
Guido van Rossum | 89da5d7 | 2006-08-22 00:21:25 +0000 | [diff] [blame] | 658 | matches = sum(triple[-1] for triple in self.get_matching_blocks()) |
Neal Norwitz | e7dfe21 | 2003-07-01 14:59:46 +0000 | [diff] [blame] | 659 | return _calculate_ratio(matches, len(self.a) + len(self.b)) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 660 | |
| 661 | def quick_ratio(self): |
| 662 | """Return an upper bound on ratio() relatively quickly. |
| 663 | |
| 664 | This isn't defined beyond that it is an upper bound on .ratio(), and |
| 665 | is faster to compute. |
| 666 | """ |
| 667 | |
| 668 | # viewing a and b as multisets, set matches to the cardinality |
| 669 | # of their intersection; this counts the number of matches |
| 670 | # without regard to order, so is clearly an upper bound |
| 671 | if self.fullbcount is None: |
| 672 | self.fullbcount = fullbcount = {} |
| 673 | for elt in self.b: |
| 674 | fullbcount[elt] = fullbcount.get(elt, 0) + 1 |
| 675 | fullbcount = self.fullbcount |
| 676 | # avail[x] is the number of times x appears in 'b' less the |
| 677 | # number of times we've seen it in 'a' so far ... kinda |
| 678 | avail = {} |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 679 | availhas, matches = avail.__contains__, 0 |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 680 | for elt in self.a: |
| 681 | if availhas(elt): |
| 682 | numb = avail[elt] |
| 683 | else: |
| 684 | numb = fullbcount.get(elt, 0) |
| 685 | avail[elt] = numb - 1 |
| 686 | if numb > 0: |
| 687 | matches = matches + 1 |
Neal Norwitz | e7dfe21 | 2003-07-01 14:59:46 +0000 | [diff] [blame] | 688 | return _calculate_ratio(matches, len(self.a) + len(self.b)) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 689 | |
| 690 | def real_quick_ratio(self): |
| 691 | """Return an upper bound on ratio() very quickly. |
| 692 | |
| 693 | This isn't defined beyond that it is an upper bound on .ratio(), and |
| 694 | is faster to compute than either .ratio() or .quick_ratio(). |
| 695 | """ |
| 696 | |
| 697 | la, lb = len(self.a), len(self.b) |
| 698 | # can't have more matches than the number of elements in the |
| 699 | # shorter sequence |
Neal Norwitz | e7dfe21 | 2003-07-01 14:59:46 +0000 | [diff] [blame] | 700 | return _calculate_ratio(min(la, lb), la + lb) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 701 | |
| 702 | def get_close_matches(word, possibilities, n=3, cutoff=0.6): |
| 703 | """Use SequenceMatcher to return list of the best "good enough" matches. |
| 704 | |
| 705 | word is a sequence for which close matches are desired (typically a |
| 706 | string). |
| 707 | |
| 708 | possibilities is a list of sequences against which to match word |
| 709 | (typically a list of strings). |
| 710 | |
| 711 | Optional arg n (default 3) is the maximum number of close matches to |
| 712 | return. n must be > 0. |
| 713 | |
| 714 | Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities |
| 715 | that don't score at least that similar to word are ignored. |
| 716 | |
| 717 | The best (no more than n) matches among the possibilities are returned |
| 718 | in a list, sorted by similarity score, most similar first. |
| 719 | |
| 720 | >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"]) |
| 721 | ['apple', 'ape'] |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 722 | >>> import keyword as _keyword |
| 723 | >>> get_close_matches("wheel", _keyword.kwlist) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 724 | ['while'] |
Guido van Rossum | 486364b | 2007-06-30 05:01:58 +0000 | [diff] [blame] | 725 | >>> get_close_matches("Apple", _keyword.kwlist) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 726 | [] |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 727 | >>> get_close_matches("accept", _keyword.kwlist) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 728 | ['except'] |
| 729 | """ |
| 730 | |
| 731 | if not n > 0: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 732 | raise ValueError("n must be > 0: %r" % (n,)) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 733 | if not 0.0 <= cutoff <= 1.0: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 734 | raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,)) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 735 | result = [] |
| 736 | s = SequenceMatcher() |
| 737 | s.set_seq2(word) |
| 738 | for x in possibilities: |
| 739 | s.set_seq1(x) |
| 740 | if s.real_quick_ratio() >= cutoff and \ |
| 741 | s.quick_ratio() >= cutoff and \ |
| 742 | s.ratio() >= cutoff: |
| 743 | result.append((s.ratio(), x)) |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 744 | |
Raymond Hettinger | 6b59f5f | 2003-10-16 05:53:16 +0000 | [diff] [blame] | 745 | # Move the best scorers to head of list |
Raymond Hettinger | aefde43 | 2004-06-15 23:53:35 +0000 | [diff] [blame] | 746 | result = heapq.nlargest(n, result) |
Raymond Hettinger | 6b59f5f | 2003-10-16 05:53:16 +0000 | [diff] [blame] | 747 | # Strip scores for the best n matches |
Raymond Hettinger | bb6b734 | 2004-06-13 09:57:33 +0000 | [diff] [blame] | 748 | return [x for score, x in result] |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 749 | |
| 750 | def _count_leading(line, ch): |
| 751 | """ |
| 752 | Return number of `ch` characters at the start of `line`. |
| 753 | |
| 754 | Example: |
| 755 | |
| 756 | >>> _count_leading(' abc', ' ') |
| 757 | 3 |
| 758 | """ |
| 759 | |
| 760 | i, n = 0, len(line) |
| 761 | while i < n and line[i] == ch: |
| 762 | i += 1 |
| 763 | return i |
| 764 | |
| 765 | class Differ: |
| 766 | r""" |
| 767 | Differ is a class for comparing sequences of lines of text, and |
| 768 | producing human-readable differences or deltas. Differ uses |
| 769 | SequenceMatcher both to compare sequences of lines, and to compare |
| 770 | sequences of characters within similar (near-matching) lines. |
| 771 | |
| 772 | Each line of a Differ delta begins with a two-letter code: |
| 773 | |
| 774 | '- ' line unique to sequence 1 |
| 775 | '+ ' line unique to sequence 2 |
| 776 | ' ' line common to both sequences |
| 777 | '? ' line not present in either input sequence |
| 778 | |
| 779 | Lines beginning with '? ' attempt to guide the eye to intraline |
| 780 | differences, and were not present in either input sequence. These lines |
| 781 | can be confusing if the sequences contain tab characters. |
| 782 | |
| 783 | Note that Differ makes no claim to produce a *minimal* diff. To the |
| 784 | contrary, minimal diffs are often counter-intuitive, because they synch |
| 785 | up anywhere possible, sometimes accidental matches 100 pages apart. |
| 786 | Restricting synch points to contiguous matches preserves some notion of |
| 787 | locality, at the occasional cost of producing a longer diff. |
| 788 | |
| 789 | Example: Comparing two texts. |
| 790 | |
| 791 | First we set up the texts, sequences of individual single-line strings |
| 792 | ending with newlines (such sequences can also be obtained from the |
| 793 | `readlines()` method of file-like objects): |
| 794 | |
| 795 | >>> text1 = ''' 1. Beautiful is better than ugly. |
| 796 | ... 2. Explicit is better than implicit. |
| 797 | ... 3. Simple is better than complex. |
| 798 | ... 4. Complex is better than complicated. |
| 799 | ... '''.splitlines(1) |
| 800 | >>> len(text1) |
| 801 | 4 |
| 802 | >>> text1[0][-1] |
| 803 | '\n' |
| 804 | >>> text2 = ''' 1. Beautiful is better than ugly. |
| 805 | ... 3. Simple is better than complex. |
| 806 | ... 4. Complicated is better than complex. |
| 807 | ... 5. Flat is better than nested. |
| 808 | ... '''.splitlines(1) |
| 809 | |
| 810 | Next we instantiate a Differ object: |
| 811 | |
| 812 | >>> d = Differ() |
| 813 | |
| 814 | Note that when instantiating a Differ object we may pass functions to |
| 815 | filter out line and character 'junk'. See Differ.__init__ for details. |
| 816 | |
| 817 | Finally, we compare the two: |
| 818 | |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 819 | >>> result = list(d.compare(text1, text2)) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 820 | |
| 821 | 'result' is a list of strings, so let's pretty-print it: |
| 822 | |
| 823 | >>> from pprint import pprint as _pprint |
| 824 | >>> _pprint(result) |
| 825 | [' 1. Beautiful is better than ugly.\n', |
| 826 | '- 2. Explicit is better than implicit.\n', |
| 827 | '- 3. Simple is better than complex.\n', |
| 828 | '+ 3. Simple is better than complex.\n', |
| 829 | '? ++\n', |
| 830 | '- 4. Complex is better than complicated.\n', |
| 831 | '? ^ ---- ^\n', |
| 832 | '+ 4. Complicated is better than complex.\n', |
| 833 | '? ++++ ^ ^\n', |
| 834 | '+ 5. Flat is better than nested.\n'] |
| 835 | |
| 836 | As a single multi-line string it looks like this: |
| 837 | |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 838 | >>> print(''.join(result), end="") |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 839 | 1. Beautiful is better than ugly. |
| 840 | - 2. Explicit is better than implicit. |
| 841 | - 3. Simple is better than complex. |
| 842 | + 3. Simple is better than complex. |
| 843 | ? ++ |
| 844 | - 4. Complex is better than complicated. |
| 845 | ? ^ ---- ^ |
| 846 | + 4. Complicated is better than complex. |
| 847 | ? ++++ ^ ^ |
| 848 | + 5. Flat is better than nested. |
| 849 | |
| 850 | Methods: |
| 851 | |
| 852 | __init__(linejunk=None, charjunk=None) |
| 853 | Construct a text differencer, with optional filters. |
| 854 | |
| 855 | compare(a, b) |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 856 | Compare two sequences of lines; generate the resulting delta. |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 857 | """ |
| 858 | |
| 859 | def __init__(self, linejunk=None, charjunk=None): |
| 860 | """ |
| 861 | Construct a text differencer, with optional filters. |
| 862 | |
| 863 | The two optional keyword parameters are for filter functions: |
| 864 | |
| 865 | - `linejunk`: A function that should accept a single string argument, |
| 866 | and return true iff the string is junk. The module-level function |
| 867 | `IS_LINE_JUNK` may be used to filter out lines without visible |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 868 | characters, except for at most one splat ('#'). It is recommended |
| 869 | to leave linejunk None; as of Python 2.3, the underlying |
| 870 | SequenceMatcher class has grown an adaptive notion of "noise" lines |
| 871 | that's better than any static definition the author has ever been |
| 872 | able to craft. |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 873 | |
| 874 | - `charjunk`: A function that should accept a string of length 1. The |
| 875 | module-level function `IS_CHARACTER_JUNK` may be used to filter out |
| 876 | whitespace characters (a blank or tab; **note**: bad idea to include |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 877 | newline in this!). Use of IS_CHARACTER_JUNK is recommended. |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 878 | """ |
| 879 | |
| 880 | self.linejunk = linejunk |
| 881 | self.charjunk = charjunk |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 882 | |
| 883 | def compare(self, a, b): |
| 884 | r""" |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 885 | Compare two sequences of lines; generate the resulting delta. |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 886 | |
| 887 | Each sequence must contain individual single-line strings ending with |
| 888 | newlines. Such sequences can be obtained from the `readlines()` method |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 889 | of file-like objects. The delta generated also consists of newline- |
| 890 | terminated strings, ready to be printed as-is via the writeline() |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 891 | method of a file-like object. |
| 892 | |
| 893 | Example: |
| 894 | |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 895 | >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1), |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 896 | ... 'ore\ntree\nemu\n'.splitlines(1))), |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 897 | ... end="") |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 898 | - one |
| 899 | ? ^ |
| 900 | + ore |
| 901 | ? ^ |
| 902 | - two |
| 903 | - three |
| 904 | ? - |
| 905 | + tree |
| 906 | + emu |
| 907 | """ |
| 908 | |
| 909 | cruncher = SequenceMatcher(self.linejunk, a, b) |
| 910 | for tag, alo, ahi, blo, bhi in cruncher.get_opcodes(): |
| 911 | if tag == 'replace': |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 912 | g = self._fancy_replace(a, alo, ahi, b, blo, bhi) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 913 | elif tag == 'delete': |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 914 | g = self._dump('-', a, alo, ahi) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 915 | elif tag == 'insert': |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 916 | g = self._dump('+', b, blo, bhi) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 917 | elif tag == 'equal': |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 918 | g = self._dump(' ', a, alo, ahi) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 919 | else: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 920 | raise ValueError('unknown tag %r' % (tag,)) |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 921 | |
| 922 | for line in g: |
| 923 | yield line |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 924 | |
| 925 | def _dump(self, tag, x, lo, hi): |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 926 | """Generate comparison results for a same-tagged range.""" |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 927 | for i in range(lo, hi): |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 928 | yield '%s %s' % (tag, x[i]) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 929 | |
| 930 | def _plain_replace(self, a, alo, ahi, b, blo, bhi): |
| 931 | assert alo < ahi and blo < bhi |
| 932 | # dump the shorter block first -- reduces the burden on short-term |
| 933 | # memory if the blocks are of very different sizes |
| 934 | if bhi - blo < ahi - alo: |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 935 | first = self._dump('+', b, blo, bhi) |
| 936 | second = self._dump('-', a, alo, ahi) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 937 | else: |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 938 | first = self._dump('-', a, alo, ahi) |
| 939 | second = self._dump('+', b, blo, bhi) |
| 940 | |
| 941 | for g in first, second: |
| 942 | for line in g: |
| 943 | yield line |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 944 | |
| 945 | def _fancy_replace(self, a, alo, ahi, b, blo, bhi): |
| 946 | r""" |
| 947 | When replacing one block of lines with another, search the blocks |
| 948 | for *similar* lines; the best-matching pair (if any) is used as a |
| 949 | synch point, and intraline difference marking is done on the |
| 950 | similar pair. Lots of work, but often worth it. |
| 951 | |
| 952 | Example: |
| 953 | |
| 954 | >>> d = Differ() |
Raymond Hettinger | 83325e9 | 2003-07-16 04:32:32 +0000 | [diff] [blame] | 955 | >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1, |
| 956 | ... ['abcdefGhijkl\n'], 0, 1) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 957 | >>> print(''.join(results), end="") |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 958 | - abcDefghiJkl |
| 959 | ? ^ ^ ^ |
| 960 | + abcdefGhijkl |
| 961 | ? ^ ^ ^ |
| 962 | """ |
| 963 | |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 964 | # don't synch up unless the lines have a similarity score of at |
| 965 | # least cutoff; best_ratio tracks the best score seen so far |
| 966 | best_ratio, cutoff = 0.74, 0.75 |
| 967 | cruncher = SequenceMatcher(self.charjunk) |
| 968 | eqi, eqj = None, None # 1st indices of equal lines (if any) |
| 969 | |
| 970 | # search for the pair that matches best without being identical |
| 971 | # (identical lines must be junk lines, & we don't want to synch up |
| 972 | # on junk -- unless we have to) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 973 | for j in range(blo, bhi): |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 974 | bj = b[j] |
| 975 | cruncher.set_seq2(bj) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 976 | for i in range(alo, ahi): |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 977 | ai = a[i] |
| 978 | if ai == bj: |
| 979 | if eqi is None: |
| 980 | eqi, eqj = i, j |
| 981 | continue |
| 982 | cruncher.set_seq1(ai) |
| 983 | # computing similarity is expensive, so use the quick |
| 984 | # upper bounds first -- have seen this speed up messy |
| 985 | # compares by a factor of 3. |
| 986 | # note that ratio() is only expensive to compute the first |
| 987 | # time it's called on a sequence pair; the expensive part |
| 988 | # of the computation is cached by cruncher |
| 989 | if cruncher.real_quick_ratio() > best_ratio and \ |
| 990 | cruncher.quick_ratio() > best_ratio and \ |
| 991 | cruncher.ratio() > best_ratio: |
| 992 | best_ratio, best_i, best_j = cruncher.ratio(), i, j |
| 993 | if best_ratio < cutoff: |
| 994 | # no non-identical "pretty close" pair |
| 995 | if eqi is None: |
| 996 | # no identical pair either -- treat it as a straight replace |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 997 | for line in self._plain_replace(a, alo, ahi, b, blo, bhi): |
| 998 | yield line |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 999 | return |
| 1000 | # no close pair, but an identical pair -- synch up on that |
| 1001 | best_i, best_j, best_ratio = eqi, eqj, 1.0 |
| 1002 | else: |
| 1003 | # there's a close pair, so forget the identical pair (if any) |
| 1004 | eqi = None |
| 1005 | |
| 1006 | # a[best_i] very similar to b[best_j]; eqi is None iff they're not |
| 1007 | # identical |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1008 | |
| 1009 | # pump out diffs from before the synch point |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1010 | for line in self._fancy_helper(a, alo, best_i, b, blo, best_j): |
| 1011 | yield line |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1012 | |
| 1013 | # do intraline marking on the synch pair |
| 1014 | aelt, belt = a[best_i], b[best_j] |
| 1015 | if eqi is None: |
| 1016 | # pump out a '-', '?', '+', '?' quad for the synched lines |
| 1017 | atags = btags = "" |
| 1018 | cruncher.set_seqs(aelt, belt) |
| 1019 | for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes(): |
| 1020 | la, lb = ai2 - ai1, bj2 - bj1 |
| 1021 | if tag == 'replace': |
| 1022 | atags += '^' * la |
| 1023 | btags += '^' * lb |
| 1024 | elif tag == 'delete': |
| 1025 | atags += '-' * la |
| 1026 | elif tag == 'insert': |
| 1027 | btags += '+' * lb |
| 1028 | elif tag == 'equal': |
| 1029 | atags += ' ' * la |
| 1030 | btags += ' ' * lb |
| 1031 | else: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 1032 | raise ValueError('unknown tag %r' % (tag,)) |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1033 | for line in self._qformat(aelt, belt, atags, btags): |
| 1034 | yield line |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1035 | else: |
| 1036 | # the synch pair is identical |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1037 | yield ' ' + aelt |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1038 | |
| 1039 | # pump out diffs from after the synch point |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1040 | for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi): |
| 1041 | yield line |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1042 | |
| 1043 | def _fancy_helper(self, a, alo, ahi, b, blo, bhi): |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1044 | g = [] |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1045 | if alo < ahi: |
| 1046 | if blo < bhi: |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1047 | g = self._fancy_replace(a, alo, ahi, b, blo, bhi) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1048 | else: |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1049 | g = self._dump('-', a, alo, ahi) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1050 | elif blo < bhi: |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1051 | g = self._dump('+', b, blo, bhi) |
| 1052 | |
| 1053 | for line in g: |
| 1054 | yield line |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1055 | |
| 1056 | def _qformat(self, aline, bline, atags, btags): |
| 1057 | r""" |
| 1058 | Format "?" output and deal with leading tabs. |
| 1059 | |
| 1060 | Example: |
| 1061 | |
| 1062 | >>> d = Differ() |
Raymond Hettinger | 83325e9 | 2003-07-16 04:32:32 +0000 | [diff] [blame] | 1063 | >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n', |
| 1064 | ... ' ^ ^ ^ ', '+ ^ ^ ^ ') |
Guido van Rossum | fff80df | 2007-02-09 20:33:44 +0000 | [diff] [blame] | 1065 | >>> for line in results: print(repr(line)) |
| 1066 | ... |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1067 | '- \tabcDefghiJkl\n' |
| 1068 | '? \t ^ ^ ^\n' |
| 1069 | '+ \t\tabcdefGhijkl\n' |
| 1070 | '? \t ^ ^ ^\n' |
| 1071 | """ |
| 1072 | |
| 1073 | # Can hurt, but will probably help most of the time. |
| 1074 | common = min(_count_leading(aline, "\t"), |
| 1075 | _count_leading(bline, "\t")) |
| 1076 | common = min(common, _count_leading(atags[:common], " ")) |
| 1077 | atags = atags[common:].rstrip() |
| 1078 | btags = btags[common:].rstrip() |
| 1079 | |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1080 | yield "- " + aline |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1081 | if atags: |
Tim Peters | 527e64f | 2001-10-04 05:36:56 +0000 | [diff] [blame] | 1082 | yield "? %s%s\n" % ("\t" * common, atags) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1083 | |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1084 | yield "+ " + bline |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1085 | if btags: |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1086 | yield "? %s%s\n" % ("\t" * common, btags) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1087 | |
| 1088 | # With respect to junk, an earlier version of ndiff simply refused to |
| 1089 | # *start* a match with a junk element. The result was cases like this: |
| 1090 | # before: private Thread currentThread; |
| 1091 | # after: private volatile Thread currentThread; |
| 1092 | # If you consider whitespace to be junk, the longest contiguous match |
| 1093 | # not starting with junk is "e Thread currentThread". So ndiff reported |
| 1094 | # that "e volatil" was inserted between the 't' and the 'e' in "private". |
| 1095 | # While an accurate view, to people that's absurd. The current version |
| 1096 | # looks for matching blocks that are entirely junk-free, then extends the |
| 1097 | # longest one of those as far as possible but only with matching junk. |
| 1098 | # So now "currentThread" is matched, then extended to suck up the |
| 1099 | # preceding blank; then "private" is matched, and extended to suck up the |
| 1100 | # following blank; then "Thread" is matched; and finally ndiff reports |
| 1101 | # that "volatile " was inserted before "Thread". The only quibble |
| 1102 | # remaining is that perhaps it was really the case that " volatile" |
| 1103 | # was inserted after "private". I can live with that <wink>. |
| 1104 | |
| 1105 | import re |
| 1106 | |
| 1107 | def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match): |
| 1108 | r""" |
| 1109 | Return 1 for ignorable line: iff `line` is blank or contains a single '#'. |
| 1110 | |
| 1111 | Examples: |
| 1112 | |
| 1113 | >>> IS_LINE_JUNK('\n') |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 1114 | True |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1115 | >>> IS_LINE_JUNK(' # \n') |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 1116 | True |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1117 | >>> IS_LINE_JUNK('hello\n') |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 1118 | False |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1119 | """ |
| 1120 | |
| 1121 | return pat(line) is not None |
| 1122 | |
| 1123 | def IS_CHARACTER_JUNK(ch, ws=" \t"): |
| 1124 | r""" |
| 1125 | Return 1 for ignorable character: iff `ch` is a space or tab. |
| 1126 | |
| 1127 | Examples: |
| 1128 | |
| 1129 | >>> IS_CHARACTER_JUNK(' ') |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 1130 | True |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1131 | >>> IS_CHARACTER_JUNK('\t') |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 1132 | True |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1133 | >>> IS_CHARACTER_JUNK('\n') |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 1134 | False |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1135 | >>> IS_CHARACTER_JUNK('x') |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 1136 | False |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1137 | """ |
| 1138 | |
| 1139 | return ch in ws |
| 1140 | |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1141 | |
| 1142 | def unified_diff(a, b, fromfile='', tofile='', fromfiledate='', |
| 1143 | tofiledate='', n=3, lineterm='\n'): |
| 1144 | r""" |
| 1145 | Compare two sequences of lines; generate the delta as a unified diff. |
| 1146 | |
| 1147 | Unified diffs are a compact way of showing line changes and a few |
| 1148 | lines of context. The number of context lines is set by 'n' which |
| 1149 | defaults to three. |
| 1150 | |
Raymond Hettinger | 0887c73 | 2003-06-17 16:53:25 +0000 | [diff] [blame] | 1151 | By default, the diff control lines (those with ---, +++, or @@) are |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1152 | created with a trailing newline. This is helpful so that inputs |
| 1153 | created from file.readlines() result in diffs that are suitable for |
| 1154 | file.writelines() since both the inputs and outputs have trailing |
| 1155 | newlines. |
| 1156 | |
| 1157 | For inputs that do not have trailing newlines, set the lineterm |
| 1158 | argument to "" so that the output will be uniformly newline free. |
| 1159 | |
| 1160 | The unidiff format normally has a header for filenames and modification |
| 1161 | times. Any or all of these may be specified using strings for |
| 1162 | 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification |
| 1163 | times are normally expressed in the format returned by time.ctime(). |
| 1164 | |
| 1165 | Example: |
| 1166 | |
| 1167 | >>> for line in unified_diff('one two three four'.split(), |
| 1168 | ... 'zero one tree four'.split(), 'Original', 'Current', |
| 1169 | ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003', |
| 1170 | ... lineterm=''): |
Guido van Rossum | fff80df | 2007-02-09 20:33:44 +0000 | [diff] [blame] | 1171 | ... print(line) |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1172 | --- Original Sat Jan 26 23:30:50 1991 |
| 1173 | +++ Current Fri Jun 06 10:20:52 2003 |
| 1174 | @@ -1,4 +1,4 @@ |
| 1175 | +zero |
| 1176 | one |
| 1177 | -two |
| 1178 | -three |
| 1179 | +tree |
| 1180 | four |
| 1181 | """ |
| 1182 | |
| 1183 | started = False |
| 1184 | for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n): |
| 1185 | if not started: |
| 1186 | yield '--- %s %s%s' % (fromfile, fromfiledate, lineterm) |
| 1187 | yield '+++ %s %s%s' % (tofile, tofiledate, lineterm) |
| 1188 | started = True |
| 1189 | i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4] |
| 1190 | yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm) |
| 1191 | for tag, i1, i2, j1, j2 in group: |
| 1192 | if tag == 'equal': |
| 1193 | for line in a[i1:i2]: |
| 1194 | yield ' ' + line |
| 1195 | continue |
| 1196 | if tag == 'replace' or tag == 'delete': |
| 1197 | for line in a[i1:i2]: |
| 1198 | yield '-' + line |
| 1199 | if tag == 'replace' or tag == 'insert': |
| 1200 | for line in b[j1:j2]: |
| 1201 | yield '+' + line |
| 1202 | |
| 1203 | # See http://www.unix.org/single_unix_specification/ |
| 1204 | def context_diff(a, b, fromfile='', tofile='', |
| 1205 | fromfiledate='', tofiledate='', n=3, lineterm='\n'): |
| 1206 | r""" |
| 1207 | Compare two sequences of lines; generate the delta as a context diff. |
| 1208 | |
| 1209 | Context diffs are a compact way of showing line changes and a few |
| 1210 | lines of context. The number of context lines is set by 'n' which |
| 1211 | defaults to three. |
| 1212 | |
| 1213 | By default, the diff control lines (those with *** or ---) are |
| 1214 | created with a trailing newline. This is helpful so that inputs |
| 1215 | created from file.readlines() result in diffs that are suitable for |
| 1216 | file.writelines() since both the inputs and outputs have trailing |
| 1217 | newlines. |
| 1218 | |
| 1219 | For inputs that do not have trailing newlines, set the lineterm |
| 1220 | argument to "" so that the output will be uniformly newline free. |
| 1221 | |
| 1222 | The context diff format normally has a header for filenames and |
| 1223 | modification times. Any or all of these may be specified using |
| 1224 | strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. |
| 1225 | The modification times are normally expressed in the format returned |
| 1226 | by time.ctime(). If not specified, the strings default to blanks. |
| 1227 | |
| 1228 | Example: |
| 1229 | |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1230 | >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1), |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1231 | ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current', |
| 1232 | ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')), |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1233 | ... end="") |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1234 | *** Original Sat Jan 26 23:30:50 1991 |
| 1235 | --- Current Fri Jun 06 10:22:46 2003 |
| 1236 | *************** |
| 1237 | *** 1,4 **** |
| 1238 | one |
| 1239 | ! two |
| 1240 | ! three |
| 1241 | four |
| 1242 | --- 1,4 ---- |
| 1243 | + zero |
| 1244 | one |
| 1245 | ! tree |
| 1246 | four |
| 1247 | """ |
| 1248 | |
| 1249 | started = False |
Raymond Hettinger | 7f2d302 | 2003-06-08 19:38:42 +0000 | [diff] [blame] | 1250 | prefixmap = {'insert':'+ ', 'delete':'- ', 'replace':'! ', 'equal':' '} |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1251 | for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n): |
| 1252 | if not started: |
| 1253 | yield '*** %s %s%s' % (fromfile, fromfiledate, lineterm) |
| 1254 | yield '--- %s %s%s' % (tofile, tofiledate, lineterm) |
| 1255 | started = True |
Raymond Hettinger | 7f2d302 | 2003-06-08 19:38:42 +0000 | [diff] [blame] | 1256 | |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1257 | yield '***************%s' % (lineterm,) |
| 1258 | if group[-1][2] - group[0][1] >= 2: |
| 1259 | yield '*** %d,%d ****%s' % (group[0][1]+1, group[-1][2], lineterm) |
| 1260 | else: |
| 1261 | yield '*** %d ****%s' % (group[-1][2], lineterm) |
Raymond Hettinger | 7f2d302 | 2003-06-08 19:38:42 +0000 | [diff] [blame] | 1262 | visiblechanges = [e for e in group if e[0] in ('replace', 'delete')] |
| 1263 | if visiblechanges: |
| 1264 | for tag, i1, i2, _, _ in group: |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1265 | if tag != 'insert': |
| 1266 | for line in a[i1:i2]: |
| 1267 | yield prefixmap[tag] + line |
Raymond Hettinger | 7f2d302 | 2003-06-08 19:38:42 +0000 | [diff] [blame] | 1268 | |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1269 | if group[-1][4] - group[0][3] >= 2: |
| 1270 | yield '--- %d,%d ----%s' % (group[0][3]+1, group[-1][4], lineterm) |
| 1271 | else: |
| 1272 | yield '--- %d ----%s' % (group[-1][4], lineterm) |
Raymond Hettinger | 7f2d302 | 2003-06-08 19:38:42 +0000 | [diff] [blame] | 1273 | visiblechanges = [e for e in group if e[0] in ('replace', 'insert')] |
| 1274 | if visiblechanges: |
| 1275 | for tag, _, _, j1, j2 in group: |
Raymond Hettinger | f0b1a1f | 2003-06-08 11:07:08 +0000 | [diff] [blame] | 1276 | if tag != 'delete': |
| 1277 | for line in b[j1:j2]: |
| 1278 | yield prefixmap[tag] + line |
| 1279 | |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 1280 | def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK): |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1281 | r""" |
| 1282 | Compare `a` and `b` (lists of strings); return a `Differ`-style delta. |
| 1283 | |
| 1284 | Optional keyword parameters `linejunk` and `charjunk` are for filter |
| 1285 | functions (or None): |
| 1286 | |
| 1287 | - linejunk: A function that should accept a single string argument, and |
Tim Peters | 81b9251 | 2002-04-29 01:37:32 +0000 | [diff] [blame] | 1288 | return true iff the string is junk. The default is None, and is |
| 1289 | recommended; as of Python 2.3, an adaptive notion of "noise" lines is |
| 1290 | used that does a good job on its own. |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1291 | |
| 1292 | - charjunk: A function that should accept a string of length 1. The |
| 1293 | default is module-level function IS_CHARACTER_JUNK, which filters out |
| 1294 | whitespace characters (a blank or tab; note: bad idea to include newline |
| 1295 | in this!). |
| 1296 | |
| 1297 | Tools/scripts/ndiff.py is a command-line front-end to this function. |
| 1298 | |
| 1299 | Example: |
| 1300 | |
| 1301 | >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), |
| 1302 | ... 'ore\ntree\nemu\n'.splitlines(1)) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1303 | >>> print(''.join(diff), end="") |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1304 | - one |
| 1305 | ? ^ |
| 1306 | + ore |
| 1307 | ? ^ |
| 1308 | - two |
| 1309 | - three |
| 1310 | ? - |
| 1311 | + tree |
| 1312 | + emu |
| 1313 | """ |
| 1314 | return Differ(linejunk, charjunk).compare(a, b) |
| 1315 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1316 | def _mdiff(fromlines, tolines, context=None, linejunk=None, |
| 1317 | charjunk=IS_CHARACTER_JUNK): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1318 | r"""Returns generator yielding marked up from/to side by side differences. |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1319 | |
| 1320 | Arguments: |
| 1321 | fromlines -- list of text lines to compared to tolines |
| 1322 | tolines -- list of text lines to be compared to fromlines |
| 1323 | context -- number of context lines to display on each side of difference, |
| 1324 | if None, all from/to text lines will be generated. |
| 1325 | linejunk -- passed on to ndiff (see ndiff documentation) |
| 1326 | charjunk -- passed on to ndiff (see ndiff documentation) |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1327 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1328 | This function returns an interator which returns a tuple: |
| 1329 | (from line tuple, to line tuple, boolean flag) |
| 1330 | |
| 1331 | from/to line tuple -- (line num, line text) |
| 1332 | line num -- integer or None (to indicate a context seperation) |
| 1333 | line text -- original line text with following markers inserted: |
| 1334 | '\0+' -- marks start of added text |
| 1335 | '\0-' -- marks start of deleted text |
| 1336 | '\0^' -- marks start of changed text |
| 1337 | '\1' -- marks end of added/deleted/changed text |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1338 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1339 | boolean flag -- None indicates context separation, True indicates |
| 1340 | either "from" or "to" line contains a change, otherwise False. |
| 1341 | |
| 1342 | This function/iterator was originally developed to generate side by side |
| 1343 | file difference for making HTML pages (see HtmlDiff class for example |
| 1344 | usage). |
| 1345 | |
| 1346 | Note, this function utilizes the ndiff function to generate the side by |
| 1347 | side difference markup. Optional ndiff arguments may be passed to this |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1348 | function and they in turn will be passed to ndiff. |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1349 | """ |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1350 | import re |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1351 | |
| 1352 | # regular expression for finding intraline change indices |
| 1353 | change_re = re.compile('(\++|\-+|\^+)') |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1354 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1355 | # create the difference iterator to generate the differences |
| 1356 | diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk) |
| 1357 | |
| 1358 | def _make_line(lines, format_key, side, num_lines=[0,0]): |
| 1359 | """Returns line of text with user's change markup and line formatting. |
| 1360 | |
| 1361 | lines -- list of lines from the ndiff generator to produce a line of |
| 1362 | text from. When producing the line of text to return, the |
| 1363 | lines used are removed from this list. |
| 1364 | format_key -- '+' return first line in list with "add" markup around |
| 1365 | the entire line. |
| 1366 | '-' return first line in list with "delete" markup around |
| 1367 | the entire line. |
| 1368 | '?' return first line in list with add/delete/change |
| 1369 | intraline markup (indices obtained from second line) |
| 1370 | None return first line in list with no markup |
| 1371 | side -- indice into the num_lines list (0=from,1=to) |
| 1372 | num_lines -- from/to current line number. This is NOT intended to be a |
| 1373 | passed parameter. It is present as a keyword argument to |
| 1374 | maintain memory of the current line numbers between calls |
| 1375 | of this function. |
| 1376 | |
| 1377 | Note, this function is purposefully not defined at the module scope so |
| 1378 | that data it needs from its parent function (within whose context it |
| 1379 | is defined) does not need to be of module scope. |
| 1380 | """ |
| 1381 | num_lines[side] += 1 |
| 1382 | # Handle case where no user markup is to be added, just return line of |
| 1383 | # text with user's line format to allow for usage of the line number. |
| 1384 | if format_key is None: |
| 1385 | return (num_lines[side],lines.pop(0)[2:]) |
| 1386 | # Handle case of intraline changes |
| 1387 | if format_key == '?': |
| 1388 | text, markers = lines.pop(0), lines.pop(0) |
| 1389 | # find intraline changes (store change type and indices in tuples) |
| 1390 | sub_info = [] |
| 1391 | def record_sub_info(match_object,sub_info=sub_info): |
| 1392 | sub_info.append([match_object.group(1)[0],match_object.span()]) |
| 1393 | return match_object.group(1) |
| 1394 | change_re.sub(record_sub_info,markers) |
| 1395 | # process each tuple inserting our special marks that won't be |
| 1396 | # noticed by an xml/html escaper. |
| 1397 | for key,(begin,end) in sub_info[::-1]: |
| 1398 | text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:] |
| 1399 | text = text[2:] |
| 1400 | # Handle case of add/delete entire line |
| 1401 | else: |
| 1402 | text = lines.pop(0)[2:] |
| 1403 | # if line of text is just a newline, insert a space so there is |
| 1404 | # something for the user to highlight and see. |
Tim Peters | 0ca0c64 | 2004-11-12 16:12:15 +0000 | [diff] [blame] | 1405 | if not text: |
| 1406 | text = ' ' |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1407 | # insert marks that won't be noticed by an xml/html escaper. |
| 1408 | text = '\0' + format_key + text + '\1' |
Georg Brandl | 7eb4b7d | 2005-07-22 21:49:32 +0000 | [diff] [blame] | 1409 | # Return line of text, first allow user's line formatter to do its |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1410 | # thing (such as adding the line number) then replace the special |
| 1411 | # marks with what the user's change markup. |
| 1412 | return (num_lines[side],text) |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1413 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1414 | def _line_iterator(): |
| 1415 | """Yields from/to lines of text with a change indication. |
| 1416 | |
| 1417 | This function is an iterator. It itself pulls lines from a |
| 1418 | differencing iterator, processes them and yields them. When it can |
| 1419 | it yields both a "from" and a "to" line, otherwise it will yield one |
| 1420 | or the other. In addition to yielding the lines of from/to text, a |
| 1421 | boolean flag is yielded to indicate if the text line(s) have |
| 1422 | differences in them. |
| 1423 | |
| 1424 | Note, this function is purposefully not defined at the module scope so |
| 1425 | that data it needs from its parent function (within whose context it |
| 1426 | is defined) does not need to be of module scope. |
| 1427 | """ |
| 1428 | lines = [] |
| 1429 | num_blanks_pending, num_blanks_to_yield = 0, 0 |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1430 | while True: |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1431 | # Load up next 4 lines so we can look ahead, create strings which |
| 1432 | # are a concatenation of the first character of each of the 4 lines |
| 1433 | # so we can do some very readable comparisons. |
| 1434 | while len(lines) < 4: |
| 1435 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1436 | lines.append(next(diff_lines_iterator)) |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1437 | except StopIteration: |
| 1438 | lines.append('X') |
| 1439 | s = ''.join([line[0] for line in lines]) |
| 1440 | if s.startswith('X'): |
| 1441 | # When no more lines, pump out any remaining blank lines so the |
| 1442 | # corresponding add/delete lines get a matching blank line so |
| 1443 | # all line pairs get yielded at the next level. |
| 1444 | num_blanks_to_yield = num_blanks_pending |
| 1445 | elif s.startswith('-?+?'): |
| 1446 | # simple intraline change |
| 1447 | yield _make_line(lines,'?',0), _make_line(lines,'?',1), True |
| 1448 | continue |
| 1449 | elif s.startswith('--++'): |
| 1450 | # in delete block, add block coming: we do NOT want to get |
| 1451 | # caught up on blank lines yet, just process the delete line |
| 1452 | num_blanks_pending -= 1 |
| 1453 | yield _make_line(lines,'-',0), None, True |
| 1454 | continue |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1455 | elif s.startswith(('--?+', '--+', '- ')): |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1456 | # in delete block and see a intraline change or unchanged line |
| 1457 | # coming: yield the delete line and then blanks |
| 1458 | from_line,to_line = _make_line(lines,'-',0), None |
| 1459 | num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0 |
| 1460 | elif s.startswith('-+?'): |
| 1461 | # intraline change |
| 1462 | yield _make_line(lines,None,0), _make_line(lines,'?',1), True |
| 1463 | continue |
| 1464 | elif s.startswith('-?+'): |
| 1465 | # intraline change |
| 1466 | yield _make_line(lines,'?',0), _make_line(lines,None,1), True |
| 1467 | continue |
| 1468 | elif s.startswith('-'): |
| 1469 | # delete FROM line |
| 1470 | num_blanks_pending -= 1 |
| 1471 | yield _make_line(lines,'-',0), None, True |
| 1472 | continue |
| 1473 | elif s.startswith('+--'): |
| 1474 | # in add block, delete block coming: we do NOT want to get |
| 1475 | # caught up on blank lines yet, just process the add line |
| 1476 | num_blanks_pending += 1 |
| 1477 | yield None, _make_line(lines,'+',1), True |
| 1478 | continue |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1479 | elif s.startswith(('+ ', '+-')): |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1480 | # will be leaving an add block: yield blanks then add line |
| 1481 | from_line, to_line = None, _make_line(lines,'+',1) |
| 1482 | num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0 |
| 1483 | elif s.startswith('+'): |
| 1484 | # inside an add block, yield the add line |
| 1485 | num_blanks_pending += 1 |
| 1486 | yield None, _make_line(lines,'+',1), True |
| 1487 | continue |
| 1488 | elif s.startswith(' '): |
| 1489 | # unchanged text, yield it to both sides |
| 1490 | yield _make_line(lines[:],None,0),_make_line(lines,None,1),False |
| 1491 | continue |
| 1492 | # Catch up on the blank lines so when we yield the next from/to |
| 1493 | # pair, they are lined up. |
| 1494 | while(num_blanks_to_yield < 0): |
| 1495 | num_blanks_to_yield += 1 |
| 1496 | yield None,('','\n'),True |
| 1497 | while(num_blanks_to_yield > 0): |
| 1498 | num_blanks_to_yield -= 1 |
| 1499 | yield ('','\n'),None,True |
| 1500 | if s.startswith('X'): |
| 1501 | raise StopIteration |
| 1502 | else: |
| 1503 | yield from_line,to_line,True |
| 1504 | |
| 1505 | def _line_pair_iterator(): |
| 1506 | """Yields from/to lines of text with a change indication. |
| 1507 | |
| 1508 | This function is an iterator. It itself pulls lines from the line |
Georg Brandl | 7eb4b7d | 2005-07-22 21:49:32 +0000 | [diff] [blame] | 1509 | iterator. Its difference from that iterator is that this function |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1510 | always yields a pair of from/to text lines (with the change |
| 1511 | indication). If necessary it will collect single from/to lines |
| 1512 | until it has a matching pair from/to pair to yield. |
| 1513 | |
| 1514 | Note, this function is purposefully not defined at the module scope so |
| 1515 | that data it needs from its parent function (within whose context it |
| 1516 | is defined) does not need to be of module scope. |
| 1517 | """ |
| 1518 | line_iterator = _line_iterator() |
| 1519 | fromlines,tolines=[],[] |
| 1520 | while True: |
| 1521 | # Collecting lines of text until we have a from/to pair |
| 1522 | while (len(fromlines)==0 or len(tolines)==0): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1523 | from_line, to_line, found_diff = next(line_iterator) |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1524 | if from_line is not None: |
| 1525 | fromlines.append((from_line,found_diff)) |
| 1526 | if to_line is not None: |
| 1527 | tolines.append((to_line,found_diff)) |
| 1528 | # Once we have a pair, remove them from the collection and yield it |
| 1529 | from_line, fromDiff = fromlines.pop(0) |
| 1530 | to_line, to_diff = tolines.pop(0) |
| 1531 | yield (from_line,to_line,fromDiff or to_diff) |
| 1532 | |
| 1533 | # Handle case where user does not want context differencing, just yield |
| 1534 | # them up without doing anything else with them. |
| 1535 | line_pair_iterator = _line_pair_iterator() |
| 1536 | if context is None: |
| 1537 | while True: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1538 | yield next(line_pair_iterator) |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1539 | # Handle case where user wants context differencing. We must do some |
| 1540 | # storage of lines until we know for sure that they are to be yielded. |
| 1541 | else: |
| 1542 | context += 1 |
| 1543 | lines_to_write = 0 |
| 1544 | while True: |
| 1545 | # Store lines up until we find a difference, note use of a |
| 1546 | # circular queue because we only need to keep around what |
| 1547 | # we need for context. |
| 1548 | index, contextLines = 0, [None]*(context) |
| 1549 | found_diff = False |
| 1550 | while(found_diff is False): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1551 | from_line, to_line, found_diff = next(line_pair_iterator) |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1552 | i = index % context |
| 1553 | contextLines[i] = (from_line, to_line, found_diff) |
| 1554 | index += 1 |
| 1555 | # Yield lines that we have collected so far, but first yield |
| 1556 | # the user's separator. |
| 1557 | if index > context: |
| 1558 | yield None, None, None |
| 1559 | lines_to_write = context |
| 1560 | else: |
| 1561 | lines_to_write = index |
| 1562 | index = 0 |
| 1563 | while(lines_to_write): |
| 1564 | i = index % context |
| 1565 | index += 1 |
| 1566 | yield contextLines[i] |
| 1567 | lines_to_write -= 1 |
| 1568 | # Now yield the context lines after the change |
| 1569 | lines_to_write = context-1 |
| 1570 | while(lines_to_write): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1571 | from_line, to_line, found_diff = next(line_pair_iterator) |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1572 | # If another change within the context, extend the context |
| 1573 | if found_diff: |
| 1574 | lines_to_write = context-1 |
| 1575 | else: |
| 1576 | lines_to_write -= 1 |
| 1577 | yield from_line, to_line, found_diff |
| 1578 | |
| 1579 | |
| 1580 | _file_template = """ |
| 1581 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" |
| 1582 | "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| 1583 | |
| 1584 | <html> |
| 1585 | |
| 1586 | <head> |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1587 | <meta http-equiv="Content-Type" |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1588 | content="text/html; charset=ISO-8859-1" /> |
| 1589 | <title></title> |
| 1590 | <style type="text/css">%(styles)s |
| 1591 | </style> |
| 1592 | </head> |
| 1593 | |
| 1594 | <body> |
| 1595 | %(table)s%(legend)s |
| 1596 | </body> |
| 1597 | |
| 1598 | </html>""" |
| 1599 | |
| 1600 | _styles = """ |
| 1601 | table.diff {font-family:Courier; border:medium;} |
| 1602 | .diff_header {background-color:#e0e0e0} |
| 1603 | td.diff_header {text-align:right} |
| 1604 | .diff_next {background-color:#c0c0c0} |
| 1605 | .diff_add {background-color:#aaffaa} |
| 1606 | .diff_chg {background-color:#ffff77} |
| 1607 | .diff_sub {background-color:#ffaaaa}""" |
| 1608 | |
| 1609 | _table_template = """ |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1610 | <table class="diff" id="difflib_chg_%(prefix)s_top" |
| 1611 | cellspacing="0" cellpadding="0" rules="groups" > |
| 1612 | <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup> |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1613 | <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup> |
| 1614 | %(header_row)s |
| 1615 | <tbody> |
| 1616 | %(data_rows)s </tbody> |
| 1617 | </table>""" |
| 1618 | |
| 1619 | _legend = """ |
| 1620 | <table class="diff" summary="Legends"> |
| 1621 | <tr> <th colspan="2"> Legends </th> </tr> |
| 1622 | <tr> <td> <table border="" summary="Colors"> |
| 1623 | <tr><th> Colors </th> </tr> |
| 1624 | <tr><td class="diff_add"> Added </td></tr> |
| 1625 | <tr><td class="diff_chg">Changed</td> </tr> |
| 1626 | <tr><td class="diff_sub">Deleted</td> </tr> |
| 1627 | </table></td> |
| 1628 | <td> <table border="" summary="Links"> |
| 1629 | <tr><th colspan="2"> Links </th> </tr> |
| 1630 | <tr><td>(f)irst change</td> </tr> |
| 1631 | <tr><td>(n)ext change</td> </tr> |
| 1632 | <tr><td>(t)op</td> </tr> |
| 1633 | </table></td> </tr> |
| 1634 | </table>""" |
| 1635 | |
| 1636 | class HtmlDiff(object): |
| 1637 | """For producing HTML side by side comparison with change highlights. |
| 1638 | |
| 1639 | This class can be used to create an HTML table (or a complete HTML file |
Andrew M. Kuchling | 55be9ea | 2004-09-10 12:59:54 +0000 | [diff] [blame] | 1640 | containing the table) showing a side by side, line by line comparison |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1641 | of text with inter-line and intra-line change highlights. The table can |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1642 | be generated in either full or contextual difference mode. |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1643 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1644 | The following methods are provided for HTML generation: |
| 1645 | |
| 1646 | make_table -- generates HTML for a single side by side table |
| 1647 | make_file -- generates complete HTML file with a single side by side table |
| 1648 | |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1649 | See tools/scripts/diff.py for an example usage of this class. |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1650 | """ |
| 1651 | |
| 1652 | _file_template = _file_template |
| 1653 | _styles = _styles |
| 1654 | _table_template = _table_template |
| 1655 | _legend = _legend |
| 1656 | _default_prefix = 0 |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1657 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1658 | def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None, |
| 1659 | charjunk=IS_CHARACTER_JUNK): |
| 1660 | """HtmlDiff instance initializer |
| 1661 | |
| 1662 | Arguments: |
| 1663 | tabsize -- tab stop spacing, defaults to 8. |
| 1664 | wrapcolumn -- column number where lines are broken and wrapped, |
| 1665 | defaults to None where lines are not wrapped. |
| 1666 | linejunk,charjunk -- keyword arguments passed into ndiff() (used to by |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1667 | HtmlDiff() to generate the side by side HTML differences). See |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1668 | ndiff() documentation for argument default values and descriptions. |
| 1669 | """ |
| 1670 | self._tabsize = tabsize |
| 1671 | self._wrapcolumn = wrapcolumn |
| 1672 | self._linejunk = linejunk |
| 1673 | self._charjunk = charjunk |
| 1674 | |
| 1675 | def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False, |
| 1676 | numlines=5): |
| 1677 | """Returns HTML file of side by side comparison with change highlights |
| 1678 | |
| 1679 | Arguments: |
| 1680 | fromlines -- list of "from" lines |
| 1681 | tolines -- list of "to" lines |
| 1682 | fromdesc -- "from" file column header string |
| 1683 | todesc -- "to" file column header string |
| 1684 | context -- set to True for contextual differences (defaults to False |
| 1685 | which shows full differences). |
| 1686 | numlines -- number of context lines. When context is set True, |
| 1687 | controls number of lines displayed before and after the change. |
| 1688 | When context is False, controls the number of lines to place |
| 1689 | the "next" link anchors before the next change (so click of |
| 1690 | "next" link jumps to just before the change). |
| 1691 | """ |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1692 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1693 | return self._file_template % dict( |
| 1694 | styles = self._styles, |
| 1695 | legend = self._legend, |
| 1696 | table = self.make_table(fromlines,tolines,fromdesc,todesc, |
| 1697 | context=context,numlines=numlines)) |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1698 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1699 | def _tab_newline_replace(self,fromlines,tolines): |
| 1700 | """Returns from/to line lists with tabs expanded and newlines removed. |
| 1701 | |
| 1702 | Instead of tab characters being replaced by the number of spaces |
| 1703 | needed to fill in to the next tab stop, this function will fill |
| 1704 | the space with tab characters. This is done so that the difference |
| 1705 | algorithms can identify changes in a file when tabs are replaced by |
| 1706 | spaces and vice versa. At the end of the HTML generation, the tab |
| 1707 | characters will be replaced with a nonbreakable space. |
| 1708 | """ |
| 1709 | def expand_tabs(line): |
| 1710 | # hide real spaces |
| 1711 | line = line.replace(' ','\0') |
| 1712 | # expand tabs into spaces |
| 1713 | line = line.expandtabs(self._tabsize) |
| 1714 | # relace spaces from expanded tabs back into tab characters |
| 1715 | # (we'll replace them with markup after we do differencing) |
| 1716 | line = line.replace(' ','\t') |
| 1717 | return line.replace('\0',' ').rstrip('\n') |
| 1718 | fromlines = [expand_tabs(line) for line in fromlines] |
| 1719 | tolines = [expand_tabs(line) for line in tolines] |
| 1720 | return fromlines,tolines |
| 1721 | |
| 1722 | def _split_line(self,data_list,line_num,text): |
| 1723 | """Builds list of text lines by splitting text lines at wrap point |
| 1724 | |
| 1725 | This function will determine if the input text line needs to be |
| 1726 | wrapped (split) into separate lines. If so, the first wrap point |
| 1727 | will be determined and the first line appended to the output |
| 1728 | text line list. This function is used recursively to handle |
| 1729 | the second part of the split line to further split it. |
| 1730 | """ |
| 1731 | # if blank line or context separator, just add it to the output list |
| 1732 | if not line_num: |
| 1733 | data_list.append((line_num,text)) |
| 1734 | return |
| 1735 | |
| 1736 | # if line text doesn't need wrapping, just add it to the output list |
| 1737 | size = len(text) |
| 1738 | max = self._wrapcolumn |
| 1739 | if (size <= max) or ((size -(text.count('\0')*3)) <= max): |
| 1740 | data_list.append((line_num,text)) |
| 1741 | return |
| 1742 | |
| 1743 | # scan text looking for the wrap point, keeping track if the wrap |
| 1744 | # point is inside markers |
| 1745 | i = 0 |
| 1746 | n = 0 |
| 1747 | mark = '' |
| 1748 | while n < max and i < size: |
| 1749 | if text[i] == '\0': |
| 1750 | i += 1 |
| 1751 | mark = text[i] |
| 1752 | i += 1 |
| 1753 | elif text[i] == '\1': |
| 1754 | i += 1 |
| 1755 | mark = '' |
| 1756 | else: |
| 1757 | i += 1 |
| 1758 | n += 1 |
| 1759 | |
| 1760 | # wrap point is inside text, break it up into separate lines |
| 1761 | line1 = text[:i] |
| 1762 | line2 = text[i:] |
| 1763 | |
| 1764 | # if wrap point is inside markers, place end marker at end of first |
| 1765 | # line and start marker at beginning of second line because each |
| 1766 | # line will have its own table tag markup around it. |
| 1767 | if mark: |
| 1768 | line1 = line1 + '\1' |
| 1769 | line2 = '\0' + mark + line2 |
| 1770 | |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1771 | # tack on first line onto the output list |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1772 | data_list.append((line_num,line1)) |
| 1773 | |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1774 | # use this routine again to wrap the remaining text |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1775 | self._split_line(data_list,'>',line2) |
| 1776 | |
| 1777 | def _line_wrapper(self,diffs): |
| 1778 | """Returns iterator that splits (wraps) mdiff text lines""" |
| 1779 | |
| 1780 | # pull from/to data and flags from mdiff iterator |
| 1781 | for fromdata,todata,flag in diffs: |
| 1782 | # check for context separators and pass them through |
| 1783 | if flag is None: |
| 1784 | yield fromdata,todata,flag |
| 1785 | continue |
| 1786 | (fromline,fromtext),(toline,totext) = fromdata,todata |
| 1787 | # for each from/to line split it at the wrap column to form |
| 1788 | # list of text lines. |
| 1789 | fromlist,tolist = [],[] |
| 1790 | self._split_line(fromlist,fromline,fromtext) |
| 1791 | self._split_line(tolist,toline,totext) |
| 1792 | # yield from/to line in pairs inserting blank lines as |
| 1793 | # necessary when one side has more wrapped lines |
| 1794 | while fromlist or tolist: |
| 1795 | if fromlist: |
| 1796 | fromdata = fromlist.pop(0) |
| 1797 | else: |
| 1798 | fromdata = ('',' ') |
| 1799 | if tolist: |
| 1800 | todata = tolist.pop(0) |
| 1801 | else: |
| 1802 | todata = ('',' ') |
| 1803 | yield fromdata,todata,flag |
| 1804 | |
| 1805 | def _collect_lines(self,diffs): |
| 1806 | """Collects mdiff output into separate lists |
| 1807 | |
| 1808 | Before storing the mdiff from/to data into a list, it is converted |
| 1809 | into a single line of text with HTML markup. |
| 1810 | """ |
| 1811 | |
| 1812 | fromlist,tolist,flaglist = [],[],[] |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1813 | # pull from/to data and flags from mdiff style iterator |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1814 | for fromdata,todata,flag in diffs: |
| 1815 | try: |
| 1816 | # store HTML markup of the lines into the lists |
| 1817 | fromlist.append(self._format_line(0,flag,*fromdata)) |
| 1818 | tolist.append(self._format_line(1,flag,*todata)) |
| 1819 | except TypeError: |
| 1820 | # exceptions occur for lines where context separators go |
| 1821 | fromlist.append(None) |
| 1822 | tolist.append(None) |
| 1823 | flaglist.append(flag) |
| 1824 | return fromlist,tolist,flaglist |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1825 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1826 | def _format_line(self,side,flag,linenum,text): |
| 1827 | """Returns HTML markup of "from" / "to" text lines |
| 1828 | |
| 1829 | side -- 0 or 1 indicating "from" or "to" text |
| 1830 | flag -- indicates if difference on line |
| 1831 | linenum -- line number (used for line number column) |
| 1832 | text -- line text to be marked up |
| 1833 | """ |
| 1834 | try: |
| 1835 | linenum = '%d' % linenum |
| 1836 | id = ' id="%s%s"' % (self._prefix[side],linenum) |
| 1837 | except TypeError: |
| 1838 | # handle blank lines where linenum is '>' or '' |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1839 | id = '' |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1840 | # replace those things that would get confused with HTML symbols |
| 1841 | text=text.replace("&","&").replace(">",">").replace("<","<") |
| 1842 | |
| 1843 | # make space non-breakable so they don't get compressed or line wrapped |
| 1844 | text = text.replace(' ',' ').rstrip() |
| 1845 | |
| 1846 | return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \ |
| 1847 | % (id,linenum,text) |
| 1848 | |
| 1849 | def _make_prefix(self): |
| 1850 | """Create unique anchor prefixes""" |
| 1851 | |
| 1852 | # Generate a unique anchor prefix so multiple tables |
| 1853 | # can exist on the same HTML page without conflicts. |
| 1854 | fromprefix = "from%d_" % HtmlDiff._default_prefix |
| 1855 | toprefix = "to%d_" % HtmlDiff._default_prefix |
| 1856 | HtmlDiff._default_prefix += 1 |
| 1857 | # store prefixes so line format method has access |
| 1858 | self._prefix = [fromprefix,toprefix] |
| 1859 | |
| 1860 | def _convert_flags(self,fromlist,tolist,flaglist,context,numlines): |
| 1861 | """Makes list of "next" links""" |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1862 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1863 | # all anchor names will be generated using the unique "to" prefix |
| 1864 | toprefix = self._prefix[1] |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1865 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1866 | # process change flags, generating middle column of next anchors/links |
| 1867 | next_id = ['']*len(flaglist) |
| 1868 | next_href = ['']*len(flaglist) |
| 1869 | num_chg, in_change = 0, False |
| 1870 | last = 0 |
| 1871 | for i,flag in enumerate(flaglist): |
| 1872 | if flag: |
| 1873 | if not in_change: |
| 1874 | in_change = True |
| 1875 | last = i |
| 1876 | # at the beginning of a change, drop an anchor a few lines |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1877 | # (the context lines) before the change for the previous |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1878 | # link |
| 1879 | i = max([0,i-numlines]) |
| 1880 | next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg) |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1881 | # at the beginning of a change, drop a link to the next |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1882 | # change |
| 1883 | num_chg += 1 |
| 1884 | next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % ( |
| 1885 | toprefix,num_chg) |
| 1886 | else: |
| 1887 | in_change = False |
| 1888 | # check for cases where there is no content to avoid exceptions |
| 1889 | if not flaglist: |
| 1890 | flaglist = [False] |
| 1891 | next_id = [''] |
| 1892 | next_href = [''] |
| 1893 | last = 0 |
| 1894 | if context: |
| 1895 | fromlist = ['<td></td><td> No Differences Found </td>'] |
| 1896 | tolist = fromlist |
| 1897 | else: |
| 1898 | fromlist = tolist = ['<td></td><td> Empty File </td>'] |
| 1899 | # if not a change on first line, drop a link |
| 1900 | if not flaglist[0]: |
| 1901 | next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix |
| 1902 | # redo the last link to link to the top |
| 1903 | next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix) |
| 1904 | |
| 1905 | return fromlist,tolist,flaglist,next_href,next_id |
| 1906 | |
| 1907 | def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False, |
| 1908 | numlines=5): |
| 1909 | """Returns HTML table of side by side comparison with change highlights |
| 1910 | |
| 1911 | Arguments: |
| 1912 | fromlines -- list of "from" lines |
| 1913 | tolines -- list of "to" lines |
| 1914 | fromdesc -- "from" file column header string |
| 1915 | todesc -- "to" file column header string |
| 1916 | context -- set to True for contextual differences (defaults to False |
| 1917 | which shows full differences). |
| 1918 | numlines -- number of context lines. When context is set True, |
| 1919 | controls number of lines displayed before and after the change. |
| 1920 | When context is False, controls the number of lines to place |
| 1921 | the "next" link anchors before the next change (so click of |
| 1922 | "next" link jumps to just before the change). |
| 1923 | """ |
| 1924 | |
| 1925 | # make unique anchor prefixes so that multiple tables may exist |
| 1926 | # on the same page without conflict. |
| 1927 | self._make_prefix() |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1928 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1929 | # change tabs to spaces before it gets more difficult after we insert |
| 1930 | # markkup |
| 1931 | fromlines,tolines = self._tab_newline_replace(fromlines,tolines) |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1932 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1933 | # create diffs iterator which generates side by side from/to data |
| 1934 | if context: |
| 1935 | context_lines = numlines |
| 1936 | else: |
| 1937 | context_lines = None |
| 1938 | diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk, |
| 1939 | charjunk=self._charjunk) |
| 1940 | |
| 1941 | # set up iterator to wrap lines that exceed desired width |
| 1942 | if self._wrapcolumn: |
| 1943 | diffs = self._line_wrapper(diffs) |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1944 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1945 | # collect up from/to lines and flags into lists (also format the lines) |
| 1946 | fromlist,tolist,flaglist = self._collect_lines(diffs) |
| 1947 | |
| 1948 | # process change flags, generating middle column of next anchors/links |
| 1949 | fromlist,tolist,flaglist,next_href,next_id = self._convert_flags( |
| 1950 | fromlist,tolist,flaglist,context,numlines) |
| 1951 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1952 | s = [] |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1953 | fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \ |
| 1954 | '<td class="diff_next">%s</td>%s</tr>\n' |
| 1955 | for i in range(len(flaglist)): |
| 1956 | if flaglist[i] is None: |
| 1957 | # mdiff yields None on separator lines skip the bogus ones |
| 1958 | # generated for the first line |
| 1959 | if i > 0: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1960 | s.append(' </tbody> \n <tbody>\n') |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1961 | else: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1962 | s.append( fmt % (next_id[i],next_href[i],fromlist[i], |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1963 | next_href[i],tolist[i])) |
| 1964 | if fromdesc or todesc: |
| 1965 | header_row = '<thead><tr>%s%s%s%s</tr></thead>' % ( |
| 1966 | '<th class="diff_next"><br /></th>', |
| 1967 | '<th colspan="2" class="diff_header">%s</th>' % fromdesc, |
| 1968 | '<th class="diff_next"><br /></th>', |
| 1969 | '<th colspan="2" class="diff_header">%s</th>' % todesc) |
| 1970 | else: |
| 1971 | header_row = '' |
| 1972 | |
| 1973 | table = self._table_template % dict( |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1974 | data_rows=''.join(s), |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1975 | header_row=header_row, |
| 1976 | prefix=self._prefix[1]) |
| 1977 | |
| 1978 | return table.replace('\0+','<span class="diff_add">'). \ |
| 1979 | replace('\0-','<span class="diff_sub">'). \ |
| 1980 | replace('\0^','<span class="diff_chg">'). \ |
| 1981 | replace('\1','</span>'). \ |
| 1982 | replace('\t',' ') |
Tim Peters | 48bd7f3 | 2004-08-29 22:38:38 +0000 | [diff] [blame] | 1983 | |
Martin v. Löwis | e064b41 | 2004-08-29 16:34:40 +0000 | [diff] [blame] | 1984 | del re |
| 1985 | |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1986 | def restore(delta, which): |
| 1987 | r""" |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1988 | Generate one of the two sequences that generated a delta. |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 1989 | |
| 1990 | Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract |
| 1991 | lines originating from file 1 or 2 (parameter `which`), stripping off line |
| 1992 | prefixes. |
| 1993 | |
| 1994 | Examples: |
| 1995 | |
| 1996 | >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), |
| 1997 | ... 'ore\ntree\nemu\n'.splitlines(1)) |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 1998 | >>> diff = list(diff) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1999 | >>> print(''.join(restore(diff, 1)), end="") |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 2000 | one |
| 2001 | two |
| 2002 | three |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 2003 | >>> print(''.join(restore(diff, 2)), end="") |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 2004 | ore |
| 2005 | tree |
| 2006 | emu |
| 2007 | """ |
| 2008 | try: |
| 2009 | tag = {1: "- ", 2: "+ "}[int(which)] |
| 2010 | except KeyError: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 2011 | raise ValueError('unknown delta choice (must be 1 or 2): %r' |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 2012 | % which) |
| 2013 | prefixes = (" ", tag) |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 2014 | for line in delta: |
| 2015 | if line[:2] in prefixes: |
Tim Peters | 8a9c284 | 2001-09-22 21:30:22 +0000 | [diff] [blame] | 2016 | yield line[2:] |
Tim Peters | 5e824c3 | 2001-08-12 22:25:01 +0000 | [diff] [blame] | 2017 | |
Tim Peters | 9ae2148 | 2001-02-10 08:00:53 +0000 | [diff] [blame] | 2018 | def _test(): |
| 2019 | import doctest, difflib |
| 2020 | return doctest.testmod(difflib) |
| 2021 | |
| 2022 | if __name__ == "__main__": |
| 2023 | _test() |