Source

sphinx / sphinx / writers / texinfo.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
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
# -*- coding: utf-8 -*-
"""
    sphinx.writers.texinfo
    ~~~~~~~~~~~~~~~~~~~~~~

    Custom docutils writer for Texinfo.

    :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import re
from os import path
import textwrap

from docutils import nodes, writers

from sphinx import addnodes, __version__
from sphinx.locale import versionlabels, _
from sphinx.util import ustrftime


COPYING = """\
@quotation
%(project)s %(release)s, %(date)s

%(author)s

Copyright @copyright{} %(copyright)s
@end quotation
"""

TEMPLATE = """\
\\input texinfo   @c -*-texinfo-*-
@c %%**start of header
@setfilename %(filename)s
@documentencoding UTF-8
@ifinfo
@*Generated by Sphinx """ + __version__ + """.@*
@end ifinfo
@settitle %(title)s
@defindex ge
@paragraphindent %(paragraphindent)s
@exampleindent %(exampleindent)s
@afourlatex
%(direntry)s
@c %%**end of header

@copying
%(copying)s
@end copying

@titlepage
@title %(title)s
@insertcopying
@end titlepage
@contents

@c %%** start of user preamble
%(preamble)s
@c %%** end of user preamble

@ifnottex
@node Top
@top %(title)s
@insertcopying
@end ifnottex

@c %%**start of body
%(body)s
@c %%**end of body
@bye
"""


def find_subsections(section):
    """Return a list of subsections for the given ``section``."""
    result = []
    for child in section.children:
        if isinstance(child, nodes.section):
            result.append(child)
            continue
        result.extend(find_subsections(child))
    return result


## Escaping
# Which characters to escape depends on the context.  In some cases,
# namely menus and node names, it's not possible to escape certain
# characters.

def escape(s):
    """Return a string with Texinfo command characters escaped."""
    s = s.replace('@', '@@')
    s = s.replace('{', '@{')
    s = s.replace('}', '@}')
    # Prevent "--" from being converted to an "em dash"
    # s = s.replace('-', '@w{-}')
    return s

def escape_arg(s):
    """Return an escaped string suitable for use as an argument
    to a Texinfo command."""
    s = escape(s)
    # Commas are the argument delimeters
    s = s.replace(',', '@comma{}')
    # Normalize white space
    s = ' '.join(s.split()).strip()
    return s

def escape_id(s):
    """Return an escaped string suitable for node names and xrefs anchors."""
    bad_chars = ',:.()'
    for bc in bad_chars:
        s = s.replace(bc, ' ')
    s = ' '.join(s.split()).strip()
    return escape(s)

def escape_menu(s):
    """Return an escaped string suitable for menu entries."""
    s = escape_arg(s)
    s = s.replace(':', ';')
    s = ' '.join(s.split()).strip()
    return s

class TexinfoWriter(writers.Writer):
    """Texinfo writer for generating Texinfo documents."""
    supported = ('texinfo', 'texi')

    settings_spec = (
        'Texinfo Specific Options',
        None,
        (
            ("Name of the resulting Info file to be created by 'makeinfo'.  "
             "Should probably end with '.info'.",
             ['--texinfo-filename'],
             {'default': '', 'metavar': '<file>'}),

            ('Specify the Info dir entry category.',
             ['--texinfo-dir-category'],
             {'default': 'Miscellaneous', 'metavar': '<name>'}),

            ('The name to use for the Info dir entry.  '
             'If not provided, no entry will be created.',
             ['--texinfo-dir-entry'],
             {'default': '', 'metavar': '<name>'}),

            ('A brief description (one or two lines) to use for the '
             'Info dir entry.',
             ['--texinfo-dir-description'],
             {'default': '', 'metavar': '<desc>'}),
            )
        )

    settings_defaults = {}
    settings_default_overrides = {'docinfo_xform': 0}

    output = None

    visitor_attributes = ('output', 'fragment')

    def __init__(self, builder):
        writers.Writer.__init__(self)
        self.builder = builder

    def translate(self):
        self.visitor = visitor = TexinfoTranslator(self.document, self.builder)
        self.document.walkabout(visitor)
        visitor.finish()
        for attr in self.visitor_attributes:
            setattr(self, attr, getattr(visitor, attr))


class TexinfoTranslator(nodes.NodeVisitor):

    ignore_missing_images = False

    default_elements = {
        'author': '',
        'body': '',
        'copying': '',
        'date': '',
        'direntry': '',
        'exampleindent': 4,
        'filename': '',
        'paragraphindent': 2,
        'preamble': '',
        'project': '',
        'release': '',
        'title': '',
        }

    def __init__(self, document, builder):
        nodes.NodeVisitor.__init__(self, document)
        self.builder = builder
        self.init_settings()

        self.written_ids = set()    # node names and anchors in output
        self.referenced_ids = set() # node names and anchors that should
                                    # be in output
        self.indices = []     # (node name, content)
        self.short_ids = {}   # anchors --> short ids
        self.node_names = {}  # node name --> node's name to display
        self.node_menus = {}  # node name --> node's menu entries
        self.rellinks = {}    # node name --> (next, previous, up)

        self.collect_indices()
        self.collect_node_names()
        self.collect_node_menus()
        self.collect_rellinks()

        self.body = []
        self.context = []
        self.previous_section = None
        self.section_level = 0
        self.seen_title = False
        self.next_section_targets = []
        self.escape_newlines = 0
        self.curfilestack = []

    def finish(self):
        for index in self.indices:
            name, content = index
            pointers = tuple([name] + self.rellinks[name])
            self.add_text('\n@node %s,%s,%s,%s\n' % pointers)
            self.add_text('@unnumbered %s\n\n%s\n' % (name, content))

        while self.referenced_ids:
            # Handle xrefs with missing anchors
            r = self.referenced_ids.pop()
            if r not in self.written_ids:
                self.document.reporter.info(
                    "Unknown cross-reference target: `%s'" % r)
                self.add_text('@anchor{%s}@w{%s}\n' % (r, ' ' * 30))
        self.fragment = ''.join(self.body).strip() + '\n'
        self.elements['body'] = self.fragment
        self.output = TEMPLATE % self.elements


    ## Helper routines

    def init_settings(self):
        settings = self.settings = self.document.settings
        elements = self.elements = self.default_elements.copy()
        elements.update({
                # if empty, the title is set to the first section title
                'title': settings.title,
                'author': settings.author,
                # if empty, use basename of input file
                'filename': settings.texinfo_filename,
                'release': escape(self.builder.config.release),
                'project': escape(self.builder.config.project),
                'copyright': escape(self.builder.config.copyright),
                'date': escape(self.builder.config.today or
                               ustrftime(self.builder.config.today_fmt
                                                or _('%B %d, %Y')))
                })
        # Title
        title = elements['title']
        if not title:
            title = self.document.next_node(nodes.title)
            title = (title and title.astext()) or '<untitled>'
        elements['title'] = escape_id(title) or '<untitled>'
        # Filename
        if not elements['filename']:
            elements['filename'] = self.document.get('source') or 'untitled'
            if elements['filename'][-4:] in ('.txt', '.rst'):
                elements['filename'] = elements['filename'][:-4]
            elements['filename'] += '.info'
        # Direntry
        if settings.texinfo_dir_entry:
            entry = self.format_menu_entry(
                escape_menu(settings.texinfo_dir_entry),
                '(%s)' % elements['filename'],
                escape_arg(settings.texinfo_dir_description))
            elements['direntry'] = ('@dircategory %s\n'
                                    '@direntry\n'
                                    '%s'
                                    '@end direntry\n') % (
                escape_id(settings.texinfo_dir_category), entry)
        elements['copying'] = COPYING % elements
        # allow the user to override them all
        elements.update(settings.texinfo_elements)

    def collect_node_names(self):
        """Generates a unique id for each section.

        Assigns the attribute ``node_name`` to each section."""
        # Must have a "Top" node
        self.document['node_name'] = 'Top'
        self.node_names['Top'] = 'Top'
        self.written_ids.update(('Top', 'top'))
        # Each index is a node
        for name, content in self.indices:
            self.node_names[name] = name
            self.written_ids.add(name)
        # Each section is also a node
        for section in self.document.traverse(nodes.section):
            title = section.next_node(nodes.Titular)
            name = (title and title.astext()) or '<untitled>'
            node_id = escape_id(name) or '<untitled>'
            assert node_id and name
            nth, suffix = 1, ''
            while node_id + suffix in self.written_ids:
                nth += 1
                suffix = '<%s>' % nth
            node_id += suffix
            assert node_id not in self.node_names
            assert node_id not in self.written_ids
            section['node_name'] = node_id
            self.node_names[node_id] = name
            self.written_ids.add(node_id)

    def collect_node_menus(self):
        """Collect the menu entries for each "node" section."""
        node_menus = self.node_menus
        for node in ([self.document] +
                     self.document.traverse(nodes.section)):
            assert 'node_name' in node and node['node_name']
            entries = [s['node_name'] for s in find_subsections(node)]
            node_menus[node['node_name']] = entries
        # Try to find a suitable "Top" node
        title = self.document.next_node(nodes.title)
        top = (title and title.parent) or self.document
        if not isinstance(top, (nodes.document, nodes.section)):
            top = self.document
        if top is not self.document:
            entries = node_menus[top['node_name']]
            entries += node_menus['Top'][1:]
            node_menus['Top'] = entries
            del node_menus[top['node_name']]
            top['node_name'] = 'Top'
        # Handle the indices
        for name, content in self.indices:
            node_menus[name] = ()
            node_menus['Top'].append(name)

    def collect_rellinks(self):
        """Collect the relative links (next, previous, up) for each "node"."""
        rellinks = self.rellinks
        node_menus = self.node_menus
        for id, entries in node_menus.items():
            rellinks[id] = ['', '', '']
        # Up's
        for id, entries in node_menus.items():
            for e in entries:
                rellinks[e][2] = id
        # Next's and prev's
        for id, entries in node_menus.items():
            for i, id in enumerate(entries):
                # First child's prev is empty
                if i != 0:
                    rellinks[id][1] = entries[i-1]
                # Last child's next is empty
                if i != len(entries) - 1:
                    rellinks[id][0] = entries[i+1]
        # Top's next is its first child
        try:
            first = node_menus['Top'][0]
        except IndexError:
            pass
        else:
            rellinks['Top'][0] = first
            rellinks[first][1] = 'Top'

    def add_text(self, text, fresh=False):
        """Add some text to the output.

        Optional argument ``fresh`` means to insert a newline before
        the text if the last character out was not a newline."""
        if fresh:
            if self.body and not self.body[-1].endswith('\n'):
                self.body.append('\n')
        self.body.append(text)

    def rstrip(self):
        """Strip trailing whitespace from the current output."""
        while self.body and not self.body[-1].strip():
            del self.body[-1]
        if not self.body:
            return
        self.body[-1] = self.body[-1].rstrip()

    def format_menu_entry(self, name, node_name, desc):
        if name == node_name:
            s = '* %s:: ' % (name,)
        else:
            s = '* %s: %s. ' % (name, node_name)
        offset = max((24, (len(name) + 4) % 78))
        wdesc = '\n'.join(' ' * offset + l for l in
                          textwrap.wrap(desc, width=78-offset))
        return s + wdesc.strip() + '\n'

    def add_menu_entries(self, entries, reg=re.compile(r'\s+---?\s+')):
        for entry in entries:
            name = self.node_names[entry]
            # Special formatting for entries that are divided by an em-dash
            parts = reg.split(name, 1)
            if len(parts) == 2:
                name, desc = parts
            else:
                desc = ''
            name = escape_menu(name)
            desc = escape(desc)
            me = self.format_menu_entry(name, entry, desc)
            self.add_text(me, fresh=1)

    def add_menu(self, node_name):
        entries = self.node_menus[node_name]
        if not entries:
            return
        self.add_text('\n@menu\n')
        self.add_menu_entries(entries)
        if node_name != 'Top':
            self.rstrip()
            self.add_text('\n@end menu\n')
            return

        def _add_detailed_menu(name):
            entries = self.node_menus[name]
            if not entries:
                return
            self.add_text('\n%s\n\n' % (escape(self.node_names[name],)))
            self.add_menu_entries(entries)
            for subentry in entries:
                _add_detailed_menu(subentry)

        self.add_text('\n@detailmenu\n'
                      ' --- The Detailed Node Listing ---\n')
        for entry in entries:
            _add_detailed_menu(entry)
        self.rstrip()
        self.add_text('\n@end detailmenu\n'
                      '@end menu\n')

    def tex_image_length(self, width_str):
        match = re.match('(\d*\.?\d*)\s*(\S*)', width_str)
        if not match:
            # fallback
            return width_str
        res = width_str
        amount, unit = match.groups()[:2]
        if not unit or unit == "px":
            # pixels: let TeX alone
            return ''
        elif unit == "%":
            # a4paper: textwidth=418.25368pt
            res = "%d.0pt" % (float(amount) * 4.1825368)
        return res

    def collect_indices(self):
        def generate(content, collapsed):
            ret = ['\n@menu\n']
            for letter, entries in content:
                for entry in entries:
                    if not entry[3]:
                        continue
                    name = escape_menu(entry[0])
                    sid = self.get_short_id(entry[3])
                    desc = escape_arg(entry[6])
                    me = self.format_menu_entry(name, sid, desc)
                    ret.append(me)
            ret.append('@end menu\n')
            return ''.join(ret)

        indices_config = self.builder.config.texinfo_domain_indices
        if indices_config:
            for domain in self.builder.env.domains.itervalues():
                for indexcls in domain.indices:
                    indexname = '%s-%s' % (domain.name, indexcls.name)
                    if isinstance(indices_config, list):
                        if indexname not in indices_config:
                            continue
                    content, collapsed = indexcls(domain).generate(
                        self.builder.docnames)
                    if not content:
                        continue
                    node_name = escape_id(indexcls.localname)
                    self.indices.append((node_name,
                                         generate(content, collapsed)))
        self.indices.append((_('Index'), '\n@printindex ge\n'))

    ## xref handling

    def get_short_id(self, id):
        """Return a shorter 'id' associated with ``id``."""
        # Shorter ids improve paragraph filling in places
        # that the id is hidden by Emacs.
        try:
            sid = self.short_ids[id]
        except KeyError:
            sid = hex(len(self.short_ids))[2:]
            self.short_ids[id] = sid
        return sid

    def add_anchor(self, id, node):
        sid = self.get_short_id(id)
        if sid not in self.written_ids:
            self.add_text('@anchor{%s}' % sid)
            self.written_ids.add(sid)

    def add_xref(self, ref, name, node):
        name = escape_menu(name)
        sid = self.get_short_id(ref)
        self.add_text('@pxref{%s,,%s}' % (sid, name))
        self.referenced_ids.add(sid)

    ## Visiting

    def visit_document(self, node):
        pass
    def depart_document(self, node):
        pass

    def visit_Text(self, node):
        s = escape(node.astext())
        if self.escape_newlines:
            s = s.replace('\n', ' ')
        self.add_text(s)
    def depart_Text(self, node):
        pass

    def visit_section(self, node):
        self.next_section_targets.extend(node.get('ids', []))
        if not self.seen_title:
            return
        if self.previous_section:
            self.add_menu(self.previous_section['node_name'])
        else:
            self.add_menu('Top')

        node_name = node['node_name']
        pointers = tuple([node_name] + self.rellinks[node_name])
        self.add_text('\n@node %s,%s,%s,%s\n' % pointers)
        for id in self.next_section_targets:
            self.add_anchor(id, node)

        self.next_section_targets = []
        self.previous_section = node
        self.section_level += 1

    def depart_section(self, node):
        self.section_level -= 1

    headings = (
        '@unnumbered',
        '@chapter',
        '@section',
        '@subsection',
        '@subsubsection',
        )

    rubrics = (
        '@heading',
        '@subheading',
        '@subsubheading',
        )

    def visit_title(self, node):
        if not self.seen_title:
            self.seen_title = 1
            raise nodes.SkipNode
        parent = node.parent
        if isinstance(parent, nodes.table):
            return
        if isinstance(parent, nodes.Admonition):
            raise nodes.SkipNode
        elif isinstance(parent, nodes.sidebar):
            self.visit_rubric(node)
        elif isinstance(parent, nodes.topic):
            raise nodes.SkipNode
        elif not isinstance(parent, nodes.section):
            self.document.reporter.warning(
                'encountered title node not in section, topic, table, '
                'admonition or sidebar', base_node=node)
            self.visit_rubric(node)
        else:
            try:
                heading = self.headings[self.section_level]
            except IndexError:
                heading = self.headings[-1]
            self.add_text('%s ' % heading, fresh=1)

    def depart_title(self, node):
        self.add_text('', fresh=1)

    def visit_rubric(self, node):
        try:
            rubric = self.rubrics[self.section_level]
        except IndexError:
            rubric = self.rubrics[-1]
        self.add_text('%s ' % rubric, fresh=1)
    def depart_rubric(self, node):
        self.add_text('', fresh=1)

    def visit_subtitle(self, node):
        self.add_text('\n\n@noindent\n')
    def depart_subtitle(self, node):
        self.add_text('\n\n')

    ## References

    def visit_target(self, node):
        if node.get('ids'):
            self.add_anchor(node['ids'][0], node)
        elif node.get('refid'):
            # Section targets need to go after the start of the section.
            next = node.next_node(ascend=1, siblings=1)
            while isinstance(next, nodes.target):
                next = next.next_node(ascend=1, siblings=1)
            if isinstance(next, nodes.section):
                self.next_section_targets.append(node['refid'])
                return
            self.add_anchor(node['refid'], node)
        elif node.get('refuri'):
            pass
        else:
            self.document.reporter.error("Unknown target type: %r" % node)

    def visit_reference(self, node):
        if isinstance(node.parent, nodes.title):
            return
        if isinstance(node[0], nodes.image):
            return
        if isinstance(node.parent, addnodes.desc_type):
            return
        name = node.get('name', node.astext()).strip()
        if node.get('refid'):
            self.add_xref(node['refid'], name, node)
            raise nodes.SkipNode
        if not node.get('refuri'):
            self.document.reporter.error("Unknown reference type: %s" % node)
            return
        uri = node['refuri']
        if uri.startswith('#'):
            self.add_xref(uri[1:], name, node)
        elif uri.startswith('%'):
            id = uri[1:]
            if '#' in id:
                src, id = uri[1:].split('#', 1)
            self.add_xref(id, name, node)
        elif uri.startswith('mailto:'):
            uri = escape_arg(uri[7:])
            name = escape_arg(name)
            if not name or name == uri:
                self.add_text('@email{%s}' % uri)
            else:
                self.add_text('@email{%s,%s}' % (uri, name))
        elif uri.startswith('info:'):
            uri = uri[5:].replace('_', ' ')
            uri = escape_arg(uri)
            id = 'Top'
            if '#' in uri:
                uri, id = uri.split('#', 1)
            id = escape_id(id)
            name = escape_menu(name)
            if name == id:
                self.add_text('@pxref{%s,,,%s}' % (id, uri))
            else:
                self.add_text('@pxref{%s,,%s,%s}' % (id, name, uri))
        else:
            uri = escape_arg(uri)
            name = escape_arg(name)
            if not name or uri == name:
                self.add_text('@indicateurl{%s}' % uri)
            else:
                self.add_text('@uref{%s,%s}' % (uri, name))
        raise nodes.SkipNode

    def depart_reference(self, node):
        pass

    def visit_title_reference(self, node):
        text = node.astext()
        self.add_text('@cite{%s}' % escape_arg(text))
        raise nodes.SkipNode
    def depart_title_reference(self, node):
        pass

    ## Blocks

    def visit_paragraph(self, node):
        if 'continued' in node or isinstance(node.parent, nodes.compound):
            self.add_text('@noindent\n', fresh=1)
    def depart_paragraph(self, node):
        self.add_text('\n\n')

    def visit_block_quote(self, node):
        self.rstrip()
        self.add_text('\n\n@quotation\n')
    def depart_block_quote(self, node):
        self.rstrip()
        self.add_text('\n@end quotation\n\n')

    def visit_literal_block(self, node):
        self.rstrip()
        self.add_text('\n\n@example\n')
    def depart_literal_block(self, node):
        self.rstrip()
        self.add_text('\n@end example\n\n'
                      '@noindent\n')

    visit_doctest_block = visit_literal_block
    depart_doctest_block = depart_literal_block

    def visit_line_block(self, node):
        self.add_text('@display\n', fresh=1)
    def depart_line_block(self, node):
        self.add_text('@end display\n', fresh=1)

    def visit_line(self, node):
        self.rstrip()
        self.add_text('\n')
        self.escape_newlines += 1
    def depart_line(self, node):
        self.add_text('@w{ }\n')
        self.escape_newlines -= 1

    ## Inline

    def visit_strong(self, node):
        self.add_text('@strong{')
    def depart_strong(self, node):
        self.add_text('}')

    def visit_emphasis(self, node):
        self.add_text('@emph{')
    def depart_emphasis(self, node):
        self.add_text('}')

    def visit_literal(self, node):
        self.add_text('@code{')
    def depart_literal(self, node):
        self.add_text('}')

    def visit_superscript(self, node):
        self.add_text('@w{^')
    def depart_superscript(self, node):
        self.add_text('}')

    def visit_subscript(self, node):
        self.add_text('@w{[')
    def depart_subscript(self, node):
        self.add_text(']}')

    ## Footnotes

    def visit_footnote(self, node):
        self.visit_block_quote(node)
    def depart_footnote(self, node):
        self.depart_block_quote(node)

    def visit_footnote_reference(self, node):
        self.add_text('@w{(')
    def depart_footnote_reference(self, node):
        self.add_text(')}')

    visit_citation = visit_footnote
    depart_citation = depart_footnote

    def visit_citation_reference(self, node):
        self.add_text('@w{[')
    def depart_citation_reference(self, node):
        self.add_text(']}')

    ## Lists

    def visit_bullet_list(self, node):
        bullet = node.get('bullet', '*')
        self.rstrip()
        self.add_text('\n\n@itemize %s\n' % bullet)
    def depart_bullet_list(self, node):
        self.rstrip()
        self.add_text('\n@end itemize\n\n')

    def visit_enumerated_list(self, node):
        # Doesn't support Roman numerals
        enum = node.get('enumtype', 'arabic')
        starters = {'arabic': '',
                    'loweralpha': 'a',
                    'upperalpha': 'A',}
        start = node.get('start', starters.get(enum, ''))
        self.rstrip()
        self.add_text('\n\n@enumerate %s\n' % start)
    def depart_enumerated_list(self, node):
        self.rstrip()
        self.add_text('\n@end enumerate\n\n')

    def visit_list_item(self, node):
        self.rstrip()
        self.add_text('\n@item\n')
    def depart_list_item(self, node):
        pass

    ## Option List

    def visit_option_list(self, node):
        self.add_text('\n@table @option\n')
    def depart_option_list(self, node):
        self.rstrip()
        self.add_text('\n@end table\n\n')

    def visit_option_list_item(self, node):
        pass
    def depart_option_list_item(self, node):
        pass

    def visit_option_group(self, node):
        self.at_item_x = '@item'
    def depart_option_group(self, node):
        pass

    def visit_option(self, node):
        self.add_text(self.at_item_x + ' ', fresh=1)
        self.at_item_x = '@itemx'
    def depart_option(self, node):
        pass

    def visit_option_string(self, node):
        pass
    def depart_option_string(self, node):
        pass

    def visit_option_argument(self, node):
        self.add_text(node.get('delimiter', ' '))
    def depart_option_argument(self, node):
        pass

    def visit_description(self, node):
        self.add_text('', fresh=1)
    def depart_description(self, node):
        pass

    ## Definitions

    def visit_definition_list(self, node):
        self.add_text('\n@table @asis\n')
    def depart_definition_list(self, node):
        self.rstrip()
        self.add_text('\n@end table\n\n')

    def visit_definition_list_item(self, node):
        self.at_item_x = '@item'
    def depart_definition_list_item(self, node):
        pass

    def visit_term(self, node):
        if node.get('ids') and node['ids'][0]:
            self.add_anchor(node['ids'][0], node)
        self.add_text(self.at_item_x + ' ', fresh=1)
        self.at_item_x = '@itemx'
    def depart_term(self, node):
        pass

    def visit_termsep(self, node):
        self.add_text(self.at_item_x + ' ', fresh=1)

    def visit_classifier(self, node):
        self.add_text(' : ')
    def depart_classifier(self, node):
        pass

    def visit_definition(self, node):
        self.add_text('', fresh=1)
    def depart_definition(self, node):
        pass

    ## Tables

    def visit_table(self, node):
        self.entry_sep = '@item'
    def depart_table(self, node):
        self.rstrip()
        self.add_text('\n@end multitable\n\n')

    def visit_tabular_col_spec(self, node):
        pass
    def depart_tabular_col_spec(self, node):
        pass

    def visit_colspec(self, node):
        self.colwidths.append(node['colwidth'])
        if len(self.colwidths) != self.n_cols:
            return
        self.add_text('@multitable ', fresh=1)
        for i, n in enumerate(self.colwidths):
            self.add_text('{%s} ' %('x' * (n+2)))
    def depart_colspec(self, node):
        pass

    def visit_tgroup(self, node):
        self.colwidths = []
        self.n_cols = node['cols']
    def depart_tgroup(self, node):
        pass

    def visit_thead(self, node):
        self.entry_sep = '@headitem'
    def depart_thead(self, node):
        pass

    def visit_tbody(self, node):
        pass
    def depart_tbody(self, node):
        pass

    def visit_row(self, node):
        pass
    def depart_row(self, node):
        self.entry_sep = '@item'

    def visit_entry(self, node):
        self.rstrip()
        self.add_text('\n%s ' % self.entry_sep)
        self.entry_sep = '@tab'
    def depart_entry(self, node):
        for i in xrange(node.get('morecols', 0)):
            self.add_text('@tab\n', fresh=1)
        self.add_text('', fresh=1)

    ## Field Lists

    def visit_field_list(self, node):
        self.add_text('\n@itemize @w\n')
    def depart_field_list(self, node):
        self.rstrip()
        self.add_text('\n@end itemize\n\n')

    def visit_field(self, node):
        if not isinstance(node.parent, nodes.field_list):
            self.visit_field_list(None)
    def depart_field(self, node):
        if not isinstance(node.parent, nodes.field_list):
            self.depart_field_list(None)

    def visit_field_name(self, node):
        self.add_text('@item ', fresh=1)
    def depart_field_name(self, node):
        self.add_text(':')

    def visit_field_body(self, node):
        self.add_text('', fresh=1)
    def depart_field_body(self, node):
        pass

    ## Admonitions

    def visit_admonition(self, node):
        title = escape(node[0].astext())
        self.add_text('\n@cartouche\n'
                       '@quotation %s\n' % title)
    def depart_admonition(self, node):
        self.rstrip()
        self.add_text('\n@end quotation\n'
                       '@end cartouche\n\n')

    def _make_visit_admonition(typ):
        def visit(self, node):
            title = escape(typ)
            self.add_text('\n@cartouche\n'
                          '@quotation %s\n' % title)
        return visit

    visit_attention = _make_visit_admonition('Attention')
    visit_caution   = _make_visit_admonition('Caution')
    visit_danger    = _make_visit_admonition('Danger')
    visit_error     = _make_visit_admonition('Error')
    visit_important = _make_visit_admonition('Important')
    visit_note      = _make_visit_admonition('Note')
    visit_tip       = _make_visit_admonition('Tip')
    visit_hint      = _make_visit_admonition('Hint')
    visit_warning   = _make_visit_admonition('Warning')

    depart_attention = depart_admonition
    depart_caution   = depart_admonition
    depart_danger    = depart_admonition
    depart_error     = depart_admonition
    depart_important = depart_admonition
    depart_note      = depart_admonition
    depart_tip       = depart_admonition
    depart_hint      = depart_admonition
    depart_warning   = depart_admonition

    ## Misc

    def visit_docinfo(self, node):
        # No 'docinfo_xform'
        raise nodes.SkipNode

    def visit_topic(self, node):
        # Ignore TOC's since we have to have a "menu" anyway
        if 'contents' in node.get('classes', []):
            raise nodes.SkipNode
        title = node[0]
        self.visit_rubric(title)
        self.add_text('%s\n' % escape(title.astext()))
        self.visit_block_quote(node)
    def depart_topic(self, node):
        self.depart_block_quote(node)

    def visit_generated(self, node):
        raise nodes.SkipNode
    def depart_generated(self, node):
        pass

    def visit_transition(self, node):
        self.add_text('\n\n@noindent\n'
                      '@exdent @w{%s}\n\n'
                      '@noindent\n' % ('_' * 70))
    def depart_transition(self, node):
        pass

    def visit_attribution(self, node):
        self.add_text('@flushright\n', fresh=1)
    def depart_attribution(self, node):
        self.add_text('@end flushright\n', fresh=1)

    def visit_raw(self, node):
        format = node.get('format', '').split()
        if 'texinfo' in format or 'texi' in format:
            self.add_text(node.astext())
        raise nodes.SkipNode
    def depart_raw(self, node):
        pass

    def visit_figure(self, node):
        self.add_text('\n@float Figure\n')
    def depart_figure(self, node):
        self.rstrip()
        self.add_text('\n@end float\n\n')

    def visit_caption(self, node):
        if not isinstance(node.parent, nodes.figure):
            self.document.reporter.warning('Caption not inside a figure.',
                                           base_node=node)
            return
        self.add_text('@caption{', fresh=1)
    def depart_caption(self, node):
        if isinstance(node.parent, nodes.figure):
            self.rstrip()
            self.add_text('}\n')

    def visit_image(self, node):
        if node['uri'] in self.builder.images:
            uri = self.builder.images[node['uri']]
        else:
            # missing image!
            if self.ignore_missing_images:
                return
            uri = node['uri']
        if uri.find('://') != -1:
            # ignore remote images
            return
        name, ext = path.splitext(uri)
        attrs = node.attributes
        # ignored in non-tex output
        width = self.tex_image_length(attrs.get('width', ''))
        height = self.tex_image_length(attrs.get('height', ''))
        alt = escape_arg(attrs.get('alt', ''))
        self.add_text('\n\n@image{%s,%s,%s,%s,%s}\n\n' %
                      (name, width, height, alt, ext[1:]))
    def depart_image(self, node):
        pass

    def visit_compound(self, node):
        pass
    def depart_compound(self, node):
        pass

    def visit_sidebar(self, node):
        pass
    def depart_sidebar(self, node):
        pass

    def visit_label(self, node):
        self.add_text('@w{(')
    def depart_label(self, node):
        self.add_text(')} ')

    def visit_legend(self, node):
        pass
    def depart_legend(self, node):
        pass

    def visit_substitution_reference(self, node):
        pass
    def depart_substitution_reference(self, node):
        pass

    def visit_substitution_definition(self, node):
        raise nodes.SkipNode
    def depart_substitution_definition(self, node):
        pass

    def visit_system_message(self, node):
        self.add_text('\n\n@w{----------- System Message: %s/%s -----------} '
                      '(%s, line %s)\n' % (
                node.get('type', '?'),
                node.get('level', '?'),
                escape(node.get('source', '?')),
                node.get('line', '?')))
    def depart_system_message(self, node):
        pass

    def visit_comment(self, node):
        for line in node.astext().splitlines():
            self.add_text('@c %s\n' % line, fresh=1)
        raise nodes.SkipNode

    def visit_problematic(self, node):
        self.add_text('>')
    def depart_problematic(self, node):
        self.add_text('<')

    def unimplemented_visit(self, node):
        self.document.reporter.error("Unimplemented node type: `%s'"
                                     % node.__class__.__name__, base_node=node)

    def unknown_visit(self, node):
        self.document.reporter.error("Unknown node type: `%s'"
                                     % node.__class__.__name__, base_node=node)
    def unknown_departure(self, node):
        pass

    ### Sphinx specific

    def visit_productionlist(self, node):
        self.visit_literal_block(None)
        names = []
        for production in node:
            names.append(production['tokenname'])
        maxlen = max(len(name) for name in names)
        for production in node:
            if production['tokenname']:
                s = production['tokenname'].ljust(maxlen) + ' ::='
                lastname = production['tokenname']
            else:
                s = '%s    ' % (' '*len(lastname))
            self.add_text(escape(s))
            self.add_text(escape(production.astext() + '\n'))
        self.depart_literal_block(None)
        raise nodes.SkipNode
    def depart_productionlist(self, node):
        pass

    def visit_literal_emphasis(self, node):
        self.add_text('@code{')
    def depart_literal_emphasis(self, node):
        self.add_text('}')

    def visit_module(self, node):
        modname = escape_id(node['modname'])
        self.add_anchor(modname, node)

    def visit_index(self, node):
        # Throws off table alignment
        if isinstance(node.parent, nodes.term):
            return
        for entry in node['entries']:
            typ, text, tid, text2 = entry
            text = escape_menu(text)
            self.add_text('@geindex %s\n' % text, fresh=1)

    def visit_autosummary_table(self, node):
        pass
    def depart_autosummary_table(self, node):
        pass

    def visit_todo_node(self, node):
        self.visit_transition(node)
        self.visit_admonition(node)
    def depart_todo_node(self, node):
        self.depart_admonition(node)
        self.visit_transition(node)

    def visit_refcount(self, node):
        self.add_text('\n')
    def depart_refcount(self, node):
        self.add_text('\n\n')

    def visit_versionmodified(self, node):
        intro = versionlabels[node['type']] % node['version']
        if node.children:
            intro += ': '
        else:
            intro += '.'
        self.add_text('%s' % escape(intro), fresh=1)
    def depart_versionmodified(self, node):
        self.rstrip()
        self.add_text('\n\n', fresh=1)

    def visit_start_of_file(self, node):
        self.curfilestack.append(node.get('docname', ''))
        if node.get('docname'):
            self.next_section_targets.append(node['docname'])
    def depart_start_of_file(self, node):
        self.curfilestack.pop()

    def visit_centered(self, node):
        txt = escape_arg(node.astext())
        self.add_text('@center %s\n' % txt, fresh=1)
        raise nodes.SkipNode
    def depart_centered(self, node):
        pass

    def visit_seealso(self, node):
        pass
    def depart_seealso(self, node):
        pass

    def visit_meta(self, node):
        raise nodes.SkipNode
    def depart_meta(self, node):
        pass

    def visit_glossary(self, node):
        pass
    def depart_glossary(self, node):
        pass

    def visit_acks(self, node):
        pass
    def depart_acks(self, node):
        pass

    def visit_highlightlang(self, node):
        pass
    def depart_highlightlang(self, node):
        pass

    ## Desc

    desc_map = {
        'function' : 'Function',
        'class': 'Class',
        'method': 'Method',
        'classmethod': 'Class Method',
        'staticmethod': 'Static Method',
        'exception': 'Exception',
        'data': 'Data',
        'attribute': 'Attribute',
        'opcode': 'Opcode',
        'cfunction': 'C Function',
        'cmember': 'C Member',
        'cmacro': 'C Macro',
        'ctype': 'C Type',
        'cvar': 'C Variable',
        'cmdoption': 'Option',
        'describe': 'Description',
        }

    def visit_desc(self, node):
        self.at_deffnx = '@deffn'
    def depart_desc(self, node):
        self.rstrip()
        self.add_text('@end deffn\n\n', fresh=1)
    def visit_desc_signature(self, node):
        self.desctype = node.parent['desctype'].strip()
        if self.desctype != 'describe' and node['ids']:
            self.add_anchor(node['ids'][0], node)
        typ = self.desc_map.get(self.desctype, self.desctype)
        self.add_text('%s {%s} ' % (self.at_deffnx, escape_arg(typ)), fresh=1)
        self.at_deffnx = '@deffnx'
    def depart_desc_signature(self, node):
        self.add_text("", fresh=1)

    def visit_desc_name(self, node):
        pass
    def depart_desc_name(self, node):
        pass

    def visit_desc_addname(self, node):
        pass
    def depart_desc_addname(self, node):
        pass

    def visit_desc_type(self, node):
        pass
    def depart_desc_type(self, node):
        pass

    def visit_desc_returns(self, node):
        self.add_text(' -> ')
    def depart_desc_returns(self, node):
        pass

    def visit_desc_parameterlist(self, node):
        self.add_text(' (')
        self.first_param = 1
    def depart_desc_parameterlist(self, node):
        self.add_text(')')

    def visit_desc_parameter(self, node):
        if not self.first_param:
            self.add_text(', ')
        else:
            self.first_param = 0
        self.add_text(escape(node.astext()))
        raise nodes.SkipNode
    def depart_desc_parameter(self, node):
        pass

    def visit_desc_optional(self, node):
        self.add_text('[')
    def depart_desc_optional(self, node):
        self.add_text(']')

    def visit_desc_annotation(self, node):
        raise nodes.SkipNode
    def depart_desc_annotation(self, node):
        pass

    def visit_desc_content(self, node):
        self.add_text("", fresh=1)
    def depart_desc_content(self, node):
        pass

    def visit_inline(self, node):
        # stub
        pass
    def depart_inline(self, node):
        pass

    def visit_abbreviation(self, node):
        self.add_text('@abbr{')
        if node.hasattr('explanation'):
            self.context.append(', %s}' % escape_arg(node['explanation']))
        else:
            self.context.append('}')
    def depart_abbreviation(self, node):
        self.body.append(self.context.pop())

    def visit_download_reference(self, node):
        pass
    def depart_download_reference(self, node):
        pass

    def visit_hlist(self, node):
        # stub
        self.visit_bullet_list(node)
    def depart_hlist(self, node):
        self.depart_bullet_list(node)

    def visit_hlistcol(self, node):
        pass
    def depart_hlistcol(self, node):
        pass
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.