Example #1
0
 def heading(self, on, depth, id=None, **kw):
     # remember depth of first heading, and adapt current depth accordingly
     if not self._base_depth:
         self._base_depth = depth
     depth = max(depth + (2 - self._base_depth), 2)
     name = u"s%i" % depth
     if on:
         found = None
         parent_depth = depth - 1
         while not found:
             found = self._curr.xml_select(u"ancestor-or-self::" + u"s%i" % (parent_depth))
             parent_depth -= 1
             if found:
                 break
         # print name, found
         self._curr = found[0]
         e = tree.element(None, name)
         id = U(id) if id else u""
         e.xml_attributes[None, u"title"] = id
         e.xml_attributes[None, u"id"] = id
         self._curr.xml_append(e)
         self._curr = e
         e = tree.element(None, u"title")
         self._curr.xml_append(e)
         self._curr = e
     else:
         parent = self._curr.xml_parent
         if self._curr.xml_local == u"title":
             parent.xml_remove(self._curr)
         self._curr = parent
     return ""
Example #2
0
    def image(self, src=None, **kw):
        if src:
            kw["src"] = src
        media = tree.element(None, u"inlinemediaobject")
        imagewrap = tree.element(None, u"imageobject")

        media.xml_append(imagewrap)

        image = tree.element(None, u"imagedata")
        if kw.has_key("src"):
            src = kw["src"]
            if src.startswith("/"):
                # convert to absolute path:
                src = self.request.getBaseURL() + src
            image.xml_attributes[u"fileref"] = src.decode("utf-8")
        if kw.has_key("width"):
            image.xml_attributes[u"width"] = unicode(kw["width"])
        if kw.has_key("height"):
            image.xml_attributes[u"depth"] = unicode(kw["height"])
        imagewrap.xml_append(image)

        # Look for any suitable title, order is important.
        title = ""
        for a in ("title", "html_title", "alt", "html_alt", "attachment_title"):
            if kw.has_key(a):
                title = kw[a]
                break
        if title:
            txtcontainer = tree.element(None, u"textobject")
            self._addTextElem(txtcontainer, u"phrase", title)
            media.xml_append(txtcontainer)

        self.cur.xml_append(media)
        return ""
Example #3
0
    def heading(self, on, depth, **kw):
        while self.cur.xml_qname in self.section_should_break:
            self.cur = self.cur.xml_parent

        if on:
            # try to go to higher level if needed
            if depth <= self.curdepth:
                # number of levels we want to go higher
                numberOfLevels = self.curdepth - depth + 1
                for dummy in range(numberOfLevels):
                    # find first non section node
                    while not self.cur.xml_qname in self._can_contain_section:
                        self.cur = self.cur.xml_parent

                    if self.cur.xml_qname == u"section":
                        self.cur = self.cur.xml_parent

            section = tree.element(None, u"section")
            self.cur.xml_append(section)
            self.cur = section

            title = tree.element(None, u"title")
            self.cur.xml_append(title)
            self.cur = title
            self.curdepth = depth
        else:
            self.cur = self.cur.xml_parent

        return ""
Example #4
0
    def _addRevisionHistory(self, targetNode):
        """
        This will generate a revhistory element which it will populate with
        revision nodes. Each revision has the revnumber, date and author-
        initial elements, and if a comment was supplied, the comment element.

        The date elements format depends on the users settings, so it will
        be in the same format as the revision history as viewed in the
        page info on the wiki.

        The authorinitials will be the UserName or if it was an anonymous
        edit, then it will be the hostname/ip-address.

        The revision history of included documents is NOT included at the
        moment due to technical difficulties.
        """
        _ = self.request.getText
        log = editlog.EditLog(self.request, rootpagename=self.title)
        user_cache = {}

        history = tree.element(None, u"revhistory")

        # read in the complete log of this page
        for line in log.reverse():
            if not line.action in ("SAVE", "SAVENEW", "SAVE/REVERT", "SAVE/RENAME"):
                # Let's ignore adding of attachments
                continue
            revision = tree.element(None, u"revision")

            # Revision number (without preceeding zeros)
            self._addTextElem(revision, u"revnumber", line.rev.lstrip("0"))

            # Date of revision
            date_text = self.request.user.getFormattedDateTime(wikiutil.version2timestamp(line.ed_time_usecs))
            self._addTextElem(revision, u"date", date_text)

            # Author or revision
            if not (line.userid in user_cache):
                user_cache[line.userid] = user.User(self.request, line.userid, auth_method="text_docbook:740")
            author = user_cache[line.userid]
            if author and author.name:
                self._addTextElem(revision, u"authorinitials", author.name)
            else:
                self._addTextElem(revision, u"authorinitials", line.hostname)

            # Comment from author of revision
            comment = line.comment
            if not comment:
                if "/REVERT" in line.action:
                    comment = _("Revert to revision %(rev)d.") % {"rev": int(line.extra)}
                elif "/RENAME" in line.action:
                    comment = _("Renamed from '%(oldpagename)s'.") % {"oldpagename": line.extra}
            if comment:
                self._addTextElem(revision, u"revremark", comment)

            history.xml_append(revision)

        if history.xml_first_child:
            # only add revision history is there is history to add
            targetNode.xml_append(history)
Example #5
0
    def image(self, src=None, **kw):
        if src:
            kw['src'] = src
        media = tree.element(None, u"inlinemediaobject")
        imagewrap = tree.element(None, u"imageobject")

        media.xml_append(imagewrap)

        image = tree.element(None, u"imagedata")
        if kw.has_key('src'):
            src = kw['src']
            if src.startswith("/"):
                # convert to absolute path:
                src = self.request.getBaseURL() + src
            image.xml_attributes[u'fileref'] = src.decode('utf-8')
        if kw.has_key('width'):
            image.xml_attributes[u'width'] = unicode(kw['width'])
        if kw.has_key('height'):
            image.xml_attributes[u'depth'] = unicode(kw['height'])
        imagewrap.xml_append(image)

        # Look for any suitable title, order is important.
        title = ''
        for a in ('title', 'html_title', 'alt', 'html_alt',
                  'attachment_title'):
            if kw.has_key(a):
                title = kw[a]
                break
        if title:
            txtcontainer = tree.element(None, u"textobject")
            self._addTextElem(txtcontainer, u"phrase", title)
            media.xml_append(txtcontainer)

        self.cur.xml_append(media)
        return ""
Example #6
0
 def heading(self, on, depth, id=None, **kw):
     # remember depth of first heading, and adapt current depth accordingly
     if not self._base_depth:
         self._base_depth = depth
     depth = max(depth + (2 - self._base_depth), 2)
     name = u's%i' % depth
     if on:
         found = None
         parent_depth = depth - 1
         while not found:
             found = self._curr.xml_select(u'ancestor-or-self::' + u's%i' %
                                           (parent_depth))
             parent_depth -= 1
             if found:
                 break
         #print name, found
         self._curr = found[0]
         e = tree.element(None, name)
         id = U(id) if id else u''
         e.xml_attributes[None, u'title'] = id
         e.xml_attributes[None, u'id'] = id
         self._curr.xml_append(e)
         self._curr = e
         e = tree.element(None, u'title')
         self._curr.xml_append(e)
         self._curr = e
     else:
         parent = self._curr.xml_parent
         if self._curr.xml_local == u'title':
             parent.xml_remove(self._curr)
         self._curr = parent
     return ''
Example #7
0
    def heading(self, on, depth, **kw):
        while self.cur.xml_qname in self.section_should_break:
            self.cur = self.cur.xml_parent

        if on:
            # try to go to higher level if needed
            if depth <= self.curdepth:
                # number of levels we want to go higher
                numberOfLevels = self.curdepth - depth + 1
                for dummy in range(numberOfLevels):
                    # find first non section node
                    while not self.cur.xml_qname in self._can_contain_section:
                        self.cur = self.cur.xml_parent

                    if self.cur.xml_qname == u"section":
                        self.cur = self.cur.xml_parent

            section = tree.element(None, u"section")
            self.cur.xml_append(section)
            self.cur = section

            title = tree.element(None, u"title")
            self.cur.xml_append(title)
            self.cur = title
            self.curdepth = depth
        else:
            self.cur = self.cur.xml_parent

        return ""
Example #8
0
 def list_services(self, ident=None):
     document = tree.entity()
     services = document.xml_append(tree.element(None, 'services'))
     for path, service in sorted(self._registered_services.iteritems()):
         if ident is not None and service.ident != ident:
             continue
         service_node = services.xml_append(tree.element(None, 'service'))
         service_node.xml_attributes['ident'] = service.ident
         E = service_node.xml_append(tree.element(None, 'path'))
         template = service.template
         if template is not None:
             E.xml_attributes["template"] = service.template.template
         E.xml_append(tree.text(path))
         E = service_node.xml_append(tree.element(None, 'description'))
         E.xml_append(tree.text(service.doc))
     return document
Example #9
0
 def addRow(self, argsdict={}):
     self.curColumn = 0
     self.row = tree.element(None, u"row")
     # Bug in yelp, doesn't affect the outcome.
     self.row.xml_attribute[None, u"rowsep"] = u"1"  # Rows should have lines between them
     self.tbody.xml_append(self.row)
     return self.row
Example #10
0
 def list_services(self, ident=None):
     document = tree.entity()
     services = document.xml_append(tree.element(None, 'services'))
     for path, service in sorted(self._registered_services.iteritems()):
         if ident is not None and service.ident != ident:
             continue
         service_node = services.xml_append(tree.element(None, 'service'))
         service_node.xml_attributes['ident'] = service.ident
         E = service_node.xml_append(tree.element(None, 'path'))
         template = service.template
         if template is not None:
             E.xml_attributes["template"] = service.template.template
         E.xml_append(tree.text(path))
         E = service_node.xml_append(tree.element(None, 'description'))
         E.xml_append(tree.text(service.doc))
     return document
Example #11
0
    def instantiate(self, context):
        context.push_string_writer(errors=False)
        for primitive in self:
            primitive.instantiate(context)
        writer = context.pop_writer()
        name = writer.get_result()
        prefix, local = splitqname(name)
        if prefix:
            namespace = self.namespaces[prefix]
        else:
            namespace = None

        context.namespaces = self.namespaces
        targets = self.select.evaluate_as_nodeset(context)
        if not targets:
            raise XUpdateError(XUpdateError.INVALID_SELECT)
        for target in targets:
            parent = target.xml_parent
            if target.xml_type == tree.attribute.xml_type:
                parent.xml_attributes[namespace, name] = target.xml_value
            elif target.xml_type == tree.processing_instruction.xml_type:
                pi = tree.processing_instruction(name, target.xml_data)
                parent.xml_replace-child(pi, target)
            elif target.xml_type == tree.element.xml_type:
                #FIXME: Use regular constructor. No more DOM factory
                element = tree.element(namespace, name)
                # Copy any existing attributes to the newly created element
                if target.xml_attributes:
                    for (ns, qname), value in target.xml_attributes.iteritems():
                        element.xml_attributes[ns, qname] = value
                # Now copy any children as well
                while target.xml_first_child:
                    element.xml_append(target.xml_first_child)
                parent.xml_replace(target, element)
        return
Example #12
0
 def _elem(self, name, on, **kw):
     if on:
         e = tree.element(None, name)
         self._curr.xml_append(e)
         self._curr = e
     elif name == self._curr.xml_local:
         self._curr = self._curr.xml_parent
     return
Example #13
0
 def _elem(self, name, on, **kw):
     if on:
         e = tree.element(None, name)
         self._curr.xml_append(e)
         self._curr = e
     elif name == self._curr.xml_local:
         self._curr = self._curr.xml_parent
     return
Example #14
0
 def addRow(self, argsdict={}):
     self.curColumn = 0
     self.row = tree.element(None, u'row')
     # Bug in yelp, doesn't affect the outcome.
     self.row.xml_attribute[
         None, u"rowsep"] = u"1"  #Rows should have lines between them
     self.tbody.xml_append(self.row)
     return self.row
Example #15
0
    def __init__(self, formatter, doc, parent, argsdict={}):
        self.formatter = formatter
        self.doc = doc

        self.tableNode = tree.element(None, u"informaltable")
        parent.xml_append(self.tableNode)
        self.colWidths = {}
        self.tgroup = tree.element(None, u"tgroup")
        # Bug in yelp, the two lines below don't affect rendering
        # self.tgroup.setAttribute('rowsep', '1')
        # self.tgroup.setAttribute('colsep', '1')
        self.curColumn = 0
        self.maxColumn = 0
        self.row = None
        self.tableNode.xml_append(self.tgroup)

        self.tbody = tree.element(None, u"tbody")  # Note: This gets appended in finalizeTable
Example #16
0
    def startDocument(self, pagename):
        self.doc = tree.entity()
        self.doc.xml_public_id = "-//OASIS//DTD DocBook XML V4.4//EN"
        self.doc.xml_system_id = "http://www.docbook.org/xml/4.4/docbookx.dtd"
        self.root = tree.element(None, unicode(self.doctype))
        self.doc.xml_append(self.root)
        self.title = pagename
        if not self.include_kludge and self.doctype == u"article":
            info = tree.element(None, u"articleinfo")
            self.root.xml_append(info)
            self._addTitleElement(self.title, targetNode=info)
            self._addRevisionHistory(targetNode=info)
        else:
            self._addTitleElement(self.title, targetNode=self.root)

        self.cur = self.root
        return ""
Example #17
0
    def startDocument(self, pagename):
        self.doc = tree.entity()
        self.doc.xml_public_id = "-//OASIS//DTD DocBook XML V4.4//EN"
        self.doc.xml_system_id = "http://www.docbook.org/xml/4.4/docbookx.dtd"
        self.root = tree.element(None, unicode(self.doctype))
        self.doc.xml_append(self.root)
        self.title = pagename
        if not self.include_kludge and self.doctype == u"article":
            info = tree.element(None, u"articleinfo")
            self.root.xml_append(info)
            self._addTitleElement(self.title, targetNode=info)
            self._addRevisionHistory(targetNode=info)
        else:
            self._addTitleElement(self.title, targetNode=self.root)

        self.cur = self.root
        return ""
Example #18
0
    def macro(self, macro_obj, name, args, markup=None):
        """As far as the DocBook formatter is concerned there are three
        kinds of macros: Bad, Handled and Unknown.

        The Bad ones are the ones that are known not to work, and are on its
        blacklist. They will be ignored and an XML comment will be written
        noting that the macro is not supported.

        Handled macros are such macros that code is written to handle them.
        For example for the FootNote macro it means that instead of executing
        the macro, a DocBook footnote entity is created, with the relevant
        pieces of information filles in.

        The Unknown are handled by executing the macro and capturing any
        textual output. There shouldn't be any textual output since macros
        should call formatter methods. This is unfortunately not always true,
        so the output it is then fed in to an xml parser and the
        resulting nodes copied to the DocBook-dom tree. If the output is not
        valid xml then a comment is written in the DocBook that the macro
        should be fixed.

        """
        # Another alternative would be to feed the output to rawHTML or even
        # combining these two approaches. The _best_ alternative would be to
        # fix the macros.
        excludes = (u"articleinfo", u"title")

        if name in self.blacklisted_macros:
            self._emitComment("The macro %s doesn't work with the DocBook formatter." % name)

        elif name == u"FootNote":
            footnote = tree.element(None, u"footnote")
            self._addTextElem(footnote, u"para", str(args))
            self.cur.xml_append(footnote)

        elif name == u"Include":
            was_in_para = self.cur.xml_qname == u"para"
            if was_in_para:
                self.paragraph(0)
            text = FormatterBase.macro(self, macro_obj, name, args)
            if text.strip():
                self._includeExternalDocument(text, exclude=excludes)
            if was_in_para:
                self.paragraph(1)

        else:
            text = FormatterBase.macro(self, macro_obj, name, args)
            if text:
                try:
                    self._includeExternalDocument(text, exclude=excludes)
                # FIXME: check for parse-related errors, realy
                except ExpatError:
                    self._emitComment(
                        u"The macro %s caused an error and should be blacklisted (and you might want to file a bug with the developer). It returned the following data which caused the docbook-formatter to choke. '%s'"
                        % (name, text)
                    )

        return u""
Example #19
0
    def macro(self, macro_obj, name, args, markup=None):
        """As far as the DocBook formatter is concerned there are three
        kinds of macros: Bad, Handled and Unknown.

        The Bad ones are the ones that are known not to work, and are on its
        blacklist. They will be ignored and an XML comment will be written
        noting that the macro is not supported.

        Handled macros are such macros that code is written to handle them.
        For example for the FootNote macro it means that instead of executing
        the macro, a DocBook footnote entity is created, with the relevant
        pieces of information filles in.

        The Unknown are handled by executing the macro and capturing any
        textual output. There shouldn't be any textual output since macros
        should call formatter methods. This is unfortunately not always true,
        so the output it is then fed in to an xml parser and the
        resulting nodes copied to the DocBook-dom tree. If the output is not
        valid xml then a comment is written in the DocBook that the macro
        should be fixed.

        """
        # Another alternative would be to feed the output to rawHTML or even
        # combining these two approaches. The _best_ alternative would be to
        # fix the macros.
        excludes = (u"articleinfo", u"title")

        if name in self.blacklisted_macros:
            self._emitComment(
                "The macro %s doesn't work with the DocBook formatter." % name)

        elif name == u"FootNote":
            footnote = tree.element(None, u"footnote")
            self._addTextElem(footnote, u"para", str(args))
            self.cur.xml_append(footnote)

        elif name == u"Include":
            was_in_para = self.cur.xml_qname == u"para"
            if was_in_para:
                self.paragraph(0)
            text = FormatterBase.macro(self, macro_obj, name, args)
            if text.strip():
                self._includeExternalDocument(text, exclude=excludes)
            if was_in_para:
                self.paragraph(1)

        else:
            text = FormatterBase.macro(self, macro_obj, name, args)
            if text:
                try:
                    self._includeExternalDocument(text, exclude=excludes)
                #FIXME: check for parse-related errors, realy
                except ExpatError:
                    self._emitComment(
                        u"The macro %s caused an error and should be blacklisted (and you might want to file a bug with the developer). It returned the following data which caused the docbook-formatter to choke. '%s'"
                        % (name, text))

        return u""
Example #20
0
 def _addTextElem(self, target, elemName, text):
     """
     Creates an element of the name elemName and adds a text node to it
     with the nodeValue of text. The new element is then added as a child
     to the element target.
     """
     newElement = tree.element(None, elemName)
     newElement.xml_append(tree.text(text))
     target.xml_append(newElement)
Example #21
0
    def __init__(self, formatter, doc, parent, argsdict={}):
        self.formatter = formatter
        self.doc = doc

        self.tableNode = tree.element(None, u'informaltable')
        parent.xml_append(self.tableNode)
        self.colWidths = {}
        self.tgroup = tree.element(None, u'tgroup')
        # Bug in yelp, the two lines below don't affect rendering
        #self.tgroup.setAttribute('rowsep', '1')
        #self.tgroup.setAttribute('colsep', '1')
        self.curColumn = 0
        self.maxColumn = 0
        self.row = None
        self.tableNode.xml_append(self.tgroup)

        self.tbody = tree.element(
            None, u'tbody')  # Note: This gets appended in finalizeTable
Example #22
0
 def image(self, src=None, **kw):
     e = tree.element(None, u"img")
     self._curr.xml_append(e)
     valid_attrs = ("src", "width", "height", "alt", "title")
     kw.update({"src": src})
     for key, value in kw.items():
         if key in valid_attrs:
             self._curr.xml_attributes[None, U(key)] = U(value)
     return ""
Example #23
0
 def _addTextElem(self, target, elemName, text):
     """
     Creates an element of the name elemName and adds a text node to it
     with the nodeValue of text. The new element is then added as a child
     to the element target.
     """
     newElement = tree.element(None, elemName)
     newElement.xml_append(tree.text(text))
     target.xml_append(newElement)
Example #24
0
 def image(self, src=None, **kw):
     e = tree.element(None, u'img')
     self._curr.xml_append(e)
     valid_attrs = ('src', 'width', 'height', 'alt', 'title')
     kw.update({'src': src})
     for key, value in kw.items():
         if key in valid_attrs:
             self._curr.xml_attributes[None, U(key)] = U(value)
     return ''
Example #25
0
 def test_create_new_doc_comment(self):
     EXPECTED = '<A a="b">One</A><!--This is easy-->'
     doc = tree.entity()
     A = tree.element(None, u'A')
     A.xml_attributes[u'a'] = u'b'
     A.xml_append(tree.text(u'One'))
     doc.xml_append(A)
     doc.xml_append(tree.comment(u"This is easy"))
     self.compare_output(doc, XMLDECL+EXPECTED)
     return 
Example #26
0
 def test_create_new_doc_comment(self):
     EXPECTED = '<A a="b">One</A><!--This is easy-->'
     doc = tree.entity()
     A = tree.element(None, u'A')
     A.xml_attributes[u'a'] = u'b'
     A.xml_append(tree.text(u'One'))
     doc.xml_append(A)
     doc.xml_append(tree.comment(u"This is easy"))
     self.compare_output(doc, XMLDECL + EXPECTED)
     return
Example #27
0
    def test_create_new_doc_attr_factory(self):
        EXPECTED = '<A a="b">One</A>'
        doc = tree.entity()
        A = tree.element(None, u'A')

        new_attr = A.xml_attribute_factory(None, u'a', u'b')
        A.xml_attributes.setnode(new_attr)
        A.xml_append(tree.text(u'One'))
        doc.xml_append(A)
        self.compare_output(doc, XMLDECL + EXPECTED)
        return
Example #28
0
 def test_create_new_doc_attr_factory(self):
     EXPECTED = '<A a="b">One</A>'
     doc = tree.entity()
     A = tree.element(None, u'A')
     
     new_attr = A.xml_attribute_factory(None, u'a', u'b')
     A.xml_attributes.setnode(new_attr)
     A.xml_append(tree.text(u'One'))
     doc.xml_append(A)
     self.compare_output(doc, XMLDECL+EXPECTED)
     return 
Example #29
0
 def test_create_new_doc_pi(self):
     EXPECTED = '<?xml-stylesheet href="classic.xsl" type="text/xml"?><A a="b">One</A>'
     doc = tree.entity()
     doc.xml_append(tree.processing_instruction(u'xml-stylesheet', 
                                                u'href="classic.xsl" type="text/xml"'))
     A = tree.element(None, u'A')
     A.xml_attributes[u'a'] = u'b'
     A.xml_append(tree.text(u'One'))
     doc.xml_append(A)
     self.compare_output(doc, XMLDECL+EXPECTED)
     return 
Example #30
0
 def test_element_no_longer(self):
     old_methods = ['nodeName', 'tagName', 'qualifiedName', 'namespaceURI',
                    'localName', 'prefix', 'childNodes', 'hasChildNodes',
                    'firstChild', 'lastChild', 'normalize', 'nextSibling', 
                    'previousSibling', 'getElementById', 'getAttributeNodeNS', 
                    'setAttributeNodeNS', 'getAttributeNS', 'setAttributeNS',
                    'hasAttributeNS', 'removeAttributeNode', 
                    'removeAttribute', 'attributes', 'appendChild', 
                    'removeChild', 'insertBefore', 'replaceChild']
     element = tree.element(None, u'A')
     for old_method in old_methods:
         self.assertRaises(AttributeError, getattr, element, "%s" % old_method)
Example #31
0
 def test_create_new_doc_pi(self):
     EXPECTED = '<?xml-stylesheet href="classic.xsl" type="text/xml"?><A a="b">One</A>'
     doc = tree.entity()
     doc.xml_append(
         tree.processing_instruction(u'xml-stylesheet',
                                     u'href="classic.xsl" type="text/xml"'))
     A = tree.element(None, u'A')
     A.xml_attributes[u'a'] = u'b'
     A.xml_append(tree.text(u'One'))
     doc.xml_append(A)
     self.compare_output(doc, XMLDECL + EXPECTED)
     return
Example #32
0
 def test_element_no_longer(self):
     old_methods = [
         'nodeName', 'tagName', 'qualifiedName', 'namespaceURI',
         'localName', 'prefix', 'childNodes', 'hasChildNodes', 'firstChild',
         'lastChild', 'normalize', 'nextSibling', 'previousSibling',
         'getElementById', 'getAttributeNodeNS', 'setAttributeNodeNS',
         'getAttributeNS', 'setAttributeNS', 'hasAttributeNS',
         'removeAttributeNode', 'removeAttribute', 'attributes',
         'appendChild', 'removeChild', 'insertBefore', 'replaceChild'
     ]
     element = tree.element(None, u'A')
     for old_method in old_methods:
         self.assertRaises(AttributeError, getattr, element,
                           "%s" % old_method)
Example #33
0
def process_pre_poem(node):
    '''
    >>> X = ['<div>', '<pre>The red cap chiefs stack up their wealth,', 'Shards of what once was bred in bone.', '', 'Church tales of wandering accursed&#8212;', 'It\'s forty years full fifty times;', '</pre>', '</div>']
    >>> X = '\n'.join(X)
    >>> doc = parse(X)
    >>> process_pre_poem(doc.xml_first_child)
    >>> doc.xml_write()
    <?xml version="1.0" encoding="UTF-8"?>
<div>
<p>The red cap chiefs stack up their wealth,<br/>Shards of what once was bred in bone.<br/></p><p>Church tales of wandering accursed—<br/>It's forty years full fifty times;<br/><br/></p>
</div>
    '''
    for pre in node.xml_select(u'.//pre'):
        ptext = U(pre)
        if pre.xml_first_child:
            pre.xml_remove(pre.xml_first_child)
        for stanza in ptext.split(u'\n\n'):
            p = element(None, u'p')
            pre.xml_append(p)
            for line in stanza.split(u'\n'):
                p.xml_append(text(line))
                p.xml_append(element(None, u'br'))
        unwrap(pre)
    return
Example #34
0
 def test_reading_building(self):
     doc = tree.entity()
     doc.xml_append(tree.processing_instruction(u'xml-stylesheet', 
                                                u'href="classic.xsl" type="text/xml"'))
     A = tree.element(None, u'A')
     A.xml_attributes[u'a'] = u'b'
     A.xml_append(tree.text(u'One'))
     doc.xml_append(A)
     doc.xml_append(tree.comment(u"This is easy"))
     doc2 = amara.parse('docs/whatsnew_doc1.xml')
     output1 = cStringIO.StringIO()        
     output2 = cStringIO.StringIO()        
     xml_print(doc, stream=output1)
     xml_print(doc2, stream=output2)
     self.assertEqual(output1.getvalue(), output2.getvalue())
     return
Example #35
0
    def addCell(self, argsdict={}):
        if "style" in argsdict:
            argsdict.update(self.formatter._convertStylesToDict(argsdict["style"].strip('"')))

        cell = tree.element(None, u"entry")
        cell.xml_attribute[None, u"rowsep"] = u"1"
        cell.xml_attribute[None, u"colsep"] = u"1"

        self.row.xml_append(cell)
        self._handleSimpleCellAttributes(cell, argsdict)
        self._handleColWidth(argsdict)
        self.curColumn += self._handleColSpan(cell, argsdict)

        self.maxColumn = max(self.curColumn, self.maxColumn)

        return cell
Example #36
0
 def test_reading_building(self):
     doc = tree.entity()
     doc.xml_append(
         tree.processing_instruction(u'xml-stylesheet',
                                     u'href="classic.xsl" type="text/xml"'))
     A = tree.element(None, u'A')
     A.xml_attributes[u'a'] = u'b'
     A.xml_append(tree.text(u'One'))
     doc.xml_append(A)
     doc.xml_append(tree.comment(u"This is easy"))
     doc2 = amara.parse('docs/whatsnew_doc1.xml')
     output1 = cStringIO.StringIO()
     output2 = cStringIO.StringIO()
     xml_print(doc, stream=output1)
     xml_print(doc2, stream=output2)
     self.assertEqual(output1.getvalue(), output2.getvalue())
     return
Example #37
0
    def finalizeTable(self):
        """Calculates the final width of the whole table and the width of each
        column. Adds the colspec-elements and applies the colwidth attributes.
        Inserts the tbody element to the tgroup and returns the tables container
        element.

        A lot of the information is gathered from the style attributes passed
        to the functions
        """
        self.tgroup.xml_attributes[None, u"cols"] = unicode(self.maxColumn)
        for colnr in range(0, self.maxColumn):
            colspecElem = tree.element(None, u"colspec")
            colspecElem.xml_attribute[None, u"colname"] = u"col_%s" % unicode(colnr)
            if self.colWidths.has_key(str(colnr)) and self.colWidths[unicode(colnr)] != "1*":
                colspecElem.xml_attribute[u"colwidth"] = unicode(self.colWidths[unicode(colnr)])
            self.tgroup.xml_append(colspecElem)
        self.tgroup.xml_append(self.tbody)
        return self.tableNode.xml_parent
Example #38
0
 def test_element_valid_properties(self):
     new_operations = ['xml_append', 'xml_attribute_added', 
                       'xml_attribute_factory', 'xml_attribute_modified',
                       'xml_attribute_removed', 'xml_attributes', 'xml_base',
                       'xml_child_inserted', 'xml_child_removed', 
                       'xml_children', 'xml_first_child', 
                       'xml_following_sibling', 'xml_index', 'xml_insert', 
                       'xml_last_child', 'xml_local', 'xml_name', 
                       'xml_namespace', 'xml_namespaces', 'xml_nodeid', 
                       'xml_normalize', 'xml_parent', 'xml_preceding_sibling', 
                       'xml_prefix', 'xml_qname', 'xml_remove', 'xml_replace', 
                       'xml_root', 'xml_select', 'xml_type', 'xml_typecode',
                       'xmlns_attributes']
     element = tree.element(None, u'A')
     new_methods = [attr for attr in dir(element) if attr.startswith('xml')]
     for operation in new_methods:
         self.assertTrue(operation in new_operations)
     return
Example #39
0
    def addCell(self, argsdict={}):
        if 'style' in argsdict:
            argsdict.update(
                self.formatter._convertStylesToDict(
                    argsdict['style'].strip('"')))

        cell = tree.element(None, u'entry')
        cell.xml_attribute[None, u'rowsep'] = u'1'
        cell.xml_attribute[None, u'colsep'] = u'1'

        self.row.xml_append(cell)
        self._handleSimpleCellAttributes(cell, argsdict)
        self._handleColWidth(argsdict)
        self.curColumn += self._handleColSpan(cell, argsdict)

        self.maxColumn = max(self.curColumn, self.maxColumn)

        return cell
Example #40
0
 def test_element_valid_properties(self):
     new_operations = [
         'xml_append', 'xml_attribute_added', 'xml_attribute_factory',
         'xml_attribute_modified', 'xml_attribute_removed',
         'xml_attributes', 'xml_base', 'xml_child_inserted',
         'xml_child_removed', 'xml_children', 'xml_first_child',
         'xml_following_sibling', 'xml_index', 'xml_insert',
         'xml_last_child', 'xml_local', 'xml_name', 'xml_namespace',
         'xml_namespaces', 'xml_nodeid', 'xml_normalize', 'xml_parent',
         'xml_preceding_sibling', 'xml_prefix', 'xml_qname', 'xml_remove',
         'xml_replace', 'xml_root', 'xml_select', 'xml_type',
         'xml_typecode', 'xmlns_attributes'
     ]
     element = tree.element(None, u'A')
     new_methods = [attr for attr in dir(element) if attr.startswith('xml')]
     for operation in new_methods:
         self.assertTrue(operation in new_operations)
     return
Example #41
0
def _map(context, nodeset, expr):
    focus = context.node, context.position, context.size
    context.size = len(nodeset)
    position = 1

    inputs = iter(nodeset)
    return_type = None
    result = set()
    for node in inputs:
        context.node = node
        context.position = position
        position += 1

        try:
            obj = expr.evaluate(context)
        except:
            lines = traceback.format_exception(*sys.exc_info())
            lines[:1] = [("Runtime error in XPath expression '%(expr)s', "
                          "lower-level traceback:\n") % {
                              'expr': string
                          }]
            context.processor.warning(''.join(lines))
        else:
            if not return_type:
                if isinstance(obj, datatypes.nodeset):
                    tag_name = None
                elif isinstance(obj, datatypes.number):
                    tag_name = 'exsl:number'
                    converter = datatypes.string
                elif isinstance(obj, datatypes.boolean):
                    tag_name = 'exsl:boolean'
                    converter = lambda obj: u'true' if obj else u''
                else:
                    tag_name = 'exsl:string'
                    converter = datatypes.string
                return_type = True
            if tag_name:
                E = tree.element(EXSL_COMMON_NS, tag_name)
                E.xml_append(tree.text(converter(obj)))
                result.add(E)
            else:
                result.update(obj)
    context.node, context.position, context.size = focus
    return datatypes.nodeset(result)
Example #42
0
def _map(context, nodeset, expr):
    focus = context.node, context.position, context.size
    context.size = len(nodeset)
    position = 1

    inputs = iter(nodeset)
    return_type = None
    result = set()
    for node in inputs:
        context.node = node
        context.position = position
        position += 1

        try:
            obj = expr.evaluate(context)
        except:
            lines = traceback.format_exception(*sys.exc_info())
            lines[:1] = [("Runtime error in XPath expression '%(expr)s', "
                            "lower-level traceback:\n") % {'expr': string}]
            context.processor.warning(''.join(lines))
        else:
            if not return_type:
                if isinstance(obj, datatypes.nodeset):
                    tag_name = None
                elif isinstance(obj, datatypes.number):
                    tag_name = 'exsl:number'
                    converter = datatypes.string
                elif isinstance(obj, datatypes.boolean):
                    tag_name = 'exsl:boolean'
                    converter = lambda obj: u'true' if obj else u''
                else:
                    tag_name = 'exsl:string'
                    converter = datatypes.string
                return_type = True
            if tag_name:
                E = tree.element(EXSL_COMMON_NS, tag_name)
                E.xml_append(tree.text(converter(obj)))
                result.add(E)
            else:
                result.update(obj)
    context.node, context.position, context.size = focus
    return datatypes.nodeset(result)
Example #43
0
    def _handleNode(self, name, on, attributes=()):
        if on:
            node = tree.element(None, name)
            self.cur.xml_append(node)
            if len(attributes) > 0:
                for name, value in attributes:
                    node.xml_attributes[None, name] = value
            self.cur = node
        else:
            """
                Because we prevent para inside para, we might get extra "please
                exit para" when we are no longer inside one.

                TODO: Maybe rethink the para in para case
            """
            if name == u"para" and self.cur.xml_qname != u"para":
                return ""

            self.cur = self.cur.xml_parent
        return ""
Example #44
0
    def _handleNode(self, name, on, attributes=()):
        if on:
            node = tree.element(None, name)
            self.cur.xml_append(node)
            if len(attributes) > 0:
                for name, value in attributes:
                    node.xml_attributes[None, name] = value
            self.cur = node
        else:
            """
                Because we prevent para inside para, we might get extra "please
                exit para" when we are no longer inside one.

                TODO: Maybe rethink the para in para case
            """
            if name == u"para" and self.cur.xml_qname != u"para":
                return ""

            self.cur = self.cur.xml_parent
        return ""
Example #45
0
    def finalizeTable(self):
        """Calculates the final width of the whole table and the width of each
        column. Adds the colspec-elements and applies the colwidth attributes.
        Inserts the tbody element to the tgroup and returns the tables container
        element.

        A lot of the information is gathered from the style attributes passed
        to the functions
        """
        self.tgroup.xml_attributes[None, u'cols'] = unicode(self.maxColumn)
        for colnr in range(0, self.maxColumn):
            colspecElem = tree.element(None, u'colspec')
            colspecElem.xml_attribute[None,
                                      u'colname'] = u'col_%s' % unicode(colnr)
            if self.colWidths.has_key(
                    str(colnr)) and self.colWidths[unicode(colnr)] != "1*":
                colspecElem.xml_attribute[u'colwidth'] = unicode(
                    self.colWidths[unicode(colnr)])
            self.tgroup.xml_append(colspecElem)
        self.tgroup.xml_append(self.tbody)
        return self.tableNode.xml_parent
Example #46
0
 def anchordef(self, id):
     e = tree.element(None, u'anchor')
     self._curr.xml_append(e)
     self._curr.xml_attributes[None, u'id'] = U(id)
     return ''
Example #47
0
 def linebreak(self, preformatted=1):
     e = tree.element(None, u'br')
     self._curr.xml_append(e)
     return ''
Example #48
0
 def rule(self, size=0, **kw):
     e = tree.element(None, u'br')  # <hr/> not supported in stylebook
     e.xml_append(tree.text((u"-" * 78)))
     self._curr.xml_append(e)
     return ''
Example #49
0
    # number literals (for special values)
    NOT_A_NUMBER,
    POSITIVE_INFINITY,
    NEGATIVE_INFINITY,
    # nodeset literals
    nodeset_literal,
    EMPTY_NODESET,
)

from amara.xpath import context
from test_expressions import DOC

default_context = context(DOC, 1, 1)


EGG1 = tree.element(None, "egg1")
EGG1.xml_append(tree.text("egg1"))
EGG2 = tree.element(None, "egg2")
EGG2.xml_append(tree.text("egg2"))

NUM = tree.element(None, "num")
NUM0 = tree.attribute(None, "num0", "0")
NUM.xml_attributes.setnode(NUM0)
NUM2 = tree.attribute(None, "num2", "2")
NUM.xml_attributes.setnode(NUM0)
NUM4 = tree.attribute(None, "num4", "4")
NUM.xml_attributes.setnode(NUM0)
NUM31 = tree.attribute(None, "num31", "31")
NUM.xml_attributes.setnode(NUM0)

Example #50
0
    TRUE,
    FALSE,
    # number literals (for special values)
    NOT_A_NUMBER,
    POSITIVE_INFINITY,
    NEGATIVE_INFINITY,
    # nodeset literals
    nodeset_literal,
    EMPTY_NODESET,
)

from amara.xpath import context
from test_expressions import DOC
default_context = context(DOC, 1, 1)

EGG1 = tree.element(None, 'egg1')
EGG1.xml_append(tree.text('egg1'))
EGG2 = tree.element(None, 'egg2')
EGG2.xml_append(tree.text('egg2'))

NUM = tree.element(None, 'num')
NUM0 = tree.attribute(None, 'num0', '0')
NUM.xml_attributes.setnode(NUM0)
NUM2 = tree.attribute(None, 'num2', '2')
NUM.xml_attributes.setnode(NUM0)
NUM4 = tree.attribute(None, 'num4', '4')
NUM.xml_attributes.setnode(NUM0)
NUM31 = tree.attribute(None, 'num31', '31')
NUM.xml_attributes.setnode(NUM0)

Example #51
0
    def _addRevisionHistory(self, targetNode):
        """
        This will generate a revhistory element which it will populate with
        revision nodes. Each revision has the revnumber, date and author-
        initial elements, and if a comment was supplied, the comment element.

        The date elements format depends on the users settings, so it will
        be in the same format as the revision history as viewed in the
        page info on the wiki.

        The authorinitials will be the UserName or if it was an anonymous
        edit, then it will be the hostname/ip-address.

        The revision history of included documents is NOT included at the
        moment due to technical difficulties.
        """
        _ = self.request.getText
        log = editlog.EditLog(self.request, rootpagename=self.title)
        user_cache = {}

        history = tree.element(None, u"revhistory")

        # read in the complete log of this page
        for line in log.reverse():
            if not line.action in (
                    'SAVE',
                    'SAVENEW',
                    'SAVE/REVERT',
                    'SAVE/RENAME',
            ):
                #Let's ignore adding of attachments
                continue
            revision = tree.element(None, u"revision")

            # Revision number (without preceeding zeros)
            self._addTextElem(revision, u"revnumber", line.rev.lstrip('0'))

            # Date of revision
            date_text = self.request.user.getFormattedDateTime(
                wikiutil.version2timestamp(line.ed_time_usecs))
            self._addTextElem(revision, u"date", date_text)

            # Author or revision
            if not (line.userid in user_cache):
                user_cache[line.userid] = user.User(
                    self.request, line.userid, auth_method="text_docbook:740")
            author = user_cache[line.userid]
            if author and author.name:
                self._addTextElem(revision, u"authorinitials", author.name)
            else:
                self._addTextElem(revision, u"authorinitials", line.hostname)

            # Comment from author of revision
            comment = line.comment
            if not comment:
                if '/REVERT' in line.action:
                    comment = _("Revert to revision %(rev)d.") % {
                        'rev': int(line.extra)
                    }
                elif '/RENAME' in line.action:
                    comment = _("Renamed from '%(oldpagename)s'.") % {
                        'oldpagename': line.extra
                    }
            if comment:
                self._addTextElem(revision, u"revremark", comment)

            history.xml_append(revision)

        if history.xml_first_child:
            #only add revision history is there is history to add
            targetNode.xml_append(history)
Example #52
0
 def linebreak(self, preformatted=1):
     e = tree.element(None, u"br")
     self._curr.xml_append(e)
     return ""
Example #53
0
 def rule(self, size=0, **kw):
     e = tree.element(None, u"br")  # <hr/> not supported in stylebook
     e.xml_append(tree.text((u"-" * 78)))
     self._curr.xml_append(e)
     return ""
Example #54
0
    ROOT,
    CHILD1,
    CHILD2,
    CHILD3,
    LCHILD1,
    LCHILD2)

# contexts for nodeset {CHILD1, CHILD2, CHILD3}
CONTEXT1 = context(CHILD1, 1, 3)
CONTEXT2 = context(CHILD2, 2, 3)
# contexts for nodeset {LCHILD1, LCHILD2, NONASCIIQNAME}
CONTEXTLANG1 = context(LCHILD1, 1, 3)
CONTEXTLANG2 = context(LCHILD2, 2, 3)

DOC = tree.entity()
EGG1 = DOC.xml_append(tree.element(None, 'egg0'))
EGG1.xml_append(tree.text('0'))
EGG2 = DOC.xml_append(tree.element(None, 'egg1'))
EGG2.xml_append(tree.text('1'))
EGG3 = DOC.xml_append(tree.element(None, 'egg0'))
EGG3.xml_append(tree.text('0'))
EGG4 = DOC.xml_append(tree.element(None, 'egg1'))
EGG4.xml_append(tree.text('1'))
EGG5 = DOC.xml_append(tree.element(None, 'egg0'))
EGG5.xml_append(tree.text('0'))

from amara.xpath.expressions.functioncalls import function_call


def test_last_function():
    for context in (CONTEXT1, CONTEXT2):
Example #55
0
 def startDocument(self, pagename):
     self._curr = tree.element(None, u's1')
     self._curr.xml_attributes[None, u'title'] = U(pagename)
     self._doc.xml_append(self._curr)
     return ''
Example #56
0
 def startDocument(self, pagename):
     self._curr = tree.element(None, u"s1")
     self._curr.xml_attributes[None, u"title"] = U(pagename)
     self._doc.xml_append(self._curr)
     return ""
Example #57
0
CONTEXT_GCHILD11 = context(GCHILD11, 1, 2)
CONTEXT_LANG = context(LANG, 1, 1)

# <elements>
#   <element>
#     <x>
#       <y>a</y>
#     </x>
#   </element>
#   <element>
#     <x>
#       <y>z</y>
#     </x>
#   </element>
# </elements>
ELEMENTS = tree.entity().xml_append(tree.element(None, 'elements'))
for cdata in ('a', 'z'):
    node = ELEMENTS.xml_append(tree.element(None, 'element'))
    node = node.xml_append(tree.element(None, 'x'))
    node = node.xml_append(tree.element(None, 'y'))
    node.xml_append(tree.text(cdata))
del node, cdata
CONTEXT_ELEMENT = context(ELEMENTS, 1, 1)
ELEMENT1, ELEMENT2 = ELEMENTS

from amara.xpath.parser import parse


def _run_parser_pass(test_cases):
    for args, expected, ctx in test_cases:
        result = parse(*args).evaluate(ctx)
Example #58
0
 def anchordef(self, id):
     e = tree.element(None, u"anchor")
     self._curr.xml_append(e)
     self._curr.xml_attributes[None, u"id"] = U(id)
     return ""