As previously discussed, a directive is a generic block of explicit markup. While Docutils provides a number of directives, Sphinx provides many more and uses directives as one of the primary extension mechanisms.

See Domains for roles added by domains.

Ver também

Refer to the reStructuredText Primer for an overview of the directives provided by Docutils.

Table of contents

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.


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


To create table of contents for current document (.rst file), use the standard reST contents directive.

.. toctree::

This directive inserts a “TOC tree” at the current location, using the individual TOCs (including “sub-TOC trees”) of the documents given in the directive body. Relative document names (not beginning with a slash) are relative to the document the directive occurs in, absolute names are relative to the source directory. A numeric maxdepth option may be given to indicate the depth of the tree; by default, all levels are included. 1

The representation of “TOC tree” is changed in each output format. The builders that output multiple files (ex. HTML) treat it as a collection of hyperlinks. On the other hand, the builders that output a single file (ex. LaTeX, man page, etc.) replace it with the content of the documents on the TOC tree.

Considere esse exemplo (obtido da biblioteca de Doc. Python, índice ref.):

.. toctree::
   :maxdepth: 2

   (many more documents listed here)

Serve para dois objetivos:

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

  • Sphinx knows the relative order of the documents intro, strings and so forth, and it knows that they are children of the shown document, the library index. From this information it generates “next chapter”, “previous chapter” and “parent chapter” links.


Document titles in the toctree will be automatically read from the title of the referenced document. If that isn’t what you want, you can specify an explicit title and target using a similar syntax to reST hyperlinks (and Sphinx’s cross-referencing syntax). This looks like:

.. toctree::

   All about strings <strings>

The second line above will link to the strings document, but will use the title “All about strings” instead of the title of the strings document.

Podem ser adicionados links externos, através de 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 opção numbered. Por exemplo:

.. toctree::


Numbering then starts at the heading of foo. Sub-toctrees are automatically numbered (don’t give the numbered flag to those).

Numbering up to a specific depth is also possible, by giving the depth as a numeric argument to numbered.

Opções adicionais

You can use the caption option to provide a toctree caption and you can use the name option to provide an implicit target name that can be referenced by using ref:

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


If you want only the titles of documents in the tree to show up, not other headings of the same level, you can use the titlesonly option:

.. toctree::


You can use “globbing” in toctree directives, by giving the glob flag option. All entries are then matched against the list of available documents, and matches are inserted into the list alphabetically. Example:

.. toctree::


This includes first all documents whose names start with intro, then all documents in the recipe folder, then all remaining documents (except the one containing the directive, of course.) 2

The special entry name self stands for the document containing the toctree directive. This is useful if you want to generate a “sitemap” from the toctree.

You can use the reversed flag option to reverse the order of the entries in the list. This can be useful when using the glob flag option to reverse the ordering of the files. Example:

.. toctree::


You can also give a “hidden” option to the directive, like this:

.. toctree::


This will still notify Sphinx of the document hierarchy, but not insert links into the document at the location of the directive – this makes sense if you intend to insert these links yourself, in a different style, or in the HTML sidebar.

In cases where you want to have only one top-level toctree and hide all other lower level toctrees you can add the “includehidden” option to the top-level toctree entry:

.. toctree::


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

In the end, all documents in the source directory (or subdirectories) must occur in some toctree directive; Sphinx will emit a warning if it finds a file that is not included, because that means that this file will not be reachable through standard navigation.

Use exclude_patterns to explicitly exclude documents or directories from building completely. Use the “orphan” metadata to let a document be built, but notify Sphinx that it is not reachable via a toctree.

The “root document” (selected by root_doc) is the “root” of the TOC tree hierarchy. It can be used as the documentation’s main page, or as a “full table of contents” if you don’t give a maxdepth option.

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

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

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

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

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

Alterado na versão 1.3: Adic. 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

    São usadas respectivamente nas opções para índice geral, índice módulo Python e página de pesquisa.

    O índice geral e preenchido com entradas dos módulos, todas gerações de índices object descriptions, e para diretivas de index.

    O módulo Python index contém uma entrada por diretiva py:module.

    A página de pesquisa contém um formulário que usa índice pesquisa em JSON e JavaScript para busca integral de texto para palavras existentes; normalmente funciona nos diversos navegadores que suportam JavaScript Moderno.

  • todo nome começando com _

    Though few such names are currently used by Sphinx, you should not create documents or document-containing directories with such names. (Using _ as a prefix for a custom template directory is fine.)


Be careful with unusual characters in filenames. Some formats may interpret these characters in unexpected ways:

  • Não usar dois pontos : para formatos base HTML. Links para outras partes podem não funcionar.

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

Paragraph-level markup

These directives create short paragraphs and can be used inside information units as well as normal text.

.. note::

An especially important bit of information about an API that a user should be aware of when using whatever bit of API the note pertains to. The content of the directive should be written in complete sentences and include all appropriate punctuation.


.. note::

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

An important bit of information about an API that a user should be very aware of when using whatever bit of API the warning pertains to. The content of the directive should be written in complete sentences and include all appropriate punctuation. This differs from note in that it is recommended over note for information regarding security.

.. versionadded:: version

This directive documents the version of the project which added the described feature to the library or C API. When this applies to an entire module, it should be placed at the top of the module section before any prose.

The first argument must be given and is the version in question; you can add a second argument consisting of a brief explanation of the change.


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

Note that there must be no blank line between the directive head and the explanation; this is to make these blocks visually continuous in the markup.

.. versionchanged:: version

Similar to versionadded, but describes when and what changed in the named feature in some way (new parameters, changed side effects, etc.).

.. deprecated:: version

Similar to versionchanged, but describes when the feature was deprecated. An explanation can also be given, for example to inform the reader what should be used instead. Example:

.. deprecated:: 3.1
   Use :func:`spam` instead.
.. seealso::

Many sections include a list of references to module documentation or external documents. These lists are created using the seealso directive.

The seealso directive is typically placed in a section just before any subsections. For the HTML output, it is shown boxed off from the main flow of the text.

The content of the seealso directive should be a reST definition list. Example:

.. seealso::

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

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

There’s also a “short form” allowed that looks like this:

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

Novo na versão 0.5: The short form.

.. rubric:: title

This directive creates a paragraph heading that is not used to create a table of contents node.


If the title of the rubric is “Footnotes” (or the selected language’s equivalent), this rubric is ignored by the LaTeX writer, since it is assumed to only contain footnote definitions and therefore would create an empty heading.

.. centered::

This directive creates a centered boldfaced line of text. Use it as follows:


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

This directive must contain a bullet list. It will transform it into a more compact list by either distributing more than one item horizontally, or reducing spacing between items, depending on the builder.

For builders that support the horizontal distribution, there is a columns option that specifies the number of columns; it defaults to 2. Example:

.. hlist::
   :columns: 3

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

Novo na versão 0.6.

Showing code examples

There are multiple ways to show syntax-highlighted literal code blocks in Sphinx:

Doctest blocks can only be used to show interactive Python sessions, while the remaining three can be used for other languages. Of these three, literal blocks are useful when an entire document, or at least large sections of it, use code blocks with the same syntax and which should be styled in the same manner. On the other hand, the code-block directive makes more sense when you want more fine-tuned control over the styling of each block or when you have a document containing code blocks using multiple varied syntaxes. Finally, the literalinclude directive is useful for including entire code files in your documentation.

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.


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


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


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


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

If given, minor errors on highlighting are ignored.

Novo na versão 2.1.

.. code-block:: [language]


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

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


:linenos: (no value)

Enable to generate line numbers for the code block:

.. code-block:: ruby

   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.

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

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

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

Novo na versão 1.3.

: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
   :dedent: 4

       some ruby code

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

Novo 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

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


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







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

if __name__ == "__main__":
    # [initialize]
    # [initialize]

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


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

      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.

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

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 gera nenhuma saída, em nenhum modo (apenas ajuda a manter rastreabilidade dos contribuidores), mas pode ser configurado valor :confval: show_authors` para True para 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 Domains.

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
   module: __main__
   module: sys
   triple: module; search; path

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:


Criar uma simples entrada no índice. Pode ser feita uma sub-entrada separando-se o texto da mesma com dois pontos (essa notação também é usada abaixo para descrever entradas criadas).


pair: sopa; mel é um atalho que cria duas entradas no índice, nomeadamente sopa; mel e mel; sopa.


Mais abrangente, triple: módulo; pesquisa; caminho é um atalho para criar três entradas no índice, a saber módulo; pesquisa caminho`, pesquisa; caminho, módulo e caminho; módulo pesquisa.


ver: entrada; outra cria entrada no índice referindo-se a entrada para outra.

ver também

Como ver, mas insere “ver também” em vez de “ver”.

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

Estas criam duas entradas no índice. Por exemplo: module: hashlib cria as entradas module; hashlib e hashlib; module. (Uso específico em Python e uso é obsoleto).

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.


:name: a label for hyperlink (text)

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

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

Novo na versão 3.0.


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

Novo 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

Marcas não definidas são por natureza falsas, marcas definidas (através da opção de linha de comando -t ou dentro do :arquivo:`conf.py`, ver aqui) são por natureza verdadeiras. Expressões booleanas, também usam parênteses (como html e (latex ou draft)) são suportadas.

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.

Novo na versão 0.6.

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


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


Usar reStructuredText tables, ex. qualquer

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

Funcionam bem saída HTML, contudo há alguns inconvenientes quando usar tabelas em LaTeX: a largura da coluna é difícil de automaticamente ser calculada. Por essa razão, existe a seguinte diretiva:

.. tabularcolumns:: column spec

Essa diretiva da “coluna espec.” para a próxima tabela que ocorrer no arquivo fonte. A spec é o segundo argumento do ambiente do pacote LaTeX tabulary (o qual o Sphinx usa para traduzir tabelas). Pode ter valores como


o que significa três colunas ajustadas a esquerda. Para colunas com textos maiores que serão automaticamente quebrados, use a construção padrão Python p{width} ou especificar tabulação automática:


descartar coluna da esquerda com largura automática


descartar coluna da direita com largura automática


centralizar coluna com largura automática


Coluna justificada com largura automática

A largura automática de colunas LRCJ são atribuídas por proporção tabulary ao observado no compartilhamento do primeiro passo onde a célula da tabela é renderizada com sua largura “horizontal” natural.

Por padrão, Sphinx usa layout de tabela J para toda coluna.

Novo na versão 0.3.

Alterado na versão 1.6: Merged cells may now contain multiple paragraphs and are much better handled, thanks to custom Sphinx LaTeX macros. This novel situation motivated the switch to J specifier and not L by default.


Sphinx actually uses T specifier having done \newcolumntype{T}{J}. To revert to previous default, insert \newcolumntype{T}{L} in the LaTeX preamble (see latex_elements).

A frequent issue with tabulary is that columns with little contents are “squeezed”. The minimal column width is a tabulary parameter called \tymin. You may set it globally in the LaTeX preamble via \setlength{\tymin}{40pt} for example.

Else, use the tabularcolumns directive with an explicit p{40pt} (for example) for that column. You may use also l specifier but this makes the task of setting column widths more difficult if some merged cell intersects that column.


Tables with more than 30 rows are rendered using longtable, not tabulary, in order to allow pagebreaks. The L, R, … specifiers do not work for these tables.

Tables that contain list-like elements such as object descriptions, blockquotes or any kind of lists cannot be set out of the box with tabulary. They are therefore set with the standard LaTeX tabular (or longtable) environment if you don’t give a tabularcolumns directive. If you do, the table will be set with tabulary but you must use the p{width} construct (or Sphinx’s \X and \Y specifiers described below) for the columns containing these elements.

Literal blocks do not work with tabulary at all, so tables containing a literal block are always set with tabular. The verbatim environment used for literal blocks only works in p{width} (and \X or \Y) columns, hence Sphinx generates such column specs for tables containing literal blocks.

Since Sphinx 1.5, the \X{a}{b} specifier is used (there is a backslash in the specifier letter). It is like p{width} with the width set to a fraction a/b of the current line width. You can use it in the tabularcolumns (it is not a problem if some LaTeX macro is also called \X.)

It is not needed for b to be the total number of columns, nor for the sum of the fractions of the \X specifiers to add up to one. For example |\X{2}{5}|\X{1}{5}|\X{1}{5}| is legitimate and the table will occupy 80% of the line width, the first of its three columns having the same width as the sum of the next two.

This is used by the :widths: option of the table directive.

Since Sphinx 1.6, there is also the \Y{f} specifier which admits a decimal argument, such has \Y{0.15}: this would have the same effect as \X{3}{20}.

Alterado na versão 1.6: Merged cells from complex grid tables (either multi-row, multi-column, or both) now allow blockquotes, lists, literal blocks, … as do regular cells.

Sphinx’s merged cells interact well with p{width}, \X{a}{b}, \Y{f} and tabulary’s columns.


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


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

      y    & = & ax^2 + bx + c \\
      f(x) & = & x^2 + 2xy + y^2

Ver também

Suporte matemático para saídas HTML no Sphinx

Rendering options for math with HTML builders.


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é


O construtor LaTeX só usa a opção maxdepth  para a primeira diretiva toctree do documento.


Anotação sobre sintaxe global disponível: podem ser usadas construções *, ?, [...] e [!...] com funcionalidade que não combinem com barras. Asterisco duplo ** pode ser usada para combinar com qualquer sequência de caracteres incluindo barras.


There is a standard .. include directive, but it raises errors if the file is not found. This one only emits a warning.


Para muitos construtores nome e formato é o mesmo. Atualmente somente os construtores derivados do html podem distinguir entre formato do construtor e nome do construtor.

Notar que o construtor corrente não possui entrada no conf.py, o construtor só está disponível depois de inicializado.