Diretivas

Como discutido anteriormente, uma diretiva é um bloco genérico de marcação explícita. Enquanto o Docutils fornece várias diretivas, o Sphinx fornece muito mais e usa diretivas como um dos mecanismos de extensão primários.

See Domínios for roles added by domains.

Ver também

Confira o Primer de reStructuredText para uma visão geral das diretivas fornecidas pelo Docutils.

Tabela de conteúdo

Como reST não tem funcionalidades para conectar diversos documentos ou dividir documentos em múltiplos arquivos de saída, Sphinx usa uma diretiva configurada para adicionar relações entre arquivos simples da documentação criada e de tabelas de conteúdos. A diretiva toctree é um elemento central.

Nota

A simples “inclusão” de um arquivo em outro pode ser feita com a diretiva include.

Nota

Para criar um índice para o documento atual (arquivo .rst), use o padrão reST diretiva de conteúdo.

.. toctree::

Esta diretiva insere uma “árvore TOC” na localização atual, usando os TOCs individuais (incluindo “árvores subTOC”) dos documentos fornecidos no corpo da diretiva. Os nomes de documentos relativos (não começando com uma barra) são relativos ao documento em que a diretiva ocorre, os nomes absolutos são relativos ao diretório fonte. Uma opção numérica maxdepth pode ser fornecida para indicar a profundidade da árvore; por padrão, todos os níveis são incluídos. [1]

A representação da “árvore TOC” é alterada em cada formato de saída. Os construtores que geram vários arquivos (por exemplo, HTML) os tratam como uma coleção de hiperlinks. Por outro lado, os construtores que geram um único arquivo (por exemplo, LaTeX, página man, etc.) substituem-no pelo conteúdo dos documentos na árvore TOC.

Considere esse exemplo (obtido da biblioteca da documentação do Python, índice de referência):

.. toctree::
   :maxdepth: 2

   intro
   strings
   datatypes
   numeric
   (many more documents listed here)

Serve para dois objetivos:

  • Tabelas de conteúdos para todos os documentos que forem inseridos, com um nível máximo de profundidade de dois, o que significa um subnível de cabeçalho. Diretivas toctree nesses documentos também são levadas em conta.

  • O Sphinx conhece a ordem relativa dos documentos intro, strings e assim por diante, e sabe que eles são filhos do documento mostrado, o índice da biblioteca. A partir dessas informações, ele gera os links “próximo capítulo”, “capítulo anterior” e “capítulo pai”.

Entradas

Os títulos dos documentos em toctree serão lidos automaticamente a partir do título do documento referenciado. Se isso não for o que você deseja, você pode especificar um título e destino explícitos usando uma sintaxe semelhante para hiperlinks de reST (e sintaxe de referência cruzada do Sphinx). Isso se parece com:

.. toctree::

   intro
   All about strings <strings>
   datatypes

A segunda linha acima terá um link para o documento strings, mas usará o título “All about strings” ao invés do título do documento strings.

Você também pode adicionar links externos, fornecendo uma URL HTTP em vez do nome de documento.

Numeração seção

Se desejar números nas seções no HTML de saída, atribua um toctree toplevel com a opção numbered. Por exemplo:

.. toctree::
   :numbered:

   foo
   bar

A numeração então começa no cabeçalho de foo. Sub-toctrees são numeradas automaticamente (não dê o sinalizador numbered para elas).

Numerar até uma profundidade específica também é possível, dando a profundidade como um argumento numérico para numbered.

Opções adicionais

Você pode usar a opção caption para fornecer uma legenda à toctree e você pode usar a opção name para fornecer um nome de destino implícito que pode ser referenciado usando ref:

.. toctree::
   :caption: Table of Contents
   :name: mastertoc

   foo

Se você quiser que apareçam apenas os títulos dos documentos na árvore, e não outros títulos do mesmo nível, você pode usar a opção títulosonly:

.. toctree::
   :titlesonly:

   foo
   bar

Você pode usar “globbing” nas diretivas toctree, dando a opção de sinalizador glob. Todas as entradas são então comparadas com a lista de documentos disponíveis e as correspondências são inseridas na lista em ordem alfabética. Exemplo:

.. toctree::
   :glob:

   intro*
   recipe/*
   *

Isso inclui primeiro todos os documentos cujos nomes começam com intro, depois todos os documentos na pasta recipe e, em seguida, todos os documentos restantes (exceto aquele que contém a diretiva, é claro). [2]

O nome de entrada especial self representa o documento que contém a diretiva toctree. Isso é útil se você deseja gerar um “sitemap” a partir da toctree.

Você pode usar a opção de sinalizador reversed para inverter a ordem das entradas na lista. Isso pode ser útil ao usar a opção de sinalizador glob para inverter a ordem dos arquivos. Exemplo:

.. toctree::
   :glob:
   :reversed:

   recipe/*

Você também pode fornecer uma opção “oculta” para a diretiva, como esta:

.. toctree::
   :hidden:

   doc_1
   doc_2

Isso ainda notificará o Sphinx sobre a hierarquia do documento, mas não inserirá links no documento no local da diretiva – isso faz sentido se você pretende inserir esses links por conta própria, em um estilo diferente ou na barra lateral HTML.

Nos casos em que você deseja ter apenas uma árvore toctree de nível superior e ocultar todas as outras toctree de nível inferior, você pode adicionar a opção “includehidden” à entrada toctree de nível superior:

.. toctree::
   :includehidden:

   doc_1
   doc_2

Todas demais entradas da toctree podem ser omitidas com a opção “hidden”.

No final, todos os documentos no diretório fonte (ou subdiretórios) devem ocorrer em alguma diretiva toctree; O Sphinx emitirá um aviso se encontrar um arquivo que não está incluído, porque isso significa que esse arquivo não será acessível através da navegação padrão.

Usa exclude_patterns para excluir explicitamente documentos ou diretórios da construção completamente. Usa os metadados “órfãos” para permitir que um documento seja construído, mas notifica o Sphinx de que não está acessível através de uma toctree.

O “documento raiz” (selecionado por root_doc) é a “raiz” da hierarquia da árvore TOC. Ele pode ser usado como a página principal da documentação ou como um “índice completo” se você não fornecer a opção maxdepth.

Alterado na versão 0.3: Opção “globbing” adicionada.

Alterado na versão 0.6: Adicionadas as opções “numbered” e “hidden” bem como links externos e suporte para referências “self”.

Alterado na versão 1.0: Adicionada a opção “titlesonly”.

Alterado na versão 1.1: Adicionado o argumento numérico para “numbered”.

Alterado na versão 1.2: Adicionada a opção “includehidden”.

Alterado na versão 1.3: Adicionada a opção “caption” e “name”.

Nomes especiais

Sphinx reserva alguns nomes de documentos para seu próprio uso; não tente criar documentos usando esses nomes – isso irá causar problemas.

Nomes especiais de documentos (e páginas geradas para eles) são:

  • genindex, modindex, search

    Estes são usados para o índice geral, o índice de módulo Python e a página de pesquisa, respectivamente.

    O índice geral e preenchido com entradas dos módulos, todas descrições de objeto de geradora de índices, e para diretivas index.

    O índice de módulo Python contém uma entrada por diretiva py:module.

    A página de pesquisa contém um formulário que usa o índice de pesquisa em JSON gerado e JavaScript para pesquisa de texto inteiro em documentos gerados por palavras da pesquisa; normalmente funciona nos diversos navegadores que oferecem suporte a JavaScript moderno.

  • todo nome começando com _

    Embora poucos desses nomes sejam usados atualmente pelo Sphinx, você não deve criar documentos ou diretórios que contenham documentos com esses nomes. (Usar _ como um prefixo para um diretório de modelo personalizado é adequado.)

Aviso

Tenha cuidado com caracteres incomuns em nomes de arquivos. Alguns formatos podem interpretar esses caracteres de maneiras inesperadas:

  • Não use dois pontos : para formatos baseados em HTML. Links para outras partes podem não funcionar.

  • Não use o sinal de mais + no formato ePub. Alguns recursos podem não ser encontrados.

Marcação de nível de parágrafo

Essas diretivas criam parágrafos curtos e podem ser usadas em unidades de informação interna, bem como em texto normal.

.. note::

Um bit de informação especialmente importante sobre uma API que o usuário deve estar ciente ao usar qualquer bit de API a que a nota pertence. O conteúdo da diretiva deve ser escrito em frases completas e incluir todas as pontuações apropriadas.

Exemplo:

.. note::

   This function is not suitable for sending spam e-mails.
.. warning::

Um bit de informação importante sobre uma API que o usuário deve estar muito ciente ao usar qualquer bit de API ao qual o aviso pertence. O conteúdo da diretiva deve ser escrito em frases completas e incluir todas as pontuações apropriadas. Isso difere de note porque é recomendado em vez de note para informações sobre segurança.

.. versionadded:: version

Esta diretiva documenta a versão do projeto que adicionou o recurso descrito à biblioteca ou API C. Quando isso se aplica a um módulo inteiro, deve ser colocado no topo da seção do módulo antes de qualquer prosa.

O primeiro argumento deve ser fornecido e é a versão em questão; você pode adicionar um segundo argumento consistindo em uma explicação breve da mudança.

Exemplo:

.. versionadded:: 2.5
   The *spam* parameter.

Observe que não deve haver nenhuma linha em branco entre o cabeçalho da diretiva e a explicação; isso faz com que esses blocos sejam visualmente contínuos na marcação.

.. versionchanged:: version

Semelhante a versionadded, mas descreve quando e o que mudou no recurso nomeado de alguma forma (novos parâmetros, efeitos colaterais alterados, etc.).

.. deprecated:: version

Semelhante a versionchanged, mas descreve quando o recurso foi preterido. Uma explicação também pode ser fornecida, por exemplo, para informar ao leitor o que deve ser usado. Exemplo:

.. deprecated:: 3.1
   Use :func:`spam` instead.
.. versionremoved:: version

Similar to versionadded, but describes when the feature was removed. An explanation may be provided to inform the reader what to use instead, or why the feature was removed. Example:

.. versionremoved:: 4.0
   The :func:`spam` function is more flexible, and should be used instead.

Adicionado na versão 7.3.

.. seealso::

Muitas seções incluem uma lista de referências à documentação do módulo ou documentos externos. Essas listas são criadas usando a diretiva seealso.

A diretiva seealso é tipicamente colocada em uma seção antes de qualquer subseção. Para a saída HTML, é mostrado em caixas fora do fluxo principal do texto.

O conteúdo da diretiva seealso deve ser uma lista de definições de reST. Exemplo:

.. seealso::

   Module :py:mod:`zipfile`
      Documentation of the :py:mod:`zipfile` standard module.

   `GNU tar manual, Basic Tar Format <https://link>`_
      Documentation for tar archive files, including GNU tar extensions.

Também existe uma “forma curta” permitida que se parece com isto:

.. seealso:: modules :py:mod:`zipfile`, :py:mod:`tarfile`

Adicionado na versão 0.5: A forma curta.

.. rubric:: title

Esta diretiva cria um título de parágrafo que não é usado para criar um nó de tabela de conteúdo.

Nota

Se o title da rubrica for “Notas de rodapé” (ou o equivalente do idioma selecionado), esta rubrica é ignorada pelo escritor de LaTeX, pois presume-se que contenha apenas definições de notas de rodapé e, portanto, criaria um título vazio.

.. centered::

Esta diretiva cria uma linha de texto em negrito centralizada. Use-a da seguinte maneira:

.. centered:: LICENSE AGREEMENT

Obsoleto desde a versão 1.1: This presentation-only directive is a legacy from older versions. Use a rst-class directive instead and add an appropriate style.

.. hlist::

Esta diretiva deve conter uma lista com marcadores. Isso a transformará em uma lista mais compacta, distribuindo mais de um item horizontalmente ou reduzindo o espaçamento entre os itens, dependendo do construtor.

Para construtores que oferecem suporte à distribuição horizontal, existe uma opção columns que especifica o número de colunas; o padrão é 2. Exemplo:

.. hlist::
   :columns: 3

   * A list of
   * short items
   * that should be
   * displayed
   * horizontally

Adicionado na versão 0.6.

Mostrando exemplos de código

Existem várias maneiras de mostrar blocos de código literal com destaque de sintaxe no Sphinx:

Os blocos de doctest só podem ser usados ​​para mostrar sessões Python interativas, enquanto os três restantes podem ser usados ​​para outras linguagens. Destes três, os blocos literais são úteis quando um documento inteiro, ou pelo menos grandes seções dele, usa blocos de código com a mesma sintaxe e que devem ser estilizados da mesma maneira. Por outro lado, a diretiva code-block faz mais sentido quando você deseja um controle mais refinado sobre o estilo de cada bloco ou quando você tem um documento contendo blocos de código usando várias sintaxes variadas. Finalmente, a diretiva literalinclude é útil para incluir arquivos de código inteiros em sua documentação.

In all cases, Syntax highlighting is provided by Pygments. When using literal blocks, this is configured using any highlight directives in the source file. When a highlight directive is encountered, it is used until the next highlight directive is encountered. If there is no highlight directive in the file, the global highlighting language is used. This defaults to python but can be configured using the highlight_language config value. The following values are supported:

  • none (no highlighting)

  • default (similar to python3 but with a fallback to none without warning highlighting fails; the default when highlight_language isn’t set)

  • guess (let Pygments guess the lexer based on contents, only works with certain well-recognizable languages)

  • python

  • rest

  • c

  • … and any other lexer alias that Pygments supports

If highlighting with the selected language fails (i.e. Pygments emits an “Error” token), the block is not highlighted in any way.

Importante

The list of lexer aliases supported is tied to the Pygment version. If you want to ensure consistent highlighting, you should fix your version of Pygments.

.. highlight:: language

Exemplo:

.. highlight:: c

This language is used until the next highlight directive is encountered. As discussed previously, language can be any lexer alias supported by Pygments.

options

:linenothreshold: threshold (number (optional))

Enable to generate line numbers for code blocks.

This option takes an optional number as threshold parameter. If any threshold given, the directive will produce line numbers only for the code blocks longer than N lines. If not given, line numbers will be produced for all of code blocks.

Exemplo:

.. highlight:: python
   :linenothreshold: 5
:force: (no value)

If given, minor errors on highlighting are ignored.

Adicionado na versão 2.1.

.. code-block:: [language]
.. sourcecode:: [language]

Exemplo:

.. code-block:: ruby

   Some Ruby code.

The directive’s alias name sourcecode works as well. This directive takes a language name as an argument. It can be any lexer alias supported by Pygments. If it is not given, the setting of highlight directive will be used. If not set, highlight_language will be used. To display a code example inline within other text, rather than as a separate block, you can use the code role instead.

Alterado na versão 2.0: The language argument becomes optional.

options

:linenos: (no value)

Enable to generate line numbers for the code block:

.. code-block:: ruby
   :linenos:

   Some more Ruby code.
:lineno-start: number (number)

Set the first line number of the code block. If present, linenos option is also automatically activated:

.. code-block:: ruby
   :lineno-start: 10

   Some more Ruby code, with line numbering starting at 10.

Adicionado na versão 1.3.

:emphasize-lines: line numbers (comma separated numbers)

Emphasize particular lines of the code block:

.. code-block:: python
   :emphasize-lines: 3,5

   def some_function():
       interesting = False
       print('This line is highlighted.')
       print('This one is not...')
       print('...but this one is.')

Adicionado na versão 1.1.

Alterado na versão 1.6.6: LaTeX supports the emphasize-lines option.

:caption: caption of code block (text)

Set a caption to the code block.

Adicionado na versão 1.3.

:name: a label for hyperlink (text)

Define implicit target name that can be referenced by using ref. For example:

.. code-block:: python
   :caption: this.py
   :name: this-py

   print('Explicit is better than implicit.')

In order to cross-reference a code-block using either the ref or the numref role, it is necessary that both name and caption be defined. The argument of name can then be given to numref to generate the cross-reference. Example:

See :numref:`this-py` for an example.

When using ref, it is possible to generate a cross-reference with only name defined, provided an explicit title is given. Example:

See :ref:`this code snippet <this-py>` for an example.

Adicionado na versão 1.3.

:class: class names (a list of class names separated by spaces)

The class name of the graph.

Adicionado na versão 1.4.

:dedent: number (number or no value)

Strip indentation characters from the code block. When number given, leading N characters are removed. When no argument given, leading spaces are removed via textwrap.dedent(). For example:

.. code-block:: ruby
   :linenos:
   :dedent: 4

       some ruby code

Adicionado na versão 1.3.

Alterado na versão 3.5: Support automatic dedent.

:force: (no value)

If given, minor errors on highlighting are ignored.

Adicionado na versão 2.1.

.. literalinclude:: filename

Longer displays of verbatim text may be included by storing the example text in an external file containing only plain text. The file may be included using the literalinclude directive. [3] For example, to include the Python source file example.py, use:

.. literalinclude:: example.py

The file name is usually relative to the current file’s path. However, if it is absolute (starting with /), it is relative to the top source directory.

Opções adicionais

Like code-block, the directive supports the linenos flag option to switch on line numbers, the lineno-start option to select the first line number, the emphasize-lines option to emphasize particular lines, the name option to provide an implicit target name, the dedent option to strip indentation characters for the code block, and a language option to select a language different from the current file’s standard language. In addition, it supports the caption option; however, this can be provided with no argument to use the filename as the caption. Example with options:

.. literalinclude:: example.rb
   :language: ruby
   :emphasize-lines: 12,15-18
   :linenos:

Tabs in the input are expanded if you give a tab-width option with the desired tab width.

Include files are assumed to be encoded in the source_encoding. If the file has a different encoding, you can specify it with the encoding option:

.. literalinclude:: example.py
   :encoding: latin-1

The directive also supports including only parts of the file. If it is a Python module, you can select a class, function or method to include using the pyobject option:

.. literalinclude:: example.py
   :pyobject: Timer.start

This would only include the code lines belonging to the start() method in the Timer class within the file.

Alternately, you can specify exactly which lines to include by giving a lines option:

.. literalinclude:: example.py
   :lines: 1,3,5-10,20-

This includes the lines 1, 3, 5 to 10 and lines 20 to the last line.

Another way to control which part of the file is included is to use the start-after and end-before options (or only one of them). If start-after is given as a string option, only lines that follow the first line containing that string are included. If end-before is given as a string option, only lines that precede the first lines containing that string are included. The start-at and end-at options behave in a similar way, but the lines containing the matched string are included.

start-after/start-at and end-before/end-at can have same string. start-after/start-at filter lines before the line that contains option string (start-at will keep the line). Then end-before/end-at filter lines after the line that contains option string (end-at will keep the line and end-before skip the first line).

Nota

If you want to select only [second-section] of ini file like the following, you can use :start-at: [second-section] and :end-before: [third-section]:

[first-section]

var_in_first=true

[second-section]

var_in_second=true

[third-section]

var_in_third=true

Useful cases of these option is working with tag comments. :start-after: [initialize] and :end-before: [initialized] options keep lines between comments:

if __name__ == "__main__":
    # [initialize]
    app.start(":8000")
    # [initialized]

When lines have been selected in any of the ways described above, the line numbers in emphasize-lines refer to those selected lines, counted consecutively starting at 1.

When specifying particular parts of a file to display, it can be useful to display the original line numbers. This can be done using the lineno-match option, which is however allowed only when the selection consists of contiguous lines.

You can prepend and/or append a line to the included code, using the prepend and append option, respectively. This is useful e.g. for highlighting PHP code that doesn’t include the <?php/?> markers.

If you want to show the diff of the code, you can specify the old file by giving a diff option:

.. literalinclude:: example.py
   :diff: example.py.orig

This shows the diff between example.py and example.py.orig with unified diff format.

A force option can ignore minor errors on highlighting.

Alterado na versão 0.4.3: Added the encoding option.

Alterado na versão 0.6: Added the pyobject, lines, start-after and end-before options, as well as support for absolute filenames.

Alterado na versão 1.0: Added the prepend, append, and tab-width options.

Alterado na versão 1.3: Added the diff, lineno-match, caption, name, and dedent options.

Alterado na versão 1.4: Added the class option.

Alterado na versão 1.5: Added the start-at, and end-at options.

Alterado na versão 1.6: With both start-after and lines in use, the first line as per start-after is considered to be with line number 1 for lines.

Alterado na versão 2.1: Added the force option.

Alterado na versão 3.5: Support automatic dedent.

Glossário

.. glossary::

This directive must contain a reST definition-list-like markup with terms and definitions. The definitions will then be referenceable with the term role. Example:

.. glossary::

   environment
      A structure where information about all documents under the root is
      saved, and used for cross-referencing.  The environment is pickled
      after the parsing stage, so that successive runs only need to read
      and parse new and changed documents.

   source directory
      The directory which, including its subdirectories, contains all
      source files for one Sphinx project.

In contrast to regular definition lists, multiple terms per entry are allowed, and inline markup is allowed in terms. You can link to all of the terms. For example:

.. glossary::

   term 1
   term 2
      Definition of both terms.

(When the glossary is sorted, the first term determines the sort order.)

If you want to specify “grouping key” for general index entries, you can put a “key” as “term : key”. For example:

.. glossary::

   term 1 : A
   term 2 : B
      Definition of both terms.

Note that “key” is used for grouping key as is. The “key” isn’t normalized; key “A” and “a” become different groups. The whole characters in “key” is used instead of a first character; it is used for “Combining Character Sequence” and “Surrogate Pairs” grouping key.

In i18n situation, you can specify “localized term : key” even if original text only have “term” part. In this case, translated “localized term” will be categorized in “key” group.

Adicionado na versão 0.6: You can now give the glossary directive a :sorted: flag that will automatically sort the entries alphabetically.

Alterado na versão 1.1: Now supports multiple terms and inline markup in terms.

Alterado na versão 1.4: Index key for glossary term should be considered experimental.

Alterado na versão 4.4: In internationalized documentation, the :sorted: flag sorts according to translated terms.

Marcação Meta-Informação

.. sectionauthor:: name <email>

Identifica o autor da seção corrente. O argumento deve incluir nome do autor que será usado na apresentação do endereço de email. O nome do domínio deve ser minúsculo. Exemplo:

.. sectionauthor:: Guido van Rossum <guido@python.org>

Por padrão, essa marcação não é refletida na saída de forma alguma (ela ajuda a acompanhar as contribuições), mas você pode definir o valor de configuração show_authors como True para fazê-los produzir um parágrafo na saída.

.. codeauthor:: name <email>

A diretiva codeauthor, na qual podem aparecer diversas vezes nomes dos autores do código descrito, como nome de autor(es) sectionauthor dos pedaços de documentação. Só haverá saída se o valor de show_authors for True.

Marcação geração índice

Sphinx automatically creates index entries from all object descriptions (like functions, classes or attributes) like discussed in Domínios.

Contudo, também existe marcação disponível, para tornar o índice mais abrangente e habilitar entradas no índice nos documentos onde a informação não está contida nas unidades de informação, como referência ao idioma.

.. index:: <entries>

Essa diretiva contem uma ou mais entradas no índice. Cada entrada consiste de um tipo e valor, separado por dois pontos.

Por exemplo:

.. index::
   single: execution; context
   pair: module; __main__
   pair: module; sys
   triple: module; search; path
   seealso: scope

The execution context
---------------------

...

A diretiva contém cinco entradas, as quais serão convertidas em entradas no índice gerado com link exato para o local onde está o comando de indexação (em caso de mídia offline, corresponde ao número da página).

Como diretivas de índice geram alvos de referências-cruzadas em suas localizações no fonte, faz sentido colocar essas antes do objeto ao qual se referem. ex: cabeçalho, como no exemplo acima.

Os tipos de entrada podem ser:

simples

Creates a single index entry. Can be made a sub-entry by separating the sub-entry text with a semicolon (this notation is also used below to describe what entries are created). Examples:

.. index:: single: execution
           single: execution; context
  • single: execution creates an index entry labelled execution.

  • single: execution; context creates an sub-entry of execution labelled context.

par

A shortcut to create two index entries. The pair of values must be separated by a semicolon. Example:

.. index:: pair: loop; statement

This would create two index entries; loop; statement and statement; loop.

triplo

A shortcut to create three index entries. All three values must be separated by a semicolon. Example:

.. index:: triple: module; search; path

This would create three index entries; module; search path, search; path, module, and path; module search.

ver

A shortcut to create an index entry that refers to another entry. Example:

.. index:: see: entry; other

This would create an index entry referring from entry to other (i.e. ‘entry’: See ‘other’).

ver também

Like see, but inserts ‘see also’ instead of ‘see’.

módulo, palavra chave, operador, objeto, exceção, comando, função interna

These deprecated shortcuts all create two index entries. For example, module: hashlib creates the entries module; hashlib and hashlib; module.

Obsoleto desde a versão 1.0: These Python-specific entry types are deprecated.

Alterado na versão 7.1: Removal version set to Sphinx 9.0. Using these entry types will now emit warnings with the index category.

Marcar entradas no índices “main” através da prefixação com ponto de exclamação “!”. Referências as entradas principais são enfatizadas e geradas no índice. Por examplo, se duas páginas contêm:

.. index:: Python

e uma página contém:

.. index:: ! Python

então a ligação com outra página é enfatizada dentre a estrutura de links.

Para diretivas de índice contendo somente entradas “simples”, existe uma notação com sintaxe curta:

.. index:: BNF, grammar, syntax, notation

Isso cria quatro entradas no índice.

Alterado na versão 1.1: Adicionado tipos “ver” e “ver também”, bem como marcando entradas principais.

options

:name: a label for hyperlink (text)

Define implicit target name that can be referenced by using ref. For example:

.. index:: Python
   :name: py-index

Adicionado na versão 3.0.

:index:

Enquanto a diretiva index é uma marca em nível de bloco e o link aponta para o começo do próximo parágrafo, também uma regra que configura diretamente onde o alvo do link é usado.

O contexto da regra pode ser uma simples frase, a qual existe no text e é usada como ponto de entrada. Também pode haver uma combinação do text e entrada no índice, com estilo explícito em referências cruzadas. Nesse caso parte do “alvo” pode ser uma entrada completa como descrito na diretiva acima. Por exemplo:

This is a normal reST :index:`paragraph` that contains several
:index:`index entries <pair: index; entry>`.

Adicionado na versão 1.1.

Incluindo conteúdo baseado em tags

.. only:: <expression>

Incluir o conteúdo da diretiva somente se a expressão for verdadeira. A expressão deve consistir de marcas, como essa:

.. only:: html and draft

Undefined tags are false, defined tags (via the -t command-line option or within conf.py, see here) are true. Boolean expressions, also using parentheses (like (latex or html) and draft) are supported.

O formato e o nome do construtor corrente (html, latex ou text) são sempre configurados com a marca tag [4]. Para fazer distinção entre formato e o nome explícito, eles são adicionados com o prefixo format_ e builder_, ex: o construtor epub define marcas html, epub, format_html e builder_epub.

Essas tags padrões são configuradas após o arquivo de configuração ter sido lido, portanto não estão disponíveis lá.

All tags must follow the standard Python identifier syntax as set out in the Identifiers and keywords documentation. That is, a tag expression may only consist of tags that conform to the syntax of Python variables. In ASCII, this consists of the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9.

Adicionado na versão 0.6.

Alterado na versão 1.2: Adicionado o nome do construtor e os prefixos.

Aviso

Essa diretiva é desenhada para controlar sómente conteúdo do documento. Não pode controlar seções, rótulos e outros.

Tabelas

Usar reStructuredText tables, ex. qualquer

A diretiva table serve como sobreposição opcional da sintaxe grid e simple.

They work fine in HTML output, but rendering tables to LaTeX is complex. Check the latex_table_style.

Alterado na versão 1.6: Merged cells (multi-row, multi-column, both) from grid tables containing complex contents such as multiple paragraphs, blockquotes, lists, literal blocks, will render correctly to LaTeX output.

.. tabularcolumns:: column spec

This directive influences only the LaTeX output for the next table in source. The mandatory argument is a column specification (known as an “alignment preamble” in LaTeX idiom). Please refer to a LaTeX documentation, such as the wiki page, for basics of such a column specification.

Adicionado na versão 0.3.

Nota

tabularcolumns conflicts with :widths: option of table directives. If both are specified, :widths: option will be ignored.

Sphinx will render tables with more than 30 rows with longtable. Besides the l, r, c and p{width} column specifiers, one can also use \X{a}{b} (new in version 1.5) which configures the column width to be a fraction a/b of the total line width and \Y{f} (new in version 1.6) where f is a decimal: for example \Y{0.2} means that the column will occupy 0.2 times the line width.

When this directive is used for a table with at most 30 rows, Sphinx will render it with tabulary. One can then use specific column types L (left), R (right), C (centered) and J (justified). They have the effect of a p{width} (i.e. each cell is a LaTeX \parbox) with the specified internal text alignment and an automatically computed width.

Aviso

  • Cells that contain list-like elements such as object descriptions, blockquotes or any kind of lists are not compatible with the LRCJ column types. The column type must then be some p{width} with an explicit width (or \X{a}{b} or \Y{f}).

  • Literal blocks do not work with tabulary at all. Sphinx will fall back to tabular or longtable environments and generate a suitable column specification.

In absence of the tabularcolumns directive, and for a table with at most 30 rows and no problematic cells as described in the above warning, Sphinx uses tabulary and the J column-type for every column.

Alterado na versão 1.6: Formerly, the L column-type was used (text is flushed-left). To revert to this, include \newcolumntype{T}{L} in the LaTeX preamble, as in fact Sphinx uses T and sets it by default to be an alias of J.

Dica

A frequent issue with tabulary is that columns with little contents appear to be “squeezed”. One can add to the LaTeX preamble for example \setlength{\tymin}{40pt} to ensure a minimal column width of 40pt, the tabulary default of 10pt being too small.

Dica

To force usage of the LaTeX longtable environment pass longtable as a :class: option to table, csv-table, or list-table. Use rst-class for other tables.

Math

A linguagem de entrada para matemática é marcação LaTeX. É de fato um padrão para notação matemática em texto simples e possui a vantagem de não precisar de tradução adicional para saída LaTeX.

Lembre-se quando introduzir simbolos matemáticos em Python docstrings lidas por autodoc, deve usar ou duplas barras invertidas ou usar string Python do tipo raw (r"raw").

.. math::

Diretiva para math exibida (math controla toda a linha por si).

A diretiva suporta múltiplas equações, que devem estar separadas por linhas em branco:

.. math::

   (a + b)^2 = a^2 + 2ab + b^2

   (a - b)^2 = a^2 - 2ab + b^2

Adicionalmente, cada simples equação é configurada com ambiente split, que significa que deve haver múltiplas linhas alinhadas na equação, alinhada em & e separada por \\:

.. math::

   (a + b)^2  &=  (a + b)(a + b) \\
              &=  a^2 + 2ab + b^2

Para maiores detalhes, veja a documentação em AmSMath LaTeX package.

Quando math é somente uma linha de texto, também pode ser usada como argumento de diretiva:

.. math:: (a + b)^2 = a^2 + 2ab + b^2

Normalmente equações não são numeradas. Se desejar que as equações tenham um número, usar opção label. Quando utilizada, irá ser escolhido um rótulo interno para a equação, através do qual poderá ser referenciada e vai causar o uso de número de equação. Ver eq para exemplo. O estilo de numeração depende do formato de saída.

Também existe uma opção nowrap que previne qualquer quebra no ambiente math. Quando usar essa opção, certifique-se que math está configurada corretamente. Por exemplo:

.. math::
   :nowrap:

   \begin{eqnarray}
      y    & = & ax^2 + bx + c \\
      f(x) & = & x^2 + 2xy + y^2
   \end{eqnarray}

Ver também

Suporte matemático para saídas HTML no Sphinx

Rendering options for math with HTML builders.

latex_engine

Explains how to configure LaTeX builder to support Unicode literals in math mark-up.

Grammar production displays

Special markup is available for displaying the productions of a formal grammar. The markup is simple and does not attempt to model all aspects of BNF (or any derived forms), but provides enough to allow context-free grammars to be displayed in a way that causes uses of a symbol to be rendered as hyperlinks to the definition of the symbol. There is this directive:

.. productionlist:: [productionGroup]

This directive is used to enclose a group of productions. Each production is given on a single line and consists of a name, separated by a colon from the following definition. If the definition spans multiple lines, each continuation line must begin with a colon placed at the same column as in the first line. Blank lines are not allowed within productionlist directive arguments.

The definition can contain token names which are marked as interpreted text (e.g., “sum ::= `integer` "+" `integer`”) – this generates cross-references to the productions of these tokens. Outside of the production list, you can reference to token productions using token.

The productionGroup argument to productionlist serves to distinguish different sets of production lists that belong to different grammars. Multiple production lists with the same productionGroup thus define rules in the same scope.

Inside of the production list, tokens implicitly refer to productions from the current group. You can refer to the production of another grammar by prefixing the token with its group name and a colon, e.g, “otherGroup:sum”. If the group of the token should not be shown in the production, it can be prefixed by a tilde, e.g., “~otherGroup:sum”. To refer to a production from an unnamed grammar, the token should be prefixed by a colon, e.g., “:sum”.

Outside of the production list, if you have given a productionGroup argument you must prefix the token name in the cross-reference with the group name and a colon, e.g., “myGroup:sum” instead of just “sum”. If the group should not be shown in the title of the link either an explicit title can be given (e.g., “myTitle <myGroup:sum>”), or the target can be prefixed with a tilde (e.g., “~myGroup:sum”).

Note that no further reST parsing is done in the production, so that you don’t have to escape * or | characters.

The following is an example taken from the Python Reference Manual:

.. productionlist::
   try_stmt: try1_stmt | try2_stmt
   try1_stmt: "try" ":" `suite`
            : ("except" [`expression` ["," `target`]] ":" `suite`)+
            : ["else" ":" `suite`]
            : ["finally" ":" `suite`]
   try2_stmt: "try" ":" `suite`
            : "finally" ":" `suite`

Notas de Rodapé