コード例 #1
0
ファイル: verse_role.py プロジェクト: yoyossy/theoreST__cdjc
def verse_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
    #print(role,' - ',rawtext,' - ',text,file=sys.stderr)
    env = inliner.document.settings.env
    bible_version = env.app.config.bible_version
    if bible_version not in version_reference_functions:
        raise Exception("Unknown bible version. I don't know about "+bible_version)
    bibleref_function = version_reference_functions[bible_version]
    p = Parser(text)
    try:
        vrlist = p.parse_verse_references()
    except ParseException as pe:
        msg = inliner.reporter.error("Exception parsing '"+text+"':"+str(pe), line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    nodels = []
    roles.set_classes(options)
    for vr in vrlist:
        #print('refuri is',bibleref_function(vr),file=sys.stderr)
        #print('opts:',options)
        node = nodes.reference(rawtext, vr.text, internal=False, refuri=bibleref_function(vr), **options)
        nodels.append(node)
        nodels.append(nodes.generated(', ',', ', **options))
    if len(nodels) > 1:
        del nodels[-1] # delete last comma
    return nodels,[]
コード例 #2
0
    def update_section_numbers(self, node, prefix=(), depth=0, level=0):
        self.suffix = '.'
        depth += 1
        if prefix:
            sectnum = 1
        else:
            sectnum = self.startvalue
        level += 1
        index_rule = 1
        index_directive = 1
        for child in node:
            if isinstance(child, nodes.section):
                title = child[0]

                if level > self.start_depth:
                    numbers = prefix + (str(sectnum), )
                    text = (self.prefix + '.'.join(numbers) + self.suffix +
                            u'\u00a0' * 2)
                else:
                    numbers = prefix
                    text = ''

                generated = nodes.generated('', text, classes=['sectnum'])
                title.insert(0, generated)
                title['auto'] = 1
                if depth < self.maxdepth:
                    self.update_section_numbers(child, numbers, depth, level)
                sectnum += 1
 def run (self):
     newnode = citationgroup(rawsource=self.arguments[0],text=self.arguments[0])
     content = '\n'.join(self.content)
     newnodes = nodes.generated(rawsource=content)
     self.state.nested_parse(self.content, self.content_offset,
                             newnodes)
     return [newnode,newnodes]
コード例 #4
0
    def run(self):
        config = self.state.document.settings.env.app.config
        if 'breathe' in self.options:
            breathe_directive_name = self.options['breathe']
        else:
            breathe_directive_name = config.breathelink_default_breathe_directive
        if 'doxylink' in self.options:
            doxylink_role_name = self.options['doxylink']
        else:
            doxylink_role_name = config.breathelink_default_doxylink_role

        new_content = []
        for argument in self.arguments:
            arguments = [argument]
            options = {'no-link': ''}
            breathe_directive_class, messages = rst.directives.directive(
                breathe_directive_name, self.state.memo.language,
                self.state.document)
            self.state.parent += messages
            breathe_directive_instance = breathe_directive_class(
                breathe_directive_name, arguments, options, self.content,
                self.lineno, self.content_offset, self.block_text, self.state,
                self.state_machine)
            new_content += breathe_directive_instance.run()

            list_item = nodes.generated('', '')
            list_item.reporter = self.state_machine.reporter
            doxylink_role_class, messages = rst.roles.role(
                doxylink_role_name, self.state.memo.language, self.lineno,
                self.state_machine.reporter)
            self.state.parent += messages
            role_nodes, messages = doxylink_role_class(doxylink_role_name, '',
                                                       arguments[0],
                                                       self.lineno, list_item)
            # The reporter function is not picklable
            list_item.reporter = None
            self.state.parent += messages
            list_item += nodes.generated('', 'See ')
            list_item += role_nodes
            list_item += nodes.generated('', ' for additional documentation.')

            link = nodes.bullet_list('')
            link['bullet'] = '-'
            link += list_item
            new_content += link

        return new_content
コード例 #5
0
    def run (self):
        if not self.options.has_key('court-id'):
            error = self.state_machine.reporter.error(
                'Invalid context: missing court-id option in court directive',
                nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
            return [error]

        traveling_jurisdiction[0] = self.options["court-id"]
        if self.options.has_key("flp-key"):
            courts_map[self.options["flp-key"]] = self.options["court-id"]

        court_id_node = courtid()
        court_id_bubble = courtbubble(rawsource=self.options['court-id'],text=self.options['court-id'])
        court_id_bubble["href"] = self.mkGitHubUrl("courts",self.options["court-id"])
        court_id_node += court_id_bubble
        court_node = court()
        court_text = nodes.inline(rawsource=self.arguments[0],text=self.arguments[0])
        if self.options.has_key("url"):
            court_ref = nodes.reference(refuri=self.options["url"])
            court_link = octiconlink()
            court_ref += court_link
            court_ref += court_text
            court_node += court_ref
        else:
            court_node += court_text

        # Split in two here, and validate.
        # notes:: is optional, must be the first element if present, and can occur only once. 
        # reporter:: is the only other permitted element.

        foundNotes = False
        foundReporter = False
        reporter_offset = 0
        for line in self.content:
            if line.startswith('.. reporter::'):
                foundReporter = True
            if line.startswith('.. notes::'):
                if foundReporter:
                    error = self.state_machine.reporter.error(
                        'Invalid structure: notes:: must come before any reporter:: in court directive',
                        nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
                    return [error]
            if not foundReporter:
                reporter_offset += 1
        
        note_content = '\n'.join(self.content[0:reporter_offset])
        note_node = nodes.generated(rawsource=note_content)
        self.state.nested_parse(self.content[0:reporter_offset], self.content_offset,
                                note_node)

        reporter_content = '\n'.join(self.content[reporter_offset:])
        reporters_node = reporters()
        self.state.nested_parse(self.content[reporter_offset:], self.content_offset + reporter_offset,
                                reporters_node)

        return [court_node,court_id_node,note_node,reporters_node]
コード例 #6
0
ファイル: breathelink.py プロジェクト: thewtex/breathelink
    def run(self):
        config = self.state.document.settings.env.app.config
        if self.options.has_key('breathe'):
            breathe_directive_name = self.options['breathe']
        else:
            breathe_directive_name = config.breathelink_default_breathe_directive
        if self.options.has_key('doxylink'):
            doxylink_role_name = self.options['doxylink']
        else:
            doxylink_role_name = config.breathelink_default_doxylink_role

        new_content = []
        for argument in self.arguments:
            arguments = [argument]
            options = {'no-link': ''}
            breathe_directive_class, messages = rst.directives.directive(breathe_directive_name,
                    self.state.memo.language, self.state.document)
            self.state.parent += messages
            breathe_directive_instance = breathe_directive_class(breathe_directive_name,
                    arguments, options, self.content, self.lineno,
                    self.content_offset, self.block_text, self.state, self.state_machine)
            new_content += breathe_directive_instance.run()

            list_item = nodes.generated('', '')
            list_item.reporter = self.state_machine.reporter
            doxylink_role_class, messages = rst.roles.role(doxylink_role_name,
                    self.state.memo.language, self.lineno, self.state_machine.reporter)
            self.state.parent += messages
            role_nodes, messages = doxylink_role_class(doxylink_role_name, '',
                    arguments[0], self.lineno, list_item)
            # The reporter function is not picklable
            list_item.reporter = None
            self.state.parent += messages
            list_item += nodes.generated('', 'See ')
            list_item += role_nodes
            list_item += nodes.generated('', ' for additional documentation.')

            link = nodes.bullet_list('')
            link['bullet'] = '-'
            link += list_item
            new_content += link

        return new_content
コード例 #7
0
def AAFigureDirective(name, arguments, options, content, lineno,
                  content_offset, block_text, state, state_machine):
    text = '\n'.join(content)

    global aafigure_counter

    # ensure that options are present and initialized with defaults if not given
    if 'background' not in options: options['background'] = '#ffffff'
    if 'foreground' not in options: options['foreground'] = '#000000'
    if 'fill' not in options: options['fill'] = options['foreground'] # fill = fore by default
    if 'scale' not in options: options['scale'] = 1
    if 'line_width' not in options: options['line_width'] = 2
    if 'format' not in options: options['format'] = DEFAULT_FORMAT
    if 'aspect' not in options: options['aspect'] = 1
    if 'proportional' not in options: options['proportional'] = False
    if 'name' not in options:
        options['name'] = 'aafigure-%i' % aafigure_counter
        aafigure_counter += 1

    output_name = options['name'] + '.' + options['format'].lower()
    try:
        (visitor, output) = aafigure.render(text, output_name, options)
    except aafigure.UnsupportedFormatError as e:
        result = [state_machine.reporter.error(str(e),
            nodes.literal_block(block_text, block_text),
            line=lineno
        )]
    output.close()

    if options['format'] == 'svg':
        #~ svgout.visit(aaimg, xml_header = False)
        # insert data into html using a raw node
        attributes = {'format': 'html'}
        #~ # result = [nodes.raw('', '<embed src="%s" %s type="image/svg+xml"/>' % (
        result = [nodes.raw('', '<object type="image/svg+xml" data="%s" %s>'
                '</object>' % (output_name, visitor.get_size_attrs()),
                **attributes)]
        #~ result = [nodes.raw('', io.getvalue(), **attributes)]
    elif options['format'] == 'pdf':
        # Return a link.
        wrapper = nodes.generated()
        wrapper.append(nodes.reference('', '%s (PDF)' % options['name'],
            refuri=os.path.basename(output_name)
        ))
        result = [wrapper]
    else:
        # Return an image directive.
        image_options = {}
        image_options['uri'] = os.path.basename(output_name)
        result = [nodes.image(output_name, **image_options)]

    return result
    def run (self):
        if not self.options.has_key('court-id'):
            error = self.state_machine.reporter.error(
                'Invalid context: missing court-id option in court directive',
                nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
            return [error]
        court_id_node = courtid()
        court_id_bubble = courtbubble(rawsource=self.options['court-id'],text=self.options['court-id'])
        court_id_bubble["href"] = self.mkGitHubUrl("courts",self.options["court-id"])
        court_id_node += court_id_bubble
        court_node = court()
        court_text = nodes.inline(rawsource=self.arguments[0],text=self.arguments[0])
        if self.options.has_key("url"):
            court_ref = nodes.reference(refuri=self.options["url"])
            court_link = octiconlink()
            court_ref += court_link
            court_ref += court_text
            court_node += court_ref
        else:
            court_node += court_text

        # Split in two here, and validate.
        # notes:: is optional, must be the first element if present, and can occur only once. 
        # reporter:: is the only other permitted element.

        foundNotes = False
        foundReporter = False
        reporter_offset = 0
        for line in self.content:
            if line.startswith('.. reporter::'):
                foundReporter = True
            if line.startswith('.. notes::'):
                if foundReporter:
                    error = self.state_machine.reporter.error(
                        'Invalid structure: notes:: must come before any reporter:: in court directive',
                        nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
                    return [error]
            if not foundReporter:
                reporter_offset += 1
        
        note_content = '\n'.join(self.content[0:reporter_offset])
        note_node = nodes.generated(rawsource=note_content)
        self.state.nested_parse(self.content[0:reporter_offset], self.content_offset,
                                note_node)

        reporter_content = '\n'.join(self.content[reporter_offset:])
        reporters_node = reporters()
        self.state.nested_parse(self.content[reporter_offset:], self.content_offset + reporter_offset,
                                reporters_node)

        return [court_node,court_id_node,note_node,reporters_node]
コード例 #9
0
ファイル: xfunction.py プロジェクト: vermosen/datatable
    def _generate_sigbody(self, node):
        row1 = xnodes.div(classes=["sig-qualifier"])
        ref = addnodes.pending_xref("",
                                    nodes.Text(self.qualifier),
                                    reftarget=self.qualifier[:-1],
                                    reftype="class",
                                    refdomain="py")
        # Note: `ref` cannot be added directly: docutils requires that
        # <reference> nodes were nested inside <TextElement> nodes.
        row1 += nodes.generated("", "", ref)
        node += row1

        row2 = xnodes.div(classes=["sig-main"])
        self._generate_sigmain(row2)
        node += row2
コード例 #10
0
 def update_section_numbers(self, node, prefix=(), depth=0):
     depth += 1
     sectnum = 1
     for child in node:
         if isinstance(child, nodes.section):
             numbers = prefix + (str(sectnum),)
             title = child[0]
             # Use &nbsp; for spacing:
             generated = nodes.generated(
                 '', '.'.join(numbers) + u'\u00a0' * 3, CLASS='sectnum')
             title.insert(0, generated)
             title['auto'] = 1
             if depth < self.maxdepth:
                 self.update_section_numbers(child, numbers, depth)
             sectnum += 1
コード例 #11
0
ファイル: util.py プロジェクト: egh/zot4rst
    def walk(html_node):
        """
        Walk the tree, building a reStructuredText object as we go.
        """
        if html_node is None:
            return None
        elif ((type(html_node) == BeautifulSoup.NavigableString) or (type(html_node) == str) or (type(html_node) == unicode)
):
            # Terminal nodes
            text = cleanString(unicode(html_node))
            # whitespace is significant in reST, so normalize empties to a single space
            if re.match("^\s+$", text):
                return nodes.Text(" ")
            else:
                return nodes.Text(text)
        else:
            # Nesting nodes.
            if (html_node.name == 'span'):
                ret = None
                if (html_node.has_key('style') and (html_node['style'] == "font-style:italic;")):
                    children = compact([walk(c) for c in html_node.contents])
                    return nodes.emphasis("", "", *children)
                elif (html_node.has_key('style') and (html_node['style'] == "font-variant:small-caps;")):
                    children = compact([walk(c) for c in html_node.contents])
                    return xciterst.smallcaps("", "", *children)
                elif (html_node.has_key('style') and (html_node['style'] == "font-style:normal;")):
                    children = compact([walk(c) for c in html_node.contents])
                    return nodes.emphasis("", "", *children)
                else:
                    children = compact(walk("".join([ str(c) for c in html_node.contents ])))
                    return nodes.generated("", "", *children)
            if (html_node.name == 'i'):
                children = compact([walk(c) for c in html_node.contents])
                return nodes.emphasis("", "", *children)
            elif (html_node.name == 'b'):
                children = compact([walk(c) for c in html_node.contents ])
                return nodes.strong("", "", *children)
            elif (html_node.name == 'p'):
                children = compact([ walk(c) for c in html_node.contents ])
                return nodes.paragraph("", "", *children)
            elif (html_node.name == 'a'):
                children = compact([ walk(c) for c in html_node.contents ])
                return apply(nodes.reference, ["", ""] + children, { 'refuri' : html_node['href'] })
            elif (html_node.name == 'div'):
                children = compact([ walk(c) for c in html_node.contents ])
                classes = re.split(" ", html_node.get('class', ""))
                return nodes.container("", *wrap_text(children), classes=classes)
コード例 #12
0
ファイル: parts.py プロジェクト: Naviacom/Configurations
 def update_section_numbers(self, node, prefix=(), depth=0):
     depth += 1
     if prefix:
         sectnum = 1
     else:
         sectnum = self.startvalue
     for child in node:
         if isinstance(child, nodes.section):
             numbers = prefix + (str(sectnum),)
             title = child[0]
             # Use &nbsp; for spacing:
             generated = nodes.generated(
                 '', (self.prefix + '.'.join(numbers) + self.suffix
                      +  '\u00a0' * 3),
                 classes=['sectnum'])
             title.insert(0, generated)
             title['auto'] = 1
             if depth < self.maxdepth:
                 self.update_section_numbers(child, numbers, depth)
             sectnum += 1
コード例 #13
0
 def update_section_numbers(self, node, prefix=(), depth=0):
     depth += 1
     if prefix:
         sectnum = 1
     else:
         sectnum = self.startvalue
     for child in node:
         if isinstance(child, nodes.section):
             numbers = prefix + (str(sectnum),)
             title = child[0]
             # Use &nbsp; for spacing:
             generated = nodes.generated(
                 '', (self.prefix + '.'.join(numbers) + self.suffix
                      +  u'\u00a0' * 3),
                 classes=['sectnum'])
             title.insert(0, generated)
             title['auto'] = 1
             if depth < self.maxdepth:
                 self.update_section_numbers(child, numbers, depth)
             sectnum += 1
コード例 #14
0
    def apply(self):

        # self.startnode is the pending marker
        # self.startnode.parent is the translation text
        # self.startnode.parent.parent is the enclosing node, whatever it is

        translation = self.startnode.parent.astext()
        empty = nodes.generated()
        self.startnode.parent.replace_self(empty)

        # Okay, so we want to add a wrapper around children,
        # and make the wrapper the new child of self.startnode.parent.parent

        altie = altwrapper()
        altie["title"] = translation
        for child in self.startnode.parent.parent.children:
            newchild = child.deepcopy()
            altie += newchild
            altie.setup_child(newchild)
        self.startnode.parent.parent.children = [altie]
        self.startnode.parent.parent.setup_child(altie)
コード例 #15
0
    def apply(self):

        # self.startnode is the pending marker
        # self.startnode.parent is the translation text
        # self.startnode.parent.parent is the enclosing node, whatever it is

        translation = self.startnode.parent.astext()
        empty = nodes.generated()
        self.startnode.parent.replace_self(empty)

        # Okay, so we want to add a wrapper around children,
        # and make the wrapper the new child of self.startnode.parent.parent

        altie = altwrapper()
        altie["title"] = translation
        for child in self.startnode.parent.parent.children:
            newchild = child.deepcopy()
            altie += newchild
            altie.setup_child(newchild)
        self.startnode.parent.parent.children = [altie]
        self.startnode.parent.parent.setup_child(altie)
コード例 #16
0
ファイル: verse_role.py プロジェクト: cdjc/theoreST
def verse_reference_role(role,
                         rawtext,
                         text,
                         lineno,
                         inliner,
                         options={},
                         content=[]):
    #print(role,' - ',rawtext,' - ',text,file=sys.stderr)
    env = inliner.document.settings.env
    bible_version = env.app.config.bible_version
    if bible_version not in version_reference_functions:
        raise Exception("Unknown bible version. I don't know about " +
                        bible_version)
    bibleref_function = version_reference_functions[bible_version]
    p = Parser(text)
    try:
        vrlist = p.parse_verse_references()
    except ParseException as pe:
        #print(pe)
        msg = inliner.reporter.error("Exception parsing '" + text + "':" +
                                     str(pe),
                                     line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    nodels = []
    roles.set_classes(options)
    for vr in vrlist:
        #print('refuri is',bibleref_function(vr),file=sys.stderr)
        #print('opts:',options)
        node = nodes.reference(rawtext,
                               vr.text,
                               internal=False,
                               refuri=bibleref_function(vr),
                               **options)
        nodels.append(node)
        nodels.append(nodes.generated(', ', ', ', **options))
    if len(nodels) > 1:
        del nodels[-1]  # delete last comma
    return nodels, []
コード例 #17
0
    def run (self):
        dates = Dates()
        if not self.options.has_key('edition-abbreviation'):
            error = self.state_machine.reporter.error(
                'Invalid context: missing edition-abbreviation option in reporter directive',
                nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
            return [error]
        if not self.options.has_key('dates'):
            error = self.state_machine.reporter.error(
                'Invalid context: missing dates in reporter directive',
                nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
            return [error]
        m = re.match("^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})-(?:([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})|(present))",self.options["dates"])
        if not m:
            error = self.state_machine.reporter.error(
                'Invalid context: misformatted dates range in reporter directive. Format must be YYYY/MM/DD-YYYY/MM/DD or YYYY/MM/DD-present',
                nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
            return [error]

        dates.startYearDisplay = m.group(1)
        dates.startYear = m.group(1)
        dates.startMonth = m.group(2)
        dates.startDay = m.group(3)
        if m.group(4):
            dates.endYear = m.group(4)
            dates.endYearDisplay = m.group(4)
            dates.endMonth = m.group(5)
            dates.endDay = m.group(6)
        else:
            dates.endYearDisplay = m.group(7)
            dates.endYear = False
            dates.endMonth = False
            dates.endDay = False

        ## Save segments as short names to avoid going crazy.

        if traveler.hook.reporter_start:
            traveler.hook.reporter_start(self.options, dates, self.arguments[0])
        
        # That's everything but variations, which are handled by the directive.
        dummy = nodes.generated()
        self.state.nested_parse(self.content, self.content_offset,
                                dummy)

        if traveler.hook.reporter_end:
            traveler.hook.reporter_end(self.options, self.arguments[0])

        reporter_box_node = self.makeContainer("reporter-box", suffix="")

        if self.options.has_key("neutral"):
            reporter_node = self.makeContainer("reporter neutral")
        else:
            reporter_node = self.makeContainer("reporter")

        reporter_name = self.arguments[0].replace("'",u"\u0027")
        reporter_name_node = self.makeContainer("reporter-name", rawsource=self.arguments[0],text=reporter_name)

        description_node = self.makeContainer("description-box",suffix="")

        abbrev = self.makeMiniBubble(self.options["jurisdiction"],self.options["edition-abbreviation"])
        start = self.makeLabelNode(dates.startYearDisplay,key="From")
        end = self.makeLabelNode(dates.endYearDisplay,key="To")
        if self.options.has_key("neutral"):
            neutral =  self.makeLabelNode("yes",key="Neutral",nodeType=valueneutral)
        else:
            neutral =  self.makeLabelNode("no",key="Neutral")
            
        if self.options.has_key("confirmed"):
            confirmed = self.makeLabelNode("yes",key="Confirmed")
        else:
            confirmed = self.makeLabelNode("no",key="Confirmed",nodeType=valueunconfirmed)

        description_node += abbrev
        description_node += start
        description_node += end
        description_node += neutral
        description_node += confirmed

        feature_node = self.makeContainer("feature-box",suffix="")
        keys = traveler.features.local.required.keys()
        keys.sort()
        for feature in keys:
            feature_node += self.makeLabelNode(u"req\u0027d",key=feature)
            
        keys = traveler.features.local.optional.keys()
        keys.sort()
        for feature in keys:
            feature_node += self.makeLabelNode("optional",key=feature)

        reporter_node += reporter_name_node
        reporter_node += description_node
        reporter_node += feature_node
        reporter_box_node += reporter_node
        return [reporter_box_node]
コード例 #18
0
    def run(self):
        dates = Dates()
        if not self.options.has_key('edition-abbreviation'):
            error = self.state_machine.reporter.error(
                'Invalid context: missing edition-abbreviation option in reporter directive',
                nodes.literal_block(self.block_text, self.block_text),
                line=self.lineno)
            return [error]
        if not self.options.has_key('dates'):
            error = self.state_machine.reporter.error(
                'Invalid context: missing dates in reporter directive',
                nodes.literal_block(self.block_text, self.block_text),
                line=self.lineno)
            return [error]
        m = re.match(
            "^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})-(?:([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})|(present))",
            self.options["dates"])
        if not m:
            error = self.state_machine.reporter.error(
                'Invalid context: misformatted dates range in reporter directive. Format must be YYYY/MM/DD-YYYY/MM/DD or YYYY/MM/DD-present',
                nodes.literal_block(self.block_text, self.block_text),
                line=self.lineno)
            return [error]

        dates.startYearDisplay = m.group(1)
        dates.startYear = m.group(1)
        dates.startMonth = m.group(2)
        dates.startDay = m.group(3)
        if m.group(4):
            dates.endYear = m.group(4)
            dates.endYearDisplay = m.group(4)
            dates.endMonth = m.group(5)
            dates.endDay = m.group(6)
        else:
            dates.endYearDisplay = m.group(7)
            dates.endYear = False
            dates.endMonth = False
            dates.endDay = False

        ## Save segments as short names to avoid going crazy.

        if traveler.hook.reporter_start:
            traveler.hook.reporter_start(self.options, dates,
                                         self.arguments[0])

        # That's everything but variations, which are handled by the directive.
        dummy = nodes.generated()
        self.state.nested_parse(self.content, self.content_offset, dummy)

        if traveler.hook.reporter_end:
            traveler.hook.reporter_end(self.options, self.arguments[0])

        reporter_box_node = self.makeContainer("reporter-box", suffix="")

        if self.options.has_key("neutral"):
            reporter_node = self.makeContainer("reporter neutral")
        else:
            reporter_node = self.makeContainer("reporter")

        reporter_name = self.arguments[0].replace("'", u"\u0027")
        reporter_name_node = self.makeContainer("reporter-name",
                                                rawsource=self.arguments[0],
                                                text=reporter_name)

        description_node = self.makeContainer("description-box", suffix="")

        abbrev = self.makeMiniBubble(self.options["jurisdiction"],
                                     self.options["edition-abbreviation"])
        start = self.makeLabelNode(dates.startYearDisplay, key="From")
        end = self.makeLabelNode(dates.endYearDisplay, key="To")
        if self.options.has_key("neutral"):
            neutral = self.makeLabelNode("yes",
                                         key="Neutral",
                                         nodeType=valueneutral)
        else:
            neutral = self.makeLabelNode("no", key="Neutral")

        if self.options.has_key("confirmed"):
            confirmed = self.makeLabelNode("yes", key="Confirmed")
        else:
            confirmed = self.makeLabelNode("no",
                                           key="Confirmed",
                                           nodeType=valueunconfirmed)

        description_node += abbrev
        description_node += start
        description_node += end
        description_node += neutral
        description_node += confirmed

        feature_node = self.makeContainer("feature-box", suffix="")
        keys = traveler.features.local.required.keys()
        keys.sort()
        for feature in keys:
            feature_node += self.makeLabelNode(u"req\u0027d", key=feature)

        keys = traveler.features.local.optional.keys()
        keys.sort()
        for feature in keys:
            feature_node += self.makeLabelNode("optional", key=feature)

        reporter_node += reporter_name_node
        reporter_node += description_node
        reporter_node += feature_node
        reporter_box_node += reporter_node
        return [reporter_box_node]
コード例 #19
0
  def cite(self, cmd, refuri):
    """
    Return a docutils Node consisting of properly formatted citations children
    nodes.
    
    Brent edit: replaced 'inline' with 'generated'.
    """
    bo, bc    = self.config['brackets']
    sep       = u'%s ' % self.config['separator']
    style     = self.config['style']
    all_auths = (cmd.endswith('s'))
    alt       = (cmd.startswith('alt') or \
                (cmd.startswith('alp')) or \
                (style == 'citeyear'))
    
    if (cmd.startswith('p') or cmd == 'yearpar') and style != 'super':
      node = nodes.generated(bo, bo, classes=['citation'])
    else:
      node = nodes.generated('', '', classes=['citation'])
    
    if self.pre:
      pre = u"%s " % self.pre.decode('latex')
      node += nodes.generated(pre, pre, classes=['pre'])
    
    for i, ref in enumerate(self.refs):
      authors = ref.persons.get('author', [])
      author_text = self.get_author(authors, all_auths).decode('latex')
      lrefuri = refuri + '#citation-' + nodes.make_id(ref.key)
      
      if i > 0 and i < len(self.refs):
        if style == "authoryear":
          node += nodes.generated(sep, sep)
        else:
          if style == "super":
            node += nodes.superscript(', ', ', ')
          else:
            node += nodes.generated(', ', ', ')
      
      if (style == "authoryear" and (cmd.startswith('p') or cmd.startswith('alp'))) or \
         (cmd.startswith('t') or cmd.startswith('alt') or cmd.startswith('author')):
        node += nodes.reference(author_text, author_text, internal=True, refuri=lrefuri)
        
        if cmd.startswith('p') or cmd.startswith('alp'):
          node += nodes.generated(', ', ', ')
        else:
          node += nodes.generated(' ', ' ')
      
      # Add in either the year or the citation number
      if not cmd.startswith('author'):
        if style != 'authoryear':
          num = self.get_ref_num(ref.key)
        else:
          num = ref.fields.get('year')
      
        refnode = nodes.reference(str(num), str(num), internal=True, refuri=lrefuri)
      
        if cmd.startswith('t') and style != 'super':
          node += nodes.generated(bo, bo)
        
        if style == 'super':
          node += nodes.superscript('', '', refnode)
        else:
          node += refnode
      
        if cmd.startswith('t') and style != 'super':
          node += nodes.generated(bc, bc)
    
    if self.post:
      post = u", %s" % self.post.decode('latex')
      node += nodes.generated(post, post, classes=['post'])  
    
    if (cmd.startswith('p') or cmd == 'yearpar') and style != 'super':
      node += nodes.generated(bc, bc, classes=['citation'])

    return node
コード例 #20
0
    if options['format'] == 'svg':
        #~ svgout.visit(aaimg, xml_header = False)
        # insert data into html using a raw node
        attributes = {'format': 'html'}
        #~ # result = [nodes.raw('', '<embed src="%s" %s type="image/svg+xml"/>' % (
        result = [
            nodes.raw(
                '', '<object type="image/svg+xml" data="%s" %s>'
                '</object>' % (output_name, visitor.get_size_attrs()),
                **attributes)
        ]
        #~ result = [nodes.raw('', io.getvalue(), **attributes)]
    elif options['format'] == 'pdf':
        # Return a link.
        wrapper = nodes.generated()
        wrapper.append(
            nodes.reference('',
                            '%s (PDF)' % options['name'],
                            refuri=os.path.basename(output_name)))
        result = [wrapper]
    else:
        # Return an image directive.
        image_options = {}
        image_options['uri'] = os.path.basename(output_name)
        result = [nodes.image(output_name, **image_options)]

    return result


AAFigureDirective.content = True
コード例 #21
0
            line=lineno
        )]
    output.close()

    if options['format'] == 'svg':
        #~ svgout.visit(aaimg, xml_header = False)
        # insert data into html using a raw node
        attributes = {'format': 'html'}
        #~ # result = [nodes.raw('', '<embed src="%s" %s type="image/svg+xml"/>' % (
        result = [nodes.raw('', '<object type="image/svg+xml" data="%s" %s>'
                '</object>' % (output_name, visitor.get_size_attrs()),
                **attributes)]
        #~ result = [nodes.raw('', io.getvalue(), **attributes)]
    elif options['format'] == 'pdf':
        # Return a link.
        wrapper = nodes.generated()
        wrapper.append(nodes.reference('', '%s (PDF)' % options['name'],
            refuri=os.path.basename(output_name)
        ))
        result = [wrapper]
    else:
        # Return an image directive.
        image_options = {}
        image_options['uri'] = os.path.basename(output_name)
        result = [nodes.image(output_name, **image_options)]

    return result

AAFigureDirective.content = True
#~ AAFigureDirective.arguments = (1, 1, 1)
AAFigureDirective.options = {
コード例 #22
0
    def run (self):
        global reporters_json
        if not self.options.has_key('edition-abbreviation'):
            error = self.state_machine.reporter.error(
                'Invalid context: missing edition-abbreviation option in reporter directive',
                nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
            return [error]
        if not self.options.has_key('dates'):
            error = self.state_machine.reporter.error(
                'Invalid context: missing dates in reporter directive',
                nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
            return [error]
        m = re.match("^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})-(?:([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})|(present))",self.options["dates"])
        if not m:
            error = self.state_machine.reporter.error(
                'Invalid context: misformatted dates range in reporter directive. Format must be YYYY/MM/DD-YYYY/MM/DD or YYYY/MM/DD-present',
                nodes.literal_block(self.block_text, self.block_text), line=self.lineno)
            return [error]

        startyearDisplay = m.group(1)
        startyear = m.group(1)
        startmonth = m.group(2)
        startday = m.group(3)
        if m.group(4):
            endyear = m.group(4)
            endyearDisplay = m.group(4)
            endmonth = m.group(5)
            endday = m.group(6)
        else:
            endyearDisplay = m.group(7)
            endyear = False
            endmonth = False
            endday = False

        ## Save segments as short names to avoid going crazy.

        bundle_key = self.options["flp-common-abbreviation"]
        if not reporters_json.has_key(bundle_key):
            bundle = []
            reporters_json[self.options["flp-common-abbreviation"]] = bundle
        else:
            bundle = reporters_json[bundle_key]
        series_name = self.arguments[0]
        edition_key = self.options["edition-abbreviation"]
        series = self.findReporterSeries(bundle,series_name)
        if not series:
            series = {}
            series["cite_type"] = self.options["flp-series-cite-type"]
            series["editions"] = {}
            series["mlz_jurisdiction"] = []
            series["name"] = series_name
            series["variations"] = {}
            bundle.append(series)
        if not series["mlz_jurisdiction"].count(traveling_jurisdiction[0]):
            series["mlz_jurisdiction"].append(traveling_jurisdiction[0])
            series["mlz_jurisdiction"].sort()
        series["editions"][edition_key] = [
            {
                "year": startyear,
                "month": startmonth,
                "day": startday
                },
            {
                "year": endyear,
                "month": endmonth,
                "day": endday
                }
            ]

        # That's everything but variations, which are handled by the directive.
        
        dummy = nodes.generated()
        self.state.nested_parse(self.content, self.content_offset,
                                dummy)
        for key in traveling_variations[0].keys():
            traveling_variations[0][key] = edition_key
        series["variations"].update(traveling_variations[0])
        traveling_variations[0] = {}

        reporter_box_node = reporterbox()

        if self.options.has_key("neutral"):
            reporter_node = reporterneutral()
        else:
            reporter_node = reporter()

        reporter_name = self.arguments[0].replace("'",u"\u0027")
        reporter_name_node = reportername(rawsource=self.arguments[0],text=reporter_name)

        description_node = descriptionbox()

        abbrev = self.makeMiniBubble(self.options["jurisdiction"],self.options["edition-abbreviation"])
        start = self.makeLabelNode(startyearDisplay,key="From")
        end = self.makeLabelNode(endyearDisplay,key="To")
        if self.options.has_key("neutral"):
            neutral =  self.makeLabelNode("yes",key="Neutral",nodeType=valueneutral)
        else:
            neutral =  self.makeLabelNode("no",key="Neutral")
            
        if self.options.has_key("confirmed"):
            confirmed = self.makeLabelNode("yes",key="Confirmed")
        else:
            confirmed = self.makeLabelNode("no",key="Confirmed",nodeType=valueunconfirmed)

        description_node += abbrev
        description_node += start
        description_node += end
        description_node += neutral
        description_node += confirmed

        feature_node = featurebox()
        keys = FEATURES.local.required.keys()
        keys.sort()
        for feature in keys:
            feature_node += self.makeLabelNode(u"req\u0027d",key=feature)
            
        keys = FEATURES.local.optional.keys()
        keys.sort()
        for feature in keys:
            feature_node += self.makeLabelNode("optional",key=feature)

        reporter_node += reporter_name_node
        reporter_node += description_node
        reporter_node += feature_node
        reporter_box_node += reporter_node
        return [reporter_box_node]
コード例 #23
0
ファイル: __init__.py プロジェクト: f-i/sphinx-natbib
  def cite(self, cmd, refuri):
    """ Return a docutils Node consisting of properly formatted citations children
    nodes.                Brent edit: replaced 'inline' with 'generated' """
    bo, bc    = self.config['brackets']
    sep       = '%s ' % self.config['separator']
    style     = self.config['style']
    all_auths = (cmd.endswith('s'))
    alt       = (cmd.startswith('alt') or \
                (cmd.startswith('alp')) or \
                (style == 'citeyear'))

    if (cmd.startswith('p') or cmd == 'yearpar') and style != 'super':
      #node = nodes.inline(bo, bo, classes=['citation'])
      node = nodes.generated(bo, bo, classes=['citation'])
    else:
      #node = nodes.inline('', '', classes=['citation'])
      node = nodes.generated('', '', classes=['citation'])

    if self.pre:
      pre="%s ".format(decod(self.pre))
      #node += nodes.inline(pre, pre, classes=['pre'])
      node += nodes.generated(pre, pre, classes=['pre'])

    for i, ref in enumerate(self.refs):
      authors = ref.persons.get('author', [])
      author_text = decod(self.get_author(authors, all_auths))
      lrefuri = refuri + '#citation-' + nodes.make_id(ref.key)

      if i > 0 and i < len(self.refs):
        if style == "authoryear":
          #node += nodes.inline(sep, sep)
          node += nodes.generated(sep, sep)
        else:
          if style == "super": node+=nodes.superscript(', ',', ')
          else:
            #node += nodes.inline(', ', ', ')
            node += nodes.generated(', ', ', ')

      if (style == "authoryear" and (cmd.startswith('p') or cmd.startswith('alp'))) or \
         (cmd.startswith('t') or cmd.startswith('alt') or cmd.startswith('author')):
        node+=nodes.reference(author_text,author_text,internal=True,refuri=lrefuri)

        if cmd.startswith('p') or cmd.startswith('alp'):
          #node+=nodes.inline(', ',', ')
          node+=nodes.generated(', ',', ')
        else:
          #node+=nodes.inline(' ',' ')
          node+=nodes.generated(' ',' ')

      # Add in either the year or the citation number
      if not cmd.startswith('author'):
        if style != 'authoryear':
          num = self.get_ref_num(ref.key)
        else:
          num = ref.fields.get('year')
      
        refnode = nodes.reference(str(num), str(num), internal=True, refuri=lrefuri)
      
        if cmd.startswith('t') and style != 'super':
          #node += nodes.inline(bo, bo)
          node += nodes.generated(bo, bo)
        
        if style == 'super':
          node += nodes.superscript('', '', refnode)
        else:
          node += refnode
      
        if cmd.startswith('t') and style != 'super':
          #node += nodes.inline(bc, bc)
          node += nodes.generated(bc, bc)
    
    if self.post:
      post=", %s".format(decod(self.post))
      #node += nodes.inline(post, post, classes=['post'])  
      node += nodes.generated(post, post, classes=['post'])  
    
    if (cmd.startswith('p') or cmd == 'yearpar') and style != 'super':
      #node += nodes.inline(bc, bc, classes=['citation'])
      node += nodes.generated(bc, bc, classes=['citation'])

    return node