More typing hints with strict checks

This commit is contained in:
Kujiu 2023-09-19 02:01:13 +02:00
parent fd0986908c
commit 3e49ee8612
Signed by: kujiu
GPG key ID: ABBB2CAC6855599F
131 changed files with 18509 additions and 40 deletions

View file

@ -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*)
====================

View file

@ -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

View file

@ -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(

View file

@ -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)

View file

@ -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()

View file

@ -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']

View file

@ -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.
"""
...

View file

@ -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."""
...

View file

@ -0,0 +1,9 @@
"""
This type stub file was generated by pyright.
"""
"""Commands for Pyppeteer."""
def install() -> None:
"""Download chromium if not install."""
...

View file

@ -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 <https://chromedevtools.github.io/devtools-protocol/>`__.
"""
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.
"""
...

View file

@ -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."""
...

View file

@ -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."""
...

View file

@ -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
<div class="feed">
<div class="tweet">Hello!</div>
<div class="tweet">Hi!</div>
</div>
.. 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."""
...

View file

@ -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."""
...

View file

@ -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."""
...

View file

@ -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."""
...

View file

@ -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 = ...

View file

@ -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."""
...

204
typings/pyppeteer/input.pyi Normal file
View file

@ -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.
"""
...

View file

@ -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/<id>`` 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 <http://peter.sh/experiments/chromium-command-line-switches/>`__.
* ``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``.
"""
...

View file

@ -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."""
...

View file

@ -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 = ...

View file

@ -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 = ...

View file

@ -0,0 +1,6 @@
"""
This type stub file was generated by pyright.
"""
"""Options module."""
config = ...

1011
typings/pyppeteer/page.pyi Normal file

File diff suppressed because it is too large Load diff

View file

@ -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``.
"""
...

View file

@ -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 <https://chromedevtools.github.io/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.
"""
...

View file

@ -0,0 +1,6 @@
"""
This type stub file was generated by pyright.
"""
"""US Keyboard Definition."""
keyDefinitions = ...

View file

@ -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."""
...

View file

@ -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)``.
"""
...

View file

@ -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:
...

View file

@ -0,0 +1,5 @@
"""
This type stub file was generated by pyright.
"""
"""The Sphinx documentation toolchain."""

483
typings/sphinx/addnodes.pyi Normal file
View file

@ -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 <p> 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::
<pending_xref refdomain="py" reftarget="io.StringIO ...>
<pending_xref_condition condition="resolved">
<literal>
StringIO
<pending_xref_condition condition="*">
<literal>
io.StringIO
If the cross-reference resolver successfully resolves the cross-reference,
then it rewrites the **pending_xref** as::
<reference>
<literal>
StringIO
Otherwise, if the cross-reference resolution failed, it rewrites the
**pending_xref** as::
<reference>
<literal>
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]:
...

View file

@ -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('</math>')
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
<https://docutils.sourceforge.io/docs/howto/rst-directives.html>`__ .
.. 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
<https://docutils.sourceforge.io/docs/howto/rst-roles.html>`__ .
.. 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 <application API>`.
(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
``<script>`` tag. See the description of *kwargs*
below.
:param priority: Files are included in ascending order of priority. If
multiple JavaScript files have the same priority,
those files will be included in order of registration.
See list of "priority range for JavaScript files" below.
:param loading_method: The loading method for the JavaScript file.
Either ``'async'`` or ``'defer'`` are allowed.
:param kwargs: Extra keyword arguments are included as attributes of the
``<script>`` tag. If the special keyword argument
``body`` is given, its value will be added as the content
of the ``<script>`` tag.
Example::
app.add_js_file('example.js')
# => <script src="_static/example.js"></script>
app.add_js_file('example.js', loading_method="async")
# => <script src="_static/example.js" async="async"></script>
app.add_js_file(None, body="var myVariable = 'foo';")
# => <script>var myVariable = 'foo';</script>
.. 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
``<link>`` tag.
Example::
app.add_css_file('custom.css')
# => <link rel="stylesheet" href="_static/custom.css" type="text/css" />
app.add_css_file('print.css', media='print')
# => <link rel="stylesheet" href="_static/print.css"
# type="text/css" media="print" />
app.add_css_file('fancy.css', rel='alternate stylesheet', title='fancy')
# => <link rel="alternate stylesheet" href="_static/fancy.css"
# type="text/css" 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
<https://mdn.io/Web/CSS/Alternative_style_sheets>`__.
.. 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).
"""
...

View file

@ -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.
"""
...

View file

@ -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.
"""
...

View file

@ -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]:
...

View file

@ -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]:
...

View file

@ -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]:
...

View file

@ -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:
...

View file

@ -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]:
...

View file

@ -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 = ...

View file

@ -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 = ...

View file

@ -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."""
...

View file

@ -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``."""
...

View file

@ -0,0 +1,5 @@
"""
This type stub file was generated by pyright.
"""
"""Modules for command line executables."""

View file

@ -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__':
...

View file

@ -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:
...

164
typings/sphinx/config.pyi Normal file
View file

@ -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]:
...

View file

@ -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

View file

@ -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]:
...

View file

@ -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."""
...

View file

@ -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]:
...

View file

@ -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]:
...

View file

@ -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]:
...

File diff suppressed because it is too large Load diff

View file

@ -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]:
...

View file

@ -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