我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用docutils.statemachine.ViewList()。
def handle_signature(self, sig, signode): print("looking for: " + sig) cache = _APP_CACHES.get(self.env.app, {}) key = CursorKind.FUNCTION_DECL, (sig, ) if key in cache: print("KEY FOunD!") node, comment, start, end, _ = cache[key] result_type = node.type.get_result() signode += addnodes.desc_type(result_type.spelling, result_type.spelling + ' ') signode += addnodes.desc_name(node.spelling, node.spelling) paramlist = addnodes.desc_parameterlist() for argument in node.get_arguments(): parameter = addnodes.desc_parameter() parameter += addnodes.desc_type(argument.type.spelling, argument.type.spelling + ' ') parameter += nodes.Text(argument.spelling, argument.spelling) paramlist += parameter signode += paramlist self.content = ViewList() comment = ''.join(comment) for lineno, line in enumerate(comment.splitlines(), start[0]): self.content.append(line, '<unknown>', lineno) return sig
def run(self): self.filenames = set() if self.arguments[0] == 'lexers': out = self.document_lexers() elif self.arguments[0] == 'formatters': out = self.document_formatters() elif self.arguments[0] == 'filters': out = self.document_filters() else: raise Exception('invalid argument for "pygmentsdoc" directive') node = nodes.compound() vl = ViewList(out.split('\n'), source='') nested_parse_with_titles(self.state, vl, node) for fn in self.filenames: self.state.document.settings.record_dependencies.add(fn) return node.children
def wrap_mangling_directive(base_directive, objtype): class directive(base_directive): def run(self): env = self.state.document.settings.env name = None if self.arguments: m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0]) name = m.group(2).strip() if not name: name = self.arguments[0] lines = list(self.content) mangle_docstrings(env.app, objtype, name, None, None, lines) self.content = ViewList(lines, self.content.parent) return base_directive.run(self) return directive
def wrap_mangling_directive(base_directive, objtype): class directive(base_directive): def run(self): env = self.state.document.settings.env name = None if self.arguments: m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0]) name = m.group(2).strip() if not name: name = self.arguments[0] lines = list(self.content) mangle_docstrings(env.app, objtype, name, None, None, lines) # local import to avoid testing dependency from docutils.statemachine import ViewList self.content = ViewList(lines, self.content.parent) return base_directive.run(self) return directive
def create_image_nodes(self, header, thumb_url, key, link_url=None): options = {'target': link_url} if link_url else {} options.update(self.options) d1 = directives.misc.Raw( 'raw', ['html'], {}, ViewList([ '<div class="sphx-glr-thumbContainer">'] ), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) d = directives.images.Figure( 'image', [thumb_url], options, ViewList([':ref:`%s`' % key]), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) d2 = directives.misc.Raw( 'raw', ['html'], {}, ViewList(['</div>']), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) return list(chain(d1.run(), d.run(), d2.run()))
def run(self): # pragma: no cover """Called by Sphinx to generate documentation for this directive.""" if self.directive_name is None: raise NotImplementedError('directive_name must be implemented by ' 'subclasses of BaseDirective') env, state = self._prepare_env() state.doc_names.add(env.docname) directive_name = '<{}>'.format(self.directive_name) node = nodes.section() node.document = self.state.document result = ViewList() for line in self._render_rst(): if line.startswith(HEADING_TOKEN): # Remove heading token, then append 2 lines, one with # the heading text, and the other with the dashes to # underline the heading. heading = line[HEADING_TOKEN_LENGTH:] result.append(heading, directive_name) result.append('-' * len(heading), directive_name) else: result.append(line, directive_name) nested_parse_with_titles(self.state, result, node) return node.children
def wrap_mangling_directive(base_directive, objtype): class directive(base_directive): def run(self): env = self.state.document.settings.env name = None if self.arguments: m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0]) name = m.group(2).strip() if not name: name = self.arguments[0] lines = list(self.content) mangle_docstrings(env.app, objtype, name, None, None, lines) if self.content: items = match_items(lines, self.content) self.content = ViewList(lines, items=items, parent=self.content.parent) return base_directive.run(self) return directive
def _parse(self, rst_text, annotation): result = ViewList() for line in rst_text.split("\n"): result.append(line, annotation) node = nodes.paragraph() node.document = self.state.document nested_parse_with_titles(self.state, result, node) return node.children
def run(self): env = self.state.document.settings.env relpath, abspath = env.relfn2path(directives.path(self.arguments[0])) # Add OpenAPI spec as a dependency to the current document. That means # the document will be rebuilt if the spec is changed. env.note_dependency(relpath) # Read the spec using encoding passed to the directive or fallback to # the one specified in Sphinx's config. encoding = self.options.get('encoding', env.config.source_encoding) with io.open(abspath, 'rt', encoding=encoding) as stream: spec = yaml.load(stream, _YamlOrderedLoader) # URI parameter is crucial for resolving relative references. So # we need to set this option properly as it's used later down the # stack. self.options.setdefault('uri', 'file://%s' % abspath) # reStructuredText DOM manipulation is pretty tricky task. It requires # passing dozen arguments which is not easy without well-documented # internals. So the idea here is to represent OpenAPI spec as # reStructuredText in-memory text and parse it in order to produce a # real DOM. viewlist = ViewList() for line in openapi2httpdomain(spec, **self.options): viewlist.append(line, '<openapi>') # Parse reStructuredText contained in `viewlist` and return produced # DOM nodes. node = nodes.section() node.document = self.state.document nested_parse_with_titles(self.state, viewlist, node) return node.children
def handle_signature(self, sig, signode): cache = _APP_CACHES.get(self.env.app, {}) key = CursorKind.MACRO_DEFINITION, (sig, ) if key in cache: node, comment, start, end, _ = cache[key] signode += addnodes.desc_name(node.displayname, node.displayname) # There is unfortunately no API to get the parameters of a macro, # so we identify them by looking at the tokens. tokens = list(node.get_tokens()) if ( tokens[1].kind is TokenKind.PUNCTUATION and tokens[1].spelling == '(' ): paramlist = addnodes.desc_parameterlist() for token in tokens[2:]: if ( token.kind is TokenKind.PUNCTUATION and token.spelling == ')' ): break elif token.kind is TokenKind.IDENTIFIER: paramlist += addnodes.desc_parameter(token.spelling, token.spelling) signode += paramlist self.content = ViewList() for lineno, line in enumerate(comment.splitlines(), start[0]): self.content.append(line, '<unknown>', lineno) return sig
def handle_signature(self, sig, signode): cache = _APP_CACHES.get(self.env.app, {}) key = CursorKind.VAR_DECL, (sig, ) if key in cache: node, comment, start, end, _ = cache[key] signode += addnodes.desc_type(node.type.spelling, node.type.spelling + ' ') signode += addnodes.desc_name(node.spelling, node.spelling) self.content = ViewList() for lineno, line in enumerate(comment.splitlines(), start[0]): self.content.append(line, '<unknown>', lineno) return sig
def handle_signature(self, sig, signode): try: tag, name = sig.split() except ValueError: tag, name = None, sig cache = _APP_CACHES.get(self.env.app, {}) key = {'struct': CursorKind.STRUCT_DECL}[tag], (name, ) if key in cache: node, comment, start, end, members = cache[key] signode += addnodes.desc_type(tag, tag + ' ') signode += addnodes.desc_name(node.spelling, node.spelling) self.content = ViewList() for line in comment.splitlines(): self.content.append(line, '<unknown>') self.content.append('', '<unknown>') for (_, member_name), value in members.items(): member_node, member_comment, _, _, _ = value self.content.append( '.. c:member:: %s %s' % (member_node.type.spelling, member_node.spelling), '<unknown>' ) self.content.append('', '<unknown>') for line in member_comment.splitlines(): self.content.append(' ' + line, '<unknown>') self.content.append('', '<unknown>') return sig
def cell(self, text): entry = nodes.entry() if not isinstance(text, string_types): text = str(text) viewlist = ViewList(text.split('\n'), source=text) self.state.nested_parse(viewlist, 0, entry) return entry
def autohelp_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """produces rst from nose help""" config = Config(parserClass=OptBucket, plugins=BuiltinPluginManager()) parser = config.getParser(TestProgram.usage()) rst = ViewList() for line in parser.format_help().split('\n'): rst.append(line, '<autodoc>') rst.append('Options', '<autodoc>') rst.append('-------', '<autodoc>') rst.append('', '<autodoc>') for opt in parser: rst.append(opt.options(), '<autodoc>') rst.append(' \n', '<autodoc>') rst.append(' ' + opt.help + '\n', '<autodoc>') rst.append('\n', '<autodoc>') node = nodes.section() node.document = state.document surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children
def add_desc_col(self, value): entry = nodes.entry() result = ViewList(value.split('\n')) self.state.nested_parse(result, 0, entry) return entry
def get_rows(self, table_data): rows = [] groups = [] trow = nodes.row() entry = nodes.entry() para = nodes.paragraph(text=unicode(table_data)) entry += para trow += entry rows.append(trow) return rows, groups # Add a column for a field. In order to have the RST inside # these fields get rendered, we need to use the # ViewList. Note, ViewList expects a list of lines, so chunk # up our content as a list to make it happy.
def add_col(self, value): entry = nodes.entry() result = ViewList(value.split('\n')) self.state.nested_parse(result, 0, entry) return entry
def run(self): node = nodes.section() node.document = self.state.document result = ViewList() for line in self.make_rst(): result.append(line, '<autotemboard>') nested_parse_with_titles(self.state, result, node) return node.children
def run(self): env = self.state.document.settings.env result = ViewList() for pattern in self.arguments[0].split(): filenames = glob.glob(env.config.cautodoc_root + '/' + pattern) if len(filenames) == 0: env.app.warn('Pattern "%s" does not match any files.' % (pattern), location=(env.docname, self.lineno)) continue for filename in filenames: mode = os.stat(filename).st_mode if stat.S_ISDIR(mode): env.app.warn('Path "%s" matching pattern "%s" is a directory.' % (filename, pattern), location=(env.docname, self.lineno)) continue # Tell Sphinx about the dependency env.note_dependency(os.path.abspath(filename)) self.parse(result, filename) node = nodes.section() try: old_reporter = self.state.memo.reporter self.state.memo.reporter = AutodocReporter(result, self.state.memo.reporter) nested_parse_with_titles(self.state, result, node) finally: self.state.memo.reporter = old_reporter return node.children
def container_wrapper(directive, literal_node, caption): container_node = nodes.container('', literal_block=True, classes=['literal-block-wrapper']) parsed = nodes.Element() directive.state.nested_parse(ViewList([caption], source=''), directive.content_offset, parsed) caption_node = nodes.caption(parsed[0].rawsource, '', *parsed[0].children) caption_node.source = parsed[0].source caption_node.line = parsed[0].line container_node += caption_node container_node += literal_node return container_node
def run(self): self.env = env = self.state.document.settings.env self.genopt = Options() self.warnings = [] self.result = ViewList() names = [x.strip().split()[0] for x in self.content if x.strip() and re.search(r'^[~a-zA-Z_]', x.strip()[0])] items = self.get_items(names) nodes = self.get_table(items) if 'toctree' in self.options: dirname = posixpath.dirname(env.docname) tree_prefix = self.options['toctree'].strip() docnames = [] for name, sig, summary, real_name in items: docname = posixpath.join(tree_prefix, real_name) docname = posixpath.normpath(posixpath.join(dirname, docname)) if docname not in env.found_docs: self.warn('toctree references unknown document %r' % docname) docnames.append(docname) tocnode = addnodes.toctree() tocnode['includefiles'] = docnames tocnode['entries'] = [(None, docn) for docn in docnames] tocnode['maxdepth'] = -1 tocnode['glob'] = None tocnode = autosummary_toc('', '', tocnode) nodes.append(tocnode) return self.warnings + nodes
def figure_wrapper(directive, node, caption): figure_node = nodes.figure('', node) parsed = nodes.Element() directive.state.nested_parse(ViewList([caption], source=''), directive.content_offset, parsed) caption_node = nodes.caption(parsed[0].rawsource, '', *parsed[0].children) caption_node.source = parsed[0].source caption_node.line = parsed[0].line figure_node += caption_node return figure_node
def run(self): self.reporter = self.state.document.reporter self.result = ViewList() self.generate_docs(self.arguments[0], self.content) if not self.result: return [] node = nodes.paragraph() node.document = self.state.document self.state.nested_parse(self.result, 0, node) return node.children