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