Welcome to sphinxcontrib-bibtex’s documentation!¶
- Release
2.5.0
- Date
Aug 22, 2022
Contents¶
Getting Started¶
Overview¶
The bibtex extension allows BibTeX
citations to be inserted into documentation generated by
Sphinx, via
a bibliography
directive,
along with :cite:p:
and :cite:t:
roles.
These work similarly to LaTeX’s thebibliography
environment
and the \citet
and \citep
commands.
For formatting, the extension relies on pybtex written by Andrey Golovizin. The extension is inspired by Matthew Brett’s bibstuff.sphinxext.bibref and Weston Nielson’s sphinx-natbib.
Download: https://pypi.org/project/sphinxcontrib-bibtex/#files
Documentation: https://sphinxcontrib-bibtex.readthedocs.io/en/latest/
Development: https://github.com/mcmtroffaes/sphinxcontrib-bibtex/
Installation¶
Install the module with pip install sphinxcontrib-bibtex
, or from
source using pip install -e .
. Then add:
extensions = ['sphinxcontrib.bibtex']
bibtex_bibfiles = ['refs.bib']
to your project’s Sphinx configuration file conf.py
.
Installation with python setup.py install
is discouraged due to potential
issues with the sphinxcontrib namespace.
Minimal Example¶
In your project’s documentation, you can use
:cite:t:
for textual citation references,
:cite:p:
for parenthetical citation references,
and .. bibliography::
for inserting the bibliography.
For example:
See :cite:t:`1987:nelson` for an introduction to non-standard analysis.
Non-standard analysis is fun :cite:p:`1987:nelson`.
.. bibliography::
where refs.bib
would contain an entry:
@Book{1987:nelson,
author = {Edward Nelson},
title = {Radically Elementary Probability Theory},
publisher = {Princeton University Press},
year = {1987}
}
In the default style, this will get rendered as:
See Nelson [Nel87a] for an introduction to non-standard analysis. Non-standard analysis is fun [Nel87a].
- Nel87a(1,2)
Edward Nelson. Radically Elementary Probability Theory. Princeton University Press, 1987.
Citations in sphinx are resolved globally across all documents.
Typically, you have a single bibliography
directive across
your entire project which collects all citations.
Advanced use cases with multiple bibliography
directives
across your project are also supported, but some care
needs to be taken from your end to avoid duplicate citations.
In contrast, footnotes in sphinx are resolved locally per document. To achieve local bibliographies per document, you can use citations represented by footnotes as follows:
See :footcite:t:`1987:nelson` for an introduction to non-standard analysis.
Non-standard analysis is fun\ :footcite:p:`1987:nelson`.
.. footbibliography::
which will get rendered as:
See Nelson1 for an introduction to non-standard analysis. Non-standard analysis is fun1.
Note the use of the backslash escaped space to suppress the space that would otherwise precede the footnote.
Typically, you have a single footbibliography
directive
at the bottom of each document that has footnote citations.
Advanced use cases with multiple footbibliography
directives
per document are also supported. Since everything is local,
there is no concern with duplicate citations when using footnotes.
Usage¶
Configuration¶
Bibliography Files and Encoding¶
New in version 2.0.0.
To configure the extension, in your conf.py
file,
set bibtex_bibfiles
to your list of bib files.
For instance, a minimal configuration may look as follows:
extensions = ['sphinxcontrib.bibtex']
bibtex_bibfiles = ['refs.bib']
In bib files, LaTeX control characters are automatically converted
to unicode characters (for instance, to convert \'e
into é
).
Be sure to write \%
when you intend to format a percent sign.
You can set the encoding of the bibliography files, using the
bibtex_encoding
variable in your conf.py
.
If no encoding is specified, utf-8-sig
is assumed.
For example:
bibtex_encoding = 'latin'
Bibliography Style¶
You can change the bibliography style,
using the bibtex_default_style
variable in your conf.py
.
If none is specified, the alpha
style is used.
Other supported styles are plain
, unsrt
, and unsrtalpha
.
Note that these four styles are identical except for labelling and sorting.
For example:
bibtex_default_style = 'unsrt'
You can also create your own style (see Custom Formatting, Sorting, and Labelling).
Referencing Style¶
New in version 2.2.0.
You can change the inline referencing style (i.e. the formatting
of the citation references themselves)
using the bibtex_reference_style
variable in your conf.py
.
Currently available built-in styles are:
label
: Use the labels generated by the bibliography style. Similar to natbib’snumbers
style and biblatex’snumeric
andalphabetic
styles (depending on the labelling style of your bibliography style). This is the default style.author_year
: Use the author and year. Similar to natbib’s and biblatex’sauthoryear
style. Note that this does not remove labels from bibliographies. This is because, in docutils, every citation must have a label.super
: Use the labels generated by the bibliography style as superscripts. This works best with numeric bibliography styles such asplain
. Similar to natbib’ssuper
style and biblatex’s\supercite
command.
The inline referencing style for footnote citations can be configured through
the bibtex_foot_reference_style
variable in your conf.py
.
Currently available built-in styles are:
foot
: Use footnotes for parenthetical citations, and author with footnote for textual citations. This is the default style (and currently also the only built-in style).
Python packages can make new styles available through
the sphinxcontrib.bibtex.style.referencing
entry point group.
See sphinxcontrib-bibtex’s own setup.py
script for examples.
Tooltips¶
New in version 2.4.2.
The extension will generate plain text tooltips for citation references, via the html title attribute, to allow a preview of the citation by hovering over the citation reference.
To disable these tooltips, set bibtex_tooltips
to False
.
By default, the bibliography style is used to format the tooltips.
You can set the bibtex_tooltips_style
option to use a different style.
Roles and Directives¶
- :cite:p:¶
New in version 2.2.0.
Create a parenthetical citation reference to a bibliographic entry. This will put the citation reference information (author and year, or label, depending on the style) between brackets. Similar to natbib’s
\citep
command, or biblatex’s\parencite
command. For example:We will make use of non-standard analysis :cite:p:`1987:nelson`.
which would be equivalent to the following LaTeX code:
We will make use of non-standard analysis \citep{1987:nelson}.
Multiple keys can be specified at once:
I love analysis :cite:p:`1987:nelson,2001:schechter`!
- :cite:t:¶
New in version 2.2.0.
Create a textual citation. This will typically render the name of the first author followed by the year or by the label, depending on the citation reference style. Similar to natbib’s
\citet
command, or biblatex’s\textcite
command. For example:See :cite:t:`1987:nelson` for an introduction to non-standard analysis.
which would be equivalent to the following LaTeX code:
See \citet{1987:nelson} for an introduction to non-standard analysis.
Here too, multiple keys can be specified at once.
- :cite:ps:¶
- :cite:ts:¶
- :cite:ct:¶
- :cite:cts:¶
New in version 2.2.0.
All these roles modify
cite:p
andcite:t
. The ones starting withc
will capitalize the first letter. The ones ending withs
will give the full author list.
- :cite:¶
This is an alias for the
cite:p
role, and will create a parenthetical citation reference. Provided for convenience and compatibility with older versions.
- :cite:label:¶
- :cite:labelpar:¶
New in version 2.2.0.
Create a citation using just the label. Use the
par
version to include brackets.
- :cite:year:¶
- :cite:yearpar:¶
New in version 2.2.0.
Create a citation using just the year. Use the
par
version to include brackets.
- :cite:author:¶
- :cite:authors:¶
- :cite:authorpar:¶
- :cite:authorpars:¶
- :cite:cauthor:¶
- :cite:cauthors:¶
New in version 2.2.0.
Create a citation using just the author(s). Use the
par
version to include brackets, and thec
version to capitalize the first letter.
- :cite:empty:¶
New in version 2.3.0.
Register a citation key as being cited without generating a reference, similar to LaTeX’s nocite command.
- .. bibliography::¶
Create bibliography for all cited references. Citations in sphinx are resolved globally across all documents. Typically, you have a single bibliography directive across your entire project which collects all citations. Citation keys can also be explicitly listed under the directive; see Listing Citation Keys.
Warning
Sphinx will attempt to resolve references to the bibliography across all documents, so you must take care that no citation key is included more than once.
The following options are recognized (all are optional).
- :all:¶
Include all references, instead of just the cited ones (equivalent to
\nocite{*}
in LaTeX). For example:.. bibliography:: :all:
- :notcited:¶
Causes all references that were not cited to be included. Listed references remain included.
- :cited:¶
This is the default and need not be specified.
- :style:¶
Overrides the default bibliography style. For example:
.. bibliography:: :style: unsrt
- :list:¶
- :enumtype:¶
- :start:¶
- :labelprefix:¶
See Label Prefixing.
- :keyprefix:¶
See Key Prefixing.
- :footcite:p:¶
New in version 2.3.0.
Create a parenthetical footnote reference to a bibliographic entry. For example:
We will make use of non-standard analysis\ :footcite:p:`1987:nelson`.
which would be equivalent to the following LaTeX code:
We will make use of non-standard analysis\footcite{1987:nelson}.
Note the use of the backslash escaped space to suppress the space that would otherwise precede the footnote.
As with all citation roles, multiple keys can be specified:
I love analysis\ :footcite:p:`1987:nelson,2001:schechter`!
- :footcite:t:¶
New in version 2.3.0.
Create a textual footnote reference to a bibliographic entry. For example:
See :footcite:t:`1987:nelson` for an introduction to non-standard analysis.
which would be equivalent to the following LaTeX code:
See Nelson\footcite{1987:nelson} for an introduction to non-standard analysis.
Here too, multiple keys can be specified at once.
- :footcite:ps:¶
- :footcite:ts:¶
- :footcite:ct:¶
- :footcite:cts:¶
New in version 2.3.0.
All these roles modify
footcite:p
andfootcite:t
. The ones starting withc
will capitalize the first letter. The ones ending withs
will give the full author list.
- :footcite:¶
New in version 2.0.0.
This is an alias for the
footcite:p
role, and will create a parenthetical footnote citation reference. Provided for convenience and compatibility with older versions.
- .. footbibliography::¶
New in version 2.0.0.
Create footnotes at this location for all references that are cited in the current document up to this point. Typically, you have a single footbibliography directive at the bottom of each document that has footcite citations.
Standard numeric footnote labels are used, so the label style is ignored. Footnotes are inserted in the order in which they occur in the document, so the sorting style is also ignored.
If specified multiple times in the same document, footnotes are only created for references that do not yet have a footnote earlier in the document.
Markdown Syntax Using MyST¶
If you use the MyST parser, all roles and directives are also available in Markdown syntax. For example:
See {cite:p}`1987:nelson` for an introduction to non-standard analysis.
```{bibliography} references.bib
```
Advanced Features¶
Splitting Bibliographies Per Bib File¶
New in version 2.0.0.
If you want multiple bibliographies each of which only contains references from specific bib files, you can specify the relevant bib files as an optional argument to the directive.
The next example shows how to split your citations between
articles and books, assuming your articles are in articles.bib
and your books are in books1.bib
and books2.bib
.
.. rubric:: Articles
.. bibliography:: articles.bib
.. rubric:: Books
.. bibliography:: books1.bib books2.bib
The bib files must be specified as a path that is relative to the containing document.
Bullet Lists and Enumerated Lists¶
New in version 0.2.4.
You can change the type of list used for rendering the bibliography. By default, a paragraph of standard citations is generated. However, instead, you can also generate a bullet list, or an enumerated list.
.. bibliography::
:list: bullet
:all:
.. bibliography::
:list: enumerated
:all:
Note that citations to these types of bibliography lists will not be resolved.
For enumerated lists, you can also specify the type (default is
arabic
), and the start of the sequence (default is 1
).
.. bibliography::
:list: enumerated
:enumtype: upperroman
:start: 3
:all:
The enumtype can be any of
arabic
(1, 2, 3, …),
loweralpha
(a, b, c, …),
upperalpha
(A, B, C, …),
lowerroman
(i, ii, iii, …), or
upperroman
(I, II, III, …).
The start can be any positive integer (1, 2, 3, …) or
continue
if you wish the enumeration to continue from the last
bibliography
directive.
This is helpful if you split up your bibliography but
still want to enumerate the entries continuously.
Listing Citation Keys¶
New in version 2.3.0.
If you have many citations to include that are not referenced anywhere,
then instead of using cite:empty
it can be more convenient to simply list the citation keys directly under
the bibliography directive where you want them to appear.
Such references can be listed by having one bibtex key per line under the
directive.
The keys should not have a key prefix if you are using that option
(see Key Prefixing).
For example:
.. bibliography::
nelson1987
boole1854
This would cause the bibliography to generate citations for all cited
references, in addition to citations with bibtex keys nelson1987
and boole1854
.
The listed keys are always included regardless of filtering.
So, if you only want the listed keys to be included, you can use the
:filter: False
option:
.. bibliography::
:filter: False
nelson1987
boole1854
See Filtering for more information on filtering.
Label Prefixing¶
New in version 0.2.5.
If you have multiple bibliographies, and experience duplicate labels,
use the labelprefix
option.
.. rubric:: References
.. bibliography::
:cited:
:labelprefix: A
.. rubric:: Further reading
.. bibliography::
:notcited:
:labelprefix: B
Key Prefixing¶
New in version 0.3.3.
If you have multiple bibliographies, and you would like entries to be
repeated in different documents, then use the keyprefix
option.
For example, suppose you have two documents, and you would like to cite
boole1854
in both of these documents, with the bibliography entries
showing in both of the documents. In one document you could have:
See :cite:`a-boole1854`
.. bibliography::
:labelprefix: A
:keyprefix: a-
whilst in the other document you could have:
See :cite:`b-boole1854`
.. bibliography::
:labelprefix: B
:keyprefix: b-
The bibliographies will then both generate an entry for boole1854
,
with links and backlinks as expected.
If you list citation keys, you should include those without key prefix. For example:
.. bibliography::
:labelprefix: B
:keyprefix: b-
nelson1987
See also
Filtering¶
New in version 0.2.7.
Whilst the cited
, all
, and notcited
options
along with Listing Citation Keys
will cover many use cases,
sometimes more advanced selection of bibliographic entries is desired.
For this purpose, you can use the filter
option:
.. bibliography::
:list: bullet
:filter: author % "Einstein"
The string specified in the filter option must be a valid Python expression.
Note
The expression is parsed using ast.parse()
and then evaluated using an ast.NodeVisitor
.
The filter expression supports:
The boolean operators
and
,or
.The unary operator
not
.The comparison operators
==
,<=
,<
,>=
, and>
.Regular expression matching using the
%
operator, where the left hand side is the string to be matched, and the right hand side is the regular expression. Matching is case insensitive. For example:.. bibliography:: :list: bullet :filter: title % "relativity"
would include all entries that have the word “relativity” in the title.
Note
The implementation uses
re.search()
.Single and double quoted strings, such as
'hello'
or"world"
.Set literals, such has
{"hello", "world"}
, as well as the set operators&
,|
,in
, andnot in
.New in version 0.3.0.
Various identifiers, such as:
type
is the entry type, as a lower case string (i.e."inproceedings"
).key
is the entry key, as a lower case string (this is because keys are considered case insensitive).cited
evaluates toTrue
if the entry was cited in the document, and toFalse
otherwise.docname
evaluates to the name of the current document.New in version 0.3.0.
docnames
evaluates to a set of names from which the entry is cited.New in version 0.3.0.
True
andFalse
.author
is the entry string of authors in standard format (last, first), separated by “and”.editor
is similar toauthor
but for editors.Any other (lower case) identifier evaluates to a string containing the value of the correspondingly named field, such as
title
,publisher
,year
, and so on. If the item is missing in the entry then it evaluates to the empty string. Here is an example of how one would typically write an expression to filter on an optional field:.. bibliography:: :list: bullet :filter: cited and year and (year <= "2003")
which would include all cited entries that have a year that is less or equal than 2003; any entries that do not specify a year would be omitted.
Local Bibliographies¶
The easiest way to have a local bibliography per
document is to use
footcite
along with footbibliography
.
If you prefer to have regular citations instead of footnotes,
both the keyprefix
and filter
options can be used
to achieve local bibliographies
with cite
and bibliography
.
The filter
system for local bibliographies
can only be used if no citation key is used in more than one
document. This is not always satisfied. If you need to cite the same
reference in multiple documents with references to multiple local
bibliographies, use the keyprefix
system; see
Key Prefixing.
To create a bibliography that includes only citations that were cited in the current document, use the following filter:
.. bibliography::
:filter: docname in docnames
More generally, you can create bibliographies for citations that were cited from specific documents only:
.. bibliography::
:filter: {"doc1", "doc2"} & docnames
This bibliography will include all citations that were cited from
doc1.rst
or doc2.rst
. Another hypothetical example:
.. bibliography::
:filter: cited and ({"doc1", "doc2"} >= docnames)
This bibliography will include all citations that were cited
in doc1.rst
or doc2.rst
, but nowhere else.
Custom Formatting, Sorting, and Labelling¶
pybtex
provides a very powerful way to create and register new
styles, using setuptools entry points,
as documented here: https://docs.pybtex.org/api/plugins.html
Simply add the following code to your conf.py
:
import pybtex.plugin
from pybtex.style.formatting.unsrt import Style as UnsrtStyle
from pybtex.style.template import toplevel # ... and anything else needed
class MyStyle(UnsrtStyle):
def format_XXX(self, e):
template = toplevel [
# etc.
]
return template.format_data(e)
pybtex.plugin.register_plugin('pybtex.style.formatting', 'mystyle', MyStyle)
Now mystyle
will be available to you as a formatting style:
bibtex_default_style = 'mystyle'
An minimal example is available here: https://github.com/mcmtroffaes/sphinxcontrib-bibtex/tree/develop/test/roots/test-bibliography_style_nowebref
The formatting code uses a very intuitive template engine.
The source code for unsrt
provides many great examples:
https://bitbucket.org/pybtex-devs/pybtex/src/master/pybtex/style/formatting/unsrt.py?at=master&fileviewer=file-view-default
The above example only demonstrates a custom formatting style plugin.
It is also possible to register custom author/editor naming plugins
(using the pybtex.style.names
group),
labelling plugins
(using the pybtex.style.labels
group),
and sorting plugins
(using the pybtex.style.sorting
group).
A few minimal examples demonstrating how to create custom label styles
are available here:
Custom Inline Citation References¶
New in version 2.2.0.
You can create and register your own referencing styles.
For instance, say we wish to use the author-year style with round brackets
instead of the default square brackets.
Simply add the following code to your conf.py
:
from dataclasses import dataclass, field
import sphinxcontrib.bibtex.plugin
from sphinxcontrib.bibtex.style.referencing import BracketStyle
from sphinxcontrib.bibtex.style.referencing.author_year \
import AuthorYearReferenceStyle
def bracket_style() -> BracketStyle:
return BracketStyle(
left='(',
right=')',
)
@dataclass
class MyReferenceStyle(AuthorYearReferenceStyle):
bracket_parenthetical: BracketStyle = field(default_factory=bracket_style)
bracket_textual: BracketStyle = field(default_factory=bracket_style)
bracket_author: BracketStyle = field(default_factory=bracket_style)
bracket_label: BracketStyle = field(default_factory=bracket_style)
bracket_year: BracketStyle = field(default_factory=bracket_style)
sphinxcontrib.bibtex.plugin.register_plugin(
'sphinxcontrib.bibtex.style.referencing',
'author_year_round', MyReferenceStyle)
Warning
You must decorate your style as a dataclass, and include a type annotation with every field, to ensure these values are correctly passed to the constructor when sphinxcontrib-bibtex instantiates your style.
Now author_year_round
will be available to you as a formatting style:
bibtex_reference_style = 'author_year_round'
An minimal example is available here: https://github.com/mcmtroffaes/sphinxcontrib-bibtex/tree/develop/test/roots/test-citation_style_round_brackets
Custom Html Anchors¶
New in version 2.4.0.
For every citation and every bibliography, an identifier
of the form idxxx
(where xxx
is some number) is generated.
These identifiers can be used as html anchors.
They are automatically
generated by docutils and are thereby guaranteed not to clash.
However, sometimes it is useful to refer to bibliographic entries from other
external documents that have not been generated with Sphinx.
Since the generated identifiers can easily break when updating documents,
they can be customized through string templates should you need this.
If you do so, it is your responsibility to ensure that no anchors will clash,
by setting up the appropriate identifier templates in your conf.py
file,
for instance as follows:
bibtex_cite_id = "cite-{bibliography_count}-{key}"
bibtex_footcite_id = "footcite-{key}"
bibtex_bibliography_id = "bibliography-{bibliography_count}"
bibtex_footbibliography_id = "footbibliography-{footbibliography_count}"
If you have at most one bibliography
directive per document,
then you can also use:
bibtex_cite_id = "cite-{key}"
The bibliography_count
template variable
counts bibliography
directives in the current document,
thus giving a unique number for each bibliography
directive
within a document.
The footbibliography_count
template variable works similarly but for
footbibliography
directives.
The key
template variable corresponds to the bibtex citation key,
including the key prefix if specified.
After formatting the template, the resulting string is filtered through
docutils’s make_id
function, which will remove and/or translate
any illegal characters.
In particular, colons and underscores will be translated into dashes.
Warning
If you have more than one bibliography
directive in any document,
then you must include bibliography_count
as part of your bibtex_cite_id
template to avoid issues with duplicate identifiers,
even if there are no duplicate citations.
This is because the extension must generate an identifier for every key
for each bibliography
directive
prior to knowing whether or not the citation needs to be included.
Custom Bibliography Header¶
New in version 2.0.0.
By default, the bibliography
and footbibliography
directives
simply insert a paragraph.
The bibtex_bibliography_header
and bibtex_footbibliography_header
configuration variables can be set
to add a header to this. For example, in your conf.py
you could
have:
bibtex_bibliography_header = ".. rubric:: References"
bibtex_footbibliography_header = bibtex_bibliography_header
This adds a rubric title to every bibliography.
Suppressing Warnings¶
New in version 2.3.1.
To suppress all warnings from sphinxcontrib-bibtex
(which is probably a bad idea!), add this to your conf.py
:
suppress_warnings = ["bibtex"]
To suppress only a subset of warnings, such as duplicate label warnings, you can use:
suppress_warnings = ["bibtex.duplicate_label"]
The complete list of warning subtypes that can be suppressed is:
bibtex.bibfile_data_error
bibtex.bibfile_error
bibtex.duplicate_citation
bibtex.duplicate_id
bibtex.duplicate_label
bibtex.filter_overrides
bibtex.filter_syntax_error
bibtex.key_not_found
bibtex.list_type_error
bibtex.missing_field
Known Issues and Workarounds¶
Encoding: Percent Signs¶
Be sure to write
\%
for percent signs at all times in your bib files
(unless your file contains a genuine comment),
otherwise the pybtex parser will ignore the remainder of the line.
Duplicate Labels When Using :style: plain
¶
With :style: plain
, labels are numeric,
restarting at [1]
for each bibliography
directive.
Consequently, when inserting multiple bibliography
directives
with :style: plain
,
you are bound to get duplicate labels for entries.
There are a few ways to work around this problem:
Use a single bibliography directive for all your references.
Use the
labelprefix
option, as documented above.Use a style that has non-numeric labelling, such as
:style: alpha
.
LaTeX Backend Fails with Citations In Figure Captions¶
Sphinx generates \phantomsection
commands for references,
however LaTeX does not support these in figure captions.
You can work around this problem by adding the following code to
your conf.py
:
latex_elements = {
'preamble': r'''
% make phantomsection empty inside figures
\usepackage{etoolbox}
\AtBeginEnvironment{figure}{\renewcommand{\phantomsection}{}}
'''
}
Warning
The above workaround no longer appears to work. If you know of a solution, please report at https://github.com/mcmtroffaes/sphinxcontrib-bibtex/issues/276
Mismatch Between Output of HTML/Text and LaTeX Backends¶
Sphinx’s LaTeX writer currently collects all citations together, and puts them on a separate page, with a separate title, whereas the html and text writers puts citations at the location where they are defined. This issue will occur also if you use regular citations in Sphinx: it has nothing to do with sphinxcontrib-bibtex per se.
To get a closer match between the two outputs, you can tell Sphinx to generate a rubric title only for html or text outputs:
.. only:: html or text
.. rubric:: References
.. bibliography::
This code could be placed in a references.rst
file that
you include at the end of your toctree.
Alternatively, to remove the bibliography section title from the LaTeX output, you can add the following to your LaTeX preamble:
\usepackage{etoolbox}
\patchcmd{\thebibliography}{\section*{\refname}}{}{}{}
Citation References Not Rendered In TocTree Directives¶
When a document title has a citation reference in it, the toctree directive will simply take the target of the reference for rendering in the table of contents, rather than the fully rendered reference.
This appears to be a limitation of the toctree directive. No workaround is currently known.
Unknown Target Name When Using Footnote Citations With Numpydoc¶
Numpydoc will sometimes duplicate the short description (i.e. the first line
of the docstring) of some python objects
such as member functions. If it does that, and you have a footnote citation
in the short description, Sphinx may not be able to properly resolve
the footnote target.
If this happens,
the workaround is not to have footnote citations in the first line of
your docstrings. Instead, put them in the long description.
Alternatively, set numpydoc_class_members_toctree
to False
in your conf.py
file. This will cause numpydoc not to
duplicate the short descriptions for class members.
Import errors after using setup.py install¶
Because sphinxcontrib-bibtex uses the standard sphinxcontrib namespace, installing the package using
python setup.py install
may result in a broken installation. This appears to be an issue with setuptools. As pip does not have this problem, it is recommended to install the package with pip:
pip install .
Import errors when running pytest¶
The test suite relies on the entry points being installed, whence, sphinxcontrib-bibtex cannot be tested without first installing the package. To run the tests, please do as follows (ideally, in a virtual environment):
pip install . -e
cd test/
pytest
Extension API¶
Sphinx Interface¶
New Roles¶
- class sphinxcontrib.bibtex.roles.CitationRef(citation_ref_id: str, docname: str, line: int, keys: List[str])[source]¶
Information about a citation reference.
- property citation_ref_id¶
Unique id of this citation reference.
- property docname¶
Document name.
- property keys¶
Citation keys (including key prefix).
- property line¶
Line number.
- class sphinxcontrib.bibtex.roles.CiteRole(fix_parens: bool = False, lowercase: bool = False, nodeclass: Optional[Type[Element]] = None, innernodeclass: Optional[Type[TextElement]] = None, warn_dangling: bool = False)[source]¶
Bases:
XRefRole
Class for processing the
cite
role.
- class sphinxcontrib.bibtex.foot_roles.FootCiteRole(fix_parens: bool = False, lowercase: bool = False, nodeclass: Optional[Type[Element]] = None, innernodeclass: Optional[Type[TextElement]] = None, warn_dangling: bool = False)[source]¶
Bases:
XRefRole
Class for processing the
footcite
role.- result_nodes(document: docutils.nodes.document, env: BuildEnvironment, node: docutils.nodes.Element, is_ref: bool) Tuple[List[docutils.nodes.Node], List[docutils.nodes.system_message]] [source]¶
Transform node into footnote references, and add footnotes to a node stored in the environment’s temporary data if they are not yet present.
See also
The node containing all footnotes is inserted into the document by
foot_directives.FootBibliographyDirective.run()
.
New Docutils Nodes¶
- class sphinxcontrib.bibtex.nodes.bibliography(rawsource='', *children, **attributes)[source]¶
Node for representing a bibliography. Replaced by a list of citations by
BibliographyTransform
.
- class sphinxcontrib.bibtex.nodes.raw_latex(rawsource='', text='', *children, **attributes)[source]¶
Node for representing raw latex data.
New Docutils Directives¶
- class sphinxcontrib.bibtex.directives.BibliographyKey(docname: str, id_: str)[source]¶
Unique key for each bibliography directive.
- property docname¶
Name of the document where the bibliography resides.
- property id_¶
The id of the bibliography node in the document.
- class sphinxcontrib.bibtex.directives.BibliographyValue(line: int, bibfiles: List[str], style: str, list_: str, enumtype: str, start: int, labelprefix: str, keyprefix: str, filter_: AST, citation_nodes: Dict[str, Element], keys: List[str])[source]¶
Contains information about a bibliography directive.
- property bibfiles¶
List of bib files for this directive.
- property citation_nodes¶
key -> citation node
- property enumtype¶
The sequence type (for enumerated lists).
- property filter_¶
Parsed filter expression.
- property keyprefix¶
String prefix for citation keys.
- property keys¶
Keys listed as content of the directive.
- property labelprefix¶
String prefix for pybtex generated labels.
- property line¶
Line number of the directive in the document.
- property list_¶
The list type.
- property start¶
The start of the sequence (for enumerated lists).
- property style¶
The pybtex style.
- class sphinxcontrib.bibtex.directives.BibliographyDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶
Class for processing the
bibliography
directive.Produces a
bibliography
node, along with (empty) citation nodes that will be formatted later in the env-updated stage, and inserted into the document in a post-transform. We cannot insert the citation nodes here because we do not yet know which keys have been cited.See also
Further processing of the resulting
bibliography
node is done byBibliographyTransform
.
- class sphinxcontrib.bibtex.foot_directives.FootBibliographyDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶
Class for processing the
footbibliography
directive.- run()[source]¶
Set file dependencies, and insert the footnotes that were created earlier by
foot_roles.FootCiteRole.result_nodes()
.
New Transforms¶
- class sphinxcontrib.bibtex.transforms.BibliographyTransform(document, startnode=None)[source]¶
Bases:
SphinxPostTransform
A docutils transform to generate citation entries for bibliography nodes.
- default_priority = 5¶
Numerical priority of this transform, 0 through 999 (override).
- run(**kwargs)[source]¶
Transform each
bibliography
node into a list of citations.
New Domains¶
Classes and methods to maintain any bibtex information that is stored outside the doctree.
- class sphinxcontrib.bibtex.domain.Citation(citation_id: str, bibliography_key: BibliographyKey, key: str, entry: Entry, formatted_entry: FormattedEntry, tooltip_entry: Optional[FormattedEntry])[source]¶
Information about a citation.
- property bibliography_key¶
Key of its bibliography directive.
- property citation_id¶
Unique id of this citation.
- property entry¶
Entry from pybtex.
- property formatted_entry¶
Formatted entry for bibliography.
- property key¶
Key (with prefix).
- property tooltip_entry¶
Formatted entry for tooltip.
- class sphinxcontrib.bibtex.domain.BibtexDomain(env: BuildEnvironment)[source]¶
Sphinx domain for the bibtex extension.
- property bibliographies: Dict[BibliographyKey, BibliographyValue]¶
Map storing information about each bibliography directive.
- property citation_refs: List[CitationRef]¶
Citation reference data.
- clear_doc(docname: str) None [source]¶
Remove traces of a document in the domain-specific inventories.
- data_version = 4¶
data version, bump this when the format of self.data changes
- get_all_cited_keys(docnames)[source]¶
Yield all citation keys for given docnames in order, then ordered by citation order.
- get_entries(bibfiles: List[str]) Iterable[Entry] [source]¶
Return all bibliography entries from the bib files, unsorted (i.e. in order of appearance in the bib files.
- get_filtered_entries(bibliography_key: BibliographyKey) Iterable[Tuple[str, Entry]] [source]¶
Return unsorted bibliography entries filtered by the filter expression.
- get_formatted_entries(bibliography_key: BibliographyKey, docnames: List[str], tooltips: bool, tooltips_style: str) Iterable[Tuple[Entry, FormattedEntry, Optional[FormattedEntry]]] [source]¶
Get sorted bibliography entries along with their pybtex labels, with additional sorting and formatting applied from the pybtex style.
- get_sorted_entries(bibliography_key: BibliographyKey, docnames: List[str]) Iterable[Tuple[str, Entry]] [source]¶
Return filtered bibliography entries sorted by citation order.
- initial_data: Dict = {'bibdata': BibData(encoding='', bibfiles={}, data=BibliographyData( entries=OrderedCaseInsensitiveDict([]), preamble=[])), 'bibliographies': {}, 'bibliography_header': <container: >, 'citation_refs': [], 'citations': []}¶
data value for a fresh environment
- label = 'BibTeX Citations'¶
domain label: longer, more descriptive (used in messages)
- merge_domaindata(docnames: List[str], otherdata: Dict) None [source]¶
Merge in data regarding docnames from a different domaindata inventory (coming from a subprocess in parallel builds).
- name = 'cite'¶
domain name: should be short, but unique
Domain for footnote citations.
- class sphinxcontrib.bibtex.foot_domain.BibtexFootDomain(env: BuildEnvironment)[source]¶
Sphinx domain for footnote citations.
- data_version = 0¶
data version, bump this when the format of self.data changes
- initial_data: Dict = {'bibliography_header': <container: >}¶
data value for a fresh environment
- label = 'BibTeX Footnote Citations'¶
domain label: longer, more descriptive (used in messages)
- merge_domaindata(docnames: List[str], otherdata: Dict) None [source]¶
Merge in data regarding docnames from domain data inventory otherdata.
As there is no document specific data for this domain, this function does nothing.
- name = 'footcite'¶
domain name: should be short, but unique
- resolve_any_xref(env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) List[Tuple[str, Element]] [source]¶
Resolve the pending reference node with the given target, where the reference comes from an “any” role.
Since citation references are resolved to regular citations, and not to footnote citations, this implementation simply returns an empty list.
Bib Files¶
Classes and methods to work with bib files.
- class sphinxcontrib.bibtex.bibfile.BibFile(mtime: float, keys: Dict[str, None])[source]¶
Contains information about a parsed bib file.
- property keys¶
Set of keys for this bib file as ordered dict.
- property mtime¶
Modification time of file when last parsed.
- class sphinxcontrib.bibtex.bibfile.BibData(encoding: str, bibfiles: Dict[str, BibFile], data: BibliographyData)[source]¶
Contains information about a collection of bib files.
- property bibfiles¶
Maps bib filename to information about it.
- property data¶
Data parsed from all bib files.
- property encoding¶
Encoding of all bib files.
- sphinxcontrib.bibtex.bibfile.normpath_filename(env: BuildEnvironment, filename: str) str [source]¶
Return normalised path to filename for the given environment env.
- sphinxcontrib.bibtex.bibfile.parse_bibdata(bibfilenames: List[str], encoding: str) BibData [source]¶
Parse bibfilenames with given encoding, and return parsed data.
Referencing Styles¶
Base Classes For Composing Styles¶
- class sphinxcontrib.bibtex.style.referencing.BaseReferenceStyle[source]¶
Base class for citation reference styles.
For consistency, all subclasses of this class must be decorated as a
dataclass
, and must provide a type annotation and default value for all attributes (unlessinit=False
is used, in which case they can be initialized in__post_init__()
). This allows client code to instantiate any reference style without needing to specify any arguments through the constructor.
- class sphinxcontrib.bibtex.style.referencing.BracketStyle(left: Union[BaseText, str] = '[', right: Union[BaseText, str] = ']', sep: Union[BaseText, str] = ', ', sep2: Optional[Union[BaseText, str]] = None, last_sep: Optional[Union[BaseText, str]] = None)[source]¶
A class which provides brackets, as well as separators and a function to facilitate formatting of the outer template.
- last_sep: Optional[Union[BaseText, str]] = None¶
Separator for outer template, for last item if three or more items.
- outer(children: List[BaseText], brackets=False, capfirst=False) Node [source]¶
Creates an outer template with separators, adding brackets if requested, and capitalizing the first word if requested.
- class sphinxcontrib.bibtex.style.referencing.GroupReferenceStyle(styles: ~typing.List[~sphinxcontrib.bibtex.style.referencing.BaseReferenceStyle] = <factory>, role_style: ~typing.Dict[str, ~sphinxcontrib.bibtex.style.referencing.BaseReferenceStyle] = <factory>)[source]¶
Composes a group of reference styles into a single consistent style.
- inner(role_name: str) Node [source]¶
Gets the inner template associated with role_name in one of the
styles
.
- outer(role_name: str, children: List[BaseText]) Node [source]¶
Gets the outer template associated with role_name in one of the
styles
.
- role_style: Dict[str, BaseReferenceStyle]¶
Dictionary from role names to styles. Automatically initialized from
styles
.
- styles: List[BaseReferenceStyle]¶
List of style types.
- class sphinxcontrib.bibtex.style.referencing.PersonStyle(style: str = 'last', abbreviate: bool = True, sep: ~typing.Union[BaseText, str] = ', ', sep2: ~typing.Optional[~typing.Union[BaseText, str]] = ' and ', last_sep: ~typing.Optional[~typing.Union[BaseText, str]] = ', and ', other: ~typing.Optional[~typing.Union[BaseText, str]] = <factory>)[source]¶
A class providing additional data and helper functions to facilitate formatting of person names.
- author_or_editor_or_title(full: bool) Node [source]¶
Returns a template formatting the author, falling back on editor or title if author is not specified.
- last_sep: Optional[Union[BaseText, str]] = ', and '¶
Separator between persons, for last person if three or more persons.
- sphinxcontrib.bibtex.style.referencing.format_references(style: BaseReferenceStyle, role_name: str, references: Iterable[Tuple[Entry, FormattedEntry, ReferenceInfo]]) BaseText [source]¶
Format the list of references according to the given role.
First formats each reference using the style’s
get_inner()
method, then joins all these formatted references together using the style’sget_outer()
method.
Basic Styles¶
Basic styles that support both textual and parenthetical citations.
Should provide roles with names
p
, ps
, t
, ts
, ct
, and cts
.
Here, t
stands for textual and p
for parenthetical.
The c
prefix causes the first letter to be capitalized,
and the s
suffix causes all authors to be named rather than
shortening the list using “et al.” or some other suffix as
specified by the style.
- class sphinxcontrib.bibtex.style.referencing.basic_label.BasicLabelParentheticalReferenceStyle(bracket: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>)[source]¶
Reference by label if parenthetical, and by author and label if textual.
- bracket: BracketStyle¶
Bracket style.
- class sphinxcontrib.bibtex.style.referencing.basic_label.BasicLabelTextualReferenceStyle(bracket: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, person: ~sphinxcontrib.bibtex.style.referencing.PersonStyle = <factory>, text_reference_sep: ~typing.Union[BaseText, str] = ' ')[source]¶
Reference by label if parenthetical, and by author and label if textual.
- bracket: BracketStyle¶
Bracket style.
- outer(role_name: str, children: List[BaseText]) Node [source]¶
Returns outer template for formatting the references.
- person: PersonStyle¶
Person style.
- class sphinxcontrib.bibtex.style.referencing.basic_author_year.BasicAuthorYearParentheticalReferenceStyle(bracket: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, person: ~sphinxcontrib.bibtex.style.referencing.PersonStyle = <factory>, author_year_sep: ~typing.Union[BaseText, str] = ', ')[source]¶
Parenthetical reference by author-year.
- bracket: BracketStyle¶
Bracket style.
- outer(role_name: str, children: List[BaseText]) Node [source]¶
Returns outer template for formatting the references.
- person: PersonStyle¶
Person style.
- class sphinxcontrib.bibtex.style.referencing.basic_author_year.BasicAuthorYearTextualReferenceStyle(bracket: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, person: ~sphinxcontrib.bibtex.style.referencing.PersonStyle = <factory>, text_reference_sep: ~typing.Union[BaseText, str] = ' ')[source]¶
Textual reference by author-year.
- bracket: BracketStyle¶
Bracket style.
- outer(role_name: str, children: List[BaseText]) Node [source]¶
Returns outer template for formatting the references.
- person: PersonStyle¶
Person style.
Extra Styles¶
For styles providing additional roles, e.g. for citations that
specifically use the label, the author, the year, etc.
The convention for these styles is to have one role for producing
whichever text needs to be had, and to have a par
suffix
in the role name if the citation text needs to be embedded in
brackets (for example label
and labelpar
).
- class sphinxcontrib.bibtex.style.referencing.extra_label.ExtraLabelReferenceStyle(bracket: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>)[source]¶
Reference just by label.
- bracket: BracketStyle¶
Bracket style.
- class sphinxcontrib.bibtex.style.referencing.extra_author.ExtraAuthorReferenceStyle(bracket: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, person: ~sphinxcontrib.bibtex.style.referencing.PersonStyle = <factory>)[source]¶
Reference just by author names.
- bracket: BracketStyle¶
Bracket style.
- outer(role_name: str, children: List[BaseText]) Node [source]¶
Returns outer template for formatting the references.
- person: PersonStyle¶
Person style.
- class sphinxcontrib.bibtex.style.referencing.extra_year.ExtraYearReferenceStyle(bracket: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>)[source]¶
Reference just by year.
- bracket: BracketStyle¶
Bracket style.
Full Styles¶
For styles that combine a basic style with one or more extra styles.
- class sphinxcontrib.bibtex.style.referencing.label.LabelReferenceStyle(styles: ~typing.List[~sphinxcontrib.bibtex.style.referencing.BaseReferenceStyle] = <factory>, role_style: ~typing.Dict[str, ~sphinxcontrib.bibtex.style.referencing.BaseReferenceStyle] = <factory>, bracket_textual: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, bracket_parenthetical: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, bracket_author: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, bracket_label: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, bracket_year: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, person: ~sphinxcontrib.bibtex.style.referencing.PersonStyle = <factory>, text_reference_sep: ~typing.Union[BaseText, str] = ' ')[source]¶
Textual or parenthetical reference by label, or just by author, label, or year.
- bracket_author: BracketStyle¶
Bracket style for author citations (:cite:author: and variations).
- bracket_label: BracketStyle¶
Bracket style for label citations (:cite:label: and variations).
- bracket_parenthetical: BracketStyle¶
Bracket style for parenthetical citations (:cite:p: and variations).
- bracket_textual: BracketStyle¶
Bracket style for textual citations (:cite:t: and variations).
- bracket_year: BracketStyle¶
Bracket style for year citations (:cite:year: and variations).
- person: PersonStyle¶
Person style.
- class sphinxcontrib.bibtex.style.referencing.author_year.AuthorYearReferenceStyle(styles: ~typing.List[~sphinxcontrib.bibtex.style.referencing.BaseReferenceStyle] = <factory>, role_style: ~typing.Dict[str, ~sphinxcontrib.bibtex.style.referencing.BaseReferenceStyle] = <factory>, bracket_textual: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, bracket_parenthetical: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, bracket_author: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, bracket_label: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, bracket_year: ~sphinxcontrib.bibtex.style.referencing.BracketStyle = <factory>, person: ~sphinxcontrib.bibtex.style.referencing.PersonStyle = <factory>, author_year_sep: ~typing.Union[BaseText, str] = ', ', text_reference_sep: ~typing.Union[BaseText, str] = ' ')[source]¶
Textual or parenthetical reference by author-year, or just by author, label, or year.
- author_year_sep: Union[BaseText, str] = ', '¶
Separator between author and year for parenthetical citations.
- bracket_author: BracketStyle¶
Bracket style for author citations (:cite:author: and variations).
- bracket_label: BracketStyle¶
Bracket style for label citations (:cite:label: and variations).
- bracket_parenthetical: BracketStyle¶
Bracket style for parenthetical citations (:cite:p: and variations).
- bracket_textual: BracketStyle¶
Bracket style for textual citations (:cite:t: and variations).
- bracket_year: BracketStyle¶
Bracket style for year citations (:cite:year: and variations).
- person: PersonStyle¶
Person style (applies to all relevant citation commands).
Plugins¶
Pybtex Extensions¶
New Text Elements¶
- class sphinxcontrib.bibtex.richtext.BaseReferenceText(info: ReferenceInfo, *parts: BaseText)[source]¶
Generic rich text element for citation references. Instances store some extra reference info that can be used when formatting. This base class renders its children without further formatting. Implementations must create a derivation from this class which overrides the render method to create the desired output. See for instance
SphinxReferenceText
.
- sphinxcontrib.bibtex.richtext.ReferenceInfo¶
Generic type parameter for types that store reference information. To be implemented by clients. See for instance
SphinxReferenceInfo
.alias of TypeVar(‘ReferenceInfo’)
New Template Nodes¶
- sphinxcontrib.bibtex.style.template.join(sep='', sep2=None, last_sep=None, other=None)[source]¶
Join text fragments together.
- sphinxcontrib.bibtex.style.template.sentence(capfirst=False, capitalize=False, add_period=True, sep=', ', sep2=None, last_sep=None, other=None)[source]¶
Join text fragments, capitalize the first letter, and add a period to the end.
- sphinxcontrib.bibtex.style.template.names(role, sep='', sep2=None, last_sep=None, other=None)[source]¶
Return formatted names.
- sphinxcontrib.bibtex.style.template.entry_label()¶
Node for inserting the label of a formatted entry.
- sphinxcontrib.bibtex.style.template.reference()¶
Pybtex node for inserting a docutils reference node to a citation. The children of the node comprise the content of the reference, and any referencing information is stored in the reference_info key of the data. The data must also contain a style key pointing to the corresponding
BaseReferenceStyle
.
- sphinxcontrib.bibtex.style.template.footnote_reference()¶
Pybtex node for inserting a footnote_reference docutils node. Any referencing information is stored in the reference_info key of the data. The data must also contain a style key pointing to the corresponding
BaseReferenceStyle
.
- class sphinxcontrib.bibtex.style.template.FootReferenceInfo(key: str, document: docutils.nodes.document, refname: str)[source]¶
Tuple containing reference info to enable sphinx to resolve a footnote reference.
- property document¶
Current docutils document.
- property key¶
Citation key.
- property refname¶
Citation reference name.
- class sphinxcontrib.bibtex.style.template.FootReferenceText(info: ReferenceInfo, *parts: BaseText)[source]¶
Pybtex rich text class generating a docutils footnote_reference node to a citation for use with
FootReferenceInfo
.
- class sphinxcontrib.bibtex.style.template.SphinxReferenceInfo(builder: Builder, fromdocname: str, todocname: str, citation_id: str, title: str)[source]¶
Tuple containing reference info to enable sphinx to resolve a reference to a citation.
- property builder¶
The Sphinx builder.
- property citation_id¶
Unique id of the citation within the bibliography.
- property fromdocname¶
Document name of the citation reference.
- property title¶
Title attribute for reference node.
- property todocname¶
Document name of the bibliography.
- class sphinxcontrib.bibtex.style.template.SphinxReferenceText(info: ReferenceInfo, *parts: BaseText)[source]¶
Pybtex rich text class generating a docutils reference node to a citation for use with
SphinxReferenceInfo
.
New Names Styles¶
Changes¶
2.5.0 (22 August 2022)¶
Add support for the rinohtype builder (reported by brechtm, see issue #275).
Migrate from
pkg_resources
toimportlib.metadata
. A side effect of this migration is that plugins registered at runtime are longer exposed as entry points. This is becauseimportlib
does not allow runtime modification of entry points.Remove sphinxcontrib namespace
__init__.py
file (no longer needed for Python 3.3+ by PEP420).Add support for docutils 0.18.
Suppress LaTeX url commands in tooltips (see issue #305, reported by 1kastner).
Document Markdown syntax for MyST (suggested by jacopok, see issue #310).
2.4.2 (10 April 2022)¶
Add support for Python 3.10 and 3.11.
New
bibtex_tooltips
option. Set toFalse
to disable tooltip generation. See issue #286.New
bibtex_tooltips_style
option to customize tooltip text style. If empty (the default), the bibliography style is used. See issue #286.Support for
root_doc
option introduced in Sphinx 4.0 (see issue #292, reported by jhmeinke).Use container node instead of paragraph node for containing bibliographies, fixing a violation against the docutils spec (see issue #273, reported by rappdw, with additional input from brechtm).
Fix mutable dataclass fields for Python 3.11 (see issue #284 and pull request #285; reported and fixed by jamesjer)
Internal refactor: embed
reference_text_class
directly inside the pybtex nodes. This enables different text classes to be used by different styles, so different sorts of docutils nodes can be generated on rendering depending on the pybtex node used. See discussion in issue #275.Add numpydoc regression test.
Bump minimal pybtex requirement to 0.24.
2.4.1 (10 September 2021)¶
Gracefully handle textual citations when author or year are missing (see issue #267, reported by fbkarsdorp).
2.4.0 (8 September 2021)¶
Allow specific warnings to be suppressed (see issue #255, contributed by stevenrhall).
Fix parsing of LaTeX url commands in bibtex fields (see issue #258, reported by Matthew Giassa).
Remove space between footnote and author for textual footnote citations in the default foot referencing style.
Document how to use a backslash escaped space to suppress space before footnotes (see issue #256, reported by hagenw).
Parse all bib files together, so macros specified in one file can be used in another file (see issue #216, reported by mforbes). As a consequence, duplicate citation keys across bib files will now also result in proper warnings. The
parse_bibfile
andprocess_bibfile
functions have been been replaced byparse_bibdata
andprocess_bibdata
in the API.New
bibtex_cite_id
,bibtex_footcite_id
,bibtex_bibliography_id
, andbibtex_footbibliography_id
settings, which allow custom ids (which can be used as html anchors) to be generated for citations and bibliographies, based on the citation keys rather than some random numbers (see issue #264, reported by kmuehlbauer). Refer to the documentation for detailed usage and examples.Switch to github actions for regression testing.
The API is now fully type checked.
Various minor improvements in documentation and code.
2.3.0 (1 June 2021)¶
Add
:footcite:p:
and:footcite:t:
roles. For capitalizing the first letter and/or listing the full author list, you can use:footcite:ct:
,:footcite:ts:
,:footcite:cts:
, and:footcite:ps:
.To configure your footnote referencing style, an optional config setting
bibtex_foot_reference_style
has been added. If not specified, this defaults to thefoot
style, which will use plain footnote references for citation references, matching the referencing style as in previous versions. Footnote reference styles can be fully customized to your heart’s desire, similar to regular citation reference styles.New
:cite:empty:
role which registers a citation without generating a reference, similar to LaTeX’s nocite command (see issue #131).Citation keys can now be listed directly under the bibliography directive, one key per line; such citations will always be included, regardless of any filter settings (see issue #54).
A plain text preview of the full citation information will be shown when hovering over a citation reference (see issue #198, requested by eric-wieser).
The separator between the text and the reference of all textual citation styles can now be customized.
2.2.1 (16 May 2021)¶
The LaTeX output now uses hyperlink instead of sphinxcite. This fixes issues with double brackets and other mismatches between LaTeX and HTML outputs (see issue #244 reported by zhi-wang).
The setup function now also returns the version of the extension (see issue #239 reported by lcnittl).
2.2.0 (5 March 2021)¶
Support the
:any:
role (see issue #232).New natbib/biblatex inspired roles for textual and parenthetical citation references (see issue #203 reported by matthew-brett). For textual citation references, use
:cite:t:
and for parenthetical citation references, use:cite:p:
. The old:cite:
role is an alias for:cite:p:
.Use the
s
suffix to include the full author list rather than abbreviating it with “et al.”::cite:ts:
,:cite:ps:
.For textual citation references, use the
c
prefix to capitalize the first letter::cite:ct:
,:cite:cts:
.New natbib inspired roles for citing just the author, year, or label, optionally with brackets, and optionally capitalizing the first letter of the author:
:cite:author:
,:cite:authorpar:
,:cite:cauthor:
,:cite:cauthorpar:
:cite:year:
,:cite:yearpar:
,:cite:label:
,:cite:labelpar:
(see issue #71 reported by bk322).To configure your referencing style, an optional config setting
bibtex_reference_style
has been added. If not specified, this defaults to thelabel
style, which will use the label to format citation references, matching the referencing style as in previous versions. The other style currently available isauthor_year
, for author-year style referencing.Reference styles can be fully customized to your heart’s desire (see issue #203 reported by amichuda). They are based on pybtex’s template system, which was already used for customizing bibliography styles. Refer to the user documentation for examples, and to the API documentation for full details.
Other packages can register custom reference styles through entry points. Refer to the user documentation for details.
Propagate pybtex FieldIsMissing exception as a warning (see issue #235 reported by Zac-HD).
2.1.4 (8 January 2021)¶
Fix ValueError exception when having citations from orphans (see issue #228, reported by VincentRouvreau).
2.1.3 (1 January 2021)¶
Sphinx 2.1 or later is now formally required (up from 2.0).
Fix unresolved references when running the latex build immediately after the html build, or when rerunning the html build after deleting the generated html files without deleting the pickled doctrees/environment (see issue #226, reported by skirpichev).
No longer insert user defined header for bibliography directives if there are no citations in it.
Warnings now consistently provide source file and line number of where the issue originated.
Simpler and faster implementation of footcite and footbibliography.
Improved type annotations throughout the API, now using forward declarations where possible.
2.1.2 (30 December 2020)¶
Fix KeyError exception when building documents with footbibliography directives but without any footnotes needing to be generated for this directive (see issue #223, reported by drammock).
2.1.1 (29 December 2020)¶
Fix latex builder KeyError exception (see issue #221, reported by jedbrown).
Fix citation references across documents in latex build.
2.1.0 (28 December 2020)¶
The extension no longer relies on the
bibtex.json
method. Instead, the extension now postpones identifying all citation cross-references to Sphinx’s consistency check phase. The actual citation references and bibliography citations are then generated in the resolve phase using post-transforms. As a result,bibtex.json
is no longer needed and thus Sphinx no longer needs to run twice as in the past if the file did not exist (closes issues #214 and #215). Thanks to everyone who chimed in on this, especially everyone who made helpful suggestions to find better implementation approaches, and everyone who helped with testing.Citations with multiple keys will now reside in the same bracket (closes issue #94).
Consistent use of doctutils note_explicit_target to set ids, to ensure no clashing ids.
Improved and robustified test suite, using regular expressions to verify generated html.
The test suite now includes a patched version of the awesome but abandoned sphinx-natbib extension, to help comparing and testing implementations and features. The long term intention is to fully support sphinx-natbib style citations.
BACKWARD INCOMPATIBLE The API has been refactored to accommodate the new design. Refer to the API documentation for details.
2.0.0 (12 December 2020)¶
There is a new
footcite
role and a newfootbibliography
directive, to allow easy and simple local (per document) bibliographies through footnotes. See issues #184 and #185.Parallel builds are now finally supported. See issues #80, #96, and #164, as well as pull request #210.
BACKWARD INCOMPATIBLE To enable parallel builds, a new mandatory config setting
bibtex_bibfiles
has been added. This setting specifies all bib files used throughout the project, relative to the source folder.BACKWARD INCOMPATIBLE The encoding of bib files has been moved to an optional config setting
bibtex_encoding
. The:encoding:
option is no longer supported.Headers for
bibliography
andfootbibliography
directives can be configured via thebibtex_bibliography_header
andbibtex_footbibliography_header
config setting.The
bibliography
directive no longer requires the bib files to be specified as an argument. However, if you do, citations will be constrained to those bib files.Support newlines/whitespace around cite keys when multiple keys are specified. Thanks to dizcza for help with testing. See issue #205 and pull request #206.
Improve citation ordering code (reported by ukos-git, see issue #182).
The unresolved citations across documents issue has been resolved. The extension stores all citation information in a
bibtex.json
file. If it does not exist, the file will be created on your first sphinx build, and you will have to rerun the build to make use of it. The file is automatically kept up to date, with a warning whenever you need to rerun the build. Thanks to dizcza for help with testing. See issues #197 and #204. Also see pull request #208.Migrate test suite to pytest, using sphinx’s testing fixtures.
BACKWARD INCOMPATIBLE The API has been refactored. Some functions have moved to different modules. Refer to the API documentation for details.
Drop Python 3.5 support.
Add Python 3.9 support.
1.0.0 (20 September 2019)¶
Drop Python 2.7 and 3.4 support (as upstream sphinx has dropped support for these as well).
Add Python 3.8 support (contributed by hroncok).
Update for Sphinx 2.x, and drop Sphinx 1.x support (as there is too much difference between the two versions).
Non-bibtex citations will now no longer issue warnings (fix contributed by chrisjsewell).
Switch to codecov for coverage reporting.
0.4.2 (7 January 2018)¶
Drop Python 3.3 support, add Python 3.7 support.
Work around issue with sphinx-testing on Fedora (reported by jamesjer in issue #157, fix contributed by mitya57 in pull request #158).
0.4.1 (28 November 2018)¶
Disable tinkerer test due to upstream bug.
Remove crossref test due to changed upstream behaviour in pybtex.
Fix latex test to match new upstream code generation.
Fix documentation of encoding option (contributed by Kai Mühlbauer).
Migrate to sphinx.util.logging in favour of old deprecated logging method.
0.4.0 (19 April 2018)¶
Remove latexcodec and curly bracket strip functionality, as this is now supported by pybtex natively (see issue #127, reported by erosennin).
Fix tests failures with Sphinx 1.7 (see pull request #136, reported and fixed by mitya57).
0.3.6 (25 September 2017)¶
Real fix for issue #111 (again reported by jamesjer).
Fix test regressions due to latest Sphinx updates (see issues #115, #120, #121, and #122, reported by ndarmage and ghisvail).
Fix test regressions on ascii locale (see issue #121, reported by ghisvail).
Support and test Python 3.6.
0.3.5 (22 February 2017)¶
Fix extremely high memory usage when handling large bibliographies (reported by agjohnson, see issue #102).
Fix tests for Sphinx 1.5.1 (see issue #111, reported by jamesjer).
0.3.4 (20 May 2016)¶
Document LaTeX workaround for
:cite:
in figure captions (contributed by xuhdev, see issue #92 and pull request #93).Add
bibtex_default_style
config value to override the default bibliography style (see issue #91 and pull request #97).Support Python 3.5 (see issue #100).
0.3.3 (23 October 2015)¶
Add per-bibliography key prefixes, enabling local bibliographies to be used in isolation from each other (see issue #87, reported by marscher).
Documentation now points to new location of pybtex on bitbucket.
Simplified testing code by using the new sphinx_testing package.
0.3.2 (20 March 2015)¶
Document how to create custom label styles (see issue #77, reported by tino).
Disable parallel_read_safe for Sphinx 1.3 and later (see issue #80, reported by andreacassioli).
0.3.1 (10 July 2014)¶
Fix for
type_.lower()
bug: pybtex 0.18 expects type to be a string (this fixes issue #68 reported by jluttine).
0.3.0 (4 May 2014)¶
BACKWARD INCOMPATIBLE The alpha style is now default, so citations are labelled in a way that is more standard for Sphinx. To get the old behaviour back, add
:style: plain
to your bibliography directives.BACKWARD INCOMPATIBLE
is_cited()
has been removed. Useget_cited_docnames()
instead, which will return an empty list for keys that are not cited.Improved support for local bibliographies (see issues #52, #62, and #63; test case provided by Boris Kheyfets):
New
docname
anddocnames
filter identifiers.Filter expressions now also support set literals and the operators
in
,not in
,&
, and|
.
See documentation for details.
Multiple comma-separated citation keys per cite command (see issue #61, suggested by Boris Kheyfets).
Add support for pypy and Python 3.4.
Drop support for Python 2.6 and Python 3.2.
Drop 2to3 and instead use six to support both Python 2 and 3 from a single code base.
Simplify instructions for custom styles.
Various test suite improvements.
0.2.9 (9 October 2013)¶
Upgrade to the latest pybtex-docutils to produce more optimal html output (specifically: no more nested
<span>
s).Remove latex codec code, and rely on latexcodec package instead.
FilterVisitor
has been removed from the public API. Useget_bibliography_entries()
instead.Fix upstream Sphinx bug concerning LaTeX citation hyperlinks (contributed by erikb85; see pull request #45).
Fix most pylint warnings, refactor code.
0.2.8 (7 August 2013)¶
Use pybtex-docutils to remove dependency on pybtex.backends.doctree.
0.2.7 (4 August 2013)¶
Integrate with coveralls.io, first release with 100% test coverage.
Minor bug fixes and code improvements.
Remove ordereddict dependency for Python 2.7 and higher (contributed by Paul Romano, see pull requests #27 and #28).
New
:filter:
option for advanced filtering (contributed by d9pouces, see pull requests #30 and #31).Refactor documentation of advanced features.
Document how to create custom pybtex styles (see issues #25, #29, and #34).
Code is now mostly pep8 compliant.
0.2.6 (2 March 2013)¶
For unsorted styles, citation entries are now sorted in the order they are cited, instead of following the order in the bib file, to reflect more closely the way LaTeX handles unsorted styles (addresses issue #15).
Skip citation label warnings on Sphinx [source] links (issue #17, contributed by Simon Clift).
0.2.5 (18 October 2012)¶
Duplicate label detection (issue #14).
New
:labelprefix:
option to avoid duplicate labels when having multiple bibliographies with a numeric label style (addresses issue #14).
0.2.4 (24 August 2012)¶
New options for the bibliography directive for rendering the bibliography as bullet lists or enumerated lists:
:list:
,:enumtype:
, and:start:
.Minor latex codec fixes.
Turn exception into warning when a citation cannot be relabeled (fixes issue #2).
Document LaTeX encoding, and how to turn it off (issue #4).
Use pybtex labels (fixes issue #6 and issue #7).
Cache tracked citation keys and labels, and bibliography enumeration counts (fixes issues with citations in repeated Sphinx runs).
Bibliography ids are now unique across documents (fixes issue that could cause the wrong bibliography to be inserted).
The plain style is now the default (addresses issue #9).
0.2.3 (30 July 2012)¶
Document workaround for Tinkerer (issue #1).
Use tox for testing.
Full 2to3 compatibility.
Document supported versions of Python (2.6, 2.7, 3.1, and 3.2).
0.2.2 (6 July 2012)¶
Documentation and manifest fixes.
0.2.1 (19 June 2012)¶
First public release.
License¶
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.