如何在Sphinx中更改pybtex引用的样式

时间:2019-05-01 21:10:48

标签: python python-sphinx restructuredtext sphinxcontrib.bibtex pybtex

我正在尝试使用sphinxcontrib.bibtex在某些文档中包含引用文献/参考文献。它说您可以set the style使用:

.. bibliography: refs.bib
   :style: plain

它具有以下样式:alphaplain,它们创建如下所示的参考标签:

  • alpha[ZieglerBenderSchreiber+14][TMT14][PCY+16a]
  • plain[1][2][3]

我发现alpha是不一致的,但是我认为plain的正数缺乏上下文。要自定义格式,它提供了以下示例:

from pybtex.style.formatting.unsrt import Style as UnsrtStyle
from pybtex.style.template import toplevel # ... and anything else needed
from pybtex.plugin import register_plugin

class MyStyle(UnsrtStyle):

    def format_XXX(self, e):
        template = toplevel [
            # etc.
        ]
        return template.format_data(e)

register_plugin('pybtex.style.formatting', 'mystyle', MyStyle)

其中sphinx失败的原因:

sphinx-build -M html . out
Running Sphinx v1.8.3

Configuration error:
There is a syntax error in your configuration file: bad input (conf.py, line 92)
Did you change the syntax from 2.x to 3.x?

似乎在后台使用了pybtex,因此请遵循该文档中的示例:

from pybtex.style.formatting import BaseStyle
from pybtex.richtext import Text, Tag

class MyStyle(BaseStyle):
    def format_article(self, entry):
        return Text('Article ', Tag('em', entry.fields['title']))

from pybtex.plugin import register_plugin
register_plugin('pybtex.style.formatting', 'mystyle', MyStyle)

并且狮身人面像失败并显示:

Exception occurred:
  File "/home/josh/codes/docs/conf.py", line 88, in format_article
    return Text('Article ', Tag('em', entry.fields['title']))
AttributeError: 'dict' object has no attribute 'fields'
The full traceback has been saved in /tmp/sphinx-err-dftwlzvr.log, if you want to report the issue to the developers.

...,我认为只是自定义书目条目文本,而不是标签文本。如何自定义标签文本?我希望使用以下其中一种:

  1. [1]一样的括号数字(plain),但带有上标标签
  2. 类似[ref.12]的事物,类似于eq.12fig.12
  3. 类似alpha,但字符数一致的

1 个答案:

答案 0 :(得分:0)

我不想回答自己的问题,但这就是我想出的。我在conf.py中添加了以下内容,它使用bibtex键作为标签文本:

from pybtex.style.formatting.unsrt import Style as UnsrtStyle
from pybtex.style.labels.alpha import LabelStyle as AlphaLabelStyle

class KeyLabelStyle(AlphaLabelStyle):
  def format_label(self, entry):
    label = entry.key
    return label

class CustomStyle(UnsrtStyle):
  default_sorting_style = 'author_year_title'

  def __init__(self, *args, **kwargs):
    super(CustomStyle, self).__init__(*args, **kwargs)
    self.label_style = KeyLabelStyle()
    self.format_labels = self.label_style.format_labels

from pybtex.plugin import register_plugin
register_plugin('pybtex.style.formatting', 'custom', CustomStyle)

要在RST中激活:

.. bibliography:: refs.bib
   :style: custom

这不是一个完整的答案,因为它实际上不会生成自定义标签...但是会覆盖现有样式的某些内部内容。有点骇人听闻,几乎可以回答...我希望它能对其他人有所帮助。

相关问题