def run(self): env = self.state.document.settings.env try: if 'header' in self.options: header = self.options['header'] else: raise ValueError('header not found') if 'link' in self.options: link = directives.uri(self.options['link']) else: raise ValueError('link not found') if 'image' in self.options: image = directives.uri(self.options['image']) else: image = os.path.join(os.path.relpath(env.app.srcdir, env.app.confdir), '../img/thumbnails/nni_icon_white.png') image_background = self.options.get('background', 'indigo') description = self.options.get('description', '') tags = self.options.get('tags', '').strip().split('/') tags = [t.strip() for t in tags if t.strip()] except ValueError as e: print(e) raise if tags: tags_rst = TAGS_TEMPLATE.format(tags=''.join([TAG_TEMPLATE.format(tag=tag) for tag in tags])) else: tags_rst = '' card_rst = CARD_HEADER.format( header=header, image=image, image_background=image_background, link=link, description=description, tags=tags_rst) card = nodes.paragraph() self.state.nested_parse(StringList(card_rst.split('\n')), self.content_offset, card) # This needs to corporate with javascript: propagate_card_link. # because sphinx can't correctly handle image in a `pending_xref` after `keepformat`. link_node = pending_xref('<a/>', reftype='doc', refdomain='std', reftarget=link, refexplicit=False, refwarn=True) link_node += nodes.paragraph(header) link_node['classes'] = ['card-link-anchor'] card += link_node self.state.nested_parse(StringList(CARD_FOOTER.split('\n')), self.content_offset, card) return [card]
def run(self): autoplay = None controls = "controls" loop = None muted = "muted" poster = None preload = None cl = None if "autoplay" in self.options: autoplay = yes_no("autoplay", self.options["autoplay"]) if "controls" in self.options: controls = yes_no("controls", self.options["controls"]) if "loop" in self.options: loop = yes_no("loop", self.options["loop"]) if "muted" in self.options: muted = yes_no("muted", self.options["muted"]) if "poster" in self.options: poster = directives.uri(self.options["poster"]) if "preload" in self.options: preload = preload_choice(self.options["preload"]) if "class" in self.options: cl = self.options["class"] uri = directives.uri(self.arguments[0]) source_dir = os.path.dirname( os.path.abspath(self.state.document.current_source)) vid = video_node(uri=uri, source_dir=source_dir, autoplay=autoplay, controls=controls, loop=loop, muted=muted, poster=poster, preload=preload, cl=cl) self.state.nested_parse(self.content, self.content_offset, vid) return [vid]
def run(self): env = self.state.document.settings.env if 'width' not in self.options: self.options['width'] = env.config.swf_width_default if 'height' not in self.options: self.options['height'] = env.config.swf_height_default if 'zoom-to-fit' not in self.options: self.options['zoom-to-fit'] = env.config.swf_zoom_to_fit_default if 'allowfullscreen' not in self.options and \ 'allowFullScreen' not in self.options: self.options['allowfullscreen'] = env.config.swf_allowfullscreen_default for opt in self.options: typ = self.option_spec[opt] if typ is bool_option: if self.options[opt].lower() in ('yes', 'true', '1'): self.options[opt] = True else: self.options[opt] = False if 'allowfullscreen' in self.options: self.options['allowFullScreen'] = self.options['allowfullscreen'] del self.options['allowfullscreen'] if 'fullscreenaspectratio' in self.options: self.options['fullScreenAspecRatio'] = \ self.options['fullscreenaspecratio'] del self.options['fullscreenaspecratio'] reference = directives.uri(self.arguments[0]) self.options['uri'] = reference env.config.swf_flash_files.append(reference) return [ swf(rawsource=self.block_text, **self.options) ]
def run(self): audio_url = directives.uri(self.arguments[0]) alt = self.options.get('alt', None) alt = ' "{alt}"'.format(alt=alt) if alt else '' html = '<audio src="{audio_url}" preload="none"{alt} controls></audio>'.format( audio_url=audio_url, alt=alt) return [nodes.raw('', html, format='html')]
def run(self): env = self.state.document.settings.env src_dir = env.srcdir uml_dir = os.path.join(src_dir, self.DIR_NAME) if os.path.basename(uml_dir) not in os.listdir(src_dir): os.mkdir(uml_dir) env.uml_dir = uml_dir module_path = self.arguments[0] os.chdir(uml_dir) basename = os.path.basename(module_path).split(".")[0] print call(['pyreverse', '-o', 'png', '-p', basename, os.path.abspath(os.path.join(src_dir, module_path))]) uri = directives.uri(os.path.join(self.DIR_NAME, "classes_{0}.png".format(basename))) scale = 100 max_width = 1000 if IMAGE: i = IMAGE.open(os.path.join(src_dir, uri)) image_width = i.size[0] if image_width > max_width: scale = max_width * scale / image_width img = nodes.image(uri=uri, scale=scale) os.chdir(src_dir) return [img]
def run(self): document = self.state.document env = document.settings.env raw_path = directives.uri(self.arguments[0]) rel_filename, filename = env.relfn2path(raw_path) basename = os.path.basename(filename) dirname = os.path.dirname(filename) save_filename = os.path.join('_videos', basename) env.note_dependency(rel_filename) env.config.video_files.append({ 'source': rel_filename, 'target': save_filename, }) self.options['path'] = os.path.relpath( save_filename, os.path.dirname(env.docname) ) # TODO: For some weird reason, the output folder # /_static/videos is created, and I can't figure # out why. Probably a case for a rainy afternoon return [nodes.raw('', self.html.format(**self.options), format='html')]
def run(self): """ process the video directive and generate html for output. :param self: :return: """ super(Video, self).run() addQuestionToDB(self) mimeMap = {'mov':'mp4','webm':'webm', 'm4v':'m4v'} sources = [SOURCE % (directives.uri(line),mimeMap[line[line.rindex(".")+1:]]) for line in self.content] if 'controls' in self.options: self.options['controls'] = 'controls' if 'loop' in self.options: self.options['loop'] = 'loop' else: self.options['loop'] = '' if 'preload' in self.options: self.options['preload'] = 'preload="auto"' else: self.options['preload'] = 'preload="none"' self.options['sources'] = "\n ".join(sources) res = CODE % self.options if 'popup' in self.options: res += POPUP % self.options else: res += INLINE % self.options addHTMLToDB(self.options['divid'], self.options['basecourse'], res) return [nodes.raw(self.block_text, res, format='html')]
def run(self): node = nodes.Element() node.document = self.state.document jinja_context_name = self.arguments[0] template_filename = self.options.get("file") cxt = self.app.config.jinja_contexts[jinja_context_name] cxt["options"] = { "header_char": self.options.get("header_char") } if template_filename: reference_uri = directives.uri(template_filename) template_path = urllib.url2pathname(reference_uri) encoded_path = template_path.encode(sys.getfilesystemencoding()) imagerealpath = os.path.abspath(encoded_path) with open(imagerealpath) as f: tpl = Template(f.read()) else: tpl = Template("\n".join(self.content)) new_content = tpl.render(**cxt) # transform the text content into a string_list that the nested_parse # can use: new_content = StringList(new_content.split("\n")) self.state.nested_parse(new_content, self.content_offset, node, match_titles=1) return node.children
def run(self): reference = directives.uri(self.arguments[0]) if 'gallery/' in reference: reference = reference.split('gallery/')[1] parts = reference.split('/') gallery_id = parts[0] photo_id = parts[2] if '#' in photo_id: photo_id = photo_id.split('#')[0] image_url = '%s/photos/%s-M.jpg' % (SMUGMUG, photo_id) lightbox = '%s/gallery/%s/1/#%s-A-LB' % ( SMUGMUG, gallery_id, photo_id) else: # New style if 'A-LB' in reference: lightbox = reference photo_id = reference.split('#')[1] photo_id = photo_id.replace('-A-LB', '') else: lightbox = reference + '-A-LB' photo_id = reference.split('/')[-1] image_url = '%s/photos/%s-M.jpg' % (SMUGMUG, photo_id) self.options['uri'] = image_url image_node = nodes.image(rawsource=self.block_text, **self.options) reference_node = nodes.reference(refuri=lightbox) reference_node += image_node return [reference_node]
def run(self): """Run the thumbnail directive.""" uri = directives.uri(self.arguments[0]) if uri.endswith('.svg'): # the ? at the end makes docutil output an <img> instead of an object for the svg, which colorbox requires self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri)) + '?' else: self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri)) self.options['target'] = uri with Image2.open('.' + uri) as im: ow, oh = im.size attrs = {'data-orig-width': str(ow), 'data-orig-height': str(oh), 'data-target': uri} (orig_node,) = Image.run(self) html_doc = docutils.utils.new_document("") html_doc.append(orig_node) html_root = parseString(docutils.core.publish_from_doctree(html_doc, writer_name='html').decode()) html_node = html_root.getElementsByTagName("img")[0] for key, val in attrs.items(): html_node.setAttribute(key, val) html_node.setAttribute('class', "{0} simpic".format(html_node.getAttribute('class'))) raw_html = html_node.toxml() node = docutils.nodes.raw('', raw_html, format='html') return [node]
def run(self): if 'align' in self.options: if isinstance(self.state, states.SubstitutionDef): # Check for align_v_values. if self.options['align'] not in self.align_v_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value ' 'for the "align" option within a substitution ' 'definition. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_v_values))) elif self.options['align'] not in self.align_h_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_h_values))) messages = [] reference = directives.uri(self.arguments[0]) self.options['uri'] = reference reference_node = None if 'target' in self.options: block = states.escape2null( self.options['target']).splitlines() block = [line for line in block] target_type, data = self.state.parse_target( block, self.block_text, self.lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference( refname=fully_normalize_name(data), name=whitespace_normalize_name(data)) reference_node.indirect_reference_name = data self.state.document.note_refname(reference_node) else: # malformed target messages.append(data) # data is a system message del self.options['target'] image_node = nodes.image(self.block_text, **self.options) if 'iconmargin' in self.options: image_node['classes'].append('iconmargin') set_classes(self.options) if 'iconmarginheight' in self.options: image_node['iconmarginheight'] = \ int(self.options['iconmarginheight']) if 'iconmarginraise' in self.options: image_node['iconmarginraise'] = True if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node]
def uri_check(self, arg): # If the first option doesn't have a space between ":key:" and "value" # docutils treats it as an argument. It can be very difficult to # debug... try: _emptystr, key, _emptystr, value = re.split( r"^\:(.*?)\:(.*?)", arg) if key in self.option_spec and key not in self.options: self.options[key] = value self.state_machine.reporter.error( '\nError parsing the "%s" directive: \n' 'A space is required between :%s: and its value \n' 'Assuming you meant ":%s: %s" \n' 'instead of "%s" \n' % (self.name, key, key, value, arg), nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return None except: pass arg = directives.uri(arg.strip().rstrip(',')) # set crossorigin to anonymous for external resources unless otherwise specified if urlparse(arg).scheme in ('http', 'https'): if 'crossorigin' not in self.options and self.crossorigin: self.options['crossorigin'] = 'anonymous' else: # convert windows path to unix path arg = pathname2url(arg) return arg
def run(self): """ process the video directive and generate html for output. :param self: :return: """ mimeMap = {'mov':'mp4','webm':'webm', 'm4v':'m4v'} sources = [SOURCE % (directives.uri(line),mimeMap[line[line.rindex(".")+1:]]) for line in self.content] self.options['divid'] = self.arguments[0] if 'controls' in self.options: self.options['controls'] = 'controls' if 'loop' in self.options: self.options['loop'] = 'loop' else: self.options['loop'] = '' if 'preload' in self.options: self.options['preload'] = 'preload="auto"' else: self.options['preload'] = 'preload="none"' self.options['sources'] = "\n ".join(sources) res = CODE % self.options if 'popup' in self.options: res += POPUP % self.options else: res += INLINE % self.options return [nodes.raw('',res , format='html')]
def run(self): """ process the video directive and generate html for output. :param self: :return: """ mimeMap = {"mov": "mp4", "webm": "webm", "m4v": "m4v"} sources = [SOURCE % (directives.uri(line), mimeMap[line[line.rindex(".") + 1 :]]) for line in self.content] self.options["divid"] = self.arguments[0] if "controls" in self.options: self.options["controls"] = "controls" if "loop" in self.options: self.options["loop"] = "loop" else: self.options["loop"] = "" if "preload" in self.options: self.options["preload"] = 'preload="auto"' else: self.options["preload"] = 'preload="none"' self.options["sources"] = "\n ".join(sources) res = CODE % self.options if "popup" in self.options: res += POPUP % self.options else: res += INLINE % self.options return [nodes.raw("", res, format="html")]
def run(self): """Perform task associated with this directive.""" env = self.state.document.settings.env wkf_file = directives.uri(self.arguments[0]) if not os.path.isabs(wkf_file): wkf_file = os.path.join(os.path.dirname(env.doc2path(env.docname)), wkf_file) wkf_name = os.path.splitext(wkf_file)[0] svg_file = "%s.svg" % wkf_name if out_of_date(wkf_file, svg_file): # render the workflow again with open(wkf_file, 'r') as f: wkf = json.load(f) w = self.options.get('width', 600) h = self.options.get('height', 600) drawing, bb = svg.export_workflow(wkf, {}, (w, h)) del bb with open(svg_file, 'w') as f: f.write(drawing) self.options['uri'] = svg_file node = nodes.image(**self.options) return [node]
def run(arguments, options, state_machine, lineno): reference = directives.uri(arguments[0]) basedir, fname = os.path.split(reference) basename, ext = os.path.splitext(fname) # todo - should we be using the _static dir for the outdir, I am # not sure we want to corrupt that dir with autogenerated files # since it also has permanent files in it which makes it difficult # to clean (save an rm -rf followed by and svn up) srcdir = 'pyplots' makefig(os.path.join(srcdir, reference), srcdir) # todo: it is not great design to assume the makefile is putting # the figs into the right place, so we may want to do that here instead. if options.has_key('include-source'): lines = ['.. literalinclude:: ../pyplots/%(reference)s' % locals()] del options['include-source'] else: lines = [] options = [' :%s: %s' % (key, val) for key, val in options.items()] options = "\n".join(options) lines.extend((template % locals()).split('\n')) state_machine.insert_input( lines, state_machine.input_lines.source(0)) return []
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 return [nodes.raw('', self.html % self.options, format='html')]
def process_doc(self, app: Sphinx, doctree: nodes.document) -> None: docname = app.env.docname static_paths = app.builder.config['html_static_path'] for node in doctree.traverse(RevealjsNode): elm = getattr(node, 'revealit_el', None) if isinstance(elm, RjsElement): for img_uri in elm.get_image_uris(): uri = directives.uri(img_uri) if uri.find('://') != -1 or any( uri.startswith(p) for p in static_paths): continue # Update imgpath to a relative path from srcdir # from a relative path from current document. imgpath, _ = app.env.relfn2path(uri, docname) app.env.dependencies[docname].add(imgpath) if not os.access(os.path.join(app.srcdir, imgpath), os.R_OK): logger.warning(__('image file not readable: %s') % imgpath, type='image', location=node, subtype='not_readable') continue app.env.images.add_file(docname, imgpath) elm.images[img_uri] = imgpath
def run(self): env = self.state.document.settings.env src_dir = env.srcdir uml_dir = os.path.join(src_dir, self.DIR_NAME) if os.path.basename(uml_dir) not in os.listdir(src_dir): os.mkdir(uml_dir) env.uml_dir = uml_dir module_path = self.arguments[0] os.chdir(uml_dir) basename = os.path.basename(module_path).split(".")[0] print call([ 'pyreverse', '-o', 'png', '-p', basename, os.path.abspath(os.path.join(src_dir, module_path)) ]) uri = directives.uri( os.path.join(self.DIR_NAME, "classes_{0}.png".format(basename))) scale = 100 max_width = 1000 if IMAGE: i = IMAGE.open(os.path.join(src_dir, uri)) image_width = i.size[0] if image_width > max_width: scale = max_width * scale / image_width img = nodes.image(uri=uri, scale=scale) os.chdir(src_dir) return [img]
def plot_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Handle the arguments to the plot directive. The real work happens in _plot_directive. """ # The user may provide a filename *or* Python code content, but not both if len(arguments): plot_path = directives.uri(arguments[0]) basedir = relpath(os.path.dirname(plot_path), setup.app.builder.srcdir) # If there is content, it will be passed as a caption. # Indent to match expansion below. XXX - The number of spaces matches # that of the 'options' expansion further down. This should be moved # to common code to prevent them from diverging accidentally. caption = '\n'.join(content) # If the optional function name is provided, use it if len(arguments) == 2: function_name = arguments[1] else: function_name = None return _plot_directive(plot_path, basedir, function_name, None, caption, options, state_machine) else: plot_code = '\n'.join(content) # Since we don't have a filename, use a hash based on the content plot_path = md5(plot_code).hexdigest()[-10:] return _plot_directive(plot_path, 'inline', None, plot_code, '', options, state_machine)
def run(self): """ process the video directive and generate html for output. :param self: :return: """ mimeMap = {'mov': 'mp4', 'webm': 'webm', 'm4v': 'm4v'} sources = [ SOURCE % (directives.uri(line), mimeMap[line[line.rindex(".") + 1:]]) for line in self.content ] self.options['divid'] = self.arguments[0] if 'controls' in self.options: self.options['controls'] = 'controls' if 'loop' in self.options: self.options['loop'] = 'loop' else: self.options['loop'] = '' if 'preload' in self.options: self.options['preload'] = 'preload="auto"' else: self.options['preload'] = 'preload="none"' self.options['sources'] = "\n ".join(sources) res = CODE % self.options if 'popup' in self.options: res += POPUP % self.options else: res += INLINE % self.options return [nodes.raw('', res, format='html')]
def run(self): #print "blocktext:", self.block_text #print "options:", self.options #print "args:", self.arguments #print "attributes:", self.state_machine.document.attributes thisfile = self.state_machine.document.attributes['source'] #print "dir:", dir(self) #print "setup:", setup.config, dir(setup.config) #print setup.app.builder, "\n" #pprint(setup.app.srcdir) rp = os.path.relpath(thisfile, setup.app.srcdir) (h,t) = os.path.split(rp) srcscript = os.path.join(setup.app.srcdir, h, self.arguments[0]) copyto_dir = os.path.join(setup.app.outdir, h) if (not os.path.isdir(copyto_dir)): os.makedirs(copyto_dir) shutil.copyfile(srcscript, os.path.join(copyto_dir, self.arguments[0])) #self.state_machine.insert_input(["HEE", "HEE"], self.state_machine.input_lines.source(0)) reference = directives.uri(self.arguments[0]) self.options['refuri'] = reference refnode = nodes.reference(text=self.arguments[0], **self.options) iline = nodes.inline() iline += [refnode] return [iline]
def run(arguments, options, lineno, content, state_machine = None, document = None, srcdir = None, builddir = None ): """process :report: directive. *srdir* - top level directory of rst documents *builddir* - build directory """ tag = "%s:%i" % (str(document), lineno) logging.debug( "report_directive.run: profile: started: rst: %s" % tag ) # sort out the paths # reference is used for time-stamping reference = directives.uri(arguments[0]) basedir, fname, basename, ext, outdir, codename = buildPaths( reference ) # get the directory of the rst file rstdir, rstfile = os.path.split( document ) # state_machine.document.attributes['source']) # root of document tree if not srcdir: srcdir = setup.srcdir # build directory if not builddir: builddir = setup.confdir # path to root relative to rst rst2srcdir = os.path.join( os.path.relpath( srcdir, start = rstdir ), outdir ) # path to root relative to rst rst2builddir = os.path.join( os.path.relpath( builddir, start = rstdir ), outdir ) # path relative to source (for images) root2builddir = os.path.join( os.path.relpath( builddir, start = srcdir ), outdir ) logging.debug( "report_directive.run: arguments=%s, options=%s, lineno=%s, content=%s, document=%s" % (str(arguments), str(options), str(lineno), str(content), str(document))) logging.debug( "report_directive.run: plotdir=%s, basename=%s, ext=%s, fname=%s, rstdir=%s, srcdir=%s, builddir=%s" %\ (reference, basename, ext, fname, rstdir, srcdir, builddir ) ) logging.debug( "report_directive.run: reference=%s, basedir=%s, rst2src=%s, root2build=%s, outdir=%s, codename=%s" %\ (reference, basedir, rst2srcdir, rst2builddir, outdir, codename)) # try to create. If several processes try to create it, # testing with `if` will not work. try: os.makedirs(outdir) except OSError, msg: pass
class AafigTransform(transforms.Transform): default_priority = 500 # TODO def apply(self): current_node = self.startnode details = current_node.details image_node = details['image_node'] options = details['aafigure_options'].copy() text = current_node.rawsource #merge_defaults(options, self) # XXX: this is an ugly hack to find out the writer being used print('>>>>>>>>>>>>>>>>>>>>>', self.document.transformer.components) if hasattr(self.document.settings, 'stylesheet_path'): # HTML options['format'] = 'png' else: # LaTeX options['format'] = 'pdf' options['format'] = 'png' try: #TODO: options['format'] = self.builder.config.aafig_format['html'] fname, outfn, id, extra = render_aafigure(self, text, options) except AafigError, exc: #TODO: self.builder.warn('aafigure error: ' + str(exc)) current_node.replace_self([]) # TODO: ascii art image_node['uri'] = directives.uri(fname) # TODO: improve image_node['alt'] current_node.replace_self(image_node)
def run(self): text = "" for c in self.content: text += c + "<br />" text = re.sub(r"\`\`(.+?)\`\`", r'<tt class="literal">\1</tt>', text) text_title = "<p class='first admonition-title'><i class=\"far fa-question-circle\"></i>Exercise</p>" text_str = text img_str = "" if 'image' in self.options: reference = directives.uri(self.options['image']) img_class = 'fluid' img_str = '<img src="{}" class="{}">'.format(reference, img_class) div_raw = '<div class="admonition exercise"> ' \ ' {}' \ ' <p>{}</p>' \ ' <p>{}</p>' \ '</div>'.format(text_title, text_str, img_str) return [ nodes.raw('', div_raw, format='html'), ]
def run(self): # Needed to get access to options global options # Reference is the link to the svg file # Adds reference to the options list reference = directives.uri(self.arguments[0]) self.options['uri'] = reference options.append(self.options['uri']) # Creates the svg class html_node = None if isLatex == False: html_node = gliffy() # Adds html class "gliffy_img" to all nodes created from now on self.options['classes'] = ['gliffy_img'] # Creates an img version of the svg # Necessary to pass X Frame Options denial # Image is not visible in browser, hidden by gliffy_img class html_node += nodes.image(rawsource=self.options['uri'], **self.options) else: # This should insert the svg into the pdf but it does nothing uri = self.options['uri'] uri = uri[:3] + "png" print("image uri is: " + uri) html_node = nodes.image(rawsource="test-svg.png", **self.options) self.add_name(html_node) return [html_node]
def run(self): node = nodes.Element() node.document = self.state.document jinja_context_name = self.arguments[0] template_filename = self.options.get("file") cxt = self.app.config.jinja_contexts[jinja_context_name] cxt["options"] = {"header_char": self.options.get("header_char")} if template_filename: reference_uri = directives.uri(template_filename) template_path = urllib.url2pathname(reference_uri) encoded_path = template_path.encode(sys.getfilesystemencoding()) imagerealpath = os.path.abspath(encoded_path) with open(imagerealpath) as f: tpl = Template(f.read()) else: tpl = Template("\n".join(self.content)) new_content = tpl.render(**cxt) # transform the text content into a string_list that the nested_parse # can use: new_content = StringList(new_content.split("\n")) self.state.nested_parse(new_content, self.content_offset, node, match_titles=1) return node.children
def get_paths(self, img_name, module_name, base_dir, src_dir, config): path_from_base = os.path.join(self.DIR_NAME, "{1}_{0}.{2}").format( module_name, img_name, config.sphinx_pyreverse_output) # use relpath to get sub-directory of the main 'source' location src_base = os.path.relpath(base_dir, start=src_dir) uri = directives.uri(os.path.join(src_base, path_from_base)) output_file = os.path.join(base_dir, path_from_base) return (uri, output_file)
def run(self): """ Image.run() handles most of the """ result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options["uri"] = data_uri_from_file(reference) return result
def run(self): """ Image.run() handles most of the """ result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri(reference)[0] return result
def run(self): self.uri = directives.uri(self.arguments[0]) self.document = self.state_machine.document self.process_parameters() self.compute_image() return directives.images.Image.run(self)
def run(arguments, options, state_machine, lineno): reference = directives.uri(arguments[0]) basedir, fname = os.path.split(reference) basename, ext = os.path.splitext(fname) if ext != '.py': basename = fname sourcename = fname #print 'plotdir', reference, basename, ext # get the directory of the rst file rstdir, rstfile = os.path.split(state_machine.document.attributes['source']) reldir = rstdir[len(setup.confdir)+1:] relparts = [p for p in os.path.split(reldir) if p.strip()] nparts = len(relparts) #print ' rstdir=%s, reldir=%s, relparts=%s, nparts=%d'%(rstdir, reldir, relparts, nparts) #print 'RUN', rstdir, reldir outdir = os.path.join(setup.confdir, setup.config.plot_output_dir, basedir) if not os.path.exists(outdir): cbook.mkdirs(outdir) linkdir = ('../' * nparts) + setup.config.plot_output_dir.replace(os.path.sep, '/') + '/' + basedir #linkdir = os.path.join('..', outdir) num_figs = makefig(reference, outdir, is_doctest=('doctest-format' in options)) #print ' reference="%s", basedir="%s", linkdir="%s", outdir="%s"'%(reference, basedir, linkdir, outdir) if options.has_key('include-source'): contents = open(reference, 'r').read() if 'doctest-format' in options: lines = [''] else: lines = ['.. code-block:: python', ''] lines += [' %s'%row.rstrip() for row in contents.split('\n')] del options['include-source'] else: lines = [] if 'doctest-format' in options: del options['doctest-format'] if num_figs > 0: options = [' :%s: %s' % (key, val) for key, val in options.items()] options = "\n".join(options) for i in range(num_figs): if num_figs == 1: outname = basename else: outname = "%s_%02d" % (basename, i) lines.extend((template % locals()).split('\n')) else: lines.extend((exception_template % locals()).split('\n')) if len(lines): state_machine.insert_input( lines, state_machine.input_lines.source(0)) return []
def run(self): """Process a new figure.""" #farfle = open('/tmp/farfle', 'a') env = self.state.document.settings.env reference = directives.uri(self.arguments[0]) if not os.path.isabs(reference): # A relative path means we should search for the image # Find the builder-specific path-list to search: bname = env.app.builder.name if bname in sphinx.builders.BUILTIN_BUILDERS: bname = sphinx.builders.BUILTIN_BUILDERS[bname][0] # Get a simplified name (htmlhelp->html, etc) if bname in env.app.config.findfigure_paths: searchdirs = env.app.config.findfigure_paths[bname] elif '*' in env.app.config.findfigure_paths: searchdirs = env.app.config.findfigure_paths['*'] else: searchdirs = (os.path.abspath('.'),) if reference.endswith('.*'): # Find the builder-specific list of extensions to try base, dummy = os.path.splitext(reference) if bname in env.app.config.findfigure_types: searchexts = env.app.config.findfigure_types[bname] elif '*' in env.app.config.findfigure_types: searchexts = env.app.config.findfigure_types['*'] else: searchexts = ('.svg', '.pdf', '.png', '.jpeg', '.jpg', '.tiff', '.tif', '.gif') else: base = reference searchexts = ('',) # Now try finding the figure. foundit = False aref = base for ext in searchexts: for path in searchdirs: try: aref = os.path.join(path, base) + ext #print ' TRY <%s>' % aref status = os.stat(aref) # Could check status bits here. foundit = True break except: foundit = False if foundit: break #print >>farfle, "Reference is %s aref %s found %s" % (self.arguments, aref, foundit) if not foundit: #print 'MISSING FILE %s' % reference return [] #print 'RESOLVED %s to %s' % (reference, aref) rewr = os.path.relpath(aref, os.path.join(env.srcdir, os.path.dirname(env.docname))) # NB: We must rewrite path relative to source directory # because otherwise the output stage will be unable # to find it. #print 'REWROTE %s to %s rel %s' % (aref, rewr, os.path.abspath(os.path.dirname(env.docname))) self.arguments[0] = rewr #farfle.close() return Figure.run(self)
def run(self): anchor_node = nodes.paragraph() try: title = self.options['title'] link = directives.uri(self.options['link']) icon = directives.uri(self.options['icon']) seemore = self.options.get('seemore', 'For a full tutorial, please go here.') except ValueError as e: print(e) raise # header, title, icon... card_rst = CARD_TEMPLATE_HEADER.format(title=title, icon=icon) card_list = StringList(card_rst.split('\n')) self.state.nested_parse(card_list, self.content_offset, anchor_node) # code snippet self.state.nested_parse(self.content, self.content_offset, anchor_node) # close body self.state.nested_parse(StringList(CARD_TEMPLATE_FOOTER.split('\n')), self.content_offset, anchor_node) # start footer self.state.nested_parse(StringList(CARD_TEMPLATE_LINK_CONTAINER_HEADER.split('\n')), self.content_offset, anchor_node) # full tutorial link link_node = pending_xref(CARD_TEMPLATE_LINK, reftype='doc', refdomain='std', reftarget=link, refexplicit=False, refwarn=True, refkeepformat=True) # refkeepformat is handled in `patch_autodoc.py` self.state.nested_parse(StringList(CARD_TEMPLATE_LINK.format(seemore=seemore).split('\n')), self.content_offset, link_node) anchor_node += link_node # close footer self.state.nested_parse(StringList(CARD_TEMPLATE_FOOTER.split('\n')), self.content_offset, anchor_node) # close whole self.state.nested_parse(StringList(CARD_TEMPLATE_FOOTER.split('\n')), self.content_offset, anchor_node) return [anchor_node]
def run(self): args = self.arguments imagenm = args[0] options = self.options hidpiimagenm = options.pop('hidpi', None) document = self.state_machine.document source_file_name = os.path.join(setup.app.builder.srcdir, directives.uri(args[0])) current_dir = os.path.dirname(self.state.document.current_source) # where will the html file go... source_rel_name = relpath(document.attributes['source'], setup.app.confdir) source_rel_dir = os.path.dirname(source_rel_name) dest_dir = os.path.abspath( os.path.join(self.app.builder.outdir, source_rel_dir)) # where will the images go... image_dir = os.path.abspath( os.path.join(self.app.builder.outdir, '_images')) if not os.path.exists(image_dir): os.makedirs(image_dir) # get relative path between images and where the html will be: image_rel = relpath(image_dir, dest_dir) # Copy image files: for fn in [imagenm, hidpiimagenm]: if fn is not None: base = os.path.basename(fn) sourceimg = os.path.join(current_dir, 'images', base) destimg = os.path.join(image_dir, base) shutil.copyfile(sourceimg, destimg) # <img srcset="elva-fairy-320w.jpg, # elva-fairy-480w.jpg 1.5x, # elva-fairy-640w.jpg 2x" # src="elva-fairy-640w.jpg" # alt="Elva dressed as a fairy"> # write html... imagebase = os.path.basename(imagenm) baseimage = os.path.join(image_rel, imagebase) hiimage = os.path.join(image_rel, os.path.basename(hidpiimagenm)) alt = options.pop('alt', '') classst = options.pop('class', None) if classst is not None: classst = f'class="{classst}"' else: classst = '' result = f'.. raw:: html\n\n <img srcset="{baseimage}, {hiimage} 2x" src="{hiimage}" alt="{alt}" {classst}>' result = statemachine.string2lines(result, convert_whitespace=True) self.state_machine.insert_input(result, source=source_file_name) return []
def run(self): uri = directives.uri(self.arguments[0]) self.options['target'] = uri self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri)) if self.content: (node,) = Figure.run(self) else: (node,) = Image.run(self) 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' return [nodes.raw('', self.html % self.options, format='html')]
def run(self): self.options['video_id'] = directives.uri(self.arguments[0]) if 'width' not in self.options: self.options['width'] = self.DEFAULT_WIDTH if 'height' not in self.options: self.options['height'] = self.DEFAULT_HEIGHT if 'align' not in self.options: self.options['align'] = self.DEFAULT_ALIGN return [docutils.nodes.raw('', self.html_code.format(**self.options), format='html')]
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" return [nodes.raw("", self.html % self.options, format="html")]
def run(self): """Process a new figure.""" env = self.state.document.settings.env reference = directives.uri(self.arguments[0]) if not os.path.isabs(reference): # A relative path means we should search for the image # Find the builder-specific path-list to search: bname = rememberedApp.builder.format if rememberedApp != None else env.app.builder.name if bname in env.app.config.findfigure_paths: searchdirs = env.app.config.findfigure_paths[bname] elif '*' in env.app.config.findfigure_paths: searchdirs = env.app.config.findfigure_paths['*'] else: searchdirs = (os.path.abspath('.'), ) if reference.endswith('.*'): # Find the builder-specific list of extensions to try base, dummy = os.path.splitext(reference) if bname in env.app.config.findfigure_types: searchexts = env.app.config.findfigure_types[bname] elif '*' in env.app.config.findfigure_types: searchexts = env.app.config.findfigure_types['*'] else: searchexts = ('.svg', '.pdf', '.png', '.jpeg', '.jpg', '.tiff', '.tif', '.gif') else: base = reference searchexts = ('', ) # Now try finding the figure. foundit = False aref = base for ext in searchexts: for path in searchdirs: try: aref = os.path.join(path, base) + ext # print ' TRY <%s>' % aref status = os.stat(aref) # Could check status bits here. foundit = True break except: foundit = False if foundit: break if not foundit: # print 'MISSING FILE %s' % reference return [] # print 'RESOLVED %s to %s' % (reference, aref) rewr = os.path.relpath( aref, os.path.join(env.srcdir, os.path.dirname(env.docname))) # NB: We must rewrite path relative to source directory # because otherwise the output stage will be unable # to find it. # print 'REWROTE %s to %s rel %s' % (aref, rewr, # os.path.abspath(os.path.dirname(env.docname))) self.arguments[0] = rewr return Figure.run(self)
def run(self): self.options['video_id'] = directives.uri(self.arguments[0]) if not self.options.get('width'): self.options['width'] = self.default_width # 16x9 if not self.options.get('height'): self.options['height'] = int(self.options['width'] / 16. * 9) if not self.options.get('align'): self.options['align'] = 'left' return [nodes.raw('', self.get_html(), format='html')]
def run(self): """Run the thumbnail directive.""" uri = directives.uri(self.arguments[0]) self.options["target"] = uri self.arguments[0] = ".thumbnail".join(os.path.splitext(uri)) if self.content: (node,) = Figure.run(self) else: (node,) = Image.run(self) return [node]
def run(self): """Process a new image.""" env = self.state.document.settings.env reference = directives.uri(self.arguments[0]) if not os.path.isabs(reference): # A relative path means we should search for the image # Find the builder-specific path-list to search: bname = rememberedApp.builder.format if rememberedApp != None else env.app.builder.name if bname in env.app.config.findfigure_paths: searchdirs = env.app.config.findfigure_paths[bname] elif '*' in env.app.config.findfigure_paths: searchdirs = env.app.config.findfigure_paths['*'] else: searchdirs = (os.path.abspath('.'),) if reference.endswith('.*'): # Find the builder-specific list of extensions to try base, dummy = os.path.splitext(reference) if bname in env.app.config.findfigure_types: searchexts = env.app.config.findfigure_types[bname] elif '*' in env.app.config.findfigure_types: searchexts = env.app.config.findfigure_types['*'] else: searchexts = ( '.svg', '.pdf', '.png', '.jpeg', '.jpg', '.tiff', '.tif', '.gif') else: base = reference searchexts = ('',) # Now try finding the figure. foundit = False aref = base for ext in searchexts: for path in searchdirs: try: aref = os.path.join(path, base) + ext # print ' TRY <%s>' % aref status = os.stat(aref) # Could check status bits here. foundit = True break except: foundit = False if foundit: break if not foundit: # print 'MISSING FILE %s' % reference return [] # print 'RESOLVED %s to %s' % (reference, aref) rewr = os.path.relpath( aref, os.path.join(env.srcdir, os.path.dirname(env.docname))) # NB: We must rewrite path relative to source directory # because otherwise the output stage will be unable # to find it. # print 'REWROTE %s to %s' % (aref, rewr) self.arguments[0] = rewr return Image.run(self)
def run(self): '''Process the argouml directive. Creates and returns an list of nodes, including an argouml node. ''' log.info('self.arguments[0] = {0}'.format(self.arguments[0])) messages = [] # Get the one and only argument of the directive which contains the # name of the ArgoUML zargo file. reference = directives.uri(self.arguments[0]) env = self.state.document.settings.env _, filename = relfn2path(env, reference) log.info('filename = {0}'.format(filename)) # Get the name of the diagram from the required :diagram: option diagram = self.options['diagram'] # Validate the :align: option if 'align' in self.options: if isinstance(self.state, states.SubstitutionDef): # Check for align_v_values. if self.options['align'] not in self.align_v_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value ' 'for the "align" option within a substitution ' 'definition. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_v_values))) elif self.options['align'] not in self.align_h_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_h_values))) set_classes(self.options) log.info("self.block_text = {0}".format(self.block_text)) log.info("self.options = {0}".format(self.options)) argouml_node = argouml(self.block_text, **self.options) argouml_node['uri'] = os.path.normpath(filename) argouml_node['diagram'] = diagram argouml_node['width'] = self.options['width'] if 'width' in self.options else '100%' argouml_node['height'] = self.options['height'] if 'height' in self.options else '100%' argouml_node['border'] = self.options['border'] if 'border' in self.options else 0 argouml_node['postprocess_command'] = self.options['postprocess'] if 'postprocess' in self.options else None argouml_node['new_window_flag'] = 'new-window' in self.options log.info("argouml_node['new_window_flag'] = {0}".format( argouml_node['new_window_flag'])) return messages + [argouml_node]
def run(self): """Process the inkscape directive. Creates and returns an list of nodes, including a inkscape node. """ log.info("self.arguments[0] = {0}".format(self.arguments[0])) messages = [] # Get the one and only argument of the directive which contains the # name of the Inkscape file. reference = directives.uri(self.arguments[0]) env = self.state.document.settings.env _, filename = relfn2path(env, reference) log.info("filename = {0}".format(filename)) # Validate the :align: option if "align" in self.options: if isinstance(self.state, states.SubstitutionDef): # Check for align_v_values. if self.options["align"] not in self.align_v_values: raise self.error( 'Error in "{0}" directive: "{1}" is not a valid value ' 'for the "align" option within a substitution ' 'definition. Valid values for "align" are: "{2}".'.format( self.name, self.options["align"], '", "'.join(self.align_v_values) ) ) elif self.options["align"] not in self.align_h_values: raise self.error( 'Error in "{0}" directive: "{1}" is not a valid value for ' 'the "align" option. Valid values for "align" are: "{2}".'.format( self.name, self.options["align"], '", "'.join(self.align_h_values) ) ) set_classes(self.options) log.info("self.block_text = {0}".format(self.block_text)) log.info("self.options = {0}".format(self.options)) inkscape_node = inkscape(self.block_text, **self.options) inkscape_node["uri"] = os.path.normpath(filename) inkscape_node["width"] = self.options["width"] if "width" in self.options else "100%" inkscape_node["height"] = self.options["height"] if "height" in self.options else "100%" inkscape_node["border"] = self.options["border"] if "border" in self.options else 0 inkscape_node["postprocess_command"] = self.options["postprocess"] if "postprocess" in self.options else None inkscape_node["new_window_flag"] = "new-window" in self.options log.info("inkscape_node['new_window_flag'] = {0}".format(inkscape_node["new_window_flag"])) return messages + [inkscape_node]
def run(self): node = embedly() node['url_or_urls'] = directives.uri(self.arguments[0].strip()) for option in ['maxwidth', 'maxheight', 'width', 'wmode', 'words', 'chars']: if option in self.options: node[option] = self.options[option] for option in ['nostyle', 'autoplay', 'videosrc', 'frame', 'secure']: if option in self.options: node[option] = True return [node]
def run(self): # remove 'align' processing # remove 'target' processing self.options.pop('align', None) reference = directives.uri(self.arguments[0]) self.options['uri'] = reference set_classes(self.options) image_node = nodes.image(self.block_text, **self.options) self.add_name(image_node) return [image_node]
def run(self): my_file = directives.uri(self.arguments[0]) full_path = posixpath.join(current_app.config['ATTACHMENT_DIR'], my_file) if full_path not in current_app.blohg.changectx.files: raise self.error('Error in "%s" directive: File not found: %s.' % (self.name, full_path)) self.arguments[0] = url_for('attachments', filename=my_file, _external=True) return Figure.run(self)
def run(self): # Raise an error if the directive does not have contents. self.assert_has_content() dotcode = '\n'.join(self.content) if not dotcode.strip(): return [self.state_machine.reporter.warning( 'Ignoring "graphviz" directive without content.', line=self.lineno)] reference = directives.uri(self.arguments[0]) #raise Exception(reference) self.render_dot(dotcode, reference, self.options) return super(Graphviz, self).run()
def run(self): self.assert_has_content() # Default values options = self.options for option in ('title', 'comments', 'subject', 'keywords'): if options.get(option) is None: options[option] = u"" if options.get('language') is None: # The website language, not the content language # because the wiki is not multilingual anyway context = get_context() languages = context.site_root.get_property('website_languages') language = context.accept_language.select_language(languages) options['language'] = language # Cover page if self.arguments: # Push cover as an option cover_uri = checkid(self.arguments[0][1:-2]) options['cover'] = directives.uri(cover_uri) # Metadata metadata = ['Book:'] for key in ('toc-depth', 'ignore-missing-pages', 'title', 'comments', 'subject', 'keywords', 'language', 'filename'): value = options.get(key) if not value: continue metadata.append(' %s: %s' % (key, value)) template = options.get('template') if template is not None: metadata.append(' template: ') meta_node = nodes.literal_block('Book Metadata', '\n'.join(metadata)) meta_node.append(nodes.reference(refuri=template, text=template, name=template, wiki_template=True)) else: meta_node = nodes.literal_block('Book Metadata', '\n'.join(metadata)) book_node = book(self.block_text, **options) if self.arguments: # Display the cover cover_text = self.arguments.pop(0) textnodes, messages = self.state.inline_text(cover_text, self.lineno) book_node += nodes.title(cover_text, '', *textnodes) book_node += messages # Parse inner list self.state.nested_parse(self.content, self.content_offset, book_node) # Automatically number pages for bullet_list in book_node.traverse(condition=nodes.bullet_list): bullet_list.__class__ = nodes.enumerated_list bullet_list.tagname = 'enumerated_list' return [meta_node, book_node]
def run(self): node = nodes.Element() node.document = self.state.document env = self.state.document.settings.env docname = env.docname template_filename = self.options.get("file") debug_template = self.options.get("debug") cxt = (self.app.config.jinja_contexts[self.arguments[0]].copy() if self.arguments else {}) cxt["options"] = { "header_char": self.options.get("header_char") } if template_filename: if debug_template is not None: print('') print('********** Begin Jinja Debug Output: Template Before Processing **********') print('********** From {} **********'.format(docname)) reference_uri = directives.uri(os.path.join('source', template_filename)) template_path = urllib.url2pathname(reference_uri) encoded_path = template_path.encode(sys.getfilesystemencoding()) imagerealpath = os.path.abspath(encoded_path) with codecs.open(imagerealpath, encoding='utf-8') as f: print(f.read()) print('********** End Jinja Debug Output: Template Before Processing **********') print('') tpl = Environment( loader=FileSystemLoader( self.app.config.jinja_base, followlinks=True) ).get_template(template_filename) else: if debug_template is not None: print('') print('********** Begin Jinja Debug Output: Template Before Processing **********') print('********** From {} **********'.format(docname)) print('\n'.join(self.content)) print('********** End Jinja Debug Output: Template Before Processing **********') print('') tpl = Environment( loader=FileSystemLoader( self.app.config.jinja_base, followlinks=True) ).from_string('\n'.join(self.content)) new_content = tpl.render(**cxt) if debug_template is not None: print('') print('********** Begin Jinja Debug Output: Template After Processing **********') print(new_content) print('********** End Jinja Debug Output: Template After Processing **********') print('') new_content = StringList(new_content.splitlines(), source='') sphinx.util.nested_parse_with_titles( self.state, new_content, node) return node.children