Esempio n. 1
0
    def _document_task(self, name, task, ctx):
        # output name of task, and note if it is the default task
        if task.body.__module__ != self.module.__name__:
            # only document tasks from this module.
            return []

        task_name = nodes.paragraph(classes=['task-name'])
        self.state.nested_parse(
            StringList([
                'task: **{}**'.format(name),
                '*(default)*' if task.is_default else ""
            ]),
            0,
            task_name
        )
        res = [task_name]

        # output the task's docstring
        getdoc = inspect.getdoc(task)
        if getdoc is not None:
            docstring = nodes.block_quote()
            self.state.nested_parse(
                StringList(getdoc.split('\n')),
                0,
                docstring
            )
            res.append(docstring)

        tuples = ctx.help_tuples()
        if tuples:
            res.append(nodes.block_quote('', self._options(tuples)))
        return res
Esempio n. 2
0
def block_quote(self, indented, line_offset):
    elements = []

    while indented:
        (blockquote_lines,
            attribution_lines,
            attribution_offset,
            indented,
            new_line_offset) = self.split_attribution(indented, line_offset)

        blockquote = nodes.block_quote()
        blockquote.rawsource = '    ' + '\n'.join(blockquote_lines.data)
        self.nested_parse(blockquote_lines, line_offset, blockquote)
        elements.append(blockquote)
        if attribution_lines:
            attribution, messages = self.parse_attribution(
                attribution_lines, attribution_offset)
            blockquote += attribution
            elements += messages
        line_offset = new_line_offset
        while indented and not indented[0]:
            indented = indented[1:]
            line_offset += 1

    return elements
    def run(self):
        filename = self.arguments[0]
        pointer = self.arguments[1]

        env = self.state.document.settings.env
        path = os.path.join(os.path.dirname(env.doc2path(env.docname)),
                            filename)
        env.note_dependency(path)

        try:
            with open(path, encoding='utf-8') as f:
                schema = json.load(f)
                description = jsonpointer.resolve_pointer(
                    schema, f'{pointer}/description')
        except FileNotFoundError:
            raise self.error(f'JSON Schema file not found: {path}')
        except PermissionError:
            raise self.error(f'JSON Schema file not readable: {path}')
        except json.decoder.JSONDecodeError:
            raise self.error(f'JSON Schema file not valid: {path}')
        except jsonpointer.JsonPointerException:
            raise self.error(
                f"Pointer '{pointer}/description' not found: {path}")

        block_quote = nodes.block_quote(
            '',
            *to_docutils(description).children,
            classes=['directive--field-description'])

        return [block_quote]
Esempio n. 4
0
    def quote(self, text):
        q = nodes.block_quote()

        with self._temp_current_node(q):
            self.grammar(text).document()

        self.current_node.append(q)
Esempio n. 5
0
    def rst_nodes(self):

        section_nodelists = {}

        # Get all sub sections
        for sectiondef in self.sectiondef:
            kind = sectiondef.section_kind()
            subnodes = sectiondef.rst_nodes()
            section_nodelists[kind] = subnodes

        nodelist = []    

        if self.briefdescription:
            nodelist.extend( self.briefdescription.rst_nodes() )

        if self.detaileddescription:
            nodelist.extend( self.detaileddescription.rst_nodes() )

        # Order the results in an appropriate manner
        for entry in sectiondefTypeSub.section_titles:
            self.extend_nodelist(nodelist, entry[0], entry[1], section_nodelists)

        self.extend_nodelist(nodelist, "", "", section_nodelists)

        return [nodes.block_quote("", *nodelist)]
Esempio n. 6
0
    def blockquote(self, block):
        q = nodes.block_quote()
        q.line = block.start_line

        with self._temp_current_node(q):
            self.convert_blocks(block.children)

        self.current_node.append(q)
Esempio n. 7
0
    def run(self):
        bq = nodes.block_quote()
        self.state.nested_parse(self.content, self.content_offset,
                                bq)

        bq['classes'].append('commentary')

        return [bq]
Esempio n. 8
0
    def blockquote(self, block):
        q = nodes.block_quote()
        q.line = block.start_line

        with self._temp_current_node(q):
            self.convert_blocks(block.children)

        self.current_node.append(q)
Esempio n. 9
0
def block_quote(node):
    """
    A block quote
    """
    o = nodes.block_quote()
    o.line = node.sourcepos[0][0]
    for n in MarkDown(node):
        o += n
    return o
Esempio n. 10
0
def block_quote(node):
    """
    A block quote
    """
    o = nodes.block_quote()
    o.line = node.sourcepos[0][0]
    for n in MarkDown(node):
        o += n
    return o
Esempio n. 11
0
File: domain.py Progetto: esho/mesh
    def run(self):
        block = nodes.block_quote('', classes=['structure-block'])
        self.state.nested_parse(self.content, self.content_offset, block)

        header = nodes.paragraph('', '', strong(self.arguments[0]), classes=['structure-header'])
        if block.children:
            return [header, block]
        else:
            return [header]
Esempio n. 12
0
 def format_tokens(self, tokens):
     root = nodes.block_quote(
         classes=['run-output', 'run-output-weaver'],
         ids=['weaver']
     )
     root += nodes.inline('', '')
     for c in tokens:
         root += c
     return root
Esempio n. 13
0
    def block_quote(self, lines: List[str],
                    line_offset: int) -> List[nodes.Element]:
        """Parse a block quote, which is a block of text,
        followed by an (optional) attribution.

        ::

           No matter where you go, there you are.

           -- Buckaroo Banzai
        """
        elements = []
        # split attribution
        last_line_blank = False
        blockquote_lines = lines
        attribution_lines = []
        attribution_line_offset = None
        # First line after a blank line must begin with a dash
        for i, line in enumerate(lines):
            if not line.strip():
                last_line_blank = True
                continue
            if not last_line_blank:
                last_line_blank = False
                continue
            last_line_blank = False
            match = self.attribution_pattern.match(line)
            if not match:
                continue
            attribution_line_offset = i
            attribution_lines = [match.group(2)]
            for at_line in lines[i + 1:]:
                indented_line = at_line[len(match.group(1)):]
                if len(indented_line) != len(at_line.lstrip()):
                    break
                attribution_lines.append(indented_line)
            blockquote_lines = lines[:i]
            break
        # parse block
        blockquote = nodes.block_quote()
        self.nested_parse(blockquote_lines, line_offset, blockquote)
        elements.append(blockquote)
        # parse attribution
        if attribution_lines:
            attribution_text = "\n".join(attribution_lines)
            lineno = self._lineno + line_offset + (attribution_line_offset
                                                   or 0)
            textnodes, messages = self.inline_text(attribution_text, lineno)
            attribution = nodes.attribution(attribution_text, "", *textnodes)
            (
                attribution.source,
                attribution.line,
            ) = self.state_machine.get_source_and_line(lineno)
            blockquote += attribution
            elements += messages
        return elements
Esempio n. 14
0
    def run(self):
        block = nodes.block_quote('', classes=['structure-block'])
        self.state.nested_parse(self.content, self.content_offset, block)

        header = nodes.paragraph('',
                                 '',
                                 strong(self.arguments[0]),
                                 classes=['structure-header'])
        if block.children:
            return [header, block]
        else:
            return [header]
Esempio n. 15
0
    def run(self):
        # Automatically generate the "rose:NAME" ref_context variable.
        self.add_ref_context(self.NAME)
        index_node, cont_node = ObjectDescription.run(self)

        # Add a marker on the output node so we can determine the context
        # namespace later (see RoseDomain.resolve_xref).
        context_var = self.ROSE_CONTEXT % self.NAME
        cont_node.ref_context = {context_var: self.process_name(
            self.arguments[0].strip())[0]}

        # Add children if initialised via python - see RoseAutoDirective.
        block = block_quote()  # Create indented section.
        for child_node in self.registered_children:
            block.append(child_node)  # Add child node to indented section.
        cont_node.append(block)  # Add indented section to this node.

        return [index_node, cont_node]
Esempio n. 16
0
    def run(self):
        # Automatically generate the "rose:NAME" ref_context variable.
        self.add_ref_context(self.NAME)
        index_node, cont_node = ObjectDescription.run(self)

        # Add a marker on the output node so we can determine the context
        # namespace later (see RoseDomain.resolve_xref).
        context_var = self.ROSE_CONTEXT % self.NAME
        cont_node.ref_context = {context_var: self.process_name(
            self.arguments[0].strip())[0]}

        # Add children if initialised via python - see RoseAutoDirective.
        block = block_quote()  # Create indented section.
        for child_node in self.registered_children:
            block.append(child_node)  # Add child node to indented section.
        cont_node.append(block)  # Add indented section to this node.

        return [index_node, cont_node]
    def run(self):
        config = self.state.document.settings.env.config
        language = config.overrides.get('language', 'en')
        try:
            headers = config.codelist_headers[language]
        except KeyError:
            raise self.error(
                f"codelist_headers in conf.py is missing a '{language}' key")

        filename = self.arguments[0]
        code = self.arguments[1]

        env = self.state.document.settings.env
        path = os.path.join(os.path.dirname(env.doc2path(env.docname)),
                            filename)
        env.note_dependency(path)

        try:
            with open(path, encoding='utf-8') as f:
                reader = csv.DictReader(f)
                description = next(row[headers['description']]
                                   for row in reader
                                   if row[headers['code']] == code)
        except FileNotFoundError:
            raise self.error(f'CSV codelist file not found: {path}')
        except PermissionError:
            raise self.error(f'CSV codelist file not readable: {path}')
        except KeyError as e:
            raise self.error(
                f"Column {e} not found ({', '.join(reader.fieldnames)}): {path}"
            )
        except StopIteration:
            raise self.error(
                f"Value '{code}' not found in column '{headers['code']}': {path}"
            )

        block_quote = nodes.block_quote(
            '',
            *to_docutils(description).children,
            classes=['directive--code-description'])

        return [block_quote]
Esempio n. 18
0
    def run(self):
        tarball_uri = 'http://pypi.python.org/packages/source/p/pybtex/pybtex-%s.tar.bz2' % version

        current_version_is = nodes.Text('Current version is ')
        pybtex_xx = nodes.reference('',
                                    'Pybtex %s' % version,
                                    name='Pybtex %s' % version,
                                    refuri=tarball_uri)
        download = nodes.reference('',
                                   'download',
                                   name='download',
                                   refname='download')
        see_whats_new = nodes.reference('',
                                        "see what's new",
                                        name="see what's new",
                                        refuri='history.txt')
        content = (current_version_is, pybtex_xx, nodes.Text(' ('), download,
                   nodes.Text(', '), see_whats_new, nodes.Text(')'))
        paragraph = nodes.paragraph('', '', *content)
        link_block = nodes.block_quote('', paragraph, classes=["pull-quote"])
        return [link_block]
Esempio n. 19
0
    def run(self):
        tarball_uri = 'http://pypi.python.org/packages/source/p/pybtex/pybtex-%s.tar.bz2' % version

        current_version_is = nodes.Text('Current version is ')
        pybtex_xx = nodes.reference('', 'Pybtex %s' % version,
            name='Pybtex %s' % version,
            refuri=tarball_uri)
        download = nodes.reference('', 'download', name='download',
            refname='download')
        see_whats_new = nodes.reference('', "see what's new",
            name="see what's new", refuri='history.txt')
        content = (
            current_version_is,
            pybtex_xx,
            nodes.Text(' ('),
            download, nodes.Text(', '),
            see_whats_new,
            nodes.Text(')')
        )
        paragraph = nodes.paragraph('', '', *content)
        link_block = nodes.block_quote('', paragraph, classes=["pull-quote"])
        return [link_block]
Esempio n. 20
0
    def run(self):
        # TODO want to put options['cite'] in <blockquote cite="...">
        q = nodes.block_quote('')
        for text in self.content:
            # TODO use nested_parse to allow rst markup inside of the
            # blockquote
            q += nodes.Text(text)

        if self.options['author']:
            addr = nodes.Element()
            if self.options['cite']:
                addr += nodes.raw('', '<a href="', format='html')
                addr += nodes.Text(self.options['cite'])
                addr += nodes.raw('', '">', format='html')
            addr += nodes.Text(self.options['author'])
            if self.options['cite']:
                addr += nodes.raw('', '</a>', format='html')
            q += nodes.raw('', '<address>', format='html')
            q += addr.children
            q += nodes.raw('', '</address>', format='html')

        return [q]
Esempio n. 21
0
 def __init__(self, options, from_verse = None, to_verse = None):
     self.options = options
     self.node_stack = [(nodes.block_quote(), 0)] # node, depth
     self.is_first = True
     self.show_label = False
     self.current_verse = 0 # TODO: Need to handle some psalms that have a 'verse 0'
     self.from_verse = from_verse
     if self.from_verse is not None and to_verse is None:
         self.to_verse = from_verse
     else:
         self.to_verse = to_verse
     if 'title' in options:
         title = nodes.Text(options['title'])
         line = nodes.line()
         line_block = nodes.line_block()
         line.append(title)
         if 'bold' in options:
             bold = nodes.strong()
             bold.append(line)
             line = bold
         line_block.append(line)
         self.node_stack[0][0].append(line_block)
Esempio n. 22
0
def blockquote(name, arguments, options, content, lineno,
               content_offset, block_text, state, state_machine):
    q = nodes.block_quote('')

    for text in content:
        # TODO use nested_parse to allow rst markup inside of the
        # blockquote
        q += nodes.Text(text)

    if options.get('author'):
        addr = nodes.Element()
        if options.get('cite'):
            addr += nodes.raw('', '<a href="', format='html')
            addr += nodes.Text(options.get('cite'))
            addr += nodes.raw('', '">', format='html')
        addr += nodes.Text(options['author'])
        if options.get('cite'):
            addr += nodes.raw('', '</a>', format='html')
        q += nodes.raw('', '<address>', format='html')
        q += addr.children
        q += nodes.raw('', '</address>', format='html')

    return [q]
Esempio n. 23
0
 def render_blockquote_open(self, token):
     quote = nodes.block_quote()
     self.add_line_and_source_path(quote, token)
     with self.current_node_context(quote, append=True):
         self.render_children(token)
Esempio n. 24
0
 def visit_blockquote(self, node):
     return nodes.block_quote()
Esempio n. 25
0
    def contribute_property(self, parent, prop_key, prop, upd_para=None,
                            id_pattern_prefix=None):
        if not id_pattern_prefix:
            id_pattern_prefix = '%s-prop'
        id_pattern = id_pattern_prefix + '-' + prop_key

        definition = self._section(parent, prop_key, id_pattern)

        self._status_str(prop.support_status, definition)

        if not prop.implemented:
            para = nodes.paragraph('', _('Not implemented.'))
            note = nodes.note('', para)
            definition.append(note)
            return

        if prop.description:
            para = nodes.paragraph('', prop.description)
            definition.append(para)

        type = nodes.paragraph('', _('%s value expected.') % prop.type)
        definition.append(type)

        if upd_para is not None:
            definition.append(upd_para)
        else:
            if prop.update_allowed:
                upd_para = nodes.paragraph(
                    '', _('Can be updated without replacement.'))
                definition.append(upd_para)
            elif prop.immutable:
                upd_para = nodes.paragraph('', _('Updates are not supported. '
                                                 'Resource update will fail on'
                                                 ' any attempt to update this '
                                                 'property.'))
                definition.append(upd_para)
            else:
                upd_para = nodes.paragraph('', _('Updates cause replacement.'))
                definition.append(upd_para)

        if prop.default is not None:
            para = nodes.paragraph('', _('Defaults to "%s".') % prop.default)
            definition.append(para)

        for constraint in prop.constraints:
            para = nodes.paragraph('', str(constraint))
            definition.append(para)

        sub_schema = None
        if prop.schema and prop.type == properties.Schema.MAP:
            para = nodes.paragraph()
            emph = nodes.emphasis('', _('Map properties:'))
            para.append(emph)
            definition.append(para)
            sub_schema = prop.schema

        elif prop.schema and prop.type == properties.Schema.LIST:
            para = nodes.paragraph()
            emph = nodes.emphasis('', _('List contents:'))
            para.append(emph)
            definition.append(para)
            sub_schema = prop.schema

        if sub_schema:
            for sub_prop_key, sub_prop in sorted(sub_schema.items(),
                                                 self.cmp_prop):
                if sub_prop.support_status.status != support.HIDDEN:
                    indent = nodes.block_quote()
                    definition.append(indent)
                    self.contribute_property(
                        indent, sub_prop_key, sub_prop, upd_para, id_pattern)
Esempio n. 26
0
def process_exercise_nodes(app, doctree, fromdocname):
    """
    This will be run after all parsing is finished and AST is constructed

    We now have the opportunity to see all collected exercises and exercise
    lists and replace them with approrpriate content.

    Behavior depends on two config values that should be defined in conf.py

    1. exercise_include_exercises (bool): if this is False then all exercises
       are purged from the text. If true, they will remain
    2. exercise_inline_exercises (bool): if true, exercises are left intact
       where they are found in the document. If False, they are collected
       in an exercise list and removed from source. The inline content will
       be replaced by a link to the new position in the exercise list
    """
    # extract config values
    include_exercises = app.config.exercise_include_exercises
    inline_exercises = app.config.exercise_inline_exercises

    # if we don't want exercises, remove them all from the doctree
    if not include_exercises:
        for node in doctree.traverse(exercise_node):
            node.parent.remove(node)

        for node in doctree.traverse(exerciselist_node):
            node.parent.remove(node)

        return

    # if we don't want inline exercises, replace the exercise with a link back
    # to the exercise in an exercise list
    if not inline_exercises:
        all_exercises = {}
        for node in doctree.traverse(exercise_node):
            all_exercises[node["_id"]] = node

    # Replace all todolist nodes with a list of the collected todos.
    # Augment each todo with a backlink to the original location.
    env = app.builder.env

    def should_include_exercise(listnode, exercise_info):
        """
        given an exerciselist_node and an exercise_info, check to see if
        the exercise belongs in the list

        Logic as follows:

        - First check labels. if listnode specified labels,
          ensure exercise_info["label"] is selected in the lists labels
        - If that passes, then check listnode's from option. If specified
          exercise_info["docname"] must match listnode["from"]
        - If that passes then check scopes.
            - If scope is file, check if  exercise_info["docname"] matches
              fromdocname (closed over)
            - If scope is section, check if exercise_info["docname"] comes
              from same section as fromdocname
        - If that passes, include everything

        """
        # unpack args
        from_file = listnode["from"]
        scope = listnode["scope"]
        labels = listnode["labels"]
        if labels is not None:
            # we just check label now
            return exercise_info["label"] in labels

        ex_src_doc = exercise_info["docname"]
        if from_file is not None:
            return ex_src_doc == from_file
        if scope == "file":
            return ex_src_doc == fromdocname
        elif scope == "section":
            # check if not inside section
            if ("/" not in ex_src_doc) and ("/" not in fromdocname):
                return True
            elif "/" not in fromdocname:
                # ex_src_doc is in a section, but the exerciselist is not
                return False
            return ex_src_doc.rsplit('/', 1)[0] == fromdocname.rsplit('/', 1)[0]

        return True

    for node in doctree.traverse(exerciselist_node):
        listinfo = env.exercise_all_exercise_lists[node["_id"]]
        content = []

        if inline_exercises and not node["force"]:
            node.parent.remove(node)
            continue

        for ex_id, ex_info in env.exercise_all_exercises.items():
            if not should_include_exercise(node, ex_info):
                continue

            # make link from location in exercise list back to site where exercise appeared
            # in document
            back_to_text_para = _make_backlink(
                app, "(", "back to text", ")",
                ex_info["docname"], fromdocname, ex_info["target"]["refid"]
            )

            # Make link from body of text back down to here in exercise list only if we
            # don't want inline exercises AND the exercise list is in the same file as
            # the exercise
            if not inline_exercises and (listinfo["docname"] == ex_info["docname"]):

                # make a link from site where exercise appeared in document, back
                # to new location in exercise list
                _ex_title = ex_info["title_root"].lower()
                inline_para = _make_backlink(
                    app, "See {} {} in the ".format(_ex_title, ex_info["number"] + 1),
                    "exercise list", "",
                    fromdocname, ex_info["docname"], listinfo["target"]["refid"]
                )

                # replace this exercise with the link
                bq = nodes.block_quote()
                bq += inline_para
                if ex_info.get("removed", False) is not True:
                    all_exercises[ex_id].replace_self([bq])
                    ex_info["removed"] = True

            ex_to_add = ex_info['node_copy'].deepcopy()
            if ex_info["docname"] != listinfo["docname"]:
                # If the exercise comes from a different file make the heading be
                # `Exercise \d (path)`, e.g. `Exercise 4 (pandas/groupby)` only here in
                # the task list... not inline
                for text_node in ex_to_add.traverse(nodes.Text):
                    if RE_EXERCISE_NUM.match(text_node):
                        parent = text_node.parent
                        assert isinstance(parent, nodes.strong)  # make sure we have what we think we do
                        _src_path = app.builder.get_relative_uri(
                            fromdocname, ex_info["docname"]
                        )
                        _title_root = ex_to_add["title_root"]
                        new_title = "{} {} ({})".format(_title_root, ex_info["number"] + 1, _src_path)
                        parent.replace_self([nodes.strong(_(new_title), _(new_title))])
            content.append(ex_to_add)
            content.append(back_to_text_para)

        if len(content) > 0:
            node.replace_self(content)
Esempio n. 27
0
    def run(self):
        filename = self.arguments[0]

        # Load rose configuration.
        try:
            conf = config.load(filename)
        except config.ConfigSyntaxError:
            LOGGER.error('Syntax error in Rose configuration file "%s".' %
                         filename)
            raise

        nodes = []
        nodes.append(addnodes.highlightlang(lang='rose', linenothreshold=20))

        # Append file level comments if present.
        if conf.comments:
            contentnode = addnodes.desc_content()
            contentnode.document = self.state.document
            self.state.nested_parse(StringList(conf.comments),
                                    self.content_offset, contentnode)
            nodes.append(contentnode)

        # Append configurations.
        section = None
        node = block_quote()
        for key, conf_node in sorted(conf.walk()):
            if isinstance(conf_node.value, str):
                # Configuration setting - "name=arg".
                name = '%s=%s' % (key[-1], conf_node.value or '')
            else:
                # Configuration section - "name"
                name = key[-1]
            # Prepare directive object.
            directive = RoseConfigDirective(
                'rose:conf',
                [name],
                {},
                StringList(conf_node.comments),
                self.lineno,
                self.content_offset,
                self.block_text,
                self.state,
                self.state_machine,
            )
            if isinstance(conf_node.value, dict):
                # Configuration section.
                if section:
                    node.append(section.run()[1])
                section = directive
            elif key[0]:
                # Sub-configuration.
                section.register_subnode(directive)
            else:
                # Top-level configuration
                node.append(directive.run()[1])
        if section:
            node.append(section.run()[1])
        nodes.append(node)

        nodes.append(addnodes.highlightlang(lang='bash', linenothreshold=20))

        return nodes
Esempio n. 28
0
    def run(self):
        sectional = ''
        if 'sectional' in self.options:
            sectional = 'sectional'

        definition = container('field', sectional)
        signature = nodes.paragraph('', '', classes=['field-signature'])

        if len(self.arguments) == 1:
            field = self.arguments[0]
        else:
            field = None

        if field:
            required = ''
            if 'required' in self.options:
                required = 'required'

            polymorphic_discriminator = ''
            if 'polymorphic_discriminator' in self.options:
                polymorphic_discriminator = 'polymorphic_discriminator'

            separator = ':'
            if polymorphic_discriminator:
                separator = ''
            elif ' ' not in field:
                try:
                    int(field)
                except ValueError:
                    pass
                else:
                    separator = '.'

            signature += strong(field + separator, 'field-name', required,
                                sectional, polymorphic_discriminator)

        type = self.options.get('type')
        if type:
            signature += text(' ')
            signature += emphasis(type, 'field-type')

        subtype = self.options.get('subtype')
        if subtype:
            span = inline('<', 'field-subtype')
            aspects = None

            if ';' in subtype:
                subtype, aspects = subtype.split(';', 1)

            span += emphasis(subtype, 'field-type')
            if aspects:
                span += text(' ')
                span += inline(aspects, 'field-flags')

            span += text('>')
            signature += text(' ')
            signature += span

        key = self.options.get('key')
        if key:
            signature += text(' ')
            signature += literal('key=%s' % key, 'field-constraints')

        constant = self.options.get('constant')
        if constant:
            signature += text(' ')
            signature += literal('constant=%s' % constant, 'field-default')

        default = self.options.get('default')
        if default and not constant:
            signature += text(' ')
            signature += literal('default=%s' % default, 'field-default')

        constraints = self.options.get('constraints')
        if constraints:
            signature += text(' ')
            signature += literal('%s' % constraints, 'field-constraints')

        flags = []
        for flag in self.flags:
            if flag in self.options:
                flags.append(flag)

        if flags:
            signature += text(' ')
            signature += inline(' '.join(flags), 'field-flags')

        title = self.options.get('title')
        if title:
            signature += text(' ')
            signature += inline('"%s"' % title, 'field-title')

        definition += signature
        block = nodes.block_quote('')

        description = self.options.get('description')
        if description:
            block += inline(description, 'field-description')

        for aspect, element in self.aspects.items():
            value = self.options.get(aspect)
            if value:
                block += aspect_block(aspect, value, element)

        self.state.nested_parse(self.content, self.content_offset, block)
        if block.children:
            definition += block

        return [definition]
Esempio n. 29
0
    def run(self):
        filename = self.arguments[0]

        # Load rose configuration.
        try:
            conf = config.load(filename)
        except config.ConfigSyntaxError:
            LOGGER.error(
                'Syntax error in Rose configuration file "%s".' % filename)
            raise

        nodes = []
        nodes.append(addnodes.highlightlang(lang='rose', linenothreshold=20))

        # Append file level comments if present.
        if conf.comments:
            contentnode = addnodes.desc_content()
            contentnode.document = self.state.document
            self.state.nested_parse(
                StringList(conf.comments),
                self.content_offset,
                contentnode
            )
            nodes.append(contentnode)

        # Append configurations.
        section = None
        node = block_quote()
        for key, conf_node in sorted(conf.walk()):
            if isinstance(conf_node.value, str):
                # Configuration setting - "name=arg".
                name = '%s=%s' % (key[-1], conf_node.value or '')
            else:
                # Configuration section - "name"
                name = key[-1]
            # Prepare directive object.
            directive = RoseConfigDirective(
                'rose:conf',
                [name],
                {},
                StringList(conf_node.comments),
                self.lineno,
                self.content_offset,
                self.block_text,
                self.state,
                self.state_machine,
            )
            if isinstance(conf_node.value, dict):
                # Configuration section.
                if section:
                    node.append(section.run()[1])
                section = directive
            elif key[0]:
                # Sub-configuration.
                section.register_subnode(directive)
            else:
                # Top-level configuration
                node.append(directive.run()[1])
        if section:
            node.append(section.run()[1])
        nodes.append(node)

        nodes.append(addnodes.highlightlang(lang='bash', linenothreshold=20))

        return nodes
Esempio n. 30
0
File: domain.py Progetto: esho/mesh
    def run(self):
        sectional = ('sectional' in self.options) and 'sectional' or ''
        definition = container('field', sectional)
        signature = nodes.paragraph('', '', classes=['field-signature'])

        if len(self.arguments) == 1:
            field = self.arguments[0]
        else:
            field = None

        if field:
            required = ('required' in self.options) and 'required' or ''
            separator = ':'
            if ' ' not in field:
                try:
                    int(field)
                except ValueError:
                    pass
                else:
                    separator = '.'
            signature += strong(field + separator, 'field-name', required, sectional)

        type = self.options.get('type')
        if type:
            signature += text(' ')
            signature += emphasis(type, 'field-type')

        subtype = self.options.get('subtype')
        if subtype:
            span = inline('<', 'field-subtype')
            aspects = None
            if ';' in subtype:
                subtype, aspects = subtype.split(';', 1)
            span += emphasis(subtype, 'field-type')
            if aspects:
                span += text(' ')
                span += inline(aspects, 'field-flags')
            span += text('>')
            signature += text(' ')
            signature += span

        key = self.options.get('key')
        if key:
            signature += literal(' key=%s' % key, 'field-constraints')

        constant = self.options.get('constant')
        if constant:
            signature += literal(' constant=%s' % constant, 'field-default')

        default = self.options.get('default')
        if default and not constant:
            signature += literal(' default=%s' % default, 'field-default')

        constraints = self.options.get('constraints')
        if constraints:
            signature += literal(' %s' % constraints, 'field-constraints')

        flags = []
        for flag in ('required', 'nonnull', 'readonly', 'deferred',
                'unique', 'polymorphic', 'ignore_null'):
            if flag in self.options:
                flags.append(flag)
        if flags:
            signature += text(' ')
            signature += inline(' '.join(flags), 'field-flags')

        title = self.options.get('title')
        if title:
            signature += text(' ')
            signature += inline('"%s"' % title, 'field-description')

        description = self.options.get('description')
        if description:
            signature += text(' ')
            signature += inline(description, 'field-description')

        definition += signature
        block = nodes.block_quote('')

        for aspect, element in self.aspects.iteritems():
            value = self.options.get(aspect)
            if value:
                block += aspect_block(aspect, value, element)

        self.state.nested_parse(self.content, self.content_offset, block)
        if block.children:
            definition += block

        return [definition]
Esempio n. 31
0
 def as_nodes(self):
     yield nodes.block_quote("", nodes.Text(self.quote))
Esempio n. 32
0
File: book.py Progetto: blais/nabu
    def apply(self, **kwargs):
        self.unid, self.storage = kwargs['unid'], kwargs['storage']

        # Note: we use a special FieldListVisitor class that we've built
        # to simplify visiting generic field lists.  You could use any of
        # the docutils visitors here instead.
        v = FieldListVisitor(self.document)
        v.apply()

        for fnode, flist in v.getfieldlists():
            book = 0
            # if there is an empty book field, this is explicitly a book.
            if 'book' in flist or 'article' in flist:
                book = 1
            # if there is an ISBN number, then it is *definitely* a book.
            elif 'isbn' in flist:
                book = 1
            elif ('title' in flist and
                  ('author' in flist or
                   'authors' in flist or
                   'publication' in flist)):
                book = 1

            if book:
                self.store(flist)

                # FIXME: we should remove all the formatting and rendering that
                # is being done here and move it to the rendering phase instead.

                # Remove the field list and render something nicer for a book.
                ifields = []
                for field, fieldnames in (
                    ('title', ('title',)),
                    ('author', ('author', 'authors')),
                    ):

                    for fname in fieldnames:
                        f = flist.get(fname)
                        if f:
                            break
                    if f:
                        f = astext(f)
                    else:
                        f = u'<unknown %s>' % field
                    ifields.append(f)

                isbn = flist.pop('isbn', None)
                if isbn:
                    # Note: ASINs for older books are often the same as 10-char ISBNs.
                    # For newer books, they may not be.
                    # New 13-char ISBNs cannot be linked directly; a search has to be made.
                    # http://affiliate-blog.amazon.co.uk/2006/12/13digitisbn_how.html
                    # You'll have to use the e-commerce services in order to do this (this sucks).
                    # In the meantime we use a heuristic, which will work most of the time.
                    tisbn = astext(isbn)
                    try:
                        amz_asin = re.sub('[^0-9]', '', toI10(tisbn))
                    except:
                        amz_asin = tisbn
                    url = book_isbn_template % amz_asin
                else:
                    booktitle = flist.get('title', '')
                    url = (book_search_template %
                           quote_plus(astext(booktitle).encode('utf-8')))

                title = paragraph('', '',
                    Text(u'Book: '),
                    reference(refuri=url,
                              classes=['external'],
                              text=u'“%s”, %s' % tuple(ifields)),
                    )

                # details
                details = []

                tfields = []
                for name, value in flist.iteritems():
                    if name not in ('title', 'author', 'comments'):
                        text = astext(value)
                        if text:
                            tfields.append(text)
                if tfields:
                    p = paragraph(text=u','.join(tfields),
                                  classes=['book-fields'])
                    details.append(p)

                for name in 'comments', 'comment', 'notes':
                    comments = flist.get('comments')
                    if comments:
                        break
                if comments:
                    comments = astext(comments)
                    p = paragraph(text=comments,
                                  classes=['book-comments'])
                    details.append(p)
                
                newbook = container(
                    '',
                    title,
                    block_quote('', *details),
                    classes=['book'])

                fnode.parent.replace(fnode, newbook)
Esempio n. 33
0
		'source': directives.unchanged}

    def run(self):
        state = self.state
        env = self.state.document.settings.env
        options = self.options
		if hasattr(env, 'new_serialno'):
			targetid = 'index-%s' % env.new_serialno('index')
		else:
			targetid = "index-%s" % env.index_num
        targetnode = nodes.target('', '', ids=[targetid])
		targetnode['classes'] = ['epigraph']

        node = quote_node()
		node += nodes.block_quote(
			'',
			nodes.paragraph('', '\n'.join(self.content), classes=['text']))
		#state.nested_parse(self.content, self.content_offset, node)

        for element in node:
            if isinstance(element, nodes.block_quote):
                element['classes'] += ['epigraph']

		signode = [nodes.attribution('--', '--')]
		# Embed all components within attributions
		siglb = nodes.line_block('')
		# Pre-format some
		if 'date' in options:
			options['date'] = '[%(date)s]' % options
		if 'source' in options:
			options['source'] = 'Source: %(source)s' % options
Esempio n. 34
0
 def run(self, reader: LineReader, document: Element) -> bool:
     quote = nodes.block_quote()
     quote.source, quote.line = reader.get_source_and_line(incr=1)
     document += quote
     self.parser.parse(BlockQuoteReader(reader), quote)
     return True
Esempio n. 35
0
 def visit_block_quote(self, mdnode):
     q = nodes.block_quote()
     q.line = mdnode.sourcepos[0][0]
     self.current_node.append(q)
     self.current_node = q
Esempio n. 36
0
    def run(self):
        sectional = ('sectional' if 'sectional' in self.options else '')
        definition = container('field', sectional)
        signature = nodes.paragraph('', '', classes=['field-signature'])

        field = (self.arguments[0] if len(self.arguments) == 1 else None)
        if field:
            required = ('required' if 'required' in self.options else '')
            separator = ':'
            if ' ' not in field:
                try:
                    int(field)
                except ValueError:
                    pass
                else:
                    separator = '.'
            signature += strong(field + separator, 'field-name', required,
                                sectional)

        type = self.options.get('type')
        if type:
            signature += text(' ')
            signature += emphasis(type, 'field-type')

        subtype = self.options.get('subtype')
        if subtype:
            span = inline('<', 'field-subtype')
            aspects = None
            if ' ' in subtype:
                subtype, aspects = subtype.split(' ', 1)
            span += emphasis(subtype, 'field-type')
            if aspects:
                span += text(' ')
                span += inline(aspects, 'field-flags')
            span += text('>')
            signature += text(' ')
            signature += span

        default = self.options.get('default')
        if default:
            signature += literal(' default=%s' % default, 'field-default')

        constraints = self.options.get('constraints')
        if constraints:
            signature += literal(' %s' % constraints, 'field-constraints')

        flags = []
        for flag in ('required', 'nonnull', 'readonly', 'deferred'):
            if flag in self.options:
                flags.append(flag)
        if flags:
            signature += text(' ')
            signature += inline(' '.join(flags), 'field-flags')

        description = self.options.get('description')
        if description:
            signature += text(' ')
            signature += inline(description, 'field-description')

        definition += signature
        block = nodes.block_quote('')

        for aspect, element in self.aspects.iteritems():
            value = self.options.get(aspect)
            if value:
                block += aspect_block(aspect, value, element)

        self.state.nested_parse(self.content, self.content_offset, block)
        if block.children:
            definition += block

        return [definition]
 def visit_block_quote(self, mdnode):
     q = nodes.block_quote()
     q.line = mdnode.sourcepos[0][0]
     self.current_node.append(q)
     self.current_node = q
Esempio n. 38
0
    def extend_nodelist(self, nodelist, section, title, section_nodelists):

        # Add title and contents if found
        if section_nodelists.has_key(section):
            nodelist.append(nodes.emphasis(text=title))
            nodelist.append(nodes.block_quote("", *section_nodelists[section]))
Esempio n. 39
0
    def contribute_property(self, parent, prop_key, prop, upd_para=None,
                            id_pattern_prefix=None, sub_prop=False):
        if not id_pattern_prefix:
            id_pattern_prefix = '%s-prop'
        id_pattern = id_pattern_prefix + '-' + prop_key

        definition = self._section(parent, prop_key, id_pattern)

        self._status_str(prop.support_status, definition)

        if not prop.implemented:
            para = nodes.paragraph('', _('Not implemented.'))
            note = nodes.note('', para)
            definition.append(note)
            return

        if sub_prop and prop.type != properties.Schema.LIST and prop.type\
                != properties.Schema.MAP:
            if prop.required:
                para = nodes.paragraph('', _('Required.'))
                definition.append(para)
            else:
                para = nodes.paragraph('', _('Optional.'))
                definition.append(para)

        if prop.description:
            para = nodes.paragraph('', prop.description)
            definition.append(para)

        type = nodes.paragraph('', _('%s value expected.') % prop.type)
        definition.append(type)

        if upd_para is not None:
            definition.append(upd_para)
        else:
            if prop.update_allowed:
                upd_para = nodes.paragraph(
                    '', _('Can be updated without replacement.'))
                definition.append(upd_para)
            elif prop.immutable:
                upd_para = nodes.paragraph('', _('Updates are not supported. '
                                                 'Resource update will fail on'
                                                 ' any attempt to update this '
                                                 'property.'))
                definition.append(upd_para)
            else:
                upd_para = nodes.paragraph('', _('Updates cause replacement.'))
                definition.append(upd_para)

        if prop.default is not None:
            para = nodes.paragraph('', _('Defaults to "%s".') % prop.default)
            definition.append(para)

        for constraint in prop.constraints:
            para = nodes.paragraph('', str(constraint))
            definition.append(para)

        sub_schema = None
        if prop.schema and prop.type == properties.Schema.MAP:
            para = nodes.paragraph()
            emph = nodes.emphasis('', _('Map properties:'))
            para.append(emph)
            definition.append(para)
            sub_schema = prop.schema

        elif prop.schema and prop.type == properties.Schema.LIST:
            para = nodes.paragraph()
            emph = nodes.emphasis('', _('List contents:'))
            para.append(emph)
            definition.append(para)
            sub_schema = prop.schema

        if sub_schema:
            for _key, _prop in sorted(sub_schema.items(),
                                      key=cmp_to_key(self.cmp_prop)):
                if _prop.support_status.status != support.HIDDEN:
                    indent = nodes.block_quote()
                    definition.append(indent)
                    self.contribute_property(
                        indent, _key, _prop, upd_para, id_pattern,
                        sub_prop=True)