Table Of Contentsο
Sphinx README - Generate Beautiful README.rst for GitHub, PyPi, GitLab, BitBucketο

A Sphinx extension to generate README.rst
files that render beautifully on GitHub, PyPi, GitLab, BitBucket
About Sphinx READMEο
Whatβs Sphinx README?
sphinx_readme
is a reStructuredText
parser that uses Sphinx
to generate rst
files that render beautifully on
GitHub, PyPi, GitLab, and BitBucket.
With sphinx_readme
, thereβs no need to rewrite your README.rst
as a README.md
file
Files generated by sphinx_readme
have nearly identical appearance and functionality
as html
builds, including sphinx.ext.autodoc
cross-references!

π Featuresο
sphinx_readme
adds support for the following sphinx
and docutils
directives and features:
sphinx.ext.autodoc
cross-references (:mod:
,:class:
,:meth:
,:func:
, and:attr:
)Standard cross-reference roles (
:doc:
and:ref:
)Generic and Specific Admonitions
Only directives
Toctrees
Rubrics
Images
β Installationο
Install using pip:
pip install sphinx-readme
Add the extension to your conf.py
:
extensions = [
'sphinx_readme',
]
π§ Configurationο
Please see Extension Configuration
Extension Configurationο
Install using pip:
pip install sphinx-readme
Add the extension to your conf.py
:
extensions = [
"sphinx_readme",
]
For an example of the minimum required configuration,
please see the sample conf.py
file
Mandatory conf.py
valuesο
html_context
ο
- html_contextο
A dictionary containing info about your repository (
html_context
)At minimum, the username and repository name must be specified
Please see HTML Context Settings to determine the correct dictionary keys for your hosting platform
- Type
Dict
html_baseurl
ο
- html_baseurlο
The base URL which points to the root of the HTML documentation (
html_baseurl
)- Type
str
readme_src_files
ο
- readme_src_filesο
An individual/list of
rst
source files to parse, or a dictionary of source files mapped to output filesImportant
Filepaths should be specified relative to the source directory and
output directory
- Type
Union[str, List]
readme_docs_url_type
ο
- readme_docs_url_typeο
The documentation source to link to when resolving
autodoc
cross-referencesMust be either
"code"
or"html"
"code"
: usessphinx.ext.linkcode
to replace references with links to highlighted source code
- Example
"html"
: replaces references with links to HTML documentation entries
- Example
Note
If set to
code
, non-external:attr:
cross-references will not be replaced with linksInstead, theyβll be replaced with
inline literals
or left as isPlease see
readme_replace_attrs
andreadme_inline_markup
Optional conf.py
valuesο
readme_out_dir
ο
- readme_out_dirο
Specifies the path of the directory to save generated
rst
files toThe value should be provided as either
An absolute path; or
A path relative to the source directory
- Type
Union[str, Path]
- Default
the root directory of your repository, via
get_repo_dir()
readme_replace_attrs
ο
- readme_replace_attrsο
Specifies if non-external attribute (
:attr:
) cross-references should be replacedβ¦
If
True
, the value ofreadme_docs_url_type
determines how replacements are made:"html"
: references are replaced with a link to the corresponding documentation entry
- Example
:attr:`icon_map`
would be replaced withicon_map
or icon_map, depending on the value ofreadme_inline_markup
"code"
: attributes are replaced with inline markup
- Example
:attr:`icon_map`
would be replaced withicon_map
Note
External attribute cross-references are always replaced with links to documentation
- Type
bool
- Default
True
readme_inline_markup
ο
readme_raw_directive
ο
- readme_raw_directiveο
Specifies if the
raw
directive is supported by the platform you intend to render the generated file onTip
GitHub supports the
raw
directivePyPi, GitLab, and BitBucket do not support the
raw
directive
If set to
False
,Admonitions will be replaced with the
list-table
directive instead of HTML tablesAll
raw
directives in the file will be removed
- Type
bool
- Default
True
readme_tags
ο
- readme_tagsο
Specifies tags to use when evaluating the
<expression>
argument ofonly
directivesTip
See
replace_only_directives()
for more detail- Type
List[str]
- Default
["readme"]
readme_include_directive
ο
- readme_include_directiveο
Specifies if
include
directives should be parsed (file content inserted) or removed- Type
bool
- Default
True
readme_admonition_icons
ο
- readme_admonition_iconsο
An optional mapping of admonition classes and their icons
If specified, will be used to update the
icon_map
(below)
- Type
Optional[Dict[str, str]]
- Default
{
'attention': 'ποΈ',
'caution': 'β οΈ',
'danger': 'β’',
'error': 'β',
'hint': 'π§ ',
'important': 'π’',
'note': 'π',
'tip': 'π‘',
'warning': 'π©',
'default': 'π'
}
readme_default_admonition_icon
ο
readme_rubric_heading
ο
- readme_rubric_headingο
The character to use when replacing
rubric
directives with section headersMust be one of the following valid section title adornment characters:
! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
If not specified, rubrics will be replaced with bold text instead of a heading
- Type
str
- Default
bold inline markup (
**title**
)
readme_blob
ο
- readme_blobο
The repository blob to link to - any of
"head"
,"last_tag"
, or"{blob}"
"head"
: links to the most recent commit hash; if this commit is tagged, uses the tag instead"last_tag"
: links to the most recently tagged commit; if no tags exist, uses"head"
"{blob}"
: links to the specified blob, for example"master"
or"v2.0.1"
- Type
str
- Default
"head"
linkcode_resolve
ο
- linkcode_resolveο
A
linkcode_resolve()
function forsphinx.ext.linkcode
to use when resolving the target ofautodoc
cross-references- Type
Callable
- Default
return value of
get_linkcode_resolve()
Sample conf.py
ο
extensions = [
"sphinx_readme",
]
html_context = {
'display_github': True,
'github_user': 'TDKorn',
'github_repo': 'sphinx-readme',
}
html_baseurl = "https://sphinx-readme.readthedocs.io/en/latest"
readme_src_files = "README.rst"
readme_docs_url_type = "code"
Important
For platforms that donβt support the raw
directive (PyPi, GitLab, and BitBucket),
be sure to disable readme_raw_directive
:
readme_raw_directive = False
The sphinx_readme
packageο
The READMEParser
Classο
- class sphinx_readme.parser.READMEParser(app)[source]View on GitHubο
Bases:
object
- __init__(app)[source]View on GitHubο
- config: READMEConfigο
The
READMEConfig
for the parser
- ref_map: Dict[str, Union[List, Dict]]ο
Mapping of info for standard and
sphinx.ext.autodoc
cross-references
- substitutions: Dict[str, Dict[str, List[str]]]ο
Mapping of source files to cross-reference substitution definitions
- objtypes: Dict[str, List[str]]ο
Mapping of role names to the object types they can cross-reference
- parse_env(env)[source]View on GitHubο
Parses domain data and document titles from the
BuildEnvironment
- parse_titles(env)[source]View on GitHubο
Parses document and section titles from the
BuildEnvironment
- parse_roles(env)[source]View on GitHubο
Parses the available roles for cross-referencing objects in the
PythonDomain
, Standard Domain, and reStructuredText Domain- Parameters
env (BuildEnvironment) β the
BuildEnvironment
- parse_objtypes(env)[source]View on GitHubο
Maps cross-reference roles to their corresponding object types in the
PythonDomain
, Standard Domain, and reStructuredText Domain- Parameters
env (BuildEnvironment) β the
BuildEnvironment
- parse_std_domain(env)[source]View on GitHubο
Parses cross-reference data from the Standard Domain
- Parameters
env (BuildEnvironment) β the
BuildEnvironment
- parse_py_domain(env)[source]View on GitHubο
Parses cross-reference data for
PythonDomain
objects- Parameters
env (BuildEnvironment) β the
BuildEnvironment
- get_py_target(entry, linkcode_resolve=None)[source]View on GitHubο
Resolves the target for a cross-reference to an object in the
PythonDomain
- add_variants(qualified_name, target, is_callable=False)[source]View on GitHubο
Adds substitution information for an object to the
ref_map
This data is used to replace any
autodoc
cross-reference to the object with a substitution, hyperlinked to the corresponding source code or documentation entryTip
See
get_all_xref_variants()
andreplace_autodoc_refs()
- parse_doctree(app, doctree, docname)[source]View on GitHubο
Parses cross-reference, admonition, rubric, and toctree data from a resolved doctree
- parse_admonitions(app, doctree, docname)[source]View on GitHubο
Parses data from generic and specific admonitions
- Parameters
doctree (document) β the doctree from one of the
src_files
- parse_intersphinx_nodes(app, doctree, docname)[source]View on GitHubο
Parses cross-references that utilize
sphinx.ext.intersphinx
- Parameters
doctree (document) β the doctree from one of the
src_files
- parse_external_node(external, role, ref_id)[source]View on GitHubο
- parse_toctrees(app, doctree, docname)[source]View on GitHubο
Parses the caption and entry data from
toctree
nodesCaution
Toctrees are currently parsed as if the directive has the
:titlesonly:
option- Parameters
doctree (document) β the doctree from one of the
src_files
- parse_rubrics(app, doctree, docname)[source]View on GitHubο
Parses the content from
rubric
directives
- get_external_ref(external, objtype, ref_id)[source]View on GitHubο
Retrieves external cross-reference data from the
sphinx.ext.intersphinx
inventory- Parameters
- Returns
an
ExternalRef
object if the lookup was successful, otherwiseNone
- Return type
- get_external_id(external, role, ref_id)[source]View on GitHubο
Helper function to get the
ref_id
when replacing external xrefs
- is_external_xref(external, role, ref_id)[source]View on GitHubο
Helper function to check if a cross-reference is explicitly external
- Return type
- resolve()[source]View on GitHubο
Uses parsed data from to replace cross-references and directives in the
src_files
Once resolved, files are written to the
out_dir
.
- replace_admonitions(rst_src, rst)[source]View on GitHubο
Replaces generic and specific admonition directives with HTML tables or
list-table
directives, depending on the value ofreadme_raw_directive
Customizing Admonitions
The
icon_map
can be overriden to use custom admonition icons/classes
- replace_toctrees(rst_src, rst)[source]View on GitHubο
Replaces
toctree
directives with hyperlinked bullet listsNote
Entries will link to HTML documentation regardless of the value of
readme_docs_url_type
- replace_rst_images(rst_src, rst)[source]View on GitHubο
Replaces filepaths in
image
directives with repository linksExample:
.. image:: /_static/logo_readme.png
would be replaced with
.. image:: https://raw.githubusercontent.com/tdkorn/sphinx-readme/main/docs/source/_static/logo_readme.png
Note
Your repository will be used as the image source regardless of the value of
readme_docs_url_type
- replace_rubrics(rst_src, rst, force_markup=False)[source]View on GitHubο
Replaces
rubric
directives with the section heading character specified byreadme_rubric_heading
If
readme_rubric_heading
is not specified, the rubric will be replaced with bold text insteadβ¦
Example:
Consider a source file that contains
.. rubric:: This is a ``rubric`` directive
Replacement without specifying
readme_rubric_heading
:**This is a** ``rubric`` **directive**
Replacement if
readme_rubric_heading = "^"
:This is a ``rubric`` directive ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- replace_xrefs(rst_src, rst)[source]View on GitHubο
Replaces cross-references from the Standard Domain and reStructuredText Domain with substitutions or inline links
Tip
This includes cross-references for any custom objects added by
Sphinx.add_object_type()
- replace_py_xrefs(rst_src, rst)[source]View on GitHubο
Replace
PythonDomain
cross-references with substitutionsThese substitutions will be hyperlinked to the corresponding source code or HTML documentation entry, depending on the value of
readme_docs_url_type
- replace_unresolved_xrefs(rst)[source]View on GitHubο
Replaces any unresolved cross-references from all domains with inline literals
- Return type
- get_xref_regex(domains, roles=None, targets=None, xref_type=None)[source]View on GitHubο
Returns the regex to match cross-references
Note
The patterns have the following match groups:
- Regular Cross-References
The full cross-reference
The external role, if present
The cross-reference role
The cross-reference target
- Explicit Title Cross-References
The full cross-reference
The external role, if present
The cross-reference role
The explicit title
The cross-reference target
- Parameters
domains (Union[str, Iterable[str]]) β an individual or list of Sphinx object domains to match
roles (Optional[Union[str, Iterable[str]]]) β an individual or list of cross-reference roles to match; matches all domain roles if not provided
targets (Optional[Union[str, Iterable[str]]]) β an individual or list of targets to match; matches all xrefs if not provided
xref_type (Optional[str]) β the xref type to match (
"regular"
or"title"
); returns both if not specified
- Returns
the regex pattern to match regular xrefs, xrefs with explicit titles, or a tuple containing both
- Return type
- get_admonition_regex(admonition)[source]View on GitHubο
Returns the regex to match a specific admonition directive
- get_admonition_icon(admonition)[source]View on GitHubο
Returns the icon to use for an admonition
The READMEConfig
Classο
- class sphinx_readme.config.READMEConfig(app)[source]View on GitHubο
Bases:
object
- __init__(app)[source]View on GitHubο
- get_repo_url()[source]View on GitHubο
Generates the URL of the projectβs repository from the
html_context
dict- Raises
ExtensionError β if
html_context
is undefined or missing values- Return type
- get_docs_url()[source]View on GitHubο
Returns the base URL of the documentation source to use when resolving
autodoc
cross-referencesIf
docs_url_type
is"code"
: uses theblob_url
"html"
: uses thehtml_baseurl
- Raises
ExtensionError β if
html_baseurl
is undefined- Return type
- setup_linkcode_resolve(app)[source]View on GitHubο
Retrieves or defines a
linkcode_resolve()
function for your package
- read_rst(rst_file, replace_only=True, is_included=False)[source]View on GitHubο
Reads and partially parses an
rst
fileTip
Files are parsed as follows:
If
replace_only
isTrue
, only directives are replaced viareplace_only_directives()
If
readme_include_directive
isTrue
, include directives are replaced with the content of the included file; otherwise, the directives will be removedIf
readme_raw_directive
isFalse
, raw directives are removed
- parse_include_directives(rst, rst_file, replace_only=True)[source]View on GitHubο
- property src_files: Dict[str, Path]View on GitHubο
Absolute paths of the
readme_src_files
mapped to corresponding output files
- property sources: Dict[str, str]View on GitHubο
Absolute paths of source files mapped to their file content
- property out_dir: PathView on GitHubο
Absolute path of the directory to save generated
rst
files to (fromreadme_out_dir
)
- property docs_url_type: strView on GitHubο
Documentation source type (
"code"
or"html
β) for resolvingautodoc
cross-references
- property repo_host: strView on GitHubο
The platform that the projectβs repository is hosted on
- property image_baseurl: strView on GitHubο
The base URL to use when replacing images with
replace_rst_images()
- property icon_map: Dict[str, str]View on GitHubο
A mapping of admonition classes to their icons
The default mapping is as follows, but can be modified via
readme_admonition_icons
{ 'attention': 'ποΈ', 'caution': 'β οΈ', 'danger': 'β’', 'error': 'β', 'hint': 'π§ ', 'important': 'π’', 'note': 'π', 'tip': 'π‘', 'warning': 'π©', 'default': 'π' }
- property admonition_template: strView on GitHubο
The template to use when replacing admonitions with
replace_admonitions()
The sphinx_readme.utils
subpackageο
The sphinx_readme.utils
subpackage contains a variety of helper functions
The sphinx_readme.utils.git
submoduleο
- sphinx_readme.utils.git.get_repo_url(context)[source]View on GitHubο
Parses the repository URL from the Sphinx
html_context
dict
- sphinx_readme.utils.git.is_valid_username(username, host)[source]View on GitHubο
Validates a username on the given hosting platform.
Username Constraints
- GitHub
Usernames can only contain alphanumeric characters and hyphens; canβt start or end with a hyphen or have consecutive hyphens; must be between 1 and 39 characters long.
- GitLab
Usernames can only contain alphanumeric characters, underscores, hyphens, and periods; canβt start or end with special characters or contain consecutive special characters; must be between 2 and 255 characters long.
- BitBucket
Usernames can only contain alphanumeric characters, hyphens, and underscores.
- sphinx_readme.utils.git.is_valid_repo(repo, host)[source]View on GitHubο
Validates the name of a git repository on the given hosting platform.
Repository Name Constraints
- GitHub
Repository names can only contain alphanumeric characters, hyphens, underscores, and periods; must be between 1 and 100 characters long.
- GitLab
Repository name can only contain alphanumeric characters, hyphens, underscores, periods, β+β, or spaces. It must start with a letter, digit, or β_β and be at least 1 character long.
- BitBucket
Repository name can only contain alphanumeric characters, hyphens, underscores, and periods. It must start with an alphanumeric character, underscore or period and canβt have consecutive hyphens or end with a hyphen. Must be between 1 and 62 characters long.
- sphinx_readme.utils.git.get_blob_url(repo_url, blob=None, context=None)[source]View on GitHubο
Generates the base URL for a specific blob of a repository
- sphinx_readme.utils.git.get_repo_host(repo_url)[source]View on GitHubο
Returns the hosting platform of a repository
>>> get_repo_host("https://github.com/TDKorn/sphinx-readme") 'github'
- sphinx_readme.utils.git.get_blob(blob)[source]View on GitHubο
Returns the git blob corresponding to
blob
The value of
blob
can be any of"head"
,"last_tag"
, or"{blob}"
"head"
: returns the hash of the most recent commit; if this commit is tagged, uses the tag instead"last_tag"
: returns the most recent commit tag; if no tags exist, uses"head"
"{blob}"
: returns the specified blob as is, for example"master"
or"v2.0.1"
- Return type
- sphinx_readme.utils.git.get_head()[source]View on GitHubο
Returns the hash of the most recent commit
If the most recent commit is tagged, the tag is returned instead
- Raises
RuntimeError β if the most recent commit canβt be found
- Return type
- sphinx_readme.utils.git.get_last_tag()[source]View on GitHubο
Returns the most recent commit tag
- Raises
RuntimeError β if there are no tagged commits
- Return type
- sphinx_readme.utils.git.get_repo_dir()[source]View on GitHubο
Returns the root directory of the repository
- Returns
A Path object representing the working directory of the repository.
- Raises
RuntimeError β if the directory canβt be determined
- Return type
The sphinx_readme.utils.linkcode
submoduleο
- sphinx_readme.utils.linkcode.get_linkcode_url(blob_url=None, repo_url=None, context=None, blob=None)[source]View on GitHubο
Generates the template URL for linking to highlighted source code
Final links are generated from the template by a
linkcode_resolve()
functionNote
Only one of
blob_url
,repo_url
, orcontext
needs to be specified- Parameters
- Raises
ExtensionError β if none of
blob_url
,repo_url
, orcontext
are provided- Return type
- sphinx_readme.utils.linkcode.get_linkcode_resolve(linkcode_url)[source]View on GitHubο
Defines and returns a
linkcode_resolve()
function for your package- Parameters
linkcode_url (str) β the template URL for linking to source code (see
get_linkcode_url()
)- Return type
The sphinx_readme.utils.rst
submoduleο
- sphinx_readme.utils.rst.escape_rst(rst)[source]View on GitHubο
Escape regex special characters from the content of an
rst
file- Return type
- sphinx_readme.utils.rst.BEFORE_XREF = ':\\[\\{\\(/"\'\\-'ο
Characters that are allowed directly before a cross-reference
- sphinx_readme.utils.rst.AFTER_XREF = '\\.:;!\\?,"\'/\\\\\\]\\)\\}\\-'ο
Characters that are allowed directly after a cross-reference
- sphinx_readme.utils.rst.format_hyperlink(target, text, sub_override=None, force_subs=False)[source]View on GitHubο
Formats a hyperlink, preserving any
inline literals
within the textSince nested inline markup isnβt possible, substitutions are used when link text contains inline literals
Example:
>>> target = "https://www.github.com/tdkorn/sphinx-readme" >>> format_hyperlink(target, "The Sphinx README Repository") ('`The Sphinx README Repository <https://www.github.com/tdkorn/sphinx-readme>`_', [])
>>> format_hyperlink(target, "The ``Sphinx README`` Repository") ('|The Sphinx README Repository|_', ['.. |The Sphinx README Repository| replace:: The ``Sphinx README`` Repository', '.. _The Sphinx README Repository: https://www.github.com/tdkorn/sphinx-readme'])
>>> format_hyperlink(target, "The ``Sphinx README`` Repository", sub_override="repo") ('|repo|_', ['.. |repo| replace:: The ``Sphinx README`` Repository', '.. _repo: https://www.github.com/tdkorn/sphinx-readme'])
- Parameters
- Returns
a tuple containing the formatted hyperlink and a list of substitution definitions
- Return type
- sphinx_readme.utils.rst.format_rst(inline_markup, rst, replace_attributes=False)[source]View on GitHubο
Formats text with the specified type of inline markup
Preserves any
inline literals
,|substitutions|
, and`Custom Link Text <https://website.com>`_
within the textExample:
>>> format_rst("bold", "This is part of the ``sphinx_readme.utils`` module") "**This is part of the** ``sphinx_readme.utils`` **module**"
This is part of the
sphinx_readme.utils
module
- sphinx_readme.utils.rst.replace_only_directives(rst, tags)[source]View on GitHubο
Replaces and removes
only
directives.The
readme_tags
are temporarily added as tags, then the<expression>
argument of the directive is evaluated.If
True
, the content will be usedIf
False
, the directive is removed
Tip
The default value of
readme_tags
is["readme"]
Expression Examples:
Using default value of
readme_tags = ["readme"]
:.. only:: readme This will be included in the generated file .. only:: html This will be excluded from the generated file .. only:: readme or html This will be included in the generated file .. only:: readme and html This will be excluded from the generated file.
Setting
readme_tags = ["pypi"]
inconf.py
:.. only:: pypi This will be included in the generated file .. only:: readme This will be excluded from the generated file .. only:: readme or pypi This will be included in the generated file
- sphinx_readme.utils.rst.remove_raw_directives(rst)[source]View on GitHubο
Removes all
raw
directives fromrst
- sphinx_readme.utils.rst.replace_attrs(rst)[source]View on GitHubο
Replaces
:attr:
cross-references withinline literals
Tip
When
readme_replace_attrs
isTrue
, this function will be called to replaceNon-external and unresolved
:attr:
xrefs whenreadme_docs_url_type
is"code"
Unresolved
:attr:
xrefs whenreadme_docs_url_type
is"html"
- sphinx_readme.utils.rst.replace_xrefs(rst, roles=None)[source]View on GitHubο
Replaces cross-references in the
PythonDomain
withinline literals
- sphinx_readme.utils.rst.get_xref_variants(target)[source]View on GitHubο
Returns a list of ways to make a cross-reference to
target
Example:
>>> get_xref_variants('mod.Class.meth') ['mod.Class.meth', '.mod.Class.meth', '~mod.Class.meth', '~.mod.Class.meth']
- sphinx_readme.utils.rst.get_all_xref_variants(fully_qualified_name)[source]View on GitHubο
Returns all possible cross-reference targets for an object
Example:
>>> get_all_xref_variants("sphinx_readme.utils.get_all_xref_variants") ['get_all_xref_variants', '.get_all_xref_variants', '~get_all_xref_variants', '~.get_all_xref_variants', 'utils.get_all_xref_variants', '.utils.get_all_xref_variants', '~utils.get_all_xref_variants', '~.utils.get_all_xref_variants', 'sphinx_readme.utils.get_all_xref_variants', '.sphinx_readme.utils.get_all_xref_variants', '~sphinx_readme.utils.get_all_xref_variants', '~.sphinx_readme.utils.get_all_xref_variants']
The sphinx_readme.utils.sphinx
submoduleο
- class sphinx_readme.utils.sphinx.ExternalRef(objtype, pkg, version, target, label, ref_id)[source]View on GitHubο
Bases:
object
Data structure to parse external cross-reference data from intersphinx
- __init__(objtype, pkg, version, target, label, ref_id)[source]View on GitHubο
- property idView on GitHubο
- property labelView on GitHubο
- sphinx_readme.utils.sphinx.set_conf_val(app, attr, value)[source]View on GitHubο
Set the value of a
conf.py
config variable
The sphinx_readme.utils.docutils
submoduleο
- sphinx_readme.utils.docutils.get_doctree(app, rst, docname='index')[source]View on GitHubο
Generate doctree from a string of reStructuredText using Sphinx application.
- Return type
document
- sphinx_readme.utils.docutils.parse_node_text(node)[source]View on GitHubο
Parses the text from a node, preserving inline literals
- Return type