Usage
=====

Configuration
-------------

Bibliography Files and Encoding
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

.. code-block:: python

   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:

.. code-block:: python

   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:

.. code-block:: python

   bibtex_default_style = 'unsrt'

You can also create your own style (see :ref:`bibtex-custom-formatting`).

Referencing Style
~~~~~~~~~~~~~~~~~

.. versionadded:: 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 <https://packaging.python.org/guides/creating-and-discovering-plugins/#using-package-metadata>`_ group.
See sphinxcontrib-bibtex's own ``setup.py`` script for examples.

Tooltips
~~~~~~~~

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

.. rst:role:: cite:p

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

   .. code-block:: rest

      We will make use of non-standard analysis :cite:p:`1987:nelson`.

   which would be equivalent to the following LaTeX code:

   .. code-block:: latex

      We will make use of non-standard analysis \citep{1987:nelson}.

   Multiple keys can be specified at once:

   .. code-block:: rest

      I love analysis :cite:p:`1987:nelson,2001:schechter`!

.. rst:role:: cite:t

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

   .. code-block:: rest

      See :cite:t:`1987:nelson` for an introduction to non-standard analysis.

   which would be equivalent to the following LaTeX code:

   .. code-block:: latex

      See \citet{1987:nelson} for an introduction to non-standard analysis.

   Here too, multiple keys can be specified at once.

.. rst:role:: cite:ps
.. rst:role:: cite:ts
.. rst:role:: cite:ct
.. rst:role:: cite:cts

   .. versionadded:: 2.2.0

   All these roles modify :rst:role:`cite:p` and :rst:role:`cite:t`.
   The ones starting with ``c`` will capitalize the first letter.
   The ones ending with ``s`` will give the full author list.

.. rst:role:: cite:alp
.. rst:role:: cite:alps

   .. versionadded:: 2.6.0

   These are identical to :rst:role:`cite:p` and :rst:role:`cite:ps`
   but suppress brackets.
   This is useful for instance when needing to add formatted pre-text or post-text.

   .. seealso::

      :ref:`section-pre-post-text`

.. rst:role:: cite

   This is an alias for the :rst:role:`cite:p` role, and will create a
   parenthetical citation reference. Provided for convenience and
   compatibility with older versions.

.. rst:role:: cite:label
.. rst:role:: cite:labelpar

   .. versionadded:: 2.2.0

   Create a citation using just the label.
   Use the ``par`` version to include brackets.

.. rst:role:: cite:year
.. rst:role:: cite:yearpar

   .. versionadded:: 2.2.0

   Create a citation using just the year.
   Use the ``par`` version to include brackets.

.. rst:role:: cite:author
.. rst:role:: cite:authors
.. rst:role:: cite:authorpar
.. rst:role:: cite:authorpars
.. rst:role:: cite:cauthor
.. rst:role:: cite:cauthors

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

.. rst:role:: cite:empty

   .. versionadded:: 2.3.0

   Register a citation key as being cited without generating a reference,
   similar to LaTeX's nocite command.

.. rst:directive:: .. 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 :ref:`section-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).

   .. rst:directive:option:: all

      Include all references, instead of just the cited ones
      (equivalent to ``\nocite{*}`` in LaTeX). For example:

      .. code-block:: rest

        .. bibliography::
           :all:

   .. rst:directive:option:: notcited

      Causes all references that were not cited to be included.
      Listed references remain included.

   .. rst:directive:option:: cited

      This is the default and need not be specified.

   .. rst:directive:option:: style

      Overrides the default bibliography style. For example:

      .. code-block:: rest

        .. bibliography::
           :style: unsrt

   .. rst:directive:option:: list
   .. rst:directive:option:: enumtype
   .. rst:directive:option:: start

      See :ref:`section-lists`.

   .. rst:directive:option:: labelprefix

      See :ref:`section-label-prefixing`.

   .. rst:directive:option:: keyprefix

      See :ref:`section-key-prefixing`.

   .. rst:directive:option:: filter

      See :ref:`section-filtering`. Note that listed references are always
      included, regardless of any filtering.

.. XXX not documenting disable-curly-bracket-strip for now; might remove it

   Finally, curly brackets are automatically removed when the bib file
   is parsed. Usually, this is what you want. If you desire to disable
   this behaviour, use the ``disable-curly-bracket-strip`` option:

   .. code-block:: rest

     .. bibliography::
        :disable-curly-bracket-strip:

.. rst:role:: footcite:p

   .. versionadded:: 2.3.0

   Create a parenthetical footnote reference to a bibliographic entry.
   For example:

   .. code-block:: rest

      We will make use of non-standard analysis\ :footcite:p:`1987:nelson`.

   which would be equivalent to the following LaTeX code:

   .. code-block:: latex

      We will make use of non-standard analysis\footcite{1987:nelson}.

   Note the use of the
   `backslash escaped space <https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#inline-markup>`_
   to suppress the space that would otherwise precede the footnote.

   As with all citation roles, multiple keys can be specified:

   .. code-block:: rest

      I love analysis\ :footcite:p:`1987:nelson,2001:schechter`!

.. rst:role:: footcite:t

   .. versionadded:: 2.3.0

   Create a textual footnote reference to a bibliographic entry. For example:

   .. code-block:: rest

      See :footcite:t:`1987:nelson` for an introduction to non-standard analysis.

   which would be equivalent to the following LaTeX code:

   .. code-block:: latex

      See Nelson\footcite{1987:nelson} for an introduction to non-standard analysis.

   Here too, multiple keys can be specified at once.

.. rst:role:: footcite:ps
.. rst:role:: footcite:ts
.. rst:role:: footcite:ct
.. rst:role:: footcite:cts

   .. versionadded:: 2.3.0

   All these roles modify :rst:role:`footcite:p` and :rst:role:`footcite:t`.
   The ones starting with ``c`` will capitalize the first letter.
   The ones ending with ``s`` will give the full author list.

.. rst:role:: footcite

   .. versionadded:: 2.0.0

   This is an alias for the :rst:role:`footcite:p` role, and will create a
   parenthetical footnote citation reference. Provided for convenience and
   compatibility with older versions.

.. rst:directive:: .. footbibliography::

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

.. code-block:: markdown

   See {cite:p}`1987:nelson` for an introduction to non-standard analysis.

   ```{bibliography} references.bib
   ```

.. seealso:: https://myst-parser.readthedocs.io/en/latest/syntax/roles-and-directives.html

Advanced Features
-----------------

.. _section-pre-post-text:

Adding pre-text and post-text to citations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. versionadded:: 2.6.0

You can add unformatted pre-text and post-text to any citation reference using the
following syntax:

.. code-block:: rest

   The axioms were introduced by :cite:t:`{see}1977:nelson`.
   The axioms were introduced by :cite:t:`1977:nelson{p. 1166}`.
   The axioms were introduced by :cite:t:`{see}1977:nelson{p. 1166}`.
   Axioms were introduced :cite:p:`{see}1977:nelson`.
   Axioms were introduced :cite:p:`1977:nelson{p. 1166}`.
   Axioms were introduced :cite:p:`{see}1977:nelson{p. 1166}`.

Pre- and post-text is not supported for footnote citations.

For formatted pre- and post-text in parenthetical citations,
you can use the :rst:role:`cite:alp` and :rst:role:`cite:alps` roles.
These roles suppress the brackets, leaving it to you to add them in the right
format and place:

.. code-block:: rest

   The three new axioms [the *IST axioms*, :cite:alp:`1977:nelson`] are discussed next.


Splitting Bibliographies Per Bib File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. versionadded:: 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``.

.. code-block:: rest

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

.. _section-lists:

Bullet Lists and Enumerated Lists
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

.. code-block:: rest

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

.. code-block:: rest

   .. 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
:rst:dir:`bibliography` directive.
This is helpful if you split up your bibliography but
still want to enumerate the entries continuously.

.. _section-listing-citation-keys:

Listing Citation Keys
~~~~~~~~~~~~~~~~~~~~~

.. versionadded:: 2.3.0

If you have many citations to include that are not referenced anywhere,
then instead of using :rst:role:`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 :ref:`section-key-prefixing`).
For example:

.. code-block:: rest

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

.. code-block:: rest

   .. bibliography::
      :filter: False

      nelson1987
      boole1854

See :ref:`section-filtering` for more information on filtering.

.. _section-label-prefixing:

Label Prefixing
~~~~~~~~~~~~~~~

.. versionadded:: 0.2.5

If you have multiple bibliographies, and experience duplicate labels,
use the ``labelprefix`` option.

.. code-block:: rest

   .. rubric:: References

   .. bibliography::
      :cited:
      :labelprefix: A

   .. rubric:: Further reading

   .. bibliography::
      :notcited:
      :labelprefix: B

.. _section-key-prefixing:

Key Prefixing
~~~~~~~~~~~~~

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

.. code-block:: rest

   See :cite:`a-boole1854`

   .. bibliography::
      :labelprefix: A
      :keyprefix: a-

whilst in the other document you could have:

.. code-block:: rest

   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:

.. code-block:: rest

   .. bibliography::
      :labelprefix: B
      :keyprefix: b-

      nelson1987

.. seealso::

   :ref:`section-local-bibliographies`

.. _section-filtering:

Filtering
~~~~~~~~~

.. versionadded:: 0.2.7

Whilst the ``cited``, ``all``, and ``notcited`` options
along with :ref:`section-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:

.. code-block:: rest

   .. 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 :func:`ast.parse`
   and then evaluated using an :class:`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:

    .. code-block:: rest

       .. bibliography::
          :list: bullet
          :filter: title % "relativity"

  would include all entries that have the word "relativity" in the title.

  .. note::

     The implementation uses :func:`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``.

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

    .. versionadded:: 0.3.0

  - ``docnames`` evaluates to a set of names from which the entry is cited.

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

    .. code-block:: rest

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

.. _section-local-bibliographies:

Local Bibliographies
~~~~~~~~~~~~~~~~~~~~

The easiest way to have a local bibliography per
document is to use
:rst:role:`footcite` along with :rst:dir:`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 :rst:role:`cite` and :rst:dir:`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
:ref:`section-key-prefixing`.

To create a bibliography that includes only citations that were cited
in the current document, use the following filter:

.. code-block:: rest
                
   .. bibliography::
      :filter: docname in docnames

More generally, you can create bibliographies for
citations that were cited from specific documents only:

.. code-block:: rest

   .. bibliography::
      :filter: {"doc1", "doc2"} & docnames

This bibliography will include all citations that were cited from
:file:`doc1.rst` or :file:`doc2.rst`. Another hypothetical example:

.. code-block:: rest

   .. bibliography::
      :filter: cited and ({"doc1", "doc2"} >= docnames)

This bibliography will include all citations that were cited
in :file:`doc1.rst` or :file:`doc2.rst`, but nowhere else.

.. _bibtex-custom-formatting:

Custom Formatting, Sorting, and Labelling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:mod:`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``:

.. code-block:: python

  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:

.. code-block:: python

   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:

* https://github.com/mcmtroffaes/sphinxcontrib-bibtex/tree/develop/test/roots/test-bibliography_style_label_1
* https://github.com/mcmtroffaes/sphinxcontrib-bibtex/tree/develop/test/roots/test-bibliography_style_label_2

Custom Inline Citation References
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. versionadded:: 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``:

.. code-block:: python

    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:

.. code-block:: python

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

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

.. code-block:: python

    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 :rst:dir:`bibliography` directive per document,
then you can also use:

.. code-block:: python

    bibtex_cite_id = "cite-{key}"

The ``bibliography_count`` template variable
counts :rst:dir:`bibliography` directives in the current document,
thus giving a unique number for each :rst:dir:`bibliography` directive
within a document.
The ``footbibliography_count`` template variable works similarly but for
:rst:dir:`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 :rst:dir:`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 :rst:dir:`bibliography` directive
   prior to knowing whether or not the citation needs to be included.

Custom Bibliography Header
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. versionadded:: 2.0.0

By default, the :rst:dir:`bibliography`
and :rst:dir:`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:

.. code-block:: python

   bibtex_bibliography_header = ".. rubric:: References"
   bibtex_footbibliography_header = bibtex_bibliography_header

This adds a rubric title to every bibliography.

Suppressing Warnings
~~~~~~~~~~~~~~~~~~~~

.. versionadded:: 2.3.1

To suppress *all* warnings from ``sphinxcontrib-bibtex``
(which is probably a bad idea!), add this to your ``conf.py``:

.. code-block:: python

   suppress_warnings = ["bibtex"]

To suppress only a subset of warnings, such as duplicate label warnings,
you can use:

.. code-block:: python

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

LaTeX Formatting Inside Bibtex Entries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Beyond simple unicode/LaTeX symbol conversions,
LaTeX formatting in bib files is not supported by pybtex.
Since sphinxcontrib-bibtex uses pybtex to parse and format bibtex entries,
that limitation is carried over to sphinxcontrib-bibtex.

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 :rst:dir:`bibliography` directive.
Consequently, when inserting multiple :rst:dir:`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``:

.. code-block:: python

   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,
first tell Sphinx to suppress its custom bibliography transform by adding the
following code to your ``conf.py``:

.. code-block:: python

    import sphinx.builders.latex.transforms

    class DummyTransform(sphinx.builders.latex.transforms.BibliographyTransform):
        def run(self, **kwargs):
            pass

    sphinx.builders.latex.transforms.BibliographyTransform = DummyTransform

Then create a :file:`references.rst` file that
you include at the end of your toctree, containing the following code:

.. code-block:: rest

    References
    ==========

    .. raw:: latex

        \begingroup
        \def\section#1#2{}
        \def\chapter#1#2{}
        \begin{thebibliography}{1234}

    .. bibliography::

    .. raw:: latex

        \end{thebibliography}
        \endgroup

.. seealso::

   This issue is being tracked on the Sphinx bug tracker here,
   where you might find other workarounds if the above one does not work
   for your use case:
   https://github.com/sphinx-doc/sphinx/issues/4775

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

.. code-block::

   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:

.. code-block::

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

.. code-block::

   pip install -e .
   cd test/
   pytest

