This file is indexed.

/usr/bin/termdiff is in xxdiff-scripts 1:4.0.1+hg487+dfsg-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
#!/usr/bin/python
"""File comparison and merge tool.

This is a single file, curses-based version of xxdiff in Python. I, the author
of xxdiff, am now working almost exclusively on remote machines using tmux,
bash, emacs, and I need my nice file comparison and merge tool to work in a
console-only environment. Nothing decent was available as of 2013-05-04, so I
decided to rewrite xxdiff in curses.

  Note: I will eventually rewrite this in Emacs-LISP, as a better version of ediff
  (which is unfortunately insufficient, even with efforts configuring it), but
  dumping Emacs is not functional anymore (it dumps core on Linux), so startup
  time will probably be an issue, so there is still value in having a visual
  diff renderer / simple merge without editing available like this.

"""
__author__ = 'Martin Blais <blais@furius.ca>'
__copyright__ = 'GNU GPL v3'

import curses
import collections
import itertools
import difflib
import os
from os import path
import re
import shutil
import subprocess
import sys
import tempfile
import StringIO


# Kinds of changes                     [2-way] [3-way]
LINE_SAME        = 'LINE_SAME       ' # (AA)    (AAA)
LINE_DIFF_1      = 'LINE_DIFF_1     ' #         (BAA)
LINE_DIFF_2      = 'LINE_DIFF_2     ' #         (ABA)
LINE_DIFF_3      = 'LINE_DIFF_3     ' #         (AAB)
LINE_DELETE_1    = 'LINE_DELETE_1   ' #         (-AA)
LINE_DELETE_2    = 'LINE_DELETE_2   ' #         (A-A)
LINE_DELETE_3    = 'LINE_DELETE_3   ' #         (AA-)
LINE_INSERT_1    = 'LINE_INSERT_1   ' # (A-)    (A--)
LINE_INSERT_2    = 'LINE_INSERT_2   ' # (-A)    (-A-)
LINE_INSERT_3    = 'LINE_INSERT_3   ' #         (--A)
LINE_DIFF_ALL    = 'LINE_DIFF_ALL   ' # (AB)    (ABC)
LINE_DIFFDEL_1   = 'LINE_DIFFDEL_1  ' #         (-AB)
LINE_DIFFDEL_2   = 'LINE_DIFFDEL_2  ' #         (A-B)
LINE_DIFFDEL_3   = 'LINE_DIFFDEL_3  ' #         (AB-)
LINE_DIRECTORIES = 'LINE_DIRECTORIES' #

# Type of selection of each line.
SEL_SEL1       = object()
SEL_SEL2       = object()
SEL_SEL3       = object()
SEL_UNSELECTED = object()
SEL_NEITHER    = object()


# Left, Middle, Right
L, R, M = 0, 1, 2


class Hunk(object):
  """A diff hunk, including regions which are the same."""
  def __init__(self, hunk_type):
    self.hunk_type = hunk_type
    # Begin and end line numbers for each file.
    self.linesL = None
    self.linesR = None
    self.linesM = None

  def __str__(self):
    return 'Hunk({}, {}, {}, {})'.format(self.hunk_type,
                                         self.linesL, self.linesM, self.linesR)


class Matcher(object):
  """A convenience class that store the result of the last match operation.
  This is used to create cascading elif conditions on regexps."""
  def __call__(self, *args, **kw):
    self.mo = re.match(*args, **kw)
    return self.mo


def line_pair((line1, line2)):
  line1 = int(line1)
  if line2 is None:
    line2 = line1 + 1
  else:
    line2 = int(line2) + 1
  return (line1, line2)

def parse_diff2_line(line):
  """Parse a single line of diff's output. This is standardized, to some extent,
  and there are many kinds of diff tools that will output compatible lists of
  changes."""

  line_type = None
  hunk = None
  matcher = Matcher()

  c = line[0]
  if c in '<>-':
    pass

  elif matcher(r'(\d+)(?:,(\d+))?c(\d+)(?:,(\d+))?', line):
    f1n1, f1n2 = line_pair(matcher.mo.group(1,2))
    f2n1, f2n2 = line_pair(matcher.mo.group(3,4))
    line_type = LINE_DIFF_ALL

  elif matcher(r'(\d+)(?:,(\d+))?d(\d+)', line):
    f1n1, f1n2 = line_pair(matcher.mo.group(1,2))
    f2n1 = f2n2 = int(matcher.mo.group(3)) + 1
    line_type = LINE_INSERT_1

  elif matcher(r'(\d+)a(\d+)(?:,(\d+))?', line):
    f1n1 = f1n2 = int(matcher.mo.group(1)) + 1
    f2n1, f2n2 = line_pair(matcher.mo.group(2,3))
    line_type = LINE_INSERT_2

  elif matcher(r'\ No newline at end of file', line):
    f1n1 = f1n2 = f2n1 = f2n2 = None
    line_type = LINE_DIRECTORIES

  if line_type is not None:
    hunk = Hunk(line_type)
    hunk.linesL = (f1n1, f1n2)
    hunk.linesR = (f2n1, f2n2)

  return hunk


def parse_diff2(command, filename1, filename2):
  """Parse a two-way diff."""
  p = subprocess.Popen(command + [filename1, filename2],
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  out, err = p.communicate()
  hunks = []
  for line in out.splitlines():
    hunk = parse_diff2_line(line)
    if hunk is not None:
      hunks.append(hunk)
  return hunks


def parse_diff3(command, filename1, filename2, filename3):
  """Parse a single line of diff3's output. 'f' is a file object."""
  p = subprocess.Popen(command + [filename1, filename2, filename3],
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  out, err = p.communicate()

  matcher = Matcher()
  hunks = []

  FILE_MAP = {'1': L, '2': M, '3': R}

  head_line, lines = None, {}
  for line in out.splitlines():
    if matcher('====(\d+)?', line):
      hline = matcher.mo.group(1)
      head_line = int(hline) if hline else None

    elif matcher('([123]):(\d+)(?:,(\d+))?([ac])', line):
      fileno = FILE_MAP[matcher.mo.group(1)]
      assert fileno not in lines

      beg = int(matcher.mo.group(2))
      if matcher.mo.group(4) == 'a':
        beg += 1

      end = (int(matcher.mo.group(3)) + 1) if matcher.mo.group(3) else beg

      lines[fileno] = (beg, end, matcher.mo.group(4))

      if len(lines) == 3:
        signature = (head_line, lines[L][2], lines[M][2], lines[R][2])
        line_type = DIFF3_MAP[signature]
        hunk = Hunk(line_type)
        hunk.linesL = lines[L][:2]
        hunk.linesM = lines[M][:2]
        hunk.linesR = lines[R][:2]
        hunks.append(hunk)
        head_line, lines = None, {}

  return hunks


DIFF3_MAP = {
  (1, 'c', 'c', 'c')    : LINE_DIFF_1,
  (2, 'c', 'c', 'c')    : LINE_DIFF_2,
  (3, 'c', 'c', 'c')    : LINE_DIFF_3,
  (1, 'a', 'c', 'c')    : LINE_DELETE_1,
  (2, 'c', 'a', 'c')    : LINE_DELETE_2,
  (3, 'c', 'c', 'a')    : LINE_DELETE_3,
  (1, 'c', 'a', 'a')    : LINE_INSERT_1,
  (2, 'a', 'c', 'a')    : LINE_INSERT_2,
  (3, 'a', 'a', 'c')    : LINE_INSERT_3,
  (None, 'c', 'c', 'c') : LINE_DIFF_ALL,
  (None, 'a', 'c', 'c') : LINE_DIFFDEL_1,
  (None, 'c', 'a', 'c') : LINE_DIFFDEL_2,
  (None, 'c', 'c', 'a') : LINE_DIFFDEL_3,
}


class FileWithNo(object):
  "A file object wrapper that tracks its line number, 1-based."

  def __init__(self, f):
    self.lineno = 1
    self.f = f
    self.name = self.f.name

  def __str__(self):
    return 'FileWithNo({}, lineno={})'.format(self.f.name, self.lineno)
  __repr__ = __str__

  def readline(self):
    lineno = self.lineno
    self.lineno += 1
    return (lineno, self.f.readline()[:-1])


class TruncLineWriter(object):
  "Writes to a file up to the given number of characters."

  def __init__(self, f, width):
    self.f = f
    self.width = width
    self.c = 0

  def write_text(self, text):
    remaining = self.width - self.c
    if remaining <= 0:
      return
    if len(text) < remaining:
      self.f.write(text)
      self.c += len(text)
    else:
      self.f.write(text[:remaining])
      self.c = self.width

  def complete(self, char):
    "Pad the end of the line with blanks, up to width, if necessary."
    remaining = self.width - self.c
    if remaining > 0:
      self.f.write(char * remaining)


def render_line(f, line, color, width, hd=None):
  """Render a single file's line in the given terminal color, fitting exactly in
  the specifed width."""
  wr = TruncLineWriter(f, width)
  f.write(color)
  if line:
    line = line.rstrip('\n\r')
    if hd is None:
      wr.write_text(line)
    else:
      ipre, isfx = hd
      wr.write_text(line[:ipre])
      f.write(COLOR_HIGHLIGHT[color])
      wr.write_text(line[ipre:isfx])
      f.write(color)
      wr.write_text(line[isfx:])
    wr.complete(' ')
  else:
    f.write(COLOR_BLANK)
    wr.complete(opts.blank_char)

  f.write(COLOR_BASE)


COLORS = [
    ('COLOR_BASE'                 ,   0, 7),
    ('COLOR_SAME'                 , 250, 0),
    ('COLOR_SAME_OTHER'           , 153, 0),
    ('COLOR_SAME_OTHER_HIGHLIGHT' , 110, 0),
    ('COLOR_INSERT'               , 157, 0),
    ('COLOR_DELETE'               , 157, 0),
    ('COLOR_CHANGE'               , 229, 0),
    ('COLOR_CHANGE_HIGHLIGHT'     , 226, 0),
    ('COLOR_BLANK'                , 245, 0),
    ('COLOR_TITLE'                , 19 , 15),
    ]


def init_colors():
  for color_name, color_id_bg, color_id_fg in COLORS:
    if (curses.tigetstr('setab') is None or
        curses.tigetstr('setaf') is None):
      raise SystemExit("Terminal does not support colors.")

    globals()[color_name] = (curses.tparm(curses.tigetstr('setab'), color_id_bg) +
                             curses.tparm(curses.tigetstr('setaf'), color_id_fg))


  global HUNK_COLORS_2
  HUNK_COLORS_2 = {
    LINE_SAME        : (COLOR_SAME   , COLOR_SAME)   ,
    LINE_DIFF_ALL    : (COLOR_CHANGE , COLOR_CHANGE) ,
    LINE_INSERT_1    : (COLOR_INSERT , COLOR_BLANK)  ,
    LINE_INSERT_2    : (COLOR_BLANK  , COLOR_DELETE) ,
    }

  global HUNK_COLORS_3
  HUNK_COLORS_3 = {
    LINE_SAME        : (COLOR_SAME       , COLOR_SAME       , COLOR_SAME)       ,
    LINE_DIFF_1      : (COLOR_CHANGE     , COLOR_SAME_OTHER , COLOR_SAME_OTHER) ,
    LINE_DIFF_2      : (COLOR_SAME_OTHER , COLOR_CHANGE     , COLOR_SAME_OTHER) ,
    LINE_DIFF_3      : (COLOR_SAME_OTHER , COLOR_SAME_OTHER , COLOR_CHANGE)     ,
    LINE_DELETE_1    : (COLOR_BLANK      , COLOR_SAME_OTHER , COLOR_SAME_OTHER) ,
    LINE_DELETE_2    : (COLOR_SAME_OTHER , COLOR_BLANK      , COLOR_SAME_OTHER) ,
    LINE_DELETE_3    : (COLOR_SAME_OTHER , COLOR_SAME_OTHER , COLOR_BLANK)      ,
    LINE_INSERT_1    : (COLOR_INSERT     , COLOR_BLANK      , COLOR_BLANK)      ,
    LINE_INSERT_2    : (COLOR_BLANK      , COLOR_INSERT     , COLOR_BLANK)      ,
    LINE_INSERT_3    : (COLOR_BLANK      , COLOR_BLANK      , COLOR_INSERT)     ,
    LINE_DIFF_ALL    : (COLOR_CHANGE     , COLOR_CHANGE     , COLOR_CHANGE)     ,
    LINE_DIFFDEL_1   : (COLOR_BLANK      , COLOR_CHANGE     , COLOR_CHANGE)     ,
    LINE_DIFFDEL_2   : (COLOR_CHANGE     , COLOR_BLANK      , COLOR_CHANGE)     ,
    LINE_DIFFDEL_3   : (COLOR_CHANGE     , COLOR_CHANGE     , COLOR_BLANK)      ,
    }

  global COLOR_HIGHLIGHT
  COLOR_HIGHLIGHT = {
      COLOR_SAME_OTHER: COLOR_SAME_OTHER_HIGHLIGHT,
      COLOR_CHANGE:  COLOR_CHANGE_HIGHLIGHT,
      }


def render_same_region(files):
  """Given a mapping of files, render a same-region, that is, a region between
  hunks whose text should match."""


def compute_horizontal_prefix(lines):
  """Return the first character that differs between the given lines."""
  for i in xrange(min(map(len, lines))):
    c = lines[0][i]
    for oline in lines[1:]:
      if oline[i] != c:
        return i

def compute_horizontal_suffix(lines):
  """Return the last character from the back that differs between the given
  lines."""
  for i in xrange(min(map(len, lines))):
    c = lines[0][-i]
    for oline in lines[1:]:
      if oline[-i] != c:
        return i
  return 0

def compute_horizontal_diffs(lines):
  """Compute the horizontal diffs of the lines that have content.
  'lines' is a dict of side (L, R, M) to lines. Lines without
  content have indexes returned as None."""

  # Linearize order or items.
  items = lines.items()

  # The result, initialized.
  indices = dict((side, None) for side in lines.iterkeys())

  # Operate on the valid lines only.
  valid_lines = [line for (side, line) in items if line]
  if len(valid_lines) < 2:
    return indices

  # Compute prefix and suffix (this is a simpler algorithm than xxdiff).
  ipre = compute_horizontal_prefix(valid_lines)
  isfx = compute_horizontal_suffix(valid_lines)

  # Fill in the computed results.
  trim = 0
  for (side, line) in items:
    if line:
      if len(line)-isfx < ipre:
        trim = max(trim, ipre - (len(line)-isfx))
  isfx -= trim

  for (side, line) in items:
    if line:
      assert len(line)-isfx >= ipre
      indices[side] = (ipre, len(line)-isfx)
  return indices






Line = collections.namedtuple('Line', 'no text color hordiff hunk')

def prerender_lines(filenames, hunks):
  """Pre-render the lines to be rendered.
  This routine reads all the file lines, processes the hunks and
  returns a dict of L,R or L,M,R -> list of line tuples for each
  file.
  """

  # Create a dict of line-lists to return.
  lines = dict((k, []) for k in filenames.iterkeys())

  # Create file wrappers for each of the files. They will be processed by
  # reading the exactly once.
  files = dict((k, FileWithNo(open(v))) for (k, v) in filenames.iteritems())
  nfiles = len(filenames)

  for hunk in hunks:
    # Check sizes
    sizeL = hunk.linesL[0] - files[L].lineno
    sizeR = hunk.linesR[0] - files[R].lineno
    assert sizeL == sizeR, (str(hunk), files)
    if nfiles == 3:
      sizeM = hunk.linesM[0] - files[M].lineno
      assert sizeM == sizeL, (hunk, files)

    # Render same lines.
    while files[L].lineno < hunk.linesL[0]:
      noL, lineL = files[L].readline()
      noR, lineR = files[R].readline()
      if nfiles != 2:
        noM, lineM = files[M].readline()

      if nfiles == 2:
        colL, colR = HUNK_COLORS_2[LINE_SAME]
        lines[L].append(Line(noL, lineL, colL, None, None))
        lines[R].append(Line(noR, lineR, colR, None, None))
      else:
        colL, colM, colR = HUNK_COLORS_3[LINE_SAME]
        lines[L].append(Line(noL, lineL, colL, None, None))
        lines[M].append(Line(noM, lineM, colM, None, None))
        lines[R].append(Line(noR, lineR, colR, None, None))

    # Render diff hunk.
    while 1:
      didread = False
      lineL = lineR = lineM = None
      if files[L].lineno < hunk.linesL[1]:
        noL, lineL = files[L].readline()
        didread = True

      if files[R].lineno < hunk.linesR[1]:
        noR, lineR = files[R].readline()
        didread = True

      if nfiles == 3 and files[M].lineno < hunk.linesM[1]:
        noM, lineM = files[M].readline()
        didread = True

      if not didread:
        break

      if nfiles == 2:
        hd = compute_horizontal_diffs({L: lineL, R: lineR})
        colL, colR = HUNK_COLORS_2[hunk.hunk_type]

        lines[L].append(Line(noL, lineL, colL, hunk, hd[L]))
        lines[R].append(Line(noR, lineR, colR, hunk, hd[R]))
      else:
        hd = compute_horizontal_diffs({L: lineL, R: lineR, M: lineM})
        colL, colM, colR = HUNK_COLORS_3[hunk.hunk_type]
        lines[L].append(Line(noL, lineL, colL, hunk, hd[L]))
        lines[M].append(Line(noM, lineM, colM, hunk, hd[M]))
        lines[R].append(Line(noR, lineR, colR, hunk, hd[R]))

  # Render the same region at the end of the file.
  while 1:
    noL, lineL = files[L].readline()
    noR, lineR = files[R].readline()
    if nfiles != 2:
      noM, lineM = files[M].readline()

    if not lineL and not lineR and (nfiles == 2 or not lineM):
      break

    if nfiles == 2:
      colL, colR = HUNK_COLORS_2[LINE_SAME]
      lines[L].append(Line(noL, lineL, colL, None, None))
      lines[R].append(Line(noR, lineR, colR, None, None))
    else:
      colL, colM, colR = HUNK_COLORS_3[LINE_SAME]
      lines[L].append(Line(noL, lineL, colL, None, None))
      lines[M].append(Line(noM, lineM, colM, None, None))
      lines[R].append(Line(noR, lineR, colR, None, None))

  return lines


def main():
  import argparse, logging
  logging.basicConfig(level=logging.INFO, format='%(levelname)-8s: %(message)s')
  parser = argparse.ArgumentParser(__doc__.strip())

  parser.add_argument('filenames', nargs='+',
                      help='Filenames')

  parser.add_argument('--cat', action='store_true',
                      help="Cat the output without a pager nor using curses.")

  parser.add_argument('--less', action='store_true',
                      help=("Equivalent to --pager='less -r'."))

  parser.add_argument('-P', '--pager', action='store',
                      help=("Cat the output into $PAGER. "
                            "Use --cat to just cat it out."))

  parser.add_argument('--prog-diff2', '--prog-diff', action='store',
                      default='diff',
                      help="Executable to call for two-day diffs.")
  parser.add_argument('--prog-diff3', action='store', default='diff3',
                      help="Executable to call for three-day diffs.")

  parser.add_argument('--blank-char', action='store', default=' ',
                      help="Blank character to use for filler.")

  group = parser.add_argument_group("Options forwarded to GNU diff")
  forwarded_options = [
      ('-i', '--ignore-case'),
      ('-E', '--ignore-tab-expansion'),
      ('-w', '--ignore-all-space'),
      ('-b', '--ignore-space-change'),
      ('-B', '--ignore-blank-lines'),
      ]
  for short, long in forwarded_options:
      group.add_argument(short, long, action='store_true')

  global opts; opts = parser.parse_args()

  if opts.cat:
    opts.pager = '-'
    del opts.cat
  elif opts.less:
    opts.pager = 'less -r'
    del opts.less

  nfiles = len(opts.filenames)

  # Determine whether this will be a directory diff or a file diff.
  # The invocation is a file diff if at least one of the files is a non-directory.
  # In this case, the file's basename is appended to all of the other directories
  # (This is just like for xxdiff.)
  isdirdiff = all(path.isdir(x) for x in opts.filenames)
  if isdirdiff:
    # FIXME: TODO, continue here
    pass ##print difflib ...

  else:
    # If any of the files is from stdin, we need to place a copy under a temp
    # file, unforunately, because we use an external tool to compute the actual
    # diffs, so the tool needs to read it, and then we do too.
    tempfiles = []
    for i, filename in enumerate(opts.filenames):
      if filename == '-':
        tf = tempfile.NamedTemporaryFile(prefix='termdiff')
        shutil.copyfileobj(sys.stdin, tf)
        tf.flush()
        opts.filenames[i] = tf.name
        tempfiles.append(tf)

    # Run an external diff and gather its output.
    # By default this works well with GNU diff and diff3, but other diffs should
    # work too (e.g. cleardiff) and you could write your own custom diff wrapper
    # as well.
    if nfiles == 2:
      command = [opts.prog_diff2]
      for short, long in forwarded_options:
        if getattr(opts, long[2:].replace('-', '_')):
          command.append(long)

      hunks = parse_diff2(command, *opts.filenames)
      filenames = {L: opts.filenames[0],
                   R: opts.filenames[1]}

    elif nfiles == 3:
      command = [opts.prog_diff3]
      hunks = parse_diff3(command, *opts.filenames)
      filenames = {L: opts.filenames[0],
                   M: opts.filenames[1],
                   R: opts.filenames[2]}

    else:
      parser.error("Invalid number of files: should be 2 or 3")

    # Pre-process the lines to be aligned and ready for on-screen rendering.
    lines = prerender_lines(filenames, hunks)

    if opts.pager:
      render_with_cat(filenames, lines, opts.pager)
    else:
      curses.wrapper(render_with_curses, filenames, lines)


#--------------------------------------------------------------------------------

def render_with_cat(filenames, lines, pager):
  """Render all the file as piped into a pager, no curses, simple."""

  # Get the terminal's width and compute how many characters we'll be able to
  # display.
  nfiles = len(filenames)
  width = (curses.tigetnum('cols') - ((nfiles-1) * len(SEPARATOR))) / nfiles

  if pager != '-':
    # Pipe into 'less'.
    p = subprocess.Popen((pager,), shell=True, stdin=subprocess.PIPE)

    sio = StringIO.StringIO()
    render_diffs(filenames, lines, p.stdin, width)
    p.communicate(sio.getvalue())
  else:
    # Write straight to the terminal.
    render_diffs(filenames, lines, sys.stdout, width)


SEPARATOR = '|'


def render_diffs(filenames, lines, outf, width):
  """Render the diffs from the given filenames and hunks, to file object 'outf',
  and constrained by 'width' characters."""

  nfiles = len(lines)

  # Render the filenames as a title at the top.
  render_line(outf, format_filename(filenames[L], width), COLOR_TITLE, width)
  outf.write(SEPARATOR)
  if nfiles == 3:
    render_line(outf, format_filename(filenames[M], width), COLOR_TITLE, width)
    outf.write(SEPARATOR)
  render_line(outf, format_filename(filenames[R], width), COLOR_TITLE, width)
  outf.write('\n')

  if nfiles == 2:
    for lineL, lineR in itertools.izip(lines[L], lines[R]):
      render_line(outf, lineL.text, lineL.color, width)
      outf.write(SEPARATOR)
      render_line(outf, lineR.text, lineR.color, width)
      outf.write('\n')
  elif nfiles == 3:
    for lineL, lineM, lineR in itertools.izip(lines[L], lines[M], lines[R]):
      render_line(outf, lineL.text, lineL.color, width)
      outf.write(SEPARATOR)
      render_line(outf, lineM.text, lineM.color, width)
      outf.write(SEPARATOR)
      render_line(outf, lineR.text, lineR.color, width)
      outf.write('\n')
  else:
    raise NotImplementedError("Invalid number of files.")


def format_filename(filename, width):
  """Format a filename for printability."""
  if len(filename) > width:
    return '...{}'.format(filename[-(width-3):])
  else:
    return filename


#--------------------------------------------------------------------------------

def render_with_curses(window, filenames, lines):
  """Render the output as a curses app."""


  ### window.stripspaces = False rem
  ##  if curses.tigetflag('bce'):



  nfiles = len(filenames)
  top_line = 0 ## FIXME: whatever
  height, width = window.getmaxyx()
  width2 = width / 2 - 1

  # outf = StringIO.StringIO()
  # render_diffs(files, hunks, outf, width)
  # lines = outf.getvalue().splitlines()

  curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_WHITE)

  while True:
    for screen_line in xrange(0, height-2):
      line = top_line + screen_line

      if nfiles == 2:
        lineL = lines[L][line]
        lineR = lines[R][line]
        out = '{: <{:d}}{}{: <{:d}}'.format(
          lineL.text if lineL.text else '',
          width2, SEPARATOR,
          lineR.text if lineR.text else '',
          width2)
        #render_line(outf, lineL.text, lineL.color, width)
        ## outf.write('{:{:d}}'.format(lineR.text, width/2))
        #render_line(outf, lineR.text, lineR.color, width)
      else:
        assert False
        # lineL = lines[L][line]
        # lineM = lines[M][line]
        # lineR = lines[R][line]
        # render_line(outf, lineL.text, lineL.color, width)
        # outf.write(SEPARATOR)
        # render_line(outf, lineM.text, lineM.color, width)
        # outf.write(SEPARATOR)
        # render_line(outf, lineR.text, lineR.color, width)

      window.addstr(screen_line, 0, out, curses.color_pair(1))
      # for x in xrange(0, len(out)):
      #   window.addch(screen_line, x, out[x], curses.color_pair(1))


    ##window.refresh()
    input = window.getch()
    top_line += 1






# FIXME: See hgview-curses source code for a great example!


# See bce problem here: http://invisible-island.net/ncurses/ncurses.faq.html
# nsterm works, xterm-color works



if __name__ == '__main__':
  curses.setupterm()
  init_colors()
  try:
    main()
  finally:
    # Make sure to reset the terminal properly when we're done.
    sys.stdout.write(curses.tparm(curses.tigetstr('setab'), 16))
    sys.stdout.write(curses.tparm(curses.tigetstr('setaf'), 15))