def run(self): obj_name = self.arguments[0] try: prefixed_name, obj, parent, modname = import_by_name(obj_name) except ImportError: raise self.error( "Could not locate Python object {} ({} directive).".format(obj_name, self.name) ) document = self.state.document code = str(obj) location = self.state_machine.get_source_and_line(self.lineno) linespec = self.options.get('emphasize-lines') if linespec: try: nlines = len(self.content) hl_lines = parselinenos(linespec, nlines) if any(i >= nlines for i in hl_lines): logger.warning(__('line number spec is out of range(1-%d): %r') % (nlines, self.options['emphasize-lines']), location=location) hl_lines = [x + 1 for x in hl_lines if x < nlines] except ValueError as err: return [document.reporter.warning(str(err), line=self.lineno)] else: hl_lines = None if 'dedent' in self.options: location = self.state_machine.get_source_and_line(self.lineno) lines = code.split('\n') lines = dedent_lines(lines, self.options['dedent'], location=location) code = '\n'.join(lines) literal = nodes.literal_block(code, code) literal['language'] = self.options[LANGUAGE_OPTION] literal['linenos'] = 'linenos' in self.options or \ 'lineno-start' in self.options literal['classes'] += self.options.get('class', []) extra_args = literal['highlight_args'] = {} if hl_lines is not None: extra_args['hl_lines'] = hl_lines if 'lineno-start' in self.options: extra_args['linenostart'] = self.options['lineno-start'] set_source_info(self, literal) caption = self.options.get('caption') if caption: try: literal = container_wrapper(self, literal, caption) except ValueError as exc: return [document.reporter.warning(str(exc), line=self.lineno)] # literal will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(literal) return [literal]
def get_codeblock_node(self, code, language): """this is copied from sphinx.directives.code.CodeBlock.run it has been changed to accept code and language as an arguments instead of reading from self """ document = self.state.document location = self.state_machine.get_source_and_line(self.lineno) linespec = self.options.get('emphasize-lines') if linespec: try: nlines = len(code.split('\n')) hl_lines = parselinenos(linespec, nlines) if any(i >= nlines for i in hl_lines): log.warning( __('line number spec is out of range(1-%d): %r') % (nlines, self.options['emphasize-lines']), location=location) hl_lines = [x + 1 for x in hl_lines if x < nlines] except ValueError as err: return [document.reporter.warning(str(err), line=self.lineno)] else: hl_lines = None if 'dedent' in self.options: location = self.state_machine.get_source_and_line(self.lineno) lines = code.split('\n') lines = dedent_lines(lines, self.options['dedent'], location=location) code = '\n'.join(lines) literal = nodes.literal_block(code, code) literal['language'] = language literal['linenos'] = 'linenos' in self.options or \ 'lineno-start' in self.options literal['classes'] += self.options.get('class', []) extra_args = literal['highlight_args'] = {} if hl_lines is not None: extra_args['hl_lines'] = hl_lines if 'lineno-start' in self.options: extra_args['linenostart'] = self.options['lineno-start'] set_source_info(self, literal) caption = self.options.get('caption') if caption: try: literal = container_wrapper(self, literal, caption) except ValueError as exc: return [document.reporter.warning(str(exc), line=self.lineno)] # literal will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(literal) return [literal]
def run(self): # type: () -> code.List[code.nodes.Node] document = self.state.document if not document.settings.file_insertion_enabled: return [ document.reporter.warning("File insertion disabled", line=self.lineno) ] # convert options['diff'] to absolute path if "diff" in self.options: _, path = self.env.relfn2path(self.options["diff"]) self.options["diff"] = path try: location = self.state_machine.get_source_and_line(self.lineno) filename = os.path.join(self.config.dials_logs, self.arguments[0]) self.env.note_dependency(filename) reader = code.LiteralIncludeReader(filename, self.options, self.config) text, lines = reader.read(location=location) retnode = code.nodes.literal_block(text, text, source=filename) self.set_source_info(retnode) if self.options.get("diff"): # if diff is set, set udiff retnode["language"] = "udiff" elif "language" in self.options: retnode["language"] = self.options["language"] retnode["linenos"] = ("linenos" in self.options or "lineno-start" in self.options or "lineno-match" in self.options) retnode["classes"] += self.options.get("class", []) extra_args = retnode["highlight_args"] = {} if "emphasize-lines" in self.options: hl_lines = code.parselinenos(self.options["emphasize-lines"], lines) if any(i >= lines for i in hl_lines): code.logger.warning( code.__("line number spec is out of range(1-%d): %r") % (lines, self.options["emphasize-lines"]), location=location, ) extra_args["hl_lines"] = [x + 1 for x in hl_lines if x < lines] extra_args["linenostart"] = reader.lineno_start if "caption" in self.options: caption = self.options["caption"] or self.arguments[0] retnode = code.container_wrapper(self, retnode, caption) # retnode will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(retnode) return [retnode] except Exception as exc: print(exc) return [document.reporter.warning(str(exc), line=self.lineno)]
def run(self): # type: () -> List[nodes.Node] document = self.state.document if not document.settings.file_insertion_enabled: return [ document.reporter.warning('File insertion disabled', line=self.lineno) ] env = document.settings.env # convert options['diff'] to absolute path if 'diff' in self.options: _, path = env.relfn2path(self.options['diff']) self.options['diff'] = path try: location = self.state_machine.get_source_and_line(self.lineno) url = self.arguments[0] reader = OnlineIncludeReader(url, self.options, env.config) text, lines = reader.read(location=location) retnode = nodes.literal_block(text, text, source=url) self.set_source_info(retnode) if self.options.get('diff'): # if diff is set, set udiff retnode['language'] = 'udiff' elif 'language' in self.options: retnode['language'] = self.options['language'] retnode['linenos'] = ('linenos' in self.options or 'lineno-start' in self.options or 'lineno-match' in self.options) retnode['classes'] += self.options.get('class', []) extra_args = retnode['highlight_args'] = {} if 'emphasize-lines' in self.options: hl_lines = parselinenos(self.options['emphasize-lines'], lines) if any(i >= lines for i in hl_lines): logger.warning( 'line number spec is out of range(1-%d): %r' % (lines, self.options['emphasize-lines']), location=location) extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines] extra_args['linenostart'] = reader.lineno_start if 'caption' in self.options: caption = self.options['caption'] or self.arguments[0] retnode = container_wrapper(self, retnode, caption) # retnode will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(retnode) return [retnode] except Exception as exc: return [document.reporter.warning(str(exc), line=self.lineno)]
def run(self): if not self.schema: return [] code = self.schema.render() literal = nodes.literal_block(code, code) literal['language'] = 'json' # add a caption literal = container_wrapper(self, literal, 'JSON schema' + self.schema.version) return [literal]
def run(self): document = self.state.document code = '\n'.join(self.content) location = self.state_machine.get_source_and_line(self.lineno) linespec = self.options.get('emphasize-lines') if linespec: try: nlines = len(self.content) hl_lines = parselinenos(linespec, nlines) if any(i >= nlines for i in hl_lines): logger.warning( __('line number spec is out of range(1-%d): %r') % (nlines, self.options['emphasize-lines']), location=location) hl_lines = [x + 1 for x in hl_lines if x < nlines] except ValueError as err: return [document.reporter.warning(err, line=self.lineno)] else: hl_lines = None if 'dedent' in self.options: location = self.state_machine.get_source_and_line(self.lineno) lines = code.split('\n') lines = dedent_lines(lines, self.options['dedent'], location=location) code = '\n'.join(lines) literal = nodes.literal_block(code, code) # type: Element if 'linenos' in self.options or 'lineno-start' in self.options: literal['linenos'] = True literal['classes'] += self.options.get('class', []) literal['force'] = 'force' in self.options if self.arguments: literal['language'] = self.arguments[0] else: literal['language'] = self.env.temp_data.get( 'highlight_language', self.config.highlight_language) extra_args = literal['highlight_args'] = {} if hl_lines is not None: extra_args['hl_lines'] = hl_lines if 'lineno-start' in self.options: extra_args['linenostart'] = self.options['lineno-start'] self.set_source_info(literal) caption = self.options.get('caption') if caption: try: literal = container_wrapper(self, literal, caption) except ValueError as exc: return [document.reporter.warning(exc, line=self.lineno)] self.add_name(literal) ########################################### filename = self.options.get('filename') addCode(self.state.document.settings.env, filename, code) ########################################### return [literal]
def run(self): pyobj = import_object(self.content[0].strip()) json_string = json.dumps(pyobj, indent=2, sort_keys=True, separators=(',', ':')) literal = nodes.literal_block(json_string, json_string) literal['language'] = 'json' set_source_info(self, literal) caption = self.options.get('caption') if caption: literal = container_wrapper(self, literal, caption) return [literal]
def run(self) -> List[Node]: document = self.state.document if not document.settings.file_insertion_enabled: return [ document.reporter.warning('File insertion disabled', line=self.lineno) ] try: uri = self.arguments[0] location = self.state_machine.get_source_and_line(self.lineno) reader = RemoteIncludeReader(uri, self.options, self.config) text, lines = reader.read(location=location) # rel_filename, filename = self.env.relfn2path(self.arguments[0]) # self.env.note_dependency(rel_filename) retnode = nodes.literal_block(text, text, source=uri) # type: Element retnode['force'] = 'force' in self.options self.set_source_info(retnode) if 'language' in self.options: retnode['language'] = self.options['language'] if ('linenos' in self.options or 'lineno-start' in self.options or 'lineno-match' in self.options): retnode['linenos'] = True retnode['classes'] += self.options.get('class', []) extra_args = retnode['highlight_args'] = {} if 'emphasize-lines' in self.options: hl_lines = parselinenos(self.options['emphasize-lines'], lines) if any(i >= lines for i in hl_lines): logger.warning( __('line number spec is out of range(1-%d): %r') % (lines, self.options['emphasize-lines']), location=location) extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines] extra_args['linenostart'] = reader.lineno_start if 'caption' in self.options: caption = self.options['caption'] or self.arguments[0] retnode = container_wrapper(self, retnode, caption) # retnode will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(retnode) return [retnode] except Exception as exc: return [document.reporter.warning(exc, line=self.lineno)]
def run(self): module, clazz = self.arguments[0].rsplit(".", 1) module = importlib.import_module(module) clazz = getattr(module, clazz) if not clazz.SCHEMA: return [] code = nodes.literal_block(text=json.dumps(clazz.SCHEMA, indent=4, sort_keys=True)) code['language'] = 'json' code = container_wrapper(self, code, "Schema") self.add_name(code) return [code]
def run(self): # type: () -> List[nodes.Node] document = self.state.document if not document.settings.file_insertion_enabled: return [ document.reporter.warning('File insertion disabled', line=self.lineno) ] try: location = self.state_machine.get_source_and_line(self.lineno) relpath = self.arguments[0] abspath, relpath = FindPath(relpath, (self.env.docname, self.lineno)) self.env.note_dependency(abspath) reader = LiteralIncludeReader(abspath, self.options, self.config) text, lines = reader.read(location=location) retnode = nodes.literal_block( text, text, source=abspath) # type: nodes.Element #self.set_source_info(retnode) if 'language' not in self.options: self.options['language'] = 'cpp' if 'language' in self.options: retnode['language'] = self.options['language'] if ('linenos' in self.options): retnode['linenos'] = True retnode['classes'] += self.options.get('class', []) extra_args = retnode['highlight_args'] = {} if 'caption' in self.options: caption = self.options['caption'] or self.arguments[0] retnode = container_wrapper(self, retnode, caption) # retnode will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(retnode) return [retnode] except Exception as exc: return [document.reporter.warning(exc, line=self.lineno)]
def run(self) -> List[Node]: logger.warning( "DeprecationWarning: doctest directives will be deprecated due to lack of interest. Please use code-block or literalinclude instead." ) node = super(c, self).run()[0] # This code copied from sphinx.directives.code linespec = self.options.get("emphasize-lines") if linespec: try: nlines = len(self.content) hl_lines = [x + 1 for x in parselinenos(linespec, nlines)] except ValueError as err: document = self.state.document return [document.reporter.warning(str(err), line=self.lineno)] else: hl_lines = None # type: ignore node["classes"] += self.options.get("class", []) extra_args = node["highlight_args"] = {} if hl_lines is not None: extra_args["hl_lines"] = hl_lines if "lineno-start" in self.options: extra_args["linenostart"] = self.options["lineno-start"] set_source_info(self, node) caption = self.options.get("caption") if caption: try: node = container_wrapper(self, node, caption) except ValueError as exc: document = self.state.document errmsg = _("Invalid caption: %s" % exc[0][0].astext()) # type: ignore return [document.reporter.warning(errmsg, line=self.lineno)] self.add_name(node) return [node]
def run(self): document = self.state.document source_file = self.arguments[0] code = u'\n'.join(self.content) # heavily inspired by https://github.com/sphinx-doc/sphinx/blob/3.x/sphinx/directives/code.py#L134 emphasized_lines = self.options.get('emphasize-lines') if emphasized_lines: try: nlines = len(self.content) hl_lines = parselinenos(emphasized_lines, nlines) if any(i >= nlines for i in hl_lines): raise RuntimeError( 'line number spec out of range 1-%d: %r' % ((nlines, self.options['emphasize-lines']))) hl_lines = [i + 1 for i in hl_lines] except ValueError as err: return [document.reporter.warning(err, line=self.lineno)] else: hl_lines = None node = SnippetSourceNode(source_file, self.lineno, code, code) if hl_lines is not None: node['highlight_args'] = {'hl_lines': hl_lines} node['commercial'] = ('commercial' in self.options) caption = self.options.get('caption') if caption: try: node = container_wrapper(self, node, caption) except ValueError as exc: return [document.reporter.warning(exc, line=self.lineno)] # See: https://github.com/sphinx-doc/sphinx/blob/3.x/sphinx/directives/code.py#L184 self.add_name(node) return [node]
def run(self): code = u'\n'.join(self.content) linespec = self.options.get('emphasize-lines') if linespec: try: nlines = len(self.content) hl_lines = [x+1 for x in parselinenos(linespec, nlines)] except ValueError as err: document = self.state.document return [document.reporter.warning(str(err), line=self.lineno)] else: hl_lines = None if 'dedent' in self.options: lines = code.split('\n') lines = dedent_lines(lines, self.options['dedent']) code = '\n'.join(lines) literal = nodes.literal_block(code, code) literal['language'] = self.arguments[0] literal['linenos'] = 'linenos' in self.options or \ 'lineno-start' in self.options extra_args = literal['highlight_args'] = {} if hl_lines is not None: extra_args['hl_lines'] = hl_lines if 'lineno-start' in self.options: extra_args['linenostart'] = self.options['lineno-start'] set_source_info(self, literal) caption = self.options.get('caption') if caption: self.options.setdefault('name', nodes.fully_normalize_name(caption)) literal = container_wrapper(self, literal, caption) self.add_name(literal) ########################################### filename = self.options.get('filename') addCode(self.state.document.settings.env, filename, code) ########################################### return [literal]
def run(self) -> List[Node]: if 'fragment' in self.options: self.options['start-after'] = self.options['fragment'] self.options['end-before'] = self.options['fragment'] document = self.state.document if not document.settings.file_insertion_enabled: return [ document.reporter.warning('File insertion disabled', line=self.lineno) ] # convert options['diff'] to absolute path if 'diff' in self.options: _, path = self.env.relfn2path(self.options['diff']) self.options['diff'] = path try: location = self.state_machine.get_source_and_line(self.lineno) doxygen_snippet_root = self.config.html_context.get( 'doxygen_snippet_root') if doxygen_snippet_root and os.path.exists(doxygen_snippet_root): rel_filename = self.arguments[0] filename = os.path.join(doxygen_snippet_root, rel_filename) else: rel_filename, filename = self.env.relfn2path(self.arguments[0]) self.env.note_dependency(rel_filename) reader = LiteralIncludeReader(filename, self.options, self.config) text, lines = reader.read(location=location) retnode = nodes.literal_block(text, text, source=filename) # type: Element retnode['force'] = 'force' in self.options self.set_source_info(retnode) if self.options.get('diff'): # if diff is set, set udiff retnode['language'] = 'udiff' elif 'language' in self.options: retnode['language'] = self.options['language'] if ('linenos' in self.options or 'lineno-start' in self.options or 'lineno-match' in self.options): retnode['linenos'] = True retnode['classes'] += self.options.get('class', []) extra_args = retnode['highlight_args'] = {} if 'emphasize-lines' in self.options: hl_lines = parselinenos(self.options['emphasize-lines'], lines) if any(i >= lines for i in hl_lines): logger.warning( __('line number spec is out of range(1-%d): %r') % (lines, self.options['emphasize-lines']), location=location) extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines] extra_args['linenostart'] = reader.lineno_start if 'caption' in self.options: caption = self.options['caption'] or self.arguments[0] retnode = container_wrapper(self, retnode, caption) # retnode will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(retnode) return [retnode] except Exception as exc: return [document.reporter.warning(exc, line=self.lineno)]
def run(self): config = None meta_node = None settings_node = None global_caption = None show_source = True editor = self.options['editor'] if 'editor' in self.options else None self.assert_has_content() source = "\n".join(self.content) source_path = self.state_machine.document.settings._source.split( "doc/manual/", 1)[1] screenshot_dir = path.join( "doc", "manual", path.dirname(self.state_machine.document.settings._source).split( "doc/manual/", 1)[1], "_static") name = source_path[:-4].replace("/", "_") if not name in counters: counters[name] = 0 else: counters[name] += 1 design = "metal" visu_config_parts = self.config_parts.copy() try: # we need one surrouding element to prevent parse errors xml = etree.fromstring("<root>%s</root>" % source) for child in xml: if etree.iselement(child): if child.tag == "settings": # meta settings settings_node = child elif child.tag == "meta": # config meta settings meta_node = child elif child.tag == "caption": global_caption = child.text else: # the config example config = child except Exception as e: print("Parse error: %s" % str(e)) example_content = etree.tostring(config, encoding='utf-8') if meta_node is not None: example_content = b"...\n%s...\n%s" % (etree.tostring( meta_node, encoding='utf-8'), example_content) visu_config_parts['meta'] = etree.tostring( meta_node, encoding='utf-8').decode('utf-8') settings = { "selector": ".widget_container", "screenshots": [], "screenshotDir": screenshot_dir } if 'scale' in self.options: scale = max(1, min(100, int(self.options['scale'] or 100))) settings['scale'] = scale shot_index = 0 if editor is not None: # change screenshot + selector settings['editor'] = editor settings['widget'] = config.tag if editor == "attributes": settings[ 'selector'] = ".treeType_%s ul.attributes" % config.tag elif editor == "elements": settings['selector'] = ".treeType_%s" % config.tag settings['screenshots'].append({ "name": "%s_editor_%s" % (name, editor), "data": {} }) show_source = False elif settings_node is not None: # read meta settings design = settings_node.get("design", "metal") settings['selector'] = settings_node.get("selector", ".widget_container") if settings_node.get("sleep"): settings['sleep'] = settings_node.get("sleep") for screenshot in settings_node.iter('screenshot'): shot = { "name": screenshot.get("name", name + str(counters[name] + shot_index)), "data": [] } if screenshot.get("sleep"): shot['sleep'] = screenshot.get("sleep") if screenshot.get("clickpath", None): shot['clickPath'] = screenshot.get('clickpath') if screenshot.get("waitfor", None): shot['waitFor'] = screenshot.get('waitfor') shot_index += 1 for data in screenshot.iter('data'): values = { 'address': data.get("address", "0/0/0"), 'value': data.text } if data.get("type"): values['type'] = data.get("type") shot['data'].append(values) for caption in screenshot.iter('caption'): if 'caption' not in shot: shot['caption'] = caption.text else: shot['caption'] += caption.text settings['screenshots'].append(shot) for caption in settings_node.iterchildren('caption'): global_caption = caption.text # no screenshots defined, add a default one if len(settings['screenshots']) == 0: settings['screenshots'].append({"name": name + str(shot_index)}) # replace the design value in the config visu_config_parts['start'] = visu_config_parts['start'].replace( "%%%DESIGN%%%", design) if config.tag == "page": visu_config_parts['content_start'] = "" visu_config_parts['content_end'] = "" # build the real config source visu_config = visu_config_parts['start'] + \ visu_config_parts['meta'] + \ visu_config_parts['content_start'] + \ etree.tostring(config, encoding='utf-8').decode('utf-8') + \ visu_config_parts['content_end'] + \ visu_config_parts['end'] # validate generated config against XSD try: etree.fromstring(visu_config, parser) except etree.XMLSyntaxError as e: raise self.error(str(e)) if not path.exists(self.example_dir): makedirs(self.example_dir) with open("%s_%s.xml" % (path.join(self.example_dir, name), counters[name]), encoding='utf-8', mode="w") as f: f.write(u"%s\n%s" % (json.dumps(settings), visu_config)) # create the code-block classes = ['code', 'xml'] # set up lexical analyzer try: tokens = Lexer(example_content, 'xml', self.state.document.settings.syntax_highlight) except LexerError as error: raise self.warning(error) if 'number-lines' in self.options: # optional argument `startline`, defaults to 1 try: startline = int(self.options['number-lines'] or 1) except ValueError: raise self.error(':number-lines: with non-integer start value') endline = startline + len(self.content) # add linenumber filter: tokens = NumberLines(tokens, startline, endline) if 'hide-source' in self.options and show_source: show_source = self.options['hide-source'] != "true" res_nodes = [] for shot in settings['screenshots']: reference = "_static/%s.png" % shot['name'] options = dict(uri=reference) if 'caption' in shot: options['alt'] = shot['caption'] image_node = nodes.image(rawsource=shot['name'], **options) figure_node = nodes.figure('', image_node) if 'align' in self.options: figure_node['align'] = self.options['align'] if 'caption' in shot: self.add_caption(shot['caption'], figure_node) elif not show_source and global_caption and len( settings['screenshots']) == 1: self.add_caption(global_caption, figure_node) res_nodes.append(figure_node) if show_source: example_content = example_content.decode('utf-8') node = nodes.literal_block(example_content, example_content) node['language'] = 'xml' node['linenos'] = 'linenos' in self.options or \ 'lineno-start' in self.options node['classes'] += self.options.get('class', []) set_source_info(self, node) if global_caption: self.options.setdefault( 'name', nodes.fully_normalize_name(global_caption)) node = container_wrapper(self, node, global_caption) self.add_name(node) res_nodes.append(node) return res_nodes