home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / difflib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-04-29  |  59.4 KB  |  1,782 lines

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