Esempio n. 1
0
def test_init(rootdir):
    # not initialized yet
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'Hello world'
    assert _('Hello sphinx') == 'Hello sphinx'
    assert _('Hello reST') == 'Hello reST'

    # load locale1
    locale.init([rootdir / 'test-locale' / 'locale1'], 'en', 'myext')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'HELLO WORLD'
    assert _('Hello sphinx') == 'Hello sphinx'
    assert _('Hello reST') == 'Hello reST'

    # load a catalog to unrelated namespace
    locale.init([rootdir / 'test-locale' / 'locale2'], 'en', 'myext', 'mynamespace')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'HELLO WORLD'
    assert _('Hello sphinx') == 'Hello sphinx'  # nothing changed here
    assert _('Hello reST') == 'Hello reST'

    # load locale2 in addition
    locale.init([rootdir / 'test-locale' / 'locale2'], 'en', 'myext')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'HELLO WORLD'
    assert _('Hello sphinx') == 'HELLO SPHINX'
    assert _('Hello reST') == 'Hello reST'
Esempio n. 2
0
def test_init(rootdir):
    # not initialized yet
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'Hello world'
    assert _('Hello sphinx') == 'Hello sphinx'
    assert _('Hello reST') == 'Hello reST'

    # load locale1
    locale.init([rootdir / 'test-locale' / 'locale1'], 'en', 'myext')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'HELLO WORLD'
    assert _('Hello sphinx') == 'Hello sphinx'
    assert _('Hello reST') == 'Hello reST'

    # load a catalog to unrelated namespace
    locale.init([rootdir / 'test-locale' / 'locale2'], 'en', 'myext',
                'mynamespace')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'HELLO WORLD'
    assert _('Hello sphinx') == 'Hello sphinx'  # nothing changed here
    assert _('Hello reST') == 'Hello reST'

    # load locale2 in addition
    locale.init([rootdir / 'test-locale' / 'locale2'], 'en', 'myext')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'HELLO WORLD'
    assert _('Hello sphinx') == 'HELLO SPHINX'
    assert _('Hello reST') == 'Hello reST'
Esempio n. 3
0
def test_add_message_catalog(app, rootdir):
    app.config.language = 'en'
    app.add_message_catalog('myext', rootdir / 'test-locale' / 'locale1')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'HELLO WORLD'
    assert _('Hello sphinx') == 'Hello sphinx'
    assert _('Hello reST') == 'Hello reST'
Esempio n. 4
0
def test_add_message_catalog(app, rootdir):
    app.config.language = 'en'
    app.add_message_catalog('myext', rootdir / 'test-locale' / 'locale1')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'HELLO WORLD'
    assert _('Hello sphinx') == 'Hello sphinx'
    assert _('Hello reST') == 'Hello reST'
Esempio n. 5
0
from sphinx.application import Sphinx
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.errors import SphinxError
from sphinx.locale import get_translation
from sphinx.util import logging
from sphinx.util import SkipProgressMessage, progress_message
from sphinx.util.fileutil import copy_asset, copy_asset_file
from sphinx.util.matching import Matcher
from sphinx.util.osutil import ensuredir, make_filename

from sphinxcontrib.applehelp.version import __version__

package_dir = path.abspath(path.dirname(__file__))
template_dir = path.join(package_dir, 'templates')

__ = get_translation(__name__, 'console')
logger = logging.getLogger(__name__)


class AppleHelpIndexerFailed(SphinxError):
    category = __('Help indexer failed')


class AppleHelpCodeSigningFailed(SphinxError):
    category = __('Code signing failed')


class AppleHelpBuilder(StandaloneHTMLBuilder):
    """
    Builder that outputs an Apple help book.  Requires Mac OS X as it relies
    on the ``hiutil`` command line tool.
Esempio n. 6
0
def test_init_with_unknown_language(rootdir):
    locale.init([rootdir / 'test-locale' / 'locale1'], 'unknown', 'myext')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'Hello world'
    assert _('Hello sphinx') == 'Hello sphinx'
    assert _('Hello reST') == 'Hello reST'
Esempio n. 7
0
def add_to_context(app, pagename, templatename, context, doctree):
    def generate_nav_html(
        level=1,
        include_item_names=False,
        with_home_page=False,
        prev_section_numbers=None,
    ):
        # Config stuff
        config = app.env.config
        if isinstance(with_home_page, str):
            with_home_page = with_home_page.lower() == "true"

        # Grab the raw toctree object and structure it so we can manipulate it
        toc_sphinx = context["toctree"](maxdepth=-1,
                                        collapse=False,
                                        titles_only=True,
                                        includehidden=True)
        toctree = bs(toc_sphinx, "html.parser")

        # Add the master_doc page as the first item if specified
        if with_home_page:
            # Pull metadata about the master doc
            master_doc = config["master_doc"]
            master_doctree = app.env.get_doctree(master_doc)
            master_url = context["pathto"](master_doc)
            master_title = list(master_doctree.traverse(nodes.title))
            if len(master_title) == 0:
                raise ValueError(f"Landing page missing a title: {master_doc}")
            master_title = master_title[0].astext()
            li_class = "toctree-l1"
            if context["pagename"] == master_doc:
                li_class += " current"
            # Insert it into our toctree
            ul_home = bs(
                f"""
            <ul>
                <li class="{li_class}">
                    <a href="{master_url}" class="reference internal">{master_title}</a>
                </li>
            </ul>""",
                "html.parser",
            )
            toctree.insert(0, ul_home("ul")[0])

        # pair "current" with "active" since that's what we use w/ bootstrap
        for li in toctree("li", {"class": "current"}):
            li["class"].append("active")

        # Add an icon for external links
        for a_ext in toctree("a", attrs={"class": ["external"]}):
            a_ext.append(
                toctree.new_tag(
                    "i", attrs={"class": ["fas", "fa-external-link-alt"]}))

        # get level specified in conf
        navbar_level = int(context["theme_show_navbar_depth"])

        # function to open/close list and add icon
        def collapse_list(li, ul, level):
            if ul:
                li.attrs["class"] = li.attrs.get("class",
                                                 []) + ["collapsible-parent"]
                if level <= 0:
                    ul.attrs["class"] = ul.attrs.get("class",
                                                     []) + ["collapse-ul"]
                    li.append(
                        toctree.new_tag(
                            "i", attrs={"class": ["fas", "fa-chevron-down"]}))
                else:
                    # Icon won't show up unless captions are collapsed
                    if not li.name == "p" and "caption" not in li["class"]:
                        li.append(
                            toctree.new_tag(
                                "i", attrs={"class": ["fas",
                                                      "fa-chevron-up"]}))

        # for top-level caption's collapse functionality
        for para in toctree("p", attrs={"class": ["caption"]}):
            ul = para.find_next_sibling()
            collapse_list(para, ul, navbar_level)

        # iterate through all the lists in the sideabar and open/close
        def iterate_toc_li(li, level):
            if hasattr(li, "name") and li.name == "li":
                ul = li.find("ul")
                collapse_list(li, ul, level)
            if isinstance(li, list) or hasattr(li, "name"):
                for entry in li:
                    if isinstance(entry, str):
                        continue
                    if hasattr(entry, "name"):
                        if entry.name == "li":
                            iterate_toc_li(entry, level - 1)
                        else:
                            iterate_toc_li(entry, level)
            return

        iterate_toc_li(toctree, navbar_level)

        # Add bootstrap classes for first `ul` items
        for ul in toctree("ul", recursive=False):
            ul.attrs["class"] = ul.attrs.get("class",
                                             []) + ["nav", "sidenav_l1"]

        return toctree.prettify()

    context["generate_nav_html"] = generate_nav_html

    def generate_toc_html():
        """Return the within-page TOC links in HTML."""

        toc = context.get("toc")
        if not toc:
            return ""

        soup = bs(toc, "html.parser")

        # Add toc-hN classes
        def add_header_level_recursive(ul, level):
            for li in ul("li", recursive=False):
                li["class"] = li.get("class", []) + [f"toc-h{level}"]
                ul = li.find("ul", recursive=False)
                if ul:
                    add_header_level_recursive(ul, level + 1)

        add_header_level_recursive(soup.find("ul"), 1)

        # Add in CSS classes for bootstrap
        for ul in soup("ul"):
            ul["class"] = ul.get("class",
                                 []) + ["nav", "section-nav", "flex-column"]
        for li in soup("li"):
            li["class"] = li.get("class", []) + ["nav-item", "toc-entry"]
            if li.find("a"):
                a = li.find("a")
                a["class"] = a.get("class", []) + ["nav-link"]

        # If we only have one h1 header, assume it's a title
        h1_headers = soup.select(".toc-h1")
        if len(h1_headers) == 1:
            title = h1_headers[0]
            # If we have no sub-headers of a title then we won't have a TOC
            if not title.select(".toc-h2"):
                return ""

            toc_out = title.find("ul").prettify()

        # Else treat the h1 headers as sections
        else:
            toc_out = soup.prettify()

        if not context["theme_toc_title"]:
            raise ValueError(
                "'toc_title' key cannot be empty. Please set a non-empty value."
            )

        out = f"""
        <div class="tocsection onthispage pt-5 pb-3">
            <i class="fas fa-list"></i>
            { context["translate"](context["theme_toc_title"]) }
        </div>
        <nav id="bd-toc-nav">
            {toc_out}
        </nav>
        """
        return out

    context["generate_toc_html"] = generate_toc_html

    # Update the page title because HTML makes it into the page title occasionally
    if pagename in app.env.titles:
        title = app.env.titles[pagename]
        context["pagetitle"] = title.astext()

    # Add a shortened page text to the context using the sections text
    if doctree:
        description = ""
        for section in doctree.traverse(nodes.section):
            description += section.astext().replace("\n", " ")
        description = description[:160]
        context["page_description"] = description

    # Add the author if it exists
    if app.config.author != "unknown":
        context["author"] = app.config.author

    # Absolute URLs for logo if `html_baseurl` is given
    # pageurl will already be set by Sphinx if so
    if app.config.html_baseurl and app.config.html_logo:
        context["logourl"] = "/".join((app.config.html_baseurl.rstrip("/"),
                                       "_static/" + context["logo"]))

    # Add HTML context variables that the pydata theme uses that we configure elsewhere
    # For some reason the source_suffix sometimes isn't there even when doctree is
    if doctree and context.get("page_source_suffix"):
        config_theme = app.config.html_theme_options
        repo_url = config_theme.get("repository_url", "")
        # Only add the edit button if `repository_url` is given
        if repo_url:
            branch = config_theme.get("repository_branch")
            if not branch:
                # Explicitly check in cae branch is ""
                branch = "master"
            relpath = config_theme.get("path_to_docs", "")
            org, repo = repo_url.strip("/").split("/")[-2:]
            context.update({
                "github_user": org,
                "github_repo": repo,
                "github_version": branch,
                "doc_path": relpath,
            })
    else:
        # Disable using the button so we don't get errors
        context["theme_use_edit_page_button"] = False

    # Make sure the context values are bool
    btns = [
        "theme_use_edit_page_button",
        "theme_use_repository_button",
        "theme_use_issues_button",
        "theme_use_download_button",
    ]
    for key in btns:
        if key in context:
            context[key] = _string_or_bool(context[key])

    translation = get_translation(MESSAGE_CATALOG_NAME)
    context["translate"] = translation
    # this is set in the html_theme
    context["theme_search_bar_text"] = translation(
        context.get("theme_search_bar_text", "Search the docs ..."))
Esempio n. 8
0
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx import addnodes
from sphinx.roles import XRefRole
from sphinx.domains import Domain, ObjType, Index
from sphinx.directives import ObjectDescription
from sphinx.locale import get_translation
from sphinx.util import logging
from sphinx.util.nodes import make_refnode
from sphinx.util.docfields import Field, GroupedField, TypedField
from sphinx.environment import BuildEnvironment
from sphinx.builders import Builder
from typing import Any, Dict, Iterable, Iterator, List, Tuple, Optional, Union

MESSAGE_CATALOG_NAME = 'sphinx-luadomain'
_ = get_translation(MESSAGE_CATALOG_NAME)

logger = logging.getLogger(__name__)

# REs for Lua signatures
lua_sig_re = re.compile(
    r'''^ ([\w.]*\.)?            # class name(s)
          (\w+)  \s*             # thing name
          (?: \((.*)\)           # optional: arguments
           (?:\s* -> \s* (.*))?  #           return annotation
          )? $                   # and nothing more
          ''', re.VERBOSE)


def _pseudo_parse_arglist(sig_node: addnodes.desc_signature,
                          arg_list: str) -> None:
Esempio n. 9
0
from sphinx.config import Config
from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.environment.adapters.indexentries import IndexEntries
from sphinx.locale import get_translation
from sphinx.util import logging
from sphinx.util import progress_message
from sphinx.util.fileutil import copy_asset_file
from sphinx.util.nodes import NodeMatcher
from sphinx.util.osutil import make_filename_from_project, relpath
from sphinx.util.template import SphinxRenderer

from sphinxcontrib.htmlhelp.version import __version__


logger = logging.getLogger(__name__)
__ = get_translation(__name__, 'console')

package_dir = path.abspath(path.dirname(__file__))
template_dir = path.join(package_dir, 'templates')


# The following list includes only languages supported by Sphinx. See
# https://docs.microsoft.com/en-us/previous-versions/windows/embedded/ms930130(v=msdn.10)
# for more.
chm_locales = {
    # lang:   LCID,  encoding
    'ca':    (0x403, 'cp1252'),
    'cs':    (0x405, 'cp1250'),
    'da':    (0x406, 'cp1252'),
    'de':    (0x407, 'cp1252'),
    'en':    (0x409, 'cp1252'),
from sphinx.util.docutils import SphinxDirective
from sphinx.util.nodes import set_source_info
from sphinx.util.texescape import tex_escape_map
from sphinx.locale import get_translation
from sphinx.environment import NoUri

import os.path

# Constants  ----------------------------------------------------------------

MODULE_NAME = "secualert"
# This will also be used as POT filename.

# Utilities  ----------------------------------------------------------------

_ = get_translation(MODULE_NAME)

# Nodes  --------------------------------------------------------------------


class secualert_node(nodes.Admonition, nodes.Element):
    pass


class secualertlist_node(nodes.General, nodes.Element):
    pass


# Directives  ---------------------------------------------------------------

Esempio n. 11
0
from docutils import nodes
from sphinx.application import Sphinx
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.domains.math import MathDomain
from sphinx.environment import BuildEnvironment
from sphinx.errors import ExtensionError
from sphinx.locale import get_translation
from sphinx.util.math import get_node_equation_number
from sphinx.writers.html import HTMLTranslator

from sphinxcontrib.jsmath.version import __version__

package_dir = path.abspath(path.dirname(__file__))

_ = get_translation(__name__)


def html_visit_math(self: HTMLTranslator, node: nodes.math) -> None:
    self.body.append(
        self.starttag(node, 'span', '', CLASS='math notranslate nohighlight'))
    self.body.append(self.encode(node.astext()) + '</span>')
    raise nodes.SkipNode


def html_visit_displaymath(self: HTMLTranslator,
                           node: nodes.math_block) -> None:
    if node['nowrap']:
        self.body.append(
            self.starttag(node, 'div', CLASS='math notranslate nohighlight'))
        self.body.append(self.encode(node.astext()))
Esempio n. 12
0
def add_to_context(app, pagename, templatename, context, doctree):

    # TODO: remove this whenever the nav collapsing functionality is in the PST
    def sbt_generate_nav_html(
        level=1,
        include_item_names=False,
        with_home_page=False,
        prev_section_numbers=None,
        show_depth=1,
    ):
        # Config stuff
        config = app.env.config
        if isinstance(with_home_page, str):
            with_home_page = with_home_page.lower() == "true"

        # Convert the pydata toctree html to beautifulsoup
        toctree = context["generate_nav_html"](
            startdepth=level - 1,
            kind="sidebar",
            maxdepth=4,
            collapse=False,
            includehidden=True,
            titles_only=True,
        )
        toctree = bs(toctree, "html.parser")

        # Add the master_doc page as the first item if specified
        if with_home_page:
            # Pull metadata about the master doc
            master_doc = config["master_doc"]
            master_doctree = app.env.get_doctree(master_doc)
            master_url = context["pathto"](master_doc)
            master_title = list(master_doctree.traverse(nodes.title))
            if len(master_title) == 0:
                raise ValueError(f"Landing page missing a title: {master_doc}")
            master_title = master_title[0].astext()
            li_class = "toctree-l1"
            if context["pagename"] == master_doc:
                li_class += " current"
            # Insert it into our toctree
            ul_home = bs(
                f"""
            <ul class="nav bd-sidenav">
                <li class="{li_class}">
                    <a href="{master_url}" class="reference internal">{master_title}</a>
                </li>
            </ul>""",
                "html.parser",
            )
            toctree.insert(0, ul_home("ul")[0])

        # Open the navbar to the proper depth
        for ii in range(int(show_depth)):
            for checkbox in toctree.select(
                f"li.toctree-l{ii} > input.toctree-checkbox"
            ):
                checkbox.attrs["checked"] = None

        return toctree.prettify()

    context["sbt_generate_nav_html"] = sbt_generate_nav_html

    # Update the page title because HTML makes it into the page title occasionally
    if pagename in app.env.titles:
        title = app.env.titles[pagename]
        context["pagetitle"] = title.astext()

    # Add a shortened page text to the context using the sections text
    if doctree:
        description = ""
        for section in doctree.traverse(nodes.section):
            description += section.astext().replace("\n", " ")
        description = description[:160]
        context["page_description"] = description

    # Add the author if it exists
    if app.config.author != "unknown":
        context["author"] = app.config.author

    # Add HTML context variables that the pydata theme uses that we configure elsewhere
    # For some reason the source_suffix sometimes isn't there even when doctree is
    if doctree and context.get("page_source_suffix"):
        config_theme = app.config.html_theme_options
        repo_url = config_theme.get("repository_url", "")
        # Only add the edit button if `repository_url` is given
        if repo_url:
            branch = config_theme.get("repository_branch")
            if not branch:
                # Explicitly check in cae branch is ""
                branch = "master"
            relpath = config_theme.get("path_to_docs", "")
            org, repo = repo_url.strip("/").split("/")[-2:]
            context.update(
                {
                    "github_user": org,
                    "github_repo": repo,
                    "github_version": branch,
                    "doc_path": relpath,
                }
            )
    else:
        # Disable using the button so we don't get errors
        context["theme_use_edit_page_button"] = False

    # Make sure the context values are bool
    btns = [
        "theme_use_edit_page_button",
        "theme_use_repository_button",
        "theme_use_issues_button",
        "theme_use_download_button",
        "theme_use_fullscreen_button",
    ]
    for key in btns:
        if key in context:
            context[key] = _string_or_bool(context[key])

    translation = get_translation(MESSAGE_CATALOG_NAME)
    context["translate"] = translation
    # this is set in the html_theme
    context["theme_search_bar_text"] = translation(
        context.get("theme_search_bar_text", "Search the docs ...")
    )
Esempio n. 13
0
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2021 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""

from sphinx.locale import get_translation

# name of this extension's gettext catalog
MESSAGE_CATALOG_NAME = 'sphinxcontrib.confluencebuilder'

# translator for messages in documentation
L = get_translation(MESSAGE_CATALOG_NAME)

# translator for console messages
C = get_translation(MESSAGE_CATALOG_NAME, 'console')
Esempio n. 14
0
def test_init_with_unknown_language(rootdir):
    locale.init([rootdir / 'test-locale' / 'locale1'], 'unknown', 'myext')
    _ = locale.get_translation('myext')
    assert _('Hello world') == 'Hello world'
    assert _('Hello sphinx') == 'Hello sphinx'
    assert _('Hello reST') == 'Hello reST'
Esempio n. 15
0
def add_to_context(app, pagename, templatename, context, doctree):
    # TODO: remove this whenever the nav collapsing functionality is in the PST
    def sbt_generate_nav_html(
        level=1,
        include_item_names=False,
        with_home_page=False,
        prev_section_numbers=None,
    ):
        # Config stuff
        config = app.env.config
        if isinstance(with_home_page, str):
            with_home_page = with_home_page.lower() == "true"

        # Grab the raw toctree object and structure it so we can manipulate it
        toc_sphinx = context["toctree"](maxdepth=-1,
                                        collapse=False,
                                        titles_only=True,
                                        includehidden=True)
        toctree = bs(toc_sphinx, "html.parser")

        # Add the master_doc page as the first item if specified
        if with_home_page:
            # Pull metadata about the master doc
            master_doc = config["master_doc"]
            master_doctree = app.env.get_doctree(master_doc)
            master_url = context["pathto"](master_doc)
            master_title = list(master_doctree.traverse(nodes.title))
            if len(master_title) == 0:
                raise ValueError(f"Landing page missing a title: {master_doc}")
            master_title = master_title[0].astext()
            li_class = "toctree-l1"
            if context["pagename"] == master_doc:
                li_class += " current"
            # Insert it into our toctree
            ul_home = bs(
                f"""
            <ul>
                <li class="{li_class}">
                    <a href="{master_url}" class="reference internal">{master_title}</a>
                </li>
            </ul>""",
                "html.parser",
            )
            toctree.insert(0, ul_home("ul")[0])

        # pair "current" with "active" since that's what we use w/ bootstrap
        for li in toctree("li", {"class": "current"}):
            li["class"].append("active")

        # Add an icon for external links
        for a_ext in toctree("a", attrs={"class": ["external"]}):
            a_ext.append(
                toctree.new_tag(
                    "i", attrs={"class": ["fas", "fa-external-link-alt"]}))

        # get level specified in conf
        navbar_level = int(context["theme_show_navbar_depth"])

        # function to open/close list and add icon
        def collapse_list(li, ul, level):
            if ul:
                li.attrs["class"] = li.attrs.get("class",
                                                 []) + ["collapsible-parent"]
                if level <= 0:
                    ul.attrs["class"] = ul.attrs.get("class",
                                                     []) + ["collapse-ul"]
                    li.append(
                        toctree.new_tag(
                            "i", attrs={"class": ["fas", "fa-chevron-down"]}))
                else:
                    # Icon won't show up unless captions are collapsed
                    if not li.name == "p" and "caption" not in li["class"]:
                        li.append(
                            toctree.new_tag(
                                "i", attrs={"class": ["fas",
                                                      "fa-chevron-up"]}))

        # for top-level caption's collapse functionality
        for para in toctree("p", attrs={"class": ["caption"]}):
            ul = para.find_next_sibling()
            collapse_list(para, ul, navbar_level)

        # iterate through all the lists in the sideabar and open/close
        def iterate_toc_li(li, level):
            if hasattr(li, "name") and li.name == "li":
                ul = li.find("ul")
                collapse_list(li, ul, level)
            if isinstance(li, list) or hasattr(li, "name"):
                for entry in li:
                    if isinstance(entry, str):
                        continue
                    if hasattr(entry, "name"):
                        if entry.name == "li":
                            iterate_toc_li(entry, level - 1)
                        else:
                            iterate_toc_li(entry, level)
            return

        iterate_toc_li(toctree, navbar_level)

        # Add bootstrap classes for first `ul` items
        for ul in toctree("ul", recursive=False):
            ul.attrs["class"] = ul.attrs.get("class",
                                             []) + ["nav", "sidenav_l1"]

        return toctree.prettify()

    context["sbt_generate_nav_html"] = sbt_generate_nav_html

    # Update the page title because HTML makes it into the page title occasionally
    if pagename in app.env.titles:
        title = app.env.titles[pagename]
        context["pagetitle"] = title.astext()

    # Add a shortened page text to the context using the sections text
    if doctree:
        description = ""
        for section in doctree.traverse(nodes.section):
            description += section.astext().replace("\n", " ")
        description = description[:160]
        context["page_description"] = description

    # Add the author if it exists
    if app.config.author != "unknown":
        context["author"] = app.config.author

    # Add HTML context variables that the pydata theme uses that we configure elsewhere
    # For some reason the source_suffix sometimes isn't there even when doctree is
    if doctree and context.get("page_source_suffix"):
        config_theme = app.config.html_theme_options
        repo_url = config_theme.get("repository_url", "")
        # Only add the edit button if `repository_url` is given
        if repo_url:
            branch = config_theme.get("repository_branch")
            if not branch:
                # Explicitly check in cae branch is ""
                branch = "master"
            relpath = config_theme.get("path_to_docs", "")
            org, repo = repo_url.strip("/").split("/")[-2:]
            context.update({
                "github_user": org,
                "github_repo": repo,
                "github_version": branch,
                "doc_path": relpath,
            })
    else:
        # Disable using the button so we don't get errors
        context["theme_use_edit_page_button"] = False

    # Make sure the context values are bool
    btns = [
        "theme_use_edit_page_button",
        "theme_use_repository_button",
        "theme_use_issues_button",
        "theme_use_download_button",
    ]
    for key in btns:
        if key in context:
            context[key] = _string_or_bool(context[key])

    translation = get_translation(MESSAGE_CATALOG_NAME)
    context["translate"] = translation
    # this is set in the html_theme
    context["theme_search_bar_text"] = translation(
        context.get("theme_search_bar_text", "Search the docs ..."))
Esempio n. 16
0
# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'standard_theme'  # 'pydata_sphinx_theme'
html_theme_path = [standard_theme.get_html_theme_path()]
html_favicon = '_static/favicon-16x16.ico'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# -- Local configuration -----------------------------------------------------

_ = get_translation('theme')

profile_identifier = 'gpa'
repository_url = 'https://github.com/open-contracting-extensions/government-procurement-agreement'

# Internationalization.
gettext_compact = False
# `DOMAIN_PREFIX` from `config.mk`.
gettext_domain_prefix = f'{profile_identifier}-' if profile_identifier else ''
locale_dirs = [
    'locale/',
    os.path.join(standard_theme.get_html_theme_path(), 'locale')
]
# We use single quotes for codes, which docutils will change to double quotes.
# https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/docutils/utils/smartquotes.py
smartquotes = False
Esempio n. 17
0
REF_TYPE_RE = re.compile(
    r'^(?:(new)\s+)?([\w\.]+)\s*(?:<(.+)>)*(\[\])*\s?(?:\((.*)\))?$')
METHOD_SIG_RE = re.compile(
    r'^((?:(?:' + MODIFIERS_RE +
    r')\s+)*)?([^\s=\(\)]+\s+)?([^\s=\(\)]+)\s?(?:\<(.+)\>)?\s?(?:\((.+)*\))$')
PARAM_SIG_RE = re.compile(r'^(?:(?:(' + PARAM_MODIFIERS_RE +
                          r')\s)*)?([^=]+)\s+([^=]+)\s*(?:=\s?(.+))?$')
VAR_SIG_RE = re.compile(r'^((?:(?:' + MODIFIERS_RE +
                        r')\s+)*)?([^=]+)\s+([^\s=]+)\s*(?:=\s*(.+))?$')
PROP_SIG_RE = re.compile(r'^((?:(?:' + MODIFIERS_RE +
                         r')\s+)*)?(.+)\s+([^\s]+)\s*(?:{(\s*get;\s*)?((?:' +
                         MODIFIERS_RE + r')?\s*set;\s*)?})$')
ENUM_SIG_RE = re.compile(r'^((?:(?:' + MODIFIERS_RE +
                         r')\s+)*)?(?:enum)\s?(\w+)$')

_ = get_translation('sphinxsharp')


class CSharpObject(ObjectDescription):
    PARENT_ATTR_NAME = 'sphinxsharp:parent'
    PARENT_TYPE_NAME = 'sphinxsharp:type'

    ParentType = namedtuple('ParentType',
                            ['parent', 'name', 'type', 'override'])

    option_spec = {'noindex': directives.flag}

    def __init__(self, *args, **kwargs):
        super(CSharpObject, self).__init__(*args, **kwargs)
        self.parentname_set = None
        self.parentname_saved = None
 * PySide2 - linking to PySide2 documentation on  "https://doc.qt.io/qtforpython/PySide2/"
"""
import importlib
import inspect
import re

from sphinx.application import Sphinx
from sphinx.config import ENUM
from sphinx.environment import BuildEnvironment
from docutils.nodes import Element, TextElement
from docutils import nodes
from typing import List, Optional, Dict, Any
from sphinx.locale import get_translation
from sphinx.ext.intersphinx import InventoryAdapter

_ = get_translation("sphinx")


def _get_signal_and_version():
    name_mapping = {
        'qtpy': (lambda: 'QT_VERSION', 'Signal'),
        'Qt': (lambda: '__qt_version__', 'Signal'),
        'PySide2':
        (lambda: importlib.import_module('PySide2.QtCore').__version__,
         'Signal'),
        'PyQt5':
        (lambda: importlib.import_module('PyQt5.QtCore').QT_VERSION_STR,
         'pyqtSignal')
    }
    for module_name, (version, signal_name) in name_mapping.items():
        try: