Source

lore2sphinx / lore2sphinx / __init__.py

   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
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
"""
An experiment in transforming lore xhtml docs to sphinx source files.

:since: 2010-01
"""

import sys
import os
import fnmatch
import textwrap
import logging
#~ from StringIO import StringIO
from string import whitespace
from pprint import pformat #, pprint

# for experiment using regexes to clean up rst artifacts
import re

import urllib
import urlparse

#~ from slimmer import xhtml_slimmer
from lxml import etree

from lore2sphinx.table import Table


NL = '\n'       # New Line
BL = '\n\n'     # Blank Line
SPACE = ' '     # a space character
ESCAPED_SPACE = r'\ '   # a rst 'escaped space'

#~ LIST_TAGS = ['ol', 'ul', 'dl']
LIST_TAGS = ['ol', 'ul']
LIST_MARKERS = {
                    'ol': '#. ',
                    'ul': '- ',
                    'dl': '  ' # yes, this is wierd
                }


# lore2sphinx version nr
__version__ = version = '0.1'

# set up experimental regexes?

# replace double-backticks without a preceding space
#~ dbl_backticks_no_prespace = re.compile('(?<=[^\s])(``)')
#~ dbl_backticks_no_prespace = re.compile('(?<=[^\s])(``.*``)')

#~ dbl_backticks_no_prespace = re.compile('(?<=[^\s])(``[^`]*``)')
#~ role_no_prespace = re.compile('(?<=\w)(:\w+:)')
#~ spaces_before_punctuation =re.compile('(?<=`) ([.,?!])')
#~ links_no_prespace

def underline(strng, char):
    '''underline a string'''
    strng = strng.strip()
    uline = char * len(strng)
    return '\n'.join((strng, uline))


def overline(strng, char):
    '''overline a string'''
    oline = char * len(strng)
    return '\n'.join((oline, strng))


def overunderline(strng, char):
    '''underline and overline a string'''
    oline = char * len(strng)
    return '\n'.join((oline, strng, oline))


def rm_ns(full_tag):
    '''remove xml namespace from a string, if present'''
    return full_tag.split('}')[-1]


def format_rest_link(text, href):
    '''Formats a link in ReST syntax.'''
    return '`%s <%s>`_ ' % (n2es(text).replace(NL, ''), href)


def n2es(strg):
    ''' None to EmptyString'''
    if strg is None:
        return ''
    return strg


def collapse_spaces(strg):
    '''return a string with at most one trailing space'''
    if strg.endswith(SPACE):
        return strg.strip(SPACE) + SPACE
    return strg


def remove_newlines(strg):
    '''Remove newlines and left-hand whitespce from a string.

    Mostly used to remove line breaks from places where they are not legal in
    ReST, such as in links, etc.
    '''
    return left_align(strg).replace('\n', ' ')


def strip_after_nl(strg):
    '''strip whitespace if it's the only thing after the last newline'''
    if NL in strg:
        some_lines, last_line = strg.rsplit(NL, 1)
        #~ last_line = strg.splitlines()[-1]
        remaining = [c for c in last_line if c not in whitespace]
        if remaining:
            return some_lines + last_line.rstrip()

    return strg


def strip_blank_lines(text):
    '''strip whitespace from lines that contain *only* whitespace'''
    lines = []
    for line in text.splitlines():
        if line.isspace():
            lines.append('')
        else:
            lines.append(line)
    return NL.join(lines)


def is_wanted(line):
    '''
    filter for toc building
    '''
    if os.path.sep in line:
        if line.endswith('index'):
            return True
    else:
        if not line.endswith('index'):
            return True
    return False

def interp_text_role(role, text, label=''):
    '''helper function to format ReST "interpreted text roles"'''
    if label:
        return ':%s:`%s <%s>` ' % (role, text, label)
    return ':%s:`%s` ' % (role, text)

def inline_markup(char, text):
    '''helper function to format ReST "inline markup"'''
    ftext = '%s%s%s ' % (char, remove_newlines(text).strip(), char)
    # TODO: need to do something here to handle leading/trailing spaces
    return ftext

def remove_blank_lines(text_block):
    '''remove blank lines from a block of text'''
    new_lines = [line for line in text_block.splitlines()
                    if line != '']
    return '\n'.join(new_lines)

def left_align(text_block):
    '''removes all indentation from left side of milti-line text block'''
    new_lines = (line.lstrip() for line in text_block.splitlines())
    return '\n'.join(new_lines)

def indent_block(text_block, indent):
    '''Indent a block of text by the given number of spaces.

    NOTE: indent should be an integer
    '''
    indent_spaces = ' ' * indent
    new_lines = (indent_spaces + line for line in text_block.splitlines())
    return '\n'.join(new_lines)

def hanging_indent(text_block, indent):
    '''indent every line after the first'''
    indent_spaces = ' ' * indent
    #~ lines = left_align(text_block).splitlines()
    lines = textwrap.dedent(text_block).splitlines()

    if lines:
        first_line = lines[0]
        other_lines = lines[1:]
        new_other_lines = [indent_spaces + line for line in other_lines]
        return '\n'.join([first_line] + new_other_lines)

    return ''

def list_wrap(text_block, marker):
    '''marker is a list marker, like '- '''
    return hanging_indent(marker + text_block, len(marker))

def is_external_link(maybe_url):
    '''predicate to determine whether a link is external to the sphinx
    project or not
    '''
    if maybe_url.startswith('http://') or maybe_url.startswith('https://'):
        return True

    return False

def get_subdirs(filepath):
    '''Get subdirectories of the directory that filepath is in.'''
    filedir = os.path.dirname(os.path.abspath(filepath))
    subdirs = [x for x in os.listdir(filedir)
                    if os.path.isdir(os.path.join(filedir, x))]
    return subdirs

def get_subindexes(filepath):
    '''get files named "index" in subdirs of filepath'''
    filedir = os.path.dirname(os.path.abspath(filepath))
    subdirs = get_subdirs(filepath)
    dfiles = []
    for dir in subdirs:
        for each_file in os.listdir(os.path.join(filedir, dir)):
            doc_ref = os.path.splitext('/'.join((dir, each_file)))[0]
            if doc_ref.endswith('index'):
                print doc_ref
                dfiles.append(doc_ref)
    return dfiles


def get_sibling_files(filepath):
    '''Get other files in the same directory with filepath.'''
    filedir = os.path.dirname(os.path.abspath(filepath))
    sibfiles = [x for x in os.listdir(filedir)
                    if os.path.isfile(os.path.join(filedir, x))
                        and  os.path.join(filedir, x) != filepath]
    return sibfiles


# cribbed from: http://www.hoboes.com/Mimsy/hacks/caching-dtds-using-lxml-and-etree/
class CachingResolver(etree.Resolver):

    cache = ''.join(('.', os.sep, 'dtd_cache'))
    def resolve(self, URL, id, context):
        #determine cache path
        url = urlparse.urlparse(URL)
        #~ print url
        filefolder, filename = os.path.split(url.path)
        #~ print filefolder
        #~ print filename
        filefolder = url.hostname + filefolder
        #~ print filefolder
        dtdFolder = os.path.join(self.cache, filefolder)
        #~ print dtdFolder
        dtdPath = os.path.join(dtdFolder, filename)
        #~ print dtdPath
        #cache if necessary
        if not os.path.exists(dtdPath):
            print "CREATING CACHE FOR", URL
            if not os.path.exists(dtdFolder):
                os.makedirs(dtdFolder)
            filename, headers = urllib.urlretrieve(URL, dtdPath)
        #resolve the cached file
        return self.resolve_file(open(dtdPath), context, base_url=URL)


class DocumentProcessor(object):
    '''
    Processes a file, turning it from lore xhtml into Restructured text.

    This basically works by recursing over an etree, and for each tag:
        - call a "prepare_X" method, where X is the tag name
          ("start tag event")
        - processing the children of a tag
        - call a "format_X" method, where X is the tag name
          ("end tag event")
    '''

    def __init__(self, config, source_filepath, dest_filepath):
        '''
        source_filepath - absolute(?) path to source file
        dest_filepath - absolute(?) path to dest file
        output_dir - output directory
        '''

        self.source_filepath = source_filepath
        self.source_filename = os.path.basename(self.source_filepath)
        self.dest_filepath = dest_filepath

        self.this_dir = os.path.dirname(source_filepath)

        self.output_dir = config['dest_dir']

        # relative to the output_directory
        self.rel_destpath = os.path.relpath(self.dest_filepath, self.output_dir)
        logging.debug('rel_destpath: ' + self.rel_destpath)
        self.doc_ref = os.path.splitext(self.rel_destpath)[0].replace(os.path.sep, '-')
        logging.debug('doc_ref: ' + self.doc_ref)

        self.toc_spaces = 4

        self.footnotes = []

        self.internal_links = []
        self.doc_refs = []
        self.unhandled_tags = {}

        self.list_stack = []
        #~ self.table_stack = []
        self.table_data = None

        self.max_width = 79

        self.txt_out = ''

        self.current_indent = 0

        self.parser = None
        self.tree = None
        self.root = None
        
        # following will be prepended to each file
        self.prelude = '''
:LastChangedDate: $LastChangedDate$
:LastChangedRevision: $LastChangedRevision$
:LastChangedBy: $LastChangedBy$
'''

    def _load_data(self):
        '''
        load data for processing
        '''
        f = open(self.source_filepath)

        #~ self.parser = etree.XMLParser()
        #~ self.parser = etree.XMLParser(recover=True)
        #~ self.parser = etree.XMLParser(resolve_entities=True)
        #~ self.parser = etree.XMLParser(resolve_entities=False)
        self.parser = etree.XMLParser(load_dtd=True, no_network=False)
        #~ self.parser = etree.XMLParser(dtd_validation=True, no_network=False)

        self.parser.resolvers.add(CachingResolver()) 

        # use slimmer?
        #~ sio = StringIO(xhtml_slimmer(f.read()))
        #~ self.tree = etree.parse(sio, self.parser)

        # don't use slimmer
        self.tree = etree.parse(f, self.parser)

        self.root = self.tree.getroot()
        f.close()

    @property
    def current_list_marker(self):
        '''returns the most "current" ReST
        list marker (e.g. "- ", "#. ")
        '''
        if self.list_stack:
            return LIST_MARKERS[self.list_stack[-1]]

        return ''

    @property
    def marker_spaces(self):
        return ' ' * len(self.current_list_marker)

    @property
    def list_spaces(self):
        list_depth = len(self.list_stack)
        if list_depth > 1:
            return ' ' * ((list_depth - 1) * 4)
        return ''

    @property
    def indent_spaces(self):
        return self.current_indent * ' '

    def toc_indent(self, a_string):
        return (' ' * self.toc_spaces) + a_string


    ################################################
    # TOC and Footnote formatting
    #   (happens outside the handle_element() flow)
            
    def format_toc(self):
        '''build the rst toctree block - from links in the document''' 
        # only put tocs in index.html files
        if not self.source_filepath.endswith('index.xhtml'):
            return ''
            
        if self.doc_refs:
            #~ toc_header = [''.join(('.. toctree::', NL, '   :maxdepth: 2', NL))]
            toc_header = [''.join(('.. toctree::', NL, '   :hidden:', NL))]
            # we need to remove entries that start with '../' because
            # they will blow up sphinx due to too much recursion
            toc_valid_entries = [e for e in self.doc_refs if not e.startswith('../')]

            # now format the entries
            toc_fmt_entries = ['   ' + e for e in toc_valid_entries]
            return NL.join(toc_header + toc_fmt_entries + [NL])

        return ''

    def format_footnotes(self):
        '''
        formats contents of footnotes (at the end of the page).
        '''
        if self.footnotes:
            fn_rubric = '.. rubric:: Footnotes'
            fn_output = ''
            fn_contents = []
            for fn in self.footnotes:
                fn_contents.append(list_wrap(fn, '.. [#] '))
            fn_output = NL.join(fn_contents)
            return ''.join((BL, fn_rubric, BL, fn_output))

        return ''


    #########################
    # Main processing methods

    def pre_process(self):
        self.txt_out += self.prelude

    def process(self):
        '''
        process the file.
        '''
        self.pre_process()
        self._load_data()
        self.txt_out += self.handle_element(self.root)
        self.post_process()
        #~ print self.tree.docinfo.doctype
        #~ print self.tree.docinfo.public_id
        #~ print self.tree.docinfo.standalone
        #~ print self.parser.error_log

    def post_process(self):
        '''
        Performs post-processing steps.

        Currently:
            - generates and inserts table of contents
            - generates and inserts footnote contents
              (at end of page)
        '''

        toc = self.format_toc()
        self.txt_out = self.txt_out.replace('TOC_TREE_PLACEHOLDER', toc)

        # TODO: output footnote contents
        self.txt_out += self.format_footnotes()
        
        # use a couple of regexes to clean up a little
        # WARNING! EXPERIMENTAL!
        # better to try getparent() or getprevious() in the parsing
        
        # TODO: this one is broken, need to only put spaces in front of 
        #       _first_ set of backticks
        #~ self.txt_out = dbl_backticks_no_prespace.sub(
                            #~ lambda m: ' %s' % m.group(1), self.txt_out)
        #~ self.txt_out = role_no_prespace.sub(
                            #~ lambda m: ' %s' % m.group(1), self.txt_out)
        #~ self.txt_out = spaces_before_punctuation.sub(
                            #~ lambda m: '\ %s' % m.group(1), self.txt_out)
        # TODO: need something to fix links without preceding spaces

    def handle_element(self, elem):
        '''
        Handle an element.

        This calls itself recursively in order to handle all tags.
        '''

        if callable(elem.tag):
            # handle comments, etc. here?
            if isinstance(elem, etree._Comment):
                return self.format_comment(elem)
            return ''

        #~ logging.debug('elem.tag: ' + str(elem.tag))

        # do stuff before handling children
        try:
            prepare_func = getattr(self, 'prepare_' + rm_ns(elem.tag).lower())
        except:
            prepare_func = self.prepare_default
        finally:
        # ACK! TODO: no prepare_X methods currently return any output, but 
        # if any ever do, this will break horribly!
            txt_out = prepare_func(elem)

        # handle children
        child_contents = ''
        for each in elem:
            child_contents += self.handle_element(each)

        # TODO: move this to the relevant list element handlers
        if rm_ns(n2es(elem.tag)) in LIST_TAGS:
            self.list_stack.pop()

        # do stuff after handling children
        try:
            format_func = getattr(self, 'format_' + rm_ns(elem.tag).lower())
        except:
            format_func = self.format_default
        finally:
            txt_out = format_func(elem, child_contents)

        return txt_out


    ##################
    # Comment handler
    #   handled separately since it's different from standard Elements

    def format_comment(self, elem):
        if '\n' in elem.text:
            first_line, rest_of_comment = elem.text.split('\n', 1)
            first_line = '.. ' + first_line
            return ''.join((BL, first_line, indent_block(rest_of_comment, 3), BL))
        else:
            comment_line = '.. ' + elem.text
            return ''.join((BL, comment_line, BL))
        #~ return ''.join((BL, '.. ', indent_block(elem.text, 3), BL))


    ################################
    # Default and pass-thru handlers

    def prepare_default(self, elem):
        '''
        By default, do nothing.
        '''
        pass

    def format_default(self, elem, contents):
        '''
        default element handler.
        '''
        self.unhandled_tags[rm_ns(str(elem.tag))] = self.unhandled_tags.get(rm_ns(str(elem.tag)), 0) + 1
        logging.debug('UNHANDLED_TAG_%s \n' % (elem.tag))

        return ''.join(('UNHANDLED_TAG_%s \n' % (elem.tag),
                          n2es(elem.text),
                          contents,
                          n2es(elem.tail)))

    def format_pass(self, elem, contents):
        '''
        do nothing - just return child contents.
        '''
        return contents

    format_html = format_pass
    format_body = format_pass
    format_head = format_pass
    format_h1 = format_pass


    #######################################
    # HEAD contents and header tag handlers

    def format_link(self, elem, contents):
        '''Format a <link> tag.'''
        rel = elem.attrib.get('rel', None)
        if rel and rel == 'author':
            author_name = elem.attrib.get('title', None)
            author = ':Author: %s' % (author_name)
            return ''.join((BL, author, BL))
        #else
        return ''

    def format_title(self, elem, contents):
        '''Format the <title> element.

        Note that in lore documents, only one <h1> element should exist,
        and the <title> element and the <h1> element should have identical
        contents, which is why there's no "format_h1" function.
        '''
        title_text = underline(remove_newlines(n2es(elem.text).strip()), '=')
        return ''.join((NL, title_text, NL, contents, BL, 'TOC_TREE_PLACEHOLDER', BL))

    def format_h2(self, elem, contents):
        '''Format a <h2> tag.'''
        title_text = ''.join((n2es(elem.text), contents)).strip()
        uline_text = underline(remove_newlines(title_text), '-')
        return ''.join((BL, uline_text, NL, n2es(elem.tail)))

    def format_h3(self, elem, contents):
        '''Format a <h3> tag.'''
        title_text = ''.join((n2es(elem.text), contents)).strip()
        uline_text = underline(remove_newlines(title_text), '~')
        return ''.join((BL, uline_text, NL, n2es(elem.tail)))

    def format_h4(self, elem, contents):
        '''Format a <h4> tag.
        
        ..note:: The Lore "specification" does not address h4 tags, 
                 but Lore itself supports it and h4 tags are used by 
                 some Lore users, so we support it.
        '''
        title_text = ''.join((n2es(elem.text), contents)).strip()
        uline_text = underline(remove_newlines(title_text), '^')
        return ''.join((BL, uline_text, NL, n2es(elem.tail)))

    def format_br(self, elem, contents):
        '''Format a <br> tag.'''
        return NL + n2es(elem.tail)

    def format_style(self, elem, contents):
        '''Format a <style> tag.'''
        # TODO: handle elem.text/elem.tail?
        return '' + n2es(elem.tail)


    ########################
    # Inline markup handlers

    # NOTE: inline elements may not be nested and may not start or end
    # with whitespace, ref: http://sphinx.pocoo.org/rest.html
    # TODO: maybe these should throw warnings if they have nested markup?

    def format_q(self, elem, contents):
        '''Format a <q> tag.'''
        return inline_markup('"', (n2es(elem.text) + contents).strip())  + n2es(elem.tail)

    def format_em(self, elem, contents):
        '''Format a <em> or <i>tag.'''
        return inline_markup('*', (n2es(elem.text) + contents).strip())  + n2es(elem.tail)

    format_i = format_em

    def format_strong(self, elem, contents):
        '''Format a <strong> or <b> tag.'''
        return inline_markup('**', (n2es(elem.text) + contents).strip())  + n2es(elem.tail)

    format_b = format_strong

    def format_code(self, elem, contents):
        '''Format a <code> tag.'''
        # TODO: handle class attributes
        code_class = elem.attrib.get('class', '')
        code_base = elem.attrib.get('base', None)
        
        if 'API' in code_class:
            if code_base:
                fqname = '.'.join((code_base, n2es(elem.text)))
            else:
                fqname = n2es(elem.text)

            return interp_text_role('api', remove_newlines(fqname), remove_newlines(n2es(elem.text))) + n2es(elem.tail)

        new_contents = remove_newlines( (n2es(elem.text) + contents).strip())
        return inline_markup('``', new_contents) + n2es(elem.tail)

    def format_sup(self, elem, contents):
        '''Format a <sup> tag.'''
        return interp_text_role('superscript', contents) + n2es(elem.tail)

    def format_sub(self, elem, contents):
        '''Format a <sub> tag.'''
        return interp_text_role('subscript', contents) + n2es(elem.tail)

    def format_cite(self, elem, contents):
        return n2es(elem.text) + contents
        

    ################
    # link handling

    def format_a(self, elem, contents):
        '''Format a <a> tag.

        This function categorizes the links and then returns the results
        of a helper function for each category.
        '''
        a_href = elem.attrib.get('href', None)
        a_name = elem.attrib.get('name', None)
        a_class = elem.attrib.get('class', None)

        inline_classes = ['py-listing', 'html-listing']

        if a_name and not a_href:
            # then its a target
            return self.format_a_target(elem, contents)

        if a_href:
            if is_external_link(a_href):
                return self.format_a_external(elem, contents)

            if a_class:
                if a_class == 'absolute':
                    return self.format_a_absolute(elem, contents)
                if a_class in inline_classes:
                    return self.format_a_inline(elem, contents)

            return self.format_a_internal(elem, contents)

        return "I DON'T KNOW WHAT TO DO WITH THIS LINK!"

    def format_a_target(self, elem, contents):
        '''Format a <a> tag which is a "target".'''
        anchor = elem.attrib.get('name')
        #~ doc_ref = self.source_filepath.replace('/', '-')
        label = '-'.join((self.doc_ref, anchor)).lower()
        target = '.. _%s:' % label
        return ''.join((target, BL, n2es(elem.text), BL,
                         contents, BL, n2es(elem.tail)))

    def format_a_external(self, elem, contents):
        '''
        Format a <a> tag which is a link to an external file.
        '''
        a_href = elem.attrib.get('href', None)
        text = n2es(elem.text).replace(NL, '').lstrip()
        if text:
            return '`%s <%s>`_ ' % (text, a_href) + n2es(elem.tail)

        return a_href + n2es(elem.tail)

    def format_a_absolute(self, elem, contents):
        '''class="absolute" is used in Lore to refer to non-Lore xhtml
        files.  Haven't needed this yet.'''
        raise NotImplementedError

    def format_a_inline(self, elem, contents):
        '''Format a <a> tag which links to content which
        should be inlined.
        '''
        a_href = elem.attrib.get('href', None)
        literalinclude_directive = '.. literalinclude:: %s' % a_href
        
        if a_href.endswith('.rtl'):
            literalinclude_directive += '\n   :language: py3'

        fname = a_href.split('/')[-1]
        dl_role = ":download:`%s <%s>`" % (fname, a_href)

        return ''.join((BL, dl_role, BL, literalinclude_directive, BL, n2es(elem.tail).lstrip()))

    def format_a_internal(self, elem, contents):
        '''Format a <a> tag which is a link to an internal document.'''
        a_href = elem.attrib.get('href', None)

        download_exts = ['.py', '.sql', '.tac']

        if '#' in a_href:
            filetarg, anchor = a_href.split('#')
            if filetarg:
                logging.debug('filetarg: ' + filetarg)
                x = os.path.dirname(self.dest_filepath)
                logging.debug('x: ' + x)
                y = os.path.join(x, filetarg)
                logging.debug('y: ' + y)
                z = os.path.abspath(y)
                logging.debug('z: ' + z)
                p = os.path.relpath(z, self.output_dir)
                logging.debug('p: ' + p)
                q = os.path.splitext(p)[0]
                logging.debug('q: ' + q)
                doc_ref = q.replace(os.path.sep, '-')
                logging.debug('doc_ref: ' + doc_ref)
                label = '-'.join((doc_ref, anchor)).lower()
            else:
                label = '-'.join((self.doc_ref, anchor)).lower()

            title = n2es(elem.text)
            title = title or 'NEEDS A TITLE'
            # TODO: change this to use interp_text_role
            return ':ref:`%s <%s>` ' % (title, label) + n2es(elem.tail)

        else:
            if a_href.endswith('/'):
                # links ending with a '/' need to pretend to end with '/index.xhtml'
                doc_ref = a_href + 'index'
                ext = '.xhtml'
            else:
                doc_ref, ext = os.path.splitext(a_href)

            if ext == '.xhtml':
                self.doc_refs.append(doc_ref)
                if elem.text:
                    return ':doc:`%s <%s>` ' % (remove_newlines(elem.text).strip(),
                                                 doc_ref) + n2es(elem.tail)
                return ':doc:`%s` ' % (doc_ref) + n2es(elem.tail)
                # TODO: change this to use interp_text_role like:
                #~ return interp_text_role('doc', doc_ref) + n2es(elem.tail)
            elif ext == '.html':
                return format_rest_link(n2es(elem.text) + contents, a_href)
                #~ raise Exception('link to html file')
            elif ext in download_exts:
                return ':download:`%s` ' % (doc_ref + ext) + n2es(elem.tail)

            return a_href + n2es(elem.tail)

    def format_span(self, elem, contents):
        '''
        Format a <span> tag.
        '''
        span_class = elem.attrib.get('class', None)

        if span_class:
            if 'footnote' in span_class:
                self.footnotes.append(n2es(elem.text) + contents)
                #~ fn_index = len(self.footnotes) + 1
                return ' [#]_ ' + n2es(elem.tail)

        return self.format_default(elem, contents)

    #######################
    # block-level elements

    def format_div(self, elem, contents):
        '''
        Format a <div> tag.

        This function categorizes the links and then returns the results
        of a helper function for each category.
        '''
        div_class = elem.attrib.get('class', None)

        if div_class is None:
            return ''.join((n2es(elem.text), contents, n2es(elem.tail)))

        if div_class in ['note', 'doit', 'boxed']:
            div_func = getattr(self, 'format_div_' + div_class.lower())
            return div_func(elem, contents)

    def format_div_note(self, elem, contents):
        '''Format a <div> tag which represents a "note".'''
        all_contents = ''.join((n2es(elem.text), contents))
        return ''.join(('.. note::', NL, indent_block(all_contents, 3),
                          BL, n2es(elem.tail)))

    def format_div_doit(self, elem, contents):
        '''
        Format a <div> tag which represents a todo item.
        '''
        return ''.join(('.. todo::', NL, n2es(elem.text),
                          contents, BL, n2es(elem.tail)))

    def format_div_boxed(self, elem, contents):
        '''Format a <div> tag which represents text that
        should be "boxed".
        '''
        # TODO: should this do something other than '.. note::'?
        all_contents = ''.join((n2es(elem.text), contents))
        return ''.join(('.. note::', NL, indent_block(all_contents, 3),
                          contents, BL, n2es(elem.tail)))

    def format_img(self, elem, contents):
        '''Format an <img> tag.'''
        image_file = elem.attrib.get('src')
        img_directive = '.. image:: %s' % image_file

        return ''.join((BL, img_directive, n2es(elem.tail), BL))

    def format_pre(self, elem, contents):
        '''Format a <pre> tag.'''
        # TODO: handle different class attributes!
        #   may not be needed, Sphinx seems to handle this ok as-is
        
        classes = {'python': 'python',
                   'python-interpreter': 'pycon',
                   'shell': 'console'
                  }
        
        pre_class = elem.attrib.get('class', None)
        
        if pre_class in classes:
            directive = '.. code-block:: %s' % classes[pre_class]
        else:
            directive = '::'
        
        self.current_indent += 4
        all_contents = n2es(elem.text) + contents
        indented_contents = indent_block(textwrap.dedent(all_contents), 4)
        #~ logging.debug(pformat(indented_contents))
        self.current_indent -= 4
        new_contents = ''.join((BL,
                                directive,
                                BL,
                                indented_contents,
                                BL,
                                n2es(elem.tail)))
        #~ logging.debug(pformat(new_contents))
        return new_contents

    def prepare_ul(self, elem):
        '''
        Prepare for an <ul> tag.

        Pushes an 'ul' onto the list stack.
        '''
        self.list_stack.append(rm_ns(elem.tag))

    def format_ul(self, elem, contents):
        '''Format a <ul> tag.'''
        return ''.join((BL,
                         strip_blank_lines(n2es(elem.text)),
                         contents,
                         n2es(elem.tail),
                         BL))

    def prepare_ol(self, elem):
        '''
        Prepare for an <ol> tag.

        Pushes an 'ol' onto the list stack.
        '''
        self.list_stack.append(rm_ns(elem.tag))

    def format_ol(self, elem, contents):
        '''Format a <ol> tag.'''
        return ''.join((BL,
                         #~ strip_blank_lines(n2es(elem.text)),
                         n2es(elem.text).lstrip(),
                         contents,
                         n2es(elem.tail).rstrip(),
                         BL))

    def prepare_li(self, elem):
        '''
        Prepare for a <li> tag.

        Since the tail of the <li> tags immediate children are conceptually part
        of the text contents of the <li> tag, and the indentation needs to be
        the same for each part, we left_align() each of them here.  Note that
        this can mean that the text contents of the <li> tag can be separate
        ReST paragraphs in the output.
        '''

        for child in elem:
            child.tail = left_align(n2es(child.tail))

    def format_li(self, elem, contents):
        '''Format a <li> tag.'''
        all_contents = ''.join((left_align(n2es(elem.text)),
                                contents,
                                n2es(elem.tail).rstrip()))
        #~ new_contents = all_contents.strip()
        new_contents = all_contents
        out_lines = list_wrap(new_contents, self.current_list_marker)
        # must be EXACTLY ONE newline after a LI element
        # NOT ALWAYS!  a LI element that contains another list (OL/UL)
        # might have a blank line before and after it!
        #~ logger.debug(pformat(out_lines))
        #~ return out_lines.rstrip() + NL
        return out_lines + NL

    def format_dl(self, elem, contents):
        '''
        Format a <dl> tag.
        '''
        return ''.join((BL, n2es(elem.text), NL, contents, n2es(elem.tail), BL))

    def format_dt(self, elem, contents):
        '''
        Format a <dt> tag.
        '''
        # TODO: decide whether to strip this line or not...
        #~ return ''.join((n2es(elem.text), contents, NL)).strip()
        return ''.join((n2es(elem.text), contents, n2es(elem.tail), NL))

    def prepare_dd(self, elem):

        for child in elem:
            child.tail = left_align(n2es(child.tail))

    def format_dd(self, elem, contents):
        '''
        Format a <dd> tag.
        '''
        new_contents = ''.join((left_align(n2es(elem.text)),
                                contents,
                                n2es(elem.tail)))
        out_lines = indent_block(new_contents, 2)

        # must be EXACTLY ONE newline after a LI element
        return out_lines.rstrip() + BL

    def prepare_p(self, elem):
        '''
        Prepare for a <p> tag.

        Since the tail of the <p> tags immediate children are conceptually part
        of the text contents of the <p> tag, and the indentation needs to be
        the same for each part, we left_align() each of them here.  Note that
        this can mean that the text contents of the <p> tag can be separate
        ReST paragraphs in the output.
        '''

        for child in elem:
            child.tail = left_align(n2es(child.tail))


    def format_p(self, elem, contents):
        '''
        Format a <p> tag.

        NOTE: why does there need to be a BL after the tail?
        Because the tail is almost always whitespace, and if it comes after
        the BL, it will jack up the indentation of the next element.
        '''
        # fix indentation
        all_contents = ''.join((left_align(n2es(elem.text)),
                               contents,
                               n2es(elem.tail)))
        #~ logging.debug(pformat(all_contents))
        return ''.join((NL, all_contents, BL))

    def prepare_blockquote(self, elem):
        '''
        Prepare for a <blockquote> tag.

        Since the tail of the <blockquote> tags immediate children are conceptually part
        of the text contents of the <blockquote> tag, and the indentation needs to be
        the same for each part, we left_align() each of them here.  Note that
        this can mean that the text contents of the <blockquote> tag can be separate
        ReST paragraphs in the output.
        '''

        for child in elem:
            child.tail = left_align(n2es(child.tail))

    def format_blockquote(self, elem, contents):
        '''Format a <blockquote> tag.

        Format this just like a <p> tag, but indent it.'''
        text_block = self.format_p(elem, contents)
        return indent_block(text_block, 4)

    #######################
    # table elements

    def prepare_tr(self, elem):
        self.table_data.append([])

    def format_tr(self, elem, contents):
        return ''

    #~ def prepare_td(self, elem):
        #~ for child in elem:
            #~ child.tail = left_align(n2es(child.tail))

    def format_td(self, elem, contents):
        #~ all_contents = n2es(elem.text)
        all_contents = ''.join((left_align(n2es(elem.text)),
                               contents,
                               n2es(elem.tail))).strip()
        if all_contents == '':
            all_contents = '\ '
        self.table_data[-1].append(all_contents)
        return ''

    #~ prepare_th = prepare_td
    format_th = format_td

    def prepare_table(self, elem):
        self.table_data = []

    def format_table(self, elem, contents):
        tbl = Table(self.table_data)
        output = tbl.create_table()
        return ''.join((NL, output, NL))
        #~ return ''.join((NL, str(tbl.widths), BL, output, NL))
        #~ return ''.join((NL, str(tbl.widths), BL, str(self.table_data), BL, output, NL))

    def write_output(self):
        '''
        write output to a file.
        '''
        dest_dir = os.path.dirname(self.dest_filepath)
        if not os.path.isdir(dest_dir):
            os.makedirs(dest_dir)

        f_out = open(self.dest_filepath, 'w')
        f_out.write(self.txt_out.encode('utf-8'))
        f_out.close()


def gen_find(filepat, top):
    '''Generator to create a sequence of files to be processed.'''
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist, filepat):
            yield os.path.join(path, name)


def destination_path(path, source_dir, dest_dir):
    '''
    Calculates the destination path of a file to be processed.
    '''
    old_rel_path = os.path.relpath(path, docs_location)
    new_path = os.path.realpath(os.path.join(dest_dir, old_rel_path))

    return os.path.splitext(new_path)[0] + '.rst'


class FileProcessor(object):
    '''
    Process a file.

    This class was created as part of a refactor that is not yet finished.

    The intention is to make this class handle the file details, and
    DocumentProcessor just deal with a string, but this has not been completed.
    '''
    def __init__(self, config, source_rel_filename):
        '''
        :param config: config dictionary
        :param source_rel_filename: filename relative to the source directory
        '''
        self.config = config

        self.source_rel_filepath = source_rel_filename
        self.source_filepath = os.path.join(config['source_dir'],
                                             source_rel_filename)

        self.dest_rel_filepath = \
                os.path.splitext(source_rel_filename)[0] + '.rst'

        new_path = os.path.join(config['dest_dir'], self.dest_rel_filepath)
        self.dest_filepath = os.path.abspath(new_path)

        logging.debug('source file: SOURCE\\%s' % self.source_rel_filepath)
        logging.debug('dest file: DEST\\%s' % self.dest_rel_filepath)

        self.unhandled_tags = None

    def process(self):
        '''
        process the file.
        '''
        # TODO: refactor...
        #   dprocessor should probably be created in __init__
        self.dprocessor = DocumentProcessor(self.config,
                                            self.source_filepath,
                                            self.dest_filepath)
        self.dprocessor.process()

        self.unhandled_tags = self.dprocessor.unhandled_tags

    def write_output(self):
        '''write output to a file

        TODO: refactor me!  currently just passes through to
        DocumentProcessor
        '''
        self.dprocessor.write_output()


class BatchProcessor(object):
    '''
    Processes a set of files, converting all ".xhtml" files in the
    given source directory into .rst files in the destination directory.
    '''
    def __init__(self, config = None):
        '''
        config object - dict of the form:
            {
                'source_dir' : source_directory,
                'dest_dir': destination_directory,
                'ignored_files': list_of_filenames_to_ignore
            }
        '''

        assert config is not None

        self.config = config

    def process(self):
        '''
        Process a set of files.
        '''
        doc_names_all = gen_find("*.xhtml", self.config['source_dir'])
        doc_names = (x for x in doc_names_all
                        if os.path.basename(x)
                            not in self.config['ignored_files'])

        all_unhandled_tags = {}
        unhandled_tags_by_page = {}

        logging.debug('SOURCE directory: %s' % self.config['source_dir'])
        logging.debug('DEST directory: %s' % self.config['dest_dir'])

        for source in doc_names:

            rel_source = (os.path.relpath(source, self.config['source_dir']))
            #~ rel_dest = (os.path.relpath(dest, self.config['dest_dir']))

            fprocessor = FileProcessor(self.config, rel_source)
            logging.debug('processing file: %s' % rel_source)
            try:
                fprocessor.process()
            except Exception:
                logging.debug(sys.exc_info())
                logging.error('FAILED on file: %s' % (source) )
                raise

            # output the file
            fprocessor.write_output()
            logging.debug('done with file: %s' % (source))

            # log info on unhandled tags
            if fprocessor.unhandled_tags:
                unhandled_tags_by_page[rel_source] = fprocessor.unhandled_tags
            for key in fprocessor.unhandled_tags:
                all_unhandled_tags[key] = all_unhandled_tags.get(key, 0) + fprocessor.unhandled_tags[key]
            logging.debug('Unhandled tags: %s\n' % fprocessor.unhandled_tags)

        logging.info('')
        logging.info('=' * 40)
        logging.info(' CONVERSION COMPLETE ')
        logging.info('=' * 40)
        logging.info('The following files were ignored (not converted): ')
        logging.info(pformat(self.config['ignored_files']))
        logging.info('')
        logging.info('All unhandled tags: %s' % all_unhandled_tags)
        logging.info('')
        logging.info('Unhandled tags by page: %s' % pformat(unhandled_tags_by_page))
        logging.info('')
        num_unhandled_tags = sum(all_unhandled_tags.values())
        logging.info('Total unhandled tags: %s' % num_unhandled_tags)
        logging.info('')