Sintaxe de referência cruzada

As referências cruzadas são geradas por muitas roles de texto interpretado semântico. Basicamente, você só precisa escrever :role:`destino`, e um link será criado para o item chamado destino do tipo indicado por role. O texto do link será o mesmo que destino.

Existem alguns recursos adicionais, no entanto, que tornam as roles de referência cruzada mais versáteis:

  • Você pode fornecer um título explícito e destino de referência, como nos hiperlinks reST diretos: :role:`título <destino>` vai fazer referência a destino, mas o texto do link será título.

  • Se você prefixar o conteúdo com !, nenhuma referência/hiperlink será criada.

  • Se você prefixar o conteúdo com ~, o texto do link será apenas o último componente do destino. Por exemplo, :py:meth:`~Queue.Queue.get` vai fazer referência a Queue.Queue.get, mas somente exibirá get como o texto do link. Isso não funciona com todas as funções de referência cruzada, mas é específico do domínio.

    Na saída HTML, o atributo title do link (por exemplo, mostrado como uma dica de ferramenta ao passar o mouse) sempre será o nome completo do destino.

Fazendo referência cruzada de qualquer coisa

:any:

Adicionado na versão 1.3.

Essa role de conveniência tenta fazer o melhor para localizar um destino válido para seu texto de referência.

  • Primeiro, ele tenta destinos de referência cruzada padrão que seriam referenciados por doc, ref ou option.

    Objetos personalizados adicionados ao domínio padrão por extensões (veja Sphinx.add_object_type()) também são pesquisados.

  • Em seguida, ele procura por objetos (destinos) em todos os domínios carregados. Depende dos domínios quão específica deve ser uma correspondência. Por exemplo, no domínio Python uma referência de :any:`Builder` corresponderia à classe sphinx.builders.Builder.

Se nenhum ou vários destinos forem encontrados, um aviso será emitido. No caso de vários destinos, você pode alterar “any” para uma role específica.

This role is a good candidate for setting default_role. If you do, you can write cross-references without a lot of markup overhead. For example, in this Python function documentation:

.. function:: install()

   This function installs a `handler` for every signal known by the
   `signal` module.  See the section `about-signals` for more information.

pode haver referências a um termo do glossário (normalmente :term:`texto`), um módulo Python (normalmente :py:mod:`signal` ou :mod:`signal` ) e uma seção (normalmente :ref:`about-signs`).

A role any também funciona junto com a extensão intersphinx: quando nenhuma referência cruzada local é encontrada, todos os tipos de objetos de inventários intersphinx também são pesquisados.

Objetos de referência cruzada

Essas roles são descritas com seus respectivos domínios:

Referência cruzada de locais arbitrários

:ref:

Para oferecer suporte a referência cruzada para locais arbitrários em qualquer documento, os rótulos reST padrão são usados. Para que isso funcione, os nomes dos rótulos devem ser exclusivos em toda a documentação. Existem duas maneiras de se referir aos rótulos:

  • Se você colocar um rótulo diretamente antes do título de uma seção, você pode fazer referência a ele com :ref:`nome-rótulo`. Por exemplo:

    .. _my-reference-label:
    
    Section to cross-reference
    --------------------------
    
    This is the text of the section.
    
    It refers to the section itself, see :ref:`my-reference-label`.
    

    A role :ref: geraria então um link para a seção, com o título do link sendo “Seção para referência cruzada”. Isso funciona tão bem quando a seção e a referência estão em arquivos fontes diferentes.

    Etiquetas automáticas também funcionam com figuras. Por exemplo:

    .. _my-figure:
    
    .. figure:: whatever
    
       Figure caption
    

    Neste caso, uma referência :ref:`minha-imagem` iria inserir uma referência à imagem com o texto do link “Legenda da imagem”.

    O mesmo funciona para tabelas que recebem uma legenda explícita usando a diretiva table.

  • Rótulos que não são colocados antes de um título de seção ainda podem ser referenciados, mas você deve dar ao link um título explícito, usando esta sintaxe: :ref:`Título do link <nome-rótulo>`.

Nota

Reference labels must start with an underscore. When referencing a label, the underscore must be omitted (see examples above).

Using ref is advised over standard reStructuredText links to sections (like `Section title`_) because it works across files, when section headings are changed, will raise warnings if incorrect, and works for all builders that support cross-references.

Cross-referencing documents

Adicionado na versão 0.6.

There is also a way to directly link to documents:

:doc:

Link to the specified document; the document name can be specified in absolute or relative fashion. For example, if the reference :doc:`parrot` occurs in the document sketches/index, then the link refers to sketches/parrot. If the reference is :doc:`/people` or :doc:`../people`, the link refers to people.

If no explicit link text is given (like usual: :doc:`Monty Python members </people>`), the link caption will be the title of the given document.

Referencing downloadable files

Adicionado na versão 0.6.

:download:

This role lets you link to files within your source tree that are not reST documents that can be viewed, but files that can be downloaded.

When you use this role, the referenced file is automatically marked for inclusion in the output when building (obviously, for HTML output only). All downloadable files are put into a _downloads/<unique hash>/ subdirectory of the output directory; duplicate filenames are handled.

An example:

See :download:`this example script <../example.py>`.

The given filename is usually relative to the directory the current source file is contained in, but if it absolute (starting with /), it is taken as relative to the top source directory.

The example.py file will be copied to the output directory, and a suitable link generated to it.

Not to show unavailable download links, you should wrap whole paragraphs that have this role:

.. only:: builder_html

   See :download:`this example script <../example.py>`.

Cross-referencing figures by figure number

Adicionado na versão 1.3.

Alterado na versão 1.5: numref role can also refer sections. And numref allows {name} for the link text.

:numref:

Link to the specified figures, tables, code-blocks and sections; the standard reST labels are used. When you use this role, it will insert a reference to the figure with link text by its figure number like “Fig. 1.1”.

If an explicit link text is given (as usual: :numref:`Image of Sphinx (Fig. %s) <my-figure>`), the link caption will serve as title of the reference. As placeholders, %s and {number} get replaced by the figure number and {name} by the figure caption. If no explicit link text is given, the numfig_format setting is used as fall-back default.

If numfig is False, figures are not numbered, so this role inserts not a reference but the label or the link text.

Cross-referencing other items of interest

The following roles do possibly create a cross-reference, but do not refer to objects:

:envvar:

An environment variable. Index entries are generated. Also generates a link to the matching envvar directive, if it exists.

:token:

The name of a grammar token (used to create links between productionlist directives).

:keyword:

The name of a keyword in Python. This creates a link to a reference label with that name, if it exists.

:option:

A command-line option to an executable program. This generates a link to a option directive, if it exists.

The following role creates a cross-reference to a term in a glossary:

:term:

Reference to a term in a glossary. A glossary is created using the glossary directive containing a definition list with terms and definitions. It does not have to be in the same file as the term markup, for example the Python docs have one global glossary in the glossary.rst file.

If you use a term that’s not explained in a glossary, you’ll get a warning during build.