#!/usr/bin/env python3
"""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, text=True)
  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, text=True)
  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 range(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 range(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, text=True)

    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 range(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 range(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))
