Source

moin-2.0 / MoinMoin / converter / docbook_in.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
# Copyright: 2010 MoinMoin:ValentinJaniaut
# License: GNU GPL v2 (or any later version), see LICENSE.txt for details.

"""
MoinMoin - DocBook input converter
Converts a DocBook document into an internal document tree.

Currently supports DocBook v5.

Some elements of DocBook v4 specification are also supported
for backward compatibility:

- ulink
"""


from __future__ import absolute_import, division

import re

from emeraldtree import ElementTree as ET

from MoinMoin import log
logging = log.getLogger(__name__)

from MoinMoin.util.tree import moin_page, xlink, docbook, xml, html

from ._wiki_macro import ConverterMacro
from ._util import allowed_uri_scheme, decode_data, normalize_split_text


class NameSpaceError(Exception):
    pass

class Converter(object):
    """
    Converter application/docbook+xml -> x.moin.document
    """
    # Namespace of our input data
    docbook_namespace = {
        docbook.namespace: 'docbook'
    }

    # DocBook elements which are completely ignored by our converter
    # We even do not process children of these elements
    ignored_tags = set([# Info elements
                       'abstract', 'artpagenums', 'annotation',
                       'artpagenums', 'author', 'authorgroup',
                       'authorinitials', 'bibliocoverage', 'biblioid',
                       'bibliomisc', 'bibliomset', 'bibliorelation',
                       'biblioset', 'bibliosource', 'collab', 'confdates',
                       'confgroup', 'confnum', 'confsponsor', 'conftitle',
                       'contractnum', 'contractsponsor', 'copyright',
                       'contrib', 'cover', 'edition', 'editor',
                       'extendedlink', 'issuenum', 'itermset', 'keyword',
                       'keywordset', 'legalnotice', 'org', 'orgname',
                       'orgdiv', 'otheraddr', 'othercredit', 'pagenums',
                       'personblurb', 'printhistory', 'productname',
                       'productnumber', 'pubdate', 'publisher',
                       'publishername', 'releaseinfo', 'revdescription',
                       'revhistory', 'revision', 'revnumber', 'revremark',
                       'seriesvolnums', 'subjectset', 'volumenum',
                       # Other bibliography elements
                       'bibliodiv', 'biblioentry', 'bibliography',
                       'bibliolist', 'bibliomixed', 'biblioref',
                       'bibliorelation', 'citation', 'citerefentry',
                       'citetitle',
                       # Callout elements
                       'callout', 'calloutlist', 'area', 'areaset',
                       'areaspec', 'co', 'imageobjectco',
                       # Class information
                       'classname', 'classsynopsis', 'classsynopsisinfo',
                       'constructorsynopsis', 'destructorsynopsis',
                       'fieldsynopsis', 'funcdef', 'funcparams',
                       'funcprototype', 'funcsynopsis',
                       'funcsynopsisinfo', 'function', 'group',
                       'initializer', 'interfacename',
                       'methodname', 'methodparam', 'methodsynopsis',
                       'ooclass', 'ooexception', 'oointerface', 'varargs',
                       'void',
                       # GUI elements
                       'guibutton', 'guiicon', 'guilabel',
                       'guimenu', 'guimenuitem', 'guisubmenu',
                       # EBNF Elements
                       'constraint', 'constraintdef', 'lhs', 'rhs',
                       'nonterminal',
                       # msg elements
                       'msg', 'msgaud', 'msgentry', 'msgexplan',
                       'msginfo', 'msglevel', 'msgmain', 'msgorig',
                       'msgrel', 'msgset', 'msgsub', 'msgtext',
                       # REF entry
                       'refclass', 'refdescriptor', 'refentry',
                       'refentrytitle', 'reference', 'refmeta',
                       'refmiscinfo', 'refname', 'refnamediv',
                       'refpurpose', 'refsect1', 'refsect2', 'refsect3',
                       'refsection', 'refsynopsisdiv'
                       # TOC
                       'toc', 'tocdiv', 'tocentry',
                       # Index elements
                       'index', 'indexdiv', 'indexentry', 'indexterm',
                       'primary', 'primaryie', 'secondary',
                       'secondaryie', 'see', 'seealso',
                       'tertiary', 'tertiaryie',
                       # Other elements
                       'info', 'bridgehead', 'arc', 'titleabbrev',
                       'spanspec', 'xref',
                       ])

    # DocBook inline elements which does not have equivalence in the DOM
    # tree, but we keep the information using <span element='tag.name'>
    inline_tags = set(['abbrev', 'address', 'accel', 'acronym', 'alt',
                       'affiliation', 'city', 'command', 'constant',
                       'country', 'database', 'date', 'errorcode',
                       'errorname', 'errortext', 'errortype',
                       'exceptionname', 'fax', 'filename', 'firstname',
                       'firstterm', 'foreignphrase', 'hardware', 'holder',
                       'honorific', 'jobtitle', 'keycap', 'keycode',
                       'keycombo', 'keysym', 'lineannotation',
                       'manvolnum', 'mousebutton', 'option', 'optional',
                       'package', 'person', 'personname', 'phone', 'pob',
                       'postcode', 'prompt', 'remark', 'replaceable',
                       'returnvalue', 'shortaffil', 'shortcut', 'state',
                       'street', 'surname', 'symbol', 'systemitem',
                       'termdef', 'type', 'uri', 'userinput',
                       'wordasword', 'varname', 'anchor',
                       ])

    # DocBook block element which does not have equivalence in the DOM
    # tree, but we keep the information using <div html:class='tag.name'>
    block_tags = set(['acknowledgements', 'appendix', 'article', 'book',
                      'caption', 'chapter', 'cmdsynopsis', 'colophon',
                      'dedication', 'epigraph', 'example', 'figure',
                      'equation', 'part', 'partintro',
                      'screenshoot', 'set', 'setindex', 'sidebar',
                      'simplesect', 'subtitle', 'synopsis',
                      'synopfragment', 'task', 'taskprerequisites',
                      'taskrelated', 'tasksummary', 'title',
                     ])

    # DocBook has admonition as individual element, but the DOM Tree
    # has only one element for it, so we will convert all the DocBook
    # admonitions in this list, into the admonition element of the DOM Tree.
    admonition_tags = set(['caution', 'important', 'note', 'tip', 'warning'])

    # DocBook can handle three kind of media: audio, image, video. Here
    # is an helper dictionary to process such of element.
    media_tags = {'audioobject': (['wav', 'mp3', 'ogg'],
                                 'audiodata',
                                 'audio/',
                                 ),
                  'imageobject': (['gif', 'png', 'jpg', 'png'],
                                 'imagedata',
                                 'image/',
                                 ),
                  'videoobject': (['ogg', 'avi', 'mp4'],
                                 'videodata',
                                 'video/',
                                 )}

    # DocBook tags which can be convert directly to a DOM Tree element
    simple_tags = {'code': moin_page.code,
                   'computeroutput': moin_page.code,
                   'entry': moin_page('table-cell'),
                   'glossdef': moin_page('list-item-body'),
                   'glossentry': moin_page('list-item'),
                   'glosslist': moin_page('list'),
                   'glossterm': moin_page('list-item-label'),
                   'literal': moin_page.code,
                   'markup': moin_page.code,
                   'para': moin_page.p,
                   'phrase': moin_page.span,
                   'programlisting': moin_page.blockcode,
                   'quote': moin_page.quote,
                   'row': moin_page('table-row'),
                   'screen': moin_page.blockcode,
                   'simpara': moin_page.p,
                   'term': moin_page('list-item-label'),
                   'listitem': moin_page('list-item-body'),
                   'thead': moin_page('table-header'),
                   'tfoot': moin_page('table-footer'),
                   'tbody': moin_page('table-body'),
                   'tr': moin_page('table-row'),
                   'variablelist': moin_page('list'),
                   'varlistentry': moin_page('list-item'),
    }

    # Other block elements which can be root element.
    root_tags = set(['blockquote', 'formalpara', 'informalequation',
                     'informalexample', 'informalfigure',
                     'informalfigure', 'orderedlist', 'sect1', 'sect2',
                     'sect3', 'sect4', 'sect5', 'section',
                     'segmentedlist', 'simplelist', 'procedure',
                     'qandaset',
    ])

    # Regular expression to find section tag.
    sect_re = re.compile('sect[1-5]')

    @classmethod
    def _factory(cls, input, output, **kw):
        return cls()

    def __call__(self, data, contenttype=None, arguments=None):
        text = decode_data(data, contenttype)
        content = normalize_split_text(text)
        docbook_str = u'\n'.join(content)
        logging.debug(docbook_str)

        # Initalize our attributes
        self.section_depth = 0
        self.heading_level = 0
        self.is_section = False

        # We store the standard attributes of an element.
        # Once we have been able to put it into an output element,
        # we clear this attribute.
        self.standard_attribute = {}

        # We will create an element tree from the DocBook content
        try:
            # XXX: The XML parser need bytestring.
            tree = ET.XML(docbook_str.encode('utf-8'))
        except ET.ParseError as detail:
            return self.error(str(detail))

        try:
            if tree.tag.name in self.block_tags:
                return self.start_dom_tree(tree, 0)
            else:
                # XXX: Internationalization
                return self.error("The root element of the docbook document is not supported by the converter")
        # XXX: Error handling could probably be better.
        except NameSpaceError as detail:
            return self.error(str(detail))

    def error(self, message):
        """
        Return a DOM Tree containing an error message.
        """
        error = self.new(moin_page('error'), attrib={}, children=[message])
        part = self.new(moin_page('part'), attrib={}, children=[error])
        body = self.new(moin_page('body'), attrib={}, children=[part])
        return self.new(moin_page('page'), attrib={}, children=[body])

    def do_children(self, element, depth):
        """
        Function to process the conversion of the children of
        a given element.
        """
        new_children = []
        depth = depth + 1
        for child in element:
            if isinstance(child, ET.Element):
                r = self.visit(child, depth)
                if r is None:
                    r = ()
                elif not isinstance(r, (list, tuple)):
                    r = (r, )
                new_children.extend(r)
            else:
                new_children.append(child)
        return new_children

    def new(self, tag, attrib, children):
        """
        Return a new element for the DocBook Tree.
        """
        if self.standard_attribute:
            attrib.update(self.standard_attribute)
            self.standard_attribute = {}
        return ET.Element(tag, attrib=attrib, children=children)

    def new_copy(self, tag, element, depth, attrib):
        """
        Function to copy one element to the DocBook Tree.

        It first converts the children of the element,
        and then the element itself.
        """
        children = self.do_children(element, depth)
        return self.new(tag, attrib, children)

    def get_standard_attributes(self, element):
        """
        We will extract the standard attributes of the element, if any.
        We save the result in our standard attribute.
        """
        result = {}
        for key, value in element.attrib.iteritems():
            if key.uri == xml \
              and key.name in ['id', 'base', 'lang']:
                result[key] = value
        if result:
            # We clear standard_attribute, if ancestror attribute
            # was stored and has not been written in to the output,
            # anyway the new standard attributes will get higher priority
            self.standard_attribute = result

    def visit(self, element, depth):
        """
        Function called at each element, to process it.

        It will just determine the namespace of our element,
        then call a dedicated function to handle conversion
        for the given namespace.
        """
        uri = element.tag.uri
        name = self.docbook_namespace.get(uri, None)
        if name is not None:
            method_name = 'visit_' + name
            method = getattr(self, method_name, None)
            if method is not None:
                return method(element, depth)

        # We did not recognize the namespace, we stop the conversion.
        raise NameSpaceError("Unknown namespace")

    def visit_docbook(self, element, depth):
        """
        Function called to handle the conversion of DocBook elements
        to the moin_page DOM Tree.

        We will detect the name of the tag, and pick up the correct method
        to convert it.
        """
        # Save the standard attribute of the element
        self.get_standard_attributes(element)

        # We have a section tag
        if self.sect_re.match(element.tag.name):
            result = []
            result.append(self.visit_docbook_sect(element, depth))
            result.extend(self.do_children(element, depth))
            return result

        # We have an inline element without equivalence in the DOM Tree
        if element.tag.name in self.inline_tags:
            return self.visit_docbook_inline(element, depth)

        # We have a block element without equivalence in the DOM Tree
        if element.tag.name in self.block_tags:
            return self.visit_docbook_block(element, depth)

        # We have an element easy to convert
        if element.tag.name in self.simple_tags:
            return self.visit_simple_tag(element, depth)

        # We have a media element
        #if element.tag.name in self.media_tags:
        #    return self.visit_data_object(element, depth)

        # We should ignore this element
        if element.tag.name in self.ignored_tags:
            logging.warning("Ignored tag:{0}".format(element.tag.name))
            return

        # We have an admonition element
        if element.tag.name in self.admonition_tags:
            return self.visit_docbook_admonition(element, depth)

        # We will find the correct method to handle our tag
        method_name = 'visit_docbook_' + element.tag.name
        method = getattr(self, method_name, None)
        if method:
            return method(element, depth)

        # Otherwise we process children of the unknown element
        # XXX: We should probably raise an error to have a strict converter
        return self.do_children(element, depth)

    def visit_data_object(self, element, depth):
        """
        We need to determine which object we can display.
        If we are not able to display an object,
        we will try to display a text.
        TODO: See for a preference list between image, data, audio
        """
        prefered_format, data_tag, mimetype = ('', '', '')
        object_data = []
        text_object = []
        caption = []
        object_element = ''
        for child in element:
            if isinstance(child, ET.Element):
                if child.tag.name in self.media_tags:
                    #XXX: Check the spec to be sure that object tag have only one child.
                    #TODO: Better way to do it
                    prefered_format, data_tag, mimetype = self.media_tags[child.tag.name]
                    object_element = child
                    for grand_child in child:
                        if isinstance(grand_child, ET.Element):
                            object_data.append(grand_child)
                if child.tag.name == 'caption':
                    caption = self.do_children(child, depth+1)[0]
                if child.tag.name == 'textobject':
                    text_object = child
        return self.visit_data_element(object_element, depth, object_data,
            text_object, caption)

    def visit_data_element(self, element, depth, object_data,
                           text_object, caption):
        """
        We will try to return an object element based on the
        object_data. If it is not possible, we return a paragraph
        with the content of text_object.
        """
        attrib = {}
        prefered_format, data_tag, mimetype = self.media_tags[element.tag.name]
        if not object_data:
            if not text_object:
                return
            else:
                children = self.do_children(child, depth+1)[0]
                return self.new(moin_page.p, attrib={},
                                children=children)
        # We try to determine the best object to show
        object_to_show = None
        for obj in object_data:
            format = obj.get('format')
            if format:
                format = format.lower()
                if format in prefered_format:
                    object_to_show = obj
                    break
            else:
                #XXX: Maybe we could add some verification over the
                #     extension of the file
                object_to_show = obj

        # If we could not find any suitable object, we return
        # the text replacement.
        if not object_to_show:
            children = self.do_children(child, depth+1)[0]
            return self.new(moin_page.p, attrib={},
                            children=children)

        href = object_to_show.get('fileref')
        if not href:
            # We could probably try to use entityref,
            # but at this time we won't support it.
            return
        attrib[xlink.href] = href
        format = object_to_show.get('format')
        if format:
            format = format.lower()
            attrib[moin_page('type')] = ''.join([mimetype, format])
        else:
            attrib[moin_page('type')] = mimetype
        return ET.Element(moin_page.object, attrib=attrib)

    def visit_docbook_admonition(self, element, depth):
        """
        <tag.name> --> <admonition tye='tag.name'>
        """
        attrib = {}
        key = moin_page('type')
        attrib[key] = element.tag.name
        return self.new_copy(moin_page.admonition, element,
                             depth, attrib=attrib)

    def visit_docbook_block(self, element, depth):
        """
        Convert a block element which does not have equivalence
        in the DOM Tree.

        <tag.name> --> <div html:class="db-tag.name">
        """
        attrib = {}
        key = html('class')
        attrib[key] = ''.join(['db-', element.tag.name])
        return self.new_copy(moin_page.div, element,
                             depth, attrib=attrib)

    def visit_docbook_blockquote(self, element, depth):
        """
        <blockquote>
          <attribution>Author</attribution>
          Text
        </blockquote>
          --> <blockquote source="Author">Text</blockquote>

        <blockquote>Text</blockquote>
          --> <blockquote source="Unknow">Text</blockquote>
        """
        # TODO: Translate
        source = u"Unknow"
        children = []
        for child in element:
            if isinstance(child, ET.Element):
                if child.tag.name == "attribution":
                    source = self.do_children(child, depth+1)
                else:
                    children.extend(self.do_children(child, depth+1))
            else:
                children.append(child)
        attrib = {}
        attrib[moin_page('source')] = source[0]
        return self.new(moin_page.blockquote, attrib=attrib, children=children)

    def visit_docbook_emphasis(self, element, depth):
        """
        emphasis element, is the only way to apply some style
        on a DocBook element directly from the DocBook tree.

        Basically, you can use it for "italic" and "bold" style.

        However, it is still semantic, so we call it emphasis and strong.
        """
        for key, value in element.attrib.iteritems():
            if key.name == 'role' and value == 'strong':
                return self.new_copy(moin_page.strong, element,
                                     depth, attrib={})
        return self.new_copy(moin_page.emphasis, element,
                             depth, attrib={})

    def visit_docbook_entrytbl(self, element, depth):
        """
        Return a table within a table-cell.
        """
        table_element = self.new_copy(moin_page.table, element,
                                      depth, attrib={})
        return self.new(moin_page('table-cell'),
                        attrib={}, children=[table_element])

    def visit_docbook_footnote(self, element, depth):
        """
        <footnote> --> <note note-class="footnote"><note-body>
        """
        attrib = {}
        key = moin_page('note-class')
        attrib[key] = "footnote"
        children = self.new(moin_page('note-body'), attrib={},
                            children=self.do_children(element, depth))
        return self.new(moin_page.note, attrib=attrib, children=[children])

    def visit_docbook_formalpara(self, element, depth):
        """
        <formalpara>
          <title>Heading</title>
          <para>Text</para>
        </formalpara>
          --> <p html:title="Heading">Text</p>
        """
        for child in element:
            if isinstance(child, ET.Element):
                if child.tag.name == 'title':
                    title_element = child
                if child.tag.name == 'para':
                    para_element = child

        if not title_element:
            #XXX: Improve error
            raise SyntaxError("title child missing for formalpara element")
        if not para_element:
            #XXX: Improve error
            raise SyntaxError("para child missing for formalpara element")

        children = self.do_children(para_element, depth+1)[0]
        attrib = {}
        attrib[html('title')] = title_element[0]
        return self.new(moin_page.p, attrib=attrib, children=children)

    def visit_docbook_informalequation(self, element, depth):
        """
        <informalequation> --> <div html:class="equation">
        """
        attrib = {}
        attrib[html('class')] = 'db-equation'
        return self.new_copy(moin_page('div'), element,
                             depth, attrib=attrib)

    def visit_docbook_informalexample(self, element, depth):
        """
        <informalexample> --> <div html:class="example">
        """
        attrib = {}
        attrib[html('class')] = 'db-example'
        return self.new_copy(moin_page('div'), element,
                             depth, attrib=attrib)

    def visit_docbook_informalfigure(self, element, depth):
        """
        <informalfigure> --> <div html:class="figure">
        """
        attrib = {}
        attrib[html('class')] = 'db-figure'
        return self.new_copy(moin_page('div'), element,
                             depth, attrib=attrib)

    def visit_docbook_inline(self, element, depth):
        """
        For some specific tags (defined in inline_tags)
        We just return <span element="tag.name">
        """
        key = html('class')
        attrib = {}
        attrib[key] = ''.join(['db-', element.tag.name])
        return self.new_copy(moin_page.span, element,
                             depth, attrib=attrib)

    def visit_docbook_inlinequation(self, element, depth):
        """
        <inlinequation> --> <span element="equation">
        """
        attrib = {}
        attrib[moin_page('element')] = 'equation'
        return self.new_copy(moin_page.span, element,
                             depth, attrib=attrib)

    def visit_docbook_inlinemediaobject(self, element, depth):
        data_element = self.visit_data_object(element, depth)
        attrib = {html('class'): 'db-inlinemediaobject'}
        return self.new(moin_page.span, attrib=attrib,
                        children=[data_element])

    def visit_docbook_itemizedlist(self, element, depth):
        """
        <itemizedlist> --> <list item-label-generate="unordered">
        """
        attrib = {}
        key = moin_page('item-label-generate')
        attrib[key] = 'unordered'
        return self.visit_simple_list(moin_page.list, attrib,
                                      element, depth)

    def visit_docbook_link(self, element, depth):
        """
        LINK Conversion.

        There is two kind of links in DocBook :
        One using the xlink namespace.
        The other one using linkend attribute.

        The xlink attributes can directly be used in the <a> tag of the
        DOM Tree since we support xlink.

        For the linkend attribute, we need to have a system supporting
        the anchors.
        """
        attrib = {}
        for key, value in element.attrib.iteritems():
            if key.uri == xlink and allowed_uri_scheme(value):
                attrib[key] = value
        linkend = element.get('linkend')
        if linkend:
            attrib[xlink.href] = ''.join(['#', linkend])
        return self.new_copy(moin_page.a, element, depth, attrib=attrib)

    def visit_docbook_literallayout(self, element, depth):
        """
        <literallayout> --> <blockcode html:class="db-literallayout">
        """
        attrib = {html('class'): 'db-literallayout'}
        return self.new_copy(moin_page.blockcode, element,
                             depth, attrib=attrib)

    def visit_docbook_mediaobject(self, element, depth):
        data_element = self.visit_data_object(element, depth)
        attrib = {html('class'): 'db-mediaobject'}
        return self.new(moin_page.div, attrib=attrib,
                        children=[data_element])

    def visit_docbook_olink(self, element, depth):
        """
        <olink targetdoc='URI' targetptr='ptr'>
          --> <a xlink:href='URI#ptr'>
        """
        targetdoc = element.get('targetdoc')
        targetptr = element.get('targetptr')
        if targetdoc and targetptr and allowed_uri_scheme(targetdoc):
            attrib = {}
            attrib[xlink.href] = ''.join([targetdoc, '#', targetptr])
            return self.new_copy(moin_page.a, element,
                                 depth, attrib=attrib)

    def visit_docbook_orderedlist(self, element, depth):
        """
        <orderedlist> --> <list item-label-generate="ordered">
        See attribute_conversion for more details about the attributes.
        """
        attrib = {}
        key = moin_page('item-label-generate')
        attrib[key] = 'ordered'
        attribute_conversion = {"upperalpha": "upper-alpha",
                                "loweralpha": "lower-alpha",
                                "upperroman": "upper-roman",
                                "lowerroman": "lower-roman"}
        numeration = element.get('numeration')
        if numeration in attribute_conversion:
            key = moin_page('list-style-type')
            attrib[key] = attribute_conversion[numeration]
        return self.visit_simple_list(moin_page.list, attrib,
                                      element, depth)

    def visit_docbook_sbr(self, element, depth):
        """
        <sbr /> --> <line-break />
        """
        return self.new(moin_page('line-break'), attrib={}, children={})

    def visit_docbook_sect(self, element, depth):
        """
        This is the function to convert a numbered section.

        Numbered section uses tag like <sectN> where N is the number
        of the section between 1 and 5.

        The sections are supposed to be correctly nested.

        We only convert a section to an heading if one of the children
        is a title element.

        TODO: See if we can unify with recursive section below.
        TODO: Add div element, with specific id
        """
        self.is_section = True
        title = ''
        for child in element:
            if isinstance(child, ET.Element):
                uri = child.tag.uri
                name = self.docbook_namespace.get(uri, None)
                if name == 'docbook' and child.tag.name == 'title':
                    title = child
                    # Remove the title element to avoid double conversion
                    element.remove(child)
        heading_level = element.tag.name[4]
        key = moin_page('outline-level')
        attrib = {}
        attrib[key] = heading_level
        return self.new(moin_page.h, attrib=attrib, children=title)

    def visit_docbook_section(self, element, depth):
        """
        This is the function to convert recursive section.

        Recursive section use tag like <section> only.

        Each section, inside another section is a subsection.

        To convert it, we will use the depth of the element, and
        two attributes of the converter which indicate the
        current depth of the section and the current level heading.
        """
        self.is_section = True
        if depth > self.section_depth:
            self.section_depth = self.section_depth + 1
            self.heading_level = self.heading_level + 1
        elif depth < self.section_depth:
            self.heading_level = self.heading_level - (self.section_depth - depth)
            self.section_depth = depth

        title = ''
        result = []
        for child in element:
            if isinstance(child, ET.Element):
                uri = child.tag.uri
                name = self.docbook_namespace.get(uri, None)
                if name == 'docbook' and child.tag.name == 'title':
                    title = child
                    # Remove the title element to avoid double conversion
                    element.remove(child)
        key = moin_page('outline-level')
        attrib = {}
        attrib[key] = self.heading_level
        result.append(self.new(moin_page.h, attrib=attrib, children=title))
        result.extend(self.do_children(element, depth))
        return result

    def visit_docbook_seglistitem(self, element, labels, depth):
        """
        A seglistitem is a list-item for a segmented list. It is quite
        special because it act list definition with label, but the labels
        are predetermined in the labels list.

        So we generate label/body couple according to the content in
        labels
        """
        new = []
        counter = 0
        for child in element:
            if isinstance(child, ET.Element):
                if child.tag.name == 'seg':
                    label_tag = ET.Element(moin_page('list-item-label'),
                            attrib={}, children=labels[counter % len(labels)])
                    body_tag = ET.Element(moin_page('list-item-body'),
                            attrib={}, children=self.visit(child, depth))
                    item_tag = ET.Element(moin_page('list-item'),
                            attrib={}, children=[label_tag, body_tag])
                    item_tag = (item_tag, )
                    new.extend(item_tag)
                    counter = counter + 1
                else:
                    r = self.visit(child)
                    if r is None:
                        r = ()
                    elif not isinstance(r, (list, tuple)):
                        r = (r, )
                    new.extend(r)
            else:
                new.append(child)
        return new

    def visit_docbook_segmentedlist(self, element, depth):
        """
        A segmented list is a like a list of definition, but the label
        are defined at the start with <segtitle> tag and then for each
        definition, we repeat the label.

        So to convert such list, we will first determine and save the
        labels. Then we will iterate over the object to get the
        definition.
        """
        labels = []
        new = []
        for child in element:
            if isinstance(child, ET.Element):
                r = None
                if child.tag.name == 'segtitle':
                    r = self.visit(child, depth)
                    if r is None:
                        r = ()
                    elif not isinstance(r, (list, tuple)):
                        r = (r, )
                    labels.extend(r)
                else:
                    if child.tag.name == 'seglistitem':
                        r = self.visit_docbook_seglistitem(child,
                            labels, depth)
                    else:
                        r = self.visit(child)
                    if r is None:
                        r = ()
                    elif not isinstance(r, (list, tuple)):
                        r = (r, )
                    new.extend(r)
            else:
                new.append(child)
        return ET.Element(moin_page.list, attrib={}, children=new)

    def visit_docbook_simplelist(self, element, depth):
        """
        <simplelist> --> <list item-label-generate="unordered">
        """
        # TODO: Add support of the type attribute
        attrib = {}
        key = moin_page('item-label-generate')
        attrib[key] = 'unordered'
        return self.visit_simple_list(moin_page.list, attrib, element, depth)

    def visit_docbook_subscript(self, element, depth):
        """
        <subscript> --> <span baseline-shift="sub">
        """
        attrib = {}
        key = moin_page('baseline-shift')
        attrib[key] = 'sub'
        return self.new_copy(moin_page.span, element,
                             depth, attrib=attrib)

    def visit_docbook_substeps(self, element, depth):
        """
        Return the same elements than a procedure
        """
        return self.visit_docbook_procedure(element, depth)

    def visit_docbook_superscript(self, element, depth):
        """
        <superscript> --> <span baseline-shift="super">
        """
        attrib = {}
        key = moin_page('baseline-shift')
        attrib[key] = 'super'
        return self.new_copy(moin_page.span, element,
                             depth, attrib=attrib)

    def visit_docbook_procedure(self, element, depth):
        """
        <procedure> --> <list item-label-generate="ordered">
        """
        # TODO: See to add Procedure text (if needed)
        attrib = {}
        key = moin_page('item-label-generate')
        attrib[key] = 'ordered'
        return self.visit_simple_list(moin_page.list, attrib,
                                      element, depth)

    def visit_docbook_qandaset(self, element, depth):
        """
        See visit_qandaset_* method.
        """
        default_label = element.get('defaultlabel')
        if default_label == 'number':
            return self.visit_qandaset_number(element, depth)
        elif default_label == 'qanda':
            return self.visit_qandaset_qanda(element, depth)
        else:
            return self.do_children(element, depth)

    def visit_docbook_table(self, element, depth):
        """
        <table> --> <table>
        """
        # we should not have any strings in the child
        list_table_elements = []
        for child in element:
            if isinstance(child, ET.Element):
                r = self.visit(child, depth)
                if r is None:
                    r = ()
                elif not isinstance(r, (list, tuple)):
                    r = (r, )
                list_table_elements.extend(r)
        return ET.Element(moin_page.table, attrib={}, children=list_table_elements)

    def visit_docbook_tag(self, element, depth):
        """
        <tag class="class.name" namespace="ns.address">TAG</tag>
          --> <span class="db-tag-class.name">{ns.address}TAG</tag>
        """
        # We get the attributes
        class_attribute = element.get('class')
        namespace_attribute = element.get('namespace')
        # We create the attribute for our final element
        attrib = {}
        children = []
        if class_attribute:
            attrib[html('class')] = ''.join(['db-tag-',
                                        class_attribute])
        else:
            attrib[html('class')] = 'db-tag'
        if namespace_attribute:
            namespace_str = ''.join(['{', namespace_attribute, '}'])
            children.append(namespace_str)
        children.extend(self.do_children(element, depth))
        return self.new(moin_page.span, attrib=attrib, children=children)

    def visit_docbook_trademark(self, element, depth):
        """
        Depending of the trademark class, a specific entities is added
        at the end of the string.
        <trademark> --> <span element="trademark">
        """
        trademark_entities = {'copyright': '&copy;',
                              'registred': '&reg;',
                              'trade': '&trade;',
                             }
        trademark_class = element.get('class')
        children = self.do_children(element, depth)
        if trademark_class in trademark_entities:
            children.append(trademark_entities[trademark_class])
        elif trademark_class == 'service':
            sup_attrib = {moin_page('baseline-shift'): 'super'}
            service_mark = self.new(moin_page.span, attrib=sup_attrib,
                                    children=['SM'])
            children.append(service_mark)
        attrib = {html('class'): 'db-trademark'}
        return self.new(moin_page.span, attrib=attrib, children=children)

    def visit_docbook_td(self, element, depth):
        """
        <td> --> <table-cell>
        """
        attrib = {}
        rowspan = element.get('rowspan')
        colspan = element.get('colspan')
        if rowspan:
            attrib[moin_page('number-rows-spanned')] = rowspan
        if colspan:
            attrib[moin_page('number-columns-spanned')] = colspan
        return self.new_copy(moin_page.table_cell,
                             element, depth, attrib=attrib)

    def visit_docbook_ulink(self, element, depth):
        """
        NB : <ulink> is not a part of DocBook v.5 however we
        support it in our converter since it is still widely used
        and it helps to keep a compatibility with DocBook v.4
        """
        attrib = {}
        href = element.get(docbook.url)
        # Since it is an element of DocBook v.4,
        # The namespace does not always work, so we will try to retrive the attribute whatever
        if not(href):
            for key, value in element.attrib.iteritems():
                if key.name == 'url' and allowed_uri_scheme(value):
                    href = value
        key = xlink.href
        attrib[key] = href
        return self.new_copy(moin_page.a, element, depth, attrib=attrib)

    def visit_qandaentry_number(self, element, depth):
        """
        <question>Q</question><answer>A</answer>
          --> <list-item>
                <list-item-body><p>Q</p><p>A</p></list-item-body>
              </list-item>
        """
        items = []
        for child in element:
            if isinstance(child, ET.Element):
                if child.tag.name == 'question' or child.tag.name == 'answer':
                    r = self.visit(child, depth)
                    if r is None:
                        r = ()
                    elif not isinstance(r, (list, tuple)):
                        r = (r, )
                    items.extend(r)
            else:
                items.append(child)

        item_body = ET.Element(moin_page('list-item-body'), attrib={}, children=items)
        return ET.Element(moin_page('list-item'), attrib={}, children=[item_body])

    def visit_qandaset_number(self, element, depth):
        """
        <qandaset defaultlabel="number">
          --> <list item-label-generate='ordered'>
        """
        attrib = {}
        key = moin_page('item-label-generate')
        attrib[key] = 'ordered'
        items = []
        for child in element:
            if isinstance(child, ET.Element):
                if child.tag.name == 'qandaentry':
                    r = self.visit_qandaentry_number(child, depth)
                else:
                    r = self.visit(child, depth)
                if r is None:
                    r = ()
                elif not isinstance(r, (list, tuple)):
                    r = (r, )
                items.extend(r, )
            else:
                items.append(child)
        return ET.Element(moin_page('list'), attrib=attrib, children=items)

    def visit_qandaentry_qanda(self, element, depth):
        """
        <question>Q body</question><answer>A Body</answer>
        --> <list-item>
              <list-item-label>Q:</list-item-label>
              <list-item-body>Q Body</list-item-body>
            </list-item>
            <list-item>
              <list-item-label>A:</list-item-label>
              <list-item-body>A Body</list-item-body>
            </list-item>
        """
        items = []
        for child in element:
            if isinstance(child, ET.Element):
                r = ()
                item_label = None
                if child.tag.name == 'question':
                    item_label = ET.Element(moin_page('list-item-label'), attrib={}, children="Q:")
                elif child.tag.name == 'answer':
                    item_label = ET.Element(moin_page('list-item-label'), attrib={}, children="A:")
                else:
                    r = self.visit(child, depth)
                    if r is None:
                        r = ()
                    elif not isinstance(r, (list, tuple)):
                        r = (r, )
                    items.extend(r)
                if item_label is not None:
                    item_body = ET.Element(moin_page('list-item-body'), attrib={}, children=self.visit(child, depth))
                    r = (item_label, item_body)
                    list_item = ET.Element(moin_page('list-item'), attrib={}, children=r)
                    items.append(list_item)
            else:
                items.append(child)
        return items

    def visit_qandaset_qanda(self, element, depth):
        """
        <qandaset defaultlabel="qanda"> --> <list>
        """
        items = []
        for child in element:
            if isinstance(child, ET.Element):
                r = ()
                if child.tag.name == 'qandaentry':
                    r = self.visit_qandaentry_qanda(child, depth)
                else:
                    r = self.visit(child, depth)
                if r is None:
                    r = ()
                elif not isinstance(r, (list, tuple)):
                    r = (r, )
                items.extend(r)
            else:
                items.append(child)
        return ET.Element(moin_page('list'), attrib={}, children=items)

    def visit_simple_list(self, moin_page_tag, attrib, element, depth):
        """
        There is different list element in DocBook with different
        semantic meaning, but with an unique result in the DOM Tree.

        Here we handle the conversion of such of list.
        """
        list_item_tags = set(['listitem', 'step', 'stepalternatives', 'member'])
        items = []
        for child in element:
            if isinstance(child, ET.Element):
                if child.tag.name in list_item_tags:
                    children = self.visit(child, depth)
                    list_item_body = ET.Element(moin_page('list-item-body'), attrib={}, children=children)
                    tag = ET.Element(moin_page('list-item'), attrib={},
                                     children=[list_item_body])
                    tag = (tag, )
                    items.extend(tag)
                else:
                    r = self.visit(child, depth)
                    if r is None:
                        r = ()
                    elif not isinstance(r, (list, tuple)):
                        r = (r, )
                    items.extend(r)
            else:
                items.append(child)
        return ET.Element(moin_page.list, attrib=attrib, children=items)

    def visit_simple_tag(self, element, depth):
        """
        Some docbook tags can be converted directly to an equivalent
        DOM Tree element. We retrieve the equivalent tag from the
        simple_tags dictionnary defined at the begining of this file.
        """
        tag_to_return = self.simple_tags[element.tag.name]
        return self.new_copy(tag_to_return, element, depth, attrib={})

    def start_dom_tree(self, element, depth):
        """
        Return the root element of the DOM tree, with all the children.

        We also add a <table-of-content> element if needed.
        """
        attrib = {}
        if self.standard_attribute:
            attrib.update(self.standard_attribute)
            self.standard_attribute = {}
        children = []
        children.append(self.visit(element, depth))
        # We show the table of content only if it is not empty
        if self.is_section:
            children.insert(0, self.new(moin_page('table-of-content'),
                                    attrib={}, children={}))
        body = self.new(moin_page.body, attrib={}, children=children)
        return self.new(moin_page.page, attrib=attrib, children=[body])

from . import default_registry
from MoinMoin.util.mime import Type, type_moin_document
default_registry.register(Converter._factory, Type('application/docbook+xml'), type_moin_document)