def make_title(self): # type: () -> Tuple[nodes.Node, unicode] title, message = tables.ListTable.make_title(self) if title: set_source_info(self, title) return title, message
def run(self): visual_node = visual(is_figure=False) set_source_info(self, visual_node) set_type_info(self, visual_node) visual_node['docname'], visual_node['visualid'] = self.get_visual_id_info() self.options['name'] = visual_node['visualid'] self.add_name(visual_node) self.emit('visual-node-inited', self, visual_node) caption = self.get_caption() legend, visual_node['content_block'] = self.get_legend_and_visual_content() if caption is not None or legend is not None: visual_node['is_figure'] = True self.emit('visual-caption-and-legend-extracted', self, visual_node, caption, legend) if visual_node['type'] == 'photo': uri = self.get_temp_image_uri() self.run_figure_or_image_with_uri(uri, visual_node, caption, legend) # Replacing image node is not a good option, but we could manipulate uri. # for image_node in visual_node.traverse(condition=nodes.image): # image_node['uri'] = something # By default, assume it doesn't need a placeholder. Later processing can change this. visual_node['placeholder'] = False elif visual_node['type'] == 'video': raise NotImplementedError('Visuals does not support videos yet') else: raise NotImplementedError('Visuals does not support link or rich oembed content yet') self.emit('visual-node-generated', self, visual_node) return [visual_node]
def add_auto_version_changed(self, node): """Add a version_node to document a version change to ``node``. Add the new node at the end of ``node``. """ symbol = self.lookup_auto_symbol() if not symbol: return package, version = symbol.properties.get( 'custom-package-version', ('', '')) if version: version_node = addnodes.versionmodified() version_node.document = self.state.document set_source_info(self, version_node) version_node['type'] = 'versionchanged' version_node['version'] = version msg = self.VERSION_CHANGE_LABEL.format( objtype=self.object_type.lname, version=version, package=package) msg_node = corenodes.inline('', msg, classes=['versionmodified']) version_node.append(corenodes.paragraph('', '', msg_node)) env = self.state.document.settings.env env.note_versionchange( version_node['type'], version_node['version'], version_node, version_node.line) node.append(version_node) return node
def run(self): node = addnodes.versionmodified() node.document = self.state.document set_source_info(self, node) node['type'] = self.name node['version'] = self.arguments[0] text = versionlabels[self.name] % self.arguments[0] if len(self.arguments) == 2: inodes, messages = self.state.inline_text(self.arguments[1], self.lineno+1) para = nodes.paragraph(self.arguments[1], '', *inodes) set_source_info(self, para) node.append(para) else: messages = [] if self.content: self.state.nested_parse(self.content, self.content_offset, node) if len(node): if isinstance(node[0], nodes.paragraph) and node[0].rawsource: content = nodes.inline(node[0].rawsource, translatable=True) content.source = node[0].source content.line = node[0].line content += node[0].children node[0].replace_self(nodes.paragraph('', '', content)) node[0].insert(0, nodes.inline('', '%s: ' % text, classes=['versionmodified'])) else: para = nodes.paragraph('', '', nodes.inline('', '%s.' % text, classes=['versionmodified'])) node.append(para) env = self.state.document.settings.env # XXX should record node.source as well env.note_versionchange(node['type'], node['version'], node, node.line) return [node] + messages
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: literal = container_wrapper(self, literal, caption) return [literal]
def make_title(self): # type: () -> Tuple[nodes.title, List[nodes.system_message]] title, message = super().make_title() if title: set_source_info(self, title) return title, message
def run(self): 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 relative_filename, filename = env.relfn2path(self.arguments[0]) encoding = self.options.get('encoding', env.config.source_encoding) codec_info = codecs.lookup(encoding) try: f = codecs.StreamReaderWriter(open(filename, 'rb'), codec_info[2], codec_info[3], 'strict') text = f.read() # file content f.close() except (IOError, OSError): return [document.reporter.warning('Include file %r not found or reading it failed' % filename, line=self.lineno)] except UnicodeError: return [document.reporter.warning('Encoding %r used for reading included file %r seems to ' 'be wrong, try giving an :encoding: option' % (encoding, filename))] retnode = GetTheCode(text, text, source=filename, filename=None) set_source_info(self, retnode) if self.options.get('language', ''): retnode['language'] = self.options['language'] if 'linenos' in self.options: retnode['linenos'] = True if 'hidden' in self.options: retnode['hidden'] = True env.note_dependency(relative_filename) return [retnode]
def run(self): env = self.state.document.settings.env app = env.app # filename *or* python code content, but not both if self.arguments and self.content: raise SphinxError("bokeh-plot:: directive can't have both args and content") # process inline examples here if self.content: app.debug("[bokeh-plot] handling inline example in %r", env.docname) source = '\n'.join(self.content) # need docname not to look like a path docname = env.docname.replace("/", "-") serialno = env.new_serialno(env.docname) js_name = "bokeh-plot-%s-inline-%d.js" % (docname, serialno) # the code runner just needs a real path to cd to, this will do path = join(env.bokeh_plot_auxdir, js_name) (script, js, js_path, source) = _process_script(source, path, env.bokeh_plot_auxdir, js_name) env.bokeh_plot_files[js_name] = (script, js, js_path, source) # process example files here else: example_path = self.arguments[0][:-3] # remove the ".py" # if it's an "internal" example, the python parser has already handled it if example_path in env.bokeh_plot_files: app.debug("[bokeh-plot] handling internal example in %r: %s", env.docname, self.arguments[0]) (script, js, js_path, source) = env.bokeh_plot_files[example_path] # handle examples external to the docs source, e.g. gallery examples else: app.debug("[bokeh-plot] handling external example in %r: %s", env.docname, self.arguments[0]) source = open(self.arguments[0]).read() source = decode_utf8(source) docname = env.docname.replace("/", "-") serialno = env.new_serialno(env.docname) js_name = "bokeh-plot-%s-external-%d.js" % (docname, serialno) (script, js, js_path, source) = _process_script(source, self.arguments[0], env.bokeh_plot_auxdir, js_name) env.bokeh_plot_files[js_name] = (script, js, js_path, source) # use the source file name to construct a friendly target_id target_id = "%s.%s" % (env.docname, basename(js_path)) target = nodes.target('', '', ids=[target_id]) result = [target] code = nodes.literal_block(source, source, language="python", linenos=False, classes=[]) set_source_info(self, code) source_position = self.options.get('source-position', 'below') if source_position == "above": result += [code] result += [nodes.raw('', script, format="html")] if source_position == "below": result += [code] return result
def run(self): filename = self.arguments[0] cwd = os.getcwd() os.chdir(TMPDIR) parts = [] try: code = AsdfFile.read(filename, _get_yaml_content=True) code = '{0}{1}\n'.format(ASDF_MAGIC, version_string) + code.strip().decode('utf-8') literal = nodes.literal_block(code, code) literal['language'] = 'yaml' set_source_info(self, literal) parts.append(literal) ff = AsdfFile.read(filename) for i, block in enumerate(ff.blocks.internal_blocks): data = codecs.encode(block.data.tostring(), 'hex') if len(data) > 40: data = data[:40] + '...'.encode() allocated = block._allocated size = block._size data_size = block._data_size flags = block._flags if flags & BLOCK_FLAG_STREAMED: allocated = size = data_size = 0 lines = [] lines.append('BLOCK {0}:'.format(i)) human_flags = [] for key, val in FLAGS.items(): if flags & key: human_flags.append(val) if len(human_flags): lines.append(' flags: {0}'.format(' | '.join(human_flags))) if block.compression: lines.append(' compression: {0}'.format(block.compression)) lines.append(' allocated_size: {0}'.format(allocated)) lines.append(' used_size: {0}'.format(size)) lines.append(' data_size: {0}'.format(data_size)) lines.append(' data: {0}'.format(data)) code = '\n'.join(lines) literal = nodes.literal_block(code, code) literal['language'] = 'yaml' set_source_info(self, literal) parts.append(literal) finally: os.chdir(cwd) result = nodes.admonition() textnodes, messages = self.state.inline_text(filename, self.lineno) title = nodes.title(filename, '', *textnodes) result += title result.children.extend(parts) return [result]
def run(self): # type: () -> List[nodes.Node] self.assert_has_content() code = '\n'.join(self.content) node = nodes.literal_block(code, code, classes=self.options.get('classes', []), highlight_args={}) self.add_name(node) set_source_info(self, node) if self.arguments: # highlight language specified node['language'] = self.arguments[0] node['force_highlighting'] = True else: # no highlight language specified. Then this directive refers the current # highlight setting via ``highlight`` directive or ``highlight_language`` # configuration. node['language'] = self.env.temp_data.get('highlight_language', self.config.highlight_language) node['force_highlighting'] = False if 'number-lines' in self.options: node['linenos'] = True # if number given, treat as lineno-start. if self.options['number-lines']: node['highlight_args']['linenostart'] = self.options['number-lines'] return [node]
def run(self): language = self.arguments[0] indexed_languages = self.options.get('index_as') or language index_specs = ['pair: {}; language'.format(l) for l in indexed_languages.splitlines()] name = nodes.fully_normalize_name(language) target = 'language-{}'.format(name) targetnode = nodes.target('', '', ids=[target]) self.state.document.note_explicit_target(targetnode) indexnode = addnodes.index() indexnode['entries'] = [] indexnode['inline'] = False set_source_info(self, indexnode) for spec in index_specs: indexnode['entries'].extend(process_index_entry(spec, target)) sectionnode = nodes.section() sectionnode['names'].append(name) title, messages = self.state.inline_text(language, self.lineno) titlenode = nodes.title(language, '', *title) sectionnode += titlenode sectionnode += messages self.state.document.note_implicit_target(sectionnode, sectionnode) self.state.nested_parse(self.content, self.content_offset, sectionnode) return [indexnode, targetnode, sectionnode]
def run(self): r'''Executes the directive. ''' from abjad import abjad_configuration self.assert_has_content() os.chdir(abjad_configuration.abjad_directory) result = [] for line in self.content: curdir = os.path.basename(os.path.abspath(os.path.curdir)) prompt = '{}$ '.format(curdir) prompt += line result.append(prompt) process = subprocess.Popen( line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout = self._read_from_pipe(process.stdout) stderr = self._read_from_pipe(process.stderr) result.append(stdout) result.append(stderr) code = '\n'.join(result) literal = nodes.literal_block(code, code) literal['language'] = 'console' set_source_info(self, literal) return [literal]
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 literal = nodes.literal_block(code, code) literal['language'] = self.arguments[0] filename = self.options.get('filename') if filename: literal['filename'] = filename 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) return [literal]
def run(self): node = ifconfig() node.document = self.state.document set_source_info(self, node) node["expr"] = self.arguments[0] self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) return [node]
def run(self): from docutils import nodes from sphinx import addnodes from sphinx.util.nodes import set_source_info node = addnodes.only() node.document = self.state.document set_source_info(self, node) node['expr'] = self.arguments[0] # hack around title style bookkeeping surrounding_title_styles = self.state.memo.title_styles surrounding_section_level = self.state.memo.section_level self.state.memo.title_styles = [] self.state.memo.section_level = 0 try: result = self.state.nested_parse(self.content, 0, node, match_titles=1) depth = len(surrounding_title_styles) if self.state.memo.title_styles: style = self.state.memo.title_styles[0] if style in surrounding_title_styles: depth = surrounding_title_styles.index(style) parent = self.state.parent for i in xrange(len(surrounding_title_styles) - depth): if parent.parent: parent = parent.parent parent.append(node) finally: self.state.memo.title_styles = surrounding_title_styles self.state.memo.section_level = surrounding_section_level return []
def run(self): document = self.state.document env = document.settings.env docname = env.docname if ':' in self.name: self.domain, self.objtype = self.name.split(':', 1) else: self.domain, self.objtype = 'py', self.name key = self.find_key(self.content.parent) targetnode = nodes.target('', '', ids=[key]) key_elem = keynode(key) # Separating argument and content causes two <dd>-s to be generated in # the same <dl> doc = addnodes.desc_content() update_attrs(doc, self) txt = '\n'.join(self.arguments) self.before_content() details = keydoc(self.state, self.content) update_attrs(details, self) DocFieldTransformer(self).transform_all(details) self.after_content() doc += nodes.paragraph(txt, txt) doc += details import os source_line = self.lineno source, _ = self.state_machine.get_source_and_line(source_line) src_file, src_other = source.split(':', 1) source_file = os.path.basename(src_file) doc_entry = ibkey(self, key, key_elem, doc) #doc_entry = make_admonition(dummy, self.name, 'Alma', self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine)[0] catalog_entry = iblist_entry( self, env, docname, src_other, source_file, source_line, key, key_elem, doc) set_source_info(self, doc_entry) set_source_info(self, catalog_entry) env.resolve_references(doc_entry, docname, env.app.builder) env.resolve_references(catalog_entry, docname, env.app.builder) if not hasattr(env, 'ibkey_all_ibkeys'): env.ibkey_all_ibkeys = dict() env.ibkey_all_ibkeys[key] = dict(docname=docname, catalog_entry=catalog_entry) # - super.run() doesnt't kill the structure, it works fine # - returning both superrun and doc_entry does (in any order) # - The todo in the method docstring is rendered outside the # method's documentation (?!) return [doc_entry] #[targetnode, doc_entry]
def run(self): node = nextslide(**self.options) node.args = self.arguments node.document = self.state.document set_source_info(self, node) return [node]
def run(self): r'''Executes the directive. ''' from abjad.tools import abjadbooktools block = abjadbooktools.abjad_reveal_block() block['reveal-label'] = self.arguments[0] set_source_info(self, block) return [block]
def run(self): node = addnodes.only() node.document = self.state.document set_source_info(self, node) node['expr'] = self.arguments[0] self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) return [node]
def run(self): code = '\n'.join(self.content) literal = snippet_with_filename(code, code) if self.arguments: literal['language'] = self.arguments[0] literal['filename'] = self.options['filename'] set_source_info(self, literal) return [literal]
def run(self): ad = make_admonition(UpdateNode, self.name, [_('Updated on')], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) ad[0]['date'] = self.arguments[0] if self.arguments else '' set_source_info(self, ad[0]) return ad
def run(self): oldStdout, sys.stdout = sys.stdout, StringIO() tab_width = self.options.get('tab-width', self.state.document.settings.tab_width) source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1) try: code = '\n'.join(self.content) exec(code) text = sys.stdout.getvalue() except Exception: return [nodes.error(None, nodes.paragraph(text = "Unable to execute python code at %s:%d:" % (basename(source), self.lineno)), nodes.paragraph(text = str(sys.exc_info()[1])))] finally: sys.stdout = oldStdout 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 chevron_code = code.split('\n') chevron_code = [c for c in chevron_code if '#hide' not in c] chevron_code = '\n'.join([''.join(['>> ', line]) for line in chevron_code]) if 'dedent' in self.options: lines = code.split('\n') lines = dedent_lines(lines, self.options['dedent']) code = '\n'.join([lines]) lines = '\n'.join([chevron_code, text]) literal = nodes.literal_block(lines, lines) # literal['language'] = 'python' 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: self.options.setdefault('name', nodes.fully_normalize_name(caption)) literal = container_wrapper(self, literal, caption) self.add_name(literal) return [literal]
def run(self): # type: () -> List[nodes.Node] node = ifconfig() node.document = self.state.document set_source_info(self, node) node['expr'] = self.arguments[0] self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) return [node]
def run(self): node = slides() node.document = self.state.document set_source_info(self, node) node.slides = self.name == "slides" self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) return [node]
def run(self): code = "\n".join(self.content) literal = snippet_with_filename(code, code) if self.arguments: literal["language"] = self.arguments[0] literal["filename"] = self.options["filename"] set_source_info(self, literal) return [literal]
def run(self): cm = self.state.document.settings.env.config.currentmode if cm == self.arguments[0]: node = nodes.Element() node.document = self.state.document set_source_info(self, node) self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) return node.children return []
def run(self): env = self.state.document.settings.env targetid = 'index-%s' % env.new_serialno('index') targetnode = nodes.target('', '', ids=[targetid]) ad = make_admonition(todo_node, self.name, [_('Todo')], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) set_source_info(self, ad[0]) return [targetnode] + ad
def run(self): r'''Executes the directive. ''' from abjad.tools import abjadbooktools path = self.arguments[0] block = abjadbooktools.abjad_import_block() block['path'] = path block['hide'] = 'hide' in self.options set_source_info(self, block) return [block]
def run(self): ad = make_admonition(UpdateNode, self.name, [_('Updated on')], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) #date = datetime.strptime(date, app.config['post_date_format']) ad[0]['date'] = self.arguments[0] if self.arguments else '' set_source_info(self, ad[0]) return ad
def run(self): try: lines = self.parse_lit(self.parse_file(self.arguments[0])) except IOError as exc: document = self.state.document return [document.reporter.warning(str(exc), line=self.lineno)] node = nodes.container() node['classes'] = ['lit-container'] node.document = self.state.document enum = nodes.enumerated_list() enum['classes'] = ['lit-docs'] node.append(enum) # make first list item list_item = nodes.list_item() list_item['classes'] = ['lit-item'] for is_doc, line in lines: if is_doc and line == ['']: continue section = nodes.section() if is_doc: section['classes'] = ['lit-annotation'] nested_parse_with_titles(self.state, ViewList(line), section) else: section['classes'] = ['lit-content'] code = '\n'.join(line) literal = nodes.literal_block(code, code) literal['language'] = 'yaml' set_source_info(self, literal) section.append(literal) list_item.append(section) # If we have a pair of annotation/content items, append the list # item and create a new list item if len(list_item.children) == 2: enum.append(list_item) list_item = nodes.list_item() list_item['classes'] = ['lit-item'] # Non-semantic div for styling bg = nodes.container() bg['classes'] = ['lit-background'] node.append(bg) return [node]
def run(self): # use ordinary docutils nodes for test code: they get special attributes # so that our builder recognizes them, and the other builders are happy. code = '\n'.join(self.content) test = None if self.name == 'doctest': if '<BLANKLINE>' in code: # convert <BLANKLINE>s to ordinary blank lines for presentation test = code code = blankline_re.sub('', code) if doctestopt_re.search(code): if not test: test = code code = doctestopt_re.sub('', code) nodetype = nodes.literal_block if self.name in ('testsetup', 'testcleanup') or 'hide' in self.options: nodetype = nodes.comment if self.arguments: groups = [x.strip() for x in self.arguments[0].split(',')] else: groups = ['default'] node = nodetype(code, code, testnodetype=self.name, groups=groups) set_source_info(self, node) if test is not None: # only save if it differs from code node['test'] = test if self.name == 'testoutput': # don't try to highlight output node['language'] = 'none' node['options'] = {} if self.name in ('doctest', 'testoutput') and 'options' in self.options: # parse doctest-like output comparison flags option_strings = self.options['options'].replace(',', ' ').split() for option in option_strings: if (option[0] not in '+-' or option[1:] not in doctest.OPTIONFLAGS_BY_NAME): # XXX warn? continue flag = doctest.OPTIONFLAGS_BY_NAME[option[1:]] node['options'][flag] = (option[0] == '+') return [node]
def run(self): r'''Executes the directive. ''' from abjad.tools import abjadbooktools self.assert_has_content() code = u'\n'.join(self.content) literal = literal_block(code, code) literal.line = self.content_offset # set the content line number block = abjadbooktools.abjad_input_block(code, literal) # Only set flags if true, for a thinner node repr. if 'allow-exceptions' in self.options: block['allow-exceptions'] = True if 'hide' in self.options: block['hide'] = True if 'no-resize' in self.options: block['no-resize'] = True if 'no-stylesheet' in self.options: block['no-stylesheet'] = True if 'no-trim' in self.options: block['no-trim'] = True if 'strip-prompt' in self.options: block['strip-prompt'] = True if 'with-thumbnail' in self.options: block['with-thumbnail'] = True pages = self.options.get('pages', None) if pages is not None: block['pages'] = self._parse_pages_string(pages) if 'reveal-label' in self.options: block['reveal-label'] = self.options.get('reveal-label') stylesheet = self.options.get('stylesheet', None) if block.get('no-stylesheet'): stylesheet = None if stylesheet: block['stylesheet'] = stylesheet text_width = self.options.get('text-width', None) if text_width is not None: block['text-width'] = text_width with_columns = self.options.get('with-columns', None) if with_columns is not None: block['with-columns'] = with_columns set_source_info(self, block) return [block]
def run(self): latex = '\n'.join(self.content) if self.arguments and self.arguments[0]: latex = self.arguments[0] + '\n\n' + latex node = displaymath() node['latex'] = latex node['number'] = None node['label'] = None if 'name' in self.options: node['label'] = self.options['name'] if 'label' in self.options: node['label'] = self.options['label'] node['nowrap'] = 'nowrap' in self.options node['docname'] = self.state.document.settings.env.docname ret = [node] set_source_info(self, node) if hasattr(self, 'src'): node.source = self.src self.add_target(ret) return ret
def _init(self, name: str, qualified_type_name: str): self._node_id = nodes.make_id(nodes.fully_normalize_name(name)) self._node = ModelElementNode(ids=[self._node_id]) self._parse_msgs = [] self._target = nodes.target() self.state.add_target(self._node_id, '', self._target, self.lineno) ## add node to index name_in_index = 'ModelElement; ' + name target_anchor = self._node_id self._indexnode = addnodes.index() self._indexnode['entries'] = ne = [] self._indexnode['inline'] = False set_source_info(self, self._indexnode) ne.extend(process_index_entry(name_in_index, target_anchor)) self._model_element_type = reflectionutil.model_element_type( qualified_type_name=qualified_type_name, )
def run(self): node = addnodes.versionmodified() node.document = self.state.document set_source_info(self, node) node['type'] = self.name node['version'] = self.arguments[0] if len(self.arguments) == 2: inodes, messages = self.state.inline_text(self.arguments[1], self.lineno + 1) node.extend(inodes) if self.content: self.state.nested_parse(self.content, self.content_offset, node) ret = [node] + messages else: ret = [node] env = self.state.document.settings.env # XXX should record node.source as well env.note_versionchange(node['type'], node['version'], node, node.line) return ret
def run(self): self.assert_has_content() result = [] with TemporaryDirectoryChange(configuration.abjad_directory): cwd = pathlib.Path.cwd() for line in self.content: result.append(f"{cwd.name}$ {line}") completed_process = subprocess.run( line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) result.append(completed_process.stdout) code = "\n".join(result) literal = literal_block(code, code) literal["language"] = "console" set_source_info(self, literal) return [literal]
def run(self): node = PostList() node.document = self.state.document set_source_info(self, node) self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) node['length'] = int(self.arguments[0]) if self.arguments else None node['tags'] = self.options.get('tags', []) node['author'] = self.options.get('author', []) node['category'] = self.options.get('category', []) node['location'] = self.options.get('location', []) node['language'] = self.options.get('language', []) node['format'] = self.options.get('format', '{date} - {title}') node['date'] = self.options.get('date', None) node['sort'] = 'sort' in self.options return [node]
def run(self): latex = '\n'.join(self.content) if self.arguments and self.arguments[0]: latex = self.arguments[0] + '\n\n' + latex node = displaymath() node['latex'] = latex node['label'] = self.options.get('name', None) if node['label'] is None: node['label'] = self.options.get('label', None) node['nowrap'] = 'nowrap' in self.options node['docname'] = self.state.document.settings.env.docname ret = [node] set_source_info(self, node) if hasattr(self, 'src'): node.source = self.src if node['label']: tnode = nodes.target('', '', ids=['equation-' + node['label']]) self.state.document.note_explicit_target(tnode) ret.insert(0, tnode) return ret
def run(self): node = PostNode() node.document = self.state.document set_source_info(self, node) self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) node["date"] = self.arguments[0] if self.arguments else None node["tags"] = self.options.get("tags", []) node["author"] = self.options.get("author", []) node["category"] = self.options.get("category", []) node["location"] = self.options.get("location", []) node["language"] = self.options.get("language", []) node["redirect"] = self.options.get("redirect", []) node["title"] = self.options.get("title", None) node["image"] = self.options.get("image", None) node["excerpt"] = self.options.get("excerpt", None) node["exclude"] = "exclude" in self.options node["nocomments"] = "nocomments" in self.options return [node]
def run(self): node = PostList() node.document = self.state.document set_source_info(self, node) self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) node["length"] = int(self.arguments[0]) if self.arguments else None node["tags"] = self.options.get("tags", []) node["author"] = self.options.get("author", []) node["category"] = self.options.get("category", []) node["location"] = self.options.get("location", []) node["language"] = self.options.get("language", []) node["format"] = self.options.get("format", "{date} - {title}") node["date"] = self.options.get("date", None) node["sort"] = "sort" in self.options node["excerpts"] = "excerpts" in self.options node["image"] = "image" in self.options node["list-style"] = self.options.get("list-style", "none") 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) # 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): filename = self.arguments[0] cwd = os.getcwd() os.chdir(TMPDIR) parts = [] try: code = AsdfFile.read(filename, _get_yaml_content=True) if len(code.strip()): literal = nodes.literal_block(code, code) literal['language'] = 'yaml' set_source_info(self, literal) parts.append(literal) ff = AsdfFile.read(filename) for i, block in enumerate(ff.blocks.internal_blocks): data = block.data.tostring().encode('hex') if len(data) > 40: data = data[:40] + '...' allocated = block._allocated size = block._size flags = block._flags if flags: allocated = 0 size = 0 code = BLOCK_DISPLAY.format(i, flags, allocated, size, data) literal = nodes.literal_block(code, code) literal['language'] = 'yaml' set_source_info(self, literal) parts.append(literal) finally: os.chdir(cwd) result = nodes.admonition() textnodes, messages = self.state.inline_text(filename, self.lineno) title = nodes.title(filename, '', *textnodes) result += title result.children.extend(parts) return [result]
def run(self): code = '\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 literal = nodes.literal_block(code, code) literal['language'] = self.arguments[0] literal['linenos'] = 'linenos' in self.options if hl_lines is not None: literal['highlight_args'] = {'hl_lines': hl_lines} set_source_info(self, literal) return [literal]
def run(self): node = PostNode() node.document = self.state.document set_source_info(self, node) self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) node['date'] = self.arguments[0] if self.arguments else None node['tags'] = self.options.get('tags', []) node['author'] = self.options.get('author', []) node['category'] = self.options.get('category', []) node['location'] = self.options.get('location', []) node['language'] = self.options.get('language', []) node['redirect'] = self.options.get('redirect', []) node['title'] = self.options.get('title', None) node['image'] = self.options.get('image', None) node['excerpt'] = self.options.get('excerpt', None) node['exclude'] = 'exclude' in self.options node['nocomments'] = 'nocomments' in self.options return [node]
def run(self): if self.name in ('slides', 'notslides',): import warnings # these are deprecated, print a warning warnings.warn( "The %s directive has been deprecated; replace with if%s" % ( self.name, self.name, ), stacklevel=2, ) node = if_slides() node.document = self.state.document set_source_info(self, node) node.attributes['ifslides'] = self.name in ('slides', 'ifslides',) self.state.nested_parse(self.content, self.content_offset, node, match_titles=1) return [node]
def process_code_block(self, source: str, docstring: str | None): source_position = self.options.get("source-position", "below") if source_position == "none": return [], [] source = _remove_module_docstring(source, docstring).strip() linenos = self.options.get("linenos", False) code_block = nodes.literal_block(source, source, language="python", linenos=linenos, classes=[]) set_source_info(self, code_block) if source_position == "above": return [code_block], [] if source_position == "below": return [], [code_block]
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) rel_filename, filename = self.env.relfn2path(self.arguments[0]) self.env.note_dependency(rel_filename) reader = CodeIncludeReader(filename, self.options, self.config) text, lines = reader.read(location=location) retnode = nodes.literal_block(text, text, source=filename) set_source_info(self, retnode) if 'language' in self.options: retnode['language'] = self.options['language'] else: for ext, lang in self.auto_language_map.items(): if filename.endswith(ext): retnode['language'] = lang break retnode['classes'] += self.options.get('class', []) if 'caption' in self.options: caption = self.options['caption'] retnode = caption_wrapper(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(text_type(exc), line=self.lineno) ]
def run(self): visual_node = visual(is_figure=False) set_source_info(self, visual_node) set_type_info(self, visual_node) visual_node['docname'], visual_node[ 'visualid'] = self.get_visual_id_info() self.options['name'] = visual_node['visualid'] self.add_name(visual_node) self.emit('visual-node-inited', self, visual_node) caption = self.get_caption() legend, visual_node[ 'content_block'] = self.get_legend_and_visual_content() if caption is not None or legend is not None: visual_node['is_figure'] = True self.emit('visual-caption-and-legend-extracted', self, visual_node, caption, legend) if visual_node['type'] == 'photo': uri = self.get_temp_image_uri() self.run_figure_or_image_with_uri(uri, visual_node, caption, legend) # Replacing image node is not a good option, but we could manipulate uri. # for image_node in visual_node.traverse(condition=nodes.image): # image_node['uri'] = something # By default, assume it doesn't need a placeholder. Later processing can change this. visual_node['placeholder'] = False elif visual_node['type'] == 'video': raise NotImplementedError('Visuals does not support videos yet') else: raise NotImplementedError( 'Visuals does not support link or rich oembed content yet') self.emit('visual-node-generated', self, visual_node) return [visual_node]
def run(self): # type: () -> List[nodes.Node] node = addnodes.versionmodified() node.document = self.state.document set_source_info(self, node) node['type'] = self.name node['version'] = self.arguments[0] text = versionlabels[self.name] % self.arguments[0] if len(self.arguments) == 2: inodes, messages = self.state.inline_text(self.arguments[1], self.lineno + 1) para = nodes.paragraph(self.arguments[1], '', *inodes, translatable=False) set_source_info(self, para) node.append(para) else: messages = [] if self.content: self.state.nested_parse(self.content, self.content_offset, node) if len(node): if isinstance(node[0], nodes.paragraph) and node[0].rawsource: content = nodes.inline(node[0].rawsource, translatable=True) content.source = node[0].source content.line = node[0].line content += node[0].children node[0].replace_self(nodes.paragraph('', '', content, translatable=False)) node[0].insert(0, nodes.inline('', '%s: ' % text, classes=['versionmodified'])) else: para = nodes.paragraph('', '', nodes.inline('', '%s.' % text, classes=['versionmodified']), translatable=False) node.append(para) domain = cast(ChangeSetDomain, self.env.get_domain('changeset')) domain.note_changeset(node) ret = [node] # type: List[nodes.Node] ret += messages return ret
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): env = self.state.document.settings.env targetid = 'index-%s' % env.new_serialno('index') targetnode = nodes.target('', '', ids=[targetid]) if not self.options.get('class'): self.options['class'] = ['panel-group'] text = '\n'.join(self.content) panel = panel_node(text) title_text = self.content[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) panel.title = title_text # panel += nodes.title(title_text, '', *textnodes) # panel += messages panel['classes'] += self.options['class'] del self.content[0] self.state.nested_parse(self.content, self.content_offset + 1, panel) panel = [panel] set_source_info(self, panel[0]) return [targetnode] + panel
def run(self): self.assert_has_content() node = media() node.document = self.state.document set_source_info(self, node) node['classes'] = ['media'] node['classes'] += self.options.get('class', []) if self.arguments: node['classes'] += directives.class_option(self.arguments[0]) self.add_name(node) self.state.nested_parse(self.content, self.content_offset, node) if isinstance(node.children[0], media) and \ 'media-right' in node.children[0]['classes']: # Move media-right to after media-body node.children.append(node.children.pop(0)) return [node]
def run(self): self.assert_has_content() text = '\n'.join(self.content) node = modal(text, **self.options) node.document = self.state.document set_source_info(self, node) node['classes'] += ['modal', 'fade'] node['classes'] += self.options.get('class', []) if self.arguments: node['classes'] += directives.class_option(self.arguments[0]) if 'name' not in self.options: raise self.warning('A modal must have a "name" ' '(to be referenced by).') self.state.nested_parse(self.content, self.content_offset, node) self.add_name(node) return [node]
def run(self): method = self.arguments[0] if '#' in method: method, suffix = method.split('#') suffix = '_' + suffix else: suffix = '' assert re.match('^[a-zA-Z][a-zA-Z0-9_]*$', method) srcdir = self.state.document.settings.env.srcdir with open(os.path.join(srcdir, 'output', method + suffix)) as fd: content = fd.read() if '\n\n' in content: params, result = content.split('\n\n') params = ', '.join(params.split('\n')) else: params, result = '', content out = ">>> ilo.%s(%s)\n%s" % (method, params, result) literal = nodes.literal_block(out, out) literal['language'] = 'python' set_source_info(self, literal) self.state.parent.children[-1].children[-1].append(literal) return []
def run(self): code = textwrap.dedent('\n'.join(self.content)) cwd = os.getcwd() os.chdir(TMPDIR) try: try: exec(code, GLOBALS, LOCALS) except: print(code) raise literal = nodes.literal_block(code, code) literal['language'] = 'python' set_source_info(self, literal) finally: os.chdir(cwd) if 'hidden' not in self.arguments: return [literal] else: return []
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): self.assert_has_content() node = addnodes.only() node.document = self.state.document set_source_info(self, node) node['expr'] = 'iguide' text = '\n'.join(self.content) admonition_node = nodes.admonition(text, **self.options) self.add_name(admonition_node) title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) admonition_node += nodes.title(title_text, '', *textnodes) admonition_node += messages admonition_node['classes'] += ['iguide'] self.state.nested_parse(self.content, self.content_offset, admonition_node) node += admonition_node return [node]
def attach_literal_node(path): from sphinx.directives.code import LiteralIncludeReader from sphinx.util.nodes import set_source_info nonlocal protocol if path.suffix == '.txt': # <literal_block highlight_args="{'linenostart': 1}" # linenos="False" # source="/home/kale/research/projects/201904_bind_dna/notebook/20190604_dnase_pick_qpcr_primers/20190604_pcr.txt" # xml:space="preserve"> # ... # From `sphinx/directives/code.py`: env = self.state.document.settings.env location = self.state_machine.get_source_and_line(self.lineno) rel_filename, filename = env.relfn2path(str(path)) env.note_dependency(rel_filename) reader = LiteralIncludeReader(filename, self.options, env.config) text, lines = reader.read(location=location) literal_node = nodes.literal_block(text, text, source=filename) set_source_info(self, literal_node) protocol += [literal_node] else: from sphinx.roles import specific_docroles protocol += specific_docroles['download']( 'download', rawtext=str(path), text=str(path), lineno=self.lineno, inliner=self.state.inliner, )[0]
def run(self): # type: () -> List[nodes.Node] subnode = addnodes.toctree() subnode['parent'] = self.env.docname # (title, ref) pairs, where ref may be a document, or an external link, # and title may be None if the document's title is to be used subnode['entries'] = [] subnode['includefiles'] = [] subnode['maxdepth'] = self.options.get('maxdepth', -1) subnode['caption'] = self.options.get('caption') subnode['glob'] = 'glob' in self.options subnode['hidden'] = 'hidden' in self.options subnode['includehidden'] = 'includehidden' in self.options subnode['numbered'] = self.options.get('numbered', 0) subnode['titlesonly'] = 'titlesonly' in self.options set_source_info(self, subnode) wrappernode = nodes.compound(classes=['toctree-wrapper']) wrappernode.append(subnode) self.add_name(wrappernode) ret = self.parse_content(subnode) ret.append(wrappernode) return ret
def run(self): node = addnodes.versionmodified() node.document = self.state.document set_source_info(self, node) node['type'] = self.name node['version'] = self.arguments[0] text = versionlabels[self.name] % self.arguments[0] if len(self.arguments) == 2: inodes, messages = self.state.inline_text(self.arguments[1], self.lineno + 1) para = nodes.paragraph(self.arguments[1], '', *inodes) set_source_info(self, para) node.append(para) else: messages = [] if self.content: self.state.nested_parse(self.content, self.content_offset, node) if len(node): if isinstance(node[0], nodes.paragraph) and node[0].rawsource: content = nodes.inline(node[0].rawsource, translatable=True) content.source = node[0].source content.line = node[0].line content += node[0].children node[0].replace_self(nodes.paragraph('', '', content)) node[0].insert( 0, nodes.inline('', '%s: ' % text, classes=['versionmodified'])) else: para = nodes.paragraph( '', '', nodes.inline('', '%s.' % text, classes=['versionmodified'])) node.append(para) env = self.state.document.settings.env # XXX should record node.source as well env.note_versionchange(node['type'], node['version'], node, node.line) return [node] + messages