Example #1
0
    def list_item_repl(self, _iter_content, stack, item, item_head, item_text):
        list_level = len(item_head)
        list_type = item_head[-1]

        # Try to locate the list element which matches the requested level and
        # type.
        while True:
            cur = stack.top()
            if cur.tag.name == 'body':
                break
            if cur.tag.name == 'list-item-body':
                if list_level > cur.list_level:
                    break
            if cur.tag.name == 'list':
                if list_level >= cur.list_level and list_type == cur.list_type:
                    break
            stack.pop()

        if cur.tag.name != 'list':
            generate = list_type == '#' and 'ordered' or 'unordered'
            attrib = {moin_page.item_label_generate: generate}
            element = moin_page.list(attrib=attrib)
            element.list_level, element.list_type = list_level, list_type
            stack.push(element)

        element = moin_page.list_item()
        element_body = moin_page.list_item_body()
        element_body.list_level, element_body.list_type = list_level, list_type

        stack.push(element)
        stack.push(element_body)

        self.parse_inline(item_text, stack)
Example #2
0
 def create_definition_list(self, items):
     """ creates an ET with a definition list made from items """
     def_list = moin_page.list()
     for label, body in items:
         item_label = moin_page.list_item_label(children=[label])
         item_body = moin_page.list_item_body(children=[body])
         item = moin_page.list_item(children=[item_label, item_body])
         def_list.append(item)
     return def_list
Example #3
0
    def create_pagelink_list(self, pagenames, ordered=False, display="FullPath"):
        """ Creates an ET with a list of pagelinks from a list of pagenames.

            Parameters:

              pagenames: a list of pages, each being like a flask request.path[1:]

              ordered: Should the list be ordered or unordered list (<ol> or <ul>)?

                  Options:
                      False : Display list as an unordered list.  (default)
                      True  : Display list as an ordered list.

              display: How should the link be displayed?

                  Options:
                      FullPath  : The full page path (default)
                      ChildPath : The last component of the FullPath, including the '/'
                      ChildName : ChildPath, but minus the leading '/'
                      UnCameled : ChildName, but with a space ' ' character between
                                  blocks of lowercase characters or numbers and an
                                  uppercase character.
                      skiptag   : skip items with this tag
                      ItemTitle : Use the title from the first header in the linked page *not implemented
            """

        page_list = moin_page.list(attrib={moin_page.item_label_generate: ordered and 'ordered' or 'unordered'})
        for pagename in pagenames:
            # This link can never reach pagelinks
            url = str(iri.Iri(scheme='wiki', authority='', path='/' + pagename))

            if display == "FullPath":
                linkname = pagename
            elif display == "ChildPath":
                index = pagename.rfind('/')
                linkname = pagename[index:]
            elif display == "ChildName":
                index = pagename.rfind('/')
                linkname = pagename[(index + 1):]
            elif display == "UnCameled":
                index = pagename.rfind('/')
                tempname = re.sub("([a-z0-9])([A-Z])", r"\g<1> \g<2>", pagename[(index + 1):])  # space before a cap char
                linkname = re.sub("([a-zA-Z])([0-9])", r"\g<1> \g<2>", tempname)
            elif display == "ItemTitle":
                raise NotImplementedError(_('"ItemTitle" is not implemented yet.'))
            else:
                raise KeyError(_('Unrecognized display value "%s".' % display))

            pagelink = moin_page.a(attrib={xlink.href: url}, children=[linkname])
            item_body = moin_page.list_item_body(children=[pagelink])
            item = moin_page.list_item(children=[item_body])
            page_list.append(item)
        return page_list
Example #4
0
 def create_number_pagelink_list(self, num_pagenames, ordered=False):
     """ creates an ET with a list of pagelinks from a list of pagenames """
     num_page_list = moin_page.list(attrib={moin_page.item_label_generate: ordered and 'ordered' or 'unordered'})
     for num, pagename in num_pagenames:
         num_code = moin_page.code(children=["{0:6d} ".format(num)])
         # This link can never reach pagelinks
         url = str(iri.Iri(scheme='wiki', authority='', path='/' + pagename))
         pagelink = moin_page.a(attrib={xlink.href: url}, children=[pagename])
         item_body = moin_page.list_item_body(children=[num_code, pagelink])
         item = moin_page.list_item(children=[item_body])
         num_page_list.append(item)
     return num_page_list
Example #5
0
 def visit_enumerated_list(self, node):
     enum_style = {
         'arabic': None,
         'loweralpha': u'lower-alpha',
         'upperalpha': u'upper-alpha',
         'lowerroman': u'lower-roman',
         'upperroman': u'upper-roman',
     }
     new_node = moin_page.list(
         attrib={moin_page.item_label_generate: u'ordered'})
     type = enum_style.get(node['enumtype'], None)
     if type:
         new_node.set(moin_page.list_style_type, type)
     self.open_moin_page_node(new_node)
Example #6
0
 def create_pagelink_list(self, pagenames, ordered=False):
     """ creates an ET with a list of pagelinks from a list of pagenames """
     page_list = moin_page.list(attrib={
         moin_page.item_label_generate:
         ordered and 'ordered' or 'unordered'
     })
     for pagename in pagenames:
         # This link can never reach pagelinks
         url = unicode(
             iri.Iri(scheme=u'wiki', authority=u'', path=u'/' + pagename))
         pagelink = moin_page.a(attrib={xlink.href: url},
                                children=[pagename])
         item_body = moin_page.list_item_body(children=[pagelink])
         item = moin_page.list_item(children=[item_body])
         page_list.append(item)
     return page_list
Example #7
0
 def visit_definition_list(self, node):
     self.open_moin_page_node(moin_page.list())
Example #8
0
 def visit_bullet_list(self, node):
     self.open_moin_page_node(moin_page.list(
         attrib={moin_page.item_label_generate: u'unordered'}))
Example #9
0
    def macro(self, content, arguments, page_url, alternative):

        # defaults
        item = None
        startswith = ""
        regex = None
        ordered = False
        display = "FullPath"
        skiptag = ""

        # process input
        args = []
        if arguments:
            args = arguments[0].split(',')
        for arg in args:
            try:
                key, val = [x.strip() for x in arg.split('=')]
            except ValueError:
                raise ValueError(_('ItemList macro: Argument "%s" does not follow <key>=<val> format (arguments, if more than one, must be comma-separated).' % arg))

            if len(val) < 2 or (val[0] != "'" and val[0] != '"') and val[-1] != val[0]:
                raise ValueError(_("ItemList macro: The key's value must be bracketed by matching quotes."))
            val = val[1:-1]  # strip out the doublequote characters

            if key == "item":
                item = val
            elif key == "startswith":
                startswith = val
            elif key == "regex":
                regex = val
            elif key == "ordered":
                if val == "False":
                    ordered = False
                elif val == "True":
                    ordered = True
                else:
                    raise ValueError(_('ItemList macro: The value must be "True" or "False". (got "%s")' % val))
            elif key == "display":
                display = val  # let 'create_pagelink_list' throw an exception if needed
            elif key == "skiptag":
                skiptag = val
            else:
                raise KeyError(_('ItemList macro: Unrecognized key "%s".' % key))

        # use curr item if not specified
        if item is None:
            item = request.path[1:]
            if item.startswith('+modify/'):
                item = item.split('/', 1)[1]

        # verify item exists and current user has read permission
        if item != "":
            if not flaskg.storage.get_item(**(split_fqname(item).query)):
                # if user lacks read permission, a 403 error was thrown on line above
                raise LookupError(_('ItemList macro: The specified item "%s" does not exist.' % item))

        # process subitems
        children = self.get_item_names(item, startswith=startswith, skiptag=skiptag)
        if regex:
            try:
                regex_re = re.compile(regex, re.IGNORECASE)
            except re.error as err:
                raise ValueError(_("ItemList macro: Error in regex {0!r}: {1}".format(regex, err)))
            newlist = []
            for child in children:
                if regex_re.search(child):
                    newlist.append(child)
            children = newlist
        if not children:
            empty_list = moin_page.list(attrib={moin_page.item_label_generate: ordered and 'ordered' or 'unordered'})
            item_body = moin_page.list_item_body(children=[_("<ItemList macro: No matching items were found.>")])
            item = moin_page.list_item(children=[item_body])
            empty_list.append(item)
            return empty_list
        return self.create_pagelink_list(children, ordered, display)
Example #10
0
    def indent_repl(self,
                    iter_content,
                    stack,
                    line,
                    indent,
                    text,
                    list_begin=None,
                    list_definition=None,
                    list_definition_text=None,
                    list_numbers=None,
                    list_bullet=None,
                    list_none=None):
        level = len(indent)
        list_type = 'unordered', 'none'
        if list_begin:
            if list_definition:
                list_type = 'definition', None
            elif list_numbers:
                list_type = 'ordered', None
            elif list_bullet:
                list_type = 'unordered', None
            elif list_none:
                list_type = None, None

        element_use = None
        while len(stack) > 1:
            cur = stack.top()
            if cur.tag.name == 'list-item-body':
                if level > cur.level:
                    element_use = cur
                    break
            if cur.tag.name == 'list':
                if level >= cur.level and list_type == cur.list_type:
                    element_use = cur
                    break
            stack.pop()

        if not element_use:
            element_use = stack.top()
        if list_begin:
            if element_use.tag.name != 'list':
                attrib = {}
                if not list_definition:
                    attrib[moin_page.item_label_generate] = list_type[0]
                if list_type[1]:
                    attrib[moin_page.list_style_type] = list_type[1]
                element = moin_page.list(attrib=attrib)
                element.level, element.list_type = level, list_type
                stack.push(element)

            stack.push(moin_page.list_item())
            if list_definition:
                element_label = moin_page.list_item_label()
                stack.top_append(element_label)
                new_stack = _Stack(element_label, iter_content=iter_content)
                # TODO: definition list doesn't work,
                #       if definition of the term on the next line
                splited_text = text.split(':')
                list_definition_text = splited_text.pop(0)
                text = ':'.join(splited_text)

                self.parse_inline(list_definition_text, new_stack,
                                  self.inline_re)

            element_body = moin_page.list_item_body()
            element_body.level, element_body.type = level, type

            stack.push(element_body)
            new_stack = _Stack(element_body, iter_content=iter_content)
        else:
            new_stack = stack
            level = 0

        is_list = list_begin
        iter = _Iter(self.indent_iter(iter_content, text, level, is_list),
                     startno=iter_content.lineno)
        for line in iter:
            match = self.block_re.match(line)
            it = iter
            # XXX: Hack to allow nowiki to ignore the list identation
            if match.lastgroup == 'table' or match.lastgroup == 'nowiki':
                it = iter_content
            self._apply(match, 'block', it, new_stack)
Example #11
0
    def indent_repl(self,
                    iter_content,
                    stack,
                    line,
                    indent,
                    text,
                    list_begin=None,
                    list_definition=None,
                    list_definition_text=None,
                    list_numbers=None,
                    list_alpha=None,
                    list_roman=None,
                    list_bullet=None,
                    list_start_number=None,
                    list_start_roman=None,
                    list_start_alpha=None,
                    list_none=None):

        level = len(indent)

        # default to blockquote / indented text / bulletless list
        list_type = 'unordered', 'no-bullet'

        if list_begin:
            if list_definition:
                list_type = 'definition', None
            elif list_numbers:
                list_type = 'ordered', None
            elif list_alpha and list_alpha[:2] == 'A.':
                list_type = 'ordered', 'upper-alpha'
            elif list_alpha:
                list_type = 'ordered', 'lower-alpha'
            elif list_roman and list_roman[:2] == 'I.':
                list_type = 'ordered', 'upper-roman'
            elif list_roman:
                list_type = 'ordered', 'lower-roman'
            elif list_bullet == u'*':
                list_type = 'unordered', None

        element_use = None
        while len(stack) > 1:
            cur = stack.top()
            if cur.tag.name == 'list-item-body':
                if level > cur.level:
                    element_use = cur
                    break
            if cur.tag.name == 'list':
                if level >= cur.level and list_type == cur.list_type:
                    element_use = cur
                    break
            stack.pop()

        if not element_use:
            element_use = stack.top()

        if indent:
            if element_use.tag.name != 'list':
                attrib = {}
                if not list_definition:
                    attrib[moin_page.item_label_generate] = list_type[0]
                if list_type[1]:
                    attrib[moin_page.list_style_type] = list_type[1]
                if list_start_number or list_start_alpha or list_start_roman:
                    attrib[
                        moin_page.
                        list_start] = list_start_number or list_start_alpha or list_start_roman
                element = moin_page.list(attrib=attrib)
                element.level, element.list_type = level, list_type
                stack.push(element)

            stack.push(moin_page.list_item())

            if list_definition_text:
                element_label = moin_page.list_item_label()
                stack.top_append(element_label)
                new_stack = _Stack(element_label, iter_content=iter_content)

                self.parse_inline(list_definition_text, new_stack,
                                  self.inline_re)
            if not list_definition_text or text:
                # if text == true, then we have object:: definition, not object::\n ::definition
                element_body = moin_page.list_item_body()
                element_body.level, element_body.type = level, type

                stack.push(element_body)
                new_stack = _Stack(element_body, iter_content=iter_content)
        else:
            new_stack = stack

        iter = _Iter(self.indent_iter(iter_content, text, level),
                     startno=iter_content.lineno)
        for line in iter:
            match = self.block_re.match(line)
            it = iter
            # XXX: Hack to allow nowiki to ignore the list identation
            if match.lastgroup == 'nowiki':
                it = iter_content
            self._apply(match, 'block', it, new_stack)
Example #12
0
    def macro(self, content, arguments, page_url, alternative):

        # defaults
        item = None
        startswith = ""
        regex = None
        ordered = False
        display = "FullPath"

        # process input
        args = []
        if arguments:
            args = arguments[0].split(',')
        for arg in args:
            try:
                key, val = [x.strip() for x in arg.split('=')]
            except ValueError:
                raise ValueError(
                    _('Argument "%s" does not follow <key>=<val> format (arguments, if more than one, must be comma-separated).'
                      % arg))

            if len(val) < 2 or (val[0] != "'"
                                and val[0] != '"') and val[-1] != val[0]:
                raise ValueError(
                    _("The key's value must be bracketed by matching quotes."))
            val = val[1:-1]  # strip out the doublequote characters

            if key == "item":
                item = val
            elif key == "startswith":
                startswith = val
            elif key == "regex":
                regex = val
            elif key == "ordered":
                if val == "False":
                    ordered = False
                elif val == "True":
                    ordered = True
                else:
                    raise ValueError(
                        _('The value must be "True" or "False". (got "%s")' %
                          val))
            elif key == "display":
                display = val  # let 'create_pagelink_list' throw an exception if needed
            else:
                raise KeyError(_('Unrecognized key "%s".' % key))

        # use curr page if not specified
        if item is None:
            item = request.path[1:]

        # test if item doesn't exist (potentially due to user's ACL, but that doesn't matter)
        if item != "":  # why are we retaining this behavior from PagenameList?
            if not flaskg.storage.get_item(**(split_fqname(item).query)):
                raise LookupError(
                    _('The specified item "%s" does not exist.' % item))

        # process child pages
        children = self.get_item_names(item, startswith)
        if regex:
            try:
                regex_re = re.compile(regex, re.IGNORECASE)
            except re.error as err:
                raise ValueError(
                    _("Error in regex {0!r}: {1}".format(regex, err)))
            newlist = []
            for child in children:
                if regex_re.search(child):
                    newlist.append(child)
            children = newlist
        if not children:
            empty_list = moin_page.list(
                attrib={
                    moin_page.item_label_generate:
                    ordered and 'ordered' or 'unordered'
                })
            item_body = moin_page.list_item_body(
                children=[_("<No matching pages were found>")])
            item = moin_page.list_item(children=[item_body])
            empty_list.append(item)
            return empty_list
        return self.create_pagelink_list(children, ordered, display)