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’s numbers style and biblatex’s numeric and alphabetic 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’s authoryear 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 as plain. Similar to natbib’s super 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.

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 and cite:t. The ones starting with c will capitalize the first letter. The ones ending with s 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 the c 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:

See Bullet Lists and Enumerated Lists.

:labelprefix:

See Label Prefixing.

:keyprefix:

See Key Prefixing.

:filter:

See Filtering. Note that listed references are always included, regardless of any filtering.

: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 and footcite:t. The ones starting with c will capitalize the first letter. The ones ending with s 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.

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

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, so it should be reasonably safe against malicious code.

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, and not 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 to True if the entry was cited in the document, and to False 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 and False.

    • author is the entry string of authors in standard format (last, first), separated by “and”.

    • editor is similar to author 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:

import dataclasses
import sphinxcontrib.bibtex.plugin

from sphinxcontrib.bibtex.style.referencing import BracketStyle
from sphinxcontrib.bibtex.style.referencing.author_year \
    import AuthorYearReferenceStyle

my_bracket_style = BracketStyle(
    left='(',
    right=')',
)


@dataclasses.dataclass
class MyReferenceStyle(AuthorYearReferenceStyle):
    bracket_parenthetical: BracketStyle = my_bracket_style
    bracket_textual: BracketStyle = my_bracket_style
    bracket_author: BracketStyle = my_bracket_style
    bracket_label: BracketStyle = my_bracket_style
    bracket_year: BracketStyle = my_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}{}}
 '''
}

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}}{}{}{}

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