예제 #1
0
    def _word_repl(self, word, groups):
        if self.in_dd:
            name = groups.get('word_name')
            current_page = self.formatter.page.page_name
            abs_name = wikiutil.AbsPageName(current_page, name)
            if abs_name == current_page:
                return self.__real_val(abs_name)
            else:
                # handle anchors
                try:
                    abs_name, anchor = rsplit(abs_name, "#", 1)
                except ValueError:
                    anchor = ""
                if self.cat_re.match(abs_name):
                    return self.__real_val(abs_name)

                else:
                    if not anchor:
                        wholename = abs_name
                    else:
                        wholename = "%s#%s" % (abs_name, anchor)

                    return self.__real_val(wholename)

        return apply(wikiParser._word_repl, (self, word, groups))
예제 #2
0
    def format(self, formatter):
        # print "format"
        # format is also called for each !# command. its called after __init__
        # is called. this is where parsers do most of their work.
        # they write their results into the Httprequest object
        # which is usually stored from __init__ in self.request.

        # print "formatter",dir(formatter)
        # formatter is a special object in MoinMoin that
        # is supposed to help people who write extensions to have
        # sort of a uniform looking thing going on.
        # see http://moinmoin.wikiwikiweb.de/ApplyingFormatters?highlight=%28formatter%29

        # but formatter is not documented well. you have to look at
        # moinmoin/formatter/base.py. And if you do, you will see that half of
        # the methods raise a 'not implemented' error.
        # formatter is also being refactored alot so dont get used to it.
        # if all else fails just use formatter.rawHTML which will
        # screw up XML output but at least it will work.

        page_name = formatter.page.page_name
        cs_template_page = wikiutil.AbsPageName(page_name,
                                                self.kw["format_args"])
        cs_template = Page(self.request, cs_template_page).getPageText()

        hdf = neo_util.HDF()
        hdf.readString(self.raw)
        hdf.setValue("Config.WhiteSpaceStrip", "0")

        cs = neo_cs.CS(hdf)
        cs.parseStr(cs_template)
        body = cs.render()
        body = wikiutil.renderText(self.request, WikiParser, body)
        self.request.write(formatter.rawHTML(body))
예제 #3
0
파일: CS.py 프로젝트: rosin-project/roswiki
def execute(macro, args):
    request = macro.request
    content = []
    page_name = macro.formatter.page.page_name

    # get args
    include_page_name = ''
    if args is not None:
        (include_page_name, _, hdf_text) = args.partition(',')

    include_page_name = wikiutil.AbsPageName(page_name, include_page_name)

    include_page = Page(request, include_page_name)

    if include_page is None:
        return ''
    if not request.user.may.read(include_page_name):
        return ''

    cstemplate = include_page.getPageText()

    pagename = macro.formatter.page.page_name

    hdf = neo_util.HDF()
    hdf.readString(hdf_text)

    hdf.setValue("Config.WhiteSpaceStrip ", "0")

    cs = neo_cs.CS(hdf)
    cs.parseStr(cstemplate)

    body = cs.render()

    body = wikiutil.renderText(request, WikiParser, body)
    return body
예제 #4
0
    def _word_repl(self, word, groups):
        """Handle WikiNames."""
        bang_present = groups.get('word_bang')
        if bang_present:
            if self.cfg.bang_meta:
                return self.formatter.nowikiword("!%s" % word)
            else:
                self.formatter.text('!')

        name = groups.get('word_name')
        current_page = self.formatter.page.page_name
        abs_name = wikiutil.AbsPageName(current_page, name)
        if abs_name == current_page:
            self.currentitems.append(('wikilink', (abs_name, abs_name)))
            self.__add_meta(abs_name, groups)
            return u''
        else:
            # handle anchors
            try:
                abs_name, anchor = rsplit(abs_name, "#", 1)
            except ValueError:
                anchor = ""
            if self.cat_re.match(abs_name):
                self.currentitems.append(('category', (abs_name)))
                self.__add_meta(abs_name, groups)

            else:
                if not anchor:
                    wholename = abs_name
                else:
                    wholename = "%s#%s" % (abs_name, anchor)

                self.currentitems.append(('wikilink', (wholename, abs_name)))
                self.__add_meta(wholename, groups)
            return u''
예제 #5
0
파일: AttachFile.py 프로젝트: aahlad/soar
def absoluteName(url, pagename):
    """ Get (pagename, filename) of an attachment: link
        @param url: PageName/filename.ext or filename.ext (unicode)
        @param pagename: name of the currently processed page (unicode)
        @rtype: tuple of unicode
        @return: PageName, filename.ext
    """
    url = wikiutil.AbsPageName(pagename, url)
    pieces = url.split(u'/')
    if len(pieces) == 1:
        return pagename, pieces[0]
    else:
        return u"/".join(pieces[:-1]), pieces[-1]
예제 #6
0
def get_wiki_page(wiki_link, macro):
    if not wiki_link:
        return {}
    page_name = macro.formatter.page.page_name
    tutorial_page_name = wikiutil.AbsPageName(page_name, wiki_link)
    tutorial_page = Page(macro.request, tutorial_page_name)
    result = formatContext(tutorial_page, macro)
    if not result:
        return {}
    tutorial = {
        'link': tutorial_page_name,
        'title': result[0],
        'desc': result[1],
        'next': result[2]
    }
    return tutorial
예제 #7
0
def execute(macro, args):
    request = macro.request
    content = []
    page_name = macro.formatter.page.page_name

    # get args
    include_page_name = ''
    if args is not None:
        include_page_name = args

    include_page_name = wikiutil.AbsPageName(page_name, include_page_name)

    include_page = Page(request, include_page_name)

    if include_page is None:
        return ''
    if not request.user.may.read(include_page_name):
        return ''

    cstemplate = include_page.getPageText()

    pagename = macro.formatter.page.page_name
    kv_page = Page(request, pagename)
    kv_body = kv_page.get_body()

    hdf = neo_util.HDF()
    for line in kv_body.split("\n"):
        if line.startswith("##"):
            line = line[2:].strip()
            parts = line.split("=", 1)
            if len(parts) == 2:
                val = parts[1].strip()
                #val = parts[1].strip().encode('utf-8')  # swh
                hdf.setValue(parts[0].strip(), val)

    hdf.setValue("Config.WhiteSpaceStrip ", "0")

    cs = neo_cs.CS(hdf)
    cs.parseStr(cstemplate)

    body = cs.render()

    body = wikiutil.renderText(request, WikiParser, body)

    open("/tmp/out.html", "w").write(body)

    return body
예제 #8
0
def execute(macro, args):
    request = macro.request
    content = []
    page_name = macro.formatter.page.page_name

    # get args
    include_page_name = ''
    if args is not None:
        include_page_name = args

    include_page_name = wikiutil.AbsPageName(page_name, include_page_name)

    include_page = Page(request, include_page_name)

    if include_page is None:
        return ''
    if not request.user.may.read(include_page_name):
        return ''
    else:
        return wikiutil.renderText(request, WikiParser, include_page.getPageText())
예제 #9
0
 def _replace(self, key):
     """ replace a item_name if it is in the renames dict
         key is either a 2-tuple ('PAGE', pagename)
         or a 3-tuple ('FILE', pagename, filename)
     """
     current_page = self.pagename
     item_type, page_name, file_name = (key + (None, ))[:3]
     abs_page_name = wikiutil.AbsPageName(current_page, page_name)
     if item_type == 'PAGE':
         key = (item_type, abs_page_name)
         new_name = self.renames.get(key)
         if new_name is None:
             # we don't have an entry in rename map - apply the same magic
             # to the page name as 1.5 did (" " -> "_") and try again:
             abs_magic_name = abs_page_name.replace(u' ', u'_')
             key = (item_type, abs_magic_name)
             new_name = self.renames.get(key)
             if new_name is None:
                 # we didn't find it under the magic name either -
                 # that means we do not rename it!
                 new_name = page_name
         if new_name != page_name and abs_page_name != page_name:
             # we have to fix the (absolute) new_name to be a relative name (as it was before)
             new_name = wikiutil.RelPageName(current_page, new_name)
     elif item_type == 'FILE':
         key = (item_type, abs_page_name, file_name)
         new_name = self.renames.get(key)
         if new_name is None:
             # we don't have an entry in rename map - apply the same magic
             # to the page name as 1.5 did (" " -> "_") and try again:
             abs_magic_name = abs_page_name.replace(u' ', u'_')
             key = (item_type, abs_magic_name, file_name)
             new_name = self.renames.get(key)
             if new_name is None:
                 # we didn't find it under the magic name either -
                 # that means we do not rename it!
                 new_name = file_name
     return new_name
예제 #10
0
        def include_subfun(mo):
            match = mo.groups()

            if wikiutil.AbsPageName(page, match[1]) == oldpagename:
                # If the link was relative:
                if not oldpagename in match[0]:
                    # If the new page will be a subpage of the
                    # source, retain relative link. Else, make
                    # an absolute link.
                    if (rel_newpagename.startswith('/') or
                        rel_newpagename.startswith('../')):
                        return match[0].replace(
                            wikiutil.RelPageName(page, oldpagename),
                            rel_newpagename)
                    else:
                        return match[0].replace(
                            wikiutil.RelPageName(page, oldpagename),
                            newpagename)

                # Else, change absolute link
                return match[0].replace(oldpagename, newpagename)
            # No match in this link -> move on
            else:
                return match[0]
예제 #11
0
    def visit_reference(self, node):
        """
            Pass links to MoinMoin to get the correct wiki space url. Extract
            the url and pass it on to the html4css1 writer to handle. Inline
            images are also handled by visit_image. Not sure what the "drawing:"
            link scheme is used for, so for now it is handled here.

            Also included here is a hack to allow MoinMoin macros. This routine
            checks for a link which starts with "<<". This link is passed to the
            MoinMoin formatter and the resulting markup is inserted into the
            document in the place of the original link reference.
        """
        if 'refuri' in node.attributes:
            refuri = node['refuri']
            prefix = ''
            link = refuri
            if ':' in refuri:
                prefix, link = refuri.lstrip().split(':', 1)

            # First see if MoinMoin should handle completely. Exits through add_wiki_markup.
            if refuri.startswith('<<') and refuri.endswith('>>'):  # moin macro
                self.process_wiki_text(refuri)
                self.wiki_text = self.fixup_wiki_formatting(self.wiki_text)
                self.add_wiki_markup()

            if prefix == 'drawing':
                self.process_wiki_text("[[%s]]" % refuri)
                self.wiki_text = self.fixup_wiki_formatting(self.wiki_text)
                self.add_wiki_markup()

            # From here down, all links are handled by docutils (except
            # missing attachments), just fixup node['refuri'].
            if prefix == 'attachment':
                if not AttachFile.exists(self.request,
                                         self.request.page.page_name, link):
                    # Attachment doesn't exist, give to MoinMoin to insert upload text.
                    self.process_wiki_text("[[%s]]" % refuri)
                    self.wiki_text = self.fixup_wiki_formatting(self.wiki_text)
                    self.add_wiki_markup()
                # Attachment exists, just get a link to it.
                node['refuri'] = AttachFile.getAttachUrl(
                    self.request.page.page_name, link, self.request)
                if not [
                        i for i in node.children
                        if i.__class__ == docutils.nodes.image
                ]:
                    node['classes'].append(prefix)
            elif prefix == 'wiki':
                wiki_name, page_name = wikiutil.split_interwiki(link)
                wikitag, wikiurl, wikitail, err = wikiutil.resolve_interwiki(
                    self.request, wiki_name, page_name)
                wikiurl = wikiutil.mapURL(self.request, wikiurl)
                node['refuri'] = wikiutil.join_wiki(wikiurl, wikitail)
                # Only add additional class information if the reference does
                # not have a child image (don't want to add additional markup
                # for images with targets).
                if not [
                        i for i in node.children
                        if i.__class__ == docutils.nodes.image
                ]:
                    node['classes'].append('interwiki')
            elif prefix == 'javascript':
                # is someone trying to do XSS with javascript?
                node['refuri'] = 'javascript:alert("it does not work")'
            elif prefix != '':
                # Some link scheme (http, file, https, mailto, etc.), add class
                # information if the reference doesn't have a child image (don't
                # want additional markup for images with targets).
                # Don't touch the refuri.
                if not [
                        i for i in node.children
                        if i.__class__ == docutils.nodes.image
                ]:
                    node['classes'].append(prefix)
            else:
                # Default case - make a link to a wiki page.
                pagename, anchor = wikiutil.split_anchor(refuri)
                page = Page(
                    self.request,
                    wikiutil.AbsPageName(self.formatter.page.page_name,
                                         pagename))
                node['refuri'] = page.url(self.request, anchor=anchor)
                if not page.exists():
                    node['classes'].append('nonexistent')
        html4css1.HTMLTranslator.visit_reference(self, node)
예제 #12
0
 def _check_abs_pagename(self, current_page, relative_page, absolute_page):
     assert absolute_page == wikiutil.AbsPageName(current_page, relative_page)
예제 #13
0
def execute(macro,
            text,
            args_re=re.compile(_args_re_pattern),
            title_re=re.compile(_title_re, re.M),
            called_by_toc=0):
    request = macro.request
    _ = request.getText

    # return immediately if getting links for the current page
    if request.mode_getpagelinks:
        return ''

    # parse and check arguments
    args = text and args_re.match(text)
    if not args:
        return (_sysmsg % ('error', _('Invalid include arguments "%s"!')) %
                (text, ))

    # prepare including page
    result = []
    print_mode = macro.form.has_key('action') and macro.form['action'][0] in (
        "print", "format")
    this_page = macro.formatter.page
    if not hasattr(this_page, '_macroInclude_pagelist'):
        this_page._macroInclude_pagelist = {}

    # get list of pages to include
    inc_name = wikiutil.AbsPageName(request, this_page.page_name,
                                    args.group('name'))
    pagelist = [inc_name]
    if inc_name.startswith("^"):
        try:
            inc_match = re.compile(inc_name)
        except re.error:
            pass  # treat as plain page name
        else:
            # Get user filtered readable page list
            pagelist = request.rootpage.getPageList(filter=inc_match.match)

    # sort and limit page list
    pagelist.sort()
    sort_dir = args.group('sort')
    if sort_dir == 'descending':
        pagelist.reverse()
    max_items = args.group('items')
    if max_items:
        pagelist = pagelist[:int(max_items)]

    skipitems = 0
    if args.group("skipitems"):
        skipitems = int(args.group("skipitems"))
    titlesonly = args.group('titlesonly')
    editlink = args.group('editlink')

    # iterate over pages
    for inc_name in pagelist:
        if not request.user.may.read(inc_name):
            continue
        if this_page._macroInclude_pagelist.has_key(inc_name):
            result.append(
                u'<p><strong class="error">Recursive include of "%s" forbidden</strong></p>'
                % (inc_name, ))
            continue
        if skipitems:
            skipitems -= 1
            continue
        fmt = macro.formatter.__class__(request, is_included=True)
        fmt._base_depth = macro.formatter._base_depth
        inc_page = Page(request, inc_name, formatter=fmt)
        if not inc_page.exists():
            continue
        inc_page._macroInclude_pagelist = this_page._macroInclude_pagelist

        # check for "from" and "to" arguments (allowing partial includes)
        body = inc_page.get_raw_body() + '\n'

        #        body = body.replace(this_page.page_name, "_" + this_page.page_name + "_")
        body = body.replace('amcl', "_" + this_page.page_name + "_")

        # set or increment include marker
        this_page._macroInclude_pagelist[inc_name] = \
            this_page._macroInclude_pagelist.get(inc_name, 0) + 1

        # output the included page
        strfile = StringIO.StringIO()
        request.redirect(strfile)
        try:
            cid = request.makeUniqueID(
                "Include_%s" % wikiutil.quoteWikinameURL(inc_page.page_name))
            inc_page.send_page(request,
                               content_only=1,
                               content_id=cid,
                               omit_footnotes=True)
            result.append(strfile.getvalue())
        finally:
            request.redirect()

        # decrement or remove include marker
        if this_page._macroInclude_pagelist[inc_name] > 1:
            this_page._macroInclude_pagelist[inc_name] = \
                this_page._macroInclude_pagelist[inc_name] - 1
        else:
            del this_page._macroInclude_pagelist[inc_name]

    # return include text
    str = ''.join(result)
    return str
예제 #14
0
파일: Include.py 프로젝트: aahlad/soar
def execute(macro, text, args_re=re.compile(_args_re_pattern), title_re=re.compile(_title_re, re.M)):
    request = macro.request
    _ = request.getText

    # return immediately if getting links for the current page
    if request.mode_getpagelinks:
        return ''

    # parse and check arguments
    args = text and args_re.match(text)
    if not args:
        return (_sysmsg % ('error', _('Invalid include arguments "%s"!')) % (text, ))

    # prepare including page
    result = []
    print_mode = request.action in ("print", "format")
    this_page = macro.formatter.page
    if not hasattr(this_page, '_macroInclude_pagelist'):
        this_page._macroInclude_pagelist = {}

    # get list of pages to include
    inc_name = wikiutil.AbsPageName(this_page.page_name, args.group('name'))
    pagelist = [inc_name]
    if inc_name.startswith("^"):
        try:
            inc_match = re.compile(inc_name)
        except re.error:
            pass # treat as plain page name
        else:
            # Get user filtered readable page list
            pagelist = request.rootpage.getPageList(filter=inc_match.match)

    # sort and limit page list
    pagelist.sort()
    sort_dir = args.group('sort')
    if sort_dir == 'descending':
        pagelist.reverse()
    max_items = args.group('items')
    if max_items:
        pagelist = pagelist[:int(max_items)]

    skipitems = 0
    if args.group("skipitems"):
        skipitems = int(args.group("skipitems"))
    titlesonly = args.group('titlesonly')
    editlink = args.group('editlink')

    # iterate over pages
    for inc_name in pagelist:
        if not request.user.may.read(inc_name):
            continue
        if inc_name in this_page._macroInclude_pagelist:
            result.append(u'<p><strong class="error">Recursive include of "%s" forbidden</strong></p>' % (inc_name, ))
            continue
        if skipitems:
            skipitems -= 1
            continue
        fmt = macro.formatter.__class__(request, is_included=True)
        fmt._base_depth = macro.formatter._base_depth
        inc_page = Page(request, inc_name, formatter=fmt)
        if not inc_page.exists():
            continue
        inc_page._macroInclude_pagelist = this_page._macroInclude_pagelist

        # check for "from" and "to" arguments (allowing partial includes)
        body = inc_page.get_raw_body() + '\n'
        from_pos = 0
        to_pos = -1
        from_re = args.group('from')
        if from_re:
            try:
                from_match = re.compile(from_re, re.M).search(body)
            except re.error:
                ##result.append("*** fe=%s ***" % e)
                from_match = re.compile(re.escape(from_re), re.M).search(body)
            if from_match:
                from_pos = from_match.end()
            else:
                result.append(_sysmsg % ('warning', 'Include: ' + _('Nothing found for "%s"!')) % from_re)
        to_re = args.group('to')
        if to_re:
            try:
                to_match = re.compile(to_re, re.M).search(body, from_pos)
            except re.error:
                to_match = re.compile(re.escape(to_re), re.M).search(body, from_pos)
            if to_match:
                to_pos = to_match.start()
            else:
                result.append(_sysmsg % ('warning', 'Include: ' + _('Nothing found for "%s"!')) % to_re)

        if titlesonly:
            levelstack = []
            for title, level in extract_titles(body[from_pos:to_pos], title_re):
                if levelstack:
                    if level > levelstack[-1]:
                        result.append(macro.formatter.bullet_list(1))
                        levelstack.append(level)
                    else:
                        while levelstack and level < levelstack[-1]:
                            result.append(macro.formatter.bullet_list(0))
                            levelstack.pop()
                        if not levelstack or level != levelstack[-1]:
                            result.append(macro.formatter.bullet_list(1))
                            levelstack.append(level)
                else:
                    result.append(macro.formatter.bullet_list(1))
                    levelstack.append(level)
                result.append(macro.formatter.listitem(1))
                result.append(inc_page.link_to(request, title))
                result.append(macro.formatter.listitem(0))
            while levelstack:
                result.append(macro.formatter.bullet_list(0))
                levelstack.pop()
            continue

        if from_pos or to_pos != -1:
            inc_page.set_raw_body(body[from_pos:to_pos], modified=True)
        ##result.append("*** f=%s t=%s ***" % (from_re, to_re))
        ##result.append("*** f=%d t=%d ***" % (from_pos, to_pos))

        if not hasattr(request, "_Include_backto"):
            request._Include_backto = this_page.page_name

        # do headings
        level = None
        if args.group('heading') and args.group('hquote'):
            heading = args.group('htext') or inc_page.split_title()
            level = 1
            if args.group('level'):
                level = int(args.group('level'))
            if print_mode:
                result.append(macro.formatter.heading(1, level) +
                              macro.formatter.text(heading) +
                              macro.formatter.heading(0, level))
            else:
                url = inc_page.url(request)
                result.extend([
                    macro.formatter.heading(1, level, id=heading),
                    macro.formatter.url(1, url, css="include-heading-link"),
                    macro.formatter.text(heading),
                    macro.formatter.url(0),
                    macro.formatter.heading(0, level),
                ])

        # set or increment include marker
        this_page._macroInclude_pagelist[inc_name] = \
            this_page._macroInclude_pagelist.get(inc_name, 0) + 1

        # output the included page
        strfile = StringIO.StringIO()
        request.redirect(strfile)
        try:
            inc_page.send_page(content_only=True,
                               omit_footnotes=True,
                               count_hit=False)
            result.append(strfile.getvalue())
        finally:
            request.redirect()

        # decrement or remove include marker
        if this_page._macroInclude_pagelist[inc_name] > 1:
            this_page._macroInclude_pagelist[inc_name] = \
                this_page._macroInclude_pagelist[inc_name] - 1
        else:
            del this_page._macroInclude_pagelist[inc_name]

        # if no heading and not in print mode, then output a helper link
        if editlink and not (level or print_mode):
            result.extend([
                macro.formatter.div(1, css_class="include-link"),
                inc_page.link_to(request, '[%s]' % (inc_name, ), css_class="include-page-link"),
                inc_page.link_to(request, '[%s]' % (_('edit'), ), css_class="include-edit-link", querystr={'action': 'edit', 'backto': request._Include_backto}),
                macro.formatter.div(0),
            ])
        # XXX page.link_to is wrong now, it escapes the edit_icon html as it escapes normal text

    # return include text
    return ''.join(result)
예제 #15
0
def execute(macro, text):
    _ = macro.request.getText

    # Retain original values
    if not hasattr(macro.request, 'includingpage'):
        macro.request.includingpage = list()
    macro.request.includingpage.append(macro.request.page)
    orig_exists = Page.exists
    orig_link_to = Page.link_to
    orig__init__ = Page.__init__
    orig_send_page = Page.send_page

    # Try-finally construct over override functions so that modified
    # copies of Page are not littered with persistent req types
    try:
        args_re = re.compile(_args_re_pattern)
        args = text and args_re.match(text)

        # Start overrides if args match
        if text and args:
            inc_name = wikiutil.AbsPageName(macro.formatter.page.page_name,
                                            args.group('name'))

            # Hook send_page into sending a div before and after each
            # included page
            def new_send_page(self, **keywords):
                self.request.write(
                    self.request.formatter.div(True,
                                               css_class='gwikiinclude',
                                               id=id_escape(self.page_name) + \
                                                   SEPARATOR))
                orig_send_page(self, **keywords)
                self.request.write(self.request.formatter.div(False))

            Page.send_page = new_send_page

            # Additions that only account for includes of specific pages
            if not inc_name.startswith('^'):
                rev = args.group('rev')
                try:
                    rev = int(rev)
                except:
                    rev = None

                # Remove from/to regexes from nonexisting pages, so
                # that nasty error messages are suppressed
                if not Page(macro.request, inc_name).exists():
                    text = re.sub(Include._arg_to, '', text)
                    text = re.sub(Include._arg_from, '', text)

                # Override exists to support including revisions and
                # the editing of nonexisting pages
                def new_exists(self, **kw):
                    exists = orig_exists(self, **kw)
                    if self.formatter:
                        # Fix a Moin bug in handling attachments: If
                        # the formatter has page defined, it will
                        # handle attachment links relative to the
                        # including page, not the included page. For
                        # some reason, the formatter has not always
                        # been initialised, leading to crashes, so
                        # check its existence first.
                        self.formatter.request.page = self

                    if self.page_name == inc_name:
                        if rev:
                            self.rev = rev

                        # Mark pages that do not really exist
                        if not exists:
                            self._macro_Include_nonexisting = True
                            exists = True

                    return exists

                Page.exists = new_exists

                if rev:

                    def new__init__(self, request, page_name, **kw):
                        kw['rev'] = rev
                        return orig__init__(self, request, page_name, **kw)

                    Page.__init__ = new__init__

                # Override link_to to support added templates
                template = args.group('template')

                def new_link_to(self,
                                request,
                                text=None,
                                querystr=dict(),
                                anchor=None,
                                **kw):

                    if self.page_name == inc_name:
                        # Let's see if we've a link to nonexisting page
                        if getattr(self, '_macro_Include_nonexisting', False):
                            # Modify editlinks with template selection
                            if kw.get('css_class', '') == "include-edit-link":
                                if template:
                                    querystr['template'] = template
                                    text = '[%s]' % _('create')
                                else:
                                    orig_page = macro.request.page.page_name
                                    msg = wr(
                                        '<form method="GET" action="%s">\n',
                                        actionname(request,
                                                   querystr['backto']))
                                    msg += wr('<select name="template">\n')
                                    msg += wr('<option value="">%s</option>\n',
                                              _("No template"))

                                    # Get list of template pages readable by current user
                                    filterfn = request.cfg.cache.page_template_regexact.search
                                    templates = request.rootpage.getPageList(
                                        filter=filterfn)
                                    for i in templates:
                                        msg += wr(
                                            '<option value="%s">%s</option>\n',
                                            i, i)

                                    msg += '</select>\n'
                                    msg += '<input type="hidden" name="action" value="newpage">\n'
                                    msg += wr(
                                        '<input type="hidden" name="pagename" value="%s">\n',
                                        inc_name)
                                    msg += wr(
                                        '<input type="submit" value="%s">\n',
                                        _('create'))
                                    msg += wr('</form>\n')

                                    return msg

                            # Do not give pagelinks to nonexisting pages
                            if kw.get('css_class', '') == "include-page-link":
                                return text

                        # Add revision information to rev links
                        elif rev:
                            if kw.get('css_class', '') == "include-page-link":
                                querystr['action'] = 'recall'
                                querystr['rev'] = str(rev)
                                text = "%s revision %d]" % (text[:-1], rev)
                            elif kw.get('css_class',
                                        '') == "include-edit-link":
                                text = '[%s]' % _("edit current version")

                    return orig_link_to(self, request, text, querystr, anchor,
                                        **kw)

                Page.link_to = new_link_to

        # Call the original Include-macro
        retval = _orig_execute(macro, text, args_re=args_re)
    finally:
        # Cleanup and return
        Page.exists = orig_exists
        Page.link_to = orig_link_to
        Page.__init__ = orig__init__
        Page.send_page = orig_send_page

    # request.page might have been changed in page.new_exists, so it
    # needs to be returned to its original value
    macro.request.page = macro.request.includingpage.pop()
    if not macro.request.includingpage:
        del macro.request.includingpage

    return retval