def set_site(self, site): """Set Nikola site.""" self.site = site roles.register_canonical_role('doc', doc_role) self.site.register_shortcode('doc', doc_shortcode) doc_role.site = site return super(Plugin, self).set_site(site)
def test_post_parse_sn(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") register_canonical_role("githublink", githublink_role)
def test_post_parse_sn(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") register_canonical_role("githublink", githublink_role)
def add_description_unit(self, directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None): additional_xref_types[directivename] = (rolename, indextemplate, parse_node) directives.register_directive(directivename, desc_directive) roles.register_canonical_role(rolename, xfileref_role) if ref_nodeclass is not None: innernodetypes[rolename] = ref_nodeclass
def add_crossref_type(self, directivename, rolename, indextemplate='', ref_nodeclass=None): additional_xref_types[directivename] = (rolename, indextemplate, None) directives.register_directive(directivename, target_directive) roles.register_canonical_role(rolename, xfileref_role) if ref_nodeclass is not None: innernodetypes[rolename] = ref_nodeclass
def set_site(self, site): """Set Nikola site.""" self.site = site roles.register_canonical_role('doc', doc_role) self.site.register_shortcode('doc', doc_shortcode) doc_role.site = site return super(Plugin, self).set_site(site)
def setup(app): # adding role for linking to InterTrac targets on t.e.o from docutils import nodes from docutils.parsers.rst import roles def teo_role(name, rawtext, text, lineno, inliner, options={}, content=[]): # special case ticket references if text[0] == '#': ref = url + '/ticket/' + text[1:] else: ref = url + '/intertrac/' + text roles.set_classes(options) node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], [] roles.register_canonical_role('teo', teo_role) def extensionpoints_role(name, rawtext, text, lineno, inliner, options={}, content=[]): ref = url + '/wiki/TracDev/PluginDevelopment/ExtensionPoints/' + text roles.set_classes(options) node = nodes.reference(rawtext, text + " extension points", refuri=ref, **options) return [node], [] roles.register_canonical_role('extensionpoints', extensionpoints_role) # ifconfig variables app.add_config_value('devel', '', True)
def setup(app: Sphinx) -> Dict[str, Any]: """Patches :mod:`sphinx_autodoc_typehints` for a more elegant display.""" # TODO: Unsure if “html” is sufficient or if we need to do “env”; # Depends on when the autodoc-process-docstring event is handled. app.add_config_value("qualname_overrides", {}, "html") app.add_config_value("annotate_defaults", True, "html") app.add_css_file("typehints.css") app.connect("config-inited", _init_vars) from .formatting import _role_annot, format_annotation app.config.typehints_formatter = format_annotation for name in ["annotation-terse", "annotation-full"]: roles.register_canonical_role( name, partial(_role_annot, additional_classes=name.split("-"))) from .autodoc_patch import dir_head_adder ClassDocumenter.add_directive_header = dir_head_adder( qualname_overrides, ClassDocumenter.add_directive_header) from .return_tuple import process_docstring # , process_signature app.connect("autodoc-process-docstring", process_docstring) # app.connect("autodoc-process-signature", process_signature) return metadata
def configure_pelican(plc): if "KATEX" in plc.settings and isinstance(plc.settings["KATEX"], dict): rendering.KATEX_DEFAULT_OPTIONS.update(plc.settings["KATEX"]) if "KATEX_PATH" in plc.settings: rendering.KATEX_PATH = plc.settings["KATEX_PATH"] if "KATEX_DIRECTIVE" in plc.settings: rst_name = str(plc.settings["KATEX_DIRECTIVE"]) else: rst_name = "math" if "KATEX_RENDER_TIMEOUT" in plc.settings: rendering.KATEX_RENDER_TIMEOUT = float( plc.settings["KATEX_RENDER_TIMEOUT"]) if "KATEX_STARTUP_TIMEOUT" in plc.settings: rendering.KATEX_STARTUP_TIMEOUT = float( plc.settings["KATEX_STARTUP_TIMEOUT"]) if "KATEX_NODEJS_BINARY" in plc.settings: rendering.KATEX_NODEJS_BINARY = plc.settings["KATEX_NODEJS_BINARY"] if "KATEX_PREAMBLE" in plc.settings: rendering.KATEX_PREAMBLE = plc.settings["KATEX_PREAMBLE"] # Integrate into reStructuredText directives.register_directive(rst_name, KatexBlock) roles.register_canonical_role(rst_name, katex_role) # Integrate into markdown if markdown_available: plc.settings["MARKDOWN"].setdefault("extensions", []).append(KatexExtension())
def setup(app): app.add_directive('tabs', TabsDirective) app.add_directive('tab', TabDirective) app.set_translator('dirhtml', nxt_translator) roles.register_canonical_role('nxt_term', nxt_term_role_fn)
def add_role(self, name, cl): """ See :epkg:`class Sphinx`. """ doc_roles.register_canonical_role(name, cl) self.mapping[str(cl)] = name self.app.add_role(name, cl) self.writer.app.add_role(name, cl)
def __init__(self): self.writer = Writer() self.writer.translator_class = GitHubHTMLTranslator roles.register_canonical_role('kbd', kbd) # Render source code in Sphinx doctest blocks directives.register_directive('doctest', DoctestDirective)
def register_linkrole(role_name, callback): def source_role(name, rawtext, text, lineno, inliner, options={}, content=[]): text, target = callback(name, text) reference_node = nodes.reference(rawtext, text, name=text, refuri=target) return [reference_node], [] source_role.content = True source_role.options = {} roles.register_canonical_role(role_name, source_role)
def register_linkrole(role_name, callback): def source_role(name, rawtext, text, lineno, inliner, options={}, content=[]): text, target = callback(name, text) reference_node = nodes.reference(rawtext, text, name=text, refuri=target) return [reference_node], [] source_role.content = True source_role.options = {} roles.register_canonical_role(role_name, source_role)
def set_site(self, site): def strike_role(role, rawtext, text, lineno, inliner, options={}, content=[]): return [nodes.raw('', '<del>{}</del>'.format(text), format='html')], [] self.site = site roles.register_canonical_role('del', strike_role) return super(Plugin, self).set_site(site)
def register_config_role(docdir): """ register a :config: ReST link role for use in documentation. """ try: from docutils.parsers.rst import directives, states, roles from pypy.tool.rest.directive import register_linkrole except ImportError: return # enable :config: link role def config_role(name, rawtext, text, lineno, inliner, options={}, content=[]): from docutils import nodes from pypy.config.pypyoption import get_pypy_config from pypy.config.makerestdoc import get_cmdline txt = docdir.join("config", text + ".txt") html = docdir.join("config", text + ".html") assert txt.check() assert name == "config" sourcedir = py.path.local(inliner.document.settings._source).dirpath() curr = sourcedir prefix = "" while 1: relative = str(html.relto(curr)) if relative: break curr = curr.dirpath() prefix += "../" config = get_pypy_config() # begin horror h, n = config._cfgimpl_get_home_by_path(text) opt = getattr(h._cfgimpl_descr, n) # end horror cmdline = get_cmdline(opt.cmdline, text) if cmdline is not None: shortest_long_option = 'X' * 1000 for cmd in cmdline.split(): if cmd.startswith( '--') and len(cmd) < len(shortest_long_option): shortest_long_option = cmd text = shortest_long_option target = prefix + relative print text, target reference_node = nodes.reference(rawtext, text, name=text, refuri=target) return [reference_node], [] config_role.content = True config_role.options = {} roles.register_canonical_role("config", config_role)
def generate_uri_role(role_name, aliases, anchor_text, base_url, interpret_url, validator): """ Create and register a uri based "interpreted role" Those are similar to the RFC, and PEP ones, and take role_name: name that will be registered aliases: list of alternate names anchor_text: text that will be used, together with the role base_url: base url for the link interpret_url: this, modulo the validated text, will be added to it validator: should return the validated text, or raise ValueError """ def uri_reference_role(role, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} try: valid_text = validator(text) except ValueError as e: msg = inliner.reporter.error(e.message % dict(text=text), line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] ref = base_url + interpret_url % valid_text set_classes(options) node = nodes.reference(rawtext, anchor_text + utils.unescape(text), refuri=ref, **options) return [node], [] uri_reference_role.__doc__ = """Role to make handy references to URIs. Use as :%(role_name)s:`71` (or any of %(aliases)s). It will use %(base_url)s+%(interpret_url)s validator should throw a ValueError, containing optionally a %%(text)s format, if the interpreted text is not valid. """ % locals() roles.register_canonical_role(role_name, uri_reference_role) from docutils.parsers.rst.languages import en en.roles[role_name] = role_name for alias in aliases: en.roles[alias] = role_name
def set_site(self, site): self.site = site directives.register_directive('itemscope', ItemScopeDirective) directives.register_directive('itempropblock', ItemPropDirective) roles.register_canonical_role('itemprop', itemprop_role) add_node(ItemProp, visit_ItemProp, depart_ItemProp) add_node(ItemPropBlock, visit_ItemPropBlock, depart_ItemPropBlock) add_node(ItemScope, visit_ItemScope, depart_ItemScope) return super(Plugin, self).set_site(site)
def set_backend_and_register_directives(backend): #XXX this is only used to work around the inflexibility of docutils: # a directive does not know the target format global _backend _backend = backend if not directives_are_functions: directives.register_directive("graphviz", GraphvizDirective) else: directives.register_directive("graphviz", GraphvizDirective().old_interface()) roles.register_canonical_role("latexformula", latexformula_role)
def set_backend_and_register_directives(backend): #XXX this is only used to work around the inflexibility of docutils: # a directive does not know the target format global _backend _backend = backend if not directives_are_functions: directives.register_directive("graphviz", GraphvizDirective) else: directives.register_directive("graphviz", GraphvizDirective().old_interface()) roles.register_canonical_role("latexformula", latexformula_role)
def _register_roles(conf): """ Registers roles to be used in this run. `conf` - configuration module. """ for rolecand, rolename in ((getattr(conf, role), role) for role in dir(conf) if role.startswith('role_')): if callable(rolecand): roles.register_canonical_role(rolename[5:], rolecand)
def set_site(self, site): self.site = site directives.register_directive('itemscope', ItemScopeDirective) directives.register_directive('itempropblock', ItemPropDirective) roles.register_canonical_role('itemprop', itemprop_role) add_node(ItemProp, visit_ItemProp, depart_ItemProp) add_node(ItemPropBlock, visit_ItemPropBlock, depart_ItemPropBlock) add_node(ItemScope, visit_ItemScope, depart_ItemScope) return super(Plugin, self).set_site(site)
def __init__(self, filename, options=None): super(Handler, self).__init__(filename, options) if not options: return for dir_name, directive in options.get('register_directives', {}).items(): directives.register_directive(dir_name, directive) for role_name, role in options.get('register_roles', {}).items(): roles.register_canonical_role(role_name, role)
def setup(app): app.add_directive('nxt_details', DetailsDirective) app.add_directive('tabs', TabsDirective) app.add_directive('tab', TabDirective) app.add_env_collector(nxt_collector) app.add_builder(nxt_builder) app.set_translator('nxt_html', nxt_translator) app.connect('doctree-read', register_tabs_as_label) roles.register_canonical_role('nxt_term', nxt_term_role_fn)
def register(): directives.register_directive('itemscope', ItemScopeDirective) roles.register_canonical_role('itemprop', itemprop_role) PelicanHTMLTranslator.visit_ItemProp = as_method(visit_ItemProp) PelicanHTMLTranslator.depart_ItemProp = as_method(depart_ItemProp) PelicanHTMLTranslator.visit_ItemScope = as_method(visit_ItemScope) PelicanHTMLTranslator.depart_ItemScope = as_method(depart_ItemScope) # handle compact parameter # TODO: find a cleaner way to handle this case PelicanHTMLTranslator.visit_paragraph = as_method(visit_paragraph)
def setup(app: Sphinx) -> Dict[str, Any]: """Patches :mod:`sphinx_autodoc_typehints` for a more elegant display.""" app.add_config_value("qualname_overrides", {}, "") app.add_css_file("typehints.css") app.connect("config-inited", _init_vars) sphinx_autodoc_typehints.format_annotation = format_annotation for name in ["annotation-terse", "annotation-full"]: roles.register_canonical_role( name, partial(_role_annot, additional_classes=name.split("-")) ) return metadata
def setup(app): def add(**kw): skw = dict() for k, v in list(kw.items()): skw[str(k)] = str(v) app.add_object_type(**skw) add(directivename='management_command', rolename='manage', indextemplate='pair: %s; management command') # add(directivename='role', rolename='role', # indextemplate='pair: %s; docutils role') # add(directivename='directive', rolename='directive', # indextemplate='pair: %s; docutils directive') # add(directivename='fab_command', # rolename='fab', # indextemplate='pair: %s; fab command') app.add_object_type( 'command', 'cmd', 'pair: %s; command', command_parse) add(directivename='xfile', rolename='xfile', indextemplate='pair: %s; file') add(directivename='setting', rolename='setting', indextemplate='pair: %s; setting') # add(directivename='actorattr', rolename='aa', # indextemplate='pair: %s; actor attribute') add(directivename='screenshot', rolename='screen', indextemplate='pair: %s; screenshot') add(directivename='modattr', rolename='modattr', indextemplate='pair: %s; model attribute') add(directivename='model', rolename='model', indextemplate='pair: %s; model') # app.connect('build-finished', handle_finished) app.connect(str('autodoc-skip-member'), autodoc_skip_member) app.connect(str('autodoc-process-docstring'), autodoc_add_srcref) # app.connect(str('autodoc-process-signature'), process_signature) app.connect(str('html-page-context'), html_page_context) app.add_role(str('coderef'), coderef_role) app.add_role(str('message'), message_role) app.add_role(str('actor'), actor_role) roles.register_canonical_role(str('blogref'), blogref_role) app.add_config_value( 'blogref_format', "http://luc.lino-framework.org/blog/%Y/%m%d.html", 'html')
def setup(app): def add(**kw): skw = dict() for k, v in list(kw.items()): skw[str(k)] = str(v) app.add_object_type(**skw) add(directivename='management_command', rolename='manage', indextemplate='pair: %s; management command') # add(directivename='role', rolename='role', # indextemplate='pair: %s; docutils role') # add(directivename='directive', rolename='directive', # indextemplate='pair: %s; docutils directive') # add(directivename='fab_command', # rolename='fab', # indextemplate='pair: %s; fab command') app.add_object_type( 'command', 'cmd', 'pair: %s; command', command_parse) add(directivename='xfile', rolename='xfile', indextemplate='pair: %s; file') add(directivename='setting', rolename='setting', indextemplate='pair: %s; setting') # add(directivename='actorattr', rolename='aa', # indextemplate='pair: %s; actor attribute') add(directivename='screenshot', rolename='screen', indextemplate='pair: %s; screenshot') add(directivename='modattr', rolename='modattr', indextemplate='pair: %s; model attribute') add(directivename='model', rolename='model', indextemplate='pair: %s; model') # app.connect('build-finished', handle_finished) app.connect(str('autodoc-skip-member'), autodoc_skip_member) app.connect(str('autodoc-process-docstring'), autodoc_add_srcref) # app.connect(str('autodoc-process-signature'), process_signature) app.connect(str('html-page-context'), html_page_context) app.add_role(str('coderef'), coderef_role) app.add_role(str('message'), message_role) app.add_role(str('actor'), actor_role) roles.register_canonical_role(str('blogref'), blogref_role) app.add_config_value( 'blogref_format', "http://luc.lino-framework.org/blog/%Y/%m%d.html", 'html')
def setup(app): app.add_config_value('javadoc_dir', os.path.join(app.outdir, 'apidocs'), 'html') # Register the 'api' and 'apiplural' role. api_role.options = {'class': directives.class_option} register_canonical_role('api', api_role) register_canonical_role('apiplural', apiplural_role) # Register the node for 'api' and 'apiplural'. app.add_node(ApiLink, **_NODE_VISITORS) pass
def setup(app): app.add_config_value('javadoc_dir', os.path.join(app.outdir, 'apidocs'), 'html') # Register the 'javadoc' role. api_role.options = {'class': directives.class_option} register_canonical_role('api', api_role) register_canonical_role('apiplural', apiplural_role) # Intercept the rendering of HTML literals. old_visitor = HTMLTranslator.visit_literal HTMLTranslator.visit_literal = lambda self, node: api_visit_literal(self, node, old_visitor) pass
def setup(app): """Connects the extension to the app.""" app.add_directive('nxt_details', DetailsDirective) app.add_directive('tabs', TabsDirective) app.add_directive('tab', TabDirective) app.add_env_collector(NxtCollector) app.add_builder(NxtBuilder) app.set_translator('nxt_html', NxtTranslator) app.connect('doctree-read', register_tabs_as_label) roles.register_canonical_role('nxt_hint', nxt_hint_role_fn)
def setup(app): # adding role for linking to InterTrac targets on t.e.o from urllib import quote from docutils import nodes from docutils.parsers.rst import roles def teo_role(name, rawtext, text, lineno, inliner, options={}, content=[]): ref = url + '/intertrac/' + quote(text) roles.set_classes(options) node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], [] roles.register_canonical_role('teo', teo_role) # ifconfig variables app.add_config_value('devel', '', True)
def setup(app): """ The Sphinx setup function used for Lino-related documentation trees. """ def add(**kw): skw = dict() for k, v in kw.items(): skw[str(k)] = str(v) app.add_object_type(**skw) add(directivename='management_command', rolename='manage', indextemplate='pair: %s; management command') # add(directivename='role', rolename='role', # indextemplate='pair: %s; docutils role') # add(directivename='directive', rolename='directive', # indextemplate='pair: %s; docutils directive') # add(directivename='fab_command', # rolename='fab', # indextemplate='pair: %s; fab command') app.add_object_type( 'command', 'cmd', 'pair: %s; command', command_parse) add(directivename='xfile', rolename='xfile', indextemplate='pair: %s; file') add(directivename='setting', rolename='setting', indextemplate='pair: %s; setting') add(directivename='actorattr', rolename='aa', indextemplate='pair: %s; actor attribute') add(directivename='screenshot', rolename='screen', indextemplate='pair: %s; screenshot') add(directivename='modattr', rolename='modattr', indextemplate='pair: %s; model attribute') add(directivename='model', rolename='model', indextemplate='pair: %s; model') #app.connect('build-finished', handle_finished) app.connect(str('autodoc-skip-member'), autodoc_skip_member) app.connect(str('autodoc-process-docstring'), autodoc_add_srcref) app.add_role(str('coderef'), coderef_role) roles.register_canonical_role(str('blogref'), blogref_role)
def setup(app): # Truncate the bibliografy file to re-create it from scratch f = open(references_file, "w", encoding="utf8") f.close() app.add_directive("jrmbibliography", HelloWorld) roles.register_canonical_role('citep', citep) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, }
def register() -> None: for r in [ # Standard roles (https://docutils.sourceforge.io/docs/ref/rst/roles.html) that don't have # equivalent non-role-based markup. "math", "pep-reference", "rfc-reference", "subscript", "superscript", ]: roles.register_canonical_role(r, generic_role) roles.register_canonical_role("download", ReferenceRole()) for domain in _subclasses(sphinx.domains.Domain): for name, role_callable in domain.roles.items(): if isinstance(role_callable, sphinx.util.docutils.ReferenceRole): roles.register_canonical_role(name, ReferenceRole()) roles.register_canonical_role(f"{domain.name}:{name}", ReferenceRole()) # `list-table` directives are parsed into table nodes by default and could be formatted as such, # but that's vulnerable to producing malformed tables when the given column widths are too # small. # docutils directives _add_directive("contents", parts.Contents) _add_directive("figure", images.Figure, raw=False) _add_directive("image", images.Image) _add_directive("include", misc.Include) _add_directive("list-table", tables.ListTable, raw=False) _add_directive("math", body.MathBlock) _add_directive("raw", misc.Raw) # sphinx directives _add_directive("autosummary", autosummary.Autosummary) _add_directive("currentmodule", PyCurrentModule) _add_directive("deprecated", other.VersionChange, raw=False) _add_directive("function", PyFunction) _add_directive("literalinclude", code.LiteralInclude) _add_directive("py:function", PyFunction) _add_directive("rst-class", other.Class) _add_directive("seealso", other.SeeAlso, raw=False) _add_directive("toctree", other.TocTree) _add_directive("versionadded", other.VersionChange, raw=False) _add_directive("versionchanged", other.VersionChange, raw=False) for d in set(_subclasses(autodoc.Documenter)): if d.objtype != "object": _add_directive(f"auto{d.objtype}", autodoc.directive.AutodocDirective, raw=False) try: import sphinxarg.ext except ImportError: pass else: # pragma: no cover _add_directive("argparse", sphinxarg.ext.ArgParseDirective)
def setup(app): # adding role for linking to InterTrac targets on t.e.o from urllib import quote from docutils import nodes from docutils.parsers.rst import roles def teo_role(name, rawtext, text, lineno, inliner, options={}, content=[]): ref = url + '/intertrac/' + quote(text) roles.set_classes(options) node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], [] roles.register_canonical_role('teo', teo_role) # ifconfig variables app.add_config_value('devel', '', True)
def register_config_role(docdir): """ register a :config: ReST link role for use in documentation. """ try: from docutils.parsers.rst import directives, states, roles from pypy.tool.rest.directive import register_linkrole except ImportError: return # enable :config: link role def config_role(name, rawtext, text, lineno, inliner, options={}, content=[]): from docutils import nodes from pypy.config.pypyoption import get_pypy_config from pypy.config.makerestdoc import get_cmdline txt = docdir.join("config", text + ".txt") html = docdir.join("config", text + ".html") assert txt.check() assert name == "config" sourcedir = py.path.local(inliner.document.settings._source).dirpath() curr = sourcedir prefix = "" while 1: relative = str(html.relto(curr)) if relative: break curr = curr.dirpath() prefix += "../" config = get_pypy_config() # begin horror h, n = config._cfgimpl_get_home_by_path(text) opt = getattr(h._cfgimpl_descr, n) # end horror cmdline = get_cmdline(opt.cmdline, text) if cmdline is not None: shortest_long_option = "X" * 1000 for cmd in cmdline.split(): if cmd.startswith("--") and len(cmd) < len(shortest_long_option): shortest_long_option = cmd text = shortest_long_option target = prefix + relative print text, target reference_node = nodes.reference(rawtext, text, name=text, refuri=target) return [reference_node], [] config_role.content = True config_role.options = {} roles.register_canonical_role("config", config_role)
def catchall_interpreted(self, rawsource, text, role, lineno): """Interpreted text role dispatch method. Replacement for Inliner.interpreted(): if a role is not known, build one on the fly instead of reporting an error. """ role_fn, messages = roles.role(role, self.language, lineno, self.reporter) # in case it's missing, register a generic role if not role_fn: role_obj = AnyRole(role) roles.register_canonical_role(role, role_obj) role_fn, messages = roles.role(role, self.language, lineno, self.reporter) assert role_fn, "can't find just defined role" nodes, messages2 = role_fn(role, rawsource, text, lineno, self) return nodes, messages + messages2
def __init__(self, path): """Parse the configuration file at ``path``.""" self.tools = {} self.config_tree = yaml.load(open(path)) tool_types = { tool_module.__name__.split('.')[-1]: tool_module for tool_module in TOOLS} for item in self.config_tree: if '(' not in item: continue tool_type, tool_name = item.split('(') tool_type = tool_type.strip().replace(' ', '_') tool_name = tool_name.strip(' )') self.config_tree[tool_type] = self.config_tree.pop(item) if tool_type in tool_types: tool_module = tool_types[tool_type] tool_class = getattr(tool_module, tool_name.capitalize()) for prop in self.config_tree[tool_type]: if ' ' in prop: new_prop = prop.replace(' ', '_') values = self.config_tree[tool_type].pop(prop) self.config_tree[tool_type][new_prop] = values try: tool_instance = tool_class(**self.config_tree[tool_type]) except Exception as exception: print('Support for %s is disabled' % tool_type) print(exception) continue self.tools[tool_type] = tool_instance for class_name in dir(tool_module): cls = getattr(tool_module, class_name) if isinstance(cls, type): if issubclass(cls, tool.Directive) and \ cls != tool.Directive: directives.register_directive( class_name.lower(), cls) elif issubclass(cls, tool.Role) and cls != tool.Role: roles.register_canonical_role( class_name.lower(), role_generator(cls()))
def generate_uri_role( role_name, aliases, anchor_text, base_url, interpret_url, validator): """ Create and register a uri based "interpreted role" Those are similar to the RFC, and PEP ones, and take role_name: name that will be registered aliases: list of alternate names anchor_text: text that will be used, together with the role base_url: base url for the link interpret_url: this, modulo the validated text, will be added to it validator: should return the validated text, or raise ValueError """ def uri_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: valid_text = validator(text) except ValueError as e: msg = inliner.reporter.error( e.message % dict(text=text), line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] ref = base_url + interpret_url % valid_text set_classes(options) node = nodes.reference(rawtext, anchor_text + utils.unescape(text), refuri=ref, **options) return [node], [] uri_reference_role.__doc__ = """Role to make handy references to URIs. Use as :%(role_name)s:`71` (or any of %(aliases)s). It will use %(base_url)s+%(interpret_url)s validator should throw a ValueError, containing optionally a %%(text)s format, if the interpreted text is not valid. """ % locals() roles.register_canonical_role(role_name, uri_reference_role) from docutils.parsers.rst.languages import en en.roles[role_name] = role_name for alias in aliases: en.roles[alias] = role_name
def setup(app: Sphinx) -> None: """Connects the extension to the app.""" pygments.lexers.data.JsonLexer.constants = \ set('truefalsenullxphi_0123456789') # Adding 'nxt_ph_N' and 'nxt_hint_N' to the charset allows # NxtHightlighter.highlight_block() to run w/o resetting lexer to 'none' # when constants such as false and true are commented with nxt_ directives. app.add_directive('nxt_details', DetailsDirective) app.add_directive('tabs', TabsDirective) app.add_directive('tab', TabDirective) app.add_env_collector(NxtCollector) app.add_builder(NxtBuilder) app.set_translator('nxt_html', NxtTranslator) app.connect('doctree-read', register_tabs_as_label) roles.register_canonical_role('nxt_hint', nxt_hint_role_fn)
def catchall_interpreted(self, rawsource, text, role, lineno): """Interpreted text role dispatch method. Replacement for Inliner.interpreted(): if a role is not known, build one on the fly instead of reporting an error. """ role_fn, messages = roles.role(role, self.language, lineno, self.reporter) # in case it's missing, register a generic role if not role_fn: role_obj = AnyRole(role) roles.register_canonical_role(role, role_obj) role_fn, messages = roles.role( role, self.language, lineno, self.reporter) assert role_fn, "can't find just defined role" nodes, messages2 = role_fn(role, rawsource, text, lineno, self) return nodes, messages + messages2
def setup(app: "Sphinx") -> Dict[str, Any]: from docutils.parsers.rst import roles for rolename, nodeclass in generic_docroles.items(): generic = roles.GenericRole(rolename, nodeclass) role = roles.CustomRole(rolename, generic, {'classes': [rolename]}) roles.register_local_role(rolename, role) for rolename, func in specific_docroles.items(): roles.register_local_role(rolename, func) # Since docutils registers it as a canonical role, override it as a # canonical role as well. roles.register_canonical_role('code', code_role) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
def __init__(self, config_dict, overrides=None): 'Handle mapping a dict to required configuration parameters' if overrides is None: overrides = dict() self._overrides = overrides self._config_dict = config_dict if self.pygments_directive: # Render code blocks using pygments directives.register_directive('code-block', pygments.pygments_directive) if self.dotgraph_directive: # Render DOT to SVG directives.register_directive('dot-graph', dotgraph.dotgraph_directive) if self.eqtexsvg_directive: # Render LaTeX to SVG eqtexsvg.CACHE_DIR = self.cache_dir directives.register_directive('maths', eqtexsvg.eqtexsvg_directive) roles.register_canonical_role('maths', eqtexsvg.eqtexsvg_role) if not isinstance(self.template_dirs, list): raise TypeError('Misconfigured: `template_dirs` should be a list') if not isinstance(self.pages, list): raise TypeError('Misconfigured: `pages` should be a list')
def register_document_elements(self) : # Register roles for item_name in dir(self.translator_class) : # Normal roles if item_name.startswith("role_") : role_name = item_name.replace("role_", "") roles.register_canonical_role(role_name, generic_inline_role) d("Registered (normal) role %s" % role_name) # Raw roles. elif item_name.startswith("raw_role_") : role_name = item_name.replace("raw_role_", "") roles.register_canonical_role(role_name, generic_raw_role) d("Registered raw role %s" % role_name) # Register directives, first from this module, the from an extension module, so can overload. items = globals() if self.extension_module : items.update(self.extension_module.__dict__) for item_name, item in items.iteritems() : if inspect.isclass(item) and issubclass(item, WriterDirective) and item != WriterDirective: d("Registering directive %s" % item_name) directives.register_directive(item.__name__, item)
def register() -> None: for r in [ # Standard roles (https://docutils.sourceforge.io/docs/ref/rst/roles.html) that don't have # equivalent non-role-based markup. "math", "pep-reference", "rfc-reference", "subscript", "superscript", ]: roles.register_canonical_role(r, generic_role) roles.register_canonical_role("download", ReferenceRole()) for domain in _subclasses(sphinx.domains.Domain): for name, role_callable in domain.roles.items(): if isinstance(role_callable, sphinx.util.docutils.ReferenceRole): roles.register_canonical_role(name, ReferenceRole()) roles.register_canonical_role(domain.name + ":" + name, ReferenceRole()) # `list-table` directives are parsed into table nodes by default and could be formatted as such, # but that's vulnerable to producing malformed tables when the given column widths are too # small. _add_directive("list-table", directives.tables.ListTable, raw=False) _add_directive("contents", parts.Contents) _add_directive("image", directives.images.Image) _add_directive("include", directives.misc.Include) _add_directive("literalinclude", sphinx.directives.code.LiteralInclude) _add_directive("toctree", sphinx.directives.other.TocTree) _add_directive("math", directives.body.MathBlock) _add_directive("raw", directives.misc.Raw) _add_directive("todo", sphinx.ext.todo.Todo) for d in set(_subclasses(autodoc.Documenter)): if d.objtype != "object": _add_directive("auto" + d.objtype, autodoc.directive.AutodocDirective, raw=False) try: import sphinxarg.ext except ImportError: pass else: _add_directive("argparse", sphinxarg.ext.ArgParseDirective)
def cw_rest_init(): global _INITIALIZED if _INITIALIZED: return _INITIALIZED = True register_canonical_role('eid', eid_reference_role) register_canonical_role('rql', rql_role) register_canonical_role('bookmark', bookmark_role) directives.register_directive('winclude', winclude_directive) if pygments_directive is not None: directives.register_directive('sourcecode', pygments_directive) directives.register_directive('rql-table', RQLTableDirective)
#return [refnode],[] def ydefault_role(role,rawtext,text,lineno,inliner,options={},content=[]): "Handle the :ydefault:`something` role. fixSignature handles it now in the member signature itself, this merely expands to nothing." return [],[] def yattrtype_role(role,rawtext,text,lineno,inliner,options={},content=[]): "Handle the :yattrtype:`something` role. fixSignature handles it now in the member signature itself, this merely expands to nothing." return [],[] # FIXME: should return readable representation of bits of the number (yade.wrapper.AttrFlags enum) def yattrflags_role(role,rawtext,text,lineno,inliner,options={},content=[]): "Handle the :yattrflags:`something` role. fixSignature handles it now in the member signature itself." return [],[] from docutils.parsers.rst import roles def yaderef_role_2(type,rawtext,text,lineno,inliner,options={},content=[]): return YadeXRefRole()('yref',rawtext,text,lineno,inliner,options,content) roles.register_canonical_role('yref', yaderef_role) roles.register_canonical_role('ysrc', yadesrc_role) roles.register_canonical_role('ydefault', ydefault_role) roles.register_canonical_role('yattrtype', yattrtype_role) roles.register_canonical_role('yattrflags', yattrflags_role) ## http://sphinx.pocoo.org/config.html#confval-rst_epilog rst_epilog = """ .. |yupdate| replace:: *(auto-updated)* .. |ycomp| replace:: *(auto-computed)* .. |ystatic| replace:: *(static)* """ import collections
def _register_role(role): roles.register_canonical_role(role_name, role) return role
return "Create" def update(self, content): self.document = content def save(self): dir = os.path.dirname(self.path) if not os.path.exists(dir): os.makedirs(dir) if not os.path.exists(self.path): isNewFile=True print "Saving %s" % self.path f = codecs.open(self.path, "w", encoding="utf8"); f.write(self.document) f.close(); # define a `ref:` role for reST, need to override the one in dojo.py to make sure we are relative to request.script_name def ref_role(role, rawtext, text, lineno, inliner, options={}, content=[]): # match :ref:`Bar! <link/link/link>` from rawText p = re.search('`(.*) <(.*)>`', rawtext) if(p): return [nodes.reference(rawtext, p.group(1), refuri= cherrypy.request.script_name + "/" + p.group(2), **options)], [] else: return [], [] # also, this could be safer: register_canonical_role("ref", ref_role)
prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] ref = base_url + interpret_url % valid_text set_classes(options) node = nodes.reference(rawtext, anchor_text + utils.unescape(text), refuri=ref, **options) return [node], [] uri_reference_role.__doc__ = """Role to make handy references to URIs. Use as :%(role_name)s:`71` (or any of %(aliases)s). It will use %(base_url)s+%(interpret_url)s validator should throw a ValueError, containing optionally a %%(text)s format, if the interpreted text is not valid. """ % locals() roles.register_canonical_role(role_name, uri_reference_role) from docutils.parsers.rst.languages import en en.roles[role_name] = role_name for alias in aliases: en.roles[alias] = role_name generate_uri_role('xep-reference', ('jep', 'xep'), 'XEP #', 'http://www.xmpp.org/extensions/', 'xep-%04d.html', pos_int_validator) generate_uri_role('gajim-ticket-reference', ('ticket','gtrack'), 'Gajim Ticket #', 'http://trac.gajim.org/ticket/', '%d', pos_int_validator) class HTMLGenerator: '''Really simple HTMLGenerator starting from publish_parts.
raise ValueError("Can't find '%s' in any provided module." % name) def api_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: target = get_element_target(text) except Exception, exc: msg = inliner.reporter.error(str(exc), line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] ref = target.get_url() node2 = nodes.literal(rawtext, utils.unescape(text)) node = nodes.reference(rawtext, '', node2, refuri=ref, **options) return [node], [] register_canonical_role('api', api_role) # Register the 'api' role as canonical role from docutils.parsers.rst import roles roles.DEFAULT_INTERPRETED_ROLE = 'api' description = ('Generates (X)HTML documents from standalone reStructuredText ' 'sources with links to Epydoc API. ' + default_description) publish_cmdline(writer_name='html', description=description)
from docutils import nodes, utils from docutils.parsers.rst.roles import register_canonical_role, set_classes def card_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): text = text.strip() try: wikiid, rest = text.split(u':', 1) except: wikiid, rest = text, text context = inliner.document.settings.context ref = context._cw.build_url('card/' + wikiid) rset = context._cw.execute('Card C WHERE C wikiid %(w)s', {'w': wikiid}) set_classes(options) if not rset: options['classes'] = ['doesnotexist'] else: options.pop('classes', None) return [nodes.reference(rawtext, utils.unescape(rest), refuri=ref, **options)], [] register_canonical_role('card', card_reference_role)
for cmd, key, ctx in KEYBINDS[text]: n = nodes.paragraph() newnode += n n += nodes.strong('Keybinding: ', 'Keybinding: ') for k in key: n += nodes.inline(k, k, classes=['kbd']) if cmd != text: n += nodes.inline(' -> ', ' -> ') n += nodes.literal(cmd, cmd, classes=['guilabel']) if ctx: n += nodes.inline(' in ', ' in ') n += nodes.literal(ctx, ctx) return [newnode], [] roles.register_canonical_role('dfhack-keybind', dfhack_keybind_role_func) # -- Autodoc for DFhack scripts ------------------------------------------- def doc_dir(dirname, files): """Yield (command, includepath) for each script in the directory.""" sdir = os.path.relpath(dirname, '.').replace('\\', '/').replace('../', '') for f in files: if f[-3:] not in ('lua', '.rb'): continue with open(os.path.join(dirname, f), 'r', encoding='utf8') as fstream: text = [l.rstrip() for l in fstream.readlines() if l.strip()] # Some legacy lua files use the ruby tokens (in 3rdparty scripts) tokens = ('=begin', '=end') if f[-4:] == '.lua' and any('[====[' in line for line in text): tokens = ('[====[', ']====]')
# FIXME: should return readable representation of bits of the number (yade.wrapper.AttrFlags enum) def yattrflags_role(role, rawtext, text, lineno, inliner, options={}, content=[]): "Handle the :yattrflags:`something` role. fixSignature handles it now in the member signature itself." return [], [] from docutils.parsers.rst import roles def yaderef_role_2(type, rawtext, text, lineno, inliner, options={}, content=[]): return YadeXRefRole()("yref", rawtext, text, lineno, inliner, options, content) roles.register_canonical_role("yref", yaderef_role) roles.register_canonical_role("ysrc", yadesrc_role) roles.register_canonical_role("ydefault", ydefault_role) roles.register_canonical_role("yattrtype", yattrtype_role) roles.register_canonical_role("yattrflags", yattrflags_role) ## http://sphinx.pocoo.org/config.html#confval-rst_epilog rst_epilog = """ .. |yupdate| replace:: *(auto-updated)* .. |ycomp| replace:: *(auto-computed)* .. |ystatic| replace:: *(static)* """ import collections
elif typ == 'rfc': indexnode['entries'] = [('single', 'RFC; RFC %s' % text, targetid, 'RFC %s' % text)] try: rfcnum = int(text) except ValueError: msg = inliner.reporter.error('invalid RFC number %s' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum sn = nodes.strong('RFC '+text, 'RFC '+text) rn = nodes.reference('', '', refuri=ref) rn += sn return [indexnode, targetnode, rn], [] roles.register_canonical_role('envvar', indexmarkup_role) roles.register_local_role('pep', indexmarkup_role) roles.register_local_role('rfc', indexmarkup_role) # default is `literal` innernodetypes = { 'ref': nodes.emphasis, 'term': nodes.emphasis, 'token': nodes.strong, 'envvar': nodes.strong, 'option': addnodes.literal_emphasis, } def _fix_parens(typ, text, env): if typ in ('func', 'meth', 'cfunc'):