我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用docutils.nodes.raw()。
def raw_role(role, rawtext, text, lineno, inliner, options={}, content=[]): if not inliner.document.settings.raw_enabled: msg = inliner.reporter.warning('raw (and derived) roles disabled') prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] if 'format' not in options: msg = inliner.reporter.error( 'No format (Writer name) is associated with this role: "%s".\n' 'The "raw" role cannot be used directly.\n' 'Instead, use the "role" directive to create a new role with ' 'an associated format.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] set_classes(options) node = nodes.raw(rawtext, utils.unescape(text, 1), **options) node.source, node.line = inliner.reporter.get_source_and_line(lineno) return [node], []
def issue_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to an issue. Must have `issues_uri` or `issues_github_path` configured in ``conf.py``. Examples: :: :issue:`123` :issue:`42,45` """ options = options or {} content = content or [] issue_nos = [each.strip() for each in utils.unescape(text).split(',')] config = inliner.document.settings.env.app.config ret = [] for i, issue_no in enumerate(issue_nos): node = _make_issue_node(issue_no, config, options=options) ret.append(node) if i != len(issue_nos) - 1: sep = nodes.raw(text=', ', format='html') ret.append(sep) return ret, []
def dispatch_visit(self, node): nodetype = type(node) if issubclass(nodetype, comment): raise SkipNode if issubclass(nodetype, raw): # Some people might put content in raw HTML that should be searched, # so we just amateurishly strip HTML tags and index the remaining # content nodetext = re.sub(r'(?is)<style.*?</style>', '', node.astext()) nodetext = re.sub(r'(?is)<script.*?</script>', '', nodetext) nodetext = re.sub(r'<[^<]+?>', '', nodetext) self.found_words.extend(self.lang.split(nodetext)) raise SkipNode if issubclass(nodetype, Text): self.found_words.extend(self.lang.split(node.astext())) elif issubclass(nodetype, title): self.found_title_words.extend(self.lang.split(node.astext()))
def add_entries_to_gallery(app, doctree, docname): """ Add entries to the gallery node Should happen when all the doctrees have been read and the gallery entries have been collected. i.e at doctree-resolved time. """ if docname != 'gallery': return if not has_gallery(app.builder.name): return # Find gallery node try: node = doctree.traverse(gallery)[0] except TypeError: return content = [] for entry in app.env.gallery_entries: raw_html_node = nodes.raw('', text=entry.html, format='html') content.append(raw_html_node) # Even when content is empty, we want the gallery node replaced node.replace_self(content)
def get_tokens(self, txtnodes): # A generator that yields ``(texttype, nodetext)`` tuples for a list # of "Text" nodes (interface to ``smartquotes.educate_tokens()``). texttype = {True: 'literal', # "literal" text is not changed: False: 'plain'} for txtnode in txtnodes: nodetype = texttype[isinstance(txtnode.parent, (nodes.literal, nodes.math, nodes.image, nodes.raw, nodes.problematic))] yield (nodetype, txtnode.astext())
def run(self): self.options['run_id'] = directives.uri(self.arguments[0]) if not self.options.get('key'): self.options['key'] = self.default_key if not self.options.get('width'): self.options['width'] = self.default_width if not self.options.get('height'): self.options['height'] = self.default_height if not self.options.get('align'): self.options['align'] = 'left' self.options['timestamp'] = '1459857519' node = nodes.raw('', self.html % self.options, format='html') node.rawsource = self._get_raw_source() return [node]
def run(self): self.options['video_id'] = directives.uri(self.arguments[0]) if not self.options.get('width'): self.options['width'] = self.default_width if not self.options.get('height'): self.options['height'] = self.default_height if not self.options.get('align'): self.options['align'] = 'left' node = nodes.raw('', self.html % self.options, format='html') node.rawsource = self._get_raw_source() return [node]
def pygments_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): try: lexer = get_lexer_by_name(arguments[0]) except ValueError: # no lexer found - use the text one instead of an exception lexer = TextLexer() # take an arbitrary option if more than one is given formatter = options and VARIANTS[options.keys()[0]] or DEFAULT parsed = highlight(u'\n'.join(content), lexer, formatter) parsed = '<div class="codeblock">%s</div>' % parsed return [nodes.raw('', parsed, format='html')]
def doctree_resolved(app, doctree, docname): i = 1 figids = {} for figure_info in doctree.traverse(figure): if app.builder.name != 'latex' and app.config.number_figures: for cap in figure_info.traverse(caption): cap[0] = Text("%s %d: %s" % (app.config.figure_caption_prefix, i, cap[0])) for id in figure_info['ids']: figids[id] = i i += 1 # replace numfig nodes with links if app.builder.name != 'latex': for ref_info in doctree.traverse(num_ref): if '#' in ref_info['reftarget']: label, target = ref_info['reftarget'].split('#') labelfmt = label + " %d" else: labelfmt = '%d' target = ref_info['reftarget'] if target not in figids: continue if app.builder.name == 'html': target_doc = app.builder.env.figid_docname_map[target] link = "%s#%s" % (app.builder.get_relative_uri(docname, target_doc), target) html = '<a class="pageref" href="%s">Fig. %s</a>' % (link, labelfmt %(figids[target])) ref_info.replace_self(raw(html, html, format='html')) else: ref_info.replace_self(Text(labelfmt % (figids[target])))
def doctree_resolved(app, doctree, docname): i = 1 figids = {} for figure_info in doctree.traverse(figure): if app.builder.name != 'latex' and app.config.number_figures: for cap in figure_info.traverse(caption): cap[0] = Text("%s %d: %s" % (app.config.figure_caption_prefix, i, cap[0])) for id in figure_info['ids']: figids[id] = i i += 1 # replace numfig nodes with links if app.builder.name != 'latex': for ref_info in doctree.traverse(num_ref): if '#' in ref_info['reftarget']: label, target = ref_info['reftarget'].split('#') labelfmt = label + " %d" else: labelfmt = '%d' target = ref_info['reftarget'] if target not in figids: continue if app.builder.name == 'html': target_doc = app.builder.env.figid_docname_map[target] link = "%s#%s" % (app.builder.get_relative_uri(docname, target_doc), target) html = '<a class="pageref" href="%s">%s</a>' % (link, labelfmt %(figids[target])) ref_info.replace_self(raw(html, html, format='html')) else: ref_info.replace_self(Text(labelfmt % (figids[target])))
def run(self): cwd = os.getcwd() tmpdir = tempfile.mkdtemp() os.chdir(tmpdir) rst_file = self.state_machine.document.attributes['source'] rst_dir = os.path.abspath(os.path.dirname(rst_file)) image_dir, image_rel_dir = make_image_dir(setup, rst_dir) # Construct script from cell content content = "\n".join(self.content) with open("temp.py", "w") as f: f.write(content) # Use sphinx logger? uid = uuid.uuid4().hex[:8] print("") print(">> Contents of the script: %s" % uid) print(content) print("") start = time.time() subprocess.call(['python', 'temp.py']) print(">> The execution of the script %s took %f s" % (uid, time.time() - start)) text = '' for im in sorted(glob.glob("*.png")): text += get_image_tag(im, image_dir, image_rel_dir) code = content literal = nodes.literal_block(code, code) literal['language'] = 'python' attributes = {'format': 'html'} img_node = nodes.raw('', text, **attributes) # clean up os.chdir(cwd) shutil.rmtree(tmpdir, True) return [literal, img_node]