diff --git a/CHANGES b/CHANGES index a35ee36..7031562 100644 --- a/CHANGES +++ b/CHANGES @@ -2,6 +2,14 @@ Changes ======= +1.0.0 (*2023-09-16*) +==================== + +- Refactor setup.py to pyproject.toml +- Configurable parameters for pyppeteer call +- Changing default parameters for pyppeteer +- Support of Mathjax + 0.1.1 (*2020-07-08*) ==================== diff --git a/pyproject.toml b/pyproject.toml index cbee92e..7694d9d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,8 @@ version = "1.0.0" requires-python = ">=3.8" dependencies = [ "Sphinx>=7.0.0", - "pyppeteer" + "pyppeteer", + "typing_extensions" ] license = {text = "EUPL-1.2"} authors = [ @@ -51,14 +52,14 @@ pyppeteer = "sphinx_pyppeteer_builder" [project.optional-dependencies] tests = [ "pytest", - "flake8", + "pyright", "pylint", "pytest-cov" ] setup = [ "Sphinx", "pytest-runner", - "flake8", + "pyright", "pylint", "babel", "flit", @@ -98,3 +99,76 @@ include = [ "*.py", ] +[tool.pyright] +analyzeUnannotatedFunctions = true +deprecateTypingAliases = true +enableExperimentalFeatures = false +enableTypeIgnoreComments = false +reportAssertAlwaysTrue = "warning" +reportCallInDefaultInitializer = "information" +reportConstantRedefinition = "warning" +reportDeprecated = "warning" +reportDuplicateImport = "warning" +reportFunctionMemberAccess = "warning" +reportGeneralTypeIssues = "error" +reportImplicitOverride = "warning" +reportImplicitStringConcatenation = "information" +reportImportCycles = "error" +reportIncompatibleMethodOverride = "warning" +reportIncompatibleVariableOverride = "warning" +reportIncompleteStub = "warning" +reportInconsistentConstructor = "warning" +reportInvalidStringEscapeSequence = "error" +reportInvalidStubStatement = "warning" +reportInvalidTypeVarUse = "warning" +reportMatchNotExhaustive = "warning" +reportMissingImports = "error" +reportMissingModuleSource = "warning" +reportMissingParameterType = "error" +reportMissingSuperCall = "warning" +reportMissingTypeArgument = "error" +reportMissingTypeStubs = "warning" +reportOptionalCall = "error" +reportOptionalContextManager = "error" +reportOptionalIterable = "error" +reportOptionalMemberAccess = "error" +reportOptionalOperand = "error" +reportOptionalSubscript = "error" +reportOverlappingOverload = "warning" +reportPrivateImportUsage = "error" +reportPrivateUsage = "warning" +reportPropertyTypeMismatch = "error" +reportSelfClsParameterName = "error" +reportShadowedImports = "warning" +reportTypeCommentUsage = "warning" +reportTypedDictNotRequiredAccess = "error" +reportUnboundVariable = "error" +reportUndefinedVariable = "error" +reportUninitializedInstanceVariable = "warning" +reportUnknownArgumentType = "error" +reportUnknownLambdaType = "error" +reportUnknownMemberType = "error" +reportUnknownParameterType = "error" +reportUnknownVariableType = "error" +reportUnnecessaryCast = "warning" +reportUnnecessaryComparison = "warning" +reportUnnecessaryContains = "warning" +reportUnnecessaryIsInstance = "warning" +reportUnnecessaryTypeIgnoreComment = "warning" +reportUnsupportedDunderAll = "warning" +reportUntypedBaseClass = "error" +reportUntypedClassDecorator = "error" +reportUntypedFunctionDecorator = "error" +reportUntypedNamedTuple = "error" +reportUnusedCallResult = "warning" +reportUnusedClass = "information" +reportUnusedCoroutine = "error" +reportUnusedExpression = "warning" +reportUnusedFunction = "information" +reportUnusedImport = "information" +reportUnusedVariable = "warning" +reportWildcardImportFromLibrary = "error" +strictDictionaryInference = true +strictListInference = true +strictParameterNoneValue = true +strictSetInference = true diff --git a/sphinx_pyppeteer_builder/__init__.py b/sphinx_pyppeteer_builder/__init__.py index 89dc8d7..45b3bc0 100644 --- a/sphinx_pyppeteer_builder/__init__.py +++ b/sphinx_pyppeteer_builder/__init__.py @@ -3,7 +3,7 @@ from copy import deepcopy from .pyppeteer_builder import PyppeteerPDFBuilder -from typing import Dict, Any +from typing import Dict, Any, Callable, Optional, List from sphinx.application import Sphinx from sphinx.config import Config from sphinx.util.osutil import make_filename @@ -12,7 +12,7 @@ import pkg_resources __version__ = pkg_resources.get_distribution(__package__).version __version_info__ = tuple(int(v) for v in __version__.split('.')) -DEFAULT_PDF_OPTIONS = { +DEFAULT_PDF_OPTIONS: Dict[str, Optional[bool|str|Dict[str,Optional[bool|str]]]] = { 'printBackground': True, 'format': 'A4', 'margin': { @@ -23,18 +23,18 @@ DEFAULT_PDF_OPTIONS = { } } -DEFAULT_PYPPETEER_ARGS = [ +DEFAULT_PYPPETEER_ARGS: List[str] = [ '--allow-file-access-from-file', '--disable-web-security', '--no-sandbox', - ] +] -def on_config_inited(app, config: Config): +def on_config_inited(app: Sphinx, config: Config): """ Change config on the fly """ - pdf_options = deepcopy(DEFAULT_PDF_OPTIONS) + pdf_options:Dict[str, Any] = deepcopy(DEFAULT_PDF_OPTIONS) pdf_options.update(app.config.pyppeteer_pdf_options) - app.config.pyppeteer_pdf_options = pdf_options + app.config["pyppeteer_pdf_options"] = pdf_options app.set_html_assets_policy("always") @@ -42,11 +42,13 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.setup_extension('sphinx.builders.html') app.add_builder(PyppeteerPDFBuilder) - app.connect('config-inited', on_config_inited) + _ = app.connect('config-inited', on_config_inited) + theme_options_func:Callable[[Config], str] = lambda self:\ + self.html_theme_options app.add_config_value( 'pyppeteer_theme_options', - lambda self: self.html_theme_options, + theme_options_func, 'pyppeteer' ) app.add_config_value( @@ -59,29 +61,44 @@ def setup(app: Sphinx) -> Dict[str, Any]: DEFAULT_PYPPETEER_ARGS, 'pyppeteer' ) + + basename_func:Callable[[Config], str] = lambda self:\ + make_filename(self.project) app.add_config_value( 'pyppeteer_basename', - lambda self: make_filename(self.project), + basename_func, 'pyppeteer' ) + + theme_func:Callable[[Config], str] = lambda self:\ + self.html_theme app.add_config_value( 'pyppeteer_theme', - lambda self: self.html_theme, + theme_func, 'pyppeteer' ) + + title_func:Callable[[Config], str] = lambda self:\ + self.html_title app.add_config_value( 'pyppeteer_title', - lambda self: self.html_title, + title_func, 'pyppeteer' ) + + theme_path_func:Callable[[Config], str] = lambda self:\ + self.html_theme_path app.add_config_value( 'pyppeteer_theme_path', - lambda self: self.html_theme_path, + theme_path_func, 'pyppeteer' ) + + short_title_func:Callable[[Config], str] = lambda self:\ + self.html_short_title app.add_config_value( 'pyppeteer_short_title', - lambda self: self.html_short_title, + short_title_func, 'pyppeteer' ) app.add_config_value( diff --git a/sphinx_pyppeteer_builder/loghandler.py b/sphinx_pyppeteer_builder/loghandler.py index 4e7db78..1cde7d5 100644 --- a/sphinx_pyppeteer_builder/loghandler.py +++ b/sphinx_pyppeteer_builder/loghandler.py @@ -1,9 +1,20 @@ #!/usr/bin/env python3 -import logging -from sphinx.util import logging as sphinx_logging +import sys +from logging import StreamHandler, Formatter, LogRecord, DEBUG + +from typing import TYPE_CHECKING, Optional, TextIO +from typing_extensions import override + +from sphinx.util.logging import getLogger, SphinxLoggerAdapter + +logger: SphinxLoggerAdapter = getLogger('pyppeteer') + +if TYPE_CHECKING: + _StreamHandler = StreamHandler[TextIO] +else: + _StreamHandler = StreamHandler -logger = sphinx_logging.getLogger('pyppeteer') ppsphinx_log_inited = False @@ -14,9 +25,9 @@ def init_ppsphinx_log() -> None: if ppsphinx_log_inited: return - formatter = logging.Formatter('%(message)s') + formatter = Formatter('%(message)s') pphandler = SphinxPyppeteerHandler() - pphandler.setLevel(logging.DEBUG) + pphandler.setLevel(DEBUG) pphandler.setFormatter(formatter) logger_names = ( 'pyppeteer', @@ -36,16 +47,17 @@ def init_ppsphinx_log() -> None: 'pyppeteer.worker', ) for logger_name in logger_names: - pplogger = logging.getLogger(logger_name) - pplogger.addHandler(pphandler) + pplogger = getLogger(logger_name) + pplogger.logger.addHandler(pphandler) -class SphinxPyppeteerHandler(logging.StreamHandler): +class SphinxPyppeteerHandler(_StreamHandler): """ Resend Pyppeteer logging to Sphinx output. """ - def __init__(self): - super(SphinxPyppeteerHandler, self).__init__() + def __init__(self, stream: Optional[TextIO]=None) -> None: + super(SphinxPyppeteerHandler, self).__init__(stream or sys.stderr) - def emit(self, record): + @override + def emit(self, record: LogRecord) -> None: logger.handle(record) diff --git a/sphinx_pyppeteer_builder/pyppeteer_builder.py b/sphinx_pyppeteer_builder/pyppeteer_builder.py index 4f670ba..a428ff1 100644 --- a/sphinx_pyppeteer_builder/pyppeteer_builder.py +++ b/sphinx_pyppeteer_builder/pyppeteer_builder.py @@ -2,18 +2,25 @@ import os import asyncio -from typing import Dict, Set, Tuple +from typing import Set, Optional, Dict, Any + +from typing_extensions import override from sphinx.builders.singlehtml import SingleFileHTMLBuilder -from sphinx.util.display import progress_message, logging +from sphinx.util.display import progress_message +from sphinx.util.logging import getLogger, SphinxLoggerAdapter from sphinx.util.osutil import os_path +from sphinx.config import Config +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.theming import Theme from sphinx.locale import __ import pyppeteer from .loghandler import init_ppsphinx_log -logger = logging.getLogger('pyppeteer*') +logger: SphinxLoggerAdapter = getLogger('pyppeteer*') class PyppeteerPDFBuilder(SingleFileHTMLBuilder): @@ -22,30 +29,44 @@ class PyppeteerPDFBuilder(SingleFileHTMLBuilder): embedded = True search = False + def __init__(self, app: Sphinx, env: BuildEnvironment) -> None: + self.config: Config + self.theme: Theme + self.globalcontext: Dict[str, Any] + self.outdir: str + super(PyppeteerPDFBuilder, self).__init__(app, env) + def _get_translations_js(self) -> str: return "" + @override def copy_translation_js(self) -> None: return + @override def copy_stemmer_js(self) -> None: return + @override def copy_html_favicon(self) -> None: return - def get_theme_config(self) -> Tuple[str, Dict]: + @override + def get_theme_config(self) -> tuple[str, Dict[str, Any]]: return ( self.config.pyppeteer_theme, self.config.pyppeteer_theme_options ) + @override def init_js_files(self) -> None: return + @override def add_js_file(self, filename: str, **kwargs: str) -> None: return + @override def prepare_writing(self, docnames: Set[str]) -> None: super(PyppeteerPDFBuilder, self).prepare_writing(docnames) if self.config.pyppeteer_style is not None: @@ -64,20 +85,22 @@ class PyppeteerPDFBuilder(SingleFileHTMLBuilder): self.globalcontext['style'] = stylename self.globalcontext['favicon'] = None + @override def finish(self) -> None: super(PyppeteerPDFBuilder, self).finish() - progress_message('Starting conversion to PDF with Pyppeteer') - infile = os.path.join( + _ = progress_message('Starting conversion to PDF with Pyppeteer') + infile:str = os.path.join( self.outdir, os_path(self.config.master_doc) + self.out_suffix ) - outfile = os.path.join( + outfile:str = os.path.join( self.outdir, self.config.pyppeteer_basename + '.pdf' ) - url = 'file://' + infile - pdf_options = self.config.pyppeteer_pdf_options + url:str = 'file://' + infile + pdf_options:Dict[str, Optional[bool|str|Dict[str,Optional[bool|str]]]] \ + = self.config.pyppeteer_pdf_options pdf_options['path'] = outfile init_ppsphinx_log() @@ -86,7 +109,7 @@ class PyppeteerPDFBuilder(SingleFileHTMLBuilder): self.generate_pdf(url, pdf_options) ) - async def generate_pdf(self, url: str, pdf_options: dict) -> None: + async def generate_pdf(self, url: str, pdf_options: Dict[str, Optional[bool|str|Dict[str,Optional[bool|str]]]]) -> None: """ Generate PDF @@ -105,8 +128,8 @@ class PyppeteerPDFBuilder(SingleFileHTMLBuilder): }) try: page = await browser.newPage() - await page.goto(url, {"waitUntil": ["networkidle2"]}) - await page.pdf(pdf_options) + _ = await page.goto(url, {"waitUntil": ["networkidle2"]}) + _ = await page.pdf(pdf_options) await browser.close() finally: await browser.close() diff --git a/typings/pyppeteer/__init__.pyi b/typings/pyppeteer/__init__.pyi new file mode 100644 index 0000000..bbdc456 --- /dev/null +++ b/typings/pyppeteer/__init__.pyi @@ -0,0 +1,19 @@ +""" +This type stub file was generated by pyright. +""" + +import logging +import os +from appdirs import AppDirs +from importlib.metadata import version +from pyppeteer.launcher import connect, defaultArgs, executablePath, launch + +"""Meta data for pyppeteer.""" +__version__ = ... +__chromium_revision__ = ... +__base_puppeteer_version__ = ... +__pyppeteer_home__: str = ... +DEBUG = ... +version = ... +version_info = ... +__all__ = ['connect', 'launch', 'executablePath', 'defaultArgs', 'version', 'version_info'] diff --git a/typings/pyppeteer/browser.pyi b/typings/pyppeteer/browser.pyi new file mode 100644 index 0000000..ef2f24e --- /dev/null +++ b/typings/pyppeteer/browser.pyi @@ -0,0 +1,202 @@ +""" +This type stub file was generated by pyright. +""" + +from subprocess import Popen +from typing import Any, Awaitable, Callable, Dict, List, Optional +from pyee import EventEmitter +from pyppeteer.connection import Connection +from pyppeteer.page import Page +from pyppeteer.target import Target + +"""Browser module.""" +logger = ... +class Browser(EventEmitter): + """Browser class. + + A Browser object is created when pyppeteer connects to chrome, either + through :func:`~pyppeteer.launcher.launch` or + :func:`~pyppeteer.launcher.connect`. + """ + Events = ... + def __init__(self, connection: Connection, contextIds: List[str], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], process: Optional[Popen] = ..., closeCallback: Callable[[], Awaitable[None]] = ..., **kwargs: Any) -> None: + ... + + @property + def process(self) -> Optional[Popen]: + """Return process of this browser. + + If browser instance is created by :func:`pyppeteer.launcher.connect`, + return ``None``. + """ + ... + + async def createIncogniteBrowserContext(self) -> BrowserContext: + """[Deprecated] Miss spelled method. + + Use :meth:`createIncognitoBrowserContext` method instead. + """ + ... + + async def createIncognitoBrowserContext(self) -> BrowserContext: + """Create a new incognito browser context. + + This won't share cookies/cache with other browser contexts. + + .. code:: + + browser = await launch() + # Create a new incognito browser context. + context = await browser.createIncognitoBrowserContext() + # Create a new page in a pristine context. + page = await context.newPage() + # Do stuff + await page.goto('https://example.com') + ... + """ + ... + + @property + def browserContexts(self) -> List[BrowserContext]: + """Return a list of all open browser contexts. + + In a newly created browser, this will return a single instance of + ``[BrowserContext]`` + """ + ... + + @staticmethod + async def create(connection: Connection, contextIds: List[str], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], process: Optional[Popen] = ..., closeCallback: Callable[[], Awaitable[None]] = ..., **kwargs: Any) -> Browser: + """Create browser object.""" + ... + + @property + def wsEndpoint(self) -> str: + """Return websocket end point url.""" + ... + + async def newPage(self) -> Page: + """Make new page on this browser and return its object.""" + ... + + def targets(self) -> List[Target]: + """Get a list of all active targets inside the browser. + + In case of multiple browser contexts, the method will return a list + with all the targets in all browser contexts. + """ + ... + + async def pages(self) -> List[Page]: + """Get all pages of this browser. + + Non visible pages, such as ``"background_page"``, will not be listed + here. You can find then using :meth:`pyppeteer.target.Target.page`. + + In case of multiple browser contexts, this method will return a list + with all the pages in all browser contexts. + """ + ... + + async def version(self) -> str: + """Get version of the browser.""" + ... + + async def userAgent(self) -> str: + """Return browser's original user agent. + + .. note:: + Pages can override browser user agent with + :meth:`pyppeteer.page.Page.setUserAgent`. + """ + ... + + async def close(self) -> None: + """Close connections and terminate browser process.""" + ... + + async def disconnect(self) -> None: + """Disconnect browser.""" + ... + + + +class BrowserContext(EventEmitter): + """BrowserContext provides multiple independent browser sessions. + + When a browser is launched, it has a single BrowserContext used by default. + The method `browser.newPage()` creates a page in the default browser + context. + + If a page opens another page, e.g. with a ``window.open`` call, the popup + will belong to the parent page's browser context. + + Pyppeteer allows creation of "incognito" browser context with + ``browser.createIncognitoBrowserContext()`` method. + "incognito" browser contexts don't write any browser data to disk. + + .. code:: + + # Create new incognito browser context + context = await browser.createIncognitoBrowserContext() + # Create a new page inside context + page = await context.newPage() + # ... do stuff with page ... + await page.goto('https://example.com') + # Dispose context once it's no longer needed + await context.close() + """ + Events = ... + def __init__(self, browser: Browser, contextId: Optional[str]) -> None: + ... + + def targets(self) -> List[Target]: + """Return a list of all active targets inside the browser context.""" + ... + + async def pages(self) -> List[Page]: + """Return list of all open pages. + + Non-visible pages, such as ``"background_page"``, will not be listed + here. You can find them using :meth:`pyppeteer.target.Target.page`. + """ + ... + + def isIncognite(self) -> bool: + """[Deprecated] Miss spelled method. + + Use :meth:`isIncognito` method instead. + """ + ... + + def isIncognito(self) -> bool: + """Return whether BrowserContext is incognito. + + The default browser context is the only non-incognito browser context. + + .. note:: + The default browser context cannot be closed. + """ + ... + + async def newPage(self) -> Page: + """Create a new page in the browser context.""" + ... + + @property + def browser(self) -> Browser: + """Return the browser this browser context belongs to.""" + ... + + async def close(self) -> None: + """Close the browser context. + + All the targets that belongs to the browser context will be closed. + + .. note:: + Only incognito browser context can be closed. + """ + ... + + + diff --git a/typings/pyppeteer/chromium_downloader.pyi b/typings/pyppeteer/chromium_downloader.pyi new file mode 100644 index 0000000..6ea8081 --- /dev/null +++ b/typings/pyppeteer/chromium_downloader.pyi @@ -0,0 +1,49 @@ +""" +This type stub file was generated by pyright. +""" + +from io import BytesIO +from pathlib import Path + +"""Chromium download module.""" +logger = ... +handler = ... +DOWNLOADS_FOLDER = ... +DEFAULT_DOWNLOAD_HOST = ... +DOWNLOAD_HOST = ... +BASE_URL = ... +REVISION = ... +NO_PROGRESS_BAR = ... +if NO_PROGRESS_BAR.lower() in ('1', 'true'): + NO_PROGRESS_BAR = ... +windowsArchive = ... +downloadURLs = ... +chromiumExecutable = ... +def current_platform() -> str: + """Get current platform name by short string.""" + ... + +def get_url() -> str: + """Get chromium download url.""" + ... + +def download_zip(url: str) -> BytesIO: + """Download data from url.""" + ... + +def extract_zip(data: BytesIO, path: Path) -> None: + """Extract zipped data to path.""" + ... + +def download_chromium() -> None: + """Download and extract chromium.""" + ... + +def chromium_executable() -> Path: + """Get path of the chromium executable.""" + ... + +def check_chromium() -> bool: + """Check if chromium is placed at correct path.""" + ... + diff --git a/typings/pyppeteer/command.pyi b/typings/pyppeteer/command.pyi new file mode 100644 index 0000000..ddca8e4 --- /dev/null +++ b/typings/pyppeteer/command.pyi @@ -0,0 +1,9 @@ +""" +This type stub file was generated by pyright. +""" + +"""Commands for Pyppeteer.""" +def install() -> None: + """Download chromium if not install.""" + ... + diff --git a/typings/pyppeteer/connection.pyi b/typings/pyppeteer/connection.pyi new file mode 100644 index 0000000..806587a --- /dev/null +++ b/typings/pyppeteer/connection.pyi @@ -0,0 +1,81 @@ +""" +This type stub file was generated by pyright. +""" + +import asyncio +from typing import Awaitable, Callable, Dict, TYPE_CHECKING, Union +from pyee import EventEmitter + +"""Connection/Session management module.""" +if TYPE_CHECKING: + ... +logger = ... +logger_connection = ... +logger_session = ... +class Connection(EventEmitter): + """Connection management class.""" + def __init__(self, url: str, loop: asyncio.AbstractEventLoop, delay: int = ...) -> None: + """Make connection. + + :arg str url: WebSocket url to connect devtool. + :arg int delay: delay to wait before processing received messages. + """ + ... + + @property + def url(self) -> str: + """Get connected WebSocket url.""" + ... + + def send(self, method: str, params: dict = ...) -> Awaitable: + """Send message via the connection.""" + ... + + def setClosedCallback(self, callback: Callable[[], None]) -> None: + """Set closed callback.""" + ... + + async def dispose(self) -> None: + """Close all connection.""" + ... + + async def createSession(self, targetInfo: Dict) -> CDPSession: + """Create new session.""" + ... + + + +class CDPSession(EventEmitter): + """Chrome Devtools Protocol Session. + + The :class:`CDPSession` instances are used to talk raw Chrome Devtools + Protocol: + + * protocol methods can be called with :meth:`send` method. + * protocol events can be subscribed to with :meth:`on` method. + + Documentation on DevTools Protocol can be found + `here `__. + """ + def __init__(self, connection: Union[Connection, CDPSession], targetType: str, sessionId: str, loop: asyncio.AbstractEventLoop) -> None: + """Make new session.""" + ... + + def send(self, method: str, params: dict = ...) -> Awaitable: + """Send message to the connected session. + + :arg str method: Protocol method name. + :arg dict params: Optional method parameters. + """ + ... + + async def detach(self) -> None: + """Detach session from target. + + Once detached, session won't emit any events and can't be used to send + messages. + """ + ... + + + diff --git a/typings/pyppeteer/coverage.pyi b/typings/pyppeteer/coverage.pyi new file mode 100644 index 0000000..4ec342f --- /dev/null +++ b/typings/pyppeteer/coverage.pyi @@ -0,0 +1,144 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Dict, List +from pyppeteer.connection import CDPSession + +"""Coverage module.""" +logger = ... +class Coverage: + """Coverage class. + + Coverage gathers information about parts of JavaScript and CSS that were + used by the page. + + An example of using JavaScript and CSS coverage to get percentage of + initially executed code:: + + # Enable both JavaScript and CSS coverage + await page.coverage.startJSCoverage() + await page.coverage.startCSSCoverage() + + # Navigate to page + await page.goto('https://example.com') + # Disable JS and CSS coverage and get results + jsCoverage = await page.coverage.stopJSCoverage() + cssCoverage = await page.coverage.stopCSSCoverage() + totalBytes = 0 + usedBytes = 0 + coverage = jsCoverage + cssCoverage + for entry in coverage: + totalBytes += len(entry['text']) + for range in entry['ranges']: + usedBytes += range['end'] - range['start'] - 1 + + print('Bytes used: {}%'.format(usedBytes / totalBytes * 100)) + """ + def __init__(self, client: CDPSession) -> None: + ... + + async def startJSCoverage(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Start JS coverage measurement. + + Available options are: + + * ``resetOnNavigation`` (bool): Whether to reset coverage on every + navigation. Defaults to ``True``. + * ``reportAnonymousScript`` (bool): Whether anonymous script generated + by the page should be reported. Defaults to ``False``. + + .. note:: + Anonymous scripts are ones that don't have an associated url. These + are scripts that are dynamically created on the page using ``eval`` + of ``new Function``. If ``reportAnonymousScript`` is set to + ``True``, anonymous scripts will have + ``__pyppeteer_evaluation_script__`` as their url. + """ + ... + + async def stopJSCoverage(self) -> List: + """Stop JS coverage measurement and get result. + + Return list of coverage reports for all scripts. Each report includes: + + * ``url`` (str): Script url. + * ``text`` (str): Script content. + * ``ranges`` (List[Dict]): Script ranges that were executed. Ranges are + sorted and non-overlapping. + + * ``start`` (int): A start offset in text, inclusive. + * ``end`` (int): An end offset in text, exclusive. + + .. note:: + JavaScript coverage doesn't include anonymous scripts by default. + However, scripts with sourceURLs are reported. + """ + ... + + async def startCSSCoverage(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Start CSS coverage measurement. + + Available options are: + + * ``resetOnNavigation`` (bool): Whether to reset coverage on every + navigation. Defaults to ``True``. + """ + ... + + async def stopCSSCoverage(self) -> List: + """Stop CSS coverage measurement and get result. + + Return list of coverage reports for all non-anonymous scripts. Each + report includes: + + * ``url`` (str): StyleSheet url. + * ``text`` (str): StyleSheet content. + * ``ranges`` (List[Dict]): StyleSheet ranges that were executed. Ranges + are sorted and non-overlapping. + + * ``start`` (int): A start offset in text, inclusive. + * ``end`` (int): An end offset in text, exclusive. + + .. note:: + CSS coverage doesn't include dynamically injected style tags without + sourceURLs (but currently includes... to be fixed). + """ + ... + + + +class JSCoverage: + """JavaScript Coverage class.""" + def __init__(self, client: CDPSession) -> None: + ... + + async def start(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Start coverage measurement.""" + ... + + async def stop(self) -> List: + """Stop coverage measurement and return results.""" + ... + + + +class CSSCoverage: + """CSS Coverage class.""" + def __init__(self, client: CDPSession) -> None: + ... + + async def start(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Start coverage measurement.""" + ... + + async def stop(self) -> List: + """Stop coverage measurement and return results.""" + ... + + + +def convertToDisjointRanges(nestedRanges: List[Any]) -> List[Any]: + """Convert ranges.""" + ... + diff --git a/typings/pyppeteer/dialog.pyi b/typings/pyppeteer/dialog.pyi new file mode 100644 index 0000000..c4e26b6 --- /dev/null +++ b/typings/pyppeteer/dialog.pyi @@ -0,0 +1,69 @@ +""" +This type stub file was generated by pyright. +""" + +from pyppeteer.connection import CDPSession + +"""Dialog module.""" +class Dialog: + """Dialog class. + + Dialog objects are dispatched by page via the ``dialog`` event. + + An example of using ``Dialog`` class: + + .. code:: + + browser = await launch() + page = await browser.newPage() + + async def close_dialog(dialog): + print(dialog.message) + await dialog.dismiss() + await browser.close() + + page.on( + 'dialog', + lambda dialog: asyncio.ensure_future(close_dialog(dialog)) + ) + await page.evaluate('() => alert("1")') + """ + Type = ... + def __init__(self, client: CDPSession, type: str, message: str, defaultValue: str = ...) -> None: + ... + + @property + def type(self) -> str: + """Get dialog type. + + One of ``alert``, ``beforeunload``, ``confirm``, or ``prompt``. + """ + ... + + @property + def message(self) -> str: + """Get dialog message.""" + ... + + @property + def defaultValue(self) -> str: + """If dialog is prompt, get default prompt value. + + If dialog is not prompt, return empty string (``''``). + """ + ... + + async def accept(self, promptText: str = ...) -> None: + """Accept the dialog. + + * ``promptText`` (str): A text to enter in prompt. If the dialog's type + is not prompt, this does not cause any effect. + """ + ... + + async def dismiss(self) -> None: + """Dismiss the dialog.""" + ... + + + diff --git a/typings/pyppeteer/element_handle.pyi b/typings/pyppeteer/element_handle.pyi new file mode 100644 index 0000000..bdae41b --- /dev/null +++ b/typings/pyppeteer/element_handle.pyi @@ -0,0 +1,232 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Dict, List, Optional, TYPE_CHECKING +from pyppeteer.connection import CDPSession +from pyppeteer.execution_context import ExecutionContext, JSHandle +from pyppeteer.frame_manager import Frame, FrameManager + +"""Element handle module.""" +if TYPE_CHECKING: + ... +logger = ... +class ElementHandle(JSHandle): + """ElementHandle class. + + This class represents an in-page DOM element. ElementHandle can be created + by the :meth:`pyppeteer.page.Page.querySelector` method. + + ElementHandle prevents DOM element from garbage collection unless the + handle is disposed. ElementHandles are automatically disposed when their + origin frame gets navigated. + + ElementHandle isinstance can be used as arguments in + :meth:`pyppeteer.page.Page.querySelectorEval` and + :meth:`pyppeteer.page.Page.evaluate` methods. + """ + def __init__(self, context: ExecutionContext, client: CDPSession, remoteObject: dict, page: Any, frameManager: FrameManager) -> None: + ... + + def asElement(self) -> ElementHandle: + """Return this ElementHandle.""" + ... + + async def contentFrame(self) -> Optional[Frame]: + """Return the content frame for the element handle. + + Return ``None`` if this handle is not referencing iframe. + """ + ... + + async def hover(self) -> None: + """Move mouse over to center of this element. + + If needed, this method scrolls element into view. If this element is + detached from DOM tree, the method raises an ``ElementHandleError``. + """ + ... + + async def click(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Click the center of this element. + + If needed, this method scrolls element into view. If the element is + detached from DOM, the method raises ``ElementHandleError``. + + ``options`` can contain the following fields: + + * ``button`` (str): ``left``, ``right``, of ``middle``, defaults to + ``left``. + * ``clickCount`` (int): Defaults to 1. + * ``delay`` (int|float): Time to wait between ``mousedown`` and + ``mouseup`` in milliseconds. Defaults to 0. + """ + ... + + async def uploadFile(self, *filePaths: str) -> dict: + """Upload files.""" + ... + + async def tap(self) -> None: + """Tap the center of this element. + + If needed, this method scrolls element into view. If the element is + detached from DOM, the method raises ``ElementHandleError``. + """ + ... + + async def focus(self) -> None: + """Focus on this element.""" + ... + + async def type(self, text: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Focus the element and then type text. + + Details see :meth:`pyppeteer.input.Keyboard.type` method. + """ + ... + + async def press(self, key: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Press ``key`` onto the element. + + This method focuses the element, and then uses + :meth:`pyppeteer.input.keyboard.down` and + :meth:`pyppeteer.input.keyboard.up`. + + :arg str key: Name of key to press, such as ``ArrowLeft``. + + This method accepts the following options: + + * ``text`` (str): If specified, generates an input event with this + text. + * ``delay`` (int|float): Time to wait between ``keydown`` and + ``keyup``. Defaults to 0. + """ + ... + + async def boundingBox(self) -> Optional[Dict[str, float]]: + """Return bounding box of this element. + + If the element is not visible, return ``None``. + + This method returns dictionary of bounding box, which contains: + + * ``x`` (int): The X coordinate of the element in pixels. + * ``y`` (int): The Y coordinate of the element in pixels. + * ``width`` (int): The width of the element in pixels. + * ``height`` (int): The height of the element in pixels. + """ + ... + + async def boxModel(self) -> Optional[Dict]: + """Return boxes of element. + + Return ``None`` if element is not visible. Boxes are represented as an + list of points; each Point is a dictionary ``{x, y}``. Box points are + sorted clock-wise. + + Returned value is a dictionary with the following fields: + + * ``content`` (List[Dict]): Content box. + * ``padding`` (List[Dict]): Padding box. + * ``border`` (List[Dict]): Border box. + * ``margin`` (List[Dict]): Margin box. + * ``width`` (int): Element's width. + * ``height`` (int): Element's height. + """ + ... + + async def screenshot(self, options: Dict[str, Any] = ..., **kwargs: Any) -> bytes: + """Take a screenshot of this element. + + If the element is detached from DOM, this method raises an + ``ElementHandleError``. + + Available options are same as :meth:`pyppeteer.page.Page.screenshot`. + """ + ... + + async def querySelector(self, selector: str) -> Optional[ElementHandle]: + """Return first element which matches ``selector`` under this element. + + If no element matches the ``selector``, returns ``None``. + """ + ... + + async def querySelectorAll(self, selector: str) -> List[ElementHandle]: + """Return all elements which match ``selector`` under this element. + + If no element matches the ``selector``, returns empty list (``[]``). + """ + ... + + async def querySelectorEval(self, selector: str, pageFunction: str, *args: Any) -> Any: + """Run ``Page.querySelectorEval`` within the element. + + This method runs ``document.querySelector`` within the element and + passes it as the first argument to ``pageFunction``. If there is no + element matching ``selector``, the method raises + ``ElementHandleError``. + + If ``pageFunction`` returns a promise, then wait for the promise to + resolve and return its value. + + ``ElementHandle.Jeval`` is a shortcut of this method. + + Example: + + .. code:: python + + tweetHandle = await page.querySelector('.tweet') + assert (await tweetHandle.querySelectorEval('.like', 'node => node.innerText')) == 100 + assert (await tweetHandle.Jeval('.retweets', 'node => node.innerText')) == 10 + """ + ... + + async def querySelectorAllEval(self, selector: str, pageFunction: str, *args: Any) -> Any: + """Run ``Page.querySelectorAllEval`` within the element. + + This method runs ``Array.from(document.querySelectorAll)`` within the + element and passes it as the first argument to ``pageFunction``. If + there is no element matching ``selector``, the method raises + ``ElementHandleError``. + + If ``pageFunction`` returns a promise, then wait for the promise to + resolve and return its value. + + Example: + + .. code:: html + +
+
Hello!
+
Hi!
+
+ + .. code:: python + + feedHandle = await page.J('.feed') + assert (await feedHandle.JJeval('.tweet', '(nodes => nodes.map(n => n.innerText))')) == ['Hello!', 'Hi!'] + """ + ... + + J = ... + JJ = ... + Jeval = ... + JJeval = ... + async def xpath(self, expression: str) -> List[ElementHandle]: + """Evaluate the XPath expression relative to this elementHandle. + + If there are no such elements, return an empty list. + + :arg str expression: XPath string to be evaluated. + """ + ... + + Jx = ... + async def isIntersectingViewport(self) -> bool: + """Return ``True`` if the element is visible in the viewport.""" + ... + + + diff --git a/typings/pyppeteer/emulation_manager.pyi b/typings/pyppeteer/emulation_manager.pyi new file mode 100644 index 0000000..f8b769b --- /dev/null +++ b/typings/pyppeteer/emulation_manager.pyi @@ -0,0 +1,19 @@ +""" +This type stub file was generated by pyright. +""" + +from pyppeteer.connection import CDPSession + +"""Emulation Manager module.""" +class EmulationManager: + """EmulationManager class.""" + def __init__(self, client: CDPSession) -> None: + """Make new emulation manager.""" + ... + + async def emulateViewport(self, viewport: dict) -> bool: + """Evaluate viewport.""" + ... + + + diff --git a/typings/pyppeteer/errors.pyi b/typings/pyppeteer/errors.pyi new file mode 100644 index 0000000..0a21e8e --- /dev/null +++ b/typings/pyppeteer/errors.pyi @@ -0,0 +1,37 @@ +""" +This type stub file was generated by pyright. +""" + +import asyncio + +"""Exceptions for pyppeteer package.""" +class PyppeteerError(Exception): + """Base exception for pyppeteer.""" + ... + + +class BrowserError(PyppeteerError): + """Exception raised from browser.""" + ... + + +class ElementHandleError(PyppeteerError): + """ElementHandle related exception.""" + ... + + +class NetworkError(PyppeteerError): + """Network/Protocol related exception.""" + ... + + +class PageError(PyppeteerError): + """Page/Frame related exception.""" + ... + + +class TimeoutError(asyncio.TimeoutError): + """Timeout Error class.""" + ... + + diff --git a/typings/pyppeteer/execution_context.pyi b/typings/pyppeteer/execution_context.pyi new file mode 100644 index 0000000..90dd75d --- /dev/null +++ b/typings/pyppeteer/execution_context.pyi @@ -0,0 +1,88 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Dict, Optional, TYPE_CHECKING +from pyppeteer.connection import CDPSession +from pyppeteer.element_handle import ElementHandle +from pyppeteer.frame_manager import Frame + +"""Execution Context Module.""" +if TYPE_CHECKING: + ... +logger = ... +EVALUATION_SCRIPT_URL = ... +SOURCE_URL_REGEX = ... +class ExecutionContext: + """Execution Context class.""" + def __init__(self, client: CDPSession, contextPayload: Dict, objectHandleFactory: Any, frame: Frame = ...) -> None: + ... + + @property + def frame(self) -> Optional[Frame]: + """Return frame associated with this execution context.""" + ... + + async def evaluate(self, pageFunction: str, *args: Any, force_expr: bool = ...) -> Any: + """Execute ``pageFunction`` on this context. + + Details see :meth:`pyppeteer.page.Page.evaluate`. + """ + ... + + async def evaluateHandle(self, pageFunction: str, *args: Any, force_expr: bool = ...) -> JSHandle: + """Execute ``pageFunction`` on this context. + + Details see :meth:`pyppeteer.page.Page.evaluateHandle`. + """ + ... + + async def queryObjects(self, prototypeHandle: JSHandle) -> JSHandle: + """Send query. + + Details see :meth:`pyppeteer.page.Page.queryObjects`. + """ + ... + + + +class JSHandle: + """JSHandle class. + + JSHandle represents an in-page JavaScript object. JSHandle can be created + with the :meth:`~pyppeteer.page.Page.evaluateHandle` method. + """ + def __init__(self, context: ExecutionContext, client: CDPSession, remoteObject: Dict) -> None: + ... + + @property + def executionContext(self) -> ExecutionContext: + """Get execution context of this handle.""" + ... + + async def getProperty(self, propertyName: str) -> JSHandle: + """Get property value of ``propertyName``.""" + ... + + async def getProperties(self) -> Dict[str, JSHandle]: + """Get all properties of this handle.""" + ... + + async def jsonValue(self) -> Dict: + """Get Jsonized value of this object.""" + ... + + def asElement(self) -> Optional[ElementHandle]: + """Return either null or the object handle itself.""" + ... + + async def dispose(self) -> None: + """Stop referencing the handle.""" + ... + + def toString(self) -> str: + """Get string representation.""" + ... + + + diff --git a/typings/pyppeteer/frame_manager.pyi b/typings/pyppeteer/frame_manager.pyi new file mode 100644 index 0000000..36503d8 --- /dev/null +++ b/typings/pyppeteer/frame_manager.pyi @@ -0,0 +1,270 @@ +""" +This type stub file was generated by pyright. +""" + +import asyncio +from typing import Any, Awaitable, Dict, Generator, List, Optional, Union +from pyee import EventEmitter +from pyppeteer.connection import CDPSession +from pyppeteer.element_handle import ElementHandle +from pyppeteer.execution_context import ExecutionContext, JSHandle + +"""Frame Manager module.""" +logger = ... +class FrameManager(EventEmitter): + """FrameManager class.""" + Events = ... + def __init__(self, client: CDPSession, frameTree: Dict, page: Any) -> None: + """Make new frame manager.""" + ... + + @property + def mainFrame(self) -> Optional[Frame]: + """Return main frame.""" + ... + + def frames(self) -> List[Frame]: + """Return all frames.""" + ... + + def frame(self, frameId: str) -> Optional[Frame]: + """Return :class:`Frame` of ``frameId``.""" + ... + + def executionContextById(self, contextId: str) -> ExecutionContext: + """Get stored ``ExecutionContext`` by ``id``.""" + ... + + def createJSHandle(self, context: ExecutionContext, remoteObject: Dict = ...) -> JSHandle: + """Create JS handle associated to the context id and remote object.""" + ... + + + +class Frame: + """Frame class. + + Frame objects can be obtained via :attr:`pyppeteer.page.Page.mainFrame`. + """ + def __init__(self, client: CDPSession, parentFrame: Optional[Frame], frameId: str) -> None: + ... + + async def executionContext(self) -> Optional[ExecutionContext]: + """Return execution context of this frame. + + Return :class:`~pyppeteer.execution_context.ExecutionContext` + associated to this frame. + """ + ... + + async def evaluateHandle(self, pageFunction: str, *args: Any) -> JSHandle: + """Execute function on this frame. + + Details see :meth:`pyppeteer.page.Page.evaluateHandle`. + """ + ... + + async def evaluate(self, pageFunction: str, *args: Any, force_expr: bool = ...) -> Any: + """Evaluate pageFunction on this frame. + + Details see :meth:`pyppeteer.page.Page.evaluate`. + """ + ... + + async def querySelector(self, selector: str) -> Optional[ElementHandle]: + """Get element which matches `selector` string. + + Details see :meth:`pyppeteer.page.Page.querySelector`. + """ + ... + + async def xpath(self, expression: str) -> List[ElementHandle]: + """Evaluate the XPath expression. + + If there are no such elements in this frame, return an empty list. + + :arg str expression: XPath string to be evaluated. + """ + ... + + async def querySelectorEval(self, selector: str, pageFunction: str, *args: Any) -> Any: + """Execute function on element which matches selector. + + Details see :meth:`pyppeteer.page.Page.querySelectorEval`. + """ + ... + + async def querySelectorAllEval(self, selector: str, pageFunction: str, *args: Any) -> Optional[Dict]: + """Execute function on all elements which matches selector. + + Details see :meth:`pyppeteer.page.Page.querySelectorAllEval`. + """ + ... + + async def querySelectorAll(self, selector: str) -> List[ElementHandle]: + """Get all elements which matches `selector`. + + Details see :meth:`pyppeteer.page.Page.querySelectorAll`. + """ + ... + + J = ... + Jx = ... + Jeval = ... + JJ = ... + JJeval = ... + async def content(self) -> str: + """Get the whole HTML contents of the page.""" + ... + + async def setContent(self, html: str) -> None: + """Set content to this page.""" + ... + + @property + def name(self) -> str: + """Get frame name.""" + ... + + @property + def url(self) -> str: + """Get url of the frame.""" + ... + + @property + def parentFrame(self) -> Optional[Frame]: + """Get parent frame. + + If this frame is main frame or detached frame, return ``None``. + """ + ... + + @property + def childFrames(self) -> List[Frame]: + """Get child frames.""" + ... + + def isDetached(self) -> bool: + """Return ``True`` if this frame is detached. + + Otherwise return ``False``. + """ + ... + + async def injectFile(self, filePath: str) -> str: + """[Deprecated] Inject file to the frame.""" + ... + + async def addScriptTag(self, options: Dict) -> ElementHandle: + """Add script tag to this frame. + + Details see :meth:`pyppeteer.page.Page.addScriptTag`. + """ + ... + + async def addStyleTag(self, options: Dict) -> ElementHandle: + """Add style tag to this frame. + + Details see :meth:`pyppeteer.page.Page.addStyleTag`. + """ + ... + + async def click(self, selector: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Click element which matches ``selector``. + + Details see :meth:`pyppeteer.page.Page.click`. + """ + ... + + async def focus(self, selector: str) -> None: + """Focus element which matches ``selector``. + + Details see :meth:`pyppeteer.page.Page.focus`. + """ + ... + + async def hover(self, selector: str) -> None: + """Mouse hover the element which matches ``selector``. + + Details see :meth:`pyppeteer.page.Page.hover`. + """ + ... + + async def select(self, selector: str, *values: str) -> List[str]: + """Select options and return selected values. + + Details see :meth:`pyppeteer.page.Page.select`. + """ + ... + + async def tap(self, selector: str) -> None: + """Tap the element which matches the ``selector``. + + Details see :meth:`pyppeteer.page.Page.tap`. + """ + ... + + async def type(self, selector: str, text: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Type ``text`` on the element which matches ``selector``. + + Details see :meth:`pyppeteer.page.Page.type`. + """ + ... + + def waitFor(self, selectorOrFunctionOrTimeout: Union[str, int, float], options: Dict[str, Any] = ..., *args: Any, **kwargs: Any) -> Union[Awaitable, WaitTask]: + """Wait until `selectorOrFunctionOrTimeout`. + + Details see :meth:`pyppeteer.page.Page.waitFor`. + """ + ... + + def waitForSelector(self, selector: str, options: Dict[str, Any] = ..., **kwargs: Any) -> WaitTask: + """Wait until element which matches ``selector`` appears on page. + + Details see :meth:`pyppeteer.page.Page.waitForSelector`. + """ + ... + + def waitForXPath(self, xpath: str, options: Dict[str, Any] = ..., **kwargs: Any) -> WaitTask: + """Wait until element which matches ``xpath`` appears on page. + + Details see :meth:`pyppeteer.page.Page.waitForXPath`. + """ + ... + + def waitForFunction(self, pageFunction: str, options: Dict[str, Any] = ..., *args: Any, **kwargs: Any) -> WaitTask: + """Wait until the function completes. + + Details see :meth:`pyppeteer.page.Page.waitForFunction`. + """ + ... + + async def title(self) -> str: + """Get title of the frame.""" + ... + + + +class WaitTask: + """WaitTask class. + + Instance of this class is awaitable. + """ + def __init__(self, frame: Frame, predicateBody: str, title: str, polling: Union[str, int], timeout: float, loop: asyncio.AbstractEventLoop, *args: Any) -> None: + ... + + def __await__(self) -> Generator: + """Make this class **awaitable**.""" + ... + + def terminate(self, error: Exception) -> None: + """Terminate this task.""" + ... + + async def rerun(self) -> None: + """Start polling.""" + ... + + + +waitForPredicatePageFunction = ... diff --git a/typings/pyppeteer/helper.pyi b/typings/pyppeteer/helper.pyi new file mode 100644 index 0000000..580fd6a --- /dev/null +++ b/typings/pyppeteer/helper.pyi @@ -0,0 +1,53 @@ +""" +This type stub file was generated by pyright. +""" + +import asyncio +import logging +from typing import Any, Awaitable, Callable, Dict, List +from pyee import EventEmitter +from pyppeteer.connection import CDPSession + +"""Helper functions.""" +logger = ... +def debugError(_logger: logging.Logger, msg: Any) -> None: + """Log error messages.""" + ... + +def evaluationString(fun: str, *args: Any) -> str: + """Convert function and arguments to str.""" + ... + +def getExceptionMessage(exceptionDetails: dict) -> str: + """Get exception message from `exceptionDetails` object.""" + ... + +def addEventListener(emitter: EventEmitter, eventName: str, handler: Callable) -> Dict[str, Any]: + """Add handler to the emitter and return emitter/handler.""" + ... + +def removeEventListeners(listeners: List[dict]) -> None: + """Remove listeners from emitter.""" + ... + +unserializableValueMap = ... +def valueFromRemoteObject(remoteObject: Dict) -> Any: + """Serialize value of remote object.""" + ... + +def releaseObject(client: CDPSession, remoteObject: dict) -> Awaitable: + """Release remote object.""" + ... + +def waitForEvent(emitter: EventEmitter, eventName: str, predicate: Callable[[Any], bool], timeout: float, loop: asyncio.AbstractEventLoop) -> Awaitable: + """Wait for an event emitted from the emitter.""" + ... + +def get_positive_int(obj: dict, name: str) -> int: + """Get and check the value of name in obj is positive integer.""" + ... + +def is_jsfunc(func: str) -> bool: + """Heuristically check function or expression.""" + ... + diff --git a/typings/pyppeteer/input.pyi b/typings/pyppeteer/input.pyi new file mode 100644 index 0000000..2cefa00 --- /dev/null +++ b/typings/pyppeteer/input.pyi @@ -0,0 +1,204 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Dict, TYPE_CHECKING +from pyppeteer.connection import CDPSession + +"""Keyboard and Mouse module.""" +if TYPE_CHECKING: + ... +class Keyboard: + """Keyboard class provides as api for managing a virtual keyboard. + + The high level api is :meth:`type`, which takes raw characters and + generate proper keydown, keypress/input, and keyup events on your page. + + For finer control, you can use :meth:`down`, :meth:`up`, and + :meth:`sendCharacter` to manually fire events as if they were generated + from a real keyboard. + + An example of holding down ``Shift`` in order to select and delete some + text: + + .. code:: + + await page.keyboard.type('Hello, World!') + await page.keyboard.press('ArrowLeft') + + await page.keyboard.down('Shift') + for i in ' World': + await page.keyboard.press('ArrowLeft') + await page.keyboard.up('Shift') + + await page.keyboard.press('Backspace') + # Result text will end up saying 'Hello!'. + + An example of pressing ``A``: + + .. code:: + + await page.keyboard.down('Shift') + await page.keyboard.press('KeyA') + await page.keyboard.up('Shift') + """ + def __init__(self, client: CDPSession) -> None: + ... + + async def down(self, key: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Dispatch a ``keydown`` event with ``key``. + + If ``key`` is a single character and no modifier keys besides ``Shift`` + are being held down, and a ``keypress``/``input`` event will also + generated. The ``text`` option can be specified to force an ``input`` + event to be generated. + + If ``key`` is a modifier key, like ``Shift``, ``Meta``, or ``Alt``, + subsequent key presses will be sent with that modifier active. To + release the modifier key, use :meth:`up` method. + + :arg str key: Name of key to press, such as ``ArrowLeft``. + :arg dict options: Option can have ``text`` field, and if this option + specified, generate an input event with this text. + + .. note:: + Modifier keys DO influence :meth:`down`. Holding down ``shift`` + will type the text in upper case. + """ + ... + + async def up(self, key: str) -> None: + """Dispatch a ``keyup`` event of the ``key``. + + :arg str key: Name of key to release, such as ``ArrowLeft``. + """ + ... + + async def sendCharacter(self, char: str) -> None: + """Send character into the page. + + This method dispatches a ``keypress`` and ``input`` event. This does + not send a ``keydown`` or ``keyup`` event. + + .. note:: + Modifier keys DO NOT effect :meth:`sendCharacter`. Holding down + ``shift`` will not type the text in upper case. + """ + ... + + async def type(self, text: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Type characters into a focused element. + + This method sends ``keydown``, ``keypress``/``input``, and ``keyup`` + event for each character in the ``text``. + + To press a special key, like ``Control`` or ``ArrowDown``, use + :meth:`press` method. + + :arg str text: Text to type into a focused element. + :arg dict options: Options can have ``delay`` (int|float) field, which + specifies time to wait between key presses in milliseconds. Defaults + to 0. + + .. note:: + Modifier keys DO NOT effect :meth:`type`. Holding down ``shift`` + will not type the text in upper case. + """ + ... + + async def press(self, key: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Press ``key``. + + If ``key`` is a single character and no modifier keys besides + ``Shift`` are being held down, a ``keypress``/``input`` event will also + generated. The ``text`` option can be specified to force an input event + to be generated. + + :arg str key: Name of key to press, such as ``ArrowLeft``. + + This method accepts the following options: + + * ``text`` (str): If specified, generates an input event with this + text. + * ``delay`` (int|float): Time to wait between ``keydown`` and + ``keyup``. Defaults to 0. + + .. note:: + Modifier keys DO effect :meth:`press`. Holding down ``Shift`` will + type the text in upper case. + """ + ... + + + +class Mouse: + """Mouse class. + + The :class:`Mouse` operates in main-frame CSS pixels relative to the + top-left corner of the viewport. + """ + def __init__(self, client: CDPSession, keyboard: Keyboard) -> None: + ... + + async def move(self, x: float, y: float, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Move mouse cursor (dispatches a ``mousemove`` event). + + Options can accepts ``steps`` (int) field. If this ``steps`` option + specified, Sends intermediate ``mousemove`` events. Defaults to 1. + """ + ... + + async def click(self, x: float, y: float, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Click button at (``x``, ``y``). + + Shortcut to :meth:`move`, :meth:`down`, and :meth:`up`. + + This method accepts the following options: + + * ``button`` (str): ``left``, ``right``, or ``middle``, defaults to + ``left``. + * ``clickCount`` (int): defaults to 1. + * ``delay`` (int|float): Time to wait between ``mousedown`` and + ``mouseup`` in milliseconds. Defaults to 0. + """ + ... + + async def down(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Press down button (dispatches ``mousedown`` event). + + This method accepts the following options: + + * ``button`` (str): ``left``, ``right``, or ``middle``, defaults to + ``left``. + * ``clickCount`` (int): defaults to 1. + """ + ... + + async def up(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Release pressed button (dispatches ``mouseup`` event). + + This method accepts the following options: + + * ``button`` (str): ``left``, ``right``, or ``middle``, defaults to + ``left``. + * ``clickCount`` (int): defaults to 1. + """ + ... + + + +class Touchscreen: + """Touchscreen class.""" + def __init__(self, client: CDPSession, keyboard: Keyboard) -> None: + """Make new touchscreen object.""" + ... + + async def tap(self, x: float, y: float) -> None: + """Tap (``x``, ``y``). + + Dispatches a ``touchstart`` and ``touchend`` event. + """ + ... + + + diff --git a/typings/pyppeteer/launcher.pyi b/typings/pyppeteer/launcher.pyi new file mode 100644 index 0000000..148b12d --- /dev/null +++ b/typings/pyppeteer/launcher.pyi @@ -0,0 +1,162 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Dict, List, TYPE_CHECKING +from pyppeteer.browser import Browser + +"""Chromium process launcher module.""" +if TYPE_CHECKING: + ... +logger = ... +pyppeteer_home = ... +CHROME_PROFILE_PATH = ... +DEFAULT_ARGS = ... +class Launcher: + """Chrome process launcher class.""" + def __init__(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Make new launcher.""" + ... + + async def launch(self) -> Browser: + """Start chrome process and return `Browser` object.""" + ... + + async def ensureInitialPage(self, browser: Browser) -> None: + """Wait for initial page target to be created.""" + ... + + def waitForChromeToClose(self) -> None: + """Terminate chrome.""" + ... + + async def killChrome(self) -> None: + """Terminate chromium process.""" + ... + + + +def get_ws_endpoint(url) -> str: + ... + +async def launch(options: Dict[str, Any] = ..., **kwargs: Any) -> Browser: + """Start chrome process and return :class:`~pyppeteer.browser.Browser`. + This function is a shortcut to :meth:`Launcher(options, **kwargs).launch`. + Available options are: + * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to + ``False``. + * ``headless`` (bool): Whether to run browser in headless mode. Defaults to + ``True`` unless ``appMode`` or ``devtools`` options is ``True``. + * ``executablePath`` (str): Path to a Chromium or Chrome executable to run + instead of default bundled Chromium. + * ``slowMo`` (int|float): Slow down pyppeteer operations by the specified + amount of milliseconds. + * ``defaultViewport`` (dict): Set a consistent viewport for each page. + Defaults to an 800x600 viewport. ``None`` disables default viewport. + * ``width`` (int): page width in pixels. + * ``height`` (int): page height in pixels. + * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be + thought as dpr). Defaults to ``1``. + * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into + account. Defaults to ``False``. + * ``hasTouch`` (bool): Specify if viewport supports touch events. + Defaults to ``False``. + * ``isLandscape`` (bool): Specify if viewport is in landscape mode. + Defaults to ``False``. + * ``args`` (List[str]): Additional arguments (flags) to pass to the browser + process. + * ``ignoreDefaultArgs`` (bool or List[str]): If ``True``, do not use + :func:`~pyppeteer.defaultArgs`. If list is given, then filter out given + default arguments. Dangerous option; use with care. Defaults to + ``False``. + * ``handleSIGINT`` (bool): Close the browser process on Ctrl+C. Defaults to + ``True``. + * ``handleSIGTERM`` (bool): Close the browser process on SIGTERM. Defaults + to ``True``. + * ``handleSIGHUP`` (bool): Close the browser process on SIGHUP. Defaults to + ``True``. + * ``dumpio`` (bool): Whether to pipe the browser process stdout and stderr + into ``process.stdout`` and ``process.stderr``. Defaults to ``False``. + * ``userDataDir`` (str): Path to a user data directory. + * ``env`` (dict): Specify environment variables that will be visible to the + browser. Defaults to same as python process. + * ``devtools`` (bool): Whether to auto-open a DevTools panel for each tab. + If this option is ``True``, the ``headless`` option will be set + ``False``. + * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the + root logger. + * ``autoClose`` (bool): Automatically close browser process when script + completed. Defaults to ``True``. + * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**). + * ``appMode`` (bool): Deprecated. + This function combines 3 steps: + 1. Infer a set of flags to launch chromium with using + :func:`~pyppeteer.defaultArgs`. + 2. Launch browser and start managing its process according to the + ``executablePath``, ``handleSIGINT``, ``dumpio``, and other options. + 3. Create an instance of :class:`~pyppeteer.browser.Browser` class and + initialize it with ``defaultViewport``, ``slowMo``, and + ``ignoreHTTPSErrors``. + ``ignoreDefaultArgs`` option can be used to customize behavior on the (1) + step. For example, to filter out ``--mute-audio`` from default arguments: + .. code:: + browser = await launch(ignoreDefaultArgs=['--mute-audio']) + .. note:: + Pyppeteer can also be used to control the Chrome browser, but it works + best with the version of Chromium it is bundled with. There is no + guarantee it will work with any other version. Use ``executablePath`` + option with extreme caution. + """ + ... + +async def connect(options: Dict[str, Any] = ..., **kwargs: Any) -> Browser: + """Connect to the existing chrome. + ``browserWSEndpoint`` or ``browserURL`` option is necessary to connect to + the chrome. The format of ``browserWSEndpoint`` is + ``ws://${host}:${port}/devtools/browser/`` and format of ``browserURL`` + is ``http://127.0.0.1:9222```. + The value of ``browserWSEndpoint`` can get by :attr:`~pyppeteer.browser.Browser.wsEndpoint`. + Available options are: + * ``browserWSEndpoint`` (str): A browser websocket endpoint to connect to. + * ``browserURL`` (str): A browser URL to connect to. + * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to + ``False``. + * ``defaultViewport`` (dict): Set a consistent viewport for each page. + Defaults to an 800x600 viewport. ``None`` disables default viewport. + * ``width`` (int): page width in pixels. + * ``height`` (int): page height in pixels. + * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be + thought as dpr). Defaults to ``1``. + * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into + account. Defaults to ``False``. + * ``hasTouch`` (bool): Specify if viewport supports touch events. + Defaults to ``False``. + * ``isLandscape`` (bool): Specify if viewport is in landscape mode. + Defaults to ``False``. + * ``slowMo`` (int|float): Slow down pyppeteer's by the specified amount of + milliseconds. + * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the + root logger. + * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**). + """ + ... + +def executablePath() -> str: + """Get executable path of default chromium.""" + ... + +def defaultArgs(options: Dict[str, Any] = ..., **kwargs: Any) -> List[str]: + """Get the default flags the chromium will be launched with. + ``options`` or keyword arguments are set of configurable options to set on + the browser. Can have the following fields: + * ``headless`` (bool): Whether to run browser in headless mode. Defaults to + ``True`` unless the ``devtools`` option is ``True``. + * ``args`` (List[str]): Additional arguments to pass to the browser + instance. The list of chromium flags can be found + `here `__. + * ``userDataDir`` (str): Path to a User Data Directory. + * ``devtools`` (bool): Whether to auto-open DevTools panel for each tab. If + this option is ``True``, the ``headless`` option will be set ``False``. + """ + ... + diff --git a/typings/pyppeteer/multimap.pyi b/typings/pyppeteer/multimap.pyi new file mode 100644 index 0000000..965e04b --- /dev/null +++ b/typings/pyppeteer/multimap.pyi @@ -0,0 +1,59 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, List, Optional + +"""Multimap module.""" +class Multimap: + """Multimap class.""" + def __init__(self) -> None: + """Make new multimap.""" + ... + + def set(self, key: Optional[str], value: Any) -> None: + """Set value.""" + ... + + def get(self, key: Optional[str]) -> List[Any]: + """Get values.""" + ... + + def has(self, key: Optional[str]) -> bool: + """Check key is in this map.""" + ... + + def hasValue(self, key: Optional[str], value: Any) -> bool: + """Check value is in this map.""" + ... + + def size(self) -> int: + """Length of this map.""" + ... + + def delete(self, key: Optional[str], value: Any) -> bool: + """Delete value from key.""" + ... + + def deleteAll(self, key: Optional[str]) -> None: + """Delete all value of the key.""" + ... + + def firstValue(self, key: Optional[str]) -> Any: + """Get first value of the key.""" + ... + + def firstKey(self) -> Optional[str]: + """Get first key.""" + ... + + def valuesArray(self) -> List[Any]: + """Get all values as list.""" + ... + + def clear(self) -> None: + """Clear all entries of this map.""" + ... + + + diff --git a/typings/pyppeteer/navigator_watcher.pyi b/typings/pyppeteer/navigator_watcher.pyi new file mode 100644 index 0000000..145383b --- /dev/null +++ b/typings/pyppeteer/navigator_watcher.pyi @@ -0,0 +1,25 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Dict +from pyppeteer.frame_manager import Frame, FrameManager + +"""Navigator Watcher module.""" +class NavigatorWatcher: + """NavigatorWatcher class.""" + def __init__(self, frameManager: FrameManager, frame: Frame, timeout: int, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Make new navigator watcher.""" + ... + + def navigationPromise(self) -> Any: + """Return navigation promise.""" + ... + + def cancel(self) -> None: + """Cancel navigation.""" + ... + + + +pyppeteerToProtocolLifecycle = ... diff --git a/typings/pyppeteer/network_manager.pyi b/typings/pyppeteer/network_manager.pyi new file mode 100644 index 0000000..1edd83f --- /dev/null +++ b/typings/pyppeteer/network_manager.pyi @@ -0,0 +1,324 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Awaitable, Dict, List, Optional, TYPE_CHECKING, Union +from pyee import EventEmitter +from pyppeteer.connection import CDPSession +from pyppeteer.frame_manager import Frame, FrameManager + +"""Network Manager module.""" +if TYPE_CHECKING: + ... +logger = ... +class NetworkManager(EventEmitter): + """NetworkManager class.""" + Events = ... + def __init__(self, client: CDPSession, frameManager: FrameManager) -> None: + """Make new NetworkManager.""" + ... + + async def authenticate(self, credentials: Dict[str, str]) -> None: + """Provide credentials for http auth.""" + ... + + async def setExtraHTTPHeaders(self, extraHTTPHeaders: Dict[str, str]) -> None: + """Set extra http headers.""" + ... + + def extraHTTPHeaders(self) -> Dict[str, str]: + """Get extra http headers.""" + ... + + async def setOfflineMode(self, value: bool) -> None: + """Change offline mode enable/disable.""" + ... + + async def setUserAgent(self, userAgent: str) -> None: + """Set user agent.""" + ... + + async def setRequestInterception(self, value: bool) -> None: + """Enable request interception.""" + ... + + + +class Request: + """Request class. + + Whenever the page sends a request, such as for a network resource, the + following events are emitted by pyppeteer's page: + + - ``'request'``: emitted when the request is issued by the page. + - ``'response'``: emitted when/if the response is received for the request. + - ``'requestfinished'``: emitted when the response body is downloaded and + the request is complete. + + If request fails at some point, then instead of ``'requestfinished'`` event + (and possibly instead of ``'response'`` event), the ``'requestfailed'`` + event is emitted. + + If request gets a ``'redirect'`` response, the request is successfully + finished with the ``'requestfinished'`` event, and a new request is issued + to a redirect url. + """ + def __init__(self, client: CDPSession, requestId: Optional[str], interceptionId: Optional[str], isNavigationRequest: bool, allowInterception: bool, url: str, resourceType: str, payload: dict, frame: Optional[Frame], redirectChain: List[Request]) -> None: + ... + + @property + def url(self) -> str: + """URL of this request.""" + ... + + @property + def resourceType(self) -> str: + """Resource type of this request perceived by the rendering engine. + + ResourceType will be one of the following: ``document``, + ``stylesheet``, ``image``, ``media``, ``font``, ``script``, + ``texttrack``, ``xhr``, ``fetch``, ``eventsource``, ``websocket``, + ``manifest``, ``other``. + """ + ... + + @property + def method(self) -> Optional[str]: + """Return this request's method (GET, POST, etc.).""" + ... + + @property + def postData(self) -> Optional[str]: + """Return post body of this request.""" + ... + + @property + def headers(self) -> Dict: + """Return a dictionary of HTTP headers of this request. + + All header names are lower-case. + """ + ... + + @property + def response(self) -> Optional[Response]: + """Return matching :class:`Response` object, or ``None``. + + If the response has not been received, return ``None``. + """ + ... + + @property + def frame(self) -> Optional[Frame]: + """Return a matching :class:`~pyppeteer.frame_manager.frame` object. + + Return ``None`` if navigating to error page. + """ + ... + + def isNavigationRequest(self) -> bool: + """Whether this request is driving frame's navigation.""" + ... + + @property + def redirectChain(self) -> List[Request]: + """Return chain of requests initiated to fetch a resource. + + * If there are no redirects and request was successful, the chain will + be empty. + * If a server responds with at least a single redirect, then the chain + will contain all the requests that were redirected. + + ``redirectChain`` is shared between all the requests of the same chain. + """ + ... + + def failure(self) -> Optional[Dict]: + """Return error text. + + Return ``None`` unless this request was failed, as reported by + ``requestfailed`` event. + + When request failed, this method return dictionary which has a + ``errorText`` field, which contains human-readable error message, e.g. + ``'net::ERR_RAILED'``. + """ + ... + + async def continue_(self, overrides: Dict = ...) -> None: + """Continue request with optional request overrides. + + To use this method, request interception should be enabled by + :meth:`pyppeteer.page.Page.setRequestInterception`. If request + interception is not enabled, raise ``NetworkError``. + + ``overrides`` can have the following fields: + + * ``url`` (str): If set, the request url will be changed. + * ``method`` (str): If set, change the request method (e.g. ``GET``). + * ``postData`` (str): If set, change the post data or request. + * ``headers`` (dict): If set, change the request HTTP header. + """ + ... + + async def respond(self, response: Dict) -> None: + """Fulfills request with given response. + + To use this, request interception should by enabled by + :meth:`pyppeteer.page.Page.setRequestInterception`. Request + interception is not enabled, raise ``NetworkError``. + + ``response`` is a dictionary which can have the following fields: + + * ``status`` (int): Response status code, defaults to 200. + * ``headers`` (dict): Optional response headers. + * ``contentType`` (str): If set, equals to setting ``Content-Type`` + response header. + * ``body`` (str|bytes): Optional response body. + """ + ... + + async def abort(self, errorCode: str = ...) -> None: + """Abort request. + + To use this, request interception should be enabled by + :meth:`pyppeteer.page.Page.setRequestInterception`. + If request interception is not enabled, raise ``NetworkError``. + + ``errorCode`` is an optional error code string. Defaults to ``failed``, + could be one of the following: + + - ``aborted``: An operation was aborted (due to user action). + - ``accessdenied``: Permission to access a resource, other than the + network, was denied. + - ``addressunreachable``: The IP address is unreachable. This usually + means that there is no route to the specified host or network. + - ``blockedbyclient``: The client chose to block the request. + - ``blockedbyresponse``: The request failed because the request was + delivered along with requirements which are not met + ('X-Frame-Options' and 'Content-Security-Policy' ancestor check, + for instance). + - ``connectionaborted``: A connection timeout as a result of not + receiving an ACK for data sent. + - ``connectionclosed``: A connection was closed (corresponding to a TCP + FIN). + - ``connectionfailed``: A connection attempt failed. + - ``connectionrefused``: A connection attempt was refused. + - ``connectionreset``: A connection was reset (corresponding to a TCP + RST). + - ``internetdisconnected``: The Internet connection has been lost. + - ``namenotresolved``: The host name could not be resolved. + - ``timedout``: An operation timed out. + - ``failed``: A generic failure occurred. + """ + ... + + + +errorReasons = ... +class Response: + """Response class represents responses which are received by ``Page``.""" + def __init__(self, client: CDPSession, request: Request, status: int, headers: Dict[str, str], fromDiskCache: bool, fromServiceWorker: bool, securityDetails: Dict = ...) -> None: + ... + + @property + def url(self) -> str: + """URL of the response.""" + ... + + @property + def ok(self) -> bool: + """Return bool whether this request is successful (200-299) or not.""" + ... + + @property + def status(self) -> int: + """Status code of the response.""" + ... + + @property + def headers(self) -> Dict: + """Return dictionary of HTTP headers of this response. + + All header names are lower-case. + """ + ... + + @property + def securityDetails(self) -> Union[Dict, SecurityDetails]: + """Return security details associated with this response. + + Security details if the response was received over the secure + connection, or `None` otherwise. + """ + ... + + def buffer(self) -> Awaitable[bytes]: + """Return awaitable which resolves to bytes with response body.""" + ... + + async def text(self) -> str: + """Get text representation of response body.""" + ... + + async def json(self) -> dict: + """Get JSON representation of response body.""" + ... + + @property + def request(self) -> Request: + """Get matching :class:`Request` object.""" + ... + + @property + def fromCache(self) -> bool: + """Return ``True`` if the response was served from cache. + + Here `cache` is either the browser's disk cache or memory cache. + """ + ... + + @property + def fromServiceWorker(self) -> bool: + """Return ``True`` if the response was served by a service worker.""" + ... + + + +def generateRequestHash(request: dict) -> str: + """Generate request hash.""" + ... + +class SecurityDetails: + """Class represents responses which are received by page.""" + def __init__(self, subjectName: str, issuer: str, validFrom: int, validTo: int, protocol: str) -> None: + ... + + @property + def subjectName(self) -> str: + """Return the subject to which the certificate was issued to.""" + ... + + @property + def issuer(self) -> str: + """Return a string with the name of issuer of the certificate.""" + ... + + @property + def validFrom(self) -> int: + """Return UnixTime of the start of validity of the certificate.""" + ... + + @property + def validTo(self) -> int: + """Return UnixTime of the end of validity of the certificate.""" + ... + + @property + def protocol(self) -> str: + """Return string of with the security protocol, e.g. "TLS1.2".""" + ... + + + +statusTexts = ... diff --git a/typings/pyppeteer/options.pyi b/typings/pyppeteer/options.pyi new file mode 100644 index 0000000..7ba96fc --- /dev/null +++ b/typings/pyppeteer/options.pyi @@ -0,0 +1,6 @@ +""" +This type stub file was generated by pyright. +""" + +"""Options module.""" +config = ... diff --git a/typings/pyppeteer/page.pyi b/typings/pyppeteer/page.pyi new file mode 100644 index 0000000..f88011e --- /dev/null +++ b/typings/pyppeteer/page.pyi @@ -0,0 +1,1011 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Awaitable, Callable, Dict, List, Optional, TYPE_CHECKING, Union +from pyee import EventEmitter +from pyppeteer.connection import CDPSession +from pyppeteer.coverage import Coverage +from pyppeteer.element_handle import ElementHandle +from pyppeteer.execution_context import JSHandle +from pyppeteer.frame_manager import Frame +from pyppeteer.input import Keyboard, Mouse, Touchscreen +from pyppeteer.network_manager import Request, Response +from pyppeteer.tracing import Tracing +from pyppeteer.worker import Worker +from pyppeteer.browser import Browser, Target + +"""Page module.""" +if TYPE_CHECKING: + ... +logger = ... +class Page(EventEmitter): + """Page class. + + This class provides methods to interact with a single tab of chrome. One + :class:`~pyppeteer.browser.Browser` object might have multiple Page object. + + The :class:`Page` class emits various :attr:`~Page.Events` which can be + handled by using ``on`` or ``once`` method, which is inherited from + `pyee `_'s ``EventEmitter`` class. + """ + Events = ... + PaperFormats: Dict[str, Dict[str, float]] = ... + @staticmethod + async def create(client: CDPSession, target: Target, ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], screenshotTaskQueue: list = ...) -> Page: + """Async function which makes new page object.""" + ... + + def __init__(self, client: CDPSession, target: Target, frameTree: Dict, ignoreHTTPSErrors: bool, screenshotTaskQueue: list = ...) -> None: + ... + + @property + def target(self) -> Target: + """Return a target this page created from.""" + ... + + @property + def browser(self) -> Browser: + """Get the browser the page belongs to.""" + ... + + @property + def mainFrame(self) -> Optional[Frame]: + """Get main :class:`~pyppeteer.frame_manager.Frame` of this page.""" + ... + + @property + def keyboard(self) -> Keyboard: + """Get :class:`~pyppeteer.input.Keyboard` object.""" + ... + + @property + def touchscreen(self) -> Touchscreen: + """Get :class:`~pyppeteer.input.Touchscreen` object.""" + ... + + @property + def coverage(self) -> Coverage: + """Return :class:`~pyppeteer.coverage.Coverage`.""" + ... + + async def tap(self, selector: str) -> None: + """Tap the element which matches the ``selector``. + + :arg str selector: A selector to search element to touch. + """ + ... + + @property + def tracing(self) -> Tracing: + """Get tracing object.""" + ... + + @property + def frames(self) -> List[Frame]: + """Get all frames of this page.""" + ... + + @property + def workers(self) -> List[Worker]: + """Get all workers of this page.""" + ... + + async def setRequestInterception(self, value: bool) -> None: + """Enable/disable request interception. + + Activating request interception enables + :class:`~pyppeteer.network_manager.Request` class's + :meth:`~pyppeteer.network_manager.Request.abort`, + :meth:`~pyppeteer.network_manager.Request.continue_`, and + :meth:`~pyppeteer.network_manager.Request.response` methods. + This provides the capability to modify network requests that are made + by a page. + + Once request interception is enabled, every request will stall unless + it's continued, responded or aborted. + + An example of a native request interceptor that aborts all image + requests: + + .. code:: python + + browser = await launch() + page = await browser.newPage() + await page.setRequestInterception(True) + + async def intercept(request): + if request.url.endswith('.png') or request.url.endswith('.jpg'): + await request.abort() + else: + await request.continue_() + + page.on('request', lambda req: asyncio.ensure_future(intercept(req))) + await page.goto('https://example.com') + await browser.close() + """ + ... + + async def setOfflineMode(self, enabled: bool) -> None: + """Set offline mode enable/disable.""" + ... + + def setDefaultNavigationTimeout(self, timeout: int) -> None: + """Change the default maximum navigation timeout. + + This method changes the default timeout of 30 seconds for the following + methods: + + * :meth:`goto` + * :meth:`goBack` + * :meth:`goForward` + * :meth:`reload` + * :meth:`waitForNavigation` + + :arg int timeout: Maximum navigation time in milliseconds. Pass ``0`` + to disable timeout. + """ + ... + + async def querySelector(self, selector: str) -> Optional[ElementHandle]: + """Get an Element which matches ``selector``. + + :arg str selector: A selector to search element. + :return Optional[ElementHandle]: If element which matches the + ``selector`` is found, return its + :class:`~pyppeteer.element_handle.ElementHandle`. If not found, + returns ``None``. + """ + ... + + async def evaluateHandle(self, pageFunction: str, *args: Any) -> JSHandle: + """Execute function on this page. + + Difference between :meth:`~pyppeteer.page.Page.evaluate` and + :meth:`~pyppeteer.page.Page.evaluateHandle` is that + ``evaluateHandle`` returns JSHandle object (not value). + + :arg str pageFunction: JavaScript function to be executed. + """ + ... + + async def queryObjects(self, prototypeHandle: JSHandle) -> JSHandle: + """Iterate js heap and finds all the objects with the handle. + + :arg JSHandle prototypeHandle: JSHandle of prototype object. + """ + ... + + async def querySelectorEval(self, selector: str, pageFunction: str, *args: Any) -> Any: + """Execute function with an element which matches ``selector``. + + :arg str selector: A selector to query page for. + :arg str pageFunction: String of JavaScript function to be evaluated on + browser. This function takes an element which + matches the selector as a first argument. + :arg Any args: Arguments to pass to ``pageFunction``. + + This method raises error if no element matched the ``selector``. + """ + ... + + async def querySelectorAllEval(self, selector: str, pageFunction: str, *args: Any) -> Any: + """Execute function with all elements which matches ``selector``. + + :arg str selector: A selector to query page for. + :arg str pageFunction: String of JavaScript function to be evaluated on + browser. This function takes Array of the + matched elements as the first argument. + :arg Any args: Arguments to pass to ``pageFunction``. + """ + ... + + async def querySelectorAll(self, selector: str) -> List[ElementHandle]: + """Get all element which matches ``selector`` as a list. + + :arg str selector: A selector to search element. + :return List[ElementHandle]: List of + :class:`~pyppeteer.element_handle.ElementHandle` which matches the + ``selector``. If no element is matched to the ``selector``, return + empty list. + """ + ... + + async def xpath(self, expression: str) -> List[ElementHandle]: + """Evaluate the XPath expression. + + If there are no such elements in this page, return an empty list. + + :arg str expression: XPath string to be evaluated. + """ + ... + + J = ... + Jeval = ... + JJ = ... + JJeval = ... + Jx = ... + async def cookies(self, *urls: str) -> List[Dict[str, Union[str, int, bool]]]: + """Get cookies. + + If no URLs are specified, this method returns cookies for the current + page URL. If URLs are specified, only cookies for those URLs are + returned. + + Returned cookies are list of dictionaries which contain these fields: + + * ``name`` (str) + * ``value`` (str) + * ``url`` (str) + * ``domain`` (str) + * ``path`` (str) + * ``expires`` (number): Unix time in seconds + * ``httpOnly`` (bool) + * ``secure`` (bool) + * ``session`` (bool) + * ``sameSite`` (str): ``'Strict'`` or ``'Lax'`` + """ + ... + + async def deleteCookie(self, *cookies: dict) -> None: + """Delete cookie. + + ``cookies`` should be dictionaries which contain these fields: + + * ``name`` (str): **required** + * ``url`` (str) + * ``domain`` (str) + * ``path`` (str) + * ``secure`` (bool) + """ + ... + + async def setCookie(self, *cookies: dict) -> None: + """Set cookies. + + ``cookies`` should be dictionaries which contain these fields: + + * ``name`` (str): **required** + * ``value`` (str): **required** + * ``url`` (str) + * ``domain`` (str) + * ``path`` (str) + * ``expires`` (number): Unix time in seconds + * ``httpOnly`` (bool) + * ``secure`` (bool) + * ``sameSite`` (str): ``'Strict'`` or ``'Lax'`` + """ + ... + + async def addScriptTag(self, options: Dict[str, Any] = ..., **kwargs: str) -> ElementHandle: + """Add script tag to this page. + + One of ``url``, ``path`` or ``content`` option is necessary. + * ``url`` (string): URL of a script to add. + * ``path`` (string): Path to the local JavaScript file to add. + * ``content`` (string): JavaScript string to add. + * ``type`` (string): Script type. Use ``module`` in order to load a + JavaScript ES6 module. + + :return ElementHandle: :class:`~pyppeteer.element_handle.ElementHandle` + of added tag. + """ + ... + + async def addStyleTag(self, options: Dict[str, Any] = ..., **kwargs: str) -> ElementHandle: + """Add style or link tag to this page. + + One of ``url``, ``path`` or ``content`` option is necessary. + * ``url`` (string): URL of the link tag to add. + * ``path`` (string): Path to the local CSS file to add. + * ``content`` (string): CSS string to add. + + :return ElementHandle: :class:`~pyppeteer.element_handle.ElementHandle` + of added tag. + """ + ... + + async def injectFile(self, filePath: str) -> str: + """[Deprecated] Inject file to this page. + + This method is deprecated. Use :meth:`addScriptTag` instead. + """ + ... + + async def exposeFunction(self, name: str, pyppeteerFunction: Callable[..., Any]) -> None: + """Add python function to the browser's ``window`` object as ``name``. + + Registered function can be called from chrome process. + + :arg string name: Name of the function on the window object. + :arg Callable pyppeteerFunction: Function which will be called on + python process. This function should + not be asynchronous function. + """ + ... + + async def authenticate(self, credentials: Dict[str, str]) -> Any: + """Provide credentials for http authentication. + + ``credentials`` should be ``None`` or dict which has ``username`` and + ``password`` field. + """ + ... + + async def setExtraHTTPHeaders(self, headers: Dict[str, str]) -> None: + """Set extra HTTP headers. + + The extra HTTP headers will be sent with every request the page + initiates. + + .. note:: + ``page.setExtraHTTPHeaders`` does not guarantee the order of + headers in the outgoing requests. + + :arg Dict headers: A dictionary containing additional http headers to + be sent with every requests. All header values must + be string. + """ + ... + + async def setUserAgent(self, userAgent: str) -> None: + """Set user agent to use in this page. + + :arg str userAgent: Specific user agent to use in this page + """ + ... + + async def metrics(self) -> Dict[str, Any]: + """Get metrics. + + Returns dictionary containing metrics as key/value pairs: + + * ``Timestamp`` (number): The timestamp when the metrics sample was + taken. + * ``Documents`` (int): Number of documents in the page. + * ``Frames`` (int): Number of frames in the page. + * ``JSEventListeners`` (int): Number of events in the page. + * ``Nodes`` (int): Number of DOM nodes in the page. + * ``LayoutCount`` (int): Total number of full partial page layout. + * ``RecalcStyleCount`` (int): Total number of page style + recalculations. + * ``LayoutDuration`` (int): Combined duration of page duration. + * ``RecalcStyleDuration`` (int): Combined duration of all page style + recalculations. + * ``ScriptDuration`` (int): Combined duration of JavaScript + execution. + * ``TaskDuration`` (int): Combined duration of all tasks performed by + the browser. + * ``JSHeapUsedSize`` (float): Used JavaScript heap size. + * ``JSHeapTotalSize`` (float): Total JavaScript heap size. + """ + ... + + @property + def url(self) -> str: + """Get URL of this page.""" + ... + + async def content(self) -> str: + """Get the full HTML contents of the page. + + Returns HTML including the doctype. + """ + ... + + async def setContent(self, html: str) -> None: + """Set content to this page. + + :arg str html: HTML markup to assign to the page. + """ + ... + + async def goto(self, url: str, options: Dict[str, Any] = ..., **kwargs: Any) -> Optional[Response]: + """Go to the ``url``. + + :arg string url: URL to navigate page to. The url should include + scheme, e.g. ``https://``. + + Available options are: + + * ``timeout`` (int): Maximum navigation time in milliseconds, defaults + to 30 seconds, pass ``0`` to disable timeout. The default value can + be changed by using the :meth:`setDefaultNavigationTimeout` method. + * ``waitUntil`` (str|List[str]): When to consider navigation succeeded, + defaults to ``load``. Given a list of event strings, navigation is + considered to be successful after all events have been fired. Events + can be either: + + * ``load``: when ``load`` event is fired. + * ``domcontentloaded``: when the ``DOMContentLoaded`` event is fired. + * ``networkidle0``: when there are no more than 0 network connections + for at least 500 ms. + * ``networkidle2``: when there are no more than 2 network connections + for at least 500 ms. + + The ``Page.goto`` will raise errors if: + + * there's an SSL error (e.g. in case of self-signed certificates) + * target URL is invalid + * the ``timeout`` is exceeded during navigation + * then main resource failed to load + + .. note:: + :meth:`goto` either raise error or return a main resource response. + The only exceptions are navigation to ``about:blank`` or navigation + to the same URL with a different hash, which would succeed and + return ``None``. + + .. note:: + Headless mode doesn't support navigation to a PDF document. + """ + ... + + async def reload(self, options: Dict[str, Any] = ..., **kwargs: Any) -> Optional[Response]: + """Reload this page. + + Available options are same as :meth:`goto` method. + """ + ... + + async def waitForNavigation(self, options: Dict[str, Any] = ..., **kwargs: Any) -> Optional[Response]: + """Wait for navigation. + + Available options are same as :meth:`goto` method. + + This returns :class:`~pyppeteer.network_manager.Response` when the page + navigates to a new URL or reloads. It is useful for when you run code + which will indirectly cause the page to navigate. In case of navigation + to a different anchor or navigation due to + `History API `_ + usage, the navigation will return ``None``. + + Consider this example: + + .. code:: + + navigationPromise = async.ensure_future(page.waitForNavigation()) + await page.click('a.my-link') # indirectly cause a navigation + await navigationPromise # wait until navigation finishes + + or, + + .. code:: + + await asyncio.wait([ + page.click('a.my-link'), + page.waitForNavigation(), + ]) + + .. note:: + Usage of the History API to change the URL is considered a + navigation. + """ + ... + + async def waitForRequest(self, urlOrPredicate: Union[str, Callable[[Request], bool]], options: Dict[str, Any] = ..., **kwargs: Any) -> Request: + """Wait for request. + + :arg urlOrPredicate: A URL or function to wait for. + + This method accepts below options: + + * ``timeout`` (int|float): Maximum wait time in milliseconds, defaults + to 30 seconds, pass ``0`` to disable the timeout. + + Example: + + .. code:: + + firstRequest = await page.waitForRequest('http://example.com/resource') + finalRequest = await page.waitForRequest(lambda req: req.url == 'http://example.com' and req.method == 'GET') + return firstRequest.url + """ + ... + + async def waitForResponse(self, urlOrPredicate: Union[str, Callable[[Response], bool]], options: Dict[str, Any] = ..., **kwargs: Any) -> Response: + """Wait for response. + + :arg urlOrPredicate: A URL or function to wait for. + + This method accepts below options: + + * ``timeout`` (int|float): Maximum wait time in milliseconds, defaults + to 30 seconds, pass ``0`` to disable the timeout. + + Example: + + .. code:: + + firstResponse = await page.waitForResponse('http://example.com/resource') + finalResponse = await page.waitForResponse(lambda res: res.url == 'http://example.com' and res.status == 200) + return finalResponse.ok + """ + ... + + async def goBack(self, options: Dict[str, Any] = ..., **kwargs: Any) -> Optional[Response]: + """Navigate to the previous page in history. + + Available options are same as :meth:`goto` method. + + If cannot go back, return ``None``. + """ + ... + + async def goForward(self, options: Dict[str, Any] = ..., **kwargs: Any) -> Optional[Response]: + """Navigate to the next page in history. + + Available options are same as :meth:`goto` method. + + If cannot go forward, return ``None``. + """ + ... + + async def bringToFront(self) -> None: + """Bring page to front (activate tab).""" + ... + + async def emulate(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Emulate given device metrics and user agent. + + This method is a shortcut for calling two methods: + + * :meth:`setUserAgent` + * :meth:`setViewport` + + ``options`` is a dictionary containing these fields: + + * ``viewport`` (dict) + + * ``width`` (int): page width in pixels. + * ``height`` (int): page width in pixels. + * ``deviceScaleFactor`` (float): Specify device scale factor (can be + thought as dpr). Defaults to 1. + * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken + into account. Defaults to ``False``. + * ``hasTouch`` (bool): Specifies if viewport supports touch events. + Defaults to ``False``. + * ``isLandscape`` (bool): Specifies if viewport is in landscape mode. + Defaults to ``False``. + + * ``userAgent`` (str): user agent string. + """ + ... + + async def setJavaScriptEnabled(self, enabled: bool) -> None: + """Set JavaScript enable/disable.""" + ... + + async def setBypassCSP(self, enabled: bool) -> None: + """Toggles bypassing page's Content-Security-Policy. + + .. note:: + CSP bypassing happens at the moment of CSP initialization rather + then evaluation. Usually this means that ``page.setBypassCSP`` + should be called before navigating to the domain. + """ + ... + + async def emulateMedia(self, mediaType: str = ...) -> None: + """Emulate css media type of the page. + + :arg str mediaType: Changes the CSS media type of the page. The only + allowed values are ``'screen'``, ``'print'``, and + ``None``. Passing ``None`` disables media + emulation. + """ + ... + + async def setViewport(self, viewport: dict) -> None: + """Set viewport. + + Available options are: + * ``width`` (int): page width in pixel. + * ``height`` (int): page height in pixel. + * ``deviceScaleFactor`` (float): Default to 1.0. + * ``isMobile`` (bool): Default to ``False``. + * ``hasTouch`` (bool): Default to ``False``. + * ``isLandscape`` (bool): Default to ``False``. + """ + ... + + @property + def viewport(self) -> Optional[Dict]: + """Get viewport as a dictionary or None. + + Fields of returned dictionary is same as :meth:`setViewport`. + """ + ... + + async def evaluate(self, pageFunction: str, *args: Any, force_expr: bool = ...) -> Any: + """Execute js-function or js-expression on browser and get result. + + :arg str pageFunction: String of js-function/expression to be executed + on the browser. + :arg bool force_expr: If True, evaluate `pageFunction` as expression. + If False (default), try to automatically detect + function or expression. + + note: ``force_expr`` option is a keyword only argument. + """ + ... + + async def evaluateOnNewDocument(self, pageFunction: str, *args: str) -> None: + """Add a JavaScript function to the document. + + This function would be invoked in one of the following scenarios: + + * whenever the page is navigated + * whenever the child frame is attached or navigated. In this case, the + function is invoked in the context of the newly attached frame. + """ + ... + + async def setCacheEnabled(self, enabled: bool = ...) -> None: + """Enable/Disable cache for each request. + + By default, caching is enabled. + """ + ... + + async def screenshot(self, options: Dict[str, Any] = ..., **kwargs: Any) -> Union[bytes, str]: + """Take a screen shot. + + The following options are available: + + * ``path`` (str): The file path to save the image to. The screenshot + type will be inferred from the file extension. + * ``type`` (str): Specify screenshot type, can be either ``jpeg`` or + ``png``. Defaults to ``png``. + * ``quality`` (int): The quality of the image, between 0-100. Not + applicable to ``png`` image. + * ``fullPage`` (bool): When true, take a screenshot of the full + scrollable page. Defaults to ``False``. + * ``clip`` (dict): An object which specifies clipping region of the + page. This option should have the following fields: + + * ``x`` (int): x-coordinate of top-left corner of clip area. + * ``y`` (int): y-coordinate of top-left corner of clip area. + * ``width`` (int): width of clipping area. + * ``height`` (int): height of clipping area. + + * ``omitBackground`` (bool): Hide default white background and allow + capturing screenshot with transparency. + * ``encoding`` (str): The encoding of the image, can be either + ``'base64'`` or ``'binary'``. Defaults to ``'binary'``. + """ + ... + + async def pdf(self, options: Dict[str, Any] = ..., **kwargs: Any) -> bytes: + """Generate a pdf of the page. + + Options: + + * ``path`` (str): The file path to save the PDF. + * ``scale`` (float): Scale of the webpage rendering, defaults to ``1``. + * ``displayHeaderFooter`` (bool): Display header and footer. + Defaults to ``False``. + * ``headerTemplate`` (str): HTML template for the print header. Should + be valid HTML markup with following classes. + + * ``date``: formatted print date + * ``title``: document title + * ``url``: document location + * ``pageNumber``: current page number + * ``totalPages``: total pages in the document + + * ``footerTemplate`` (str): HTML template for the print footer. Should + use the same template as ``headerTemplate``. + * ``printBackground`` (bool): Print background graphics. Defaults to + ``False``. + * ``landscape`` (bool): Paper orientation. Defaults to ``False``. + * ``pageRanges`` (string): Paper ranges to print, e.g., '1-5,8,11-13'. + Defaults to empty string, which means all pages. + * ``format`` (str): Paper format. If set, takes priority over + ``width`` or ``height``. Defaults to ``Letter``. + * ``width`` (str): Paper width, accepts values labeled with units. + * ``height`` (str): Paper height, accepts values labeled with units. + * ``margin`` (dict): Paper margins, defaults to ``None``. + + * ``top`` (str): Top margin, accepts values labeled with units. + * ``right`` (str): Right margin, accepts values labeled with units. + * ``bottom`` (str): Bottom margin, accepts values labeled with units. + * ``left`` (str): Left margin, accepts values labeled with units. + + * ``preferCSSPageSize``: Give any CSS ``@page`` size declared in the + page priority over what is declared in ``width`` and ``height`` or + ``format`` options. Defaults to ``False``, which will scale the + content to fit the paper size. + + :return: Return generated PDF ``bytes`` object. + + .. note:: + Generating a pdf is currently only supported in headless mode. + + :meth:`pdf` generates a pdf of the page with ``print`` css media. To + generate a pdf with ``screen`` media, call + ``page.emulateMedia('screen')`` before calling :meth:`pdf`. + + .. note:: + By default, :meth:`pdf` generates a pdf with modified colors for + printing. Use the ``--webkit-print-color-adjust`` property to force + rendering of exact colors. + + .. code:: + + await page.emulateMedia('screen') + await page.pdf({'path': 'page.pdf'}) + + The ``width``, ``height``, and ``margin`` options accept values labeled + with units. Unlabeled values are treated as pixels. + + A few examples: + + - ``page.pdf({'width': 100})``: prints with width set to 100 pixels. + - ``page.pdf({'width': '100px'})``: prints with width set to 100 pixels. + - ``page.pdf({'width': '10cm'})``: prints with width set to 100 centimeters. + + All available units are: + + - ``px``: pixel + - ``in``: inch + - ``cm``: centimeter + - ``mm``: millimeter + + The format options are: + + - ``Letter``: 8.5in x 11in + - ``Legal``: 8.5in x 14in + - ``Tabloid``: 11in x 17in + - ``Ledger``: 17in x 11in + - ``A0``: 33.1in x 46.8in + - ``A1``: 23.4in x 33.1in + - ``A2``: 16.5in x 23.4in + - ``A3``: 11.7in x 16.5in + - ``A4``: 8.27in x 11.7in + - ``A5``: 5.83in x 8.27in + - ``A6``: 4.13in x 5.83in + + .. note:: + ``headerTemplate`` and ``footerTemplate`` markup have the following + limitations: + + 1. Script tags inside templates are not evaluated. + 2. Page styles are not visible inside templates. + """ + ... + + async def plainText(self) -> str: + """[Deprecated] Get page content as plain text.""" + ... + + async def title(self) -> str: + """Get page's title.""" + ... + + async def close(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Close this page. + + Available options: + + * ``runBeforeUnload`` (bool): Defaults to ``False``. Whether to run the + `before unload `_ + page handlers. + + By defaults, :meth:`close` **does not** run beforeunload handlers. + + .. note:: + If ``runBeforeUnload`` is passed as ``True``, a ``beforeunload`` + dialog might be summoned and should be handled manually via page's + ``dialog`` event. + """ + ... + + def isClosed(self) -> bool: + """Indicate that the page has been closed.""" + ... + + @property + def mouse(self) -> Mouse: + """Get :class:`~pyppeteer.input.Mouse` object.""" + ... + + async def click(self, selector: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Click element which matches ``selector``. + + This method fetches an element with ``selector``, scrolls it into view + if needed, and then uses :attr:`mouse` to click in the center of the + element. If there's no element matching ``selector``, the method raises + ``PageError``. + + Available options are: + + * ``button`` (str): ``left``, ``right``, or ``middle``, defaults to + ``left``. + * ``clickCount`` (int): defaults to 1. + * ``delay`` (int|float): Time to wait between ``mousedown`` and + ``mouseup`` in milliseconds. defaults to 0. + + .. note:: If this method triggers a navigation event and there's a + separate :meth:`waitForNavigation`, you may end up with a race + condition that yields unexpected results. The correct pattern for + click and wait for navigation is the following:: + + await asyncio.gather( + page.waitForNavigation(waitOptions), + page.click(selector, clickOptions), + ) + """ + ... + + async def hover(self, selector: str) -> None: + """Mouse hover the element which matches ``selector``. + + If no element matched the ``selector``, raise ``PageError``. + """ + ... + + async def focus(self, selector: str) -> None: + """Focus the element which matches ``selector``. + + If no element matched the ``selector``, raise ``PageError``. + """ + ... + + async def select(self, selector: str, *values: str) -> List[str]: + """Select options and return selected values. + + If no element matched the ``selector``, raise ``ElementHandleError``. + """ + ... + + async def type(self, selector: str, text: str, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Type ``text`` on the element which matches ``selector``. + + If no element matched the ``selector``, raise ``PageError``. + + Details see :meth:`pyppeteer.input.Keyboard.type`. + """ + ... + + def waitFor(self, selectorOrFunctionOrTimeout: Union[str, int, float], options: Dict[str, Any] = ..., *args: Any, **kwargs: Any) -> Awaitable: + """Wait for function, timeout, or element which matches on page. + + This method behaves differently with respect to the first argument: + + * If ``selectorOrFunctionOrTimeout`` is number (int or float), then it + is treated as a timeout in milliseconds and this returns future which + will be done after the timeout. + * If ``selectorOrFunctionOrTimeout`` is a string of JavaScript + function, this method is a shortcut to :meth:`waitForFunction`. + * If ``selectorOrFunctionOrTimeout`` is a selector string or xpath + string, this method is a shortcut to :meth:`waitForSelector` or + :meth:`waitForXPath`. If the string starts with ``//``, the string is + treated as xpath. + + Pyppeteer tries to automatically detect function or selector, but + sometimes miss-detects. If not work as you expected, use + :meth:`waitForFunction` or :meth:`waitForSelector` directly. + + :arg selectorOrFunctionOrTimeout: A selector, xpath, or function + string, or timeout (milliseconds). + :arg Any args: Arguments to pass the function. + :return: Return awaitable object which resolves to a JSHandle of the + success value. + + Available options: see :meth:`waitForFunction` or + :meth:`waitForSelector` + """ + ... + + def waitForSelector(self, selector: str, options: Dict[str, Any] = ..., **kwargs: Any) -> Awaitable: + """Wait until element which matches ``selector`` appears on page. + + Wait for the ``selector`` to appear in page. If at the moment of + calling the method the ``selector`` already exists, the method will + return immediately. If the selector doesn't appear after the + ``timeout`` milliseconds of waiting, the function will raise error. + + :arg str selector: A selector of an element to wait for. + :return: Return awaitable object which resolves when element specified + by selector string is added to DOM. + + This method accepts the following options: + + * ``visible`` (bool): Wait for element to be present in DOM and to be + visible; i.e. to not have ``display: none`` or ``visibility: hidden`` + CSS properties. Defaults to ``False``. + * ``hidden`` (bool): Wait for element to not be found in the DOM or to + be hidden, i.e. have ``display: none`` or ``visibility: hidden`` CSS + properties. Defaults to ``False``. + * ``timeout`` (int|float): Maximum time to wait for in milliseconds. + Defaults to 30000 (30 seconds). Pass ``0`` to disable timeout. + """ + ... + + def waitForXPath(self, xpath: str, options: Dict[str, Any] = ..., **kwargs: Any) -> Awaitable: + """Wait until element which matches ``xpath`` appears on page. + + Wait for the ``xpath`` to appear in page. If the moment of calling the + method the ``xpath`` already exists, the method will return + immediately. If the xpath doesn't appear after ``timeout`` milliseconds + of waiting, the function will raise exception. + + + :arg str xpath: A [xpath] of an element to wait for. + :return: Return awaitable object which resolves when element specified + by xpath string is added to DOM. + + Available options are: + + * ``visible`` (bool): wait for element to be present in DOM and to be + visible, i.e. to not have ``display: none`` or ``visibility: hidden`` + CSS properties. Defaults to ``False``. + * ``hidden`` (bool): wait for element to not be found in the DOM or to + be hidden, i.e. have ``display: none`` or ``visibility: hidden`` CSS + properties. Defaults to ``False``. + * ``timeout`` (int|float): maximum time to wait for in milliseconds. + Defaults to 30000 (30 seconds). Pass ``0`` to disable timeout. + """ + ... + + def waitForFunction(self, pageFunction: str, options: Dict[str, Any] = ..., *args: str, **kwargs: Any) -> Awaitable: + """Wait until the function completes and returns a truthy value. + + :arg Any args: Arguments to pass to ``pageFunction``. + :return: Return awaitable object which resolves when the + ``pageFunction`` returns a truthy value. It resolves to a + :class:`~pyppeteer.execution_context.JSHandle` of the truthy + value. + + This method accepts the following options: + + * ``polling`` (str|number): An interval at which the ``pageFunction`` + is executed, defaults to ``raf``. If ``polling`` is a number, then + it is treated as an interval in milliseconds at which the function + would be executed. If ``polling`` is a string, then it can be one of + the following values: + + * ``raf``: to constantly execute ``pageFunction`` in + ``requestAnimationFrame`` callback. This is the tightest polling + mode which is suitable to observe styling changes. + * ``mutation``: to execute ``pageFunction`` on every DOM mutation. + + * ``timeout`` (int|float): maximum time to wait for in milliseconds. + Defaults to 30000 (30 seconds). Pass ``0`` to disable timeout. + """ + ... + + + +supportedMetrics = ... +unitToPixels = ... +def convertPrintParameterToInches(parameter: Union[None, int, float, str]) -> Optional[float]: + """Convert print parameter to inches.""" + ... + +class ConsoleMessage: + """Console message class. + + ConsoleMessage objects are dispatched by page via the ``console`` event. + """ + def __init__(self, type: str, text: str, args: List[JSHandle] = ...) -> None: + ... + + @property + def type(self) -> str: + """Return type of this message.""" + ... + + @property + def text(self) -> str: + """Return text representation of this message.""" + ... + + @property + def args(self) -> List[JSHandle]: + """Return list of args (JSHandle) of this message.""" + ... + + + diff --git a/typings/pyppeteer/target.pyi b/typings/pyppeteer/target.pyi new file mode 100644 index 0000000..87af8f3 --- /dev/null +++ b/typings/pyppeteer/target.pyi @@ -0,0 +1,64 @@ +""" +This type stub file was generated by pyright. +""" + +import asyncio +from typing import Any, Callable, Coroutine, Dict, List, Optional, TYPE_CHECKING +from pyppeteer.connection import CDPSession +from pyppeteer.page import Page +from pyppeteer.browser import Browser, BrowserContext + +"""Target module.""" +if TYPE_CHECKING: + ... +class Target: + """Browser's target class.""" + def __init__(self, targetInfo: Dict, browserContext: BrowserContext, sessionFactory: Callable[[], Coroutine[Any, Any, CDPSession]], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], screenshotTaskQueue: List, loop: asyncio.AbstractEventLoop) -> None: + ... + + async def createCDPSession(self) -> CDPSession: + """Create a Chrome Devtools Protocol session attached to the target.""" + ... + + async def page(self) -> Optional[Page]: + """Get page of this target. + + If the target is not of type "page" or "background_page", return + ``None``. + """ + ... + + @property + def url(self) -> str: + """Get url of this target.""" + ... + + @property + def type(self) -> str: + """Get type of this target. + + Type can be ``'page'``, ``'background_page'``, ``'service_worker'``, + ``'browser'``, or ``'other'``. + """ + ... + + @property + def browser(self) -> Browser: + """Get the browser the target belongs to.""" + ... + + @property + def browserContext(self) -> BrowserContext: + """Return the browser context the target belongs to.""" + ... + + @property + def opener(self) -> Optional[Target]: + """Get the target that opened this target. + + Top-level targets return ``None``. + """ + ... + + + diff --git a/typings/pyppeteer/tracing.pyi b/typings/pyppeteer/tracing.pyi new file mode 100644 index 0000000..c4dfd24 --- /dev/null +++ b/typings/pyppeteer/tracing.pyi @@ -0,0 +1,47 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any +from pyppeteer.connection import CDPSession + +"""Tracing module.""" +class Tracing: + """Tracing class. + + You can use :meth:`start` and :meth:`stop` to create a trace file which can + be opened in Chrome DevTools or + `timeline viewer `_. + + .. code:: + + await page.tracing.start({'path': 'trace.json'}) + await page.goto('https://www.google.com') + await page.tracing.stop() + """ + def __init__(self, client: CDPSession) -> None: + ... + + async def start(self, options: Dict[str, Any] = ..., **kwargs: Any) -> None: + """Start tracing. + + Only one trace can be active at a time per browser. + + This method accepts the following options: + + * ``path`` (str): A path to write the trace file to. + * ``screenshots`` (bool): Capture screenshots in the trace. + * ``categories`` (List[str]): Specify custom categories to use instead + of default. + """ + ... + + async def stop(self) -> str: + """Stop tracing. + + :return: trace data as string. + """ + ... + + + diff --git a/typings/pyppeteer/us_keyboard_layout.pyi b/typings/pyppeteer/us_keyboard_layout.pyi new file mode 100644 index 0000000..00ba4fb --- /dev/null +++ b/typings/pyppeteer/us_keyboard_layout.pyi @@ -0,0 +1,6 @@ +""" +This type stub file was generated by pyright. +""" + +"""US Keyboard Definition.""" +keyDefinitions = ... diff --git a/typings/pyppeteer/util.pyi b/typings/pyppeteer/util.pyi new file mode 100644 index 0000000..ebfa853 --- /dev/null +++ b/typings/pyppeteer/util.pyi @@ -0,0 +1,16 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Dict, Optional + +"""Utility functions.""" +__all__ = ['check_chromium', 'chromium_executable', 'download_chromium', 'get_free_port', 'merge_dict'] +def get_free_port() -> int: + """Get free port.""" + ... + +def merge_dict(dict1: Optional[Dict], dict2: Optional[Dict]) -> Dict: + """Merge two dictionaries into new one.""" + ... + diff --git a/typings/pyppeteer/worker.pyi b/typings/pyppeteer/worker.pyi new file mode 100644 index 0000000..e98bc97 --- /dev/null +++ b/typings/pyppeteer/worker.pyi @@ -0,0 +1,51 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, Dict, List, TYPE_CHECKING +from pyee import EventEmitter +from pyppeteer.execution_context import ExecutionContext, JSHandle +from pyppeteer.connection import CDPSession + +"""Worker module.""" +if TYPE_CHECKING: + ... +logger = ... +class Worker(EventEmitter): + """The Worker class represents a WebWorker. + + The events `workercreated` and `workerdestroyed` are emitted on the page + object to signal the worker lifecycle. + + .. code:: + + page.on('workercreated', lambda worker: print('Worker created:', worker.url)) + """ + def __init__(self, client: CDPSession, url: str, consoleAPICalled: Callable[[str, List[JSHandle]], None], exceptionThrown: Callable[[Dict], None]) -> None: + ... + + @property + def url(self) -> str: + """Return URL.""" + ... + + async def executionContext(self) -> ExecutionContext: + """Return ExecutionContext.""" + ... + + async def evaluate(self, pageFunction: str, *args: Any) -> Any: + """Evaluate ``pageFunction`` with ``args``. + + Shortcut for ``(await worker.executionContext).evaluate(pageFunction, *args)``. + """ + ... + + async def evaluateHandle(self, pageFunction: str, *args: Any) -> JSHandle: + """Evaluate ``pageFunction`` with ``args`` and return :class:`~pyppeteer.execution_context.JSHandle`. + + Shortcut for ``(await worker.executionContext).evaluateHandle(pageFunction, *args)``. + """ + ... + + + diff --git a/typings/sphinx/__init__.pyi b/typings/sphinx/__init__.pyi new file mode 100644 index 0000000..98d48fe --- /dev/null +++ b/typings/sphinx/__init__.pyi @@ -0,0 +1,20 @@ +""" +This type stub file was generated by pyright. +""" + +import os +import warnings +import subprocess +from os import path +from .deprecation import RemovedInNextVersionWarning + +"""The Sphinx documentation toolchain.""" +if 'PYTHONWARNINGS' not in os.environ: + ... +__version__ = ... +__display_version__ = ... +version_info = ... +package_dir = ... +_in_development = ... +if _in_development: + ... diff --git a/typings/sphinx/__main__.pyi b/typings/sphinx/__main__.pyi new file mode 100644 index 0000000..1534213 --- /dev/null +++ b/typings/sphinx/__main__.pyi @@ -0,0 +1,5 @@ +""" +This type stub file was generated by pyright. +""" + +"""The Sphinx documentation toolchain.""" diff --git a/typings/sphinx/addnodes.pyi b/typings/sphinx/addnodes.pyi new file mode 100644 index 0000000..020d92e --- /dev/null +++ b/typings/sphinx/addnodes.pyi @@ -0,0 +1,483 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils import nodes +from collections.abc import Sequence +from docutils.nodes import Element +from sphinx.application import Sphinx + +"""Document tree nodes that Sphinx defines on top of those in Docutils.""" +if TYPE_CHECKING: + ... +_DEPRECATED_OBJECTS = ... +def __getattr__(name): # -> Incomplete: + ... + +class document(nodes.document): + """The document root element patched by Sphinx. + + This fixes that document.set_id() does not support a node having multiple node Ids. + see https://sourceforge.net/p/docutils/patches/167/ + + .. important:: This is only for Sphinx internal use. Please don't use this + in your extensions. It will be removed without deprecation period. + """ + def set_id(self, node: Element, msgnode: Element | None = ..., suggested_prefix: str = ...) -> str: + ... + + + +class translatable(nodes.Node): + """Node which supports translation. + + The translation goes forward with following steps: + + 1. Preserve original translatable messages + 2. Apply translated messages from message catalog + 3. Extract preserved messages (for gettext builder) + + The translatable nodes MUST preserve original messages. + And these messages should not be overridden at applying step. + Because they are used at final step; extraction. + """ + def preserve_original_messages(self) -> None: + """Preserve original translatable messages.""" + ... + + def apply_translated_message(self, original_message: str, translated_message: str) -> None: + """Apply translated message.""" + ... + + def extract_original_messages(self) -> Sequence[str]: + """Extract translation messages. + + :returns: list of extracted messages or messages generator + """ + ... + + + +class not_smartquotable: + """A node which does not support smart-quotes.""" + support_smartquotes = ... + + +class toctree(nodes.General, nodes.Element, translatable): + """Node for inserting a "TOC tree".""" + def preserve_original_messages(self) -> None: + ... + + def apply_translated_message(self, original_message: str, translated_message: str) -> None: + ... + + def extract_original_messages(self) -> list[str]: + ... + + + +class _desc_classes_injector(nodes.Element, not_smartquotable): + """Helper base class for injecting a fixed list of classes. + + Use as the first base class. + """ + classes: list[str] = ... + def __init__(self, *args: Any, **kwargs: Any) -> None: + ... + + + +class desc(nodes.Admonition, nodes.Element): + """Node for a list of object signatures and a common description of them. + + Contains one or more :py:class:`desc_signature` nodes + and then a single :py:class:`desc_content` node. + + This node always has two classes: + + - The name of the domain it belongs to, e.g., ``py`` or ``cpp``. + - The name of the object type in the domain, e.g., ``function``. + """ + ... + + +class desc_signature(_desc_classes_injector, nodes.Part, nodes.Inline, nodes.TextElement): + """Node for a single object signature. + + As default the signature is a single-line signature. + Set ``is_multiline = True`` to describe a multi-line signature. + In that case all child nodes must be :py:class:`desc_signature_line` nodes. + + This node always has the classes ``sig``, ``sig-object``, and the domain it belongs to. + """ + classes = ... + @property + def child_text_separator(self): # -> Literal[' ']: + ... + + + +class desc_signature_line(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for a line in a multi-line object signature. + + It should only be used as a child of a :py:class:`desc_signature` + with ``is_multiline`` set to ``True``. + Set ``add_permalink = True`` for the line that should get the permalink. + """ + sphinx_line_type = ... + + +class desc_content(nodes.General, nodes.Element): + """Node for object description content. + + Must be the last child node in a :py:class:`desc` node. + """ + ... + + +class desc_inline(_desc_classes_injector, nodes.Inline, nodes.TextElement): + """Node for a signature fragment in inline text. + + This is for example used for roles like :rst:role:`cpp:expr`. + + This node always has the classes ``sig``, ``sig-inline``, + and the name of the domain it belongs to. + """ + classes = ... + def __init__(self, domain: str, *args: Any, **kwargs: Any) -> None: + ... + + + +class desc_name(_desc_classes_injector, nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for the main object name. + + For example, in the declaration of a Python class ``MyModule.MyClass``, + the main name is ``MyClass``. + + This node always has the class ``sig-name``. + """ + classes = ... + + +class desc_addname(_desc_classes_injector, nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for additional name parts for an object. + + For example, in the declaration of a Python class ``MyModule.MyClass``, + the additional name part is ``MyModule.``. + + This node always has the class ``sig-prename``. + """ + classes = ... + + +desc_classname = desc_addname +class desc_type(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for return types or object type names.""" + ... + + +class desc_returns(desc_type): + """Node for a "returns" annotation (a la -> in Python).""" + def astext(self) -> str: + ... + + + +class desc_parameterlist(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for a general parameter list. + + As default the parameter list is written in line with the rest of the signature. + Set ``multi_line_parameter_list = True`` to describe a multi-line parameter list. + In that case each parameter will then be written on its own, indented line. + """ + child_text_separator = ... + def astext(self): # -> str: + ... + + + +class desc_type_parameter_list(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for a general type parameter list. + + As default the type parameters list is written in line with the rest of the signature. + Set ``multi_line_parameter_list = True`` to describe a multi-line type parameters list. + In that case each type parameter will then be written on its own, indented line. + """ + child_text_separator = ... + def astext(self): # -> str: + ... + + + +class desc_parameter(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for a single parameter.""" + ... + + +class desc_type_parameter(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for a single type parameter.""" + ... + + +class desc_optional(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for marking optional parts of the parameter list.""" + child_text_separator = ... + def astext(self) -> str: + ... + + + +class desc_annotation(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for signature annotations (not Python 3-style annotations).""" + ... + + +SIG_ELEMENTS: set[type[desc_sig_element]] = ... +class desc_sig_element(nodes.inline, _desc_classes_injector): + """Common parent class of nodes for inline text of a signature.""" + classes: list[str] = ... + def __init__(self, rawsource: str = ..., text: str = ..., *children: Element, **attributes: Any) -> None: + ... + + def __init_subclass__(cls, *, _sig_element=..., **kwargs): # -> None: + ... + + + +class desc_sig_space(desc_sig_element, _sig_element=True): + """Node for a space in a signature.""" + classes = ... + def __init__(self, rawsource: str = ..., text: str = ..., *children: Element, **attributes: Any) -> None: + ... + + + +class desc_sig_name(desc_sig_element, _sig_element=True): + """Node for an identifier in a signature.""" + classes = ... + + +class desc_sig_operator(desc_sig_element, _sig_element=True): + """Node for an operator in a signature.""" + classes = ... + + +class desc_sig_punctuation(desc_sig_element, _sig_element=True): + """Node for punctuation in a signature.""" + classes = ... + + +class desc_sig_keyword(desc_sig_element, _sig_element=True): + """Node for a general keyword in a signature.""" + classes = ... + + +class desc_sig_keyword_type(desc_sig_element, _sig_element=True): + """Node for a keyword which is a built-in type in a signature.""" + classes = ... + + +class desc_sig_literal_number(desc_sig_element, _sig_element=True): + """Node for a numeric literal in a signature.""" + classes = ... + + +class desc_sig_literal_string(desc_sig_element, _sig_element=True): + """Node for a string literal in a signature.""" + classes = ... + + +class desc_sig_literal_char(desc_sig_element, _sig_element=True): + """Node for a character literal in a signature.""" + classes = ... + + +class versionmodified(nodes.Admonition, nodes.TextElement): + """Node for version change entries. + + Currently used for "versionadded", "versionchanged" and "deprecated" + directives. + """ + ... + + +class seealso(nodes.Admonition, nodes.Element): + """Custom "see also" admonition.""" + ... + + +class productionlist(nodes.Admonition, nodes.Element): + """Node for grammar production lists. + + Contains ``production`` nodes. + """ + ... + + +class production(nodes.Part, nodes.Inline, nodes.FixedTextElement): + """Node for a single grammar production rule.""" + ... + + +class index(nodes.Invisible, nodes.Inline, nodes.TextElement): + """Node for index entries. + + This node is created by the ``index`` directive and has one attribute, + ``entries``. Its value is a list of 5-tuples of ``(entrytype, entryname, + target, ignored, key)``. + + *entrytype* is one of "single", "pair", "double", "triple". + + *key* is categorization characters (usually a single character) for + general index page. For the details of this, please see also: + :rst:dir:`glossary` and issue #2320. + """ + ... + + +class centered(nodes.Part, nodes.TextElement): + """This node is deprecated.""" + ... + + +class acks(nodes.Element): + """Special node for "acks" lists.""" + ... + + +class hlist(nodes.Element): + """Node for "horizontal lists", i.e. lists that should be compressed to + take up less vertical space. + """ + ... + + +class hlistcol(nodes.Element): + """Node for one column in a horizontal list.""" + ... + + +class compact_paragraph(nodes.paragraph): + """Node for a compact paragraph (which never makes a

node).""" + ... + + +class glossary(nodes.Element): + """Node to insert a glossary.""" + ... + + +class only(nodes.Element): + """Node for "only" directives (conditional inclusion based on tags).""" + ... + + +class start_of_file(nodes.Element): + """Node to mark start of a new file, used in the LaTeX builder only.""" + ... + + +class highlightlang(nodes.Element): + """Inserted to set the highlight language and line number options for + subsequent code blocks. + """ + ... + + +class tabular_col_spec(nodes.Element): + """Node for specifying tabular columns, used for LaTeX output.""" + ... + + +class pending_xref(nodes.Inline, nodes.Element): + """Node for cross-references that cannot be resolved without complete + information about all documents. + + These nodes are resolved before writing output, in + BuildEnvironment.resolve_references. + """ + child_text_separator = ... + + +class pending_xref_condition(nodes.Inline, nodes.TextElement): + """Node representing a potential way to create a cross-reference and the + condition in which this way should be used. + + This node is only allowed to be placed under a :py:class:`pending_xref` + node. A **pending_xref** node must contain either no **pending_xref_condition** + nodes or it must only contains **pending_xref_condition** nodes. + + The cross-reference resolver will replace a :py:class:`pending_xref` which + contains **pending_xref_condition** nodes by the content of exactly one of + those **pending_xref_condition** nodes' content. It uses the **condition** + attribute to decide which **pending_xref_condition** node's content to + use. For example, let us consider how the cross-reference resolver acts on:: + + + + StringIO + + + io.StringIO + + If the cross-reference resolver successfully resolves the cross-reference, + then it rewrites the **pending_xref** as:: + + + + StringIO + + Otherwise, if the cross-reference resolution failed, it rewrites the + **pending_xref** as:: + + + + io.StringIO + + The **pending_xref_condition** node should have **condition** attribute. + Domains can be store their individual conditions into the attribute to + filter contents on resolving phase. As a reserved condition name, + ``condition="*"`` is used for the fallback of resolution failure. + Additionally, as a recommended condition name, ``condition="resolved"`` + represents a resolution success in the intersphinx module. + + .. versionadded:: 4.0 + """ + ... + + +class number_reference(nodes.reference): + """Node for number references, similar to pending_xref.""" + ... + + +class download_reference(nodes.reference): + """Node for download references, similar to pending_xref.""" + ... + + +class literal_emphasis(nodes.emphasis, not_smartquotable): + """Node that behaves like `emphasis`, but further text processors are not + applied (e.g. smartypants for HTML output). + """ + ... + + +class literal_strong(nodes.strong, not_smartquotable): + """Node that behaves like `strong`, but further text processors are not + applied (e.g. smartypants for HTML output). + """ + ... + + +class manpage(nodes.Inline, nodes.FixedTextElement): + """Node for references to manpages.""" + ... + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/application.pyi b/typings/sphinx/application.pyi new file mode 100644 index 0000000..5eeb20e --- /dev/null +++ b/typings/sphinx/application.pyi @@ -0,0 +1,901 @@ +""" +This type stub file was generated by pyright. +""" + +import os +from collections.abc import Sequence +from typing import Any, Callable, Protocol, Optional, IO, TYPE_CHECKING +from docutils.nodes import Element, TextElement +from docutils.parsers.rst import Directive +from docutils.transforms import Transform +from pygments.lexer import Lexer +from docutils import nodes +from docutils.parsers import Parser +from sphinx.builders import Builder +from sphinx.config import Config +from sphinx.domains import Domain, Index +from sphinx.environment.collectors import EnvironmentCollector +from sphinx.roles import XRefRole +from sphinx.theming import Theme +from sphinx.util.typing import RoleFunction, TitleGetter + +"""Sphinx application class and extensibility interface. + +Gracefully adapted from the TextPress system by Armin. +""" + +class GenericCallback(Protocol): + def __call__(self, *args: Optional[Any], **kwargs: Optional[Any]) -> None: + ... + +if TYPE_CHECKING: + ... +builtin_extensions: tuple[str, ...] = ... +_first_party_extensions = ... +_first_party_themes = ... +ENV_PICKLE_FILENAME = ... +logger = ... +class Sphinx: + """The main application class and extensibility interface. + + :ivar srcdir: Directory containing source. + :ivar confdir: Directory containing ``conf.py``. + :ivar doctreedir: Directory for storing pickled doctrees. + :ivar outdir: Directory for storing build documents. + """ + warningiserror: bool + _warncount: int + config: Config + def __init__(self, srcdir: str | os.PathLike[str], confdir: str | os.PathLike[str] | None, outdir: str | os.PathLike[str], doctreedir: str | os.PathLike[str], buildername: str, confoverrides: dict | None = ..., status: IO | None = ..., warning: IO | None = ..., freshenv: bool = ..., warningiserror: bool = ..., tags: list[str] | None = ..., verbosity: int = ..., parallel: int = ..., keep_going: bool = ..., pdb: bool = ...) -> None: + ... + + def preload_builder(self, name: str) -> None: + ... + + def create_builder(self, name: str) -> Builder: + ... + + def build(self, force_all: bool = ..., filenames: list[str] | None = ...) -> None: + ... + + def setup_extension(self, extname: str) -> None: + """Import and setup a Sphinx extension module. + + Load the extension given by the module *name*. Use this if your + extension needs the features provided by another extension. No-op if + called twice. + """ + ... + + @staticmethod + def require_sphinx(version: tuple[int, int] | str) -> None: + """Check the Sphinx version if requested. + + Compare *version* with the version of the running Sphinx, and abort the + build when it is too old. + + :param version: The required version in the form of ``major.minor`` or + ``(major, minor)``. + + .. versionadded:: 1.0 + .. versionchanged:: 7.1 + Type of *version* now allows ``(major, minor)`` form. + """ + ... + + def connect(self, event: str, callback: GenericCallback, priority: int = ...) -> int: + """Register *callback* to be called when *event* is emitted. + + For details on available core events and the arguments of callback + functions, please see :ref:`events`. + + :param event: The name of target event + :param callback: Callback function for the event + :param priority: The priority of the callback. The callbacks will be invoked + in order of *priority* (ascending). + :return: A listener ID. It can be used for :meth:`disconnect`. + + .. versionchanged:: 3.0 + + Support *priority* + """ + ... + + def disconnect(self, listener_id: int) -> None: + """Unregister callback by *listener_id*. + + :param listener_id: A listener_id that :meth:`connect` returns + """ + ... + + def emit(self, event: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ...) -> list: + """Emit *event* and pass *arguments* to the callback functions. + + Return the return values of all callbacks as a list. Do not emit core + Sphinx events in extensions! + + :param event: The name of event that will be emitted + :param args: The arguments for the event + :param allowed_exceptions: The list of exceptions that are allowed in the callbacks + + .. versionchanged:: 3.1 + + Added *allowed_exceptions* to specify path-through exceptions + """ + ... + + def emit_firstresult(self, event: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ...) -> Any: + """Emit *event* and pass *arguments* to the callback functions. + + Return the result of the first callback that doesn't return ``None``. + + :param event: The name of event that will be emitted + :param args: The arguments for the event + :param allowed_exceptions: The list of exceptions that are allowed in the callbacks + + .. versionadded:: 0.5 + .. versionchanged:: 3.1 + + Added *allowed_exceptions* to specify path-through exceptions + """ + ... + + def add_builder(self, builder: type[Builder], override: bool = ...) -> None: + """Register a new builder. + + :param builder: A builder class + :param override: If true, install the builder forcedly even if another builder + is already installed as the same name + + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_config_value(self, name: str, default: Any, rebuild: bool | str, types: Any = ...) -> None: + """Register a configuration value. + + This is necessary for Sphinx to recognize new values and set default + values accordingly. + + + :param name: The name of the configuration value. It is recommended to be prefixed + with the extension name (ex. ``html_logo``, ``epub_title``) + :param default: The default value of the configuration. + :param rebuild: The condition of rebuild. It must be one of those values: + + * ``'env'`` if a change in the setting only takes effect when a + document is parsed -- this means that the whole environment must be + rebuilt. + * ``'html'`` if a change in the setting needs a full rebuild of HTML + documents. + * ``''`` if a change in the setting will not need any special rebuild. + :param types: The type of configuration value. A list of types can be specified. For + example, ``[str]`` is used to describe a configuration that takes string + value. + + .. versionchanged:: 0.4 + If the *default* value is a callable, it will be called with the + config object as its argument in order to get the default value. + This can be used to implement config values whose default depends on + other values. + + .. versionchanged:: 0.6 + Changed *rebuild* from a simple boolean (equivalent to ``''`` or + ``'env'``) to a string. However, booleans are still accepted and + converted internally. + """ + ... + + def add_event(self, name: str) -> None: + """Register an event called *name*. + + This is needed to be able to emit it. + + :param name: The name of the event + """ + ... + + def set_translator(self, name: str, translator_class: type[nodes.NodeVisitor], override: bool = ...) -> None: + """Register or override a Docutils translator class. + + This is used to register a custom output translator or to replace a + builtin translator. This allows extensions to use a custom translator + and define custom nodes for the translator (see :meth:`add_node`). + + :param name: The name of the builder for the translator + :param translator_class: A translator class + :param override: If true, install the translator forcedly even if another translator + is already installed as the same name + + .. versionadded:: 1.3 + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_node(self, node: type[Element], override: bool = ..., **kwargs: tuple[Callable, Callable | None]) -> None: + """Register a Docutils node class. + + This is necessary for Docutils internals. It may also be used in the + future to validate nodes in the parsed documents. + + :param node: A node class + :param kwargs: Visitor functions for each builder (see below) + :param override: If true, install the node forcedly even if another node is already + installed as the same name + + Node visitor functions for the Sphinx HTML, LaTeX, text and manpage + writers can be given as keyword arguments: the keyword should be one or + more of ``'html'``, ``'latex'``, ``'text'``, ``'man'``, ``'texinfo'`` + or any other supported translators, the value a 2-tuple of ``(visit, + depart)`` methods. ``depart`` can be ``None`` if the ``visit`` + function raises :exc:`docutils.nodes.SkipNode`. Example: + + .. code-block:: python + + class math(docutils.nodes.Element): pass + + def visit_math_html(self, node): + self.body.append(self.starttag(node, 'math')) + def depart_math_html(self, node): + self.body.append('') + + app.add_node(math, html=(visit_math_html, depart_math_html)) + + Obviously, translators for which you don't specify visitor methods will + choke on the node when encountered in a document to translate. + + .. versionchanged:: 0.5 + Added the support for keyword arguments giving visit functions. + """ + ... + + def add_enumerable_node(self, node: type[Element], figtype: str, title_getter: TitleGetter | None = ..., override: bool = ..., **kwargs: tuple[Callable, Callable]) -> None: + """Register a Docutils node class as a numfig target. + + Sphinx numbers the node automatically. And then the users can refer it + using :rst:role:`numref`. + + :param node: A node class + :param figtype: The type of enumerable nodes. Each figtype has individual numbering + sequences. As system figtypes, ``figure``, ``table`` and + ``code-block`` are defined. It is possible to add custom nodes to + these default figtypes. It is also possible to define new custom + figtype if a new figtype is given. + :param title_getter: A getter function to obtain the title of node. It takes an + instance of the enumerable node, and it must return its title as + string. The title is used to the default title of references for + :rst:role:`ref`. By default, Sphinx searches + ``docutils.nodes.caption`` or ``docutils.nodes.title`` from the + node as a title. + :param kwargs: Visitor functions for each builder (same as :meth:`add_node`) + :param override: If true, install the node forcedly even if another node is already + installed as the same name + + .. versionadded:: 1.4 + """ + ... + + def add_directive(self, name: str, cls: type[Directive], override: bool = ...) -> None: + """Register a Docutils directive. + + :param name: The name of the directive + :param cls: A directive class + :param override: If false, do not install it if another directive + is already installed as the same name + If true, unconditionally install the directive. + + For example, a custom directive named ``my-directive`` would be added + like this: + + .. code-block:: python + + from docutils.parsers.rst import Directive, directives + + class MyDirective(Directive): + has_content = True + required_arguments = 1 + optional_arguments = 0 + final_argument_whitespace = True + option_spec = { + 'class': directives.class_option, + 'name': directives.unchanged, + } + + def run(self): + ... + + def setup(app): + app.add_directive('my-directive', MyDirective) + + For more details, see `the Docutils docs + `__ . + + .. versionchanged:: 0.6 + Docutils 0.5-style directive classes are now supported. + .. deprecated:: 1.8 + Docutils 0.4-style (function based) directives support is deprecated. + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_role(self, name: str, role: Any, override: bool = ...) -> None: + """Register a Docutils role. + + :param name: The name of role + :param role: A role function + :param override: If false, do not install it if another role + is already installed as the same name + If true, unconditionally install the role. + + For more details about role functions, see `the Docutils docs + `__ . + + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_generic_role(self, name: str, nodeclass: Any, override: bool = ...) -> None: + """Register a generic Docutils role. + + Register a Docutils role that does nothing but wrap its contents in the + node given by *nodeclass*. + + :param override: If false, do not install it if another role + is already installed as the same name + If true, unconditionally install the role. + + .. versionadded:: 0.6 + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_domain(self, domain: type[Domain], override: bool = ...) -> None: + """Register a domain. + + :param domain: A domain class + :param override: If false, do not install it if another domain + is already installed as the same name + If true, unconditionally install the domain. + + .. versionadded:: 1.0 + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_directive_to_domain(self, domain: str, name: str, cls: type[Directive], override: bool = ...) -> None: + """Register a Docutils directive in a domain. + + Like :meth:`add_directive`, but the directive is added to the domain + named *domain*. + + :param domain: The name of target domain + :param name: A name of directive + :param cls: A directive class + :param override: If false, do not install it if another directive + is already installed as the same name + If true, unconditionally install the directive. + + .. versionadded:: 1.0 + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_role_to_domain(self, domain: str, name: str, role: RoleFunction | XRefRole, override: bool = ...) -> None: + """Register a Docutils role in a domain. + + Like :meth:`add_role`, but the role is added to the domain named + *domain*. + + :param domain: The name of the target domain + :param name: The name of the role + :param role: The role function + :param override: If false, do not install it if another role + is already installed as the same name + If true, unconditionally install the role. + + .. versionadded:: 1.0 + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_index_to_domain(self, domain: str, index: type[Index], override: bool = ...) -> None: + """Register a custom index for a domain. + + Add a custom *index* class to the domain named *domain*. + + :param domain: The name of the target domain + :param index: The index class + :param override: If false, do not install it if another index + is already installed as the same name + If true, unconditionally install the index. + + .. versionadded:: 1.0 + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_object_type(self, directivename: str, rolename: str, indextemplate: str = ..., parse_node: Callable | None = ..., ref_nodeclass: type[TextElement] | None = ..., objname: str = ..., doc_field_types: Sequence = ..., override: bool = ...) -> None: + """Register a new object type. + + This method is a very convenient way to add a new :term:`object` type + that can be cross-referenced. It will do this: + + - Create a new directive (called *directivename*) for documenting an + object. It will automatically add index entries if *indextemplate* + is nonempty; if given, it must contain exactly one instance of + ``%s``. See the example below for how the template will be + interpreted. + - Create a new role (called *rolename*) to cross-reference to these + object descriptions. + - If you provide *parse_node*, it must be a function that takes a + string and a docutils node, and it must populate the node with + children parsed from the string. It must then return the name of the + item to be used in cross-referencing and index entries. See the + :file:`conf.py` file in the source for this documentation for an + example. + - The *objname* (if not given, will default to *directivename*) names + the type of object. It is used when listing objects, e.g. in search + results. + + For example, if you have this call in a custom Sphinx extension:: + + app.add_object_type('directive', 'dir', 'pair: %s; directive') + + you can use this markup in your documents:: + + .. rst:directive:: function + + Document a function. + + <...> + + See also the :rst:dir:`function` directive. + + For the directive, an index entry will be generated as if you had prepended :: + + .. index:: pair: function; directive + + The reference node will be of class ``literal`` (so it will be rendered + in a proportional font, as appropriate for code) unless you give the + *ref_nodeclass* argument, which must be a docutils node class. Most + useful are ``docutils.nodes.emphasis`` or ``docutils.nodes.strong`` -- + you can also use ``docutils.nodes.generated`` if you want no further + text decoration. If the text should be treated as literal (e.g. no + smart quote replacement), but not have typewriter styling, use + ``sphinx.addnodes.literal_emphasis`` or + ``sphinx.addnodes.literal_strong``. + + For the role content, you have the same syntactical possibilities as + for standard Sphinx roles (see :ref:`xref-syntax`). + + If *override* is True, the given object_type is forcedly installed even if + an object_type having the same name is already installed. + + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_crossref_type(self, directivename: str, rolename: str, indextemplate: str = ..., ref_nodeclass: type[TextElement] | None = ..., objname: str = ..., override: bool = ...) -> None: + """Register a new crossref object type. + + This method is very similar to :meth:`~Sphinx.add_object_type` except that the + directive it generates must be empty, and will produce no output. + + That means that you can add semantic targets to your sources, and refer + to them using custom roles instead of generic ones (like + :rst:role:`ref`). Example call:: + + app.add_crossref_type('topic', 'topic', 'single: %s', + docutils.nodes.emphasis) + + Example usage:: + + .. topic:: application API + + The application API + ------------------- + + Some random text here. + + See also :topic:`this section `. + + (Of course, the element following the ``topic`` directive needn't be a + section.) + + + :param override: If false, do not install it if another cross-reference type + is already installed as the same name + If true, unconditionally install the cross-reference type. + + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_transform(self, transform: type[Transform]) -> None: + """Register a Docutils transform to be applied after parsing. + + Add the standard docutils :class:`~docutils.transforms.Transform` + subclass *transform* to the list of transforms that are applied after + Sphinx parses a reST document. + + :param transform: A transform class + + .. list-table:: priority range categories for Sphinx transforms + :widths: 20,80 + + * - Priority + - Main purpose in Sphinx + * - 0-99 + - Fix invalid nodes by docutils. Translate a doctree. + * - 100-299 + - Preparation + * - 300-399 + - early + * - 400-699 + - main + * - 700-799 + - Post processing. Deadline to modify text and referencing. + * - 800-899 + - Collect referencing and referenced nodes. Domain processing. + * - 900-999 + - Finalize and clean up. + + refs: `Transform Priority Range Categories`__ + + __ https://docutils.sourceforge.io/docs/ref/transforms.html#transform-priority-range-categories + """ + ... + + def add_post_transform(self, transform: type[Transform]) -> None: + """Register a Docutils transform to be applied before writing. + + Add the standard docutils :class:`~docutils.transforms.Transform` + subclass *transform* to the list of transforms that are applied before + Sphinx writes a document. + + :param transform: A transform class + """ + ... + + def add_js_file(self, filename: str | None, priority: int = ..., loading_method: str | None = ..., **kwargs: Any) -> None: + """Register a JavaScript file to include in the HTML output. + + :param filename: The name of a JavaScript file that the default HTML + template will include. It must be relative to the HTML + static path, or a full URI with scheme, or ``None`` . + The ``None`` value is used to create an inline + `` + + app.add_js_file('example.js', loading_method="async") + # => + + app.add_js_file(None, body="var myVariable = 'foo';") + # => + + .. list-table:: priority range for JavaScript files + :widths: 20,80 + + * - Priority + - Main purpose in Sphinx + * - 200 + - default priority for built-in JavaScript files + * - 500 + - default priority for extensions + * - 800 + - default priority for :confval:`html_js_files` + + A JavaScript file can be added to the specific HTML page when an extension + calls this method on :event:`html-page-context` event. + + .. versionadded:: 0.5 + + .. versionchanged:: 1.8 + Renamed from ``app.add_javascript()``. + And it allows keyword arguments as attributes of script tag. + + .. versionchanged:: 3.5 + Take priority argument. Allow to add a JavaScript file to the specific page. + .. versionchanged:: 4.4 + Take loading_method argument. Allow to change the loading method of the + JavaScript file. + """ + ... + + def add_css_file(self, filename: str, priority: int = ..., **kwargs: Any) -> None: + """Register a stylesheet to include in the HTML output. + + :param filename: The name of a CSS file that the default HTML + template will include. It must be relative to the HTML + static path, or a full URI with scheme. + :param priority: Files are included in ascending order of priority. If + multiple CSS files have the same priority, + those files will be included in order of registration. + See list of "priority range for CSS files" below. + :param kwargs: Extra keyword arguments are included as attributes of the + ```` tag. + + Example:: + + app.add_css_file('custom.css') + # => + + app.add_css_file('print.css', media='print') + # => + + app.add_css_file('fancy.css', rel='alternate stylesheet', title='fancy') + # => + + .. list-table:: priority range for CSS files + :widths: 20,80 + + * - Priority + - Main purpose in Sphinx + * - 200 + - default priority for built-in CSS files + * - 500 + - default priority for extensions + * - 800 + - default priority for :confval:`html_css_files` + + A CSS file can be added to the specific HTML page when an extension calls + this method on :event:`html-page-context` event. + + .. versionadded:: 1.0 + + .. versionchanged:: 1.6 + Optional ``alternate`` and/or ``title`` attributes can be supplied + with the arguments *alternate* (a Boolean) and *title* (a string). + The default is no title and *alternate* = ``False``. For + more information, refer to the `documentation + `__. + + .. versionchanged:: 1.8 + Renamed from ``app.add_stylesheet()``. + And it allows keyword arguments as attributes of link tag. + + .. versionchanged:: 3.5 + Take priority argument. Allow to add a CSS file to the specific page. + """ + ... + + def add_latex_package(self, packagename: str, options: str | None = ..., after_hyperref: bool = ...) -> None: + r"""Register a package to include in the LaTeX source code. + + Add *packagename* to the list of packages that LaTeX source code will + include. If you provide *options*, it will be taken to the `\usepackage` + declaration. If you set *after_hyperref* truthy, the package will be + loaded after ``hyperref`` package. + + .. code-block:: python + + app.add_latex_package('mypackage') + # => \usepackage{mypackage} + app.add_latex_package('mypackage', 'foo,bar') + # => \usepackage[foo,bar]{mypackage} + + .. versionadded:: 1.3 + .. versionadded:: 3.1 + + *after_hyperref* option. + """ + ... + + def add_lexer(self, alias: str, lexer: type[Lexer]) -> None: + """Register a new lexer for source code. + + Use *lexer* to highlight code blocks with the given language *alias*. + + .. versionadded:: 0.6 + .. versionchanged:: 2.1 + Take a lexer class as an argument. + .. versionchanged:: 4.0 + Removed support for lexer instances as an argument. + """ + ... + + def add_autodocumenter(self, cls: Any, override: bool = ...) -> None: + """Register a new documenter class for the autodoc extension. + + Add *cls* as a new documenter class for the :mod:`sphinx.ext.autodoc` + extension. It must be a subclass of + :class:`sphinx.ext.autodoc.Documenter`. This allows auto-documenting + new types of objects. See the source of the autodoc module for + examples on how to subclass :class:`~sphinx.ext.autodoc.Documenter`. + + If *override* is True, the given *cls* is forcedly installed even if + a documenter having the same name is already installed. + + See :ref:`autodoc_ext_tutorial`. + + .. versionadded:: 0.6 + .. versionchanged:: 2.2 + Add *override* keyword. + """ + ... + + def add_autodoc_attrgetter(self, typ: type, getter: Callable[[Any, str, Any], Any]) -> None: + """Register a new ``getattr``-like function for the autodoc extension. + + Add *getter*, which must be a function with an interface compatible to + the :func:`getattr` builtin, as the autodoc attribute getter for + objects that are instances of *typ*. All cases where autodoc needs to + get an attribute of a type are then handled by this function instead of + :func:`getattr`. + + .. versionadded:: 0.6 + """ + ... + + def add_search_language(self, cls: Any) -> None: + """Register a new language for the HTML search index. + + Add *cls*, which must be a subclass of + :class:`sphinx.search.SearchLanguage`, as a support language for + building the HTML full-text search index. The class must have a *lang* + attribute that indicates the language it should be used for. See + :confval:`html_search_language`. + + .. versionadded:: 1.1 + """ + ... + + def add_source_suffix(self, suffix: str, filetype: str, override: bool = ...) -> None: + """Register a suffix of source files. + + Same as :confval:`source_suffix`. The users can override this + using the config setting. + + :param override: If false, do not install it the same suffix + is already installed. + If true, unconditionally install the suffix. + + .. versionadded:: 1.8 + """ + ... + + def add_source_parser(self, parser: type[Parser], override: bool = ...) -> None: + """Register a parser class. + + :param override: If false, do not install it if another parser + is already installed for the same suffix. + If true, unconditionally install the parser. + + .. versionadded:: 1.4 + .. versionchanged:: 1.8 + *suffix* argument is deprecated. It only accepts *parser* argument. + Use :meth:`add_source_suffix` API to register suffix instead. + .. versionchanged:: 1.8 + Add *override* keyword. + """ + ... + + def add_env_collector(self, collector: type[EnvironmentCollector]) -> None: + """Register an environment collector class. + + Refer to :ref:`collector-api`. + + .. versionadded:: 1.6 + """ + ... + + def add_html_theme(self, name: str, theme_path: str) -> None: + """Register a HTML Theme. + + The *name* is a name of theme, and *theme_path* is a full path to the + theme (refs: :ref:`distribute-your-theme`). + + .. versionadded:: 1.6 + """ + ... + + def add_html_math_renderer(self, name: str, inline_renderers: tuple[Callable, Callable | None] | None = ..., block_renderers: tuple[Callable, Callable | None] | None = ...) -> None: + """Register a math renderer for HTML. + + The *name* is a name of math renderer. Both *inline_renderers* and + *block_renderers* are used as visitor functions for the HTML writer: + the former for inline math node (``nodes.math``), the latter for + block math node (``nodes.math_block``). Regarding visitor functions, + see :meth:`add_node` for details. + + .. versionadded:: 1.8 + + """ + ... + + def add_message_catalog(self, catalog: str, locale_dir: str) -> None: + """Register a message catalog. + + :param catalog: The name of the catalog + :param locale_dir: The base path of the message catalog + + For more details, see :func:`sphinx.locale.get_translation()`. + + .. versionadded:: 1.8 + """ + ... + + def is_parallel_allowed(self, typ: str) -> bool: + """Check whether parallel processing is allowed or not. + + :param typ: A type of processing; ``'read'`` or ``'write'``. + """ + ... + + def set_html_assets_policy(self, policy: str) -> None: + """Set the policy to include assets in HTML pages. + + - always: include the assets in all the pages + - per_page: include the assets only in pages where they are used + + .. versionadded: 4.1 + """ + ... + + + +class TemplateBridge: + """ + This class defines the interface for a "template bridge", that is, a class + that renders templates given a template name and a context. + """ + def init(self, builder: Builder, theme: Theme | None = ..., dirs: list[str] | None = ...) -> None: + """Called by the builder to initialize the template system. + + *builder* is the builder object; you'll probably want to look at the + value of ``builder.config.templates_path``. + + *theme* is a :class:`sphinx.theming.Theme` object or None; in the latter + case, *dirs* can be list of fixed directories to look for templates. + """ + ... + + def newest_template_mtime(self) -> float: + """Called by the builder to determine if output files are outdated + because of template changes. Return the mtime of the newest template + file that was changed. The default implementation returns ``0``. + """ + ... + + def render(self, template: str, context: dict) -> None: + """Called by the builder to render a template given as a filename with + a specified context (a Python dictionary). + """ + ... + + def render_string(self, template: str, context: dict) -> str: + """Called by the builder to render a template given as a string with a + specified context (a Python dictionary). + """ + ... + + + diff --git a/typings/sphinx/builders/__init__.pyi b/typings/sphinx/builders/__init__.pyi new file mode 100644 index 0000000..abc9eab --- /dev/null +++ b/typings/sphinx/builders/__init__.pyi @@ -0,0 +1,204 @@ +""" +This type stub file was generated by pyright. +""" + +import codecs +import pickle +import time +from __future__ import annotations +from os import path +from typing import Any, TYPE_CHECKING +from docutils import nodes +from docutils.utils import DependencyList +from sphinx.environment import BuildEnvironment, CONFIG_CHANGED_REASON, CONFIG_OK +from sphinx.environment.adapters.asset import ImageAdapter +from sphinx.errors import SphinxError +from sphinx.locale import __ +from sphinx.util import UnicodeDecodeErrorHandler, get_filetype, import_object, logging, rst +from sphinx.util.build_phase import BuildPhase +from sphinx.util.console import bold +from sphinx.util.display import progress_message, status_iterator +from sphinx.util.docutils import sphinx_domains +from sphinx.util.i18n import CatalogInfo, CatalogRepository, docname_to_domain +from sphinx.util.osutil import SEP, ensuredir, relative_uri, relpath +from sphinx.util.parallel import ParallelTasks, SerialTasks, make_chunks, parallel_available +from sphinx import directives, roles +from collections.abc import Iterable, Sequence +from docutils.nodes import Node +from sphinx.application import Sphinx +from sphinx.config import Config +from sphinx.events import EventManager +from sphinx.util.tags import Tags +from sphinx.util.typing import NoneType + +"""Builder superclass for all builders.""" +if TYPE_CHECKING: + ... +logger = ... +class Builder: + """ + Builds target formats from the reST sources. + """ + name = ... + format = ... + epilog = ... + default_translator_class: type[nodes.NodeVisitor] + versioning_method = ... + versioning_compare = ... + allow_parallel = ... + use_message_catalog = ... + supported_image_types: list[str] = ... + supported_remote_images = ... + supported_data_uri_images = ... + def __init__(self, app: Sphinx, env: BuildEnvironment) -> None: + ... + + def get_translator_class(self, *args: Any) -> type[nodes.NodeVisitor]: + """Return a class of translator.""" + ... + + def create_translator(self, *args: Any) -> nodes.NodeVisitor: + """Return an instance of translator. + + This method returns an instance of ``default_translator_class`` by default. + Users can replace the translator class with ``app.set_translator()`` API. + """ + ... + + def init(self) -> None: + """Load necessary templates and perform initialization. The default + implementation does nothing. + """ + ... + + def create_template_bridge(self) -> None: + """Return the template bridge configured.""" + ... + + def get_target_uri(self, docname: str, typ: str | None = ...) -> str: + """Return the target URI for a document name. + + *typ* can be used to qualify the link characteristic for individual + builders. + """ + ... + + def get_relative_uri(self, from_: str, to: str, typ: str | None = ...) -> str: + """Return a relative URI between two source filenames. + + May raise environment.NoUri if there's no way to return a sensible URI. + """ + ... + + def get_outdated_docs(self) -> str | Iterable[str]: + """Return an iterable of output files that are outdated, or a string + describing what an update build will build. + + If the builder does not output individual files corresponding to + source files, return a string here. If it does, return an iterable + of those files that need to be written. + """ + ... + + def get_asset_paths(self) -> list[str]: + """Return list of paths for assets (ex. templates, CSS, etc.).""" + ... + + def post_process_images(self, doctree: Node) -> None: + """Pick the best candidate for all image URIs.""" + ... + + def compile_catalogs(self, catalogs: set[CatalogInfo], message: str) -> None: + ... + + def compile_all_catalogs(self) -> None: + ... + + def compile_specific_catalogs(self, specified_files: list[str]) -> None: + ... + + def compile_update_catalogs(self) -> None: + ... + + def build_all(self) -> None: + """Build all source files.""" + ... + + def build_specific(self, filenames: list[str]) -> None: + """Only rebuild as much as needed for changes in the *filenames*.""" + ... + + def build_update(self) -> None: + """Only rebuild what was changed or added since last build.""" + ... + + def build(self, docnames: Iterable[str] | None, summary: str | None = ..., method: str = ...) -> None: + """Main build method. + + First updates the environment, and then calls + :meth:`!write`. + """ + ... + + def read(self) -> list[str]: + """(Re-)read all files new or changed since last update. + + Store all environment docnames in the canonical format (ie using SEP as + a separator in place of os.path.sep). + """ + ... + + def read_doc(self, docname: str, *, _cache: bool = ...) -> None: + """Parse a file and add/update inventory entries for the doctree.""" + ... + + def write_doctree(self, docname: str, doctree: nodes.document, *, _cache: bool = ...) -> None: + """Write the doctree to a file.""" + ... + + def write(self, build_docnames: Iterable[str] | None, updated_docnames: Sequence[str], method: str = ...) -> None: + ... + + def prepare_writing(self, docnames: set[str]) -> None: + """A place where you can add logic before :meth:`write_doc` is run""" + ... + + def copy_assets(self) -> None: + """Where assets (images, static files, etc) are copied before writing""" + ... + + def write_doc(self, docname: str, doctree: nodes.document) -> None: + """Where you actually write something to the filesystem.""" + ... + + def write_doc_serialized(self, docname: str, doctree: nodes.document) -> None: + """Handle parts of write_doc that must be called in the main process + if parallel build is active. + """ + ... + + def finish(self) -> None: + """Finish the building process. + + The default implementation does nothing. + """ + ... + + def cleanup(self) -> None: + """Cleanup any resources. + + The default implementation does nothing. + """ + ... + + def get_builder_config(self, option: str, default: str) -> Any: + """Return a builder specific option. + + This method allows customization of common builder settings by + inserting the name of the current builder in the option key. + If the key does not exist, use default as builder name. + """ + ... + + + diff --git a/typings/sphinx/builders/_epub_base.pyi b/typings/sphinx/builders/_epub_base.pyi new file mode 100644 index 0000000..9783aaa --- /dev/null +++ b/typings/sphinx/builders/_epub_base.pyi @@ -0,0 +1,221 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, NamedTuple, TYPE_CHECKING +from docutils import nodes +from sphinx.builders.html import BuildInfo, StandaloneHTMLBuilder +from docutils.nodes import Node + +"""Base class of epub2/epub3 builders.""" +if TYPE_CHECKING: + ... +logger = ... +COVERPAGE_NAME = ... +TOCTREE_TEMPLATE = ... +LINK_TARGET_TEMPLATE = ... +FOOTNOTE_LABEL_TEMPLATE = ... +FOOTNOTES_RUBRIC_NAME = ... +CSS_LINK_TARGET_CLASS = ... +GUIDE_TITLES = ... +MEDIA_TYPES = ... +VECTOR_GRAPHICS_EXTENSIONS = ... +REFURI_RE = ... +class ManifestItem(NamedTuple): + href: str + id: str + media_type: str + ... + + +class Spine(NamedTuple): + idref: str + linear: bool + ... + + +class Guide(NamedTuple): + type: str + title: str + uri: str + ... + + +class NavPoint(NamedTuple): + navpoint: str + playorder: int + text: str + refuri: str + children: list[NavPoint] + ... + + +def sphinx_smarty_pants(t: str, language: str = ...) -> str: + ... + +ssp = ... +class EpubBuilder(StandaloneHTMLBuilder): + """ + Builder that outputs epub files. + + It creates the metainfo files container.opf, toc.ncx, mimetype, and + META-INF/container.xml. Afterwards, all necessary files are zipped to an + epub file. + """ + copysource = ... + supported_image_types = ... + supported_remote_images = ... + add_permalinks = ... + allow_sharp_as_current_path = ... + embedded = ... + download_support = ... + html_scaled_image_link = ... + search = ... + coverpage_name = ... + toctree_template = ... + link_target_template = ... + css_link_target_class = ... + guide_titles = ... + media_types = ... + refuri_re = ... + template_dir = ... + doctype = ... + def init(self) -> None: + ... + + def create_build_info(self) -> BuildInfo: + ... + + def get_theme_config(self) -> tuple[str, dict]: + ... + + def make_id(self, name: str) -> str: + """Return a unique id for name.""" + ... + + def get_refnodes(self, doctree: Node, result: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Collect section titles, their depth in the toc and the refuri.""" + ... + + def check_refnodes(self, nodes: list[dict[str, Any]]) -> None: + ... + + def get_toc(self) -> None: + """Get the total table of contents, containing the root_doc + and pre and post files not managed by sphinx. + """ + ... + + def toc_add_files(self, refnodes: list[dict[str, Any]]) -> None: + """Add the root_doc, pre and post files to a list of refnodes. + """ + ... + + def fix_fragment(self, prefix: str, fragment: str) -> str: + """Return a href/id attribute with colons replaced by hyphens.""" + ... + + def fix_ids(self, tree: nodes.document) -> None: + """Replace colons with hyphens in href and id attributes. + + Some readers crash because they interpret the part as a + transport protocol specification. + """ + ... + + def add_visible_links(self, tree: nodes.document, show_urls: str = ...) -> None: + """Add visible link targets for external links""" + ... + + def write_doc(self, docname: str, doctree: nodes.document) -> None: + """Write one document file. + + This method is overwritten in order to fix fragment identifiers + and to add visible external links. + """ + ... + + def fix_genindex(self, tree: list[tuple[str, list[tuple[str, Any]]]]) -> None: + """Fix href attributes for genindex pages.""" + ... + + def is_vector_graphics(self, filename: str) -> bool: + """Does the filename extension indicate a vector graphic format?""" + ... + + def copy_image_files_pil(self) -> None: + """Copy images using Pillow, the Python Imaging Library. + The method tries to read and write the files with Pillow, converting + the format and resizing the image if necessary/possible. + """ + ... + + def copy_image_files(self) -> None: + """Copy image files to destination directory. + This overwritten method can use Pillow to convert image files. + """ + ... + + def copy_download_files(self) -> None: + ... + + def handle_page(self, pagename: str, addctx: dict, templatename: str = ..., outfilename: str | None = ..., event_arg: Any = ...) -> None: + """Create a rendered page. + + This method is overwritten for genindex pages in order to fix href link + attributes. + """ + ... + + def build_mimetype(self) -> None: + """Write the metainfo file mimetype.""" + ... + + def build_container(self, outname: str = ...) -> None: + """Write the metainfo file META-INF/container.xml.""" + ... + + def content_metadata(self) -> dict[str, Any]: + """Create a dictionary with all metadata for the content.opf + file properly escaped. + """ + ... + + def build_content(self) -> None: + """Write the metainfo file content.opf It contains bibliographic data, + a file list and the spine (the reading order). + """ + ... + + def new_navpoint(self, node: dict[str, Any], level: int, incr: bool = ...) -> NavPoint: + """Create a new entry in the toc from the node at given level.""" + ... + + def build_navpoints(self, nodes: list[dict[str, Any]]) -> list[NavPoint]: + """Create the toc navigation structure. + + Subelements of a node are nested inside the navpoint. For nested nodes + the parent node is reinserted in the subnav. + """ + ... + + def toc_metadata(self, level: int, navpoints: list[NavPoint]) -> dict[str, Any]: + """Create a dictionary with all metadata for the toc.ncx file + properly escaped. + """ + ... + + def build_toc(self) -> None: + """Write the metainfo file toc.ncx.""" + ... + + def build_epub(self) -> None: + """Write the epub file. + + It is a zip file with the mimetype file stored uncompressed as the first + entry. + """ + ... + + + diff --git a/typings/sphinx/builders/epub3.pyi b/typings/sphinx/builders/epub3.pyi new file mode 100644 index 0000000..47b1235 --- /dev/null +++ b/typings/sphinx/builders/epub3.pyi @@ -0,0 +1,93 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, NamedTuple, TYPE_CHECKING +from sphinx.builders import _epub_base +from sphinx.config import Config +from sphinx.application import Sphinx + +"""Build epub3 files. + +Originally derived from epub.py. +""" +if TYPE_CHECKING: + ... +logger = ... +class NavPoint(NamedTuple): + text: str + refuri: str + children: list[NavPoint] + ... + + +PAGE_PROGRESSION_DIRECTIONS = ... +IBOOK_SCROLL_AXIS = ... +THEME_WRITING_MODES = ... +DOCTYPE = ... +HTML_TAG = ... +_xml_name_start_char = ... +_xml_name_char = ... +_XML_NAME_PATTERN = ... +class Epub3Builder(_epub_base.EpubBuilder): + """ + Builder that outputs epub3 files. + + It creates the metainfo files content.opf, nav.xhtml, toc.ncx, mimetype, + and META-INF/container.xml. Afterwards, all necessary files are zipped to + an epub file. + """ + name = ... + epilog = ... + supported_remote_images = ... + template_dir = ... + doctype = ... + html_tag = ... + use_meta_charset = ... + def handle_finish(self) -> None: + """Create the metainfo files and finally the epub.""" + ... + + def content_metadata(self) -> dict[str, Any]: + """Create a dictionary with all metadata for the content.opf + file properly escaped. + """ + ... + + def prepare_writing(self, docnames: set[str]) -> None: + ... + + def build_navlist(self, navnodes: list[dict[str, Any]]) -> list[NavPoint]: + """Create the toc navigation structure. + + This method is almost same as build_navpoints method in epub.py. + This is because the logical navigation structure of epub3 is not + different from one of epub2. + + The difference from build_navpoints method is templates which are used + when generating navigation documents. + """ + ... + + def navigation_doc_metadata(self, navlist: list[NavPoint]) -> dict[str, Any]: + """Create a dictionary with all metadata for the nav.xhtml file + properly escaped. + """ + ... + + def build_navigation_doc(self) -> None: + """Write the metainfo file nav.xhtml.""" + ... + + + +def validate_config_values(app: Sphinx) -> None: + ... + +def convert_epub_css_files(app: Sphinx, config: Config) -> None: + """This converts string styled epub_css_files to tuple styled one.""" + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/builders/gettext.pyi b/typings/sphinx/builders/gettext.pyi new file mode 100644 index 0000000..12220ab --- /dev/null +++ b/typings/sphinx/builders/gettext.pyi @@ -0,0 +1,124 @@ +""" +This type stub file was generated by pyright. +""" + +import os +from os import getenv +from typing import Any, TYPE_CHECKING +from docutils import nodes +from sphinx.builders import Builder +from sphinx.util.i18n import CatalogInfo +from sphinx.util.tags import Tags +from sphinx.util.template import SphinxRenderer +from collections.abc import Generator, Iterable +from docutils.nodes import Element +from sphinx.application import Sphinx + +"""The MessageCatalogBuilder class.""" +if TYPE_CHECKING: + ... +logger = ... +class Message: + """An entry of translatable message.""" + def __init__(self, text: str, locations: list[tuple[str, int]], uuids: list[str]) -> None: + ... + + + +class Catalog: + """Catalog of translatable messages.""" + def __init__(self) -> None: + ... + + def add(self, msg: str, origin: Element | MsgOrigin) -> None: + ... + + def __iter__(self) -> Generator[Message, None, None]: + ... + + + +class MsgOrigin: + """ + Origin holder for Catalog message origin. + """ + def __init__(self, source: str, line: int) -> None: + ... + + + +class GettextRenderer(SphinxRenderer): + def __init__(self, template_path: list[str | os.PathLike[str]] | None = ..., outdir: str | os.PathLike[str] | None = ...) -> None: + ... + + def render(self, filename: str, context: dict[str, Any]) -> str: + ... + + + +class I18nTags(Tags): + """Dummy tags module for I18nBuilder. + + To translate all text inside of only nodes, this class + always returns True value even if no tags are defined. + """ + def eval_condition(self, condition: Any) -> bool: + ... + + + +class I18nBuilder(Builder): + """ + General i18n builder. + """ + name = ... + versioning_method = ... + use_message_catalog = ... + def init(self) -> None: + ... + + def get_target_uri(self, docname: str, typ: str | None = ...) -> str: + ... + + def get_outdated_docs(self) -> set[str]: + ... + + def prepare_writing(self, docnames: set[str]) -> None: + ... + + def compile_catalogs(self, catalogs: set[CatalogInfo], message: str) -> None: + ... + + def write_doc(self, docname: str, doctree: nodes.document) -> None: + ... + + + +if source_date_epoch := getenv('SOURCE_DATE_EPOCH') is not None: + timestamp = ... +else: + timestamp = ... +ctime = ... +def should_write(filepath: str, new_content: str) -> bool: + ... + +class MessageCatalogBuilder(I18nBuilder): + """ + Builds gettext-style message catalogs (.pot files). + """ + name = ... + epilog = ... + def init(self) -> None: + ... + + def build(self, docnames: Iterable[str] | None, summary: str | None = ..., method: str = ...) -> None: + ... + + def finish(self) -> None: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/builders/html/__init__.pyi b/typings/sphinx/builders/html/__init__.pyi new file mode 100644 index 0000000..e7d290d --- /dev/null +++ b/typings/sphinx/builders/html/__init__.pyi @@ -0,0 +1,335 @@ +""" +This type stub file was generated by pyright. +""" + +import contextlib +import hashlib +import html +import os +import posixpath +import re +import sys +import time +import warnings +import docutils.readers.doctree +from __future__ import annotations +from os import path +from typing import Any, IO, TYPE_CHECKING +from urllib.parse import quote +from docutils import nodes +from docutils.core import Publisher +from docutils.frontend import OptionParser +from docutils.io import DocTreeInput, StringOutput +from docutils.utils import relative_path +from sphinx import __display_version__, package_dir, version_info as sphinx_version +from sphinx.builders import Builder +from sphinx.builders.html._assets import _CascadingStyleSheet, _JavaScript, _file_checksum +from sphinx.config import Config, ENUM +from sphinx.deprecation import _deprecation_warning +from sphinx.domains import Domain, Index, IndexEntry +from sphinx.environment.adapters.asset import ImageAdapter +from sphinx.environment.adapters.indexentries import IndexEntries +from sphinx.environment.adapters.toctree import document_toc, global_toctree_for_doc +from sphinx.errors import ConfigError, ThemeError +from sphinx.highlighting import PygmentsBridge +from sphinx.locale import _, __ +from sphinx.search import js_index +from sphinx.theming import HTMLThemeFactory +from sphinx.util import isurl, logging +from sphinx.util.display import progress_message, status_iterator +from sphinx.util.docutils import new_document +from sphinx.util.fileutil import copy_asset +from sphinx.util.i18n import format_date +from sphinx.util.inventory import InventoryFile +from sphinx.util.matching import DOTFILES, Matcher, patmatch +from sphinx.util.osutil import SEP, copyfile, ensuredir, os_path, relative_uri +from sphinx.writers.html import HTMLWriter +from sphinx.writers.html5 import HTML5Translator +from collections.abc import Iterable, Iterator, Sequence +from docutils.nodes import Node +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.util.tags import Tags + +"""Several HTML builders.""" +if TYPE_CHECKING: + ... +INVENTORY_FILENAME = ... +logger = ... +return_codes_re = ... +DOMAIN_INDEX_TYPE = tuple[str, type[Index], list[tuple[str, list[IndexEntry]]], bool,] +def get_stable_hash(obj: Any) -> str: + """ + Return a stable hash for a Python data structure. We can't just use + the md5 of str(obj) since for example dictionary items are enumerated + in unpredictable order due to hash randomization in newer Pythons. + """ + ... + +def convert_locale_to_language_tag(locale: str | None) -> str | None: + """Convert a locale string to a language tag (ex. en_US -> en-US). + + refs: BCP 47 (:rfc:`5646`) + """ + ... + +class BuildInfo: + """buildinfo file manipulator. + + HTMLBuilder and its family are storing their own envdata to ``.buildinfo``. + This class is a manipulator for the file. + """ + @classmethod + def load(cls, f: IO) -> BuildInfo: + ... + + def __init__(self, config: Config | None = ..., tags: Tags | None = ..., config_categories: Sequence[str] = ...) -> None: + ... + + def __eq__(self, other: BuildInfo) -> bool: + ... + + def dump(self, f: IO) -> None: + ... + + + +class StandaloneHTMLBuilder(Builder): + """ + Builds standalone HTML docs. + """ + name = ... + format = ... + epilog = ... + default_translator_class = HTML5Translator + copysource = ... + allow_parallel = ... + out_suffix = ... + link_suffix = ... + indexer_format: Any = ... + indexer_dumps_unicode = ... + html_scaled_image_link = ... + supported_image_types = ... + supported_remote_images = ... + supported_data_uri_images = ... + searchindex_filename = ... + add_permalinks = ... + allow_sharp_as_current_path = ... + embedded = ... + search = ... + use_index = ... + download_support = ... + imgpath: str = ... + domain_indices: list[DOMAIN_INDEX_TYPE] = ... + def __init__(self, app: Sphinx, env: BuildEnvironment) -> None: + ... + + def init(self) -> None: + ... + + def create_build_info(self) -> BuildInfo: + ... + + def get_theme_config(self) -> tuple[str, dict]: + ... + + def init_templates(self) -> None: + ... + + def init_highlighter(self) -> None: + ... + + @property + def css_files(self) -> list[_CascadingStyleSheet]: + ... + + def init_css_files(self) -> None: + ... + + def add_css_file(self, filename: str, **kwargs: Any) -> None: + ... + + @property + def script_files(self) -> list[_JavaScript]: + ... + + def init_js_files(self) -> None: + ... + + def add_js_file(self, filename: str, **kwargs: Any) -> None: + ... + + @property + def math_renderer_name(self) -> str | None: + ... + + def get_outdated_docs(self) -> Iterator[str]: + ... + + def get_asset_paths(self) -> list[str]: + ... + + def render_partial(self, node: Node | None) -> dict[str, str]: + """Utility: Render a lone doctree node.""" + ... + + def prepare_writing(self, docnames: set[str]) -> None: + ... + + def get_doc_context(self, docname: str, body: str, metatags: str) -> dict[str, Any]: + """Collect items for the template context of a page.""" + ... + + def copy_assets(self) -> None: + ... + + def write_doc(self, docname: str, doctree: nodes.document) -> None: + ... + + def write_doc_serialized(self, docname: str, doctree: nodes.document) -> None: + ... + + def finish(self) -> None: + ... + + @progress_message(__('generating indices')) + def gen_indices(self) -> None: + ... + + def gen_pages_from_extensions(self) -> None: + ... + + @progress_message(__('writing additional pages')) + def gen_additional_pages(self) -> None: + ... + + def write_genindex(self) -> None: + ... + + def write_domain_indices(self) -> None: + ... + + def copy_image_files(self) -> None: + ... + + def copy_download_files(self) -> None: + ... + + def create_pygments_style_file(self) -> None: + """create a style file for pygments.""" + ... + + def copy_translation_js(self) -> None: + """Copy a JavaScript file for translations.""" + ... + + def copy_stemmer_js(self) -> None: + """Copy a JavaScript file for stemmer.""" + ... + + def copy_theme_static_files(self, context: dict[str, Any]) -> None: + ... + + def copy_html_static_files(self, context: dict) -> None: + ... + + def copy_html_logo(self) -> None: + ... + + def copy_html_favicon(self) -> None: + ... + + def copy_static_files(self) -> None: + ... + + def copy_extra_files(self) -> None: + """copy html_extra_path files.""" + ... + + def write_buildinfo(self) -> None: + ... + + def cleanup(self) -> None: + ... + + def post_process_images(self, doctree: Node) -> None: + """Pick the best candidate for an image and link down-scaled images to + their high res version. + """ + ... + + def load_indexer(self, docnames: Iterable[str]) -> None: + ... + + def index_page(self, pagename: str, doctree: nodes.document, title: str) -> None: + ... + + def get_outfilename(self, pagename: str) -> str: + ... + + def add_sidebars(self, pagename: str, ctx: dict) -> None: + ... + + def get_target_uri(self, docname: str, typ: str | None = ...) -> str: + ... + + def handle_page(self, pagename: str, addctx: dict, templatename: str = ..., outfilename: str | None = ..., event_arg: Any = ...) -> None: + ... + + def update_page_context(self, pagename: str, templatename: str, ctx: dict, event_arg: Any) -> None: + ... + + def handle_finish(self) -> None: + ... + + @progress_message(__('dumping object inventory')) + def dump_inventory(self) -> None: + ... + + def dump_search_index(self) -> None: + ... + + + +def convert_html_css_files(app: Sphinx, config: Config) -> None: + """This converts string styled html_css_files to tuple styled one.""" + ... + +def convert_html_js_files(app: Sphinx, config: Config) -> None: + """This converts string styled html_js_files to tuple styled one.""" + ... + +def setup_resource_paths(app: Sphinx, pagename: str, templatename: str, context: dict, doctree: Node) -> None: + """Set up relative resource paths.""" + ... + +def validate_math_renderer(app: Sphinx) -> None: + ... + +def validate_html_extra_path(app: Sphinx, config: Config) -> None: + """Check html_extra_paths setting.""" + ... + +def validate_html_static_path(app: Sphinx, config: Config) -> None: + """Check html_static_paths setting.""" + ... + +def validate_html_logo(app: Sphinx, config: Config) -> None: + """Check html_logo setting.""" + ... + +def validate_html_favicon(app: Sphinx, config: Config) -> None: + """Check html_favicon setting.""" + ... + +def error_on_html_4(_app: Sphinx, config: Config) -> None: + """Error on HTML 4.""" + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + +_DEPRECATED_OBJECTS = ... +def __getattr__(name): # -> type[_CascadingStyleSheet] | type[_JavaScript]: + ... + diff --git a/typings/sphinx/builders/html/_assets.pyi b/typings/sphinx/builders/html/_assets.pyi new file mode 100644 index 0000000..a9f8729 --- /dev/null +++ b/typings/sphinx/builders/html/_assets.pyi @@ -0,0 +1,69 @@ +""" +This type stub file was generated by pyright. +""" + +import os +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + ... +class _CascadingStyleSheet: + filename: str | os.PathLike[str] + priority: int + attributes: dict[str, str] + def __init__(self, filename: str | os.PathLike[str], /, *, priority: int = ..., rel: str = ..., type: str = ..., **attributes: str) -> None: + ... + + def __str__(self) -> str: + ... + + def __eq__(self, other) -> bool: + ... + + def __hash__(self) -> int: + ... + + def __setattr__(self, key, value): + ... + + def __delattr__(self, key): + ... + + def __getattr__(self, key): # -> Any: + ... + + def __getitem__(self, key): # -> str: + ... + + + +class _JavaScript: + filename: str | os.PathLike[str] + priority: int + attributes: dict[str, str] + def __init__(self, filename: str | os.PathLike[str], /, *, priority: int = ..., **attributes: str) -> None: + ... + + def __str__(self) -> str: + ... + + def __eq__(self, other) -> bool: + ... + + def __hash__(self) -> int: + ... + + def __setattr__(self, key, value): + ... + + def __delattr__(self, key): + ... + + def __getattr__(self, key): # -> Any: + ... + + def __getitem__(self, key): # -> str: + ... + + + diff --git a/typings/sphinx/builders/latex/__init__.pyi b/typings/sphinx/builders/latex/__init__.pyi new file mode 100644 index 0000000..0b93354 --- /dev/null +++ b/typings/sphinx/builders/latex/__init__.pyi @@ -0,0 +1,148 @@ +""" +This type stub file was generated by pyright. +""" + +import os +import warnings +import sphinx.builders.latex.nodes +from __future__ import annotations +from os import path +from typing import Any, TYPE_CHECKING +from docutils.frontend import OptionParser +from sphinx import addnodes, highlighting, package_dir +from sphinx.builders import Builder +from sphinx.builders.latex.constants import ADDITIONAL_SETTINGS, DEFAULT_SETTINGS, SHORTHANDOFF +from sphinx.builders.latex.theming import Theme, ThemeFactory +from sphinx.builders.latex.util import ExtBabel +from sphinx.config import Config, ENUM +from sphinx.environment.adapters.asset import ImageAdapter +from sphinx.errors import NoUri, SphinxError +from sphinx.locale import _, __ +from sphinx.util import logging, texescape +from sphinx.util.console import bold, darkgreen +from sphinx.util.display import progress_message, status_iterator +from sphinx.util.docutils import SphinxFileOutput, new_document +from sphinx.util.fileutil import copy_asset_file +from sphinx.util.i18n import format_date +from sphinx.util.nodes import inline_all_toctrees +from sphinx.util.osutil import SEP, make_filename_from_project +from sphinx.util.template import LaTeXRenderer +from sphinx.writers.latex import LaTeXTranslator, LaTeXWriter +from docutils import nodes +from collections.abc import Iterable +from docutils.nodes import Node +from sphinx.application import Sphinx + +"""LaTeX builder.""" +if TYPE_CHECKING: + ... +XINDY_LANG_OPTIONS = ... +XINDY_CYRILLIC_SCRIPTS = ... +logger = ... +class LaTeXBuilder(Builder): + """ + Builds LaTeX output to create PDF. + """ + name = ... + format = ... + epilog = ... + if os.name == 'posix': + ... + supported_image_types = ... + supported_remote_images = ... + default_translator_class = LaTeXTranslator + def init(self) -> None: + ... + + def get_outdated_docs(self) -> str | list[str]: + ... + + def get_target_uri(self, docname: str, typ: str | None = ...) -> str: + ... + + def get_relative_uri(self, from_: str, to: str, typ: str | None = ...) -> str: + ... + + def init_document_data(self) -> None: + ... + + def init_context(self) -> None: + ... + + def update_context(self) -> None: + """Update template variables for .tex file just before writing.""" + ... + + def init_babel(self) -> None: + ... + + def init_multilingual(self) -> None: + ... + + def write_stylesheet(self) -> None: + ... + + def copy_assets(self) -> None: + ... + + def write(self, *ignored: Any) -> None: + ... + + def get_contentsname(self, indexfile: str) -> str: + ... + + def update_doc_context(self, title: str, author: str, theme: Theme) -> None: + ... + + def assemble_doctree(self, indexfile: str, toctree_only: bool, appendices: list[str]) -> nodes.document: + ... + + def finish(self) -> None: + ... + + @progress_message(__('copying TeX support files')) + def copy_support_files(self) -> None: + """copy TeX support files from texinputs.""" + ... + + @progress_message(__('copying additional files')) + def copy_latex_additional_files(self) -> None: + ... + + def copy_image_files(self) -> None: + ... + + def write_message_catalog(self) -> None: + ... + + + +def validate_config_values(app: Sphinx, config: Config) -> None: + ... + +def validate_latex_theme_options(app: Sphinx, config: Config) -> None: + ... + +def install_packages_for_ja(app: Sphinx) -> None: + """Install packages for Japanese.""" + ... + +def default_latex_engine(config: Config) -> str: + """ Better default latex_engine settings for specific languages. """ + ... + +def default_latex_docclass(config: Config) -> dict[str, str]: + """ Better default latex_docclass settings for specific languages. """ + ... + +def default_latex_use_xindy(config: Config) -> bool: + """ Better default latex_use_xindy settings for specific engines. """ + ... + +def default_latex_documents(config: Config) -> list[tuple[str, str, str, str, str]]: + """ Better default latex_documents settings. """ + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/builders/latex/constants.pyi b/typings/sphinx/builders/latex/constants.pyi new file mode 100644 index 0000000..9a205b3 --- /dev/null +++ b/typings/sphinx/builders/latex/constants.pyi @@ -0,0 +1,15 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any + +"""constants for LaTeX builder.""" +PDFLATEX_DEFAULT_FONTPKG = ... +PDFLATEX_DEFAULT_FONTSUBSTITUTION = ... +XELATEX_DEFAULT_FONTPKG = ... +XELATEX_GREEK_DEFAULT_FONTPKG = ... +LUALATEX_DEFAULT_FONTPKG = ... +DEFAULT_SETTINGS: dict[str, Any] = ... +ADDITIONAL_SETTINGS: dict[Any, dict[str, Any]] = ... +SHORTHANDOFF = ... diff --git a/typings/sphinx/builders/latex/nodes.pyi b/typings/sphinx/builders/latex/nodes.pyi new file mode 100644 index 0000000..95d438f --- /dev/null +++ b/typings/sphinx/builders/latex/nodes.pyi @@ -0,0 +1,33 @@ +""" +This type stub file was generated by pyright. +""" + +from docutils import nodes + +"""Additional nodes for LaTeX writer.""" +class captioned_literal_block(nodes.container): + """A node for a container of literal_block having a caption.""" + ... + + +class footnotemark(nodes.Inline, nodes.Referential, nodes.TextElement): + """A node represents ``\footnotemark``.""" + ... + + +class footnotetext(nodes.General, nodes.BackLinkable, nodes.Element, nodes.Labeled, nodes.Targetable): + """A node represents ``\footnotetext``.""" + ... + + +class math_reference(nodes.Inline, nodes.Referential, nodes.TextElement): + """A node for a reference for equation.""" + ... + + +class thebibliography(nodes.container): + """A node for wrapping bibliographies.""" + ... + + +HYPERLINK_SUPPORT_NODES = ... diff --git a/typings/sphinx/builders/latex/theming.pyi b/typings/sphinx/builders/latex/theming.pyi new file mode 100644 index 0000000..0b03fac --- /dev/null +++ b/typings/sphinx/builders/latex/theming.pyi @@ -0,0 +1,60 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from sphinx.application import Sphinx +from sphinx.config import Config + +"""Theming support for LaTeX builder.""" +if TYPE_CHECKING: + ... +logger = ... +class Theme: + """A set of LaTeX configurations.""" + LATEX_ELEMENTS_KEYS = ... + UPDATABLE_KEYS = ... + def __init__(self, name: str) -> None: + ... + + def update(self, config: Config) -> None: + """Override theme settings by user's configuration.""" + ... + + + +class BuiltInTheme(Theme): + """A built-in LaTeX theme.""" + def __init__(self, name: str, config: Config) -> None: + ... + + + +class UserTheme(Theme): + """A user defined LaTeX theme.""" + REQUIRED_CONFIG_KEYS = ... + OPTIONAL_CONFIG_KEYS = ... + def __init__(self, name: str, filename: str) -> None: + ... + + + +class ThemeFactory: + """A factory class for LaTeX Themes.""" + def __init__(self, app: Sphinx) -> None: + ... + + def load_builtin_themes(self, config: Config) -> None: + """Load built-in themes.""" + ... + + def get(self, name: str) -> Theme: + """Get a theme for given *name*.""" + ... + + def find_user_theme(self, name: str) -> Theme | None: + """Find a theme named as *name* from latex_theme_path.""" + ... + + + diff --git a/typings/sphinx/builders/latex/util.pyi b/typings/sphinx/builders/latex/util.pyi new file mode 100644 index 0000000..9eb6f01 --- /dev/null +++ b/typings/sphinx/builders/latex/util.pyi @@ -0,0 +1,27 @@ +""" +This type stub file was generated by pyright. +""" + +from docutils.writers.latex2e import Babel + +"""Utilities for LaTeX builder.""" +class ExtBabel(Babel): + cyrillic_languages = ... + def __init__(self, language_code: str, use_polyglossia: bool = ...) -> None: + ... + + def uses_cyrillic(self) -> bool: + ... + + def is_supported_language(self) -> bool: + ... + + def language_name(self, language_code: str) -> str: + ... + + def get_mainlanguage_options(self) -> str | None: + """Return options for polyglossia's ``\\setmainlanguage``.""" + ... + + + diff --git a/typings/sphinx/cmd/__init__.pyi b/typings/sphinx/cmd/__init__.pyi new file mode 100644 index 0000000..41582fb --- /dev/null +++ b/typings/sphinx/cmd/__init__.pyi @@ -0,0 +1,5 @@ +""" +This type stub file was generated by pyright. +""" + +"""Modules for command line executables.""" diff --git a/typings/sphinx/cmd/build.pyi b/typings/sphinx/cmd/build.pyi new file mode 100644 index 0000000..7b896f6 --- /dev/null +++ b/typings/sphinx/cmd/build.pyi @@ -0,0 +1,39 @@ +""" +This type stub file was generated by pyright. +""" + +import argparse +from typing import Any, TYPE_CHECKING, TextIO +from sphinx.application import Sphinx +from collections.abc import Sequence + +"""Build documentation from a provided source.""" +if TYPE_CHECKING: + ... +def handle_exception(app: Sphinx | None, args: Any, exception: BaseException, stderr: TextIO = ...) -> None: + ... + +def jobs_argument(value: str) -> int: + """ + Special type to handle 'auto' flags passed to 'sphinx-build' via -j flag. Can + be expanded to handle other special scaling requests, such as setting job count + to cpu_count. + """ + ... + +def get_parser() -> argparse.ArgumentParser: + ... + +def make_main(argv: Sequence[str]) -> int: + """Sphinx build "make mode" entry.""" + ... + +def build_main(argv: Sequence[str]) -> int: + """Sphinx build "main" command-line entry.""" + ... + +def main(argv: Sequence[str] = ..., /) -> int: + ... + +if __name__ == '__main__': + ... diff --git a/typings/sphinx/cmd/make_mode.pyi b/typings/sphinx/cmd/make_mode.pyi new file mode 100644 index 0000000..bda3e50 --- /dev/null +++ b/typings/sphinx/cmd/make_mode.pyi @@ -0,0 +1,51 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from collections.abc import Sequence + +"""sphinx-build -M command-line handling. + +This replaces the old, platform-dependent and once-generated content +of Makefile / make.bat. + +This is in its own module so that importing it is fast. It should not +import the main Sphinx modules (like sphinx.applications, sphinx.builders). +""" +if TYPE_CHECKING: + ... +BUILDERS = ... +class Make: + def __init__(self, srcdir: str, builddir: str, opts: Sequence[str]) -> None: + ... + + def builddir_join(self, *comps: str) -> str: + ... + + def build_clean(self) -> int: + ... + + def build_help(self) -> None: + ... + + def build_latexpdf(self) -> int: + ... + + def build_latexpdfja(self) -> int: + ... + + def build_info(self) -> int: + ... + + def build_gettext(self) -> int: + ... + + def run_generic_build(self, builder: str, doctreedir: str | None = ...) -> int: + ... + + + +def run_make_mode(args: Sequence[str]) -> int: + ... + diff --git a/typings/sphinx/config.pyi b/typings/sphinx/config.pyi new file mode 100644 index 0000000..31172fc --- /dev/null +++ b/typings/sphinx/config.pyi @@ -0,0 +1,164 @@ +""" +This type stub file was generated by pyright. +""" + +import os +from typing import Any, NamedTuple, TYPE_CHECKING +from collections.abc import Generator, Iterator, Sequence +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.util.tags import Tags + +"""Build configuration file handling.""" +if TYPE_CHECKING: + ... +logger = ... +CONFIG_FILENAME = ... +UNSERIALIZABLE_TYPES = ... +class ConfigValue(NamedTuple): + name: str + value: Any + rebuild: bool | str + ... + + +def is_serializable(obj: Any) -> bool: + """Check if object is serializable or not.""" + ... + +class ENUM: + """Represents the candidates which a config value should be one of. + + Example: + app.add_config_value('latex_show_urls', 'no', None, ENUM('no', 'footnote', 'inline')) + """ + def __init__(self, *candidates: str | bool | None) -> None: + ... + + def match(self, value: str | list | tuple) -> bool: + ... + + + +class Config: + r"""Configuration file abstraction. + + The config object makes the values of all config values available as + attributes. + + It is exposed via the :py:class:`~sphinx.application.Sphinx`\ ``.config`` + and :py:class:`sphinx.environment.BuildEnvironment`\ ``.config`` attributes. + For example, to get the value of :confval:`language`, use either + ``app.config.language`` or ``env.config.language``. + """ + config_values: dict[str, tuple] = ... + def __init__(self, config: dict[str, Any] | None = ..., overrides: dict[str, Any] | None = ...) -> None: + ... + + @classmethod + def read(cls, confdir: str | os.PathLike[str], overrides: dict | None = ..., tags: Tags | None = ...) -> Config: + """Create a Config object from configuration file.""" + ... + + def convert_overrides(self, name: str, value: Any) -> Any: + ... + + def pre_init_values(self) -> None: + """ + Initialize some limited config variables before initializing i18n and loading + extensions. + """ + ... + + def init_values(self) -> None: + ... + + def post_init_values(self) -> None: + """ + Initialize additional config variables that are added after init_values() called. + """ + ... + + def __getattr__(self, name: str) -> Any: + ... + + def __getitem__(self, name: str) -> Any: + ... + + def __setitem__(self, name: str, value: Any) -> None: + ... + + def __delitem__(self, name: str) -> None: + ... + + def __contains__(self, name: str) -> bool: + ... + + def __iter__(self) -> Generator[ConfigValue, None, None]: + ... + + def add(self, name: str, default: Any, rebuild: bool | str, types: Any) -> None: + ... + + def filter(self, rebuild: str | Sequence[str]) -> Iterator[ConfigValue]: + ... + + def __getstate__(self) -> dict: + """Obtains serializable data for pickling.""" + ... + + def __setstate__(self, state: dict) -> None: + ... + + + +def eval_config_file(filename: str, tags: Tags | None) -> dict[str, Any]: + """Evaluate a config file.""" + ... + +def convert_source_suffix(app: Sphinx, config: Config) -> None: + """Convert old styled source_suffix to new styled one. + + * old style: str or list + * new style: a dict which maps from fileext to filetype + """ + ... + +def convert_highlight_options(app: Sphinx, config: Config) -> None: + """Convert old styled highlight_options to new styled one. + + * old style: options + * new style: a dict which maps from language name to options + """ + ... + +def init_numfig_format(app: Sphinx, config: Config) -> None: + """Initialize :confval:`numfig_format`.""" + ... + +def correct_copyright_year(_app: Sphinx, config: Config) -> None: + """Correct values of copyright year that are not coherent with + the SOURCE_DATE_EPOCH environment variable (if set) + + See https://reproducible-builds.org/specs/source-date-epoch/ + """ + ... + +def check_confval_types(app: Sphinx | None, config: Config) -> None: + """Check all values for deviation from the default value's type, since + that can result in TypeErrors all over the place NB. + """ + ... + +def check_primary_domain(app: Sphinx, config: Config) -> None: + ... + +def check_root_doc(app: Sphinx, env: BuildEnvironment, added: set[str], changed: set[str], removed: set[str]) -> set[str]: + """Adjust root_doc to 'contents' to support an old project which does not have + any root_doc setting. + """ + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/deprecation.pyi b/typings/sphinx/deprecation.pyi new file mode 100644 index 0000000..9245027 --- /dev/null +++ b/typings/sphinx/deprecation.pyi @@ -0,0 +1,14 @@ +""" +This type stub file was generated by pyright. +""" + +"""Sphinx deprecation classes and utilities.""" +class RemovedInSphinx80Warning(DeprecationWarning): + ... + + +class RemovedInSphinx90Warning(PendingDeprecationWarning): + ... + + +RemovedInNextVersionWarning = RemovedInSphinx80Warning diff --git a/typings/sphinx/directives/__init__.pyi b/typings/sphinx/directives/__init__.pyi new file mode 100644 index 0000000..d8b4867 --- /dev/null +++ b/typings/sphinx/directives/__init__.pyi @@ -0,0 +1,150 @@ +""" +This type stub file was generated by pyright. +""" + +import re +from __future__ import annotations +from typing import Any, Generic, TYPE_CHECKING, TypeVar, cast +from docutils import nodes +from docutils.parsers.rst import directives, roles +from sphinx import addnodes +from sphinx.addnodes import desc_signature +from sphinx.util import docutils +from sphinx.util.docfields import DocFieldTransformer, Field, TypedField +from sphinx.util.docutils import SphinxDirective +from sphinx.util.nodes import nested_parse_with_titles +from sphinx.util.typing import OptionSpec +from docutils.nodes import Node +from sphinx.application import Sphinx + +"""Handlers for additional ReST directives.""" +if TYPE_CHECKING: + ... +nl_escape_re = ... +strip_backslash_re = ... +def optional_int(argument: str) -> int | None: + """ + Check for an integer argument or None value; raise ``ValueError`` if not. + """ + ... + +ObjDescT = TypeVar('ObjDescT') +class ObjectDescription(SphinxDirective, Generic[ObjDescT]): + """ + Directive to describe a class, function or similar object. Not used + directly, but subclassed (in domain-specific directives) to add custom + behavior. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + doc_field_types: list[Field] = ... + domain: str | None = ... + objtype: str + indexnode: addnodes.index + _doc_field_type_map: dict[str, tuple[Field, bool]] = ... + def get_field_type_map(self) -> dict[str, tuple[Field, bool]]: + ... + + def get_signatures(self) -> list[str]: + """ + Retrieve the signatures to document from the directive arguments. By + default, signatures are given as arguments, one per line. + """ + ... + + def handle_signature(self, sig: str, signode: desc_signature) -> ObjDescT: + """ + Parse the signature *sig* into individual nodes and append them to + *signode*. If ValueError is raised, parsing is aborted and the whole + *sig* is put into a single desc_name node. + + The return value should be a value that identifies the object. It is + passed to :meth:`add_target_and_index()` unchanged, and otherwise only + used to skip duplicates. + """ + ... + + def add_target_and_index(self, name: ObjDescT, sig: str, signode: desc_signature) -> None: + """ + Add cross-reference IDs and entries to self.indexnode, if applicable. + + *name* is whatever :meth:`handle_signature()` returned. + """ + ... + + def before_content(self) -> None: + """ + Called before parsing content. Used to set information about the current + directive context on the build environment. + """ + ... + + def transform_content(self, contentnode: addnodes.desc_content) -> None: + """ + Called after creating the content through nested parsing, + but before the ``object-description-transform`` event is emitted, + and before the info-fields are transformed. + Can be used to manipulate the content. + """ + ... + + def after_content(self) -> None: + """ + Called after parsing content. Used to reset information about the + current directive context on the build environment. + """ + ... + + def run(self) -> list[Node]: + """ + Main directive entry function, called by docutils upon encountering the + directive. + + This directive is meant to be quite easily subclassable, so it delegates + to several additional methods. What it does: + + * find out if called as a domain-specific directive, set self.domain + * create a `desc` node to fit all description inside + * parse standard options, currently `no-index` + * create an index node if needed as self.indexnode + * parse all given signatures (as returned by self.get_signatures()) + using self.handle_signature(), which should either return a name + or raise ValueError + * add index entries using self.add_target_and_index() + * parse the content and handle doc fields in it + """ + ... + + + +class DefaultRole(SphinxDirective): + """ + Set the default interpreted text role. Overridden from docutils. + """ + optional_arguments = ... + final_argument_whitespace = ... + def run(self) -> list[Node]: + ... + + + +class DefaultDomain(SphinxDirective): + """ + Directive to (re-)set the default domain for this source file. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/__init__.pyi b/typings/sphinx/domains/__init__.pyi new file mode 100644 index 0000000..0a1bf71 --- /dev/null +++ b/typings/sphinx/domains/__init__.pyi @@ -0,0 +1,307 @@ +""" +This type stub file was generated by pyright. +""" + +import copy +from __future__ import annotations +from abc import ABC, abstractmethod +from typing import Any, Callable, NamedTuple, Optional, TYPE_CHECKING, cast +from docutils.nodes import Element, Node, system_message +from sphinx.errors import SphinxError +from sphinx.locale import _ +from collections.abc import Iterable, Sequence +from docutils import nodes +from docutils.parsers.rst import Directive +from docutils.parsers.rst.states import Inliner +from sphinx.addnodes import pending_xref +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.roles import XRefRole +from sphinx.util.typing import RoleFunction + +"""Support for domains. + +Domains are groupings of description directives +and roles describing e.g. constructs of one programming language. +""" +if TYPE_CHECKING: + ... +class ObjType: + """ + An ObjType is the description for a type of object that a domain can + document. In the object_types attribute of Domain subclasses, object type + names are mapped to instances of this class. + + Constructor arguments: + + - *lname*: localized name of the type (do not include domain name) + - *roles*: all the roles that can refer to an object of this type + - *attrs*: object attributes -- currently only "searchprio" is known, + which defines the object's priority in the full-text search index, + see :meth:`Domain.get_objects()`. + """ + known_attrs = ... + def __init__(self, lname: str, *roles: Any, **attrs: Any) -> None: + ... + + + +class IndexEntry(NamedTuple): + name: str + subtype: int + docname: str + anchor: str + extra: str + qualifier: str + descr: str + ... + + +class Index(ABC): + """ + An Index is the description for a domain-specific index. To add an index to + a domain, subclass Index, overriding the three name attributes: + + * `name` is an identifier used for generating file names. + It is also used for a hyperlink target for the index. Therefore, users can + refer the index page using ``ref`` role and a string which is combined + domain name and ``name`` attribute (ex. ``:ref:`py-modindex```). + * `localname` is the section title for the index. + * `shortname` is a short name for the index, for use in the relation bar in + HTML output. Can be empty to disable entries in the relation bar. + + and providing a :meth:`generate()` method. Then, add the index class to + your domain's `indices` list. Extensions can add indices to existing + domains using :meth:`~sphinx.application.Sphinx.add_index_to_domain()`. + + .. versionchanged:: 3.0 + + Index pages can be referred by domain name and index name via + :rst:role:`ref` role. + """ + name: str + localname: str + shortname: str | None = ... + def __init__(self, domain: Domain) -> None: + ... + + @abstractmethod + def generate(self, docnames: Iterable[str] | None = ...) -> tuple[list[tuple[str, list[IndexEntry]]], bool]: + """Get entries for the index. + + If ``docnames`` is given, restrict to entries referring to these + docnames. + + The return value is a tuple of ``(content, collapse)``: + + ``collapse`` + A boolean that determines if sub-entries should start collapsed (for + output formats that support collapsing sub-entries). + + ``content``: + A sequence of ``(letter, entries)`` tuples, where ``letter`` is the + "heading" for the given ``entries``, usually the starting letter, and + ``entries`` is a sequence of single entries. Each entry is a sequence + ``[name, subtype, docname, anchor, extra, qualifier, descr]``. The + items in this sequence have the following meaning: + + ``name`` + The name of the index entry to be displayed. + + ``subtype`` + The sub-entry related type. One of: + + ``0`` + A normal entry. + ``1`` + An entry with sub-entries. + ``2`` + A sub-entry. + + ``docname`` + *docname* where the entry is located. + + ``anchor`` + Anchor for the entry within ``docname`` + + ``extra`` + Extra info for the entry. + + ``qualifier`` + Qualifier for the description. + + ``descr`` + Description for the entry. + + Qualifier and description are not rendered for some output formats such + as LaTeX. + """ + ... + + + +TitleGetter = Callable[[Node], Optional[str]] +class Domain: + """ + A Domain is meant to be a group of "object" description directives for + objects of a similar nature, and corresponding roles to create references to + them. Examples would be Python modules, classes, functions etc., elements + of a templating language, Sphinx roles and directives, etc. + + Each domain has a separate storage for information about existing objects + and how to reference them in `self.data`, which must be a dictionary. It + also must implement several functions that expose the object information in + a uniform way to parts of Sphinx that allow the user to reference or search + for objects in a domain-agnostic way. + + About `self.data`: since all object and cross-referencing information is + stored on a BuildEnvironment instance, the `domain.data` object is also + stored in the `env.domaindata` dict under the key `domain.name`. Before the + build process starts, every active domain is instantiated and given the + environment object; the `domaindata` dict must then either be nonexistent or + a dictionary whose 'version' key is equal to the domain class' + :attr:`data_version` attribute. Otherwise, `OSError` is raised and the + pickled environment is discarded. + """ + name = ... + label = ... + object_types: dict[str, ObjType] = ... + directives: dict[str, type[Directive]] = ... + roles: dict[str, RoleFunction | XRefRole] = ... + indices: list[type[Index]] = ... + dangling_warnings: dict[str, str] = ... + enumerable_nodes: dict[type[Node], tuple[str, TitleGetter | None]] = ... + initial_data: dict = ... + data: dict + data_version = ... + def __init__(self, env: BuildEnvironment) -> None: + ... + + def setup(self) -> None: + """Set up domain object.""" + ... + + def add_object_type(self, name: str, objtype: ObjType) -> None: + """Add an object type.""" + ... + + def role(self, name: str) -> RoleFunction | None: + """Return a role adapter function that always gives the registered + role its full name ('domain:name') as the first argument. + """ + ... + + def directive(self, name: str) -> Callable | None: + """Return a directive adapter class that always gives the registered + directive its full name ('domain:name') as ``self.name``. + """ + class DirectiveAdapter(BaseDirective): + ... + + + + def clear_doc(self, docname: str) -> None: + """Remove traces of a document in the domain-specific inventories.""" + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict) -> None: + """Merge in data regarding *docnames* from a different domaindata + inventory (coming from a subprocess in parallel builds). + """ + ... + + def process_doc(self, env: BuildEnvironment, docname: str, document: nodes.document) -> None: + """Process a document after it is read by the environment.""" + ... + + def check_consistency(self) -> None: + """Do consistency checks (**experimental**).""" + ... + + def process_field_xref(self, pnode: pending_xref) -> None: + """Process a pending xref created in a doc field. + For example, attach information about the current scope. + """ + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + """Resolve the pending_xref *node* with the given *typ* and *target*. + + This method should return a new node, to replace the xref node, + containing the *contnode* which is the markup content of the + cross-reference. + + If no resolution can be found, None can be returned; the xref node will + then given to the :event:`missing-reference` event, and if that yields no + resolution, replaced by *contnode*. + + The method can also raise :exc:`sphinx.environment.NoUri` to suppress + the :event:`missing-reference` event being emitted. + """ + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + """Resolve the pending_xref *node* with the given *target*. + + The reference comes from an "any" or similar role, which means that we + don't know the type. Otherwise, the arguments are the same as for + :meth:`resolve_xref`. + + The method must return a list (potentially empty) of tuples + ``('domain:role', newnode)``, where ``'domain:role'`` is the name of a + role that could have created the same reference, e.g. ``'py:func'``. + ``newnode`` is what :meth:`resolve_xref` would return. + + .. versionadded:: 1.3 + """ + ... + + def get_objects(self) -> Iterable[tuple[str, str, str, str, str, int]]: + """Return an iterable of "object descriptions". + + Object descriptions are tuples with six items: + + ``name`` + Fully qualified name. + + ``dispname`` + Name to display when searching/linking. + + ``type`` + Object type, a key in ``self.object_types``. + + ``docname`` + The document where it is to be found. + + ``anchor`` + The anchor name for the object. + + ``priority`` + How "important" the object is (determines placement in search + results). One of: + + ``1`` + Default priority (placed before full-text matches). + ``0`` + Object is important (placed before default-priority objects). + ``2`` + Object is unimportant (placed after full-text matches). + ``-1`` + Object should not show up in search at all. + """ + ... + + def get_type_name(self, type: ObjType, primary: bool = ...) -> str: + """Return full name for given ObjType.""" + ... + + def get_enumerable_node_type(self, node: Node) -> str | None: + """Get type of enumerable nodes (experimental).""" + ... + + def get_full_qualified_name(self, node: Element) -> str | None: + """Return full qualified name for given node.""" + ... + + + diff --git a/typings/sphinx/domains/c.pyi b/typings/sphinx/domains/c.pyi new file mode 100644 index 0000000..3b5f0b1 --- /dev/null +++ b/typings/sphinx/domains/c.pyi @@ -0,0 +1,923 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING, TypeVar, Union +from docutils import nodes +from docutils.parsers.rst import directives +from sphinx.directives import ObjectDescription +from sphinx.domains import Domain +from sphinx.roles import SphinxRole, XRefRole +from sphinx.transforms import SphinxTransform +from sphinx.util.cfamily import ASTAttributeList, ASTBaseBase, ASTBaseParenExprList, BaseParser +from sphinx.util.docutils import SphinxDirective +from collections.abc import Iterator +from docutils.nodes import Element, Node, TextElement, system_message +from sphinx.addnodes import pending_xref +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec + +"""The C language domain.""" +if TYPE_CHECKING: + ... +logger = ... +T = TypeVar('T') +DeclarationType = Union["ASTStruct", "ASTUnion", "ASTEnum", "ASTEnumerator", "ASTType", "ASTTypeWithInit", "ASTMacro",] +_keywords = ... +_macroKeywords = ... +_expression_bin_ops = ... +_expression_unary_ops = ... +_expression_assignment_ops = ... +_max_id = ... +_id_prefix = ... +_string_re = ... +_simple_type_specifiers_re = ... +class _DuplicateSymbolError(Exception): + def __init__(self, symbol: Symbol, declaration: ASTDeclaration) -> None: + ... + + def __str__(self) -> str: + ... + + + +class ASTBase(ASTBaseBase): + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTIdentifier(ASTBaseBase): + def __init__(self, identifier: str) -> None: + ... + + def __eq__(self, other: Any) -> bool: + ... + + def is_anon(self) -> bool: + ... + + def __str__(self) -> str: + ... + + def get_display_string(self) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, prefix: str, symbol: Symbol) -> None: + ... + + + +class ASTNestedName(ASTBase): + def __init__(self, names: list[ASTIdentifier], rooted: bool) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTExpression(ASTBase): + ... + + +class ASTLiteral(ASTExpression): + ... + + +class ASTBooleanLiteral(ASTLiteral): + def __init__(self, value: bool) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTNumberLiteral(ASTLiteral): + def __init__(self, data: str) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTCharLiteral(ASTLiteral): + def __init__(self, prefix: str, data: str) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTStringLiteral(ASTLiteral): + def __init__(self, data: str) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTIdExpression(ASTExpression): + def __init__(self, name: ASTNestedName) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTParenExpr(ASTExpression): + def __init__(self, expr) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixOp(ASTBase): + ... + + +class ASTPostfixCallExpr(ASTPostfixOp): + def __init__(self, lst: ASTParenExprList | ASTBracedInitList) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixArray(ASTPostfixOp): + def __init__(self, expr: ASTExpression) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixInc(ASTPostfixOp): + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixDec(ASTPostfixOp): + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixMemberOfPointer(ASTPostfixOp): + def __init__(self, name) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixExpr(ASTExpression): + def __init__(self, prefix: ASTExpression, postFixes: list[ASTPostfixOp]) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTUnaryOpExpr(ASTExpression): + def __init__(self, op: str, expr: ASTExpression) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTSizeofType(ASTExpression): + def __init__(self, typ) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTSizeofExpr(ASTExpression): + def __init__(self, expr: ASTExpression) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTAlignofExpr(ASTExpression): + def __init__(self, typ: ASTType) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTCastExpr(ASTExpression): + def __init__(self, typ: ASTType, expr: ASTExpression) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTBinOpExpr(ASTBase): + def __init__(self, exprs: list[ASTExpression], ops: list[str]) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTAssignmentExpr(ASTExpression): + def __init__(self, exprs: list[ASTExpression], ops: list[str]) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTFallbackExpr(ASTExpression): + def __init__(self, expr: str) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTrailingTypeSpec(ASTBase): + ... + + +class ASTTrailingTypeSpecFundamental(ASTTrailingTypeSpec): + def __init__(self, names: list[str]) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTrailingTypeSpecName(ASTTrailingTypeSpec): + def __init__(self, prefix: str, nestedName: ASTNestedName) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTFunctionParameter(ASTBase): + def __init__(self, arg: ASTTypeWithInit | None, ellipsis: bool = ...) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: Any, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTParameters(ASTBase): + def __init__(self, args: list[ASTFunctionParameter], attrs: ASTAttributeList) -> None: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclSpecsSimple(ASTBaseBase): + def __init__(self, storage: str, threadLocal: str, inline: bool, restrict: bool, volatile: bool, const: bool, attrs: ASTAttributeList) -> None: + ... + + def mergeWith(self, other: ASTDeclSpecsSimple) -> ASTDeclSpecsSimple: + ... + + def describe_signature(self, modifiers: list[Node]) -> None: + ... + + + +class ASTDeclSpecs(ASTBase): + def __init__(self, outer: str, leftSpecs: ASTDeclSpecsSimple, rightSpecs: ASTDeclSpecsSimple, trailing: ASTTrailingTypeSpec) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTArray(ASTBase): + def __init__(self, static: bool, const: bool, volatile: bool, restrict: bool, vla: bool, size: ASTExpression) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclarator(ASTBase): + @property + def name(self) -> ASTNestedName: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + + +class ASTDeclaratorNameParam(ASTDeclarator): + def __init__(self, declId: ASTNestedName, arrayOps: list[ASTArray], param: ASTParameters) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorNameBitField(ASTDeclarator): + def __init__(self, declId: ASTNestedName, size: ASTExpression) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorPtr(ASTDeclarator): + def __init__(self, next: ASTDeclarator, restrict: bool, volatile: bool, const: bool, attrs: ASTAttributeList) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorParen(ASTDeclarator): + def __init__(self, inner: ASTDeclarator, next: ASTDeclarator) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTParenExprList(ASTBaseParenExprList): + def __init__(self, exprs: list[ASTExpression]) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTBracedInitList(ASTBase): + def __init__(self, exprs: list[ASTExpression], trailingComma: bool) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTInitializer(ASTBase): + def __init__(self, value: ASTBracedInitList | ASTExpression, hasAssign: bool = ...) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTType(ASTBase): + def __init__(self, declSpecs: ASTDeclSpecs, decl: ASTDeclarator) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + def get_type_declaration_prefix(self) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTypeWithInit(ASTBase): + def __init__(self, type: ASTType, init: ASTInitializer) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTMacroParameter(ASTBase): + def __init__(self, arg: ASTNestedName | None, ellipsis: bool = ..., variadic: bool = ...) -> None: + ... + + def describe_signature(self, signode: Any, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTMacro(ASTBase): + def __init__(self, ident: ASTNestedName, args: list[ASTMacroParameter] | None) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTStruct(ASTBase): + def __init__(self, name: ASTNestedName) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTUnion(ASTBase): + def __init__(self, name: ASTNestedName) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTEnum(ASTBase): + def __init__(self, name: ASTNestedName) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTEnumerator(ASTBase): + def __init__(self, name: ASTNestedName, init: ASTInitializer | None, attrs: ASTAttributeList) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaration(ASTBaseBase): + def __init__(self, objectType: str, directiveType: str | None, declaration: DeclarationType | ASTFunctionParameter, semicolon: bool = ...) -> None: + ... + + def clone(self) -> ASTDeclaration: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter] | None: + ... + + def get_id(self, version: int, prefixed: bool = ...) -> str: + ... + + def get_newest_id(self) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, options: dict) -> None: + ... + + + +class SymbolLookupResult: + def __init__(self, symbols: Iterator[Symbol], parentSymbol: Symbol, ident: ASTIdentifier) -> None: + ... + + + +class LookupKey: + def __init__(self, data: list[tuple[ASTIdentifier, str]]) -> None: + ... + + def __str__(self) -> str: + ... + + + +class Symbol: + debug_indent = ... + debug_indent_string = ... + debug_lookup = ... + debug_show_tree = ... + def __copy__(self): + ... + + def __deepcopy__(self, memo): # -> Symbol: + ... + + @staticmethod + def debug_print(*args: Any) -> None: + ... + + def __setattr__(self, key: str, value: Any) -> None: + ... + + def __init__(self, parent: Symbol, ident: ASTIdentifier, declaration: ASTDeclaration | None, docname: str | None, line: int | None) -> None: + ... + + def remove(self) -> None: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def get_all_symbols(self) -> Iterator[Symbol]: + ... + + @property + def children(self) -> Iterator[Symbol]: + ... + + @property + def children_recurse_anon(self) -> Iterator[Symbol]: + ... + + def get_lookup_key(self) -> LookupKey: + ... + + def get_full_nested_name(self) -> ASTNestedName: + ... + + def merge_with(self, other: Symbol, docnames: list[str], env: BuildEnvironment) -> None: + ... + + def add_name(self, nestedName: ASTNestedName) -> Symbol: + ... + + def add_declaration(self, declaration: ASTDeclaration, docname: str, line: int) -> Symbol: + ... + + def find_identifier(self, ident: ASTIdentifier, matchSelf: bool, recurseInAnon: bool, searchInSiblings: bool) -> Symbol | None: + ... + + def direct_lookup(self, key: LookupKey) -> Symbol | None: + ... + + def find_declaration(self, nestedName: ASTNestedName, typ: str, matchSelf: bool, recurseInAnon: bool) -> Symbol | None: + ... + + def to_string(self, indent: int) -> str: + ... + + def dump(self, indent: int) -> str: + ... + + + +class DefinitionParser(BaseParser): + @property + def language(self) -> str: + ... + + @property + def id_attributes(self): # -> Any: + ... + + @property + def paren_attributes(self): # -> Any: + ... + + def parse_declaration(self, objectType: str, directiveType: str) -> ASTDeclaration: + ... + + def parse_namespace_object(self) -> ASTNestedName: + ... + + def parse_xref_object(self) -> ASTNestedName: + ... + + def parse_expression(self) -> ASTExpression | ASTType: + ... + + + +class CObject(ObjectDescription[ASTDeclaration]): + """ + Description of a C language object. + """ + option_spec: OptionSpec = ... + def add_target_and_index(self, ast: ASTDeclaration, sig: str, signode: TextElement) -> None: + ... + + @property + def object_type(self) -> str: + ... + + @property + def display_object_type(self) -> str: + ... + + def get_index_text(self, name: str) -> str: + ... + + def parse_definition(self, parser: DefinitionParser) -> ASTDeclaration: + ... + + def describe_signature(self, signode: TextElement, ast: ASTDeclaration, options: dict) -> None: + ... + + def run(self) -> list[Node]: + ... + + def handle_signature(self, sig: str, signode: TextElement) -> ASTDeclaration: + ... + + def before_content(self) -> None: + ... + + def after_content(self) -> None: + ... + + + +class CMemberObject(CObject): + object_type = ... + @property + def display_object_type(self) -> str: + ... + + + +_function_doc_field_types = ... +class CFunctionObject(CObject): + object_type = ... + doc_field_types = ... + + +class CMacroObject(CObject): + object_type = ... + doc_field_types = ... + + +class CStructObject(CObject): + object_type = ... + + +class CUnionObject(CObject): + object_type = ... + + +class CEnumObject(CObject): + object_type = ... + + +class CEnumeratorObject(CObject): + object_type = ... + + +class CTypeObject(CObject): + object_type = ... + + +class CNamespaceObject(SphinxDirective): + """ + This directive is just to tell Sphinx that we're documenting stuff in + namespace foo. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class CNamespacePushObject(SphinxDirective): + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class CNamespacePopObject(SphinxDirective): + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class AliasNode(nodes.Element): + def __init__(self, sig: str, aliasOptions: dict, document: Any, env: BuildEnvironment | None = ..., parentKey: LookupKey | None = ...) -> None: + ... + + def copy(self) -> AliasNode: + ... + + + +class AliasTransform(SphinxTransform): + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class CAliasObject(ObjectDescription): + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + """ + On purpose this doesn't call the ObjectDescription version, but is based on it. + Each alias signature may expand into multiple real signatures if 'noroot'. + The code is therefore based on the ObjectDescription version. + """ + ... + + + +class CXRefRole(XRefRole): + def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str) -> tuple[str, str]: + ... + + + +class CExprRole(SphinxRole): + def __init__(self, asCode: bool) -> None: + ... + + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + + +class CDomain(Domain): + """C language domain.""" + name = ... + label = ... + object_types = ... + directives = ... + roles = ... + initial_data: dict[str, Symbol | dict[str, tuple[str, str, str]]] = ... + def clear_doc(self, docname: str) -> None: + ... + + def process_doc(self, env: BuildEnvironment, docname: str, document: nodes.document) -> None: + ... + + def process_field_xref(self, pnode: pending_xref) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict) -> None: + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + ... + + def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/changeset.pyi b/typings/sphinx/domains/changeset.pyi new file mode 100644 index 0000000..d6023de --- /dev/null +++ b/typings/sphinx/domains/changeset.pyi @@ -0,0 +1,72 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, NamedTuple, TYPE_CHECKING +from docutils import nodes +from sphinx import addnodes +from sphinx.domains import Domain +from sphinx.util.docutils import SphinxDirective +from docutils.nodes import Node +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec + +"""The changeset domain.""" +if TYPE_CHECKING: + ... +versionlabels = ... +versionlabel_classes = ... +class ChangeSet(NamedTuple): + type: str + docname: str + lineno: int + module: str | None + descname: str | None + content: str + ... + + +class VersionChange(SphinxDirective): + """ + Directive to describe a change/addition/deprecation in a specific version. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class ChangeSetDomain(Domain): + """Domain for changesets.""" + name = ... + label = ... + initial_data: dict[str, Any] = ... + @property + def changesets(self) -> dict[str, list[ChangeSet]]: + ... + + def note_changeset(self, node: addnodes.versionmodified) -> None: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict[str, Any]) -> None: + ... + + def process_doc(self, env: BuildEnvironment, docname: str, document: nodes.document) -> None: + ... + + def get_changesets_for(self, version: str) -> list[ChangeSet]: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/citation.pyi b/typings/sphinx/domains/citation.pyi new file mode 100644 index 0000000..6f72eeb --- /dev/null +++ b/typings/sphinx/domains/citation.pyi @@ -0,0 +1,76 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils import nodes +from sphinx.addnodes import pending_xref +from sphinx.domains import Domain +from sphinx.transforms import SphinxTransform +from docutils.nodes import Element +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment + +"""The citation domain.""" +if TYPE_CHECKING: + ... +logger = ... +class CitationDomain(Domain): + """Domain for citations.""" + name = ... + label = ... + dangling_warnings = ... + @property + def citations(self) -> dict[str, tuple[str, str, int]]: + ... + + @property + def citation_refs(self) -> dict[str, set[str]]: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict[str, Any]) -> None: + ... + + def note_citation(self, node: nodes.citation) -> None: + ... + + def note_citation_reference(self, node: pending_xref) -> None: + ... + + def check_consistency(self) -> None: + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + ... + + + +class CitationDefinitionTransform(SphinxTransform): + """Mark citation definition labels as not smartquoted.""" + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class CitationReferenceTransform(SphinxTransform): + """ + Replace citation references by pending_xref nodes before the default + docutils transform tries to resolve them. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/cpp.pyi b/typings/sphinx/domains/cpp.pyi new file mode 100644 index 0000000..4005b2f --- /dev/null +++ b/typings/sphinx/domains/cpp.pyi @@ -0,0 +1,1822 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING, TypeVar +from docutils import nodes +from docutils.parsers.rst import directives +from sphinx.directives import ObjectDescription +from sphinx.domains import Domain +from sphinx.roles import SphinxRole, XRefRole +from sphinx.transforms import SphinxTransform +from sphinx.util.cfamily import ASTAttributeList, ASTBaseBase, ASTBaseParenExprList, BaseParser +from sphinx.util.docfields import Field +from sphinx.util.docutils import SphinxDirective +from collections.abc import Generator, Iterator +from docutils.nodes import Element, Node, TextElement, system_message +from sphinx.addnodes import desc_signature, pending_xref +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec + +"""The C++ language domain.""" +if TYPE_CHECKING: + ... +logger = ... +T = TypeVar('T') +udl_identifier_re = ... +_string_re = ... +_visibility_re = ... +_operator_re = ... +_fold_operator_re = ... +_keywords = ... +_simple_type_specifiers_re = ... +_max_id = ... +_id_prefix = ... +_id_fundamental_v1 = ... +_id_shorthands_v1 = ... +_id_operator_v1 = ... +_id_fundamental_v2 = ... +_id_operator_v2 = ... +_id_operator_unary_v2 = ... +_id_char_from_prefix: dict[str | None, str] = ... +_expression_bin_ops = ... +_expression_unary_ops = ... +_expression_assignment_ops = ... +_id_explicit_cast = ... +class _DuplicateSymbolError(Exception): + def __init__(self, symbol: Symbol, declaration: ASTDeclaration) -> None: + ... + + def __str__(self) -> str: + ... + + + +class ASTBase(ASTBaseBase): + ... + + +class ASTIdentifier(ASTBase): + def __init__(self, identifier: str) -> None: + ... + + def is_anon(self) -> bool: + ... + + def get_id(self, version: int) -> str: + ... + + def __str__(self) -> str: + ... + + def get_display_string(self) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, prefix: str, templateArgs: str, symbol: Symbol) -> None: + ... + + + +class ASTNestedNameElement(ASTBase): + def __init__(self, identOrOp: ASTIdentifier | ASTOperator, templateArgs: ASTTemplateArgs) -> None: + ... + + def is_operator(self) -> bool: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, prefix: str, symbol: Symbol) -> None: + ... + + + +class ASTNestedName(ASTBase): + def __init__(self, names: list[ASTNestedNameElement], templates: list[bool], rooted: bool) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def num_templates(self) -> int: + ... + + def get_id(self, version: int, modifiers: str = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTExpression(ASTBase): + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTLiteral(ASTExpression): + ... + + +class ASTPointerLiteral(ASTLiteral): + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTBooleanLiteral(ASTLiteral): + def __init__(self, value: bool) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTNumberLiteral(ASTLiteral): + def __init__(self, data: str) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTStringLiteral(ASTLiteral): + def __init__(self, data: str) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTCharLiteral(ASTLiteral): + def __init__(self, prefix: str, data: str) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTUserDefinedLiteral(ASTLiteral): + def __init__(self, literal: ASTLiteral, ident: ASTIdentifier) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTThisLiteral(ASTExpression): + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTFoldExpr(ASTExpression): + def __init__(self, leftExpr: ASTExpression, op: str, rightExpr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTParenExpr(ASTExpression): + def __init__(self, expr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTIdExpression(ASTExpression): + def __init__(self, name: ASTNestedName) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixOp(ASTBase): + def get_id(self, idPrefix: str, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixArray(ASTPostfixOp): + def __init__(self, expr: ASTExpression) -> None: + ... + + def get_id(self, idPrefix: str, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixMember(ASTPostfixOp): + def __init__(self, name: ASTNestedName) -> None: + ... + + def get_id(self, idPrefix: str, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixMemberOfPointer(ASTPostfixOp): + def __init__(self, name: ASTNestedName) -> None: + ... + + def get_id(self, idPrefix: str, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixInc(ASTPostfixOp): + def get_id(self, idPrefix: str, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixDec(ASTPostfixOp): + def get_id(self, idPrefix: str, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixCallExpr(ASTPostfixOp): + def __init__(self, lst: ASTParenExprList | ASTBracedInitList) -> None: + ... + + def get_id(self, idPrefix: str, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPostfixExpr(ASTExpression): + def __init__(self, prefix: ASTType, postFixes: list[ASTPostfixOp]) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTExplicitCast(ASTExpression): + def __init__(self, cast: str, typ: ASTType, expr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTypeId(ASTExpression): + def __init__(self, typeOrExpr: ASTType | ASTExpression, isType: bool) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTUnaryOpExpr(ASTExpression): + def __init__(self, op: str, expr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTSizeofParamPack(ASTExpression): + def __init__(self, identifier: ASTIdentifier) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTSizeofType(ASTExpression): + def __init__(self, typ: ASTType) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTSizeofExpr(ASTExpression): + def __init__(self, expr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTAlignofExpr(ASTExpression): + def __init__(self, typ: ASTType) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTNoexceptExpr(ASTExpression): + def __init__(self, expr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTNewExpr(ASTExpression): + def __init__(self, rooted: bool, isNewTypeId: bool, typ: ASTType, initList: ASTParenExprList | ASTBracedInitList) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeleteExpr(ASTExpression): + def __init__(self, rooted: bool, array: bool, expr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTCastExpr(ASTExpression): + def __init__(self, typ: ASTType, expr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTBinOpExpr(ASTExpression): + def __init__(self, exprs: list[ASTExpression], ops: list[str]) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTConditionalExpr(ASTExpression): + def __init__(self, ifExpr: ASTExpression, thenExpr: ASTExpression, elseExpr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTBracedInitList(ASTBase): + def __init__(self, exprs: list[ASTExpression | ASTBracedInitList], trailingComma: bool) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTAssignmentExpr(ASTExpression): + def __init__(self, leftExpr: ASTExpression, op: str, rightExpr: ASTExpression | ASTBracedInitList) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTCommaExpr(ASTExpression): + def __init__(self, exprs: list[ASTExpression]) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTFallbackExpr(ASTExpression): + def __init__(self, expr: str) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTOperator(ASTBase): + def is_anon(self) -> bool: + ... + + def is_operator(self) -> bool: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, prefix: str, templateArgs: str, symbol: Symbol) -> None: + ... + + + +class ASTOperatorBuildIn(ASTOperator): + def __init__(self, op: str) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + + +class ASTOperatorLiteral(ASTOperator): + def __init__(self, identifier: ASTIdentifier) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + + +class ASTOperatorType(ASTOperator): + def __init__(self, type: ASTType) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def get_name_no_template(self) -> str: + ... + + + +class ASTTemplateArgConstant(ASTBase): + def __init__(self, value: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTemplateArgs(ASTBase): + def __init__(self, args: list[ASTType | ASTTemplateArgConstant], packExpansion: bool) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTrailingTypeSpec(ASTBase): + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTrailingTypeSpecFundamental(ASTTrailingTypeSpec): + def __init__(self, names: list[str], canonNames: list[str]) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTrailingTypeSpecDecltypeAuto(ASTTrailingTypeSpec): + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTrailingTypeSpecDecltype(ASTTrailingTypeSpec): + def __init__(self, expr: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTrailingTypeSpecName(ASTTrailingTypeSpec): + def __init__(self, prefix: str, nestedName: ASTNestedName, placeholderType: str | None) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTFunctionParameter(ASTBase): + def __init__(self, arg: ASTTypeWithInit | ASTTemplateParamConstrainedTypeWithInit, ellipsis: bool = ...) -> None: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTNoexceptSpec(ASTBase): + def __init__(self, expr: ASTExpression | None) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTParametersQualifiers(ASTBase): + def __init__(self, args: list[ASTFunctionParameter], volatile: bool, const: bool, refQual: str | None, exceptionSpec: ASTNoexceptSpec, trailingReturn: ASTType, override: bool, final: bool, attrs: ASTAttributeList, initializer: str | None) -> None: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + def get_modifiers_id(self, version: int) -> str: + ... + + def get_param_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTExplicitSpec(ASTBase): + def __init__(self, expr: ASTExpression | None) -> None: + ... + + def describe_signature(self, signode: TextElement, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclSpecsSimple(ASTBase): + def __init__(self, storage: str, threadLocal: bool, inline: bool, virtual: bool, explicitSpec: ASTExplicitSpec | None, consteval: bool, constexpr: bool, constinit: bool, volatile: bool, const: bool, friend: bool, attrs: ASTAttributeList) -> None: + ... + + def mergeWith(self, other: ASTDeclSpecsSimple) -> ASTDeclSpecsSimple: + ... + + def describe_signature(self, signode: TextElement, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclSpecs(ASTBase): + def __init__(self, outer: str, leftSpecs: ASTDeclSpecsSimple, rightSpecs: ASTDeclSpecsSimple, trailing: ASTTrailingTypeSpec) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTArray(ASTBase): + def __init__(self, size: ASTExpression) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclarator(ASTBase): + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + @property + def isPack(self) -> bool: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + @property + def trailingReturn(self) -> ASTType: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def get_modifiers_id(self, version: int) -> str: + ... + + def get_param_id(self, version: int) -> str: + ... + + def get_ptr_suffix_id(self, version: int) -> str: + ... + + def get_type_id(self, version: int, returnTypeId: str) -> str: + ... + + def is_function_type(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorNameParamQual(ASTDeclarator): + def __init__(self, declId: ASTNestedName, arrayOps: list[ASTArray], paramQual: ASTParametersQualifiers) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + @property + def isPack(self) -> bool: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + @property + def trailingReturn(self) -> ASTType: + ... + + def get_modifiers_id(self, version: int) -> str: + ... + + def get_param_id(self, version: int) -> str: + ... + + def get_ptr_suffix_id(self, version: int) -> str: + ... + + def get_type_id(self, version: int, returnTypeId: str) -> str: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def is_function_type(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorNameBitField(ASTDeclarator): + def __init__(self, declId: ASTNestedName, size: ASTExpression) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + def get_param_id(self, version: int) -> str: + ... + + def get_ptr_suffix_id(self, version: int) -> str: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def is_function_type(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorPtr(ASTDeclarator): + def __init__(self, next: ASTDeclarator, volatile: bool, const: bool, attrs: ASTAttributeList) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + @property + def isPack(self) -> bool: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + @property + def trailingReturn(self) -> ASTType: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def get_modifiers_id(self, version: int) -> str: + ... + + def get_param_id(self, version: int) -> str: + ... + + def get_ptr_suffix_id(self, version: int) -> str: + ... + + def get_type_id(self, version: int, returnTypeId: str) -> str: + ... + + def is_function_type(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorRef(ASTDeclarator): + def __init__(self, next: ASTDeclarator, attrs: ASTAttributeList) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + @property + def isPack(self) -> bool: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + @property + def trailingReturn(self) -> ASTType: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def get_modifiers_id(self, version: int) -> str: + ... + + def get_param_id(self, version: int) -> str: + ... + + def get_ptr_suffix_id(self, version: int) -> str: + ... + + def get_type_id(self, version: int, returnTypeId: str) -> str: + ... + + def is_function_type(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorParamPack(ASTDeclarator): + def __init__(self, next: ASTDeclarator) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + @property + def trailingReturn(self) -> ASTType: + ... + + @property + def isPack(self) -> bool: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def get_modifiers_id(self, version: int) -> str: + ... + + def get_param_id(self, version: int) -> str: + ... + + def get_ptr_suffix_id(self, version: int) -> str: + ... + + def get_type_id(self, version: int, returnTypeId: str) -> str: + ... + + def is_function_type(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorMemPtr(ASTDeclarator): + def __init__(self, className: ASTNestedName, const: bool, volatile: bool, next: ASTDeclarator) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + @property + def isPack(self): # -> bool: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + @property + def trailingReturn(self) -> ASTType: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def get_modifiers_id(self, version: int) -> str: + ... + + def get_param_id(self, version: int) -> str: + ... + + def get_ptr_suffix_id(self, version: int) -> str: + ... + + def get_type_id(self, version: int, returnTypeId: str) -> str: + ... + + def is_function_type(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaratorParen(ASTDeclarator): + def __init__(self, inner: ASTDeclarator, next: ASTDeclarator) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + @property + def isPack(self): # -> bool: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + @property + def trailingReturn(self) -> ASTType: + ... + + def require_space_after_declSpecs(self) -> bool: + ... + + def get_modifiers_id(self, version: int) -> str: + ... + + def get_param_id(self, version: int) -> str: + ... + + def get_ptr_suffix_id(self, version: int) -> str: + ... + + def get_type_id(self, version: int, returnTypeId: str) -> str: + ... + + def is_function_type(self) -> bool: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTPackExpansionExpr(ASTExpression): + def __init__(self, expr: ASTExpression | ASTBracedInitList) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTParenExprList(ASTBaseParenExprList): + def __init__(self, exprs: list[ASTExpression | ASTBracedInitList]) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTInitializer(ASTBase): + def __init__(self, value: ASTExpression | ASTBracedInitList, hasAssign: bool = ...) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTType(ASTBase): + def __init__(self, declSpecs: ASTDeclSpecs, decl: ASTDeclarator) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @name.setter + def name(self, name: ASTNestedName) -> None: + ... + + @property + def isPack(self) -> bool: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + @property + def trailingReturn(self) -> ASTType: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def get_type_declaration_prefix(self) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTemplateParamConstrainedTypeWithInit(ASTBase): + def __init__(self, type: ASTType, init: ASTType) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def isPack(self) -> bool: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTypeWithInit(ASTBase): + def __init__(self, type: ASTType, init: ASTInitializer) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def isPack(self) -> bool: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTypeUsing(ASTBase): + def __init__(self, name: ASTNestedName, type: ASTType) -> None: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def get_type_declaration_prefix(self) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTConcept(ASTBase): + def __init__(self, nestedName: ASTNestedName, initializer: ASTInitializer) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTBaseClass(ASTBase): + def __init__(self, name: ASTNestedName, visibility: str, virtual: bool, pack: bool) -> None: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTClass(ASTBase): + def __init__(self, name: ASTNestedName, final: bool, bases: list[ASTBaseClass], attrs: ASTAttributeList) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTUnion(ASTBase): + def __init__(self, name: ASTNestedName, attrs: ASTAttributeList) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTEnum(ASTBase): + def __init__(self, name: ASTNestedName, scoped: str, underlyingType: ASTType, attrs: ASTAttributeList) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTEnumerator(ASTBase): + def __init__(self, name: ASTNestedName, init: ASTInitializer | None, attrs: ASTAttributeList) -> None: + ... + + def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTemplateParam(ASTBase): + def get_identifier(self) -> ASTIdentifier: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, parentNode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + @property + def isPack(self) -> bool: + ... + + @property + def name(self) -> ASTNestedName: + ... + + + +class ASTTemplateKeyParamPackIdDefault(ASTTemplateParam): + def __init__(self, key: str, identifier: ASTIdentifier, parameterPack: bool, default: ASTType) -> None: + ... + + def get_identifier(self) -> ASTIdentifier: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTemplateParamType(ASTTemplateParam): + def __init__(self, data: ASTTemplateKeyParamPackIdDefault) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def isPack(self) -> bool: + ... + + def get_identifier(self) -> ASTIdentifier: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTemplateParamTemplateType(ASTTemplateParam): + def __init__(self, nestedParams: ASTTemplateParams, data: ASTTemplateKeyParamPackIdDefault) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def isPack(self) -> bool: + ... + + def get_identifier(self) -> ASTIdentifier: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTemplateParamNonType(ASTTemplateParam): + def __init__(self, param: ASTTypeWithInit | ASTTemplateParamConstrainedTypeWithInit, parameterPack: bool = ...) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def isPack(self) -> bool: + ... + + def get_identifier(self) -> ASTIdentifier: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTemplateParams(ASTBase): + def __init__(self, params: list[ASTTemplateParam], requiresClause: ASTRequiresClause | None) -> None: + ... + + def get_id(self, version: int, excludeRequires: bool = ...) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + def describe_signature_as_introducer(self, parentNode: desc_signature, mode: str, env: BuildEnvironment, symbol: Symbol, lineSpec: bool) -> None: + ... + + + +class ASTTemplateIntroductionParameter(ASTBase): + def __init__(self, identifier: ASTIdentifier, parameterPack: bool) -> None: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def isPack(self) -> bool: + ... + + def get_identifier(self) -> ASTIdentifier: + ... + + def get_id(self, version: int, objectType: str | None = ..., symbol: Symbol | None = ...) -> str: + ... + + def get_id_as_arg(self, version: int) -> str: + ... + + def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTTemplateIntroduction(ASTBase): + def __init__(self, concept: ASTNestedName, params: list[ASTTemplateIntroductionParameter]) -> None: + ... + + def get_id(self, version: int) -> str: + ... + + def describe_signature_as_introducer(self, parentNode: desc_signature, mode: str, env: BuildEnvironment, symbol: Symbol, lineSpec: bool) -> None: + ... + + + +class ASTTemplateDeclarationPrefix(ASTBase): + def __init__(self, templates: list[ASTTemplateParams | ASTTemplateIntroduction]) -> None: + ... + + def get_requires_clause_in_last(self) -> ASTRequiresClause | None: + ... + + def get_id_except_requires_clause_in_last(self, version: int) -> str: + ... + + def describe_signature(self, signode: desc_signature, mode: str, env: BuildEnvironment, symbol: Symbol, lineSpec: bool) -> None: + ... + + + +class ASTRequiresClause(ASTBase): + def __init__(self, expr: ASTExpression) -> None: + ... + + def describe_signature(self, signode: nodes.TextElement, mode: str, env: BuildEnvironment, symbol: Symbol) -> None: + ... + + + +class ASTDeclaration(ASTBase): + def __init__(self, objectType: str, directiveType: str | None = ..., visibility: str | None = ..., templatePrefix: ASTTemplateDeclarationPrefix | None = ..., declaration: Any = ..., trailingRequiresClause: ASTRequiresClause | None = ..., semicolon: bool = ...) -> None: + ... + + def clone(self) -> ASTDeclaration: + ... + + @property + def name(self) -> ASTNestedName: + ... + + @property + def function_params(self) -> list[ASTFunctionParameter]: + ... + + def get_id(self, version: int, prefixed: bool = ...) -> str: + ... + + def get_newest_id(self) -> str: + ... + + def describe_signature(self, signode: desc_signature, mode: str, env: BuildEnvironment, options: dict) -> None: + ... + + + +class ASTNamespace(ASTBase): + def __init__(self, nestedName: ASTNestedName, templatePrefix: ASTTemplateDeclarationPrefix) -> None: + ... + + + +class SymbolLookupResult: + def __init__(self, symbols: Iterator[Symbol], parentSymbol: Symbol, identOrOp: ASTIdentifier | ASTOperator, templateParams: Any, templateArgs: ASTTemplateArgs) -> None: + ... + + + +class LookupKey: + def __init__(self, data: list[tuple[ASTNestedNameElement, ASTTemplateParams | ASTTemplateIntroduction, str]]) -> None: + ... + + + +class Symbol: + debug_indent = ... + debug_indent_string = ... + debug_lookup = ... + debug_show_tree = ... + def __copy__(self): + ... + + def __deepcopy__(self, memo): # -> Symbol: + ... + + @staticmethod + def debug_print(*args: Any) -> None: + ... + + def __setattr__(self, key: str, value: Any) -> None: + ... + + def __init__(self, parent: Symbol | None, identOrOp: ASTIdentifier | ASTOperator | None, templateParams: ASTTemplateParams | ASTTemplateIntroduction | None, templateArgs: Any, declaration: ASTDeclaration | None, docname: str | None, line: int | None) -> None: + ... + + def remove(self) -> None: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def get_all_symbols(self) -> Iterator[Any]: + ... + + @property + def children_recurse_anon(self) -> Generator[Symbol, None, None]: + ... + + def get_lookup_key(self) -> LookupKey: + ... + + def get_full_nested_name(self) -> ASTNestedName: + ... + + def merge_with(self, other: Symbol, docnames: list[str], env: BuildEnvironment) -> None: + ... + + def add_name(self, nestedName: ASTNestedName, templatePrefix: ASTTemplateDeclarationPrefix | None = ...) -> Symbol: + ... + + def add_declaration(self, declaration: ASTDeclaration, docname: str, line: int) -> Symbol: + ... + + def find_identifier(self, identOrOp: ASTIdentifier | ASTOperator, matchSelf: bool, recurseInAnon: bool, searchInSiblings: bool) -> Symbol: + ... + + def direct_lookup(self, key: LookupKey) -> Symbol: + ... + + def find_name(self, nestedName: ASTNestedName, templateDecls: list[Any], typ: str, templateShorthand: bool, matchSelf: bool, recurseInAnon: bool, searchInSiblings: bool) -> tuple[list[Symbol], str]: + class QualifiedSymbolIsTemplateParam(Exception): + ... + + + + def find_declaration(self, declaration: ASTDeclaration, typ: str, templateShorthand: bool, matchSelf: bool, recurseInAnon: bool) -> Symbol: + ... + + def to_string(self, indent: int) -> str: + ... + + def dump(self, indent: int) -> str: + ... + + + +class DefinitionParser(BaseParser): + @property + def language(self) -> str: + ... + + @property + def id_attributes(self): # -> Any: + ... + + @property + def paren_attributes(self): # -> Any: + ... + + def parse_declaration(self, objectType: str, directiveType: str) -> ASTDeclaration: + ... + + def parse_namespace_object(self) -> ASTNamespace: + ... + + def parse_xref_object(self) -> tuple[ASTNamespace | ASTDeclaration, bool]: + ... + + def parse_expression(self) -> ASTExpression | ASTType: + ... + + + +class CPPObject(ObjectDescription[ASTDeclaration]): + """Description of a C++ language object.""" + doc_field_types: list[Field] = ... + option_spec: OptionSpec = ... + def add_target_and_index(self, ast: ASTDeclaration, sig: str, signode: TextElement) -> None: + ... + + @property + def object_type(self) -> str: + ... + + @property + def display_object_type(self) -> str: + ... + + def get_index_text(self, name: str) -> str: + ... + + def parse_definition(self, parser: DefinitionParser) -> ASTDeclaration: + ... + + def describe_signature(self, signode: desc_signature, ast: ASTDeclaration, options: dict) -> None: + ... + + def run(self) -> list[Node]: + ... + + def handle_signature(self, sig: str, signode: desc_signature) -> ASTDeclaration: + ... + + def before_content(self) -> None: + ... + + def after_content(self) -> None: + ... + + + +class CPPTypeObject(CPPObject): + object_type = ... + + +class CPPConceptObject(CPPObject): + object_type = ... + + +class CPPMemberObject(CPPObject): + object_type = ... + + +class CPPFunctionObject(CPPObject): + object_type = ... + doc_field_types = ... + + +class CPPClassObject(CPPObject): + object_type = ... + @property + def display_object_type(self) -> str: + ... + + + +class CPPUnionObject(CPPObject): + object_type = ... + + +class CPPEnumObject(CPPObject): + object_type = ... + + +class CPPEnumeratorObject(CPPObject): + object_type = ... + + +class CPPNamespaceObject(SphinxDirective): + """ + This directive is just to tell Sphinx that we're documenting stuff in + namespace foo. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class CPPNamespacePushObject(SphinxDirective): + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class CPPNamespacePopObject(SphinxDirective): + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class AliasNode(nodes.Element): + def __init__(self, sig: str, aliasOptions: dict, env: BuildEnvironment | None = ..., parentKey: LookupKey | None = ...) -> None: + ... + + def copy(self) -> AliasNode: + ... + + + +class AliasTransform(SphinxTransform): + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class CPPAliasObject(ObjectDescription): + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + """ + On purpose this doesn't call the ObjectDescription version, but is based on it. + Each alias signature may expand into multiple real signatures (an overload set). + The code is therefore based on the ObjectDescription version. + """ + ... + + + +class CPPXRefRole(XRefRole): + def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str) -> tuple[str, str]: + ... + + + +class CPPExprRole(SphinxRole): + def __init__(self, asCode: bool) -> None: + ... + + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + + +class CPPDomain(Domain): + """C++ language domain. + + There are two 'object type' attributes being used:: + + - Each object created from directives gets an assigned .objtype from ObjectDescription.run. + This is simply the directive name. + - Each declaration (see the distinction in the directives dict below) has a nested .ast of + type ASTDeclaration. That object has .objectType which corresponds to the keys in the + object_types dict below. They are the core different types of declarations in C++ that + one can document. + """ + name = ... + label = ... + object_types = ... + directives = ... + roles = ... + initial_data = ... + def clear_doc(self, docname: str) -> None: + ... + + def process_doc(self, env: BuildEnvironment, docname: str, document: nodes.document) -> None: + ... + + def process_field_xref(self, pnode: pending_xref) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict) -> None: + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + ... + + def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: + ... + + def get_full_qualified_name(self, node: Element) -> str: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/index.pyi b/typings/sphinx/domains/index.pyi new file mode 100644 index 0000000..e9cdd0c --- /dev/null +++ b/typings/sphinx/domains/index.pyi @@ -0,0 +1,60 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from sphinx.domains import Domain +from sphinx.util.docutils import ReferenceRole, SphinxDirective +from collections.abc import Iterable +from docutils.nodes import Node, system_message +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec + +"""The index domain.""" +if TYPE_CHECKING: + ... +logger = ... +class IndexDomain(Domain): + """Mathematics domain.""" + name = ... + label = ... + @property + def entries(self) -> dict[str, list[tuple[str, str, str, str, str | None]]]: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: Iterable[str], otherdata: dict[str, Any]) -> None: + ... + + def process_doc(self, env: BuildEnvironment, docname: str, document: Node) -> None: + """Process a document after it is read by the environment.""" + ... + + + +class IndexDirective(SphinxDirective): + """ + Directive to add entries to the index. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class IndexRole(ReferenceRole): + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/javascript.pyi b/typings/sphinx/domains/javascript.pyi new file mode 100644 index 0000000..fc218f2 --- /dev/null +++ b/typings/sphinx/domains/javascript.pyi @@ -0,0 +1,183 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils.parsers.rst import directives +from sphinx.directives import ObjectDescription +from sphinx.domains import Domain +from sphinx.roles import XRefRole +from sphinx.util.docutils import SphinxDirective +from collections.abc import Iterator +from docutils.nodes import Element, Node +from sphinx.addnodes import desc_signature, pending_xref +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec + +"""The JavaScript domain.""" +if TYPE_CHECKING: + ... +logger = ... +class JSObject(ObjectDescription[tuple[str, str]]): + """ + Description of a JavaScript object. + """ + has_arguments = ... + allow_nesting = ... + option_spec: OptionSpec = ... + def get_display_prefix(self) -> list[Node]: + ... + + def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]: + """Breaks down construct signatures + + Parses out prefix and argument list from construct definition. The + namespace and class will be determined by the nesting of domain + directives. + """ + ... + + def add_target_and_index(self, name_obj: tuple[str, str], sig: str, signode: desc_signature) -> None: + ... + + def get_index_text(self, objectname: str, name_obj: tuple[str, str]) -> str: + ... + + def before_content(self) -> None: + """Handle object nesting before content + + :py:class:`JSObject` represents JavaScript language constructs. For + constructs that are nestable, this method will build up a stack of the + nesting hierarchy so that it can be later de-nested correctly, in + :py:meth:`after_content`. + + For constructs that aren't nestable, the stack is bypassed, and instead + only the most recent object is tracked. This object prefix name will be + removed with :py:meth:`after_content`. + + The following keys are used in ``self.env.ref_context``: + + js:objects + Stores the object prefix history. With each nested element, we + add the object prefix to this list. When we exit that object's + nesting level, :py:meth:`after_content` is triggered and the + prefix is removed from the end of the list. + + js:object + Current object prefix. This should generally reflect the last + element in the prefix history + """ + ... + + def after_content(self) -> None: + """Handle object de-nesting after content + + If this class is a nestable object, removing the last nested class prefix + ends further nesting in the object. + + If this class is not a nestable object, the list of classes should not + be altered as we didn't affect the nesting levels in + :py:meth:`before_content`. + """ + ... + + + +class JSCallable(JSObject): + """Description of a JavaScript function, method or constructor.""" + has_arguments = ... + doc_field_types = ... + + +class JSConstructor(JSCallable): + """Like a callable but with a different prefix.""" + allow_nesting = ... + def get_display_prefix(self) -> list[Node]: + ... + + + +class JSModule(SphinxDirective): + """ + Directive to mark description of a new JavaScript module. + + This directive specifies the module name that will be used by objects that + follow this directive. + + Options + ------- + + no-index + If the ``:no-index:`` option is specified, no linkable elements will be + created, and the module won't be added to the global module index. This + is useful for splitting up the module definition across multiple + sections or files. + + :param mod_name: Module name + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class JSXRefRole(XRefRole): + def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str) -> tuple[str, str]: + ... + + + +class JavaScriptDomain(Domain): + """JavaScript language domain.""" + name = ... + label = ... + object_types = ... + directives = ... + roles = ... + initial_data: dict[str, dict[str, tuple[str, str]]] = ... + @property + def objects(self) -> dict[str, tuple[str, str, str]]: + ... + + def note_object(self, fullname: str, objtype: str, node_id: str, location: Any = ...) -> None: + ... + + @property + def modules(self) -> dict[str, tuple[str, str]]: + ... + + def note_module(self, modname: str, node_id: str) -> None: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict[str, Any]) -> None: + ... + + def find_obj(self, env: BuildEnvironment, mod_name: str, prefix: str, name: str, typ: str | None, searchorder: int = ...) -> tuple[str | None, tuple[str, str, str] | None]: + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + ... + + def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: + ... + + def get_full_qualified_name(self, node: Element) -> str | None: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/math.pyi b/typings/sphinx/domains/math.pyi new file mode 100644 index 0000000..dc7c6fc --- /dev/null +++ b/typings/sphinx/domains/math.pyi @@ -0,0 +1,69 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils import nodes +from docutils.nodes import Element, Node, system_message +from sphinx.domains import Domain +from sphinx.roles import XRefRole +from collections.abc import Iterable +from sphinx.addnodes import pending_xref +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment + +"""The math domain.""" +if TYPE_CHECKING: + ... +logger = ... +class MathReferenceRole(XRefRole): + def result_nodes(self, document: nodes.document, env: BuildEnvironment, node: Element, is_ref: bool) -> tuple[list[Node], list[system_message]]: + ... + + + +class MathDomain(Domain): + """Mathematics domain.""" + name = ... + label = ... + initial_data: dict[str, Any] = ... + dangling_warnings = ... + enumerable_nodes = ... + roles = ... + @property + def equations(self) -> dict[str, tuple[str, int]]: + ... + + def note_equation(self, docname: str, labelid: str, location: Any = ...) -> None: + ... + + def get_equation_number_for(self, labelid: str) -> int | None: + ... + + def process_doc(self, env: BuildEnvironment, docname: str, document: nodes.document) -> None: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: Iterable[str], otherdata: dict[str, Any]) -> None: + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + ... + + def get_objects(self) -> Iterable[tuple[str, str, str, str, str, int]]: + ... + + def has_equations(self, docname: str | None = ...) -> bool: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/python.pyi b/typings/sphinx/domains/python.pyi new file mode 100644 index 0000000..7cb8c64 --- /dev/null +++ b/typings/sphinx/domains/python.pyi @@ -0,0 +1,393 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, NamedTuple, TYPE_CHECKING +from docutils import nodes +from docutils.parsers.rst import directives +from sphinx import addnodes +from sphinx.addnodes import desc_signature, pending_xref +from sphinx.directives import ObjectDescription +from sphinx.domains import Domain, Index, IndexEntry, ObjType +from sphinx.pycode.parser import Token, TokenProcessor +from sphinx.roles import XRefRole +from sphinx.util.docfields import Field, GroupedField, TypedField +from sphinx.util.docutils import SphinxDirective +from collections.abc import Iterable, Iterator +from docutils.nodes import Element, Node +from docutils.parsers.rst.states import Inliner +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec, TextlikeNode + +"""The Python domain.""" +if TYPE_CHECKING: + ... +logger = ... +py_sig_re = ... +pairindextypes = ... +class ObjectEntry(NamedTuple): + docname: str + node_id: str + objtype: str + aliased: bool + ... + + +class ModuleEntry(NamedTuple): + docname: str + node_id: str + synopsis: str + platform: str + deprecated: bool + ... + + +def parse_reftarget(reftarget: str, suppress_prefix: bool = ...) -> tuple[str, str, str, bool]: + """Parse a type string and return (reftype, reftarget, title, refspecific flag)""" + ... + +def type_to_xref(target: str, env: BuildEnvironment, *, suppress_prefix: bool = ...) -> addnodes.pending_xref: + """Convert a type string to a cross reference node.""" + ... + +class _TypeParameterListParser(TokenProcessor): + def __init__(self, sig: str) -> None: + ... + + def fetch_type_param_spec(self) -> list[Token]: + ... + + def parse(self) -> None: + ... + + + +class PyXrefMixin: + def make_xref(self, rolename: str, domain: str, target: str, innernode: type[TextlikeNode] = ..., contnode: Node | None = ..., env: BuildEnvironment | None = ..., inliner: Inliner | None = ..., location: Node | None = ...) -> Node: + ... + + def make_xrefs(self, rolename: str, domain: str, target: str, innernode: type[TextlikeNode] = ..., contnode: Node | None = ..., env: BuildEnvironment | None = ..., inliner: Inliner | None = ..., location: Node | None = ...) -> list[Node]: + ... + + + +class PyField(PyXrefMixin, Field): + ... + + +class PyGroupedField(PyXrefMixin, GroupedField): + ... + + +class PyTypedField(PyXrefMixin, TypedField): + ... + + +class PyObject(ObjectDescription[tuple[str, str]]): + """ + Description of a general Python object. + + :cvar allow_nesting: Class is an object that allows for nested namespaces + :vartype allow_nesting: bool + """ + option_spec: OptionSpec = ... + doc_field_types = ... + allow_nesting = ... + def get_signature_prefix(self, sig: str) -> list[nodes.Node]: + """May return a prefix to put before the object name in the + signature. + """ + ... + + def needs_arglist(self) -> bool: + """May return true if an empty argument list is to be generated even if + the document contains none. + """ + ... + + def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]: + """Transform a Python signature into RST nodes. + + Return (fully qualified name of the thing, classname if any). + + If inside a class, the current class name is handled intelligently: + * it is stripped from the displayed name if present + * it is added to the full name (return value) if not present + """ + ... + + def get_index_text(self, modname: str, name: tuple[str, str]) -> str: + """Return the text for the index entry of the object.""" + ... + + def add_target_and_index(self, name_cls: tuple[str, str], sig: str, signode: desc_signature) -> None: + ... + + def before_content(self) -> None: + """Handle object nesting before content + + :py:class:`PyObject` represents Python language constructs. For + constructs that are nestable, such as a Python classes, this method will + build up a stack of the nesting hierarchy so that it can be later + de-nested correctly, in :py:meth:`after_content`. + + For constructs that aren't nestable, the stack is bypassed, and instead + only the most recent object is tracked. This object prefix name will be + removed with :py:meth:`after_content`. + """ + ... + + def after_content(self) -> None: + """Handle object de-nesting after content + + If this class is a nestable object, removing the last nested class prefix + ends further nesting in the object. + + If this class is not a nestable object, the list of classes should not + be altered as we didn't affect the nesting levels in + :py:meth:`before_content`. + """ + ... + + + +class PyFunction(PyObject): + """Description of a function.""" + option_spec: OptionSpec = ... + def get_signature_prefix(self, sig: str) -> list[nodes.Node]: + ... + + def needs_arglist(self) -> bool: + ... + + def add_target_and_index(self, name_cls: tuple[str, str], sig: str, signode: desc_signature) -> None: + ... + + def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str: + ... + + + +class PyDecoratorFunction(PyFunction): + """Description of a decorator.""" + def run(self) -> list[Node]: + ... + + def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]: + ... + + def needs_arglist(self) -> bool: + ... + + + +class PyVariable(PyObject): + """Description of a variable.""" + option_spec: OptionSpec = ... + def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]: + ... + + def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str: + ... + + + +class PyClasslike(PyObject): + """ + Description of a class-like object (classes, interfaces, exceptions). + """ + option_spec: OptionSpec = ... + allow_nesting = ... + def get_signature_prefix(self, sig: str) -> list[nodes.Node]: + ... + + def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str: + ... + + + +class PyMethod(PyObject): + """Description of a method.""" + option_spec: OptionSpec = ... + def needs_arglist(self) -> bool: + ... + + def get_signature_prefix(self, sig: str) -> list[nodes.Node]: + ... + + def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str: + ... + + + +class PyClassMethod(PyMethod): + """Description of a classmethod.""" + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class PyStaticMethod(PyMethod): + """Description of a staticmethod.""" + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class PyDecoratorMethod(PyMethod): + """Description of a decoratormethod.""" + def run(self) -> list[Node]: + ... + + def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]: + ... + + def needs_arglist(self) -> bool: + ... + + + +class PyAttribute(PyObject): + """Description of an attribute.""" + option_spec: OptionSpec = ... + def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]: + ... + + def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str: + ... + + + +class PyProperty(PyObject): + """Description of an attribute.""" + option_spec = ... + def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]: + ... + + def get_signature_prefix(self, sig: str) -> list[nodes.Node]: + ... + + def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str: + ... + + + +class PyModule(SphinxDirective): + """ + Directive to mark description of a new module. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class PyCurrentModule(SphinxDirective): + """ + This directive is just to tell Sphinx that we're documenting + stuff in module foo, but links to module foo won't lead here. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class PyXRefRole(XRefRole): + def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str) -> tuple[str, str]: + ... + + + +def filter_meta_fields(app: Sphinx, domain: str, objtype: str, content: Element) -> None: + """Filter ``:meta:`` field from its docstring.""" + ... + +class PythonModuleIndex(Index): + """ + Index subclass to provide the Python module index. + """ + name = ... + localname = ... + shortname = ... + def generate(self, docnames: Iterable[str] | None = ...) -> tuple[list[tuple[str, list[IndexEntry]]], bool]: + ... + + + +class PythonDomain(Domain): + """Python language domain.""" + name = ... + label = ... + object_types: dict[str, ObjType] = ... + directives = ... + roles = ... + initial_data: dict[str, dict[str, tuple[Any]]] = ... + indices = ... + @property + def objects(self) -> dict[str, ObjectEntry]: + ... + + def note_object(self, name: str, objtype: str, node_id: str, aliased: bool = ..., location: Any = ...) -> None: + """Note a python object for cross reference. + + .. versionadded:: 2.1 + """ + ... + + @property + def modules(self) -> dict[str, ModuleEntry]: + ... + + def note_module(self, name: str, node_id: str, synopsis: str, platform: str, deprecated: bool) -> None: + """Note a python module for cross reference. + + .. versionadded:: 2.1 + """ + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict[str, Any]) -> None: + ... + + def find_obj(self, env: BuildEnvironment, modname: str, classname: str, name: str, type: str | None, searchmode: int = ...) -> list[tuple[str, ObjectEntry]]: + """Find a Python object for "name", perhaps using the given module + and/or classname. Returns a list of (name, object entry) tuples. + """ + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, type: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + ... + + def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: + ... + + def get_full_qualified_name(self, node: Element) -> str | None: + ... + + + +def builtin_resolver(app: Sphinx, env: BuildEnvironment, node: pending_xref, contnode: Element) -> Element | None: + """Do not emit nitpicky warnings for built-in types.""" + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/rst.pyi b/typings/sphinx/domains/rst.pyi new file mode 100644 index 0000000..6ca43f1 --- /dev/null +++ b/typings/sphinx/domains/rst.pyi @@ -0,0 +1,124 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils.parsers.rst import directives +from sphinx.directives import ObjectDescription +from sphinx.domains import Domain +from collections.abc import Iterator +from docutils.nodes import Element +from sphinx.addnodes import desc_signature, pending_xref +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec + +"""The reStructuredText domain.""" +if TYPE_CHECKING: + ... +logger = ... +dir_sig_re = ... +class ReSTMarkup(ObjectDescription[str]): + """ + Description of generic reST markup. + """ + option_spec: OptionSpec = ... + def add_target_and_index(self, name: str, sig: str, signode: desc_signature) -> None: + ... + + def get_index_text(self, objectname: str, name: str) -> str: + ... + + + +def parse_directive(d: str) -> tuple[str, str]: + """Parse a directive signature. + + Returns (directive, arguments) string tuple. If no arguments are given, + returns (directive, ''). + """ + ... + +class ReSTDirective(ReSTMarkup): + """ + Description of a reST directive. + """ + def handle_signature(self, sig: str, signode: desc_signature) -> str: + ... + + def get_index_text(self, objectname: str, name: str) -> str: + ... + + def before_content(self) -> None: + ... + + def after_content(self) -> None: + ... + + + +class ReSTDirectiveOption(ReSTMarkup): + """ + Description of an option for reST directive. + """ + option_spec: OptionSpec = ... + def handle_signature(self, sig: str, signode: desc_signature) -> str: + ... + + def add_target_and_index(self, name: str, sig: str, signode: desc_signature) -> None: + ... + + @property + def current_directive(self) -> str: + ... + + + +class ReSTRole(ReSTMarkup): + """ + Description of a reST role. + """ + def handle_signature(self, sig: str, signode: desc_signature) -> str: + ... + + def get_index_text(self, objectname: str, name: str) -> str: + ... + + + +class ReSTDomain(Domain): + """ReStructuredText domain.""" + name = ... + label = ... + object_types = ... + directives = ... + roles = ... + initial_data: dict[str, dict[tuple[str, str], str]] = ... + @property + def objects(self) -> dict[tuple[str, str], tuple[str, str]]: + ... + + def note_object(self, objtype: str, name: str, node_id: str, location: Any = ...) -> None: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict[str, Any]) -> None: + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + ... + + def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/domains/std.pyi b/typings/sphinx/domains/std.pyi new file mode 100644 index 0000000..9175637 --- /dev/null +++ b/typings/sphinx/domains/std.pyi @@ -0,0 +1,254 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, Final, TYPE_CHECKING +from docutils import nodes +from docutils.nodes import Element, Node, system_message +from docutils.parsers.rst import Directive, directives +from sphinx.addnodes import desc_signature, pending_xref +from sphinx.directives import ObjectDescription +from sphinx.domains import Domain, ObjType, TitleGetter +from sphinx.roles import XRefRole +from sphinx.util.docutils import SphinxDirective +from collections.abc import Iterable, Iterator +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec, RoleFunction + +"""The standard domain.""" +if TYPE_CHECKING: + ... +logger = ... +option_desc_re = ... +token_re = ... +samp_role = ... +class GenericObject(ObjectDescription[str]): + """ + A generic x-ref directive registered with Sphinx.add_object_type(). + """ + indextemplate: str = ... + parse_node: Callable[[BuildEnvironment, str, desc_signature], str] | None = ... + def handle_signature(self, sig: str, signode: desc_signature) -> str: + ... + + def add_target_and_index(self, name: str, sig: str, signode: desc_signature) -> None: + ... + + + +class EnvVar(GenericObject): + indextemplate = ... + + +class EnvVarXRefRole(XRefRole): + """ + Cross-referencing role for environment variables (adds an index entry). + """ + def result_nodes(self, document: nodes.document, env: BuildEnvironment, node: Element, is_ref: bool) -> tuple[list[Node], list[system_message]]: + ... + + + +class Target(SphinxDirective): + """ + Generic target for user-defined cross-reference types. + """ + indextemplate = ... + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class Cmdoption(ObjectDescription[str]): + """ + Description of a command-line option (.. option). + """ + def handle_signature(self, sig: str, signode: desc_signature) -> str: + """Transform an option description into RST nodes.""" + ... + + def add_target_and_index(self, firstname: str, sig: str, signode: desc_signature) -> None: + ... + + + +class Program(SphinxDirective): + """ + Directive to name the program for which options are documented. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class OptionXRefRole(XRefRole): + def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str) -> tuple[str, str]: + ... + + + +def split_term_classifiers(line: str) -> list[str | None]: + ... + +def make_glossary_term(env: BuildEnvironment, textnodes: Iterable[Node], index_key: str, source: str, lineno: int, node_id: str | None, document: nodes.document) -> nodes.term: + ... + +class Glossary(SphinxDirective): + """ + Directive to create a glossary with cross-reference targets for :term: + roles. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +def token_xrefs(text: str, productionGroup: str = ...) -> list[Node]: + ... + +class ProductionList(SphinxDirective): + """ + Directive to list grammar productions. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class TokenXRefRole(XRefRole): + def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str) -> tuple[str, str]: + ... + + + +class StandardDomain(Domain): + """ + Domain for all objects that don't fit into another domain or are added + via the application interface. + """ + name = ... + label = ... + object_types: dict[str, ObjType] = ... + directives: dict[str, type[Directive]] = ... + roles: dict[str, RoleFunction | XRefRole] = ... + initial_data: Final = ... + _virtual_doc_names: dict[str, tuple[str, str]] = ... + dangling_warnings = ... + enumerable_nodes: dict[type[Node], tuple[str, TitleGetter | None]] = ... + def __init__(self, env: BuildEnvironment) -> None: + ... + + def note_hyperlink_target(self, name: str, docname: str, node_id: str, title: str = ...) -> None: + """Add a hyperlink target for cross reference. + + .. warning:: + + This is only for internal use. Please don't use this from your extension. + ``document.note_explicit_target()`` or ``note_implicit_target()`` are recommended to + add a hyperlink target to the document. + + This only adds a hyperlink target to the StandardDomain. And this does not add a + node_id to node. Therefore, it is very fragile to calling this without + understanding hyperlink target framework in both docutils and Sphinx. + + .. versionadded:: 3.0 + """ + ... + + @property + def objects(self) -> dict[tuple[str, str], tuple[str, str]]: + ... + + def note_object(self, objtype: str, name: str, labelid: str, location: Any = ...) -> None: + """Note a generic object for cross reference. + + .. versionadded:: 3.0 + """ + ... + + @property + def progoptions(self) -> dict[tuple[str | None, str], tuple[str, str]]: + ... + + @property + def labels(self) -> dict[str, tuple[str, str, str]]: + ... + + @property + def anonlabels(self) -> dict[str, tuple[str, str]]: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict[str, Any]) -> None: + ... + + def process_doc(self, env: BuildEnvironment, docname: str, document: nodes.document) -> None: + ... + + def add_program_option(self, program: str | None, name: str, docname: str, labelid: str) -> None: + ... + + def build_reference_node(self, fromdocname: str, builder: Builder, docname: str, labelid: str, sectname: str, rolename: str, **options: Any) -> Element: + ... + + def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) -> Element | None: + ... + + def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) -> list[tuple[str, Element]]: + ... + + def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: + ... + + def get_type_name(self, type: ObjType, primary: bool = ...) -> str: + ... + + def is_enumerable_node(self, node: Node) -> bool: + ... + + def get_numfig_title(self, node: Node) -> str | None: + """Get the title of enumerable nodes to refer them using its title""" + ... + + def get_enumerable_node_type(self, node: Node) -> str | None: + """Get type of enumerable nodes.""" + ... + + def get_fignumber(self, env: BuildEnvironment, builder: Builder, figtype: str, docname: str, target_node: Element) -> tuple[int, ...] | None: + ... + + def get_full_qualified_name(self, node: Element) -> str | None: + ... + + + +def warn_missing_reference(app: Sphinx, domain: Domain, node: pending_xref) -> bool | None: + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/environment/__init__.pyi b/typings/sphinx/environment/__init__.pyi new file mode 100644 index 0000000..4e2b09d --- /dev/null +++ b/typings/sphinx/environment/__init__.pyi @@ -0,0 +1,310 @@ +""" +This type stub file was generated by pyright. +""" + +import functools +import os +import pickle +import time +from __future__ import annotations +from collections import defaultdict +from copy import copy +from os import path +from typing import Any, Callable, Literal, TYPE_CHECKING +from sphinx import addnodes +from sphinx.environment.adapters import toctree as toctree_adapters +from sphinx.errors import BuildEnvironmentError, DocumentError, ExtensionError, SphinxError +from sphinx.locale import __ +from sphinx.transforms import SphinxTransformer +from sphinx.util import DownloadFiles, FilenameUniqDict, logging +from sphinx.util.docutils import LoggingReporter +from sphinx.util.i18n import CatalogRepository, docname_to_domain +from sphinx.util.nodes import is_translatable +from sphinx.util.osutil import canon_path, os_path +from collections.abc import Generator, Iterator, MutableMapping +from pathlib import Path +from docutils import nodes +from docutils.nodes import Node +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.config import Config +from sphinx.domains import Domain +from sphinx.events import EventManager +from sphinx.project import Project +from typing_extensions import overload +from sphinx.domains.c import CDomain +from sphinx.domains.changeset import ChangeSetDomain +from sphinx.domains.citation import CitationDomain +from sphinx.domains.cpp import CPPDomain +from sphinx.domains.index import IndexDomain +from sphinx.domains.javascript import JavaScriptDomain +from sphinx.domains.math import MathDomain +from sphinx.domains.python import PythonDomain +from sphinx.domains.rst import ReSTDomain +from sphinx.domains.std import StandardDomain +from sphinx.ext.duration import DurationDomain +from sphinx.ext.todo import TodoDomain + +"""Global creation environment.""" +if TYPE_CHECKING: + ... +logger = ... +default_settings: dict[str, Any] = ... +ENV_VERSION = ... +CONFIG_UNSET = ... +CONFIG_OK = ... +CONFIG_NEW = ... +CONFIG_CHANGED = ... +CONFIG_EXTENSIONS_CHANGED = ... +CONFIG_CHANGED_REASON = ... +versioning_conditions: dict[str, bool | Callable] = ... +if TYPE_CHECKING: + class _DomainsType(MutableMapping[str, Domain]): + @overload + def __getitem__(self, key: Literal["c"]) -> CDomain: + ... + + @overload + def __getitem__(self, key: Literal["cpp"]) -> CPPDomain: + ... + + @overload + def __getitem__(self, key: Literal["changeset"]) -> ChangeSetDomain: + ... + + @overload + def __getitem__(self, key: Literal["citation"]) -> CitationDomain: + ... + + @overload + def __getitem__(self, key: Literal["index"]) -> IndexDomain: + ... + + @overload + def __getitem__(self, key: Literal["js"]) -> JavaScriptDomain: + ... + + @overload + def __getitem__(self, key: Literal["math"]) -> MathDomain: + ... + + @overload + def __getitem__(self, key: Literal["py"]) -> PythonDomain: + ... + + @overload + def __getitem__(self, key: Literal["rst"]) -> ReSTDomain: + ... + + @overload + def __getitem__(self, key: Literal["std"]) -> StandardDomain: + ... + + @overload + def __getitem__(self, key: Literal["duration"]) -> DurationDomain: + ... + + @overload + def __getitem__(self, key: Literal["todo"]) -> TodoDomain: + ... + + @overload + def __getitem__(self, key: str) -> Domain: + ... + + def __getitem__(self, key): + ... + + def __setitem__(self, key, value): + ... + + def __delitem__(self, key): + ... + + def __iter__(self): + ... + + def __len__(self): + ... + + + +else: + ... +class BuildEnvironment: + """ + The environment in which the ReST files are translated. + Stores an inventory of cross-file targets and provides doctree + transformations to resolve links to them. + """ + domains: _DomainsType + def __init__(self, app: Sphinx) -> None: + ... + + def __getstate__(self) -> dict: + """Obtains serializable data for pickling.""" + ... + + def __setstate__(self, state: dict) -> None: + ... + + def setup(self, app: Sphinx) -> None: + """Set up BuildEnvironment object.""" + ... + + def set_versioning_method(self, method: str | Callable, compare: bool) -> None: + """This sets the doctree versioning method for this environment. + + Versioning methods are a builder property; only builders with the same + versioning method can share the same doctree directory. Therefore, we + raise an exception if the user tries to use an environment with an + incompatible versioning method. + """ + ... + + def clear_doc(self, docname: str) -> None: + """Remove all traces of a source file in the inventory.""" + ... + + def merge_info_from(self, docnames: list[str], other: BuildEnvironment, app: Sphinx) -> None: + """Merge global information gathered about *docnames* while reading them + from the *other* environment. + + This possibly comes from a parallel build process. + """ + ... + + def path2doc(self, filename: str | os.PathLike[str]) -> str | None: + """Return the docname for the filename if the file is document. + + *filename* should be absolute or relative to the source directory. + """ + ... + + def doc2path(self, docname: str, base: bool = ...) -> str: + """Return the filename for the document name. + + If *base* is True, return absolute path under self.srcdir. + If *base* is False, return relative path to self.srcdir. + """ + ... + + def relfn2path(self, filename: str, docname: str | None = ...) -> tuple[str, str]: + """Return paths to a file referenced from a document, relative to + documentation root and absolute. + + In the input "filename", absolute filenames are taken as relative to the + source dir, while relative filenames are relative to the dir of the + containing document. + """ + ... + + @property + def found_docs(self) -> set[str]: + """contains all existing docnames.""" + ... + + def find_files(self, config: Config, builder: Builder) -> None: + """Find all source files in the source dir and put them in + self.found_docs. + """ + ... + + def get_outdated_files(self, config_changed: bool) -> tuple[set[str], set[str], set[str]]: + """Return (added, changed, removed) sets.""" + ... + + def check_dependents(self, app: Sphinx, already: set[str]) -> Generator[str, None, None]: + ... + + def prepare_settings(self, docname: str) -> None: + """Prepare to set up environment for reading.""" + ... + + @property + def docname(self) -> str: + """Returns the docname of the document currently being parsed.""" + ... + + def new_serialno(self, category: str = ...) -> int: + """Return a serial number, e.g. for index entry targets. + + The number is guaranteed to be unique in the current document. + """ + ... + + def note_dependency(self, filename: str) -> None: + """Add *filename* as a dependency of the current document. + + This means that the document will be rebuilt if this file changes. + + *filename* should be absolute or relative to the source directory. + """ + ... + + def note_included(self, filename: str) -> None: + """Add *filename* as a included from other document. + + This means the document is not orphaned. + + *filename* should be absolute or relative to the source directory. + """ + ... + + def note_reread(self) -> None: + """Add the current document to the list of documents that will + automatically be re-read at the next build. + """ + ... + + def get_domain(self, domainname: str) -> Domain: + """Return the domain instance with the specified name. + + Raises an ExtensionError if the domain is not registered. + """ + ... + + def get_doctree(self, docname: str) -> nodes.document: + """Read the doctree for a file from the pickle and return it.""" + ... + + @functools.cached_property + def master_doctree(self) -> nodes.document: + ... + + def get_and_resolve_doctree(self, docname: str, builder: Builder, doctree: nodes.document | None = ..., prune_toctrees: bool = ..., includehidden: bool = ...) -> nodes.document: + """Read the doctree from the pickle, resolve cross-references and + toctrees and return it. + """ + ... + + def resolve_toctree(self, docname: str, builder: Builder, toctree: addnodes.toctree, prune: bool = ..., maxdepth: int = ..., titles_only: bool = ..., collapse: bool = ..., includehidden: bool = ...) -> Node | None: + """Resolve a *toctree* node into individual bullet lists with titles + as items, returning None (if no containing titles are found) or + a new node. + + If *prune* is True, the tree is pruned to *maxdepth*, or if that is 0, + to the value of the *maxdepth* option on the *toctree* node. + If *titles_only* is True, only toplevel document titles will be in the + resulting tree. + If *collapse* is True, all branches not containing docname will + be collapsed. + """ + ... + + def resolve_references(self, doctree: nodes.document, fromdocname: str, builder: Builder) -> None: + ... + + def apply_post_transforms(self, doctree: nodes.document, docname: str) -> None: + """Apply all post-transforms.""" + ... + + def collect_relations(self) -> dict[str, list[str | None]]: + ... + + def check_consistency(self) -> None: + """Do consistency checks.""" + ... + + + diff --git a/typings/sphinx/environment/adapters/__init__.pyi b/typings/sphinx/environment/adapters/__init__.pyi new file mode 100644 index 0000000..0e6251b --- /dev/null +++ b/typings/sphinx/environment/adapters/__init__.pyi @@ -0,0 +1,5 @@ +""" +This type stub file was generated by pyright. +""" + +"""Sphinx environment adapters""" diff --git a/typings/sphinx/environment/adapters/asset.pyi b/typings/sphinx/environment/adapters/asset.pyi new file mode 100644 index 0000000..6738cf6 --- /dev/null +++ b/typings/sphinx/environment/adapters/asset.pyi @@ -0,0 +1,17 @@ +""" +This type stub file was generated by pyright. +""" + +from sphinx.environment import BuildEnvironment + +"""Assets adapter for sphinx.environment.""" +class ImageAdapter: + def __init__(self, env: BuildEnvironment) -> None: + ... + + def get_original_image_uri(self, name: str) -> str: + """Get the original image URI.""" + ... + + + diff --git a/typings/sphinx/environment/adapters/indexentries.pyi b/typings/sphinx/environment/adapters/indexentries.pyi new file mode 100644 index 0000000..5cf2f21 --- /dev/null +++ b/typings/sphinx/environment/adapters/indexentries.pyi @@ -0,0 +1,23 @@ +""" +This type stub file was generated by pyright. +""" + +import re +from typing import Any, TYPE_CHECKING +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment + +"""Index entries adapters for sphinx.environment.""" +if TYPE_CHECKING: + ... +logger = ... +class IndexEntries: + def __init__(self, env: BuildEnvironment) -> None: + ... + + def create_index(self, builder: Builder, group_entries: bool = ..., _fixre: re.Pattern = ...) -> list[tuple[str, list[tuple[str, Any]]]]: + """Create the real index from the collected index entries.""" + ... + + + diff --git a/typings/sphinx/environment/adapters/toctree.pyi b/typings/sphinx/environment/adapters/toctree.pyi new file mode 100644 index 0000000..fca0a0a --- /dev/null +++ b/typings/sphinx/environment/adapters/toctree.pyi @@ -0,0 +1,59 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING, TypeVar +from docutils.nodes import Element, Node +from sphinx import addnodes +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.tags import Tags + +"""Toctree adapter for sphinx.environment.""" +if TYPE_CHECKING: + ... +logger = ... +def note_toctree(env: BuildEnvironment, docname: str, toctreenode: addnodes.toctree) -> None: + """Note a TOC tree directive in a document and gather information about + file relations from it. + """ + ... + +def document_toc(env: BuildEnvironment, docname: str, tags: Tags) -> Node: + """Get the (local) table of contents for a document. + + Note that this is only the sections within the document. + For a ToC tree that shows the document's place in the + ToC structure, use `get_toctree_for`. + """ + ... + +def global_toctree_for_doc(env: BuildEnvironment, docname: str, builder: Builder, collapse: bool = ..., includehidden: bool = ..., maxdepth: int = ..., titles_only: bool = ...) -> Element | None: + """Get the global ToC tree at a given document. + + This gives the global ToC, with all ancestors and their siblings. + """ + ... + +ET = TypeVar('ET', bound=Element) +class TocTree: + def __init__(self, env: BuildEnvironment) -> None: + ... + + def note(self, docname: str, toctreenode: addnodes.toctree) -> None: + ... + + def resolve(self, docname: str, builder: Builder, toctree: addnodes.toctree, prune: bool = ..., maxdepth: int = ..., titles_only: bool = ..., collapse: bool = ..., includehidden: bool = ...) -> Element | None: + ... + + def get_toctree_ancestors(self, docname: str) -> list[str]: + ... + + def get_toc_for(self, docname: str, builder: Builder) -> Node: + ... + + def get_toctree_for(self, docname: str, builder: Builder, collapse: bool, **kwargs: Any) -> Element | None: + ... + + + diff --git a/typings/sphinx/environment/collectors/__init__.pyi b/typings/sphinx/environment/collectors/__init__.pyi new file mode 100644 index 0000000..7e49307 --- /dev/null +++ b/typings/sphinx/environment/collectors/__init__.pyi @@ -0,0 +1,61 @@ +""" +This type stub file was generated by pyright. +""" + +from __future__ import annotations +from typing import TYPE_CHECKING +from docutils import nodes +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment + +"""The data collector components for sphinx.environment.""" +if TYPE_CHECKING: + ... +class EnvironmentCollector: + """An EnvironmentCollector is a specific data collector from each document. + + It gathers data and stores :py:class:`BuildEnvironment + ` as a database. Examples of specific + data would be images, download files, section titles, metadatas, index + entries and toctrees, etc. + """ + listener_ids: dict[str, int] | None = ... + def enable(self, app: Sphinx) -> None: + ... + + def disable(self, app: Sphinx) -> None: + ... + + def clear_doc(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None: + """Remove specified data of a document. + + This method is called on the removal of the document.""" + ... + + def merge_other(self, app: Sphinx, env: BuildEnvironment, docnames: set[str], other: BuildEnvironment) -> None: + """Merge in specified data regarding docnames from a different `BuildEnvironment` + object which coming from a subprocess in parallel builds.""" + ... + + def process_doc(self, app: Sphinx, doctree: nodes.document) -> None: + """Process a document and gather specific data from it. + + This method is called after the document is read.""" + ... + + def get_updated_docs(self, app: Sphinx, env: BuildEnvironment) -> list[str]: + """Return a list of docnames to re-read. + + This methods is called after reading the whole of documents (experimental). + """ + ... + + def get_outdated_docs(self, app: Sphinx, env: BuildEnvironment, added: set[str], changed: set[str], removed: set[str]) -> list[str]: + """Return a list of docnames to re-read. + + This methods is called before reading the documents. + """ + ... + + + diff --git a/typings/sphinx/errors.pyi b/typings/sphinx/errors.pyi new file mode 100644 index 0000000..ec8f366 --- /dev/null +++ b/typings/sphinx/errors.pyi @@ -0,0 +1,111 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any + +"""Contains SphinxError and a few subclasses.""" +class SphinxError(Exception): + """Base class for Sphinx errors. + + This is the base class for "nice" exceptions. When such an exception is + raised, Sphinx will abort the build and present the exception category and + message to the user. + + Extensions are encouraged to derive from this exception for their custom + errors. + + Exceptions *not* derived from :exc:`SphinxError` are treated as unexpected + and shown to the user with a part of the traceback (and the full traceback + saved in a temporary file). + + .. attribute:: category + + Description of the exception "category", used in converting the + exception to a string ("category: message"). Should be set accordingly + in subclasses. + """ + category = ... + + +class SphinxWarning(SphinxError): + """Warning, treated as error.""" + category = ... + + +class ApplicationError(SphinxError): + """Application initialization error.""" + category = ... + + +class ExtensionError(SphinxError): + """Extension error.""" + def __init__(self, message: str, orig_exc: Exception | None = ..., modname: str | None = ...) -> None: + ... + + @property + def category(self) -> str: + ... + + def __repr__(self) -> str: + ... + + def __str__(self) -> str: + ... + + + +class BuildEnvironmentError(SphinxError): + """BuildEnvironment error.""" + category = ... + + +class ConfigError(SphinxError): + """Configuration error.""" + category = ... + + +class DocumentError(SphinxError): + """Document error.""" + category = ... + + +class ThemeError(SphinxError): + """Theme error.""" + category = ... + + +class VersionRequirementError(SphinxError): + """Incompatible Sphinx version error.""" + category = ... + + +class SphinxParallelError(SphinxError): + """Sphinx parallel build error.""" + category = ... + def __init__(self, message: str, traceback: Any) -> None: + ... + + def __str__(self) -> str: + ... + + + +class PycodeError(Exception): + """Pycode Python source code analyser error.""" + def __str__(self) -> str: + ... + + + +class NoUri(Exception): + """Raised by builder.get_relative_uri() or from missing-reference handlers + if there is no URI available.""" + ... + + +class FiletypeNotFoundError(Exception): + """Raised by get_filetype() if a filename matches no source suffix.""" + ... + + diff --git a/typings/sphinx/events.pyi b/typings/sphinx/events.pyi new file mode 100644 index 0000000..a6e7447 --- /dev/null +++ b/typings/sphinx/events.pyi @@ -0,0 +1,52 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, NamedTuple, TYPE_CHECKING +from sphinx.application import Sphinx + +"""Sphinx core events. + +Gracefully adapted from the TextPress system by Armin. +""" +if TYPE_CHECKING: + ... +logger = ... +class EventListener(NamedTuple): + id: int + handler: Callable + priority: int + ... + + +core_events = ... +class EventManager: + """Event manager for Sphinx.""" + def __init__(self, app: Sphinx) -> None: + ... + + def add(self, name: str) -> None: + """Register a custom Sphinx event.""" + ... + + def connect(self, name: str, callback: Callable, priority: int) -> int: + """Connect a handler to specific event.""" + ... + + def disconnect(self, listener_id: int) -> None: + """Disconnect a handler.""" + ... + + def emit(self, name: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ...) -> list: + """Emit a Sphinx event.""" + ... + + def emit_firstresult(self, name: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ...) -> Any: + """Emit a Sphinx event and returns first result. + + This returns the result of the first handler that doesn't return ``None``. + """ + ... + + + diff --git a/typings/sphinx/ext/__init__.pyi b/typings/sphinx/ext/__init__.pyi new file mode 100644 index 0000000..256df23 --- /dev/null +++ b/typings/sphinx/ext/__init__.pyi @@ -0,0 +1,5 @@ +""" +This type stub file was generated by pyright. +""" + +"""Contains Sphinx features not activated by default.""" diff --git a/typings/sphinx/ext/autodoc/__init__.pyi b/typings/sphinx/ext/autodoc/__init__.pyi new file mode 100644 index 0000000..2c3aded --- /dev/null +++ b/typings/sphinx/ext/autodoc/__init__.pyi @@ -0,0 +1,848 @@ +""" +This type stub file was generated by pyright. +""" + +import re +import sys +import warnings +import sphinx +from __future__ import annotations +from inspect import Parameter, Signature +from typing import Any, Callable, TYPE_CHECKING, TypeVar +from docutils.statemachine import StringList +from sphinx.config import Config, ENUM +from sphinx.deprecation import RemovedInSphinx80Warning +from sphinx.ext.autodoc.importer import get_class_members, import_module, import_object +from sphinx.ext.autodoc.mock import ismock, mock, undecorate +from sphinx.locale import _, __ +from sphinx.pycode import ModuleAnalyzer, PycodeError +from sphinx.util import inspect, logging +from sphinx.util.docstrings import prepare_docstring, separate_metadata +from sphinx.util.inspect import evaluate_signature, getdoc, object_description, safe_getattr, stringify_signature +from sphinx.util.typing import OptionSpec, get_type_hints, restify, stringify_annotation +from collections.abc import Iterator, Sequence +from types import ModuleType +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.ext.autodoc.directive import DocumenterBridge + +"""Extension to create automatic documentation from code docstrings. + +Automatically insert docstrings for functions, classes or whole modules into +the doctree, thus avoiding duplication between docstrings and documentation +for those who like elaborate docstrings. +""" +if TYPE_CHECKING: + ... +logger = ... +MethodDescriptorType = ... +py_ext_sig_re = ... +special_member_re = ... +def identity(x: Any) -> Any: + ... + +class _All: + """A special value for :*-members: that matches to any member.""" + def __contains__(self, item: Any) -> bool: + ... + + def append(self, item: Any) -> None: + ... + + + +class _Empty: + """A special value for :exclude-members: that never matches to any member.""" + def __contains__(self, item: Any) -> bool: + ... + + + +ALL = ... +EMPTY = ... +UNINITIALIZED_ATTR = ... +INSTANCEATTR = ... +SLOTSATTR = ... +def members_option(arg: Any) -> object | list[str]: + """Used to convert the :members: option to auto directives.""" + ... + +def exclude_members_option(arg: Any) -> object | set[str]: + """Used to convert the :exclude-members: option.""" + ... + +def inherited_members_option(arg: Any) -> set[str]: + """Used to convert the :inherited-members: option to auto directives.""" + ... + +def member_order_option(arg: Any) -> str | None: + """Used to convert the :member-order: option to auto directives.""" + ... + +def class_doc_from_option(arg: Any) -> str | None: + """Used to convert the :class-doc-from: option to autoclass directives.""" + ... + +SUPPRESS = ... +def annotation_option(arg: Any) -> Any: + ... + +def bool_option(arg: Any) -> bool: + """Used to convert flag options to auto directives. (Instead of + directives.flag(), which returns None). + """ + ... + +def merge_members_option(options: dict) -> None: + """Merge :private-members: and :special-members: options to the + :members: option. + """ + ... + +def cut_lines(pre: int, post: int = ..., what: str | None = ...) -> Callable: + """Return a listener that removes the first *pre* and last *post* + lines of every docstring. If *what* is a sequence of strings, + only docstrings of a type in *what* will be processed. + + Use like this (e.g. in the ``setup()`` function of :file:`conf.py`):: + + from sphinx.ext.autodoc import cut_lines + app.connect('autodoc-process-docstring', cut_lines(4, what=['module'])) + + This can (and should) be used in place of :confval:`automodule_skip_lines`. + """ + ... + +def between(marker: str, what: Sequence[str] | None = ..., keepempty: bool = ..., exclude: bool = ...) -> Callable: + """Return a listener that either keeps, or if *exclude* is True excludes, + lines between lines that match the *marker* regular expression. If no line + matches, the resulting docstring would be empty, so no change will be made + unless *keepempty* is true. + + If *what* is a sequence of strings, only docstrings of a type in *what* will + be processed. + """ + ... + +class Options(dict): + """A dict/attribute hybrid that returns None on nonexisting keys.""" + def copy(self) -> Options: + ... + + def __getattr__(self, name: str) -> Any: + ... + + + +class ObjectMember: + """A member of object. + + This is used for the result of `Documenter.get_module_members()` to + represent each member of the object. + + .. Note:: + + An instance of this class behaves as a tuple of (name, object) + for compatibility to old Sphinx. The behavior will be dropped + in the future. Therefore extensions should not use the tuple + interface. + """ + def __init__(self, name: str, obj: Any, *, docstring: str | None = ..., class_: Any = ..., skipped: bool = ...) -> None: + ... + + def __getitem__(self, index): # -> Any: + ... + + + +class Documenter: + """ + A Documenter knows how to autodocument a single object type. When + registered with the AutoDirective, it will be used to document objects + of that type when needed by autodoc. + + Its *objtype* attribute selects what auto directive it is assigned to + (the directive name is 'auto' + objtype), and what directive it generates + by default, though that can be overridden by an attribute called + *directivetype*. + + A Documenter has an *option_spec* that works like a docutils directive's; + in fact, it will be used to parse an auto directive's options that matches + the Documenter. + """ + objtype = ... + content_indent = ... + priority = ... + member_order = ... + titles_allowed = ... + option_spec: OptionSpec = ... + def get_attr(self, obj: Any, name: str, *defargs: Any) -> Any: + """getattr() override for types such as Zope interfaces.""" + ... + + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + """Called to see if a member can be documented by this Documenter.""" + ... + + def __init__(self, directive: DocumenterBridge, name: str, indent: str = ...) -> None: + ... + + @property + def documenters(self) -> dict[str, type[Documenter]]: + """Returns registered Documenter classes""" + ... + + def add_line(self, line: str, source: str, *lineno: int) -> None: + """Append one line of generated reST to the output.""" + ... + + def resolve_name(self, modname: str | None, parents: Any, path: str, base: str) -> tuple[str | None, list[str]]: + """Resolve the module and name of the object to document given by the + arguments and the current module/class. + + Must return a pair of the module name and a chain of attributes; for + example, it would return ``('zipfile', ['ZipFile', 'open'])`` for the + ``zipfile.ZipFile.open`` method. + """ + ... + + def parse_name(self) -> bool: + """Determine what module to import and what attribute to document. + + Returns True and sets *self.modname*, *self.objpath*, *self.fullname*, + *self.args* and *self.retann* if parsing and resolving was successful. + """ + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + """Import the object given by *self.modname* and *self.objpath* and set + it as *self.object*. + + Returns True if successful, False if an error occurred. + """ + ... + + def get_real_modname(self) -> str: + """Get the real module name of an object to document. + + It can differ from the name of the module through which the object was + imported. + """ + ... + + def check_module(self) -> bool: + """Check if *self.object* is really defined in the module given by + *self.modname*. + """ + ... + + def format_args(self, **kwargs: Any) -> str: + """Format the argument signature of *self.object*. + + Should return None if the object does not have a signature. + """ + ... + + def format_name(self) -> str: + """Format the name of *self.object*. + + This normally should be something that can be parsed by the generated + directive, but doesn't need to be (Sphinx will display it unparsed + then). + """ + ... + + def format_signature(self, **kwargs: Any) -> str: + """Format the signature (arguments and return annotation) of the object. + + Let the user process it via the ``autodoc-process-signature`` event. + """ + ... + + def add_directive_header(self, sig: str) -> None: + """Add the directive header and options to the generated content.""" + ... + + def get_doc(self) -> list[list[str]] | None: + """Decode and return lines of the docstring(s) for the object. + + When it returns None, autodoc-process-docstring will not be called for this + object. + """ + ... + + def process_doc(self, docstrings: list[list[str]]) -> Iterator[str]: + """Let the user process the docstrings before adding them.""" + ... + + def get_sourcename(self) -> str: + ... + + def add_content(self, more_content: StringList | None) -> None: + """Add content from docstrings, attribute documentation and user.""" + ... + + def get_object_members(self, want_all: bool) -> tuple[bool, list[ObjectMember]]: + """Return `(members_check_module, members)` where `members` is a + list of `(membername, member)` pairs of the members of *self.object*. + + If *want_all* is True, return all members. Else, only return those + members given by *self.options.members* (which may also be None). + """ + ... + + def filter_members(self, members: list[ObjectMember], want_all: bool) -> list[tuple[str, Any, bool]]: + """Filter the given member list. + + Members are skipped if + + - they are private (except if given explicitly or the private-members + option is set) + - they are special methods (except if given explicitly or the + special-members option is set) + - they are undocumented (except if the undoc-members option is set) + + The user can override the skipping decision by connecting to the + ``autodoc-skip-member`` event. + """ + ... + + def document_members(self, all_members: bool = ...) -> None: + """Generate reST for member documentation. + + If *all_members* is True, document all members, else those given by + *self.options.members*. + """ + ... + + def sort_members(self, documenters: list[tuple[Documenter, bool]], order: str) -> list[tuple[Documenter, bool]]: + """Sort the given member list.""" + ... + + def generate(self, more_content: StringList | None = ..., real_modname: str | None = ..., check_module: bool = ..., all_members: bool = ...) -> None: + """Generate reST for the object given by *self.name*, and possibly for + its members. + + If *more_content* is given, include that content. If *real_modname* is + given, use that module name to find attribute docs. If *check_module* is + True, only generate if the object is defined in the module name it is + imported from. If *all_members* is True, document all members. + """ + ... + + + +class ModuleDocumenter(Documenter): + """ + Specialized Documenter subclass for modules. + """ + objtype = ... + content_indent = ... + _extra_indent = ... + option_spec: OptionSpec = ... + def __init__(self, *args: Any) -> None: + ... + + def add_content(self, more_content: StringList | None) -> None: + ... + + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + ... + + def resolve_name(self, modname: str | None, parents: Any, path: str, base: str) -> tuple[str | None, list[str]]: + ... + + def parse_name(self) -> bool: + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + ... + + def add_directive_header(self, sig: str) -> None: + ... + + def get_module_members(self) -> dict[str, ObjectMember]: + """Get members of target module.""" + ... + + def get_object_members(self, want_all: bool) -> tuple[bool, list[ObjectMember]]: + ... + + def sort_members(self, documenters: list[tuple[Documenter, bool]], order: str) -> list[tuple[Documenter, bool]]: + ... + + + +class ModuleLevelDocumenter(Documenter): + """ + Specialized Documenter subclass for objects on module level (functions, + classes, data/constants). + """ + def resolve_name(self, modname: str | None, parents: Any, path: str, base: str) -> tuple[str | None, list[str]]: + ... + + + +class ClassLevelDocumenter(Documenter): + """ + Specialized Documenter subclass for objects on class level (methods, + attributes). + """ + def resolve_name(self, modname: str | None, parents: Any, path: str, base: str) -> tuple[str | None, list[str]]: + ... + + + +class DocstringSignatureMixin: + """ + Mixin for FunctionDocumenter and MethodDocumenter to provide the + feature of reading the signature from the docstring. + """ + _new_docstrings: list[list[str]] | None = ... + _signatures: list[str] = ... + def get_doc(self) -> list[list[str]] | None: + ... + + def format_signature(self, **kwargs: Any) -> str: + ... + + + +class DocstringStripSignatureMixin(DocstringSignatureMixin): + """ + Mixin for AttributeDocumenter to provide the + feature of stripping any function signature from the docstring. + """ + def format_signature(self, **kwargs: Any) -> str: + ... + + + +class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): + """ + Specialized Documenter subclass for functions. + """ + objtype = ... + member_order = ... + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + ... + + def format_args(self, **kwargs: Any) -> str: + ... + + def document_members(self, all_members: bool = ...) -> None: + ... + + def add_directive_header(self, sig: str) -> None: + ... + + def format_signature(self, **kwargs: Any) -> str: + ... + + def merge_default_value(self, actual: Signature, overload: Signature) -> Signature: + """Merge default values of actual implementation to the overload variants.""" + ... + + def annotate_to_first_argument(self, func: Callable, typ: type) -> Callable | None: + """Annotate type hint to the first argument of function if needed.""" + ... + + + +class DecoratorDocumenter(FunctionDocumenter): + """ + Specialized Documenter subclass for decorator functions. + """ + objtype = ... + priority = ... + def format_args(self, **kwargs: Any) -> str: + ... + + + +_METACLASS_CALL_BLACKLIST = ... +_CLASS_NEW_BLACKLIST = ... +class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): + """ + Specialized Documenter subclass for classes. + """ + objtype = ... + member_order = ... + option_spec: OptionSpec = ... + priority = ... + _signature_class: Any = ... + _signature_method_name: str = ... + def __init__(self, *args: Any) -> None: + ... + + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + ... + + def format_args(self, **kwargs: Any) -> str: + ... + + def format_signature(self, **kwargs: Any) -> str: + ... + + def get_overloaded_signatures(self) -> list[Signature]: + ... + + def get_canonical_fullname(self) -> str | None: + ... + + def add_directive_header(self, sig: str) -> None: + ... + + def get_object_members(self, want_all: bool) -> tuple[bool, list[ObjectMember]]: + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + def get_variable_comment(self) -> list[str] | None: + ... + + def add_content(self, more_content: StringList | None) -> None: + ... + + def document_members(self, all_members: bool = ...) -> None: + ... + + def generate(self, more_content: StringList | None = ..., real_modname: str | None = ..., check_module: bool = ..., all_members: bool = ...) -> None: + ... + + + +class ExceptionDocumenter(ClassDocumenter): + """ + Specialized ClassDocumenter subclass for exceptions. + """ + objtype = ... + member_order = ... + priority = ... + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + ... + + + +class DataDocumenterMixinBase: + config: Config + env: BuildEnvironment + modname: str + parent: Any + object: Any + objpath: list[str] + def should_suppress_directive_header(self) -> bool: + """Check directive header should be suppressed.""" + ... + + def should_suppress_value_header(self) -> bool: + """Check :value: header should be suppressed.""" + ... + + def update_content(self, more_content: StringList) -> None: + """Update docstring, for example with TypeVar variance.""" + ... + + + +class GenericAliasMixin(DataDocumenterMixinBase): + """ + Mixin for DataDocumenter and AttributeDocumenter to provide the feature for + supporting GenericAliases. + """ + def should_suppress_directive_header(self) -> bool: + ... + + def update_content(self, more_content: StringList) -> None: + ... + + + +class UninitializedGlobalVariableMixin(DataDocumenterMixinBase): + """ + Mixin for DataDocumenter to provide the feature for supporting uninitialized + (type annotation only) global variables. + """ + def import_object(self, raiseerror: bool = ...) -> bool: + ... + + def should_suppress_value_header(self) -> bool: + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + + +class DataDocumenter(GenericAliasMixin, UninitializedGlobalVariableMixin, ModuleLevelDocumenter): + """ + Specialized Documenter subclass for data items. + """ + objtype = ... + member_order = ... + priority = ... + option_spec: OptionSpec = ... + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + ... + + def update_annotations(self, parent: Any) -> None: + """Update __annotations__ to support type_comment and so on.""" + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + ... + + def should_suppress_value_header(self) -> bool: + ... + + def add_directive_header(self, sig: str) -> None: + ... + + def document_members(self, all_members: bool = ...) -> None: + ... + + def get_real_modname(self) -> str: + ... + + def get_module_comment(self, attrname: str) -> list[str] | None: + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + def add_content(self, more_content: StringList | None) -> None: + ... + + + +class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): + """ + Specialized Documenter subclass for methods (normal, static and class). + """ + objtype = ... + directivetype = ... + member_order = ... + priority = ... + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + ... + + def format_args(self, **kwargs: Any) -> str: + ... + + def add_directive_header(self, sig: str) -> None: + ... + + def document_members(self, all_members: bool = ...) -> None: + ... + + def format_signature(self, **kwargs: Any) -> str: + ... + + def merge_default_value(self, actual: Signature, overload: Signature) -> Signature: + """Merge default values of actual implementation to the overload variants.""" + ... + + def annotate_to_first_argument(self, func: Callable, typ: type) -> Callable | None: + """Annotate type hint to the first argument of function if needed.""" + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + + +class NonDataDescriptorMixin(DataDocumenterMixinBase): + """ + Mixin for AttributeDocumenter to provide the feature for supporting non + data-descriptors. + + .. note:: This mix-in must be inherited after other mix-ins. Otherwise, docstring + and :value: header will be suppressed unexpectedly. + """ + def import_object(self, raiseerror: bool = ...) -> bool: + ... + + def should_suppress_value_header(self) -> bool: + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + + +class SlotsMixin(DataDocumenterMixinBase): + """ + Mixin for AttributeDocumenter to provide the feature for supporting __slots__. + """ + def isslotsattribute(self) -> bool: + """Check the subject is an attribute in __slots__.""" + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + ... + + def should_suppress_value_header(self) -> bool: + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + + +class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): + """ + Mixin for AttributeDocumenter to provide the feature for supporting runtime + instance attributes (that are defined in __init__() methods with doc-comments). + + Example: + + class Foo: + def __init__(self): + self.attr = None #: This is a target of this mix-in. + """ + RUNTIME_INSTANCE_ATTRIBUTE = ... + def is_runtime_instance_attribute(self, parent: Any) -> bool: + """Check the subject is an attribute defined in __init__().""" + ... + + def is_runtime_instance_attribute_not_commented(self, parent: Any) -> bool: + """Check the subject is an attribute defined in __init__() without comment.""" + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + """Check the existence of runtime instance attribute after failing to import the + attribute.""" + ... + + def should_suppress_value_header(self) -> bool: + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + + +class UninitializedInstanceAttributeMixin(DataDocumenterMixinBase): + """ + Mixin for AttributeDocumenter to provide the feature for supporting uninitialized + instance attributes (PEP-526 styled, annotation only attributes). + + Example: + + class Foo: + attr: int #: This is a target of this mix-in. + """ + def is_uninitialized_instance_attribute(self, parent: Any) -> bool: + """Check the subject is an annotation only attribute.""" + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + """Check the exisitence of uninitialized instance attribute when failed to import + the attribute.""" + ... + + def should_suppress_value_header(self) -> bool: + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + + +class AttributeDocumenter(GenericAliasMixin, SlotsMixin, RuntimeInstanceAttributeMixin, UninitializedInstanceAttributeMixin, NonDataDescriptorMixin, DocstringStripSignatureMixin, ClassLevelDocumenter): + """ + Specialized Documenter subclass for attributes. + """ + objtype = ... + member_order = ... + option_spec: OptionSpec = ... + priority = ... + @staticmethod + def is_function_or_method(obj: Any) -> bool: + ... + + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + ... + + def document_members(self, all_members: bool = ...) -> None: + ... + + def update_annotations(self, parent: Any) -> None: + """Update __annotations__ to support type_comment and so on.""" + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + ... + + def get_real_modname(self) -> str: + ... + + def should_suppress_value_header(self) -> bool: + ... + + def add_directive_header(self, sig: str) -> None: + ... + + def get_attribute_comment(self, parent: Any, attrname: str) -> list[str] | None: + ... + + def get_doc(self) -> list[list[str]] | None: + ... + + def add_content(self, more_content: StringList | None) -> None: + ... + + + +class PropertyDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter): + """ + Specialized Documenter subclass for properties. + """ + objtype = ... + member_order = ... + priority = ... + @classmethod + def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool: + ... + + def import_object(self, raiseerror: bool = ...) -> bool: + """Check the exisitence of uninitialized instance attribute when failed to import + the attribute.""" + ... + + def format_args(self, **kwargs: Any) -> str: + ... + + def document_members(self, all_members: bool = ...) -> None: + ... + + def get_real_modname(self) -> str: + ... + + def add_directive_header(self, sig: str) -> None: + ... + + + +def autodoc_attrgetter(app: Sphinx, obj: Any, name: str, *defargs: Any) -> Any: + """Alternative getattr() for types""" + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/ext/autodoc/directive.pyi b/typings/sphinx/ext/autodoc/directive.pyi new file mode 100644 index 0000000..54bcc7d --- /dev/null +++ b/typings/sphinx/ext/autodoc/directive.pyi @@ -0,0 +1,61 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, TYPE_CHECKING +from docutils.statemachine import StringList +from docutils.utils import Reporter +from sphinx.ext.autodoc import Documenter, Options +from sphinx.util.docutils import SphinxDirective +from docutils.nodes import Node +from docutils.parsers.rst.states import RSTState +from sphinx.config import Config +from sphinx.environment import BuildEnvironment + +if TYPE_CHECKING: + ... +logger = ... +AUTODOC_DEFAULT_OPTIONS = ... +AUTODOC_EXTENDABLE_OPTIONS = ... +class DummyOptionSpec(dict): + """An option_spec allows any options.""" + def __bool__(self) -> bool: + """Behaves like some options are defined.""" + ... + + def __getitem__(self, key: str) -> Callable[[str], str]: + ... + + + +class DocumenterBridge: + """A parameters container for Documenters.""" + def __init__(self, env: BuildEnvironment, reporter: Reporter | None, options: Options, lineno: int, state: Any) -> None: + ... + + + +def process_documenter_options(documenter: type[Documenter], config: Config, options: dict) -> Options: + """Recognize options of Documenter from user input.""" + ... + +def parse_generated_content(state: RSTState, content: StringList, documenter: Documenter) -> list[Node]: + """Parse an item of content generated by Documenter.""" + ... + +class AutodocDirective(SphinxDirective): + """A directive class for all autodoc directives. It works as a dispatcher of Documenters. + + It invokes a Documenter upon running. After the processing, it parses and returns + the content generated by Documenter. + """ + option_spec = ... + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + def run(self) -> list[Node]: + ... + + + diff --git a/typings/sphinx/ext/autodoc/importer.pyi b/typings/sphinx/ext/autodoc/importer.pyi new file mode 100644 index 0000000..7819ff7 --- /dev/null +++ b/typings/sphinx/ext/autodoc/importer.pyi @@ -0,0 +1,44 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, NamedTuple, TYPE_CHECKING +from sphinx.pycode import ModuleAnalyzer +from sphinx.ext.autodoc import ObjectMember + +"""Importer utilities for autodoc""" +if TYPE_CHECKING: + ... +logger = ... +def mangle(subject: Any, name: str) -> str: + """Mangle the given name.""" + ... + +def unmangle(subject: Any, name: str) -> str | None: + """Unmangle the given name.""" + ... + +def import_module(modname: str, warningiserror: bool = ...) -> Any: + """ + Call importlib.import_module(modname), convert exceptions to ImportError + """ + ... + +def import_object(modname: str, objpath: list[str], objtype: str = ..., attrgetter: Callable[[Any, str], Any] = ..., warningiserror: bool = ...) -> Any: + ... + +class Attribute(NamedTuple): + name: str + directly_defined: bool + value: Any + ... + + +def get_object_members(subject: Any, objpath: list[str], attrgetter: Callable, analyzer: ModuleAnalyzer | None = ...) -> dict[str, Attribute]: + """Get members and attributes of target object.""" + ... + +def get_class_members(subject: Any, objpath: Any, attrgetter: Callable, inherit_docstrings: bool = ...) -> dict[str, ObjectMember]: + """Get members and attributes of target class.""" + ... + diff --git a/typings/sphinx/ext/autodoc/mock.pyi b/typings/sphinx/ext/autodoc/mock.pyi new file mode 100644 index 0000000..5dbb659 --- /dev/null +++ b/typings/sphinx/ext/autodoc/mock.pyi @@ -0,0 +1,120 @@ +""" +This type stub file was generated by pyright. +""" + +import contextlib +from importlib.abc import Loader, MetaPathFinder +from importlib.machinery import ModuleSpec +from types import ModuleType +from typing import Any, TYPE_CHECKING +from collections.abc import Generator, Iterator, Sequence + +"""mock for autodoc""" +if TYPE_CHECKING: + ... +logger = ... +class _MockObject: + """Used by autodoc_mock_imports.""" + __display_name__ = ... + __name__ = ... + __sphinx_mock__ = ... + __sphinx_decorator_args__: tuple[Any, ...] = ... + def __new__(cls, *args: Any, **kwargs: Any) -> Any: + ... + + def __init__(self, *args: Any, **kwargs: Any) -> None: + ... + + def __len__(self) -> int: + ... + + def __contains__(self, key: str) -> bool: + ... + + def __iter__(self) -> Iterator: + ... + + def __mro_entries__(self, bases: tuple) -> tuple: + ... + + def __getitem__(self, key: Any) -> _MockObject: + ... + + def __getattr__(self, key: str) -> _MockObject: + ... + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + ... + + def __repr__(self) -> str: + ... + + + +class _MockModule(ModuleType): + """Used by autodoc_mock_imports.""" + __file__ = ... + __sphinx_mock__ = ... + def __init__(self, name: str) -> None: + ... + + def __getattr__(self, name: str) -> _MockObject: + ... + + def __repr__(self) -> str: + ... + + + +class MockLoader(Loader): + """A loader for mocking.""" + def __init__(self, finder: MockFinder) -> None: + ... + + def create_module(self, spec: ModuleSpec) -> ModuleType: + ... + + def exec_module(self, module: ModuleType) -> None: + ... + + + +class MockFinder(MetaPathFinder): + """A finder for mocking.""" + def __init__(self, modnames: list[str]) -> None: + ... + + def find_spec(self, fullname: str, path: Sequence[bytes | str] | None, target: ModuleType | None = ...) -> ModuleSpec | None: + ... + + def invalidate_caches(self) -> None: + """Invalidate mocked modules on sys.modules.""" + ... + + + +@contextlib.contextmanager +def mock(modnames: list[str]) -> Generator[None, None, None]: + """Insert mock modules during context:: + + with mock(['target.module.name']): + # mock modules are enabled here + ... + """ + ... + +def ismockmodule(subject: Any) -> bool: + """Check if the object is a mocked module.""" + ... + +def ismock(subject: Any) -> bool: + """Check if the object is mocked.""" + ... + +def undecorate(subject: _MockObject) -> Any: + """Unwrap mock if *subject* is decorated by mocked object. + + If not decorated, returns given *subject* itself. + """ + ... + diff --git a/typings/sphinx/ext/duration.pyi b/typings/sphinx/ext/duration.pyi new file mode 100644 index 0000000..001020c --- /dev/null +++ b/typings/sphinx/ext/duration.pyi @@ -0,0 +1,56 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from sphinx.domains import Domain +from docutils import nodes +from sphinx.application import Sphinx + +"""Measure document reading durations.""" +if TYPE_CHECKING: + ... +logger = ... +class DurationDomain(Domain): + """A domain for durations of Sphinx processing.""" + name = ... + @property + def reading_durations(self) -> dict[str, float]: + ... + + def note_reading_duration(self, duration: float) -> None: + ... + + def clear(self) -> None: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict[str, float]) -> None: + ... + + + +def on_builder_inited(app: Sphinx) -> None: + """Initialize DurationDomain on bootstrap. + + This clears the results of the last build. + """ + ... + +def on_source_read(app: Sphinx, docname: str, content: list[str]) -> None: + """Start to measure reading duration.""" + ... + +def on_doctree_read(app: Sphinx, doctree: nodes.document) -> None: + """Record a reading duration.""" + ... + +def on_build_finished(app: Sphinx, error: Exception) -> None: + """Display duration ranking on the current build.""" + ... + +def setup(app: Sphinx) -> dict[str, bool | str]: + ... + diff --git a/typings/sphinx/ext/todo.pyi b/typings/sphinx/ext/todo.pyi new file mode 100644 index 0000000..8e38257 --- /dev/null +++ b/typings/sphinx/ext/todo.pyi @@ -0,0 +1,111 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils import nodes +from docutils.parsers.rst.directives.admonitions import BaseAdmonition +from sphinx.domains import Domain +from sphinx.util.docutils import SphinxDirective +from docutils.nodes import Element, Node +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import OptionSpec +from sphinx.writers.html import HTML5Translator +from sphinx.writers.latex import LaTeXTranslator + +"""Allow todos to be inserted into your documentation. + +Inclusion of todos can be switched of by a configuration variable. +The todolist directive collects all todos of your project and lists them along +with a backlink to the original location. +""" +if TYPE_CHECKING: + ... +logger = ... +class todo_node(nodes.Admonition, nodes.Element): + ... + + +class todolist(nodes.General, nodes.Element): + ... + + +class Todo(BaseAdmonition, SphinxDirective): + """ + A todo entry, displayed (if configured) in the form of an admonition. + """ + node_class = todo_node + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class TodoDomain(Domain): + name = ... + label = ... + @property + def todos(self) -> dict[str, list[todo_node]]: + ... + + def clear_doc(self, docname: str) -> None: + ... + + def merge_domaindata(self, docnames: list[str], otherdata: dict) -> None: + ... + + def process_doc(self, env: BuildEnvironment, docname: str, document: nodes.document) -> None: + ... + + + +class TodoList(SphinxDirective): + """ + A list of all todo entries. + """ + has_content = ... + required_arguments = ... + optional_arguments = ... + final_argument_whitespace = ... + option_spec: OptionSpec = ... + def run(self) -> list[Node]: + ... + + + +class TodoListProcessor: + def __init__(self, app: Sphinx, doctree: nodes.document, docname: str) -> None: + ... + + def process(self, doctree: nodes.document, docname: str) -> None: + ... + + def create_todo_reference(self, todo: todo_node, docname: str) -> nodes.paragraph: + ... + + def resolve_reference(self, todo: todo_node, docname: str) -> None: + """Resolve references in the todo content.""" + ... + + + +def visit_todo_node(self: HTML5Translator, node: todo_node) -> None: + ... + +def depart_todo_node(self: HTML5Translator, node: todo_node) -> None: + ... + +def latex_visit_todo_node(self: LaTeXTranslator, node: todo_node) -> None: + ... + +def latex_depart_todo_node(self: LaTeXTranslator, node: todo_node) -> None: + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/extension.pyi b/typings/sphinx/extension.pyi new file mode 100644 index 0000000..358fdcc --- /dev/null +++ b/typings/sphinx/extension.pyi @@ -0,0 +1,32 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from sphinx.application import Sphinx +from sphinx.config import Config + +"""Utilities for Sphinx extensions.""" +if TYPE_CHECKING: + ... +logger = ... +class Extension: + def __init__(self, name: str, module: Any, **kwargs: Any) -> None: + ... + + + +def verify_needs_extensions(app: Sphinx, config: Config) -> None: + """Check that extensions mentioned in :confval:`needs_extensions` satisfy the version + requirement, and warn if an extension is not loaded. + + Warns if an extension in :confval:`needs_extension` is not loaded. + + :raises VersionRequirementError: if the version of an extension in + :confval:`needs_extension` is unknown or older than the required version. + """ + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/highlighting.pyi b/typings/sphinx/highlighting.pyi new file mode 100644 index 0000000..af02d9b --- /dev/null +++ b/typings/sphinx/highlighting.pyi @@ -0,0 +1,42 @@ +""" +This type stub file was generated by pyright. +""" + +from functools import partial +from typing import Any, TYPE_CHECKING +from pygments.formatters import HtmlFormatter, LatexFormatter +from pygments.formatter import Formatter +from pygments.lexer import Lexer +from pygments.style import Style + +"""Highlight code blocks using Pygments.""" +if TYPE_CHECKING: + ... +logger = ... +lexers: dict[str, Lexer] = ... +lexer_classes: dict[str, type[Lexer] | partial[Lexer]] = ... +escape_hl_chars = ... +_LATEX_ADD_STYLES = ... +class PygmentsBridge: + html_formatter = HtmlFormatter + latex_formatter = LatexFormatter + def __init__(self, dest: str = ..., stylename: str = ..., latex_engine: str | None = ...) -> None: + ... + + def get_style(self, stylename: str) -> Style: + ... + + def get_formatter(self, **kwargs: Any) -> Formatter: + ... + + def get_lexer(self, source: str, lang: str, opts: dict | None = ..., force: bool = ..., location: Any = ...) -> Lexer: + ... + + def highlight_block(self, source: str, lang: str, opts: dict | None = ..., force: bool = ..., location: Any = ..., **kwargs: Any) -> str: + ... + + def get_stylesheet(self) -> str: + ... + + + diff --git a/typings/sphinx/io.pyi b/typings/sphinx/io.pyi new file mode 100644 index 0000000..b25a553 --- /dev/null +++ b/typings/sphinx/io.pyi @@ -0,0 +1,96 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils import nodes +from docutils.core import Publisher +from docutils.io import FileInput, Input +from docutils.readers import standalone +from docutils.writers import UnfilteredWriter +from docutils.frontend import Values +from docutils.parsers import Parser +from docutils.transforms import Transform +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment + +"""Input/Output files""" +if TYPE_CHECKING: + ... +logger = ... +class SphinxBaseReader(standalone.Reader): + """ + A base class of readers for Sphinx. + + This replaces reporter by Sphinx's on generating document. + """ + transforms: list[type[Transform]] = ... + def __init__(self, *args: Any, **kwargs: Any) -> None: + ... + + def setup(self, app: Sphinx) -> None: + ... + + def get_transforms(self) -> list[type[Transform]]: + ... + + def new_document(self) -> nodes.document: + """ + Creates a new document object which has a special reporter object good + for logging. + """ + ... + + + +class SphinxStandaloneReader(SphinxBaseReader): + """ + A basic document reader for Sphinx. + """ + def setup(self, app: Sphinx) -> None: + ... + + def read(self, source: Input, parser: Parser, settings: Values) -> nodes.document: + ... + + def read_source(self, env: BuildEnvironment) -> str: + """Read content from source and do post-process.""" + ... + + + +class SphinxI18nReader(SphinxBaseReader): + """ + A document reader for i18n. + + This returns the source line number of original text as current source line number + to let users know where the error happened. + Because the translated texts are partial and they don't have correct line numbers. + """ + def setup(self, app: Sphinx) -> None: + ... + + + +class SphinxDummyWriter(UnfilteredWriter): + """Dummy writer module used for generating doctree.""" + supported = ... + def translate(self) -> None: + ... + + + +def SphinxDummySourceClass(source: Any, *args: Any, **kwargs: Any) -> Any: + """Bypass source object as is to cheat Publisher.""" + ... + +class SphinxFileInput(FileInput): + """A basic FileInput for Sphinx.""" + def __init__(self, *args: Any, **kwargs: Any) -> None: + ... + + + +def create_publisher(app: Sphinx, filetype: str) -> Publisher: + ... + diff --git a/typings/sphinx/jinja2glue.pyi b/typings/sphinx/jinja2glue.pyi new file mode 100644 index 0000000..3b9e21f --- /dev/null +++ b/typings/sphinx/jinja2glue.pyi @@ -0,0 +1,67 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, TYPE_CHECKING +from jinja2 import BaseLoader, FileSystemLoader +from jinja2.utils import pass_context +from sphinx.application import TemplateBridge +from jinja2.environment import Environment +from sphinx.builders import Builder +from sphinx.theming import Theme + +"""Glue code for the jinja2 templating engine.""" +if TYPE_CHECKING: + ... +def accesskey(context: Any, key: str) -> str: + """Helper to output each access key only once.""" + ... + +class idgen: + def __init__(self) -> None: + ... + + def current(self) -> int: + ... + + def __next__(self) -> int: + ... + + next = ... + + +@pass_context +def warning(context: dict, message: str, *args: Any, **kwargs: Any) -> str: + ... + +class SphinxFileSystemLoader(FileSystemLoader): + """ + FileSystemLoader subclass that is not so strict about '..' entries in + template names. + """ + def get_source(self, environment: Environment, template: str) -> tuple[str, str, Callable]: + ... + + + +class BuiltinTemplateLoader(TemplateBridge, BaseLoader): + """ + Interfaces the rendering environment of jinja2 for use in Sphinx. + """ + def init(self, builder: Builder, theme: Theme | None = ..., dirs: list[str] | None = ...) -> None: + ... + + def render(self, template: str, context: dict) -> str: + ... + + def render_string(self, source: str, context: dict) -> str: + ... + + def newest_template_mtime(self) -> float: + ... + + def get_source(self, environment: Environment, template: str) -> tuple[str, str, Callable]: + ... + + + diff --git a/typings/sphinx/locale/__init__.pyi b/typings/sphinx/locale/__init__.pyi new file mode 100644 index 0000000..9a3fd96 --- /dev/null +++ b/typings/sphinx/locale/__init__.pyi @@ -0,0 +1,135 @@ +""" +This type stub file was generated by pyright. +""" + +import locale +from __future__ import annotations +from gettext import NullTranslations, translation +from os import path +from typing import Any, Callable, TYPE_CHECKING +from collections.abc import Iterable + +"""Locale utilities.""" +if TYPE_CHECKING: + ... +class _TranslationProxy: + """ + The proxy implementation attempts to be as complete as possible, so that + the lazy objects should mostly work as expected, for example for sorting. + """ + __slots__ = ... + def __init__(self, catalogue: str, namespace: str, message: str) -> None: + ... + + def __str__(self) -> str: + ... + + def __dir__(self) -> list[str]: + ... + + def __getattr__(self, name: str) -> Any: + ... + + def __getstate__(self) -> tuple[str, str, str]: + ... + + def __setstate__(self, tup: tuple[str, str, str]) -> None: + ... + + def __copy__(self) -> _TranslationProxy: + ... + + def __repr__(self) -> str: + ... + + def __add__(self, other: str) -> str: + ... + + def __radd__(self, other: str) -> str: + ... + + def __mod__(self, other: str) -> str: + ... + + def __rmod__(self, other: str) -> str: + ... + + def __mul__(self, other: Any) -> str: + ... + + def __rmul__(self, other: Any) -> str: + ... + + def __hash__(self) -> int: + ... + + def __eq__(self, other) -> bool: + ... + + def __lt__(self, string) -> bool: + ... + + def __contains__(self, char): # -> bool: + ... + + def __len__(self): # -> int: + ... + + def __getitem__(self, index): # -> str: + ... + + + +translators: dict[tuple[str, str], NullTranslations] = ... +def init(locale_dirs: Iterable[str | None], language: str | None, catalog: str = ..., namespace: str = ...) -> tuple[NullTranslations, bool]: + """Look for message catalogs in `locale_dirs` and *ensure* that there is at + least a NullTranslations catalog set in `translators`. If called multiple + times or if several ``.mo`` files are found, their contents are merged + together (thus making ``init`` reentrant). + """ + ... + +_LOCALE_DIR = ... +def init_console(locale_dir: str | None = ..., catalog: str = ...) -> tuple[NullTranslations, bool]: + """Initialize locale for console. + + .. versionadded:: 1.8 + """ + ... + +def get_translator(catalog: str = ..., namespace: str = ...) -> NullTranslations: + ... + +def is_translator_registered(catalog: str = ..., namespace: str = ...) -> bool: + ... + +def get_translation(catalog: str, namespace: str = ...) -> Callable[[str], str]: + """Get a translation function based on the *catalog* and *namespace*. + + The extension can use this API to translate the messages on the + extension:: + + import os + from sphinx.locale import get_translation + + MESSAGE_CATALOG_NAME = 'myextension' # name of *.pot, *.po and *.mo files + _ = get_translation(MESSAGE_CATALOG_NAME) + text = _('Hello Sphinx!') + + + def setup(app): + package_dir = os.path.abspath(os.path.dirname(__file__)) + locale_dir = os.path.join(package_dir, 'locales') + app.add_message_catalog(MESSAGE_CATALOG_NAME, locale_dir) + + With this code, sphinx searches a message catalog from + ``${package_dir}/locales/${language}/LC_MESSAGES/myextension.mo``. + The :confval:`language` is used for the searching. + + .. versionadded:: 1.8 + """ + ... + +_ = ... +__ = ... +admonitionlabels = ... diff --git a/typings/sphinx/parsers.pyi b/typings/sphinx/parsers.pyi new file mode 100644 index 0000000..62b6c44 --- /dev/null +++ b/typings/sphinx/parsers.pyi @@ -0,0 +1,59 @@ +""" +This type stub file was generated by pyright. +""" + +import docutils.parsers +import docutils.parsers.rst +from typing import Any, TYPE_CHECKING +from docutils import nodes +from docutils.statemachine import StringList +from docutils.transforms import Transform +from sphinx.application import Sphinx +from sphinx.config import Config +from sphinx.environment import BuildEnvironment + +"""A Base class for additional parsers.""" +if TYPE_CHECKING: + ... +class Parser(docutils.parsers.Parser): + """ + A base class of source parsers. The additional parsers should inherit this class instead + of ``docutils.parsers.Parser``. Compared with ``docutils.parsers.Parser``, this class + improves accessibility to Sphinx APIs. + + The subclasses can access sphinx core runtime objects (app, config and env). + """ + config: Config + env: BuildEnvironment + def set_application(self, app: Sphinx) -> None: + """set_application will be called from Sphinx to set app and other instance variables + + :param sphinx.application.Sphinx app: Sphinx application object + """ + ... + + + +class RSTParser(docutils.parsers.rst.Parser, Parser): + """A reST parser for Sphinx.""" + def get_transforms(self) -> list[type[Transform]]: + """ + Sphinx's reST parser replaces a transform class for smart-quotes by its own + + refs: sphinx.io.SphinxStandaloneReader + """ + ... + + def parse(self, inputstring: str | StringList, document: nodes.document) -> None: + """Parse text and generate a document tree.""" + ... + + def decorate(self, content: StringList) -> None: + """Preprocess reST content before parsing.""" + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/project.pyi b/typings/sphinx/project.pyi new file mode 100644 index 0000000..23157a6 --- /dev/null +++ b/typings/sphinx/project.pyi @@ -0,0 +1,45 @@ +""" +This type stub file was generated by pyright. +""" + +import os +from typing import TYPE_CHECKING +from collections.abc import Iterable + +"""Utility function and classes for Sphinx projects.""" +if TYPE_CHECKING: + ... +logger = ... +EXCLUDE_PATHS = ... +class Project: + """A project is the source code set of the Sphinx document(s).""" + def __init__(self, srcdir: str | os.PathLike[str], source_suffix: Iterable[str]) -> None: + ... + + def restore(self, other: Project) -> None: + """Take over a result of last build.""" + ... + + def discover(self, exclude_paths: Iterable[str] = ..., include_paths: Iterable[str] = ...) -> set[str]: + """Find all document files in the source directory and put them in + :attr:`docnames`. + """ + ... + + def path2doc(self, filename: str | os.PathLike[str]) -> str | None: + """Return the docname for the filename if the file is a document. + + *filename* should be absolute or relative to the source directory. + """ + ... + + def doc2path(self, docname: str, absolute: bool) -> str: + """Return the filename for the document name. + + If *absolute* is True, return as an absolute path. + Else, return as a relative path to the source directory. + """ + ... + + + diff --git a/typings/sphinx/pycode/__init__.pyi b/typings/sphinx/pycode/__init__.pyi new file mode 100644 index 0000000..6bb3dbc --- /dev/null +++ b/typings/sphinx/pycode/__init__.pyi @@ -0,0 +1,62 @@ +""" +This type stub file was generated by pyright. +""" + +import tokenize +from __future__ import annotations +from importlib import import_module +from os import path +from typing import Any, TYPE_CHECKING +from sphinx.errors import PycodeError +from sphinx.pycode.parser import Parser +from inspect import Signature + +"""Utilities parsing and analyzing Python code.""" +if TYPE_CHECKING: + ... +class ModuleAnalyzer: + annotations: dict[tuple[str, str], str] + attr_docs: dict[tuple[str, str], list[str]] + finals: list[str] + overloads: dict[str, list[Signature]] + tagorder: dict[str, int] + tags: dict[str, tuple[str, int, int]] + cache: dict[tuple[str, str], Any] = ... + @staticmethod + def get_module_source(modname: str) -> tuple[str | None, str | None]: + """Try to find the source code for a module. + + Returns ('filename', 'source'). One of it can be None if + no filename or source found + """ + ... + + @classmethod + def for_string(cls, string: str, modname: str, srcname: str = ...) -> ModuleAnalyzer: + ... + + @classmethod + def for_file(cls, filename: str, modname: str) -> ModuleAnalyzer: + ... + + @classmethod + def for_module(cls, modname: str) -> ModuleAnalyzer: + ... + + def __init__(self, source: str, modname: str, srcname: str) -> None: + ... + + def analyze(self) -> None: + """Analyze the source code.""" + ... + + def find_attr_docs(self) -> dict[tuple[str, str], list[str]]: + """Find class and module-level attributes and their documentation.""" + ... + + def find_tags(self) -> dict[str, tuple[str, int, int]]: + """Find class, function and method definitions and their location.""" + ... + + + diff --git a/typings/sphinx/pycode/ast.pyi b/typings/sphinx/pycode/ast.pyi new file mode 100644 index 0000000..ace10af --- /dev/null +++ b/typings/sphinx/pycode/ast.pyi @@ -0,0 +1,75 @@ +""" +This type stub file was generated by pyright. +""" + +import ast +from typing import overload + +"""Helpers for AST (Abstract Syntax Tree).""" +OPERATORS: dict[type[ast.AST], str] = ... +@overload +def unparse(node: None, code: str = ...) -> None: + ... + +@overload +def unparse(node: ast.AST, code: str = ...) -> str: + ... + +def unparse(node: ast.AST | None, code: str = ...) -> str | None: + """Unparse an AST to string.""" + ... + +class _UnparseVisitor(ast.NodeVisitor): + def __init__(self, code: str = ...) -> None: + ... + + def visit_arg(self, node: ast.arg) -> str: + ... + + def visit_arguments(self, node: ast.arguments) -> str: + ... + + def visit_Attribute(self, node: ast.Attribute) -> str: + ... + + def visit_BinOp(self, node: ast.BinOp) -> str: + ... + + def visit_BoolOp(self, node: ast.BoolOp) -> str: + ... + + def visit_Call(self, node: ast.Call) -> str: + ... + + def visit_Constant(self, node: ast.Constant) -> str: + ... + + def visit_Dict(self, node: ast.Dict) -> str: + ... + + def visit_Lambda(self, node: ast.Lambda) -> str: + ... + + def visit_List(self, node: ast.List) -> str: + ... + + def visit_Name(self, node: ast.Name) -> str: + ... + + def visit_Set(self, node: ast.Set) -> str: + ... + + def visit_Subscript(self, node: ast.Subscript) -> str: + ... + + def visit_UnaryOp(self, node: ast.UnaryOp) -> str: + ... + + def visit_Tuple(self, node: ast.Tuple) -> str: + ... + + def generic_visit(self, node): + ... + + + diff --git a/typings/sphinx/pycode/parser.pyi b/typings/sphinx/pycode/parser.pyi new file mode 100644 index 0000000..4ed04db --- /dev/null +++ b/typings/sphinx/pycode/parser.pyi @@ -0,0 +1,222 @@ +""" +This type stub file was generated by pyright. +""" + +import ast +from typing import Any + +"""Utilities parsing and analyzing Python code.""" +comment_re = ... +indent_re = ... +emptyline_re = ... +def filter_whitespace(code: str) -> str: + ... + +def get_assign_targets(node: ast.AST) -> list[ast.expr]: + """Get list of targets from Assign and AnnAssign node.""" + ... + +def get_lvar_names(node: ast.AST, self: ast.arg | None = ...) -> list[str]: + """Convert assignment-AST to variable names. + + This raises `TypeError` if the assignment does not create new variable:: + + ary[0] = 'foo' + dic["bar"] = 'baz' + # => TypeError + """ + ... + +def dedent_docstring(s: str) -> str: + """Remove common leading indentation from docstring.""" + ... + +class Token: + """Better token wrapper for tokenize module.""" + def __init__(self, kind: int, value: Any, start: tuple[int, int], end: tuple[int, int], source: str) -> None: + ... + + def __eq__(self, other: Any) -> bool: + ... + + def match(self, *conditions: Any) -> bool: + ... + + def __repr__(self) -> str: + ... + + + +class TokenProcessor: + def __init__(self, buffers: list[str]) -> None: + ... + + def get_line(self, lineno: int) -> str: + """Returns specified line.""" + ... + + def fetch_token(self) -> Token | None: + """Fetch the next token from source code. + + Returns ``None`` if sequence finished. + """ + ... + + def fetch_until(self, condition: Any) -> list[Token]: + """Fetch tokens until specified token appeared. + + .. note:: This also handles parenthesis well. + """ + ... + + + +class AfterCommentParser(TokenProcessor): + """Python source code parser to pick up comments after assignments. + + This parser takes code which starts with an assignment statement, + and returns the comment for the variable if one exists. + """ + def __init__(self, lines: list[str]) -> None: + ... + + def fetch_rvalue(self) -> list[Token]: + """Fetch right-hand value of assignment.""" + ... + + def parse(self) -> None: + """Parse the code and obtain comment after assignment.""" + ... + + + +class VariableCommentPicker(ast.NodeVisitor): + """Python source code parser to pick up variable comments.""" + def __init__(self, buffers: list[str], encoding: str) -> None: + ... + + def get_qualname_for(self, name: str) -> list[str] | None: + """Get qualified name for given object as a list of string(s).""" + ... + + def add_entry(self, name: str) -> None: + ... + + def add_final_entry(self, name: str) -> None: + ... + + def add_overload_entry(self, func: ast.FunctionDef) -> None: + ... + + def add_variable_comment(self, name: str, comment: str) -> None: + ... + + def add_variable_annotation(self, name: str, annotation: ast.AST) -> None: + ... + + def is_final(self, decorators: list[ast.expr]) -> bool: + ... + + def is_overload(self, decorators: list[ast.expr]) -> bool: + ... + + def get_self(self) -> ast.arg | None: + """Returns the name of the first argument if in a function.""" + ... + + def get_line(self, lineno: int) -> str: + """Returns specified line.""" + ... + + def visit(self, node: ast.AST) -> None: + """Updates self.previous to the given node.""" + ... + + def visit_Import(self, node: ast.Import) -> None: + """Handles Import node and record the order of definitions.""" + ... + + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: + """Handles Import node and record the order of definitions.""" + ... + + def visit_Assign(self, node: ast.Assign) -> None: + """Handles Assign node and pick up a variable comment.""" + ... + + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: + """Handles AnnAssign node and pick up a variable comment.""" + ... + + def visit_Expr(self, node: ast.Expr) -> None: + """Handles Expr node and pick up a comment if string.""" + ... + + def visit_Try(self, node: ast.Try) -> None: + """Handles Try node and processes body and else-clause. + + .. note:: pycode parser ignores objects definition in except-clause. + """ + ... + + def visit_ClassDef(self, node: ast.ClassDef) -> None: + """Handles ClassDef node and set context.""" + ... + + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: + """Handles FunctionDef node and set context.""" + ... + + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: + """Handles AsyncFunctionDef node and set context.""" + ... + + + +class DefinitionFinder(TokenProcessor): + """Python source code parser to detect location of functions, + classes and methods. + """ + def __init__(self, lines: list[str]) -> None: + ... + + def add_definition(self, name: str, entry: tuple[str, int, int]) -> None: + """Add a location of definition.""" + ... + + def parse(self) -> None: + """Parse the code to obtain location of definitions.""" + ... + + def parse_definition(self, typ: str) -> None: + """Parse AST of definition.""" + ... + + def finalize_block(self) -> None: + """Finalize definition block.""" + ... + + + +class Parser: + """Python source code parser to pick up variable comments. + + This is a better wrapper for ``VariableCommentPicker``. + """ + def __init__(self, code: str, encoding: str = ...) -> None: + ... + + def parse(self) -> None: + """Parse the source code.""" + ... + + def parse_comments(self) -> None: + """Parse the code and pick up comments.""" + ... + + def parse_definition(self) -> None: + """Parse the location of definitions from the code.""" + ... + + + diff --git a/typings/sphinx/pygments_styles.pyi b/typings/sphinx/pygments_styles.pyi new file mode 100644 index 0000000..5a04f4d --- /dev/null +++ b/typings/sphinx/pygments_styles.pyi @@ -0,0 +1,31 @@ +""" +This type stub file was generated by pyright. +""" + +from pygments.style import Style + +"""Sphinx theme specific highlighting styles.""" +class NoneStyle(Style): + """Style without any styling.""" + ... + + +class SphinxStyle(Style): + """ + Like friendly, but a bit darker to enhance contrast on the green + background. + """ + background_color = ... + default_style = ... + styles = ... + + +class PyramidStyle(Style): + """ + Pylons/pyramid pygments style based on friendly style, by Blaise Laflamme. + """ + background_color = ... + default_style = ... + styles = ... + + diff --git a/typings/sphinx/registry.pyi b/typings/sphinx/registry.pyi new file mode 100644 index 0000000..c4d3701 --- /dev/null +++ b/typings/sphinx/registry.pyi @@ -0,0 +1,153 @@ +""" +This type stub file was generated by pyright. +""" + +import sys +from typing import Any, Callable, TYPE_CHECKING +from sphinx.domains import Domain, Index +from sphinx.roles import XRefRole +from collections.abc import Iterator, Sequence +from docutils import nodes +from docutils.core import Publisher +from docutils.nodes import Element, Node, TextElement +from docutils.parsers import Parser +from docutils.parsers.rst import Directive +from docutils.transforms import Transform +from sphinx.application import Sphinx +from sphinx.builders import Builder +from sphinx.config import Config +from sphinx.environment import BuildEnvironment +from sphinx.ext.autodoc import Documenter +from sphinx.util.typing import RoleFunction, TitleGetter + +"""Sphinx component registry.""" +if sys.version_info >= (3, 10): + ... +else: + ... +if TYPE_CHECKING: + ... +logger = ... +EXTENSION_BLACKLIST = ... +class SphinxComponentRegistry: + def __init__(self) -> None: + ... + + def add_builder(self, builder: type[Builder], override: bool = ...) -> None: + ... + + def preload_builder(self, app: Sphinx, name: str) -> None: + ... + + def create_builder(self, app: Sphinx, name: str, env: BuildEnvironment) -> Builder: + ... + + def add_domain(self, domain: type[Domain], override: bool = ...) -> None: + ... + + def has_domain(self, domain: str) -> bool: + ... + + def create_domains(self, env: BuildEnvironment) -> Iterator[Domain]: + ... + + def add_directive_to_domain(self, domain: str, name: str, cls: type[Directive], override: bool = ...) -> None: + ... + + def add_role_to_domain(self, domain: str, name: str, role: RoleFunction | XRefRole, override: bool = ...) -> None: + ... + + def add_index_to_domain(self, domain: str, index: type[Index], override: bool = ...) -> None: + ... + + def add_object_type(self, directivename: str, rolename: str, indextemplate: str = ..., parse_node: Callable | None = ..., ref_nodeclass: type[TextElement] | None = ..., objname: str = ..., doc_field_types: Sequence = ..., override: bool = ...) -> None: + ... + + def add_crossref_type(self, directivename: str, rolename: str, indextemplate: str = ..., ref_nodeclass: type[TextElement] | None = ..., objname: str = ..., override: bool = ...) -> None: + ... + + def add_source_suffix(self, suffix: str, filetype: str, override: bool = ...) -> None: + ... + + def add_source_parser(self, parser: type[Parser], override: bool = ...) -> None: + ... + + def get_source_parser(self, filetype: str) -> type[Parser]: + ... + + def get_source_parsers(self) -> dict[str, type[Parser]]: + ... + + def create_source_parser(self, app: Sphinx, filename: str) -> Parser: + ... + + def add_translator(self, name: str, translator: type[nodes.NodeVisitor], override: bool = ...) -> None: + ... + + def add_translation_handlers(self, node: type[Element], **kwargs: tuple[Callable, Callable | None]) -> None: + ... + + def get_translator_class(self, builder: Builder) -> type[nodes.NodeVisitor]: + ... + + def create_translator(self, builder: Builder, *args: Any) -> nodes.NodeVisitor: + ... + + def add_transform(self, transform: type[Transform]) -> None: + ... + + def get_transforms(self) -> list[type[Transform]]: + ... + + def add_post_transform(self, transform: type[Transform]) -> None: + ... + + def get_post_transforms(self) -> list[type[Transform]]: + ... + + def add_documenter(self, objtype: str, documenter: type[Documenter]) -> None: + ... + + def add_autodoc_attrgetter(self, typ: type, attrgetter: Callable[[Any, str, Any], Any]) -> None: + ... + + def add_css_files(self, filename: str, **attributes: Any) -> None: + ... + + def add_js_file(self, filename: str | None, **attributes: Any) -> None: + ... + + def has_latex_package(self, name: str) -> bool: + ... + + def add_latex_package(self, name: str, options: str | None, after_hyperref: bool = ...) -> None: + ... + + def add_enumerable_node(self, node: type[Node], figtype: str, title_getter: TitleGetter | None = ..., override: bool = ...) -> None: + ... + + def add_html_math_renderer(self, name: str, inline_renderers: tuple[Callable, Callable | None] | None, block_renderers: tuple[Callable, Callable | None] | None) -> None: + ... + + def add_html_theme(self, name: str, theme_path: str) -> None: + ... + + def load_extension(self, app: Sphinx, extname: str) -> None: + """Load a Sphinx extension.""" + ... + + def get_envversion(self, app: Sphinx) -> dict[str, str]: + ... + + def get_publisher(self, app: Sphinx, filetype: str) -> Publisher: + ... + + + +def merge_source_suffix(app: Sphinx, config: Config) -> None: + """Merge any user-specified source_suffix with any added by extensions.""" + ... + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/roles.pyi b/typings/sphinx/roles.pyi new file mode 100644 index 0000000..e3add36 --- /dev/null +++ b/typings/sphinx/roles.pyi @@ -0,0 +1,142 @@ +""" +This type stub file was generated by pyright. +""" + +import docutils.parsers.rst.states +from typing import Any, TYPE_CHECKING +from docutils import nodes +from sphinx.util.docutils import ReferenceRole, SphinxRole +from collections.abc import Sequence +from docutils.nodes import Element, Node, TextElement, system_message +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import RoleFunction + +"""Handlers for additional ReST roles.""" +if TYPE_CHECKING: + ... +generic_docroles = ... +class XRefRole(ReferenceRole): + """ + A generic cross-referencing role. To create a callable that can be used as + a role function, create an instance of this class. + + The general features of this role are: + + * Automatic creation of a reference and a content node. + * Optional separation of title and target with `title `. + * The implementation is a class rather than a function to make + customization easier. + + Customization can be done in two ways: + + * Supplying constructor parameters: + * `fix_parens` to normalize parentheses (strip from target, and add to + title if configured) + * `lowercase` to lowercase the target + * `nodeclass` and `innernodeclass` select the node classes for + the reference and the content node + + * Subclassing and overwriting `process_link()` and/or `result_nodes()`. + """ + nodeclass: type[Element] = ... + innernodeclass: type[TextElement] = ... + def __init__(self, fix_parens: bool = ..., lowercase: bool = ..., nodeclass: type[Element] | None = ..., innernodeclass: type[TextElement] | None = ..., warn_dangling: bool = ...) -> None: + ... + + def update_title_and_target(self, title: str, target: str) -> tuple[str, str]: + ... + + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + def create_non_xref_node(self) -> tuple[list[Node], list[system_message]]: + ... + + def create_xref_node(self) -> tuple[list[Node], list[system_message]]: + ... + + def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str) -> tuple[str, str]: + """Called after parsing title and target text, and creating the + reference node (given in *refnode*). This method can alter the + reference node and must return a new (or the same) ``(title, target)`` + tuple. + """ + ... + + def result_nodes(self, document: nodes.document, env: BuildEnvironment, node: Element, is_ref: bool) -> tuple[list[Node], list[system_message]]: + """Called before returning the finished nodes. *node* is the reference + node if one was created (*is_ref* is then true), else the content node. + This method can add other nodes and must return a ``(nodes, messages)`` + tuple (the usual return value of a role function). + """ + ... + + + +class AnyXRefRole(XRefRole): + def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str) -> tuple[str, str]: + ... + + + +class PEP(ReferenceRole): + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + def build_uri(self) -> str: + ... + + + +class RFC(ReferenceRole): + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + def build_uri(self) -> str: + ... + + + +_amp_re = ... +class GUILabel(SphinxRole): + amp_re = ... + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + + +class MenuSelection(GUILabel): + BULLET_CHARACTER = ... + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + + +_litvar_re = ... +parens_re = ... +class EmphasizedLiteral(SphinxRole): + parens_re = ... + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + def parse(self, text: str) -> list[Node]: + ... + + + +_abbr_re = ... +class Abbreviation(SphinxRole): + abbr_re = ... + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + + +def code_role(name: str, rawtext: str, text: str, lineno: int, inliner: docutils.parsers.rst.states.Inliner, options: dict | None = ..., content: Sequence[str] = ...) -> tuple[list[Node], list[system_message]]: + ... + +specific_docroles: dict[str, RoleFunction] = ... +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/search/__init__.pyi b/typings/sphinx/search/__init__.pyi new file mode 100644 index 0000000..8d58b75 --- /dev/null +++ b/typings/sphinx/search/__init__.pyi @@ -0,0 +1,205 @@ +""" +This type stub file was generated by pyright. +""" + +import dataclasses +import functools +import html +import json +import pickle +import re +from __future__ import annotations +from importlib import import_module +from os import path +from typing import Any, IO, TYPE_CHECKING +from docutils import nodes +from docutils.nodes import Element, Node +from sphinx import addnodes, package_dir +from sphinx.environment import BuildEnvironment +from sphinx.util.index_entries import split_index_msg +from collections.abc import Iterable +from sphinx.search.en import SearchEnglish + +"""Create a full-text search index for offline search.""" +if TYPE_CHECKING: + ... +class SearchLanguage: + """ + This class is the base class for search natural language preprocessors. If + you want to add support for a new language, you should override the methods + of this class. + + You should override `lang` class property too (e.g. 'en', 'fr' and so on). + + .. attribute:: stopwords + + This is a set of stop words of the target language. Default `stopwords` + is empty. This word is used for building index and embedded in JS. + + .. attribute:: js_splitter_code + + Return splitter function of JavaScript version. The function should be + named as ``splitQuery``. And it should take a string and return list of + strings. + + .. versionadded:: 3.0 + + .. attribute:: js_stemmer_code + + Return stemmer class of JavaScript version. This class' name should be + ``Stemmer`` and this class must have ``stemWord`` method. This string is + embedded as-is in searchtools.js. + + This class is used to preprocess search word which Sphinx HTML readers + type, before searching index. Default implementation does nothing. + """ + lang: str | None = ... + language_name: str | None = ... + stopwords: set[str] = ... + js_splitter_code: str = ... + js_stemmer_rawcode: str | None = ... + js_stemmer_code = ... + _word_re = ... + def __init__(self, options: dict) -> None: + ... + + def init(self, options: dict) -> None: + """ + Initialize the class with the options the user has given. + """ + ... + + def split(self, input: str) -> list[str]: + """ + This method splits a sentence into words. Default splitter splits input + at white spaces, which should be enough for most languages except CJK + languages. + """ + ... + + def stem(self, word: str) -> str: + """ + This method implements stemming algorithm of the Python version. + + Default implementation does nothing. You should implement this if the + language has any stemming rules. + + This class is used to preprocess search words before registering them in + the search index. The stemming of the Python version and the JS version + (given in the js_stemmer_code attribute) must be compatible. + """ + ... + + def word_filter(self, word: str) -> bool: + """ + Return true if the target word should be registered in the search index. + This method is called after stemming. + """ + ... + + + +def parse_stop_word(source: str) -> set[str]: + """ + Parse snowball style word list like this: + + * http://snowball.tartarus.org/algorithms/finnish/stop.txt + """ + ... + +languages: dict[str, str | type[SearchLanguage]] = ... +class _JavaScriptIndex: + """ + The search index as JavaScript file that calls a function + on the documentation search object to register the index. + """ + PREFIX = ... + SUFFIX = ... + def dumps(self, data: Any) -> str: + ... + + def loads(self, s: str) -> Any: + ... + + def dump(self, data: Any, f: IO) -> None: + ... + + def load(self, f: IO) -> Any: + ... + + + +js_index = ... +@dataclasses.dataclass +class WordStore: + words: list[str] = ... + titles: list[tuple[str, str]] = ... + title_words: list[str] = ... + + +class WordCollector(nodes.NodeVisitor): + """ + A special visitor that collects words for the `IndexBuilder`. + """ + def __init__(self, document: nodes.document, lang: SearchLanguage) -> None: + ... + + def dispatch_visit(self, node: Node) -> None: + ... + + + +class IndexBuilder: + """ + Helper class that creates a search index based on the doctrees + passed to the `feed` method. + """ + formats = ... + def __init__(self, env: BuildEnvironment, lang: str, options: dict, scoring: str) -> None: + ... + + def load(self, stream: IO, format: Any) -> None: + """Reconstruct from frozen data.""" + ... + + def dump(self, stream: IO, format: Any) -> None: + """Dump the frozen index to a stream.""" + ... + + def get_objects(self, fn2index: dict[str, int]) -> dict[str, list[tuple[int, int, int, str, str]]]: + ... + + def get_terms(self, fn2index: dict) -> tuple[dict[str, list[str]], dict[str, list[str]]]: + ... + + def freeze(self) -> dict[str, Any]: + """Create a usable data structure for serializing.""" + ... + + def label(self) -> str: + ... + + def prune(self, docnames: Iterable[str]) -> None: + """Remove data for all docnames not in the list.""" + ... + + def feed(self, docname: str, filename: str, title: str, doctree: nodes.document) -> None: + """Feed a doctree to the index.""" + ... + + def context_for_searchtool(self) -> dict[str, Any]: + ... + + def get_js_stemmer_rawcodes(self) -> list[str]: + """Returns a list of non-minified stemmer JS files to copy.""" + ... + + def get_js_stemmer_rawcode(self) -> str | None: + ... + + def get_js_stemmer_code(self) -> str: + """Returns JS code that will be inserted into language_data.js.""" + ... + + + diff --git a/typings/sphinx/search/en.pyi b/typings/sphinx/search/en.pyi new file mode 100644 index 0000000..8b8d3fd --- /dev/null +++ b/typings/sphinx/search/en.pyi @@ -0,0 +1,22 @@ +""" +This type stub file was generated by pyright. +""" + +from sphinx.search import SearchLanguage + +"""English search language: includes the JS porter stemmer.""" +english_stopwords = ... +js_porter_stemmer = ... +class SearchEnglish(SearchLanguage): + lang = ... + language_name = ... + js_stemmer_code = ... + stopwords = ... + def init(self, options: dict) -> None: + ... + + def stem(self, word: str) -> str: + ... + + + diff --git a/typings/sphinx/testing/__init__.pyi b/typings/sphinx/testing/__init__.pyi new file mode 100644 index 0000000..89175cb --- /dev/null +++ b/typings/sphinx/testing/__init__.pyi @@ -0,0 +1,11 @@ +""" +This type stub file was generated by pyright. +""" + +"""Sphinx test utilities + +You can require sphinx.testing pytest fixtures in a test module or a conftest +file like this: + + pytest_plugins = 'sphinx.testing.fixtures' +""" diff --git a/typings/sphinx/theming.pyi b/typings/sphinx/theming.pyi new file mode 100644 index 0000000..33d576b --- /dev/null +++ b/typings/sphinx/theming.pyi @@ -0,0 +1,93 @@ +""" +This type stub file was generated by pyright. +""" + +import sys +from typing import Any, TYPE_CHECKING +from sphinx.application import Sphinx + +"""Theming support for HTML builders.""" +if sys.version_info >= (3, 10): + ... +else: + ... +if TYPE_CHECKING: + ... +logger = ... +NODEFAULT = ... +THEMECONF = ... +def extract_zip(filename: str, targetdir: str) -> None: + """Extract zip file to target directory.""" + ... + +class Theme: + """A Theme is a set of HTML templates and configurations. + + This class supports both theme directory and theme archive (zipped theme).""" + def __init__(self, name: str, theme_path: str, factory: HTMLThemeFactory) -> None: + ... + + def get_theme_dirs(self) -> list[str]: + """Return a list of theme directories, beginning with this theme's, + then the base theme's, then that one's base theme's, etc. + """ + ... + + def get_config(self, section: str, name: str, default: Any = ...) -> Any: + """Return the value for a theme configuration setting, searching the + base theme chain. + """ + ... + + def get_options(self, overrides: dict[str, Any] | None = ...) -> dict[str, Any]: + """Return a dictionary of theme options and their values.""" + ... + + def cleanup(self) -> None: + """Remove temporary directories.""" + ... + + + +def is_archived_theme(filename: str) -> bool: + """Check whether the specified file is an archived theme file or not.""" + ... + +class HTMLThemeFactory: + """A factory class for HTML Themes.""" + def __init__(self, app: Sphinx) -> None: + ... + + def load_builtin_themes(self) -> None: + """Load built-in themes.""" + ... + + def load_additional_themes(self, theme_paths: str) -> None: + """Load additional themes placed at specified directories.""" + ... + + def load_extra_theme(self, name: str) -> None: + """Try to load a theme with the specified name.""" + ... + + def load_alabaster_theme(self) -> None: + """Load alabaster theme.""" + ... + + def load_external_theme(self, name: str) -> None: + """Try to load a theme using entry_points. + + Sphinx refers to ``sphinx_themes`` entry_points. + """ + ... + + def find_themes(self, theme_path: str) -> dict[str, str]: + """Search themes from specified directory.""" + ... + + def create(self, name: str) -> Theme: + """Create an instance of theme.""" + ... + + + diff --git a/typings/sphinx/transforms/__init__.pyi b/typings/sphinx/transforms/__init__.pyi new file mode 100644 index 0000000..93189db --- /dev/null +++ b/typings/sphinx/transforms/__init__.pyi @@ -0,0 +1,266 @@ +""" +This type stub file was generated by pyright. +""" + +import re +import unicodedata +from __future__ import annotations +from typing import Any, TYPE_CHECKING, cast +from docutils import nodes +from docutils.transforms import Transform, Transformer +from docutils.transforms.parts import ContentsFilter +from docutils.transforms.universal import SmartQuotes +from docutils.utils import normalize_language_tag +from docutils.utils.smartquotes import smartchars +from sphinx import addnodes +from sphinx.locale import _, __ +from sphinx.util import logging +from sphinx.util.docutils import new_document +from sphinx.util.i18n import format_date +from sphinx.util.nodes import apply_source_workaround, is_smartquotable +from collections.abc import Generator +from docutils.nodes import Node, Text +from sphinx.application import Sphinx +from sphinx.config import Config +from sphinx.domains.std import StandardDomain +from sphinx.environment import BuildEnvironment + +"""Docutils transforms used by Sphinx when reading documents.""" +if TYPE_CHECKING: + ... +logger = ... +default_substitutions = ... +class SphinxTransform(Transform): + """A base class of Transforms. + + Compared with ``docutils.transforms.Transform``, this class improves accessibility to + Sphinx APIs. + """ + @property + def app(self) -> Sphinx: + """Reference to the :class:`.Sphinx` object.""" + ... + + @property + def env(self) -> BuildEnvironment: + """Reference to the :class:`.BuildEnvironment` object.""" + ... + + @property + def config(self) -> Config: + """Reference to the :class:`.Config` object.""" + ... + + + +class SphinxTransformer(Transformer): + """ + A transformer for Sphinx. + """ + document: nodes.document + env: BuildEnvironment | None = ... + def set_environment(self, env: BuildEnvironment) -> None: + ... + + def apply_transforms(self) -> None: + ... + + + +class DefaultSubstitutions(SphinxTransform): + """ + Replace some substitutions if they aren't defined in the document. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class MoveModuleTargets(SphinxTransform): + """ + Move module targets that are the first thing in a section to the section + title. + + XXX Python specific + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class HandleCodeBlocks(SphinxTransform): + """ + Several code block related transformations. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class AutoNumbering(SphinxTransform): + """ + Register IDs of tables, figures and literal_blocks to assign numbers. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class SortIds(SphinxTransform): + """ + Sort section IDs so that the "id[0-9]+" one comes last. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +TRANSLATABLE_NODES = ... +class ApplySourceWorkaround(SphinxTransform): + """ + Update source and rawsource attributes + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class AutoIndexUpgrader(SphinxTransform): + """ + Detect old style (4 column based indices) and automatically upgrade to new style. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class ExtraTranslatableNodes(SphinxTransform): + """ + Make nodes translatable + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class UnreferencedFootnotesDetector(SphinxTransform): + """ + Detect unreferenced footnotes and emit warnings + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class DoctestTransform(SphinxTransform): + """Set "doctest" style to each doctest_block node""" + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class FilterSystemMessages(SphinxTransform): + """Filter system messages from a doctree.""" + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class SphinxContentsFilter(ContentsFilter): + """ + Used with BuildEnvironment.add_toc_from() to discard cross-file links + within table-of-contents link nodes. + """ + visit_pending_xref = ... + def visit_image(self, node: nodes.image) -> None: + ... + + + +class SphinxSmartQuotes(SmartQuotes, SphinxTransform): + """ + Customized SmartQuotes to avoid transform for some extra node types. + + refs: sphinx.parsers.RSTParser + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + def is_available(self) -> bool: + ... + + def get_tokens(self, txtnodes: list[Text]) -> Generator[tuple[str, str], None, None]: + ... + + + +class DoctreeReadEvent(SphinxTransform): + """Emit :event:`doctree-read` event.""" + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class ManpageLink(SphinxTransform): + """Find manpage section numbers and names""" + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class GlossarySorter(SphinxTransform): + """Sort glossaries that have the ``sorted`` flag.""" + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class ReorderConsecutiveTargetAndIndexNodes(SphinxTransform): + """Index nodes interspersed between target nodes prevent other + Transformations from combining those target nodes, + e.g. ``PropagateTargets``. This transformation reorders them: + + Given the following ``document`` as input:: + + + + + + + + + + The transformed result will be:: + + + + + + + + + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/transforms/i18n.pyi b/typings/sphinx/transforms/i18n.pyi new file mode 100644 index 0000000..60c3d80 --- /dev/null +++ b/typings/sphinx/transforms/i18n.pyi @@ -0,0 +1,119 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING, TypeVar +from docutils import nodes +from sphinx.transforms import SphinxTransform +from collections.abc import Sequence +from sphinx.application import Sphinx +from sphinx.config import Config + +"""Docutils transforms used by Sphinx when reading documents.""" +if TYPE_CHECKING: + ... +logger = ... +EXCLUDED_PENDING_XREF_ATTRIBUTES = ... +N = TypeVar('N', bound=nodes.Node) +def publish_msgstr(app: Sphinx, source: str, source_path: str, source_line: int, config: Config, settings: Any) -> nodes.Element: + """Publish msgstr (single line) into docutils document + + :param sphinx.application.Sphinx app: sphinx application + :param str source: source text + :param str source_path: source path for warning indication + :param source_line: source line for warning indication + :param sphinx.config.Config config: sphinx config + :param docutils.frontend.Values settings: docutils settings + :return: document + :rtype: docutils.nodes.document + """ + ... + +def parse_noqa(source: str) -> tuple[str, bool]: + ... + +class PreserveTranslatableMessages(SphinxTransform): + """ + Preserve original translatable messages before translation + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class _NodeUpdater: + """Contains logic for updating one node with the translated content.""" + def __init__(self, node: nodes.Element, patch: nodes.Element, document: nodes.document, noqa: bool) -> None: + ... + + def compare_references(self, old_refs: Sequence[nodes.Element], new_refs: Sequence[nodes.Element], warning_msg: str) -> None: + """Warn about mismatches between references in original and translated content.""" + ... + + def update_title_mapping(self) -> bool: + ... + + def update_autofootnote_references(self) -> None: + ... + + def update_refnamed_references(self) -> None: + ... + + def update_refnamed_footnote_references(self) -> None: + ... + + def update_citation_references(self) -> None: + ... + + def update_pending_xrefs(self) -> None: + ... + + def update_leaves(self) -> None: + ... + + + +class Locale(SphinxTransform): + """ + Replace translatable nodes with their translated doctree. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class TranslationProgressTotaliser(SphinxTransform): + """ + Calculate the number of translated and untranslated nodes. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class AddTranslationClasses(SphinxTransform): + """ + Add ``translated`` or ``untranslated`` classes to indicate translation status. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +class RemoveTranslatableInline(SphinxTransform): + """ + Remove inline nodes used for translation as placeholders. + """ + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/transforms/post_transforms/__init__.pyi b/typings/sphinx/transforms/post_transforms/__init__.pyi new file mode 100644 index 0000000..797dbfe --- /dev/null +++ b/typings/sphinx/transforms/post_transforms/__init__.pyi @@ -0,0 +1,104 @@ +""" +This type stub file was generated by pyright. +""" + +import re +from __future__ import annotations +from typing import Any, TYPE_CHECKING, cast +from docutils import nodes +from docutils.nodes import Element, Node +from sphinx import addnodes +from sphinx.errors import NoUri +from sphinx.locale import __ +from sphinx.transforms import SphinxTransform +from sphinx.util import logging +from sphinx.util.docutils import SphinxTranslator +from sphinx.util.nodes import find_pending_xref_condition, process_only_nodes +from collections.abc import Sequence +from sphinx.addnodes import pending_xref +from sphinx.application import Sphinx +from sphinx.domains import Domain + +"""Docutils transforms used by Sphinx.""" +if TYPE_CHECKING: + ... +logger = ... +class SphinxPostTransform(SphinxTransform): + """A base class of post-transforms. + + Post transforms are invoked to modify the document to restructure it for outputting. + They resolve references, convert images, do special transformation for each output + formats and so on. This class helps to implement these post transforms. + """ + builders: tuple[str, ...] = ... + formats: tuple[str, ...] = ... + def apply(self, **kwargs: Any) -> None: + ... + + def is_supported(self) -> bool: + """Check this transform working for current builder.""" + ... + + def run(self, **kwargs: Any) -> None: + """Main method of post transforms. + + Subclasses should override this method instead of ``apply()``. + """ + ... + + + +class ReferencesResolver(SphinxPostTransform): + """ + Resolves cross-references on doctrees. + """ + default_priority = ... + def run(self, **kwargs: Any) -> None: + ... + + def resolve_anyref(self, refdoc: str, node: pending_xref, contnode: Element) -> Element | None: + """Resolve reference generated by the "any" role.""" + ... + + def warn_missing_reference(self, refdoc: str, typ: str, target: str, node: pending_xref, domain: Domain | None) -> None: + ... + + def find_pending_xref_condition(self, node: pending_xref, conditions: Sequence[str]) -> list[Node] | None: + ... + + + +class OnlyNodeTransform(SphinxPostTransform): + default_priority = ... + def run(self, **kwargs: Any) -> None: + ... + + + +class SigElementFallbackTransform(SphinxPostTransform): + """Fallback various desc_* nodes to inline if translator does not support them.""" + default_priority = ... + def run(self, **kwargs: Any) -> None: + ... + + def fallback(self, node_type: Any) -> None: + """Translate nodes of type *node_type* to docutils inline nodes. + + The original node type name is stored as a string in a private + ``_sig_node_type`` attribute if the latter did not exist. + """ + ... + + + +class PropagateDescDomain(SphinxPostTransform): + """Add the domain name of the parent node as a class in each desc_signature node.""" + default_priority = ... + def run(self, **kwargs: Any) -> None: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/transforms/references.pyi b/typings/sphinx/transforms/references.pyi new file mode 100644 index 0000000..bf6290f --- /dev/null +++ b/typings/sphinx/transforms/references.pyi @@ -0,0 +1,30 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils.transforms.references import DanglingReferences +from sphinx.transforms import SphinxTransform +from sphinx.application import Sphinx + +"""Docutils transforms used by Sphinx.""" +if TYPE_CHECKING: + ... +class SphinxDanglingReferences(DanglingReferences): + """DanglingReferences transform which does not output info messages.""" + def apply(self, **kwargs: Any) -> None: + ... + + + +class SphinxDomains(SphinxTransform): + """Collect objects to Sphinx domains for cross references.""" + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/util/__init__.pyi b/typings/sphinx/util/__init__.pyi new file mode 100644 index 0000000..51f21e2 --- /dev/null +++ b/typings/sphinx/util/__init__.pyi @@ -0,0 +1,121 @@ +""" +This type stub file was generated by pyright. +""" + +import hashlib +import os +import posixpath +import re +from __future__ import annotations +from importlib import import_module +from os import path +from typing import Any, IO +from urllib.parse import parse_qsl, quote_plus, urlencode, urlsplit, urlunsplit +from sphinx.errors import ExtensionError, FiletypeNotFoundError +from sphinx.locale import __ +from sphinx.util import display as _display, exceptions as _exceptions, http_date as _http_date, index_entries as _index_entries, logging, osutil as _osutil +from sphinx.util.console import strip_colors +from sphinx.util.matching import patfilter +from sphinx.util.nodes import caption_ref_re, explicit_title_re, nested_parse_with_titles, split_explicit_title +from sphinx.util.osutil import SEP, copyfile, copytimes, ensuredir, make_filename, mtimes_of_files, os_path, relative_uri + +"""Utility functions for Sphinx.""" +logger = ... +ws_re: re.Pattern[str] = ... +url_re: re.Pattern[str] = ... +def docname_join(basedocname: str, docname: str) -> str: + ... + +def get_filetype(source_suffix: dict[str, str], filename: str) -> str: + ... + +class FilenameUniqDict(dict): + """ + A dictionary that automatically generates unique names for its keys, + interpreted as filenames, and keeps track of a set of docnames they + appear in. Used for images and downloadable files in the environment. + """ + def __init__(self) -> None: + ... + + def add_file(self, docname: str, newfile: str) -> str: + ... + + def purge_doc(self, docname: str) -> None: + ... + + def merge_other(self, docnames: set[str], other: dict[str, tuple[set[str], Any]]) -> None: + ... + + def __getstate__(self) -> set[str]: + ... + + def __setstate__(self, state: set[str]) -> None: + ... + + + +class DownloadFiles(dict): + """A special dictionary for download files. + + .. important:: This class would be refactored in nearly future. + Hence don't hack this directly. + """ + def add_file(self, docname: str, filename: str) -> str: + ... + + def purge_doc(self, docname: str) -> None: + ... + + def merge_other(self, docnames: set[str], other: dict[str, tuple[set[str], Any]]) -> None: + ... + + + +_coding_re = ... +class UnicodeDecodeErrorHandler: + """Custom error handler for open() that warns and replaces.""" + def __init__(self, docname: str) -> None: + ... + + def __call__(self, error: UnicodeDecodeError) -> tuple[str, int]: + ... + + + +class Tee: + """ + File-like object writing to two streams. + """ + def __init__(self, stream1: IO, stream2: IO) -> None: + ... + + def write(self, text: str) -> None: + ... + + def flush(self) -> None: + ... + + + +def parselinenos(spec: str, total: int) -> list[int]: + """Parse a line number spec (such as "1,2,4-6") and return a list of + wanted line numbers. + """ + ... + +def import_object(objname: str, source: str | None = ...) -> Any: + """Import python object by qualname.""" + ... + +def encode_uri(uri: str) -> str: + ... + +def isurl(url: str) -> bool: + """Check *url* is URL or not.""" + ... + +_DEPRECATED_OBJECTS = ... +def __getattr__(name): # -> ((filepath: str | PathLike[str], /) -> str) | ((chunk: Any) -> str) | ((iterable: Unknown, summary: str, color: str = 'darkgreen', length: int = 0, verbosity: int = 0, stringify_func: ((Any) -> str) = display_chunk) -> Unknown) | type[SkipProgressMessage] | type[progress_message] | ((epoch: float) -> str) | ((rfc1123: str) -> float) | ((app: Sphinx | None, exc: BaseException) -> str) | ((x: int = 1) -> str) | (() -> Pattern[str]) | ((entry_type: str, value: str) -> list[str]) | ((data: bytes = b'', **_kw: Unknown) -> _Hash): + ... + diff --git a/typings/sphinx/util/_pathlib.pyi b/typings/sphinx/util/_pathlib.pyi new file mode 100644 index 0000000..9255925 --- /dev/null +++ b/typings/sphinx/util/_pathlib.pyi @@ -0,0 +1,44 @@ +""" +This type stub file was generated by pyright. +""" + +import sys +from pathlib import PosixPath + +"""What follows is awful and will be gone in Sphinx 8""" +_STR_METHODS = ... +_PATH_NAME = ... +_MSG = ... +if sys.platform == 'win32': + ... +else: + class _StrPath(PosixPath): + def replace(self, old, new, count=..., /): # -> str: + ... + + def __getattr__(self, item): # -> Any: + ... + + def __add__(self, other): + ... + + def __bool__(self): # -> bool: + ... + + def __contains__(self, item): # -> bool: + ... + + def __eq__(self, other) -> bool: + ... + + def __hash__(self) -> int: + ... + + def __getitem__(self, item): # -> str: + ... + + def __len__(self): # -> int: + ... + + + diff --git a/typings/sphinx/util/build_phase.pyi b/typings/sphinx/util/build_phase.pyi new file mode 100644 index 0000000..5addcaf --- /dev/null +++ b/typings/sphinx/util/build_phase.pyi @@ -0,0 +1,16 @@ +""" +This type stub file was generated by pyright. +""" + +from enum import IntEnum + +"""Build phase of Sphinx application.""" +class BuildPhase(IntEnum): + """Build phase of Sphinx application.""" + INITIALIZATION = ... + READING = ... + CONSISTENCY_CHECK = ... + RESOLVING = ... + WRITING = ... + + diff --git a/typings/sphinx/util/cfamily.pyi b/typings/sphinx/util/cfamily.pyi new file mode 100644 index 0000000..43da28e --- /dev/null +++ b/typings/sphinx/util/cfamily.pyi @@ -0,0 +1,192 @@ +""" +This type stub file was generated by pyright. +""" + +import re +from typing import Any, Callable, TYPE_CHECKING +from docutils import nodes +from docutils.nodes import TextElement +from sphinx.config import Config + +"""Utility functions common to the C and C++ domains.""" +if TYPE_CHECKING: + ... +logger = ... +StringifyTransform = Callable[[Any], str] +_whitespace_re = ... +anon_identifier_re = ... +identifier_re = ... +integer_literal_re = ... +octal_literal_re = ... +hex_literal_re = ... +binary_literal_re = ... +integers_literal_suffix_re = ... +float_literal_re = ... +float_literal_suffix_re = ... +char_literal_re = ... +def verify_description_mode(mode: str) -> None: + ... + +class NoOldIdError(Exception): + ... + + +class ASTBaseBase: + def __eq__(self, other: Any) -> bool: + ... + + __hash__ = ... + def clone(self) -> Any: + ... + + def __str__(self) -> str: + ... + + def get_display_string(self) -> str: + ... + + def __repr__(self) -> str: + ... + + + +class ASTAttribute(ASTBaseBase): + def describe_signature(self, signode: TextElement) -> None: + ... + + + +class ASTCPPAttribute(ASTAttribute): + def __init__(self, arg: str) -> None: + ... + + def describe_signature(self, signode: TextElement) -> None: + ... + + + +class ASTGnuAttribute(ASTBaseBase): + def __init__(self, name: str, args: ASTBaseParenExprList | None) -> None: + ... + + + +class ASTGnuAttributeList(ASTAttribute): + def __init__(self, attrs: list[ASTGnuAttribute]) -> None: + ... + + def describe_signature(self, signode: TextElement) -> None: + ... + + + +class ASTIdAttribute(ASTAttribute): + """For simple attributes defined by the user.""" + def __init__(self, id: str) -> None: + ... + + def describe_signature(self, signode: TextElement) -> None: + ... + + + +class ASTParenAttribute(ASTAttribute): + """For paren attributes defined by the user.""" + def __init__(self, id: str, arg: str) -> None: + ... + + def describe_signature(self, signode: TextElement) -> None: + ... + + + +class ASTAttributeList(ASTBaseBase): + def __init__(self, attrs: list[ASTAttribute]) -> None: + ... + + def __len__(self) -> int: + ... + + def __add__(self, other: ASTAttributeList) -> ASTAttributeList: + ... + + def describe_signature(self, signode: TextElement) -> None: + ... + + + +class ASTBaseParenExprList(ASTBaseBase): + ... + + +class UnsupportedMultiCharacterCharLiteral(Exception): + ... + + +class DefinitionError(Exception): + ... + + +class BaseParser: + def __init__(self, definition: str, *, location: nodes.Node | tuple[str, int] | str, config: Config) -> None: + ... + + @property + def language(self) -> str: + ... + + def status(self, msg: str) -> None: + ... + + def fail(self, msg: str) -> None: + ... + + def warn(self, msg: str) -> None: + ... + + def match(self, regex: re.Pattern[str]) -> bool: + ... + + def skip_string(self, string: str) -> bool: + ... + + def skip_word(self, word: str) -> bool: + ... + + def skip_ws(self) -> bool: + ... + + def skip_word_and_ws(self, word: str) -> bool: + ... + + def skip_string_and_ws(self, string: str) -> bool: + ... + + @property + def eof(self) -> bool: + ... + + @property + def current_char(self) -> str: + ... + + @property + def matched_text(self) -> str: + ... + + def read_rest(self) -> str: + ... + + def assert_end(self, *, allowSemicolon: bool = ...) -> None: + ... + + @property + def id_attributes(self): + ... + + @property + def paren_attributes(self): + ... + + + diff --git a/typings/sphinx/util/console.pyi b/typings/sphinx/util/console.pyi new file mode 100644 index 0000000..18d29bb --- /dev/null +++ b/typings/sphinx/util/console.pyi @@ -0,0 +1,42 @@ +""" +This type stub file was generated by pyright. +""" + +import re + +"""Format colored console output.""" +_ansi_re: re.Pattern[str] = ... +codes: dict[str, str] = ... +def terminal_safe(s: str) -> str: + """Safely encode a string for printing to the terminal.""" + ... + +def get_terminal_width() -> int: + """Return the width of the terminal in columns.""" + ... + +_tw: int = ... +def term_width_line(text: str) -> str: + ... + +def color_terminal() -> bool: + ... + +def nocolor() -> None: + ... + +def coloron() -> None: + ... + +def colorize(name: str, text: str, input_mode: bool = ...) -> str: + ... + +def strip_colors(s: str) -> str: + ... + +def create_color_func(name: str) -> None: + ... + +_attrs = ... +_colors = ... +_orig_codes = ... diff --git a/typings/sphinx/util/display.pyi b/typings/sphinx/util/display.pyi new file mode 100644 index 0000000..6e51725 --- /dev/null +++ b/typings/sphinx/util/display.pyi @@ -0,0 +1,35 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, TypeVar + +if False: + ... +logger = ... +def display_chunk(chunk: Any) -> str: + ... + +T = TypeVar('T') +def status_iterator(iterable: Iterable[T], summary: str, color: str = ..., length: int = ..., verbosity: int = ..., stringify_func: Callable[[Any], str] = ...) -> Iterator[T]: + ... + +class SkipProgressMessage(Exception): + ... + + +class progress_message: + def __init__(self, message: str) -> None: + ... + + def __enter__(self) -> None: + ... + + def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> bool: + ... + + def __call__(self, f: Callable) -> Callable: + ... + + + diff --git a/typings/sphinx/util/docfields.pyi b/typings/sphinx/util/docfields.pyi new file mode 100644 index 0000000..f1a98ab --- /dev/null +++ b/typings/sphinx/util/docfields.pyi @@ -0,0 +1,123 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from docutils import nodes +from docutils.nodes import Element, Node +from sphinx import addnodes +from docutils.parsers.rst.states import Inliner +from sphinx.directives import ObjectDescription +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import TextlikeNode + +"""Utility code for "Doc fields". + +"Doc fields" are reST field lists in object descriptions that will +be domain-specifically transformed to a more appealing presentation. +""" +if TYPE_CHECKING: + ... +logger = ... +class Field: + """A doc field that is never grouped. It can have an argument or not, the + argument can be linked using a specified *rolename*. Field should be used + for doc fields that usually don't occur more than once. + + The body can be linked using a specified *bodyrolename* if the content is + just a single inline or text node. + + Example:: + + :returns: description of the return value + :rtype: description of the return type + """ + is_grouped = ... + is_typed = ... + def __init__(self, name: str, names: tuple[str, ...] = ..., label: str = ..., has_arg: bool = ..., rolename: str = ..., bodyrolename: str = ...) -> None: + ... + + def make_xref(self, rolename: str, domain: str, target: str, innernode: type[TextlikeNode] = ..., contnode: Node | None = ..., env: BuildEnvironment | None = ..., inliner: Inliner | None = ..., location: Element | None = ...) -> Node: + ... + + def make_xrefs(self, rolename: str, domain: str, target: str, innernode: type[TextlikeNode] = ..., contnode: Node | None = ..., env: BuildEnvironment | None = ..., inliner: Inliner | None = ..., location: Element | None = ...) -> list[Node]: + ... + + def make_entry(self, fieldarg: str, content: list[Node]) -> tuple[str, list[Node]]: + ... + + def make_field(self, types: dict[str, list[Node]], domain: str, item: tuple, env: BuildEnvironment | None = ..., inliner: Inliner | None = ..., location: Element | None = ...) -> nodes.field: + ... + + + +class GroupedField(Field): + """ + A doc field that is grouped; i.e., all fields of that type will be + transformed into one field with its body being a bulleted list. It always + has an argument. The argument can be linked using the given *rolename*. + GroupedField should be used for doc fields that can occur more than once. + If *can_collapse* is true, this field will revert to a Field if only used + once. + + Example:: + + :raises ErrorClass: description when it is raised + """ + is_grouped = ... + list_type = nodes.bullet_list + def __init__(self, name: str, names: tuple[str, ...] = ..., label: str = ..., rolename: str = ..., can_collapse: bool = ...) -> None: + ... + + def make_field(self, types: dict[str, list[Node]], domain: str, items: tuple, env: BuildEnvironment | None = ..., inliner: Inliner | None = ..., location: Element | None = ...) -> nodes.field: + ... + + + +class TypedField(GroupedField): + """ + A doc field that is grouped and has type information for the arguments. It + always has an argument. The argument can be linked using the given + *rolename*, the type using the given *typerolename*. + + Two uses are possible: either parameter and type description are given + separately, using a field from *names* and one from *typenames*, + respectively, or both are given using a field from *names*, see the example. + + Example:: + + :param foo: description of parameter foo + :type foo: SomeClass + + -- or -- + + :param SomeClass foo: description of parameter foo + """ + is_typed = ... + def __init__(self, name: str, names: tuple[str, ...] = ..., typenames: tuple[str, ...] = ..., label: str = ..., rolename: str = ..., typerolename: str = ..., can_collapse: bool = ...) -> None: + ... + + def make_field(self, types: dict[str, list[Node]], domain: str, items: tuple, env: BuildEnvironment | None = ..., inliner: Inliner | None = ..., location: Element | None = ...) -> nodes.field: + ... + + + +class DocFieldTransformer: + """ + Transforms field lists in "doc field" syntax into better-looking + equivalents, using the field type definitions given on a domain. + """ + typemap: dict[str, tuple[Field, bool]] + def __init__(self, directive: ObjectDescription) -> None: + ... + + def transform_all(self, node: addnodes.desc_content) -> None: + """Transform all field list children of a node.""" + ... + + def transform(self, node: nodes.field_list) -> None: + """Transform a single field list *node*.""" + ... + + + diff --git a/typings/sphinx/util/docstrings.pyi b/typings/sphinx/util/docstrings.pyi new file mode 100644 index 0000000..e50c876 --- /dev/null +++ b/typings/sphinx/util/docstrings.pyi @@ -0,0 +1,26 @@ +""" +This type stub file was generated by pyright. +""" + +"""Utilities for docstring processing.""" +field_list_item_re = ... +def separate_metadata(s: str | None) -> tuple[str | None, dict[str, str]]: + """Separate docstring into metadata and others.""" + ... + +def prepare_docstring(s: str, tabsize: int = ...) -> list[str]: + """Convert a docstring into lines of parseable reST. Remove common leading + indentation, where the indentation of the first line is ignored. + + Return the docstring as a list of lines usable for inserting into a docutils + ViewList (used as argument of nested_parse().) An empty line is added to + act as a separator between this docstring and following content. + """ + ... + +def prepare_commentdoc(s: str) -> list[str]: + """Extract documentation comment lines (starting with #:) and return them + as a list of lines. Returns an empty list if there is no documentation. + """ + ... + diff --git a/typings/sphinx/util/docutils.pyi b/typings/sphinx/util/docutils.pyi new file mode 100644 index 0000000..8054a0e --- /dev/null +++ b/typings/sphinx/util/docutils.pyi @@ -0,0 +1,355 @@ +""" +This type stub file was generated by pyright. +""" + +from collections.abc import Generator, Sequence +from contextlib import contextmanager +from typing import Any, TYPE_CHECKING +from docutils import nodes +from docutils.io import FileOutput +from docutils.parsers.rst import Directive +from docutils.parsers.rst.states import Inliner +from docutils.statemachine import State, StringList +from docutils.utils import Reporter +from types import ModuleType +from docutils.frontend import Values +from docutils.nodes import Element, Node, system_message +from sphinx.builders import Builder +from sphinx.config import Config +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import RoleFunction + +"""Utility functions for docutils.""" +logger = ... +report_re = ... +if TYPE_CHECKING: + ... +_DEPRECATED_OBJECTS = ... +def __getattr__(name): # -> VersionInfo: + ... + +additional_nodes: set[type[Element]] = ... +@contextmanager +def docutils_namespace() -> Generator[None, None, None]: + """Create namespace for reST parsers.""" + ... + +def is_directive_registered(name: str) -> bool: + """Check the *name* directive is already registered.""" + ... + +def register_directive(name: str, directive: type[Directive]) -> None: + """Register a directive to docutils. + + This modifies global state of docutils. So it is better to use this + inside ``docutils_namespace()`` to prevent side-effects. + """ + ... + +def is_role_registered(name: str) -> bool: + """Check the *name* role is already registered.""" + ... + +def register_role(name: str, role: RoleFunction) -> None: + """Register a role to docutils. + + This modifies global state of docutils. So it is better to use this + inside ``docutils_namespace()`` to prevent side-effects. + """ + ... + +def unregister_role(name: str) -> None: + """Unregister a role from docutils.""" + ... + +def is_node_registered(node: type[Element]) -> bool: + """Check the *node* is already registered.""" + ... + +def register_node(node: type[Element]) -> None: + """Register a node to docutils. + + This modifies global state of some visitors. So it is better to use this + inside ``docutils_namespace()`` to prevent side-effects. + """ + ... + +def unregister_node(node: type[Element]) -> None: + """Unregister a node from docutils. + + This is inverse of ``nodes._add_nodes_class_names()``. + """ + ... + +@contextmanager +def patched_get_language() -> Generator[None, None, None]: + """Patch docutils.languages.get_language() temporarily. + + This ignores the second argument ``reporter`` to suppress warnings. + refs: https://github.com/sphinx-doc/sphinx/issues/3788 + """ + ... + +@contextmanager +def patched_rst_get_language() -> Generator[None, None, None]: + """Patch docutils.parsers.rst.languages.get_language(). + Starting from docutils 0.17, get_language() in ``rst.languages`` + also has a reporter, which needs to be disabled temporarily. + + This should also work for old versions of docutils, + because reporter is none by default. + + refs: https://github.com/sphinx-doc/sphinx/issues/10179 + """ + ... + +@contextmanager +def using_user_docutils_conf(confdir: str | None) -> Generator[None, None, None]: + """Let docutils know the location of ``docutils.conf`` for Sphinx.""" + ... + +@contextmanager +def du19_footnotes() -> Generator[None, None, None]: + ... + +@contextmanager +def patch_docutils(confdir: str | None = ...) -> Generator[None, None, None]: + """Patch to docutils temporarily.""" + ... + +class CustomReSTDispatcher: + """Custom reST's mark-up dispatcher. + + This replaces docutils's directives and roles dispatch mechanism for reST parser + by original one temporarily. + """ + def __init__(self) -> None: + ... + + def __enter__(self) -> None: + ... + + def __exit__(self, exc_type: type[Exception], exc_value: Exception, traceback: Any) -> None: + ... + + def enable(self) -> None: + ... + + def disable(self) -> None: + ... + + def directive(self, directive_name: str, language_module: ModuleType, document: nodes.document) -> tuple[type[Directive] | None, list[system_message]]: + ... + + def role(self, role_name: str, language_module: ModuleType, lineno: int, reporter: Reporter) -> tuple[RoleFunction, list[system_message]]: + ... + + + +class ElementLookupError(Exception): + ... + + +class sphinx_domains(CustomReSTDispatcher): + """Monkey-patch directive and role dispatch, so that domain-specific + markup takes precedence. + """ + def __init__(self, env: BuildEnvironment) -> None: + ... + + def lookup_domain_element(self, type: str, name: str) -> Any: + """Lookup a markup element (directive or role), given its name which can + be a full name (with domain). + """ + ... + + def directive(self, directive_name: str, language_module: ModuleType, document: nodes.document) -> tuple[type[Directive] | None, list[system_message]]: + ... + + def role(self, role_name: str, language_module: ModuleType, lineno: int, reporter: Reporter) -> tuple[RoleFunction, list[system_message]]: + ... + + + +class WarningStream: + def write(self, text: str) -> None: + ... + + + +class LoggingReporter(Reporter): + @classmethod + def from_reporter(cls, reporter: Reporter) -> LoggingReporter: + """Create an instance of LoggingReporter from other reporter object.""" + ... + + def __init__(self, source: str, report_level: int = ..., halt_level: int = ..., debug: bool = ..., error_handler: str = ...) -> None: + ... + + + +class NullReporter(Reporter): + """A dummy reporter; write nothing.""" + def __init__(self) -> None: + ... + + + +@contextmanager +def switch_source_input(state: State, content: StringList) -> Generator[None, None, None]: + """Switch current source input of state temporarily.""" + ... + +class SphinxFileOutput(FileOutput): + """Better FileOutput class for Sphinx.""" + def __init__(self, **kwargs: Any) -> None: + ... + + def write(self, data: str) -> str: + ... + + + +class SphinxDirective(Directive): + """A base class for Sphinx directives. + + This class provides helper methods for Sphinx directives. + + .. note:: The subclasses of this class might not work with docutils. + This class is strongly coupled with Sphinx. + """ + @property + def env(self) -> BuildEnvironment: + """Reference to the :class:`.BuildEnvironment` object.""" + ... + + @property + def config(self) -> Config: + """Reference to the :class:`.Config` object.""" + ... + + def get_source_info(self) -> tuple[str, int]: + """Get source and line number.""" + ... + + def set_source_info(self, node: Node) -> None: + """Set source and line number to the node.""" + ... + + def get_location(self) -> str: + """Get current location info for logging.""" + ... + + + +class SphinxRole: + """A base class for Sphinx roles. + + This class provides helper methods for Sphinx roles. + + .. note:: The subclasses of this class might not work with docutils. + This class is strongly coupled with Sphinx. + """ + name: str + rawtext: str + text: str + lineno: int + inliner: Inliner + options: dict[str, Any] + content: Sequence[str] + def __call__(self, name: str, rawtext: str, text: str, lineno: int, inliner: Inliner, options: dict | None = ..., content: Sequence[str] = ...) -> tuple[list[Node], list[system_message]]: + ... + + def run(self) -> tuple[list[Node], list[system_message]]: + ... + + @property + def env(self) -> BuildEnvironment: + """Reference to the :class:`.BuildEnvironment` object.""" + ... + + @property + def config(self) -> Config: + """Reference to the :class:`.Config` object.""" + ... + + def get_source_info(self, lineno: int | None = ...) -> tuple[str, int]: + ... + + def set_source_info(self, node: Node, lineno: int | None = ...) -> None: + ... + + def get_location(self) -> str: + """Get current location info for logging.""" + ... + + + +class ReferenceRole(SphinxRole): + """A base class for reference roles. + + The reference roles can accept ``link title `` style as a text for + the role. The parsed result; link title and target will be stored to + ``self.title`` and ``self.target``. + """ + has_explicit_title: bool + disabled: bool + title: str + target: str + explicit_title_re = ... + def __call__(self, name: str, rawtext: str, text: str, lineno: int, inliner: Inliner, options: dict | None = ..., content: Sequence[str] = ...) -> tuple[list[Node], list[system_message]]: + ... + + + +class SphinxTranslator(nodes.NodeVisitor): + """A base class for Sphinx translators. + + This class adds a support for visitor/departure method for super node class + if visitor/departure method for node class is not found. + + It also provides helper methods for Sphinx translators. + + .. note:: The subclasses of this class might not work with docutils. + This class is strongly coupled with Sphinx. + """ + def __init__(self, document: nodes.document, builder: Builder) -> None: + ... + + def dispatch_visit(self, node: Node) -> None: + """ + Dispatch node to appropriate visitor method. + The priority of visitor method is: + + 1. ``self.visit_{node_class}()`` + 2. ``self.visit_{super_node_class}()`` + 3. ``self.unknown_visit()`` + """ + ... + + def dispatch_departure(self, node: Node) -> None: + """ + Dispatch node to appropriate departure method. + The priority of departure method is: + + 1. ``self.depart_{node_class}()`` + 2. ``self.depart_{super_node_class}()`` + 3. ``self.unknown_departure()`` + """ + ... + + def unknown_visit(self, node: Node) -> None: + ... + + + +__document_cache__: tuple[Values, Reporter] +def new_document(source_path: str, settings: Any = ...) -> nodes.document: + """Return a new empty document object. This is an alternative of docutils'. + + This is a simple wrapper for ``docutils.utils.new_document()``. It + caches the result of docutils' and use it on second call for instantiation. + This makes an instantiation of document nodes much faster. + """ + ... + diff --git a/typings/sphinx/util/exceptions.pyi b/typings/sphinx/util/exceptions.pyi new file mode 100644 index 0000000..988e1b3 --- /dev/null +++ b/typings/sphinx/util/exceptions.pyi @@ -0,0 +1,17 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from sphinx.application import Sphinx + +if TYPE_CHECKING: + ... +def save_traceback(app: Sphinx | None, exc: BaseException) -> str: + """Save the given exception's traceback in a temporary file.""" + ... + +def format_exception_cut_frames(x: int = ...) -> str: + """Format an exception with traceback, but only the last x frames.""" + ... + diff --git a/typings/sphinx/util/fileutil.pyi b/typings/sphinx/util/fileutil.pyi new file mode 100644 index 0000000..bcf7cad --- /dev/null +++ b/typings/sphinx/util/fileutil.pyi @@ -0,0 +1,40 @@ +""" +This type stub file was generated by pyright. +""" + +import os +from typing import Callable, TYPE_CHECKING +from sphinx.util.template import BaseRenderer +from sphinx.util.typing import PathMatcher + +"""File utility functions for Sphinx.""" +if TYPE_CHECKING: + ... +def copy_asset_file(source: str | os.PathLike[str], destination: str | os.PathLike[str], context: dict | None = ..., renderer: BaseRenderer | None = ...) -> None: + """Copy an asset file to destination. + + On copying, it expands the template variables if context argument is given and + the asset is a template file. + + :param source: The path to source file + :param destination: The path to destination file or directory + :param context: The template variables. If not given, template files are simply copied + :param renderer: The template engine. If not given, SphinxRenderer is used by default + """ + ... + +def copy_asset(source: str | os.PathLike[str], destination: str | os.PathLike[str], excluded: PathMatcher = ..., context: dict | None = ..., renderer: BaseRenderer | None = ..., onerror: Callable[[str, Exception], None] | None = ...) -> None: + """Copy asset files to destination recursively. + + On copying, it expands the template variables if context argument is given and + the asset is a template file. + + :param source: The path to source file or directory + :param destination: The path to destination directory + :param excluded: The matcher to determine the given path should be copied or not + :param context: The template variables. If not given, template files are simply copied + :param renderer: The template engine. If not given, SphinxRenderer is used by default + :param onerror: The error handler. + """ + ... + diff --git a/typings/sphinx/util/http_date.pyi b/typings/sphinx/util/http_date.pyi new file mode 100644 index 0000000..346537f --- /dev/null +++ b/typings/sphinx/util/http_date.pyi @@ -0,0 +1,17 @@ +""" +This type stub file was generated by pyright. +""" + +"""Convert times to and from HTTP-date serialisations. + +Reference: https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 +""" +_GMT_OFFSET = ... +def epoch_to_rfc1123(epoch: float) -> str: + """Return HTTP-date string from epoch offset.""" + ... + +def rfc1123_to_epoch(rfc1123: str) -> float: + """Return epoch offset from HTTP-date string.""" + ... + diff --git a/typings/sphinx/util/i18n.pyi b/typings/sphinx/util/i18n.pyi new file mode 100644 index 0000000..c831896 --- /dev/null +++ b/typings/sphinx/util/i18n.pyi @@ -0,0 +1,83 @@ +""" +This type stub file was generated by pyright. +""" + +import os +from datetime import datetime +from typing import Callable, NamedTuple, TYPE_CHECKING +from collections.abc import Generator +from sphinx.environment import BuildEnvironment + +"""Builder superclass for all builders.""" +if TYPE_CHECKING: + ... +logger = ... +class LocaleFileInfoBase(NamedTuple): + base_dir: str + domain: str + charset: str + ... + + +class CatalogInfo(LocaleFileInfoBase): + @property + def po_file(self) -> str: + ... + + @property + def mo_file(self) -> str: + ... + + @property + def po_path(self) -> str: + ... + + @property + def mo_path(self) -> str: + ... + + def is_outdated(self) -> bool: + ... + + def write_mo(self, locale: str, use_fuzzy: bool = ...) -> None: + ... + + + +class CatalogRepository: + """A repository for message catalogs.""" + def __init__(self, basedir: str | os.PathLike[str], locale_dirs: list[str], language: str, encoding: str) -> None: + ... + + @property + def locale_dirs(self) -> Generator[str, None, None]: + ... + + @property + def pofiles(self) -> Generator[tuple[str, str], None, None]: + ... + + @property + def catalogs(self) -> Generator[CatalogInfo, None, None]: + ... + + + +def docname_to_domain(docname: str, compaction: bool | str) -> str: + """Convert docname to domain for catalogs.""" + ... + +date_format_mappings = ... +date_format_re = ... +def babel_format_date(date: datetime, format: str, locale: str, formatter: Callable = ...) -> str: + ... + +def format_date(format: str, *, date: datetime | None = ..., language: str) -> str: + ... + +def get_image_filename_for_language(filename: str | os.PathLike[str], env: BuildEnvironment) -> str: + ... + +def search_image_for_language(filename: str, env: BuildEnvironment) -> str: + ... + diff --git a/typings/sphinx/util/images.pyi b/typings/sphinx/util/images.pyi new file mode 100644 index 0000000..b8612c3 --- /dev/null +++ b/typings/sphinx/util/images.pyi @@ -0,0 +1,39 @@ +""" +This type stub file was generated by pyright. +""" + +from os import PathLike +from typing import NamedTuple, TYPE_CHECKING, overload + +"""Image utility functions for Sphinx.""" +if TYPE_CHECKING: + ... +mime_suffixes = ... +_suffix_from_mime = ... +class DataURI(NamedTuple): + mimetype: str + charset: str + data: bytes + ... + + +def get_image_size(filename: str) -> tuple[int, int] | None: + ... + +@overload +def guess_mimetype(filename: PathLike[str] | str, default: str) -> str: + ... + +@overload +def guess_mimetype(filename: PathLike[str] | str, default: None = ...) -> str | None: + ... + +def guess_mimetype(filename: PathLike[str] | str = ..., default: str | None = ...) -> str | None: + ... + +def get_image_extension(mimetype: str) -> str | None: + ... + +def parse_data_uri(uri: str) -> DataURI | None: + ... + diff --git a/typings/sphinx/util/index_entries.pyi b/typings/sphinx/util/index_entries.pyi new file mode 100644 index 0000000..2c15e24 --- /dev/null +++ b/typings/sphinx/util/index_entries.pyi @@ -0,0 +1,7 @@ +""" +This type stub file was generated by pyright. +""" + +def split_index_msg(entry_type: str, value: str) -> list[str]: + ... + diff --git a/typings/sphinx/util/inspect.pyi b/typings/sphinx/util/inspect.pyi new file mode 100644 index 0000000..137da50 --- /dev/null +++ b/typings/sphinx/util/inspect.pyi @@ -0,0 +1,260 @@ +""" +This type stub file was generated by pyright. +""" + +import ast +import inspect +from collections.abc import Mapping, Sequence +from types import MethodType +from typing import Any, Callable + +"""Helpers for inspecting Python modules.""" +logger = ... +memory_address_re = ... +def unwrap(obj: Any) -> Any: + """Get an original object from wrapped object (wrapped functions).""" + ... + +def unwrap_all(obj: Any, *, stop: Callable | None = ...) -> Any: + """ + Get an original object from wrapped object (unwrapping partials, wrapped + functions, and other decorators). + """ + ... + +def getall(obj: Any) -> Sequence[str] | None: + """Get __all__ attribute of the module as dict. + + Return None if given *obj* does not have __all__. + Raises ValueError if given *obj* have invalid __all__. + """ + ... + +def getannotations(obj: Any) -> Mapping[str, Any]: + """Get __annotations__ from given *obj* safely.""" + ... + +def getglobals(obj: Any) -> Mapping[str, Any]: + """Get __globals__ from given *obj* safely.""" + ... + +def getmro(obj: Any) -> tuple[type, ...]: + """Get __mro__ from given *obj* safely.""" + ... + +def getorigbases(obj: Any) -> tuple[Any, ...] | None: + """Get __orig_bases__ from *obj* safely.""" + ... + +def getslots(obj: Any) -> dict[str, Any] | None: + """Get __slots__ attribute of the class as dict. + + Return None if gienv *obj* does not have __slots__. + Raises TypeError if given *obj* is not a class. + Raises ValueError if given *obj* have invalid __slots__. + """ + ... + +def isNewType(obj: Any) -> bool: + """Check the if object is a kind of NewType.""" + ... + +def isenumclass(x: Any) -> bool: + """Check if the object is subclass of enum.""" + ... + +def isenumattribute(x: Any) -> bool: + """Check if the object is attribute of enum.""" + ... + +def unpartial(obj: Any) -> Any: + """Get an original object from partial object. + + This returns given object itself if not partial. + """ + ... + +def ispartial(obj: Any) -> bool: + """Check if the object is partial.""" + ... + +def isclassmethod(obj: Any, cls: Any = ..., name: str | None = ...) -> bool: + """Check if the object is classmethod.""" + ... + +def isstaticmethod(obj: Any, cls: Any = ..., name: str | None = ...) -> bool: + """Check if the object is staticmethod.""" + ... + +def isdescriptor(x: Any) -> bool: + """Check if the object is some kind of descriptor.""" + ... + +def isabstractmethod(obj: Any) -> bool: + """Check if the object is an abstractmethod.""" + ... + +def isboundmethod(method: MethodType) -> bool: + """Check if the method is a bound method.""" + ... + +def is_cython_function_or_method(obj: Any) -> bool: + """Check if the object is a function or method in cython.""" + ... + +def isattributedescriptor(obj: Any) -> bool: + """Check if the object is an attribute like descriptor.""" + ... + +def is_singledispatch_function(obj: Any) -> bool: + """Check if the object is singledispatch function.""" + ... + +def is_singledispatch_method(obj: Any) -> bool: + """Check if the object is singledispatch method.""" + ... + +def isfunction(obj: Any) -> bool: + """Check if the object is function.""" + ... + +def isbuiltin(obj: Any) -> bool: + """Check if the object is function.""" + ... + +def isroutine(obj: Any) -> bool: + """Check is any kind of function or method.""" + ... + +def iscoroutinefunction(obj: Any) -> bool: + """Check if the object is coroutine-function.""" + ... + +def isproperty(obj: Any) -> bool: + """Check if the object is property.""" + ... + +def isgenericalias(obj: Any) -> bool: + """Check if the object is GenericAlias.""" + ... + +def safe_getattr(obj: Any, name: str, *defargs: Any) -> Any: + """A getattr() that turns all exceptions into AttributeErrors.""" + ... + +def object_description(obj: Any, *, _seen: frozenset = ...) -> str: + """A repr() implementation that returns text safe to use in reST context. + + Maintains a set of 'seen' object IDs to detect and avoid infinite recursion. + """ + ... + +def is_builtin_class_method(obj: Any, attr_name: str) -> bool: + """If attr_name is implemented at builtin class, return True. + + >>> is_builtin_class_method(int, '__init__') + True + + Why this function needed? CPython implements int.__init__ by Descriptor + but PyPy implements it by pure Python code. + """ + ... + +class DefaultValue: + """A simple wrapper for default value of the parameters of overload functions.""" + def __init__(self, value: str) -> None: + ... + + def __eq__(self, other: object) -> bool: + ... + + def __repr__(self) -> str: + ... + + + +class TypeAliasForwardRef: + """Pseudo typing class for autodoc_type_aliases. + + This avoids the error on evaluating the type inside `get_type_hints()`. + """ + def __init__(self, name: str) -> None: + ... + + def __call__(self) -> None: + ... + + def __eq__(self, other: Any) -> bool: + ... + + def __hash__(self) -> int: + ... + + def __repr__(self) -> str: + ... + + + +class TypeAliasModule: + """Pseudo module class for autodoc_type_aliases.""" + def __init__(self, modname: str, mapping: dict[str, str]) -> None: + ... + + def __getattr__(self, name: str) -> Any: + ... + + + +class TypeAliasNamespace(dict[str, Any]): + """Pseudo namespace class for autodoc_type_aliases. + + This enables to look up nested modules and classes like `mod1.mod2.Class`. + """ + def __init__(self, mapping: dict[str, str]) -> None: + ... + + def __getitem__(self, key: str) -> Any: + ... + + + +def signature(subject: Callable, bound_method: bool = ..., type_aliases: dict | None = ...) -> inspect.Signature: + """Return a Signature object for the given *subject*. + + :param bound_method: Specify *subject* is a bound method or not + """ + ... + +def evaluate_signature(sig: inspect.Signature, globalns: dict | None = ..., localns: dict | None = ...) -> inspect.Signature: + """Evaluate unresolved type annotations in a signature object.""" + ... + +def stringify_signature(sig: inspect.Signature, show_annotation: bool = ..., show_return_annotation: bool = ..., unqualified_typehints: bool = ...) -> str: + """Stringify a Signature object. + + :param show_annotation: If enabled, show annotations on the signature + :param show_return_annotation: If enabled, show annotation of the return value + :param unqualified_typehints: If enabled, show annotations as unqualified + (ex. io.StringIO -> StringIO) + """ + ... + +def signature_from_str(signature: str) -> inspect.Signature: + """Create a Signature object from string.""" + ... + +def signature_from_ast(node: ast.FunctionDef, code: str = ...) -> inspect.Signature: + """Create a Signature object from AST *node*.""" + ... + +def getdoc(obj: Any, attrgetter: Callable = ..., allow_inherited: bool = ..., cls: Any = ..., name: str | None = ...) -> str | None: + """Get the docstring for the object. + + This tries to obtain the docstring for some kind of objects additionally: + + * partial functions + * inherited docstring + * inherited decorated methods + """ + ... + diff --git a/typings/sphinx/util/inventory.pyi b/typings/sphinx/util/inventory.pyi new file mode 100644 index 0000000..e720506 --- /dev/null +++ b/typings/sphinx/util/inventory.pyi @@ -0,0 +1,59 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Callable, IO, TYPE_CHECKING +from collections.abc import Iterator +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.typing import Inventory + +"""Inventory utility functions for Sphinx.""" +BUFSIZE = ... +logger = ... +if TYPE_CHECKING: + ... +class InventoryFileReader: + """A file reader for an inventory file. + + This reader supports mixture of texts and compressed texts. + """ + def __init__(self, stream: IO) -> None: + ... + + def read_buffer(self) -> None: + ... + + def readline(self) -> str: + ... + + def readlines(self) -> Iterator[str]: + ... + + def read_compressed_chunks(self) -> Iterator[bytes]: + ... + + def read_compressed_lines(self) -> Iterator[str]: + ... + + + +class InventoryFile: + @classmethod + def load(cls, stream: IO, uri: str, joinfunc: Callable) -> Inventory: + ... + + @classmethod + def load_v1(cls, stream: InventoryFileReader, uri: str, join: Callable) -> Inventory: + ... + + @classmethod + def load_v2(cls, stream: InventoryFileReader, uri: str, join: Callable) -> Inventory: + ... + + @classmethod + def dump(cls, filename: str, env: BuildEnvironment, builder: Builder) -> None: + ... + + + diff --git a/typings/sphinx/util/logging.pyi b/typings/sphinx/util/logging.pyi new file mode 100644 index 0000000..cceaaef --- /dev/null +++ b/typings/sphinx/util/logging.pyi @@ -0,0 +1,295 @@ +""" +This type stub file was generated by pyright. +""" + +import logging +import logging.handlers +from collections import defaultdict +from contextlib import contextmanager +from typing import Any, IO, TYPE_CHECKING +from collections.abc import Generator +from docutils.nodes import Node +from sphinx.application import Sphinx + +"""Logging utility functions for Sphinx.""" +if TYPE_CHECKING: + ... +NAMESPACE = ... +VERBOSE = ... +LEVEL_NAMES: defaultdict[str, int] = ... +VERBOSITY_MAP: defaultdict[int, int] = ... +COLOR_MAP: defaultdict[int, str] = ... +def getLogger(name: str) -> SphinxLoggerAdapter: + """Get logger wrapped by :class:`sphinx.util.logging.SphinxLoggerAdapter`. + + Sphinx logger always uses ``sphinx.*`` namespace to be independent from + settings of root logger. It ensures logging is consistent even if a + third-party extension or imported application resets logger settings. + + Example usage:: + + >>> from sphinx.util import logging + >>> logger = logging.getLogger(__name__) + >>> logger.info('Hello, this is an extension!') + Hello, this is an extension! + """ + ... + +def convert_serializable(records: list[logging.LogRecord]) -> None: + """Convert LogRecord serializable.""" + ... + +class SphinxLogRecord(logging.LogRecord): + """Log record class supporting location""" + prefix = ... + location: Any = ... + def getMessage(self) -> str: + ... + + + +class SphinxInfoLogRecord(SphinxLogRecord): + """Info log record class supporting location""" + prefix = ... + + +class SphinxWarningLogRecord(SphinxLogRecord): + """Warning log record class supporting location""" + @property + def prefix(self) -> str: + ... + + + +class SphinxLoggerAdapter(logging.LoggerAdapter): + """LoggerAdapter allowing ``type`` and ``subtype`` keywords.""" + KEYWORDS = ... + logger: logging.Logger + def log(self, level: int | str, msg: str, *args: Any, **kwargs: Any) -> None: + ... + + def verbose(self, msg: str, *args: Any, **kwargs: Any) -> None: + ... + + def process(self, msg: str, kwargs: dict) -> tuple[str, dict]: + ... + + def handle(self, record: logging.LogRecord) -> None: + ... + + + +class WarningStreamHandler(logging.StreamHandler): + """StreamHandler for warnings.""" + ... + + +class NewLineStreamHandler(logging.StreamHandler): + """StreamHandler which switches line terminator by record.nonl flag.""" + def emit(self, record: logging.LogRecord) -> None: + ... + + + +class MemoryHandler(logging.handlers.BufferingHandler): + """Handler buffering all logs.""" + buffer: list[logging.LogRecord] + def __init__(self) -> None: + ... + + def shouldFlush(self, record: logging.LogRecord) -> bool: + ... + + def flush(self) -> None: + ... + + def flushTo(self, logger: logging.Logger) -> None: + ... + + def clear(self) -> list[logging.LogRecord]: + ... + + + +@contextmanager +def pending_warnings() -> Generator[logging.Handler, None, None]: + """Context manager to postpone logging warnings temporarily. + + Similar to :func:`pending_logging`. + """ + ... + +@contextmanager +def suppress_logging() -> Generator[MemoryHandler, None, None]: + """Context manager to suppress logging all logs temporarily. + + For example:: + + >>> with suppress_logging(): + >>> logger.warning('Warning message!') # suppressed + >>> some_long_process() + >>> + """ + ... + +@contextmanager +def pending_logging() -> Generator[MemoryHandler, None, None]: + """Context manager to postpone logging all logs temporarily. + + For example:: + + >>> with pending_logging(): + >>> logger.warning('Warning message!') # not flushed yet + >>> some_long_process() + >>> + Warning message! # the warning is flushed here + """ + ... + +@contextmanager +def skip_warningiserror(skip: bool = ...) -> Generator[None, None, None]: + """Context manager to skip WarningIsErrorFilter temporarily.""" + ... + +@contextmanager +def prefixed_warnings(prefix: str) -> Generator[None, None, None]: + """Context manager to prepend prefix to all warning log records temporarily. + + For example:: + + >>> with prefixed_warnings("prefix:"): + >>> logger.warning('Warning message!') # => prefix: Warning message! + + .. versionadded:: 2.0 + """ + ... + +class LogCollector: + def __init__(self) -> None: + ... + + @contextmanager + def collect(self) -> Generator[None, None, None]: + ... + + + +class InfoFilter(logging.Filter): + """Filter error and warning messages.""" + def filter(self, record: logging.LogRecord) -> bool: + ... + + + +def is_suppressed_warning(type: str, subtype: str, suppress_warnings: list[str]) -> bool: + """Check whether the warning is suppressed or not.""" + ... + +class WarningSuppressor(logging.Filter): + """Filter logs by `suppress_warnings`.""" + def __init__(self, app: Sphinx) -> None: + ... + + def filter(self, record: logging.LogRecord) -> bool: + ... + + + +class WarningIsErrorFilter(logging.Filter): + """Raise exception if warning emitted.""" + def __init__(self, app: Sphinx) -> None: + ... + + def filter(self, record: logging.LogRecord) -> bool: + ... + + + +class DisableWarningIsErrorFilter(logging.Filter): + """Disable WarningIsErrorFilter if this filter installed.""" + def filter(self, record: logging.LogRecord) -> bool: + ... + + + +class MessagePrefixFilter(logging.Filter): + """Prepend prefix to all log records.""" + def __init__(self, prefix: str) -> None: + ... + + def filter(self, record: logging.LogRecord) -> bool: + ... + + + +class OnceFilter(logging.Filter): + """Show the message only once.""" + def __init__(self, name: str = ...) -> None: + ... + + def filter(self, record: logging.LogRecord) -> bool: + ... + + + +class SphinxLogRecordTranslator(logging.Filter): + """Converts a log record to one Sphinx expects + + * Make a instance of SphinxLogRecord + * docname to path if location given + """ + LogRecordClass: type[logging.LogRecord] + def __init__(self, app: Sphinx) -> None: + ... + + def filter(self, record: SphinxWarningLogRecord) -> bool: + ... + + + +class InfoLogRecordTranslator(SphinxLogRecordTranslator): + """LogRecordTranslator for INFO level log records.""" + LogRecordClass = SphinxInfoLogRecord + + +class WarningLogRecordTranslator(SphinxLogRecordTranslator): + """LogRecordTranslator for WARNING level log records.""" + LogRecordClass = SphinxWarningLogRecord + + +def get_node_location(node: Node) -> str | None: + ... + +class ColorizeFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + ... + + + +class SafeEncodingWriter: + """Stream writer which ignores UnicodeEncodeError silently""" + def __init__(self, stream: IO) -> None: + ... + + def write(self, data: str) -> None: + ... + + def flush(self) -> None: + ... + + + +class LastMessagesWriter: + """Stream writer storing last 10 messages in memory to save trackback""" + def __init__(self, app: Sphinx, stream: IO) -> None: + ... + + def write(self, data: str) -> None: + ... + + + +def setup(app: Sphinx, status: IO, warning: IO) -> None: + """Setup root logger for Sphinx""" + ... + diff --git a/typings/sphinx/util/matching.pyi b/typings/sphinx/util/matching.pyi new file mode 100644 index 0000000..806efce --- /dev/null +++ b/typings/sphinx/util/matching.pyi @@ -0,0 +1,58 @@ +""" +This type stub file was generated by pyright. +""" + +import re +from typing import Callable, TYPE_CHECKING +from collections.abc import Iterable, Iterator + +"""Pattern-matching utility functions for Sphinx.""" +if TYPE_CHECKING: + ... +def compile_matchers(patterns: Iterable[str]) -> list[Callable[[str], re.Match[str] | None]]: + ... + +class Matcher: + """A pattern matcher for Multiple shell-style glob patterns. + + Note: this modifies the patterns to work with copy_asset(). + For example, "**/index.rst" matches with "index.rst" + """ + def __init__(self, exclude_patterns: Iterable[str]) -> None: + ... + + def __call__(self, string: str) -> bool: + ... + + def match(self, string: str) -> bool: + ... + + + +DOTFILES = ... +_pat_cache: dict[str, re.Pattern[str]] = ... +def patmatch(name: str, pat: str) -> re.Match[str] | None: + """Return if name matches the regular expression (pattern) + ``pat```. Adapted from fnmatch module.""" + ... + +def patfilter(names: Iterable[str], pat: str) -> list[str]: + """Return the subset of the list ``names`` that match + the regular expression (pattern) ``pat``. + + Adapted from fnmatch module. + """ + ... + +def get_matching_files(dirname: str | os.PathLike[str], include_patterns: Iterable[str] = ..., exclude_patterns: Iterable[str] = ...) -> Iterator[str]: + """Get all file names in a directory, recursively. + + Filter file names by the glob-style include_patterns and exclude_patterns. + The default values include all files ("**") and exclude nothing (""). + + Only files matching some pattern in *include_patterns* are included, and + exclusions from *exclude_patterns* take priority over inclusions. + + """ + ... + diff --git a/typings/sphinx/util/math.pyi b/typings/sphinx/util/math.pyi new file mode 100644 index 0000000..48b19e3 --- /dev/null +++ b/typings/sphinx/util/math.pyi @@ -0,0 +1,17 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from docutils import nodes +from sphinx.builders.html import HTML5Translator + +"""Utility functions for math.""" +if TYPE_CHECKING: + ... +def get_node_equation_number(writer: HTML5Translator, node: nodes.math_block) -> str: + ... + +def wrap_displaymath(text: str, label: str | None, numbering: bool) -> str: + ... + diff --git a/typings/sphinx/util/nodes.pyi b/typings/sphinx/util/nodes.pyi new file mode 100644 index 0000000..d1409f1 --- /dev/null +++ b/typings/sphinx/util/nodes.pyi @@ -0,0 +1,168 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, TYPE_CHECKING +from docutils import nodes +from sphinx import addnodes +from collections.abc import Iterable +from docutils.nodes import Element, Node +from docutils.parsers.rst import Directive +from docutils.parsers.rst.states import Inliner +from docutils.statemachine import StringList +from sphinx.builders import Builder +from sphinx.environment import BuildEnvironment +from sphinx.util.tags import Tags + +"""Docutils node-related utility functions for Sphinx.""" +if TYPE_CHECKING: + ... +logger = ... +explicit_title_re = ... +caption_ref_re = ... +class NodeMatcher: + """A helper class for Node.findall(). + + It checks that the given node is an instance of the specified node-classes and + has the specified node-attributes. + + For example, following example searches ``reference`` node having ``refdomain`` + and ``reftype`` attributes:: + + matcher = NodeMatcher(nodes.reference, refdomain='std', reftype='citation') + doctree.findall(matcher) + # => [, , ...] + + A special value ``typing.Any`` matches any kind of node-attributes. For example, + following example searches ``reference`` node having ``refdomain`` attributes:: + + from __future__ import annotations +from typing import TYPE_CHECKING, Any + matcher = NodeMatcher(nodes.reference, refdomain=Any) + doctree.findall(matcher) + # => [, , ...] + """ + def __init__(self, *node_classes: type[Node], **attrs: Any) -> None: + ... + + def match(self, node: Node) -> bool: + ... + + def __call__(self, node: Node) -> bool: + ... + + + +def get_full_module_name(node: Node) -> str: + """ + Return full module dotted path like: 'docutils.nodes.paragraph' + + :param nodes.Node node: target node + :return: full module dotted path + """ + ... + +def repr_domxml(node: Node, length: int = ...) -> str: + """ + return DOM XML representation of the specified node like: + 'New in version...' + + :param nodes.Node node: target node + :param int length: + length of return value to be striped. if false-value is specified, repr_domxml + returns full of DOM XML representation. + :return: DOM XML representation + """ + ... + +def apply_source_workaround(node: Element) -> None: + ... + +IGNORED_NODES = ... +def is_translatable(node: Node) -> bool: + ... + +LITERAL_TYPE_NODES = ... +IMAGE_TYPE_NODES = ... +def extract_messages(doctree: Element) -> Iterable[tuple[Element, str]]: + """Extract translatable messages from a document tree.""" + ... + +def get_node_source(node: Element) -> str: + ... + +def get_node_line(node: Element) -> int: + ... + +def traverse_parent(node: Element, cls: Any = ...) -> Iterable[Element]: + ... + +def get_prev_node(node: Node) -> Node | None: + ... + +def traverse_translatable_index(doctree: Element) -> Iterable[tuple[Element, list[tuple[str, str, str, str, str | None]]]]: + """Traverse translatable index node from a document tree.""" + ... + +def nested_parse_with_titles(state: Any, content: StringList, node: Node, content_offset: int = ...) -> str: + """Version of state.nested_parse() that allows titles and does not require + titles to have the same decoration as the calling document. + + This is useful when the parsed content comes from a completely different + context, such as docstrings. + """ + ... + +def clean_astext(node: Element) -> str: + """Like node.astext(), but ignore images.""" + ... + +def split_explicit_title(text: str) -> tuple[bool, str, str]: + """Split role content into title and target, if given.""" + ... + +indextypes = ... +def process_index_entry(entry: str, targetid: str) -> list[tuple[str, str, str, str, str | None]]: + ... + +def inline_all_toctrees(builder: Builder, docnameset: set[str], docname: str, tree: nodes.document, colorfunc: Callable, traversed: list[str]) -> nodes.document: + """Inline all toctrees in the *tree*. + + Record all docnames in *docnameset*, and output docnames with *colorfunc*. + """ + ... + +_non_id_chars = ... +_non_id_at_ends = ... +_non_id_translate = ... +_non_id_translate_digraphs = ... +def make_id(env: BuildEnvironment, document: nodes.document, prefix: str = ..., term: str | None = ...) -> str: + """Generate an appropriate node_id for given *prefix* and *term*.""" + ... + +def find_pending_xref_condition(node: addnodes.pending_xref, condition: str) -> Element | None: + """Pick matched pending_xref_condition node up from the pending_xref.""" + ... + +def make_refnode(builder: Builder, fromdocname: str, todocname: str, targetid: str | None, child: Node | list[Node], title: str | None = ...) -> nodes.reference: + """Shortcut to create a reference node.""" + ... + +def set_source_info(directive: Directive, node: Node) -> None: + ... + +def set_role_source_info(inliner: Inliner, lineno: int, node: Node) -> None: + ... + +def copy_source_info(src: Element, dst: Element) -> None: + ... + +NON_SMARTQUOTABLE_PARENT_NODES = ... +def is_smartquotable(node: Node) -> bool: + """Check whether the node is smart-quotable or not.""" + ... + +def process_only_nodes(document: Node, tags: Tags) -> None: + """Filter ``only`` nodes which do not match *tags*.""" + ... + diff --git a/typings/sphinx/util/osutil.pyi b/typings/sphinx/util/osutil.pyi new file mode 100644 index 0000000..b53b488 --- /dev/null +++ b/typings/sphinx/util/osutil.pyi @@ -0,0 +1,118 @@ +""" +This type stub file was generated by pyright. +""" + +import contextlib +import os +from typing import Any, TYPE_CHECKING +from collections.abc import Iterator + +"""Operating system-related utility functions for Sphinx.""" +if TYPE_CHECKING: + ... +SEP = ... +def os_path(canonical_path: str, /) -> str: + ... + +def canon_path(native_path: str | os.PathLike[str], /) -> str: + """Return path in OS-independent form""" + ... + +def path_stabilize(filepath: str | os.PathLike[str], /) -> str: + "Normalize path separator and unicode string" + ... + +def relative_uri(base: str, to: str) -> str: + """Return a relative URL from ``base`` to ``to``.""" + ... + +def ensuredir(file: str | os.PathLike[str]) -> None: + """Ensure that a path exists.""" + ... + +def mtimes_of_files(dirnames: list[str], suffix: str) -> Iterator[float]: + ... + +def copytimes(source: str | os.PathLike[str], dest: str | os.PathLike[str]) -> None: + """Copy a file's modification times.""" + ... + +def copyfile(source: str | os.PathLike[str], dest: str | os.PathLike[str]) -> None: + """Copy a file and its modification times, if possible. + + Note: ``copyfile`` skips copying if the file has not been changed""" + ... + +no_fn_re = ... +project_suffix_re = ... +def make_filename(string: str) -> str: + ... + +def make_filename_from_project(project: str) -> str: + ... + +def relpath(path: str | os.PathLike[str], start: str | os.PathLike[str] | None = ...) -> str: + """Return a relative filepath to *path* either from the current directory or + from an optional *start* directory. + + This is an alternative of ``os.path.relpath()``. This returns original path + if *path* and *start* are on different drives (for Windows platform). + """ + ... + +safe_relpath = ... +fs_encoding = ... +abspath = ... +class _chdir: + """Remove this fall-back once support for Python 3.10 is removed.""" + def __init__(self, target_dir: str, /) -> None: + ... + + def __enter__(self): # -> None: + ... + + def __exit__(self, _exc_type, _exc_value, _traceback, /): # -> None: + ... + + + +@contextlib.contextmanager +def cd(target_dir: str) -> Iterator[None]: + ... + +class FileAvoidWrite: + """File-like object that buffers output and only writes if content changed. + + Use this class like when writing to a file to avoid touching the original + file if the content hasn't changed. This is useful in scenarios where file + mtime is used to invalidate caches or trigger new behavior. + + When writing to this file handle, all writes are buffered until the object + is closed. + + Objects can be used as context managers. + """ + def __init__(self, path: str) -> None: + ... + + def write(self, data: str) -> None: + ... + + def close(self) -> None: + """Stop accepting writes and write file, if needed.""" + ... + + def __enter__(self) -> FileAvoidWrite: + ... + + def __exit__(self, exc_type: type[Exception], exc_value: Exception, traceback: Any) -> bool: + ... + + def __getattr__(self, name: str) -> Any: + ... + + + +def rmtree(path: str) -> None: + ... + diff --git a/typings/sphinx/util/parallel.pyi b/typings/sphinx/util/parallel.pyi new file mode 100644 index 0000000..bff691f --- /dev/null +++ b/typings/sphinx/util/parallel.pyi @@ -0,0 +1,45 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, Callable, TYPE_CHECKING +from collections.abc import Sequence + +"""Parallel building utilities.""" +HAS_MULTIPROCESSING = ... +if TYPE_CHECKING: + ... +logger = ... +parallel_available = ... +class SerialTasks: + """Has the same interface as ParallelTasks, but executes tasks directly.""" + def __init__(self, nproc: int = ...) -> None: + ... + + def add_task(self, task_func: Callable, arg: Any = ..., result_func: Callable | None = ...) -> None: + ... + + def join(self) -> None: + ... + + + +class ParallelTasks: + """Executes *nproc* tasks in parallel after forking.""" + def __init__(self, nproc: int) -> None: + ... + + def add_task(self, task_func: Callable, arg: Any = ..., result_func: Callable | None = ...) -> None: + ... + + def join(self) -> None: + ... + + def terminate(self) -> None: + ... + + + +def make_chunks(arguments: Sequence[str], nproc: int, maxbatch: int = ...) -> list[Any]: + ... + diff --git a/typings/sphinx/util/rst.pyi b/typings/sphinx/util/rst.pyi new file mode 100644 index 0000000..a3de811 --- /dev/null +++ b/typings/sphinx/util/rst.pyi @@ -0,0 +1,42 @@ +""" +This type stub file was generated by pyright. +""" + +from contextlib import contextmanager +from typing import TYPE_CHECKING +from jinja2 import Environment, pass_environment +from collections.abc import Generator +from docutils.statemachine import StringList + +"""reST helper functions.""" +if TYPE_CHECKING: + ... +logger = ... +FIELD_NAME_RE = ... +symbols_re = ... +SECTIONING_CHARS = ... +WIDECHARS: dict[str, str] = ... +def escape(text: str) -> str: + ... + +def textwidth(text: str, widechars: str = ...) -> int: + """Get width of text.""" + ... + +@pass_environment +def heading(env: Environment, text: str, level: int = ...) -> str: + """Create a heading for *level*.""" + ... + +@contextmanager +def default_role(docname: str, name: str) -> Generator[None, None, None]: + ... + +def prepend_prolog(content: StringList, prolog: str) -> None: + """Prepend a string to content body as prolog.""" + ... + +def append_epilog(content: StringList, epilog: str) -> None: + """Append a string to content body as epilog.""" + ... + diff --git a/typings/sphinx/util/tags.pyi b/typings/sphinx/util/tags.pyi new file mode 100644 index 0000000..b1941cd --- /dev/null +++ b/typings/sphinx/util/tags.pyi @@ -0,0 +1,43 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from jinja2.parser import Parser +from collections.abc import Iterator +from jinja2.nodes import Node + +if TYPE_CHECKING: + ... +env = ... +class BooleanParser(Parser): + """ + Only allow condition exprs and/or/not operations. + """ + def parse_compare(self) -> Node: + ... + + + +class Tags: + def __init__(self, tags: list[str] | None = ...) -> None: + ... + + def has(self, tag: str) -> bool: + ... + + __contains__ = ... + def __iter__(self) -> Iterator[str]: + ... + + def add(self, tag: str) -> None: + ... + + def remove(self, tag: str) -> None: + ... + + def eval_condition(self, condition: str) -> bool: + ... + + + diff --git a/typings/sphinx/util/template.pyi b/typings/sphinx/util/template.pyi new file mode 100644 index 0000000..edb2f03 --- /dev/null +++ b/typings/sphinx/util/template.pyi @@ -0,0 +1,67 @@ +""" +This type stub file was generated by pyright. +""" + +import os +from typing import Any, Callable, TYPE_CHECKING +from jinja2.loaders import BaseLoader +from collections.abc import Sequence +from jinja2.environment import Environment + +"""Templates utility functions for Sphinx.""" +if TYPE_CHECKING: + ... +class BaseRenderer: + def __init__(self, loader: BaseLoader | None = ...) -> None: + ... + + def render(self, template_name: str, context: dict[str, Any]) -> str: + ... + + def render_string(self, source: str, context: dict[str, Any]) -> str: + ... + + + +class FileRenderer(BaseRenderer): + def __init__(self, search_path: Sequence[str | os.PathLike[str]]) -> None: + ... + + @classmethod + def render_from_file(cls, filename: str, context: dict[str, Any]) -> str: + ... + + + +class SphinxRenderer(FileRenderer): + def __init__(self, template_path: Sequence[str | os.PathLike[str]] | None = ...) -> None: + ... + + @classmethod + def render_from_file(cls, filename: str, context: dict[str, Any]) -> str: + ... + + + +class LaTeXRenderer(SphinxRenderer): + def __init__(self, template_path: Sequence[str | os.PathLike[str]] | None = ..., latex_engine: str | None = ...) -> None: + ... + + + +class ReSTRenderer(SphinxRenderer): + def __init__(self, template_path: Sequence[str | os.PathLike[str]] | None = ..., language: str | None = ...) -> None: + ... + + + +class SphinxTemplateLoader(BaseLoader): + """A loader supporting template inheritance""" + def __init__(self, confdir: str | os.PathLike[str], templates_paths: Sequence[str | os.PathLike[str]], system_templates_paths: Sequence[str | os.PathLike[str]]) -> None: + ... + + def get_source(self, environment: Environment, template: str) -> tuple[str, str, Callable]: + ... + + + diff --git a/typings/sphinx/util/texescape.pyi b/typings/sphinx/util/texescape.pyi new file mode 100644 index 0000000..9737c95 --- /dev/null +++ b/typings/sphinx/util/texescape.pyi @@ -0,0 +1,28 @@ +""" +This type stub file was generated by pyright. +""" + +"""TeX escaping helper.""" +tex_replacements = ... +ascii_tex_replacements = ... +unicode_tex_replacements = ... +tex_replace_map: dict[int, str] = ... +_tex_escape_map: dict[int, str] = ... +_tex_escape_map_without_unicode: dict[int, str] = ... +_tex_hlescape_map: dict[int, str] = ... +_tex_hlescape_map_without_unicode: dict[int, str] = ... +def escape(s: str, latex_engine: str | None = ...) -> str: + """Escape text for LaTeX output.""" + ... + +def hlescape(s: str, latex_engine: str | None = ...) -> str: + """Escape text for LaTeX highlighter.""" + ... + +def escape_abbr(text: str) -> str: + """Adjust spacing after abbreviations. Works with @ letter or other.""" + ... + +def init() -> None: + ... + diff --git a/typings/sphinx/util/typing.pyi b/typings/sphinx/util/typing.pyi new file mode 100644 index 0000000..b0fbfe6 --- /dev/null +++ b/typings/sphinx/util/typing.pyi @@ -0,0 +1,71 @@ +""" +This type stub file was generated by pyright. +""" + +from collections.abc import Sequence +from typing import Any, Callable, TYPE_CHECKING, Union +from docutils import nodes +from docutils.parsers.rst.states import Inliner + +"""The composite types for Sphinx.""" +if TYPE_CHECKING: + ... +INVALID_BUILTIN_CLASSES = ... +def is_invalid_builtin_class(obj: Any) -> bool: + """Check *obj* is an invalid built-in class.""" + ... + +TextlikeNode = Union[nodes.Text, nodes.TextElement] +NoneType = ... +PathMatcher = Callable[[str], bool] +RoleFunction = Callable[[str, str, str, int, Inliner, dict[str, Any], Sequence[str]], tuple[list[nodes.Node], list[nodes.system_message]]] +OptionSpec = dict[str, Callable[[str], Any]] +TitleGetter = Callable[[nodes.Node], str] +InventoryItem = tuple[str, str, str, str,] +Inventory = dict[str, dict[str, InventoryItem]] +def get_type_hints(obj: Any, globalns: dict[str, Any] | None = ..., localns: dict[str, Any] | None = ...) -> dict[str, Any]: + """Return a dictionary containing type hints for a function, method, module or class + object. + + This is a simple wrapper of `typing.get_type_hints()` that does not raise an error on + runtime. + """ + ... + +def is_system_TypeVar(typ: Any) -> bool: + """Check *typ* is system defined TypeVar.""" + ... + +def restify(cls: type | None, mode: str = ...) -> str: + """Convert python class to a reST reference. + + :param mode: Specify a method how annotations will be stringified. + + 'fully-qualified-except-typing' + Show the module name and qualified name of the annotation except + the "typing" module. + 'smart' + Show the name of the annotation. + """ + ... + +def stringify_annotation(annotation: Any, /, mode: str = ...) -> str: + """Stringify type annotation object. + + :param annotation: The annotation to stringified. + :param mode: Specify a method how annotations will be stringified. + + 'fully-qualified-except-typing' + Show the module name and qualified name of the annotation except + the "typing" module. + 'smart' + Show the name of the annotation. + 'fully-qualified' + Show the module name and qualified name of the annotation. + """ + ... + +_DEPRECATED_OBJECTS = ... +def __getattr__(name): # -> (annotation: Any, /, mode: str = 'fully-qualified-except-typing') -> str: + ... + diff --git a/typings/sphinx/versioning.pyi b/typings/sphinx/versioning.pyi new file mode 100644 index 0000000..4b52536 --- /dev/null +++ b/typings/sphinx/versioning.pyi @@ -0,0 +1,60 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from sphinx.transforms import SphinxTransform +from collections.abc import Iterator +from docutils.nodes import Node +from sphinx.application import Sphinx + +"""Implements the low-level algorithms Sphinx uses for versioning doctrees.""" +if TYPE_CHECKING: + ... +IS_SPEEDUP = ... +VERSIONING_RATIO = ... +def add_uids(doctree: Node, condition: Any) -> Iterator[Node]: + """Add a unique id to every node in the `doctree` which matches the + condition and yield the nodes. + + :param doctree: + A :class:`docutils.nodes.document` instance. + + :param condition: + A callable which returns either ``True`` or ``False`` for a given node. + """ + ... + +def merge_doctrees(old: Node, new: Node, condition: Any) -> Iterator[Node]: + """Merge the `old` doctree with the `new` one while looking at nodes + matching the `condition`. + + Each node which replaces another one or has been added to the `new` doctree + will be yielded. + + :param condition: + A callable which returns either ``True`` or ``False`` for a given node. + """ + ... + +def get_ratio(old: str, new: str) -> float: + """Return a "similarity ratio" (in percent) representing the similarity + between the two strings where 0 is equal and anything above less than equal. + """ + ... + +def levenshtein_distance(a: str, b: str) -> int: + """Return the Levenshtein edit distance between two strings *a* and *b*.""" + ... + +class UIDTransform(SphinxTransform): + """Add UIDs to doctree for versioning.""" + default_priority = ... + def apply(self, **kwargs: Any) -> None: + ... + + + +def setup(app: Sphinx) -> dict[str, Any]: + ... + diff --git a/typings/sphinx/writers/__init__.pyi b/typings/sphinx/writers/__init__.pyi new file mode 100644 index 0000000..8f6501f --- /dev/null +++ b/typings/sphinx/writers/__init__.pyi @@ -0,0 +1,5 @@ +""" +This type stub file was generated by pyright. +""" + +"""Custom docutils writers.""" diff --git a/typings/sphinx/writers/html.pyi b/typings/sphinx/writers/html.pyi new file mode 100644 index 0000000..a36a403 --- /dev/null +++ b/typings/sphinx/writers/html.pyi @@ -0,0 +1,24 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from docutils.writers.html4css1 import Writer +from sphinx.writers.html5 import HTML5Translator +from sphinx.builders.html import StandaloneHTMLBuilder + +"""docutils writers handling Sphinx' custom nodes.""" +if TYPE_CHECKING: + ... +logger = ... +HTMLTranslator = HTML5Translator +class HTMLWriter(Writer): + settings_default_overrides = ... + def __init__(self, builder: StandaloneHTMLBuilder) -> None: + ... + + def translate(self) -> None: + ... + + + diff --git a/typings/sphinx/writers/html5.pyi b/typings/sphinx/writers/html5.pyi new file mode 100644 index 0000000..d59086a --- /dev/null +++ b/typings/sphinx/writers/html5.pyi @@ -0,0 +1,406 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import TYPE_CHECKING +from docutils import nodes +from docutils.writers.html5_polyglot import HTMLTranslator as BaseTranslator +from sphinx.util.docutils import SphinxTranslator +from docutils.nodes import Element, Text +from sphinx.builders import Builder +from sphinx.builders.html import StandaloneHTMLBuilder + +"""Experimental docutils writers for HTML5 handling Sphinx's custom nodes.""" +if TYPE_CHECKING: + ... +logger = ... +def multiply_length(length: str, scale: int) -> str: + """Multiply *length* (width or height) by *scale*.""" + ... + +class HTML5Translator(SphinxTranslator, BaseTranslator): + """ + Our custom HTML translator. + """ + builder: StandaloneHTMLBuilder + supported_inline_tags: set[str] = ... + def __init__(self, document: nodes.document, builder: Builder) -> None: + ... + + def visit_start_of_file(self, node: Element) -> None: + ... + + def depart_start_of_file(self, node: Element) -> None: + ... + + def visit_desc(self, node: Element) -> None: + ... + + def depart_desc(self, node: Element) -> None: + ... + + def visit_desc_signature(self, node: Element) -> None: + ... + + def depart_desc_signature(self, node: Element) -> None: + ... + + def visit_desc_signature_line(self, node: Element) -> None: + ... + + def depart_desc_signature_line(self, node: Element) -> None: + ... + + def visit_desc_content(self, node: Element) -> None: + ... + + def depart_desc_content(self, node: Element) -> None: + ... + + def visit_desc_inline(self, node: Element) -> None: + ... + + def depart_desc_inline(self, node: Element) -> None: + ... + + def visit_desc_name(self, node: Element) -> None: + ... + + def depart_desc_name(self, node: Element) -> None: + ... + + def visit_desc_addname(self, node: Element) -> None: + ... + + def depart_desc_addname(self, node: Element) -> None: + ... + + def visit_desc_type(self, node: Element) -> None: + ... + + def depart_desc_type(self, node: Element) -> None: + ... + + def visit_desc_returns(self, node: Element) -> None: + ... + + def depart_desc_returns(self, node: Element) -> None: + ... + + def visit_desc_parameterlist(self, node: Element) -> None: + ... + + def depart_desc_parameterlist(self, node: Element) -> None: + ... + + def visit_desc_type_parameter_list(self, node: Element) -> None: + ... + + def depart_desc_type_parameter_list(self, node: Element) -> None: + ... + + def visit_desc_parameter(self, node: Element) -> None: + ... + + def depart_desc_parameter(self, node: Element) -> None: + ... + + def visit_desc_type_parameter(self, node: Element) -> None: + ... + + def depart_desc_type_parameter(self, node: Element) -> None: + ... + + def visit_desc_optional(self, node: Element) -> None: + ... + + def depart_desc_optional(self, node: Element) -> None: + ... + + def visit_desc_annotation(self, node: Element) -> None: + ... + + def depart_desc_annotation(self, node: Element) -> None: + ... + + def visit_versionmodified(self, node: Element) -> None: + ... + + def depart_versionmodified(self, node: Element) -> None: + ... + + def visit_reference(self, node: Element) -> None: + ... + + def visit_number_reference(self, node: Element) -> None: + ... + + def depart_number_reference(self, node: Element) -> None: + ... + + def visit_comment(self, node: Element) -> None: + ... + + def visit_admonition(self, node: Element, name: str = ...) -> None: + ... + + def depart_admonition(self, node: Element | None = ...) -> None: + ... + + def visit_seealso(self, node: Element) -> None: + ... + + def depart_seealso(self, node: Element) -> None: + ... + + def get_secnumber(self, node: Element) -> tuple[int, ...] | None: + ... + + def add_secnumber(self, node: Element) -> None: + ... + + def add_fignumber(self, node: Element) -> None: + ... + + def add_permalink_ref(self, node: Element, title: str) -> None: + ... + + def visit_bullet_list(self, node: Element) -> None: + ... + + def visit_definition(self, node: Element) -> None: + ... + + def depart_definition(self, node: Element) -> None: + ... + + def visit_classifier(self, node: Element) -> None: + ... + + def depart_classifier(self, node: Element) -> None: + ... + + def visit_term(self, node: Element) -> None: + ... + + def depart_term(self, node: Element) -> None: + ... + + def visit_title(self, node: Element) -> None: + ... + + def depart_title(self, node: Element) -> None: + ... + + def visit_literal_block(self, node: Element) -> None: + ... + + def visit_caption(self, node: Element) -> None: + ... + + def depart_caption(self, node: Element) -> None: + ... + + def visit_doctest_block(self, node: Element) -> None: + ... + + def visit_block_quote(self, node: Element) -> None: + ... + + def depart_block_quote(self, node: Element) -> None: + ... + + def visit_literal(self, node: Element) -> None: + ... + + def depart_literal(self, node: Element) -> None: + ... + + def visit_productionlist(self, node: Element) -> None: + ... + + def depart_productionlist(self, node: Element) -> None: + ... + + def visit_production(self, node: Element) -> None: + ... + + def depart_production(self, node: Element) -> None: + ... + + def visit_centered(self, node: Element) -> None: + ... + + def depart_centered(self, node: Element) -> None: + ... + + def visit_compact_paragraph(self, node: Element) -> None: + ... + + def depart_compact_paragraph(self, node: Element) -> None: + ... + + def visit_download_reference(self, node: Element) -> None: + ... + + def depart_download_reference(self, node: Element) -> None: + ... + + def visit_figure(self, node: Element) -> None: + ... + + def visit_image(self, node: Element) -> None: + ... + + def depart_image(self, node: Element) -> None: + ... + + def visit_toctree(self, node: Element) -> None: + ... + + def visit_index(self, node: Element) -> None: + ... + + def visit_tabular_col_spec(self, node: Element) -> None: + ... + + def visit_glossary(self, node: Element) -> None: + ... + + def depart_glossary(self, node: Element) -> None: + ... + + def visit_acks(self, node: Element) -> None: + ... + + def depart_acks(self, node: Element) -> None: + ... + + def visit_hlist(self, node: Element) -> None: + ... + + def depart_hlist(self, node: Element) -> None: + ... + + def visit_hlistcol(self, node: Element) -> None: + ... + + def depart_hlistcol(self, node: Element) -> None: + ... + + def visit_Text(self, node: Text) -> None: + ... + + def visit_note(self, node: Element) -> None: + ... + + def depart_note(self, node: Element) -> None: + ... + + def visit_warning(self, node: Element) -> None: + ... + + def depart_warning(self, node: Element) -> None: + ... + + def visit_attention(self, node: Element) -> None: + ... + + def depart_attention(self, node: Element) -> None: + ... + + def visit_caution(self, node: Element) -> None: + ... + + def depart_caution(self, node: Element) -> None: + ... + + def visit_danger(self, node: Element) -> None: + ... + + def depart_danger(self, node: Element) -> None: + ... + + def visit_error(self, node: Element) -> None: + ... + + def depart_error(self, node: Element) -> None: + ... + + def visit_hint(self, node: Element) -> None: + ... + + def depart_hint(self, node: Element) -> None: + ... + + def visit_important(self, node: Element) -> None: + ... + + def depart_important(self, node: Element) -> None: + ... + + def visit_tip(self, node: Element) -> None: + ... + + def depart_tip(self, node: Element) -> None: + ... + + def visit_literal_emphasis(self, node: Element) -> None: + ... + + def depart_literal_emphasis(self, node: Element) -> None: + ... + + def visit_literal_strong(self, node: Element) -> None: + ... + + def depart_literal_strong(self, node: Element) -> None: + ... + + def visit_abbreviation(self, node: Element) -> None: + ... + + def depart_abbreviation(self, node: Element) -> None: + ... + + def visit_manpage(self, node: Element) -> None: + ... + + def depart_manpage(self, node: Element) -> None: + ... + + def visit_table(self, node: Element) -> None: + ... + + def depart_table(self, node: Element) -> None: + ... + + def visit_row(self, node: Element) -> None: + ... + + def visit_field_list(self, node: Element) -> None: + ... + + def depart_field_list(self, node: Element) -> None: + ... + + def visit_field(self, node: Element) -> None: + ... + + def visit_math(self, node: Element, math_env: str = ...) -> None: + ... + + def depart_math(self, node: Element, math_env: str = ...) -> None: + ... + + def visit_math_block(self, node: Element, math_env: str = ...) -> None: + ... + + def depart_math_block(self, node: Element, math_env: str = ...) -> None: + ... + + def visit_footnote_reference(self, node): # -> None: + ... + + + diff --git a/typings/sphinx/writers/latex.pyi b/typings/sphinx/writers/latex.pyi new file mode 100644 index 0000000..bf93772 --- /dev/null +++ b/typings/sphinx/writers/latex.pyi @@ -0,0 +1,827 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Any, TYPE_CHECKING +from docutils import nodes, writers +from sphinx.errors import SphinxError +from sphinx.util.docutils import SphinxTranslator +from docutils.nodes import Element, Text +from sphinx.builders.latex import LaTeXBuilder +from sphinx.builders.latex.theming import Theme + +"""Custom docutils writer for LaTeX. + +Much of this code is adapted from Dave Kuhlman's "docpy" writer from his +docutils sandbox. +""" +if TYPE_CHECKING: + ... +logger = ... +MAX_CITATION_LABEL_LENGTH = ... +LATEXSECTIONNAMES = ... +ENUMERATE_LIST_STYLE = ... +CR = ... +BLANKLINE = ... +EXTRA_RE = ... +class collected_footnote(nodes.footnote): + """Footnotes that are collected are assigned this class.""" + ... + + +class UnsupportedError(SphinxError): + category = ... + + +class LaTeXWriter(writers.Writer): + supported = ... + settings_spec = ... + settings_defaults: dict[str, Any] = ... + theme: Theme + def __init__(self, builder: LaTeXBuilder) -> None: + ... + + def translate(self) -> None: + ... + + + +class Table: + """A table data""" + def __init__(self, node: Element) -> None: + ... + + def is_longtable(self) -> bool: + """True if and only if table uses longtable environment.""" + ... + + def get_table_type(self) -> str: + """Returns the LaTeX environment name for the table. + + The class currently supports: + + * longtable + * tabular + * tabulary + """ + ... + + def get_colspec(self) -> str: + """Returns a column spec of table. + + This is what LaTeX calls the 'preamble argument' of the used table environment. + + .. note:: + + The ``\\X`` and ``T`` column type specifiers are defined in + ``sphinxlatextables.sty``. + """ + ... + + def add_cell(self, height: int, width: int) -> None: + """Adds a new cell to a table. + + It will be located at current position: (``self.row``, ``self.col``). + """ + ... + + def cell(self, row: int | None = ..., col: int | None = ...) -> TableCell | None: + """Returns a cell object (i.e. rectangular area) containing given position. + + If no option arguments: ``row`` or ``col`` are given, the current position; + ``self.row`` and ``self.col`` are used to get a cell object by default. + """ + ... + + + +class TableCell: + """Data of a cell in a table.""" + def __init__(self, table: Table, row: int, col: int) -> None: + ... + + @property + def width(self) -> int: + """Returns the cell width.""" + ... + + @property + def height(self) -> int: + """Returns the cell height.""" + ... + + + +def escape_abbr(text: str) -> str: + """Adjust spacing after abbreviations.""" + ... + +def rstdim_to_latexdim(width_str: str, scale: int = ...) -> str: + """Convert `width_str` with rst length to LaTeX length.""" + ... + +class LaTeXTranslator(SphinxTranslator): + builder: LaTeXBuilder + secnumdepth = ... + ignore_missing_images = ... + def __init__(self, document: nodes.document, builder: LaTeXBuilder, theme: Theme) -> None: + ... + + def pushbody(self, newbody: list[str]) -> None: + ... + + def popbody(self) -> list[str]: + ... + + def astext(self) -> str: + ... + + def hypertarget(self, id: str, withdoc: bool = ..., anchor: bool = ...) -> str: + ... + + def hypertarget_to(self, node: Element, anchor: bool = ...) -> str: + ... + + def hyperlink(self, id: str) -> str: + ... + + def hyperpageref(self, id: str) -> str: + ... + + def escape(self, s: str) -> str: + ... + + def idescape(self, id: str) -> str: + ... + + def babel_renewcommand(self, command: str, definition: str) -> str: + ... + + def generate_indices(self) -> str: + ... + + def render(self, template_name: str, variables: dict[str, Any]) -> str: + ... + + @property + def table(self) -> Table | None: + """Get current table.""" + ... + + def visit_document(self, node: Element) -> None: + ... + + def depart_document(self, node: Element) -> None: + ... + + def visit_start_of_file(self, node: Element) -> None: + ... + + def depart_start_of_file(self, node: Element) -> None: + ... + + def visit_section(self, node: Element) -> None: + ... + + def depart_section(self, node: Element) -> None: + ... + + def visit_problematic(self, node: Element) -> None: + ... + + def depart_problematic(self, node: Element) -> None: + ... + + def visit_topic(self, node: Element) -> None: + ... + + def depart_topic(self, node: Element) -> None: + ... + + visit_sidebar = ... + depart_sidebar = ... + def visit_glossary(self, node: Element) -> None: + ... + + def depart_glossary(self, node: Element) -> None: + ... + + def visit_productionlist(self, node: Element) -> None: + ... + + def depart_productionlist(self, node: Element) -> None: + ... + + def visit_production(self, node: Element) -> None: + ... + + def depart_production(self, node: Element) -> None: + ... + + def visit_transition(self, node: Element) -> None: + ... + + def depart_transition(self, node: Element) -> None: + ... + + def visit_title(self, node: Element) -> None: + ... + + def depart_title(self, node: Element) -> None: + ... + + def visit_subtitle(self, node: Element) -> None: + ... + + def depart_subtitle(self, node: Element) -> None: + ... + + def visit_desc(self, node: Element) -> None: + ... + + def depart_desc(self, node: Element) -> None: + ... + + def visit_desc_signature(self, node: Element) -> None: + ... + + def depart_desc_signature(self, node: Element) -> None: + ... + + def visit_desc_signature_line(self, node: Element) -> None: + ... + + def depart_desc_signature_line(self, node: Element) -> None: + ... + + def visit_desc_content(self, node: Element) -> None: + ... + + def depart_desc_content(self, node: Element) -> None: + ... + + def visit_desc_inline(self, node: Element) -> None: + ... + + def depart_desc_inline(self, node: Element) -> None: + ... + + def visit_desc_name(self, node: Element) -> None: + ... + + def depart_desc_name(self, node: Element) -> None: + ... + + def visit_desc_addname(self, node: Element) -> None: + ... + + def depart_desc_addname(self, node: Element) -> None: + ... + + def visit_desc_type(self, node: Element) -> None: + ... + + def depart_desc_type(self, node: Element) -> None: + ... + + def visit_desc_returns(self, node: Element) -> None: + ... + + def depart_desc_returns(self, node: Element) -> None: + ... + + def visit_desc_parameterlist(self, node: Element) -> None: + ... + + def depart_desc_parameterlist(self, node: Element) -> None: + ... + + def visit_desc_type_parameter_list(self, node: Element) -> None: + ... + + def depart_desc_type_parameter_list(self, node: Element) -> None: + ... + + def visit_desc_parameter(self, node: Element) -> None: + ... + + def depart_desc_parameter(self, node: Element) -> None: + ... + + def visit_desc_type_parameter(self, node: Element) -> None: + ... + + def depart_desc_type_parameter(self, node: Element) -> None: + ... + + def visit_desc_optional(self, node: Element) -> None: + ... + + def depart_desc_optional(self, node: Element) -> None: + ... + + def visit_desc_annotation(self, node: Element) -> None: + ... + + def depart_desc_annotation(self, node: Element) -> None: + ... + + def visit_seealso(self, node: Element) -> None: + ... + + def depart_seealso(self, node: Element) -> None: + ... + + def visit_rubric(self, node: Element) -> None: + ... + + def depart_rubric(self, node: Element) -> None: + ... + + def visit_footnote(self, node: Element) -> None: + ... + + def depart_footnote(self, node: Element) -> None: + ... + + def visit_label(self, node: Element) -> None: + ... + + def visit_tabular_col_spec(self, node: Element) -> None: + ... + + def visit_table(self, node: Element) -> None: + ... + + def depart_table(self, node: Element) -> None: + ... + + def visit_colspec(self, node: Element) -> None: + ... + + def depart_colspec(self, node: Element) -> None: + ... + + def visit_tgroup(self, node: Element) -> None: + ... + + def depart_tgroup(self, node: Element) -> None: + ... + + def visit_thead(self, node: Element) -> None: + ... + + def depart_thead(self, node: Element) -> None: + ... + + def visit_tbody(self, node: Element) -> None: + ... + + def depart_tbody(self, node: Element) -> None: + ... + + def visit_row(self, node: Element) -> None: + ... + + def depart_row(self, node: Element) -> None: + ... + + def visit_entry(self, node: Element) -> None: + ... + + def depart_entry(self, node: Element) -> None: + ... + + def visit_acks(self, node: Element) -> None: + ... + + def visit_bullet_list(self, node: Element) -> None: + ... + + def depart_bullet_list(self, node: Element) -> None: + ... + + def visit_enumerated_list(self, node: Element) -> None: + ... + + def depart_enumerated_list(self, node: Element) -> None: + ... + + def visit_list_item(self, node: Element) -> None: + ... + + def depart_list_item(self, node: Element) -> None: + ... + + def visit_definition_list(self, node: Element) -> None: + ... + + def depart_definition_list(self, node: Element) -> None: + ... + + def visit_definition_list_item(self, node: Element) -> None: + ... + + def depart_definition_list_item(self, node: Element) -> None: + ... + + def visit_term(self, node: Element) -> None: + ... + + def depart_term(self, node: Element) -> None: + ... + + def visit_classifier(self, node: Element) -> None: + ... + + def depart_classifier(self, node: Element) -> None: + ... + + def visit_definition(self, node: Element) -> None: + ... + + def depart_definition(self, node: Element) -> None: + ... + + def visit_field_list(self, node: Element) -> None: + ... + + def depart_field_list(self, node: Element) -> None: + ... + + def visit_field(self, node: Element) -> None: + ... + + def depart_field(self, node: Element) -> None: + ... + + visit_field_name = ... + depart_field_name = ... + visit_field_body = ... + depart_field_body = ... + def visit_paragraph(self, node: Element) -> None: + ... + + def depart_paragraph(self, node: Element) -> None: + ... + + def visit_centered(self, node: Element) -> None: + ... + + def depart_centered(self, node: Element) -> None: + ... + + def visit_hlist(self, node: Element) -> None: + ... + + def depart_hlist(self, node: Element) -> None: + ... + + def visit_hlistcol(self, node: Element) -> None: + ... + + def depart_hlistcol(self, node: Element) -> None: + ... + + def latex_image_length(self, width_str: str, scale: int = ...) -> str | None: + ... + + def is_inline(self, node: Element) -> bool: + """Check whether a node represents an inline element.""" + ... + + def visit_image(self, node: Element) -> None: + ... + + def depart_image(self, node: Element) -> None: + ... + + def visit_figure(self, node: Element) -> None: + ... + + def depart_figure(self, node: Element) -> None: + ... + + def visit_caption(self, node: Element) -> None: + ... + + def depart_caption(self, node: Element) -> None: + ... + + def visit_legend(self, node: Element) -> None: + ... + + def depart_legend(self, node: Element) -> None: + ... + + def visit_admonition(self, node: Element) -> None: + ... + + def depart_admonition(self, node: Element) -> None: + ... + + visit_attention = ... + depart_attention = ... + visit_caution = ... + depart_caution = ... + visit_danger = ... + depart_danger = ... + visit_error = ... + depart_error = ... + visit_hint = ... + depart_hint = ... + visit_important = ... + depart_important = ... + visit_note = ... + depart_note = ... + visit_tip = ... + depart_tip = ... + visit_warning = ... + depart_warning = ... + def visit_versionmodified(self, node: Element) -> None: + ... + + def depart_versionmodified(self, node: Element) -> None: + ... + + def visit_target(self, node: Element) -> None: + ... + + def depart_target(self, node: Element) -> None: + ... + + def visit_attribution(self, node: Element) -> None: + ... + + def depart_attribution(self, node: Element) -> None: + ... + + def visit_index(self, node: Element) -> None: + ... + + def visit_raw(self, node: Element) -> None: + ... + + def visit_reference(self, node: Element) -> None: + ... + + def depart_reference(self, node: Element) -> None: + ... + + def visit_number_reference(self, node: Element) -> None: + ... + + def visit_download_reference(self, node: Element) -> None: + ... + + def depart_download_reference(self, node: Element) -> None: + ... + + def visit_pending_xref(self, node: Element) -> None: + ... + + def depart_pending_xref(self, node: Element) -> None: + ... + + def visit_emphasis(self, node: Element) -> None: + ... + + def depart_emphasis(self, node: Element) -> None: + ... + + def visit_literal_emphasis(self, node: Element) -> None: + ... + + def depart_literal_emphasis(self, node: Element) -> None: + ... + + def visit_strong(self, node: Element) -> None: + ... + + def depart_strong(self, node: Element) -> None: + ... + + def visit_literal_strong(self, node: Element) -> None: + ... + + def depart_literal_strong(self, node: Element) -> None: + ... + + def visit_abbreviation(self, node: Element) -> None: + ... + + def depart_abbreviation(self, node: Element) -> None: + ... + + def visit_manpage(self, node: Element) -> None: + ... + + def depart_manpage(self, node: Element) -> None: + ... + + def visit_title_reference(self, node: Element) -> None: + ... + + def depart_title_reference(self, node: Element) -> None: + ... + + def visit_thebibliography(self, node: Element) -> None: + ... + + def depart_thebibliography(self, node: Element) -> None: + ... + + def visit_citation(self, node: Element) -> None: + ... + + def depart_citation(self, node: Element) -> None: + ... + + def visit_citation_reference(self, node: Element) -> None: + ... + + def depart_citation_reference(self, node: Element) -> None: + ... + + def visit_literal(self, node: Element) -> None: + ... + + def depart_literal(self, node: Element) -> None: + ... + + def visit_footnote_reference(self, node: Element) -> None: + ... + + def visit_footnotemark(self, node: Element) -> None: + ... + + def depart_footnotemark(self, node: Element) -> None: + ... + + def visit_footnotetext(self, node: Element) -> None: + ... + + def depart_footnotetext(self, node: Element) -> None: + ... + + def visit_captioned_literal_block(self, node: Element) -> None: + ... + + def depart_captioned_literal_block(self, node: Element) -> None: + ... + + def visit_literal_block(self, node: Element) -> None: + ... + + def depart_literal_block(self, node: Element) -> None: + ... + + visit_doctest_block = ... + depart_doctest_block = ... + def visit_line(self, node: Element) -> None: + ... + + def depart_line(self, node: Element) -> None: + ... + + def visit_line_block(self, node: Element) -> None: + ... + + def depart_line_block(self, node: Element) -> None: + ... + + def visit_block_quote(self, node: Element) -> None: + ... + + def depart_block_quote(self, node: Element) -> None: + ... + + def visit_option(self, node: Element) -> None: + ... + + def depart_option(self, node: Element) -> None: + ... + + def visit_option_argument(self, node: Element) -> None: + """The delimiter between an option and its argument.""" + ... + + def depart_option_argument(self, node: Element) -> None: + ... + + def visit_option_group(self, node: Element) -> None: + ... + + def depart_option_group(self, node: Element) -> None: + ... + + def visit_option_list(self, node: Element) -> None: + ... + + def depart_option_list(self, node: Element) -> None: + ... + + def visit_option_list_item(self, node: Element) -> None: + ... + + def depart_option_list_item(self, node: Element) -> None: + ... + + def visit_option_string(self, node: Element) -> None: + ... + + def visit_description(self, node: Element) -> None: + ... + + def depart_description(self, node: Element) -> None: + ... + + def visit_superscript(self, node: Element) -> None: + ... + + def depart_superscript(self, node: Element) -> None: + ... + + def visit_subscript(self, node: Element) -> None: + ... + + def depart_subscript(self, node: Element) -> None: + ... + + def visit_inline(self, node: Element) -> None: + ... + + def depart_inline(self, node: Element) -> None: + ... + + def visit_generated(self, node: Element) -> None: + ... + + def depart_generated(self, node: Element) -> None: + ... + + def visit_compound(self, node: Element) -> None: + ... + + def depart_compound(self, node: Element) -> None: + ... + + def visit_container(self, node: Element) -> None: + ... + + def depart_container(self, node: Element) -> None: + ... + + def visit_decoration(self, node: Element) -> None: + ... + + def depart_decoration(self, node: Element) -> None: + ... + + def visit_header(self, node: Element) -> None: + ... + + def visit_footer(self, node: Element) -> None: + ... + + def visit_docinfo(self, node: Element) -> None: + ... + + def encode(self, text: str) -> str: + ... + + def encode_uri(self, text: str) -> str: + ... + + def visit_Text(self, node: Text) -> None: + ... + + def depart_Text(self, node: Text) -> None: + ... + + def visit_comment(self, node: Element) -> None: + ... + + def visit_meta(self, node: Element) -> None: + ... + + def visit_system_message(self, node: Element) -> None: + ... + + def depart_system_message(self, node: Element) -> None: + ... + + def visit_math(self, node: Element) -> None: + ... + + def visit_math_block(self, node: Element) -> None: + ... + + def visit_math_reference(self, node: Element) -> None: + ... + + def depart_math_reference(self, node: Element) -> None: + ... + + +