我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用docutils.parsers.rst.directives.directive()。
def parse_directive_arguments(self, directive, arg_block): required = directive.required_arguments optional = directive.optional_arguments arg_text = '\n'.join(arg_block) arguments = arg_text.split() if len(arguments) < required: raise MarkupError('%s argument(s) required, %s supplied' % (required, len(arguments))) elif len(arguments) > required + optional: if directive.final_argument_whitespace: arguments = arg_text.split(None, required + optional - 1) else: raise MarkupError( 'maximum %s argument(s) allowed, %s supplied' % (required + optional, len(arguments))) return arguments
def lookup_domain_element(self, type, name): """Lookup a markup element (directive or role), given its name which can be a full name (with domain). """ name = name.lower() # explicit domain given? if ':' in name: domain_name, name = name.split(':', 1) if domain_name in self.domains: domain = self.domains[domain_name] element = getattr(domain, type)(name) if element is not None: return element, [] # else look in the default domain else: def_domain = self.temp_data.get('default_domain') if def_domain is not None: element = getattr(def_domain, type)(name) if element is not None: return element, [] # always look in the std domain element = getattr(self.domains['std'], type)(name) if element is not None: return element, [] raise ElementLookupError
def patch_lookup_functions(self): """Monkey-patch directive and role dispatch, so that domain-specific markup takes precedence. """ def directive(name, lang_module, document): try: return self.lookup_domain_element('directive', name) except ElementLookupError: return orig_directive_function(name, lang_module, document) def role(name, lang_module, lineno, reporter): try: return self.lookup_domain_element('role', name) except ElementLookupError: return orig_role_function(name, lang_module, lineno, reporter) directives.directive = directive roles.role = role
def create_title_from(self, docname, document): """Add a title node to the document (just copy the first section title), and store that title in the environment. """ titlenode = nodes.title() longtitlenode = titlenode # explicit title set with title directive; use this only for # the <title> tag in HTML output if 'title' in document: longtitlenode = nodes.title() longtitlenode += nodes.Text(document['title']) # look for first section title and use that as the title for node in document.traverse(nodes.section): visitor = SphinxContentsFilter(document) node[0].walkabout(visitor) titlenode += visitor.get_entry_text() break else: # document has no title titlenode += nodes.Text('<no title>') self.titles[docname] = titlenode self.longtitles[docname] = longtitlenode
def process_only_nodes(self, doctree, builder, fromdocname=None): # A comment on the comment() nodes being inserted: replacing by [] would # result in a "Losing ids" exception if there is a target node before # the only node, so we make sure docutils can transfer the id to # something, even if it's just a comment and will lose the id anyway... for node in doctree.traverse(addnodes.only): try: ret = builder.tags.eval_condition(node['expr']) except Exception as err: self.warn_node('exception while evaluating only ' 'directive expression: %s' % err, node) node.replace_self(node.children or nodes.comment()) else: if ret: node.replace_self(node.children or nodes.comment()) else: node.replace_self(nodes.comment())
def directive(self, match, **option_presets): """Returns a 2-tuple: list of nodes, and a "blank finish" boolean.""" type_name = match.group(1) directive_class, messages = directives.directive( type_name, self.memo.language, self.document) self.parent += messages if directive_class: return self.run_directive( directive_class, match, type_name, option_presets) else: return self.unknown_directive(type_name)
def unknown_directive(self, type_name): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(0, strip_indent=False) text = '\n'.join(indented) error = self.reporter.error( 'Unknown directive type "%s".' % type_name, nodes.literal_block(text, text), line=lineno) return [error], blank_finish
def note_toctree(self, docname, toctreenode): """Note a TOC tree directive in a document and gather information about file relations from it. """ if toctreenode['glob']: self.glob_toctrees.add(docname) if toctreenode.get('numbered'): self.numbered_toctrees.add(docname) includefiles = toctreenode['includefiles'] for includefile in includefiles: # note that if the included file is rebuilt, this one must be # too (since the TOC of the included file could have changed) self.files_to_rebuild.setdefault(includefile, set()).add(docname) self.toctree_includes.setdefault(docname, []).extend(includefiles)
def run_directive(self, directive, match, type_name, option_presets): """ Parse a directive then run its directive function. Parameters: - `directive`: The class implementing the directive. Must be a subclass of `rst.Directive`. - `match`: A regular expression match object which matched the first line of the directive. - `type_name`: The directive name, as used in the source text. - `option_presets`: A dictionary of preset options, defaults for the directive options. Currently, only an "alt" option is passed by substitution definitions (value: the substitution name), which may be used by an embedded image directive. Returns a 2-tuple: list of nodes, and a "blank finish" boolean. """ if isinstance(directive, (FunctionType, MethodType)): from docutils.parsers.rst import convert_directive_function directive = convert_directive_function(directive) lineno = self.state_machine.abs_line_number() initial_line_offset = self.state_machine.line_offset indented, indent, line_offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), strip_top=0) block_text = '\n'.join(self.state_machine.input_lines[ initial_line_offset : self.state_machine.line_offset + 1]) try: arguments, options, content, content_offset = ( self.parse_directive_block(indented, line_offset, directive, option_presets)) except MarkupError, detail: error = self.reporter.error( 'Error in "%s" directive:\n%s.' % (type_name, ' '.join(detail.args)), nodes.literal_block(block_text, block_text), line=lineno) return [error], blank_finish directive_instance = directive( type_name, arguments, options, content, lineno, content_offset, block_text, self, self.state_machine) try: result = directive_instance.run() except docutils.parsers.rst.DirectiveError, error: msg_node = self.reporter.system_message(error.level, error.msg, line=lineno) msg_node += nodes.literal_block(block_text, block_text) result = [msg_node] assert isinstance(result, list), \ 'Directive "%s" must return a list of nodes.' % type_name for i in range(len(result)): assert isinstance(result[i], nodes.Node), \ ('Directive "%s" returned non-Node object (index %s): %r' % (type_name, i, result[i])) return (result, blank_finish or self.state_machine.is_next_line_blank())
def parse_directive_block(self, indented, line_offset, directive, option_presets): option_spec = directive.option_spec has_content = directive.has_content if indented and not indented[0].strip(): indented.trim_start() line_offset += 1 while indented and not indented[-1].strip(): indented.trim_end() if indented and (directive.required_arguments or directive.optional_arguments or option_spec): for i, line in enumerate(indented): if not line.strip(): break else: i += 1 arg_block = indented[:i] content = indented[i+1:] content_offset = line_offset + i + 1 else: content = indented content_offset = line_offset arg_block = [] if option_spec: options, arg_block = self.parse_directive_options( option_presets, option_spec, arg_block) else: options = {} if arg_block and not (directive.required_arguments or directive.optional_arguments): content = arg_block + indented[i:] content_offset = line_offset arg_block = [] while content and not content[0].strip(): content.trim_start() content_offset += 1 if directive.required_arguments or directive.optional_arguments: arguments = self.parse_directive_arguments( directive, arg_block) else: arguments = [] if content and not has_content: raise MarkupError('no content permitted') return (arguments, options, content, content_offset)
def run_directive(self, directive, match, type_name, option_presets): """ Parse a directive then run its directive function. Parameters: - `directive`: The class implementing the directive. Must be a subclass of `rst.Directive`. - `match`: A regular expression match object which matched the first line of the directive. - `type_name`: The directive name, as used in the source text. - `option_presets`: A dictionary of preset options, defaults for the directive options. Currently, only an "alt" option is passed by substitution definitions (value: the substitution name), which may be used by an embedded image directive. Returns a 2-tuple: list of nodes, and a "blank finish" boolean. """ if isinstance(directive, (FunctionType, MethodType)): from docutils.parsers.rst import convert_directive_function directive = convert_directive_function(directive) lineno = self.state_machine.abs_line_number() initial_line_offset = self.state_machine.line_offset indented, indent, line_offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), strip_top=0) block_text = '\n'.join(self.state_machine.input_lines[ initial_line_offset : self.state_machine.line_offset + 1]) try: arguments, options, content, content_offset = ( self.parse_directive_block(indented, line_offset, directive, option_presets)) except MarkupError as detail: error = self.reporter.error( 'Error in "%s" directive:\n%s.' % (type_name, ' '.join(detail.args)), nodes.literal_block(block_text, block_text), line=lineno) return [error], blank_finish directive_instance = directive( type_name, arguments, options, content, lineno, content_offset, block_text, self, self.state_machine) try: result = directive_instance.run() except docutils.parsers.rst.DirectiveError as error: msg_node = self.reporter.system_message(error.level, error.msg, line=lineno) msg_node += nodes.literal_block(block_text, block_text) result = [msg_node] assert isinstance(result, list), \ 'Directive "%s" must return a list of nodes.' % type_name for i in range(len(result)): assert isinstance(result[i], nodes.Node), \ ('Directive "%s" returned non-Node object (index %s): %r' % (type_name, i, result[i])) return (result, blank_finish or self.state_machine.is_next_line_blank())