Example #1
0
 def role(name, rawtext, text, lineno, inliner, options={}, content=[]):
     text_has_explicit_title, link_text, link = split_explicit_title(text)
     pattern_has_explicit_title, pattern_text, pattern_link = split_explicit_title(
         pattern)
     url = pattern_link.format(link)
     if not text_has_explicit_title and pattern_has_explicit_title:
         link_text = pattern_text.format(link)
     node = nodes.reference(rawtext, link_text, refuri=url, **options)
     return [node], []
Example #2
0
def linklang_role(name,
                  rawtext,
                  text,
                  lineno,
                  inliner,
                  options={},
                  content=[]):

    unescaped_text = utils.unescape(text)
    has_explicit_title, rawtitle, lang_prefix_url \
            = split_explicit_title(unescaped_text)

    m = lang_prefixed_web_url_re_obj.match(lang_prefix_url)
    assert m, ('%s is not a valid URL for "linklang" role, http or https ' \
            + 'URL with optional language code + hyphen prefix expected ' \
            + '(e.g. fr-http://www.frenchwebsite.fr)') % lang_prefix_url

    url = m.group(2)
    if m.group(1):
        lang = m.group(1)[:-1]
        if has_explicit_title:
            title = rawtitle
        else:
            title = rawtitle[len(lang) + 1:]
    else:
        lang = ''
        title = rawtitle

    node = linklang_ref(rawtext, title, refuri=url, lang=lang, **options)
    return [node], []
Example #3
0
def blogref_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    # thanks to http://docutils.sourceforge.net/docs/howto/rst-roles.html
    # this code originally from roles.pep_reference_role
    #~ print 20130315, rawtext, text, utils.unescape(text)
    has_explicit_title, title, target = split_explicit_title(text)
    try:
        date = i2d(int(target))
    except ValueError:
        msg = inliner.reporter.error(
            'Invalid text %r: must be an integer date of style "20130315" .'
            % text, line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    #~ print repr(env)
    #~ raise Exception(20130315)
    #~ ref = inliner.document.settings.pep_base_url
           #~ + inliner.document.settings.pep_file_url_template % date)
    roles.set_classes(options)
    #~ from django.conf import settings
    #~ shown_text = settings.SITE.dtos(date)
    env = inliner.document.settings.env
    if not has_explicit_title:
        title = date.strftime(env.settings.get('today_fmt', '%Y-%m-%d'))
    title = utils.unescape(title)
    return [nodes.reference(rawtext, title,
                            refuri=get_blog_url(env, date),
                            **options)], []
Example #4
0
 def DocumentRole(typ,
                  rawtext,
                  text,
                  lineno,
                  inliner,
                  options={},
                  content=[]):
     # type: (unicode, unicode, unicode, int, Inliner, Dict, List[unicode]) -> Tuple[List[nodes.Node], List[nodes.Node]]  # NOQA
     env = inliner.document.settings.env
     # split title and target in role content
     has_explicit_title, title, target = split_explicit_title(text)
     title = utils.unescape(title)
     target = pattern.format(utils.unescape(target))
     # create the reference node
     refnode = addnodes.pending_xref(rawtext,
                                     reftype='doc',
                                     refdomain='std',
                                     refexplicit=has_explicit_title)
     # we may need the line number for warnings
     set_role_source_info(inliner, lineno, refnode)  # type: ignore
     # now that the target and title are finally determined, set them
     refnode['reftarget'] = target
     refnode += nodes.inline(rawtext, title, classes=['xref', 'doc'])
     # we also need the source document
     refnode['refdoc'] = env.docname
     refnode['refwarn'] = True
     return [refnode], []
Example #5
0
def php_class_role(typ, rawtext, text, lineno, inliner, options={},
                   content=[]):
    text = utils.unescape(text)
    env = inliner.document.settings.env
    base_url = env.app.config.api_url
    has_explicit_title, title, full_class = split_explicit_title(text)

    try:
        full_url = base_url % full_class.replace('\\', '/') + '.html'
    except (TypeError, ValueError):
        env.warn(
            env.docname, 'unable to expand %s api_url with base '
            'URL %r, please make sure the base contains \'%%s\' '
            'exactly once' % (typ, base_url))
        full_url = base_url + utils.escape(full_class)
    if not has_explicit_title:
        class_name = full_class.lstrip('\\')
        ns = class_name.rfind('\\')
        if ns != -1:
            class_name = class_name[ns + 1:]
        title = class_name
    list = [
        nodes.reference(
            title, title, internal=False, refuri=full_url, reftitle=full_class)
    ]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
Example #6
0
def php_phpfunction_role(typ,
                         rawtext,
                         text,
                         lineno,
                         inliner,
                         options={},
                         content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, full_function = split_explicit_title(text)

    full_url = 'http://php.net/manual/en/function.%s.php' % lower(
        full_function.replace('_', '-'))

    if not has_explicit_title:
        title = full_function
    list = [
        nodes.reference(
            title,
            title,
            internal=False,
            refuri=full_url,
            reftitle=full_function)
    ]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
Example #7
0
def index_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    # create new reference target
    env = inliner.document.settings.env
    targetid = 'index-%s' % env.new_serialno('index')
    targetnode = nodes.target('', '', ids=[targetid])
    # split text and target in role content
    has_explicit_title, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    # if an explicit target is given, we can process it as a full entry
    if has_explicit_title:
        entries = process_index_entry(target, targetid)
    # otherwise we just create a "single" entry
    else:
        # but allow giving main entry
        main = ''
        if target.startswith('!'):
            target = target[1:]
            title = title[1:]
            main = 'main'
        entries = [('single', target, targetid, main)]
    indexnode = addnodes.index()
    indexnode['entries'] = entries
    set_role_source_info(inliner, lineno, indexnode)
    textnode = nodes.Text(title, title)
    return [indexnode, targetnode, textnode], []
Example #8
0
def coderef_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, target = split_explicit_title(text)
    try:
        modname, name = target.rsplit('.', 1)
    except ValueError:
        raise Exception("Don't know how to import name %s" % target)
    mod = import_module(modname)

    try:
        value = getattr(mod, name, None)
    except AttributeError:
        raise Exception("No name '%s' in module '%s'" % (name, modname))
    #~ raise Exception("20130908 %s " % lines)
    if isinstance(value, type):
        if value.__module__ != modname:
            raise Exception("20130908 %r != %r" % (value.__module__, modname))

    url = srcref(mod)

    lines, line_no = inspect.getsourcelines(value)
    if line_no:
        url += "#" + str(line_no)
    if not has_explicit_title:
        pass
    pnode = nodes.reference(title, title, internal=False, refuri=url)
    return [pnode], []
Example #9
0
def php_method_role(typ,
                    rawtext,
                    text,
                    lineno,
                    inliner,
                    options={},
                    content=[]):
    text = utils.unescape(text)
    env = inliner.document.settings.env
    has_explicit_title, title, class_and_method = split_explicit_title(text)

    ns = class_and_method.rfind('::')
    full_class = class_and_method[:ns]
    method = class_and_method[ns + 2:]
    backslash = full_class.rfind('\\')
    namespace = full_class[:backslash]
    class_name = full_class[backslash + 1:]

    if len(re.findall(r'[^\\]\\[^\\]', rawtext)) > 0:
        env.warn(env.docname, 'backslash not escaped in %s' % rawtext, lineno)

    full_url = build_url('method', namespace, class_name, method, inliner)

    if not has_explicit_title:
        title = method + '()'
    list = [
        nodes.reference(title,
                        title,
                        internal=False,
                        refuri=full_url,
                        reftitle=full_class + '::' + method + '()')
    ]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
Example #10
0
    def __call__(self, name, rawtext, text, lineno, inliner,
                 options={}, content=[]):

        text = docutils.utils.unescape(text)
        has_title, title, reftext = split_explicit_title(text)

        warnings = []
        try:
            where, what = self.find_ref(reftext)
            url = self.to_url(where, what)
            if not has_title:
                title = self.to_title(where, what)
        except JavarefError as e:
            url = None
            warnings.append(e.reason)

        if url:
            # if no scheme, assume a local path relative to the src root
            if not urlparse(url).scheme:
                docdir = os.path.dirname(inliner.document.current_source)
                if docdir != self.env.srcdir:
                    url = os.path.relpath(self.env.srcdir, docdir) + '/' + url

            ref = docutils.nodes.reference('', '', internal=False, refuri=url)
            ref.append(docutils.nodes.literal(rawsource=title, text=title))
        else:
            ref = docutils.nodes.literal(rawsource=title, text=title)

        return [ref], [inliner.reporter.warning(w, line=lineno) for w in warnings]
Example #11
0
    def make_node(self, name: str, issue_no: str, config: Config, options=None):
        if issue_no in ("-", "0"):
            return None

        options = options or {}

        has_explicit_title, title, target = split_explicit_title(issue_no)

        if has_explicit_title:
            issue_no = str(target)

        repo_match = self.EXTERNAL_REPO_REGEX.match(issue_no)

        if repo_match:
            # External repo
            group, project, original_separator, issue_no = repo_match.groups()
            text = f"{group}/{project}{self.format_text(config, issue_no)}"
            ref = _get_uri(
                self.uri_config,
                config,
                issue_no,
                (group, project),
            )
        else:
            text = self.format_text(config, issue_no)
            ref = _get_uri(self.uri_config, config, issue_no)
        if has_explicit_title:
            return nodes.reference(text=title, refuri=ref, **options)
        else:
            return nodes.reference(text=text, refuri=ref, **options)
Example #12
0
def blogref_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """
    Inserts a reference to the blog entry of the specified date.
    
    Instead of writing ``:doc:`/blog/2011/0406```
    it is better to write ``:blogref:`20110406```
    because the latter works between Sphinx trees and also supports archived blog entries.
    
    """
    # thanks to http://docutils.sourceforge.net/docs/howto/rst-roles.html
    # this code originally from roles.pep_reference_role
    #~ print 20130315, rawtext, text, utils.unescape(text)
    has_explicit_title, title, target = split_explicit_title(text)
    try:
        date = i2d(int(target))
    except ValueError:
        msg = inliner.reporter.error(
            'Invalid text %r: must be an integer date of style "20130315" .'
            % text, line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    #~ print repr(env)
    #~ raise Exception(20130315)
    #~ ref = inliner.document.settings.pep_base_url
           #~ + inliner.document.settings.pep_file_url_template % date)
    roles.set_classes(options)
    #~ from django.conf import settings
    #~ shown_text = settings.SITE.dtos(date)
    env = inliner.document.settings.env
    if not has_explicit_title:
        title = date.strftime(env.settings.get('today_fmt', '%Y-%m-%d'))
    title = utils.unescape(title)
    return [nodes.reference(rawtext, title,
                            refuri=get_blog_url(date),
                            **options)], []
Example #13
0
    def icon_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
        """Docutils role which instantiates an IconNode."""
        errors = []
        has_explicit_title, label, icon_name = split_explicit_title(text)
        if icon_name not in icon_set.icons:
            msg = 'Unknown {} icon: {}'.format(typ, icon_name)
            errors.append(inliner.reporter.error(msg, line=lineno))

        label = label if has_explicit_title else class_to_label(icon_name)
        config = inliner.document.settings.env.config

        # Some MMS icon fonts contain an emblem; e.g. an "add" or "edit" emblem in one corner.
        # Try to find such a suffix, and split it off.
        emblem = next(
            (suffix for suffix in ALL_SUFFIXES if icon_name.endswith(suffix)),
            '')
        if emblem:
            icon_name = icon_name[:len(icon_name) - len(emblem)]
            emblem = emblem.lstrip('-')

        if config._raw_config['tags'].eval_condition('html'):
            return [
                IconNode(icon_name=icon_name, label=label, mms_emblem=emblem)
            ], []

        return [nodes.Text(label)], errors
Example #14
0
def coderef_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, target = split_explicit_title(text)
    try:
        modname, name = target.rsplit('.', 1)
    except ValueError:
        raise Exception("Don't know how to import name %s" % target)
    mod = import_module(modname)

    try:
        value = getattr(mod, name, None)
    except AttributeError:
        raise Exception("No name '%s' in module '%s'" % (name, modname))
    #~ raise Exception("20130908 %s " % lines)
    if isinstance(value, type):
        if value.__module__ != modname:
            raise Exception("20130908 %r != %r" % (value.__module__, modname))

    url = srcref(mod)

    lines, line_no = inspect.getsourcelines(value)
    if line_no:
        url += "#" + str(line_no)
    if not has_explicit_title:
        pass
    pnode = nodes.reference(title, title, internal=False, refuri=url)
    return [pnode], []
Example #15
0
def wikipedia_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    has_title, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    target = target.replace(' ', '_')
    refnode = nodes.reference(title, title, refuri=WIKIPEDIA_URI % target)
    return [refnode], []
Example #16
0
def php_method_role(typ,
                    rawtext,
                    text,
                    lineno,
                    inliner,
                    options={},
                    content=[]):
    text = utils.unescape(text)
    env = inliner.document.settings.env
    base_url = env.app.config.api_url
    has_explicit_title, title, class_and_method = split_explicit_title(text)

    ns = class_and_method.rfind('::')
    full_class = class_and_method[:ns]
    method = class_and_method[ns + 2:]

    try:
        full_url = base_url % full_class.replace('\\', '/')
    except (TypeError, ValueError):
        env.warn(
            env.docname, 'unable to expand %s api_url with base '
            'URL %r, please make sure the base contains \'%%s\' '
            'exactly once' % (typ, base_url))
        full_url = base_url + utils.escape(full_class)
    if not has_explicit_title:
        title = method + '()'
    list = [
        nodes.reference(title,
                        title,
                        internal=False,
                        refuri=full_url,
                        reftitle=full_class + '::' + method + '()')
    ]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
Example #17
0
def user_role(name, rawtext, text, lineno, inliner, options=None, content=None):
    """Sphinx role for linking to a user profile. Defaults to linking to
    Github profiles, but the profile URIS can be configured via the
    ``issues_user_uri`` config value.

    Examples: ::

        :user:`sloria`

    Anchor text also works: ::

        :user:`Steven Loria <sloria>`
    """
    options = options or {}
    content = content or []
    has_explicit_title, title, target = split_explicit_title(text)

    target = utils.unescape(target).strip()
    title = utils.unescape(title).strip()
    config = inliner.document.settings.env.app.config
    if config.issues_user_uri:
        ref = config.issues_user_uri.format(user=target)
    else:
        ref = "https://github.com/{0}".format(target)
    if has_explicit_title:
        text = title
    else:
        text = "@{0}".format(target)

    link = nodes.reference(text=text, refuri=ref, **options)
    return [link], []
def user_role(name,
              rawtext,
              text,
              lineno,
              inliner,
              options=None,
              content=None):
    """Sphinx role for linking to a user profile. Defaults to linking to
    Github profiles, but the profile URIS can be configured via the
    ``issues_user_uri`` config value.
    Examples: ::
        :user:`sloria`
    Anchor text also works: ::
        :user:`Steven Loria <sloria>`
    """
    options = options or {}
    content = content or []
    has_explicit_title, title, target = split_explicit_title(text)

    target = utils.unescape(target).strip()
    title = utils.unescape(title).strip()
    config = inliner.document.settings.env.app.config
    if config.issues_user_uri:
        ref = config.issues_user_uri.format(user=target)
    else:
        ref = "https://github.com/{0}".format(target)
    if has_explicit_title:
        text = title
    else:
        text = "@{0}".format(target)

    link = nodes.reference(text=text, refuri=ref, **options)
    return [link], []
Example #19
0
def php_phpmethod_role(typ,
                       rawtext,
                       text,
                       lineno,
                       inliner,
                       options={},
                       content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, class_and_method = split_explicit_title(text)

    ns = class_and_method.rfind('::')
    full_class = class_and_method[:ns]
    method = class_and_method[ns + 2:]

    full_url = 'http://php.net/manual/en/%s.%s.php' % (lower(full_class),
                                                       lower(method))

    if not has_explicit_title:
        title = full_class + '::' + method + '()'
    list = [
        nodes.reference(title,
                        title,
                        internal=False,
                        refuri=full_url,
                        reftitle=full_class)
    ]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
Example #20
0
def php_class_role(typ,
                   rawtext,
                   text,
                   lineno,
                   inliner,
                   options={},
                   content=[]):
    text = utils.unescape(text)
    env = inliner.document.settings.env
    has_explicit_title, title, full_class = split_explicit_title(text)
    backslash = full_class.rfind('\\')
    namespace = full_class[:backslash]
    class_name = full_class[backslash + 1:]

    if len(re.findall(r'[^\\]\\[^\\]', rawtext)) > 0:
        env.warn(env.docname, 'backslash not escaped in %s' % rawtext, lineno)

    full_url = build_url('class', namespace, class_name, None, inliner)

    if not has_explicit_title:
        class_name = full_class.lstrip('\\')
        ns = class_name.rfind('\\')
        if ns != -1:
            class_name = class_name[ns + 1:]
        title = class_name
    list = [
        nodes.reference(title,
                        title,
                        internal=False,
                        refuri=full_url,
                        reftitle=full_class)
    ]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
	def find_doxygen_link(name, rawtext, text, lineno, inliner, options={}, content=[]):
		text = utils.unescape(text)
		# from :name:`title <part>`
		has_explicit_title, title, part = split_explicit_title(text)
		warning_messages = []
		if tag_file:
			url = find_url(tag_file, part)
			try:
				url = find_url2(app.env.doxylink_cache[cache_name]['mapping'], part)
			except LookupError as error:
				warning_messages.append('Error while parsing `%s`. Is not a well-formed C++ function call or symbol. If this is not the case, it is a doxylink bug so please report it. Error reported was: %s' % (part, error))
			if url:
				
				#If it's an absolute path then the link will work regardless of the document directory
				#Also check if it is a URL (i.e. it has a 'scheme' like 'http' or 'file')
				if os.path.isabs(rootdir) or urlparse.urlparse(rootdir).scheme:
					full_url = join(rootdir, url['file'])
				#But otherwise we need to add the relative path of the current document to the root source directory to the link
				else:
					relative_path_to_docsrc = os.path.relpath(app.env.srcdir, os.path.dirname(inliner.document.current_source))
					full_url = join(relative_path_to_docsrc, '/', rootdir, url['file']) #We always use the '/' here rather than os.sep since this is a web link avoids problems like documentation/.\../library/doc/ (mixed slashes)
				
				if url['kind'] == 'function' and app.config.add_function_parentheses and not normalise(title)[1]:
					title = join(title, '()')
				
				pnode = nodes.reference(title, title, internal=False, refuri=full_url)
				return [pnode], []
			#By here, no match was found
			warning_messages.append('Could not find match for `%s` in `%s` tag file' % (part, tag_filename))
		else:
			warning_messages.append('Could not find match for `%s` because tag file not found' % (part))
		
		pnode = nodes.inline(rawsource=title, text=title)
		return [pnode], [inliner.reporter.warning(message, line=lineno) for message in warning_messages]
Example #22
0
def index_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner,
               options: Dict = {}, content: List[str] = []
               ) -> Tuple[List[Node], List[system_message]]:
    warnings.warn('index_role() is deprecated.  Please use Index class instead.',
                  RemovedInSphinx40Warning, stacklevel=2)
    # create new reference target
    env = inliner.document.settings.env
    targetid = 'index-%s' % env.new_serialno('index')
    targetnode = nodes.target('', '', ids=[targetid])
    # split text and target in role content
    has_explicit_title, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    # if an explicit target is given, we can process it as a full entry
    if has_explicit_title:
        entries = process_index_entry(target, targetid)
    # otherwise we just create a "single" entry
    else:
        # but allow giving main entry
        main = ''
        if target.startswith('!'):
            target = target[1:]
            title = title[1:]
            main = 'main'
        entries = [('single', target, targetid, main, None)]
    indexnode = addnodes.index()
    indexnode['entries'] = entries
    set_role_source_info(inliner, lineno, indexnode)
    textnode = nodes.Text(title, title)
    return [indexnode, targetnode, textnode], []
Example #23
0
def paper_ref_role(
    typ: str,
    rawtext: str,
    text: str,
    lineno: int,
    inliner,
    options: Dict = {},
    content: List[str] = [],
):
    """
    Parse :paper:`xxx`. Similar to the "extlinks" sphinx extension.
    """
    from docutils import nodes, utils
    from sphinx.util.nodes import split_explicit_title

    text = utils.unescape(text)
    has_explicit_title, title, link = split_explicit_title(text)
    link = link.lower()
    if link not in _PAPER_DATA:
        inliner.reporter.warning("Cannot find paper " + link)
        paper_url, paper_title = "#", link
    else:
        paper_url, paper_title = _PAPER_DATA[link]
        if "/" not in paper_url:
            paper_url = "https://arxiv.org/abs/" + paper_url
    if not has_explicit_title:
        title = paper_title
    pnode = nodes.reference(title, title, internal=False, refuri=paper_url)
    return [pnode], []
Example #24
0
 def __call__(self,
              typ,
              rawtext,
              text,
              lineno,
              inliner,
              options={},
              content=[]):
     env = inliner.document.settings.env
     if not typ:
         typ = env.temp_data.get('default_role')
         if not typ:
             typ = env.config.default_role
         if not typ:
             raise SphinxError('cannot determine default role!')
     else:
         typ = typ.lower()
     if ':' not in typ:
         domain, role = '', typ
         classes = ['xref', role]
     else:
         domain, role = typ.split(':', 1)
         classes = ['xref', domain, '%s-%s' % (domain, role)]
     # if the first character is a bang, don't cross-reference at all
     if text[0:1] == '!':
         text = utils.unescape(text)[1:]
         if self.fix_parens:
             text, tgt = self._fix_parens(env, False, text, "")
         innernode = self.innernodeclass(rawtext, text, classes=classes)
         return self.result_nodes(inliner.document,
                                  env,
                                  innernode,
                                  is_ref=False)
     # split title and target in role content
     has_explicit_title, title, target = split_explicit_title(text)
     title = utils.unescape(title)
     target = utils.unescape(target)
     # fix-up title and target
     if self.lowercase:
         target = target.lower()
     if self.fix_parens:
         title, target = self._fix_parens(env, has_explicit_title, title,
                                          target)
     # create the reference node
     refnode = self.nodeclass(rawtext,
                              reftype=role,
                              refdomain=domain,
                              refexplicit=has_explicit_title)
     # we may need the line number for warnings
     set_role_source_info(inliner, lineno, refnode)
     title, target = self.process_link(env, refnode, has_explicit_title,
                                       title, target)
     # now that the target and title are finally determined, set them
     refnode['reftarget'] = target
     refnode += self.innernodeclass(rawtext, title, classes=classes)
     # we also need the source document
     refnode['refdoc'] = env.docname
     refnode['refwarn'] = self.warn_dangling
     # result_nodes allow further modification of return values
     return self.result_nodes(inliner.document, env, refnode, is_ref=True)
Example #25
0
def indexmarkup_role(typ, rawtext, text, lineno, inliner,
                     options={}, content=[]):
    """Role for PEP/RFC references that generate an index entry."""
    env = inliner.document.settings.env
    if not typ:
        typ = env.config.default_role
    else:
        typ = typ.lower()
    has_explicit_title, title, target = split_explicit_title(text)  # type: bool, unicode, unicode  # NOQA
    title = utils.unescape(title)
    target = utils.unescape(target)
    targetid = 'index-%s' % env.new_serialno('index')
    indexnode = addnodes.index()
    targetnode = nodes.target('', '', ids=[targetid])
    inliner.document.note_explicit_target(targetnode)
    if typ == 'pep':
        indexnode['entries'] = [
            ('single', _('Python Enhancement Proposals; PEP %s') % target,
             targetid, '', None)]
        anchor = ''  # type: unicode
        anchorindex = target.find('#')
        if anchorindex > 0:
            target, anchor = target[:anchorindex], target[anchorindex:]
        if not has_explicit_title:
            title = "PEP " + utils.unescape(title)
        try:
            pepnum = int(target)
        except ValueError:
            msg = inliner.reporter.error('invalid PEP number %s' % target,
                                         line=lineno)
            prb = inliner.problematic(rawtext, rawtext, msg)
            return [prb], [msg]
        ref = inliner.document.settings.pep_base_url + 'pep-%04d' % pepnum
        sn = nodes.strong(title, title)
        rn = nodes.reference('', '', internal=False, refuri=ref + anchor,
                             classes=[typ])
        rn += sn
        return [indexnode, targetnode, rn], []
    elif typ == 'rfc':
        indexnode['entries'] = [
            ('single', 'RFC; RFC %s' % target, targetid, '', None)]
        anchor = ''
        anchorindex = target.find('#')
        if anchorindex > 0:
            target, anchor = target[:anchorindex], target[anchorindex:]
        if not has_explicit_title:
            title = "RFC " + utils.unescape(title)
        try:
            rfcnum = int(target)
        except ValueError:
            msg = inliner.reporter.error('invalid RFC number %s' % target,
                                         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(title, title)
        rn = nodes.reference('', '', internal=False, refuri=ref + anchor,
                             classes=[typ])
        rn += sn
        return [indexnode, targetnode, rn], []
Example #26
0
def indexmarkup_role(typ, rawtext, text, lineno, inliner,
                     options={}, content=[]):
    """Role for PEP/RFC references that generate an index entry."""
    env = inliner.document.settings.env
    if not typ:
        typ = env.config.default_role
    else:
        typ = typ.lower()
    has_explicit_title, title, target = split_explicit_title(text)  # type: bool, unicode, unicode  # NOQA
    title = utils.unescape(title)
    target = utils.unescape(target)
    targetid = 'index-%s' % env.new_serialno('index')
    indexnode = addnodes.index()
    targetnode = nodes.target('', '', ids=[targetid])
    inliner.document.note_explicit_target(targetnode)
    if typ == 'pep':
        indexnode['entries'] = [
            ('single', _('Python Enhancement Proposals; PEP %s') % target,
             targetid, '', None)]
        anchor = ''  # type: unicode
        anchorindex = target.find('#')
        if anchorindex > 0:
            target, anchor = target[:anchorindex], target[anchorindex:]
        if not has_explicit_title:
            title = "PEP " + utils.unescape(title)
        try:
            pepnum = int(target)
        except ValueError:
            msg = inliner.reporter.error('invalid PEP number %s' % target,
                                         line=lineno)
            prb = inliner.problematic(rawtext, rawtext, msg)
            return [prb], [msg]
        ref = inliner.document.settings.pep_base_url + 'pep-%04d' % pepnum
        sn = nodes.strong(title, title)
        rn = nodes.reference('', '', internal=False, refuri=ref+anchor,
                             classes=[typ])
        rn += sn
        return [indexnode, targetnode, rn], []
    elif typ == 'rfc':
        indexnode['entries'] = [
            ('single', 'RFC; RFC %s' % target, targetid, '', None)]
        anchor = ''
        anchorindex = target.find('#')
        if anchorindex > 0:
            target, anchor = target[:anchorindex], target[anchorindex:]
        if not has_explicit_title:
            title = "RFC " + utils.unescape(title)
        try:
            rfcnum = int(target)
        except ValueError:
            msg = inliner.reporter.error('invalid RFC number %s' % target,
                                         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(title, title)
        rn = nodes.reference('', '', internal=False, refuri=ref+anchor,
                             classes=[typ])
        rn += sn
        return [indexnode, targetnode, rn], []
Example #27
0
def bitbucket_role(role,
                   rawtext,
                   text,
                   lineno,
                   inliner,
                   options=None,
                   content=None):

    if options is None:
        options = {}
    if content is None:
        content = []
    out = '<span class="icon-holder">'
    text = utils.unescape(text)
    has_explicit_title, title, part = split_explicit_title(text)
    with open("source/exts/icons/bitbucket.svg", "r") as svg:
        out = out + svg.read() + "</span>"
        node = raw('', text=out, format='html')
    set_classes(options)
    if not has_explicit_title:
        node = reference(rawtext,
                         text,
                         refuri="https://bitbucket.org/" + text,
                         **options)
    else:
        node = reference(title,
                         tilte,
                         refuri="https://bitbucket.org/" + part,
                         **options)
    node.insert(0, raw('', text=out, format='html'))

    return [node], []
Example #28
0
 def role(
         typ: str,
         rawtext: str,
         text: str,
         lineno: int,
         inliner: Inliner,
         options: Dict = {},
         content: List[str] = []
 ) -> Tuple[List[Node], List[system_message]]:
     text = utils.unescape(text)
     has_explicit_title, title, part = split_explicit_title(text)
     try:
         full_url = base_url % part
     except (TypeError, ValueError):
         inliner.reporter.warning(
             'unable to expand %s extlink with base URL %r, please make '
             'sure the base contains \'%%s\' exactly once' %
             (typ, base_url),
             line=lineno)
         full_url = base_url + part
     if not has_explicit_title:
         if prefix is None:
             title = full_url
         else:
             title = prefix + part
     pnode = nodes.reference(title, title, internal=False, refuri=full_url)
     return [pnode], []
Example #29
0
def wiki_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
    has_explicit, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    node = nodes.reference(title, title,
        refuri=f"https://en.wikipedia.org/wiki/{target}", **options)
    return [node], []
Example #30
0
def php_class_role(typ,
                   rawtext,
                   text,
                   lineno,
                   inliner,
                   options={},
                   content=[]):
    text = utils.unescape(text)
    env = inliner.document.settings.env
    base_url = env.app.config.api_url
    has_explicit_title, title, full_class = split_explicit_title(text)

    try:
        full_url = base_url % full_class.replace('\\', '/') + '.html'
    except (TypeError, ValueError):
        env.warn(
            env.docname, 'unable to expand %s api_url with base '
            'URL %r, please make sure the base contains \'%%s\' '
            'exactly once' % (typ, base_url))
        full_url = base_url + utils.escape(full_class)
    if not has_explicit_title:
        class_name = full_class.lstrip('\\')
        ns = class_name.rfind('\\')
        if ns != -1:
            class_name = class_name[ns + 1:]
        title = class_name
    list = [
        nodes.reference(title,
                        title,
                        internal=False,
                        refuri=full_url,
                        reftitle=full_class)
    ]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
Example #31
0
    def role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
        text = utils.unescape(text)

        has_explicit_title, title, refspec = split_explicit_title(text)

        # TODO: this code with exception handling should go get_url
        #       the warning should style be generated with typ and lineno parameters,
        try:
            full_url = get_url(url_pattern, refspec)
        except (TypeError, ValueError):
            # TODO: check which exception can be raised by get_url and add them here
            inliner.reporter.warning(
                'unable to expand %s extlink with base URL %r, please make '
                'sure the base contains \'%%s\' exactly once' %
                (typ, url_pattern),
                line=lineno)
            full_url = url_pattern + refspec

        if not has_explicit_title:
            if display_pattern is None:
                title = full_url
            else:
                title = get_display(display_pattern, refspec)
        pnode = nodes.reference(title, title, internal=False, refuri=full_url)
        return [pnode], []
Example #32
0
def index_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    # create new reference target
    env = inliner.document.settings.env
    targetid = 'index-%s' % env.new_serialno('index')
    targetnode = nodes.target('', '', ids=[targetid])
    # split text and target in role content
    has_explicit_title, title, target = split_explicit_title(text)
    title = utils.unescape(title)
    target = utils.unescape(target)
    # if an explicit target is given, we can process it as a full entry
    if has_explicit_title:
        entries = process_index_entry(target, targetid)
    # otherwise we just create a "single" entry
    else:
        # but allow giving main entry
        main = ''
        if target.startswith('!'):
            target = target[1:]
            title = title[1:]
            main = 'main'
        entries = [('single', target, targetid, main)]
    indexnode = addnodes.index()
    indexnode['entries'] = entries
    set_role_source_info(inliner, lineno, indexnode)
    textnode = nodes.Text(title, title)
    return [indexnode, targetnode, textnode], []
Example #33
0
def blogref_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    # thanks to http://docutils.sourceforge.net/docs/howto/rst-roles.html
    # this code originally from roles.pep_reference_role
    #~ print 20130315, rawtext, text, utils.unescape(text)
    has_explicit_title, title, target = split_explicit_title(text)
    try:
        date = i2d(int(target))
    except ValueError:
        msg = inliner.reporter.error(
            'Invalid text %r: must be an integer date of style "20130315" .'
            % text, line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
    #~ print repr(env)
    #~ raise Exception(20130315)
    #~ ref = inliner.document.settings.pep_base_url
           #~ + inliner.document.settings.pep_file_url_template % date)
    roles.set_classes(options)
    #~ from django.conf import settings
    #~ shown_text = settings.SITE.dtos(date)
    env = inliner.document.settings.env
    if not has_explicit_title:
        title = date.strftime(env.settings.get('today_fmt', '%Y-%m-%d'))
    title = utils.unescape(title)
    return [nodes.reference(rawtext, title,
                            refuri=get_blog_url(env, date),
                            **options)], []
Example #34
0
	def find_doxygen_link(name, rawtext, text, lineno, inliner, options={}, content=[]):
		text = utils.unescape(text)
		# from :name:`title <part>`
		has_explicit_title, title, part = split_explicit_title(text)
		warning_messages = []
		if tag_file:
			url = find_url(tag_file, part)
			try:
				url = find_url2(app.env.doxylink_cache[cache_name]['mapping'], part)
			except LookupError as error:
				warning_messages.append('Error while parsing `%s`. Is not a well-formed C++ function call or symbol. If this is not the case, it is a doxylink bug so please report it. Error reported was: %s' % (part, error))
			if url:
				
				#If it's an absolute path then the link will work regardless of the document directory
				#Also check if it is a URL (i.e. it has a 'scheme' like 'http' or 'file')
				if os.path.isabs(rootdir) or urlparse.urlparse(rootdir).scheme:
					full_url = join(rootdir, url['file'])
				#But otherwise we need to add the relative path of the current document to the root source directory to the link
				else:
					relative_path_to_docsrc = os.path.relpath(app.env.srcdir, os.path.dirname(inliner.document.current_source))
					full_url = join(relative_path_to_docsrc, '/', rootdir, url['file']) #We always use the '/' here rather than os.sep since this is a web link avoids problems like documentation/.\../library/doc/ (mixed slashes)
				
				if url['kind'] == 'function' and app.config.add_function_parentheses and not normalise(title)[1]:
					title = join(title, '()')
				
				pnode = nodes.reference(title, title, internal=False, refuri=full_url)
				return [pnode], []
			#By here, no match was found
			warning_messages.append('Could not find match for `%s` in `%s` tag file' % (part, tag_filename))
		else:
			warning_messages.append('Could not find match for `%s` because tag file not found' % (part))
		
		pnode = nodes.inline(rawsource=title, text=title)
		return [pnode], [inliner.reporter.warning(message, line=lineno) for message in warning_messages]
Example #35
0
def arxiv_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, part = split_explicit_title(text)
    full_url = "https://arxiv.org/abs/" + part
    if not has_explicit_title:
        title = "arXiv:" + part
    pnode = nodes.reference(title, title, internal=False, refuri=full_url)
    return [pnode], []
Example #36
0
def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    has_t, title, target = split_explicit_title(text)
    title = docutils.utils.unescape(title)
    target = docutils.utils.unescape(target)
    refnode = docutils.nodes.reference(title,
                                       title,
                                       refuri=SOURCE_URI + target)
    return [refnode], []
Example #37
0
 def role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
     text = utils.unescape(text)
     has_explicit_title, symbol, title = split_explicit_title(text)
     try:
         kind, filename, anchor = lookup_url(app, tagfile, symbol)
     except KeyError, e:
         inliner.reporter.warning(unicode(e.args[0]), line=lineno)
         return [nodes.Text(title)], []
Example #38
0
def arxiv_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, part = split_explicit_title(text)
    full_url = 'https://arxiv.org/abs/' + part
    if not has_explicit_title:
        title = 'arXiv:' + part
    pnode = nodes.reference(title, title, internal=False, refuri=full_url)
    return [pnode], []
Example #39
0
def doi_role(typ, rawtext, text, lineno, inliner, options=None, content=()):
    text = utils.unescape(text)
    has_explicit_title, title, part = split_explicit_title(text)
    full_url = 'https://doi.org/' + part
    if not has_explicit_title:
        title = 'DOI:' + part
    pnode = nodes.reference(title, title, internal=False, refuri=full_url)
    return [pnode], []
Example #40
0
def tex_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """Role for inserting latex code as is."""
    text = utils.unescape(text, restore_backslashes=True)
    has_explicit, texsnipet, target = split_explicit_title(text)
    
    pnode = nodes.raw(rawtext, texsnipet, format='latex')

    return [pnode], []
Example #41
0
def gh_issue(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, part = split_explicit_title(text)
    if not has_explicit_title:
        title = 'issue #%s' % part
    full_url = 'https://github.com/cms-dev/cms/issues/%s' % part

    retnode = nodes.reference(title, title, internal=False, refuri=full_url, **options)
    return [retnode], []
Example #42
0
    def gh_blob(typ, rawtext, text, lineno, inliner, options={}, content=[]):
        text = utils.unescape(text)
        has_explicit_title, title, part = split_explicit_title(text)
        if not has_explicit_title:
            title = part
        full_url = 'https://github.com/cms-dev/cms/blob/v%s/%s' % (app.config.release, part)

        refnode = nodes.reference(title, title, internal=False, refuri=full_url, **options)
        return [refnode], []
Example #43
0
def php_phpclass_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, full_class = split_explicit_title(text)

    full_url = 'http://php.net/manual/en/class.%s.php' % string.lower(full_class)

    if not has_explicit_title:
        title = full_class
    list = [nodes.reference(title, title, internal=False, refuri=full_url, reftitle=full_class)]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
Example #44
0
    def gh_tree(typ, rawtext, text, lineno, inliner, options={}, content=[]):
        text = utils.unescape(text)
        has_explicit_title, title, part = split_explicit_title(text)
        if not has_explicit_title:
            title = part
        full_url = 'https://github.com/cms-dev/cms/tree/v%s/%s' % (app.config.release, part)

        refnode = nodes.reference(title, title, internal=False, refuri=full_url, **options)
        retnode = nodes.literal(role=typ.lower(), classes=[typ])
        retnode += refnode
        return [retnode], []
Example #45
0
def icon_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    has_explicit_title, label, target = split_explicit_title(text)
    css_class = target

    label = label if has_explicit_title else class_to_label(css_class)

    config = inliner.document.settings.env.config
    if config._raw_config['tags'].eval_condition('html'):
        return [IconNode(css_class=css_class, label=label)], []

    return [nodes.Text(label)], []
Example #46
0
def releaseref_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    config = inliner.document.settings.env.config
    text = text.replace("|version|", config.version)
    text = text.replace("|release|", config.release)

    has_explicit_title, title, target = split_explicit_title(text)
    if not has_explicit_title:
        title = os.path.basename(target)

    node = nodes.reference(rawtext, title, refuri=target, **options)

    return [node], []
 def role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
     has_explicit, title, other = split_explicit_title(utils.unescape(text))
     args = [other]
     if use_explicit:
         args.append(has_explicit)
     result = func(*args)
     if isinstance(result, (list, tuple)):
         url, title = result
     else:
         url = result
     node = nodes.raw("", u"<a href='{url}'>{title}</a>".format(title=title, url=html_escape(url)), format="html")
     return [node], []
Example #48
0
 def __call__(self, typ, rawtext, text, lineno, inliner,
              options={}, content=[]):
     # type: (unicode, unicode, unicode, int, Inliner, Dict, List[unicode]) -> Tuple[List[nodes.Node], List[nodes.Node]]  # NOQA
     env = inliner.document.settings.env
     if not typ:
         typ = env.temp_data.get('default_role')
         if not typ:
             typ = env.config.default_role
         if not typ:
             raise SphinxError('cannot determine default role!')
     else:
         typ = typ.lower()
     if ':' not in typ:
         domain, role = '', typ  # type: unicode, unicode
         classes = ['xref', role]
     else:
         domain, role = typ.split(':', 1)
         classes = ['xref', domain, '%s-%s' % (domain, role)]
     # if the first character is a bang, don't cross-reference at all
     if text[0:1] == '!':
         text = utils.unescape(text)[1:]
         if self.fix_parens:
             text, tgt = self._fix_parens(env, False, text, "")
         innernode = self.innernodeclass(rawtext, text, classes=classes)
         return self.result_nodes(inliner.document, env, innernode,
                                  is_ref=False)
     # split title and target in role content
     has_explicit_title, title, target = split_explicit_title(text)
     title = utils.unescape(title)
     target = utils.unescape(target)
     # fix-up title and target
     if self.lowercase:
         target = target.lower()
     if self.fix_parens:
         title, target = self._fix_parens(
             env, has_explicit_title, title, target)
     # create the reference node
     refnode = self.nodeclass(rawtext, reftype=role, refdomain=domain,
                              refexplicit=has_explicit_title)
     # we may need the line number for warnings
     set_role_source_info(inliner, lineno, refnode)  # type: ignore
     title, target = self.process_link(
         env, refnode, has_explicit_title, title, target)
     # now that the target and title are finally determined, set them
     refnode['reftarget'] = target
     refnode += self.innernodeclass(rawtext, title, classes=classes)
     # we also need the source document
     refnode['refdoc'] = env.docname
     refnode['refwarn'] = self.warn_dangling
     # result_nodes allow further modification of return values
     return self.result_nodes(inliner.document, env, refnode, is_ref=True)
def img_altfix(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    img_altfix_base, text = text.split(",", 1)
    has_explicit, alt, src = split_explicit_title(utils.unescape(text))
    basename = os.path.basename(src)
    if not has_explicit:
        alt = basename
    output = subprocess.check_output(["find", "-L", ".", "-name", basename], cwd=img_altfix_base)
    template = u"<img src='{src}' alt='{alt}'{altfix}>"
    altfix = ""
    for line in output.splitlines():
        altfix = u" onerror='this.onerror=null;delete this.onerror;this.src=\"{0}\";'".format(html_escape(line.lstrip(".")))
        break
    node = nodes.raw("", template.format(src=html_escape(src), alt=html_escape(alt), altfix=altfix), format="html")
    return [node], []
def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None):
    """Sphinx role for linking to a CVE on https://cve.mitre.org.
    Examples: ::
        :cve:`CVE-2018-17175`
    """
    options = options or {}
    content = content or []
    has_explicit_title, title, target = split_explicit_title(text)

    target = utils.unescape(target).strip()
    title = utils.unescape(title).strip()
    ref = "https://cve.mitre.org/cgi-bin/cvename.cgi?name={0}".format(target)
    text = title if has_explicit_title else target
    link = nodes.reference(text=text, refuri=ref, **options)
    return [link], []
Example #51
0
def php_phpmethod_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    has_explicit_title, title, class_and_method = split_explicit_title(text)

    ns = class_and_method.rfind('::')
    full_class = class_and_method[:ns]
    method = class_and_method[ns+2:]

    full_url = 'http://php.net/manual/en/%s.%s.php' % (string.lower(full_class), string.lower(method))

    if not has_explicit_title:
        title = full_class + '::' + method + '()'
    list = [nodes.reference(title, title, internal=False, refuri=full_url, reftitle=full_class)]
    pnode = nodes.literal('', '', *list)
    return [pnode], []
Example #52
0
def pypi_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    """Role for linking to PyPI packages."""
    env = inliner.document.settings.env
    text = utils.unescape(text)
    has_explicit, title, target = split_explicit_title(text)
    m = re.match(r'(.*)\s+\((.*?)\)', target)
    if m:
        dist, version = m.groups()
        url = env.config.cheeseshop_url + '/' + dist + '/' + version
        if not has_explicit:
            title = '%s %s' % (dist, version)
    else:
        url = env.config.cheeseshop_url + '/' + target
    ref = nodes.reference(rawtext, title, refuri=url)
    return [ref], []
Example #53
0
def bitbucket_role(role, rawtext, text, lineno, inliner, options={}, content=[]):

    out = '<span class="icon-holder">'
    text = utils.unescape(text)
    has_explicit_title, title, part = split_explicit_title(text)
    with open("source/exts/icons/bitbucket.svg", "r") as svg:
        out = out + svg.read() + "</span>"
        node = raw('', text=out, format='html')
    set_classes(options)
    if not has_explicit_title:
        node = reference(rawtext, text, refuri="https://bitbucket.org/"+text, **options)
    else:
        node = reference(title, tilte, refuri="https://bitbucket.org/"+part, **options)
    node.insert(0, raw('', text=out, format='html'))

    return [node], []
Example #54
0
 def role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
     text = utils.unescape(text)
     has_explicit_title, title, part = split_explicit_title(text)
     try:
         full_url = base_url % part
     except (TypeError, ValueError):
         inliner.reporter.warning(
             'unable to expand %s apilink with base URL %r, please make '
             'sure the base contains \'%%s\' exactly once'
             % (typ, base_url), line=lineno)
         full_url = base_url + part
     if not has_explicit_title:
         idents = part.split(".")
         title = idents[len(idents)-1]
     pnode = nodes.reference(title, title, internal=False, refuri=full_url)
     return [pnode], []
 def role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
     text = utils.unescape(text)
     has_explicit_title, title, symbol = split_explicit_title(text)
     try:
         kind, filename, anchor = lookup_url(app, tagfile, symbol)
     except KeyError as e:
         inliner.reporter.warning(unicode(e.args[0]), line=lineno)
         return [nodes.Text(title)], []
     full_url = base_url + filename
     if anchor:
         full_url += '#' + anchor
     if not has_explicit_title:
         title = symbol
         if app.config.add_function_parentheses and kind == 'function':
             title += '()'
     pnode = nodes.reference(title, title, internal=False, refuri=full_url)
     return [pnode], []
Example #56
0
def make_wikipedia_link(name, rawtext, text, lineno, inliner,
                      options={}, content=[]):
    env = inliner.document.settings.env
    lang =  env.config.wikipedia_lang

    text = utils.unescape(text)
    has_explicit, title, target = split_explicit_title(text)
 
    m = re.match(r'\:(.*?)\:(.*)', target)
    if m:
        lang, target = m.groups()
        if not has_explicit:
            title = target
    ref = base_url % lang + urllib.quote(target.replace(' ', '_').encode('utf8'), safe='')

    node = nodes.reference(rawtext, title, refuri=ref, **options)
    return [node],[]
Example #57
0
def nicovideo_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """Role for linking to nicovideo pages."""
    text = utils.unescape(text)
    has_explicit, title, movie_id = split_explicit_title(text)

    try:
        movie = NicoVideo(movie_id)
        if has_explicit == False:
            title = movie.title

        ref = nodes.reference(rawtext, title, refuri=movie.url)
        return [ref], []
    except:
        msg = inliner.reporter.error('fail to load nicovideo: %s' % movie_id,
                                     line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]