Domínios

Novo na versão 1.0.

Originalmente, o Sphinx foi concebido para um único projeto, a documentação da linguagem Python. Pouco depois, foi disponibilizado para todos como uma ferramenta de documentação, mas a documentação dos módulos Python permaneceu profundamente embutida – as diretivas mais fundamentais, como function, foram projetadas para objetos Python. Como o Sphinx se tornou um tanto popular, surgiu o interesse em usá-lo para muitos propósitos diferentes: projetos C/C++, JavaScript ou mesmo marcação reStructuredText (como nesta documentação).

Enquanto isso sempre foi possível, agora é muito mais fácil apoiar facilmente a documentação de projetos usando linguagens de programação diferentes ou mesmo aquelas não suportadas pela distribuição principal do Sphinx, fornecendo um domínio para cada uma dessas finalidades.

Um domínio é uma coleção de marcação (diretivas e papeis do reStructuredText) para descrever e vincular a objetos pertencentes um ao outro, por exemplo, elementos de uma linguagem de programação. Nomes de diretivas e papeis em um domínio têm nomes como domain:name, por exemplo py:function. Os domínios também podem fornecer índices personalizados (como o índice do módulo Python).

Ter domínios significa que não há problemas de nomenclatura quando um conjunto de documentação deseja fazer referência a Classes C++ e Python. Isso também significa que as extensões que suportam a documentação de novos idiomas são muito mais fáceis de serem escritas.

Esta seção descreve o que os domínios incluídos no Sphinx fornecem. A API de domínio também está documentada na seção Domain API.

Marcação Básica

Most domains provide a number of object description directives, used to describe specific objects provided by modules. Each directive requires one or more signatures to provide basic information about what is being described, and the content should be the description.

A domain will typically keep an internal index of all entities to aid cross-referencing. Typically it will also add entries in the shown general index. If you want to suppress the addition of an entry in the shown index, you can give the directive option flag :noindexentry:. If you want to exclude the object description from the table of contents, you can give the directive option flag :nocontentsentry:. If you want to typeset an object description, without even making it available for cross-referencing, you can give the directive option flag :noindex: (which implies :noindexentry:). Though, note that not every directive in every domain may support these options.

Novo na versão 3.2: The directive option noindexentry in the Python, C, C++, and Javascript domains.

Novo na versão 5.2.3: The directive option :nocontentsentry: in the Python, C, C++, Javascript, and reStructuredText domains.

An example using a Python domain directive:

.. py:function:: spam(eggs)
                 ham(eggs)

   Spam or ham the foo.

Isso descreve as duas funções Python spam e ham. (Observe que quando as assinaturas ficam muito longas, você pode quebrá-las se adicionar uma barra invertida às linhas que continuam na próxima linha. Exemplo:

.. py:function:: filterwarnings(action, message='', category=Warning, \
                                module='', lineno=0, append=False)
   :noindex:

(Este exemplo também mostra como usar o sinalizador :noindex:.)

The domains also provide roles that link back to these object descriptions. For example, to link to one of the functions described in the example above, you could say

The function :py:func:`spam` does a similar thing.

Como você pode ver, os nomes de diretiva e papel contêm o nome de domínio e o nome da diretiva.

Domínio Padrão

Para documentação que descreve objetos de apenas um domínio, os autores não terão que declarar novamente seu nome em cada diretiva, função, etc… depois de especificar um padrão. Isso pode ser feito por meio do valor de configuração primary_domain ou por meio desta diretiva:

.. default-domain:: name

Selecione um novo domínio padrão. Enquanto primary_domain seleciona um padrão global, isso só tem efeito dentro do mesmo arquivo.

Se nenhum outro padrão for selecionado, o domínio Python (denominado py) é o padrão, principalmente para compatibilidade com a documentação escrita para versões anteriores do Sphinx.

As diretivas e papéis que pertencem ao domínio padrão podem ser mencionadas sem fornecer o nome do domínio, ou seja:

.. function:: pyfunc()

   Describes a Python function.

Reference to :func:`pyfunc`.

Sintaxe Ref. Cruzada

Para funções de referência cruzada fornecidas por domínios, existem os mesmos recursos que existem para referências cruzadas gerais. Veja Sintaxe de referência cruzada.

Resumindo:

  • Você pode fornecer um título explícito e destino de referência: :role:`title <target>` irá se referir a target, mas o texto do link será title.

  • 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` irá se referir a Queue.Queue.get, mas somente exibirá get como o texto do link.

Domínio Python

O domínio Python (nome py) fornece as seguintes diretivas para declarações de módulo:

.. py:module:: name

This directive marks the beginning of the description of a module (or package submodule, in which case the name should be fully qualified, including the package name). A description of the module such as the docstring can be placed in the body of the directive.

Esta diretiva também causará uma entrada no índice do módulo global.

Alterado na versão 5.2: Module directives support body content.

options

:platform: platforms (comma separated list)

Indicate platforms which the module is available (if it is available on all platforms, the option should be omitted). The keys are short identifiers; examples that are in use include “IRIX”, “Mac”, “Windows” and “Unix”. It is important to use a key which has already been used when applicable.

:synopsis: purpose (text)

Consist of one sentence describing the module’s purpose – it is currently only used in the Global Module Index.

:deprecated: (no argument)

Mark a module as deprecated; it will be designated as such in various locations then.

.. py:currentmodule:: name

Esta diretiva diz ao Sphinx que as classes, funções, etc. documentadas a partir daqui estão no módulo fornecido (como py:module), mas não criará entradas de índice, uma entrada no Índice Global de Módulo ou um link de destino para py:mod. Isso é útil em situações onde a documentação para coisas em um módulo é espalhada por vários arquivos ou seções – um local tem a diretiva py: module, os outros apenas py:currentmodule .

As seguintes diretivas são fornecidas para o conteúdo do módulo e da classe:

.. py:function:: name(parameters)

Descreve uma função de nível de módulo. A assinatura deve incluir os parâmetros fornecidos na definição da função Python, consulte Assinaturas Python. Por exemplo:

.. py:function:: Timer.repeat(repeat=3, number=1000000)

Para métodos, você deve usar py:method.

A descrição normalmente inclui informações sobre os parâmetros necessários e como eles são usados (especialmente se os objetos mutáveis passados como parâmetros são modificados), efeitos colaterais e possíveis exceções.

Esta informação pode (em qualquer diretiva py) opcionalmente ser fornecida em uma forma estruturada, veja Lista Informação Campos.

options

:async: (no value)

Indicate the function is an async function.

Novo na versão 2.1.

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

Novo na versão 4.0.

.. py:data:: name

Descreve dados globais em um módulo, incluindo variáveis e valores usados como “constantes definidas”. Atributos de classe e objeto não são documentados usando este ambiente.

options

:type: type of the variable (text)

Novo na versão 2.4.

:value: initial value of the variable (text)

Novo na versão 2.4.

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

Novo na versão 4.0.

.. py:exception:: name

Descreve uma classe de exceção. A assinatura pode, mas não precisa incluir parênteses com argumentos do construtor.

options

:final: (no value)

Indicate the class is a final class.

Novo na versão 3.1.

.. py:class:: name
.. py:class:: name(parameters)

Descreve uma classe. A assinatura pode incluir opcionalmente parênteses com parâmetros que serão mostrados como argumentos do construtor. Veja também Assinaturas Python.

Métodos e atributos pertencentes à classe devem ser colocados no corpo desta diretiva. Se forem colocados fora, o nome fornecido deve conter o nome da classe para que as referências cruzadas ainda funcionem. Exemplo:

.. py:class:: Foo

   .. py:method:: quux()

-- or --

.. py:class:: Bar

.. py:method:: Bar.quux()

A primeira maneira é a preferida.

options

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

Novo na versão 4.0.

:final: (no value)

Indicate the class is a final class.

Novo na versão 3.1.

.. py:attribute:: name

Descreve um atributo de dados do objeto. A descrição deve incluir informações sobre o tipo de dados esperados e se eles podem ser alterados diretamente.

options

:type: type of the attribute (text)

Novo na versão 2.4.

:value: initial value of the attribute (text)

Novo na versão 2.4.

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

Novo na versão 4.0.

.. py:property:: name

Describes an object property.

Novo na versão 4.0.

options

:abstractmethod: (no value)

Indicate the property is abstract.

:classmethod: (no value)

Indicate the property is a classmethod.

:type: type of the property (text)
.. py:method:: name(parameters)

Descreve um método de objeto. Os parâmetros não devem incluir o parâmetro self. A descrição deve incluir informações semelhantes às descritas para function. Veja também Assinaturas Python e Lista Informação Campos.

options

:abstractmethod: (no value)

Indicate the method is an abstract method.

Novo na versão 2.1.

:async: (no value)

Indicate the method is an async method.

Novo na versão 2.1.

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

Novo na versão 4.0.

:classmethod: (no value)

Indicate the method is a class method.

Novo na versão 2.1.

:final: (no value)

Indicate the class is a final method.

Novo na versão 3.1.

:staticmethod: (no value)

Indicate the method is a static method.

Novo na versão 2.1.

.. py:staticmethod:: name(parameters)

Como py:method, mas indica que o método é um método estático.

Novo na versão 0.4.

.. py:classmethod:: name(parameters)

Como py:method, mas indica que o método é um método de classe.

Novo na versão 0.6.

.. py:decorator:: name
.. py:decorator:: name(parameters)

Descreve uma função de decorador. A assinatura deve representar o uso como decorador. Por exemplo, dadas as funções

def removename(func):
    func.__name__ = ''
    return func

def setnewname(name):
    def decorator(func):
        func.__name__ = name
        return func
    return decorator

as descrições devem se parecer com isso:

.. py:decorator:: removename

   Remove name of the decorated function.

.. py:decorator:: setnewname(name)

   Set name of the decorated function to *name*.

(em oposição a .. py:decorator:: removename(func).)

Não há papel py:deco para vincular a um decorador que está marcado com esta diretiva; em vez disso, use o papel py: func.

.. py:decoratormethod:: name
.. py:decoratormethod:: name(signature)

O mesmo que py:decorator, mas para decoradores que são métodos.

Consulte um método decorador usando o papel py:meth.

Assinaturas Python

As assinaturas de funções, métodos e construtores de classes podem ser fornecidas como se fossem escritas em Python.

Valores padrão para argumentos opcionais podem ser fornecidos (mas se eles contiverem vírgulas, eles irão confundir o analisador de assinatura). Anotações de argumento no estilo Python 3 também podem ser fornecidas, bem como anotações de tipo de retorno:

.. py:function:: compile(source : string, filename, symbol='file') -> ast object

Para funções com parâmetros opcionais que não têm valores padrão (normalmente funções implementadas em módulos de extensão C sem suporte de argumento nomeado), você pode usar colchetes para especificar as partes opcionais:

compile(source[, filename[, symbol]])

É comum colocar o colchete de abertura antes da vírgula.

Lista Informação Campos

Novo na versão 0.4.

Alterado na versão 3.0: meta fields are added.

Dentro das diretivas de descrição de objeto Python, as listas de campos reST com esses campos são reconhecidas e formatadas de maneira adequada:

  • param, parameter, arg, argument, key, keyword: Descrição de um parâmetro.

  • type: Tipo de parâmetro. Cria um link, se possível.

  • raises, raise, except, exception: Que (e quando) uma exceção específica é levantada.

  • var, ivar, cvar: Descrição de uma variável.

  • vartype: Tipo de uma variável. Cria um link, se possível.

  • returns, return: Descrição do valor de retorno.

  • rtype: Tipo de retorno. Cria um link, se possível.

  • meta: Add metadata to description of the python object. The metadata will not be shown on output document. For example, :meta private: indicates the python object is private member. It is used in sphinx.ext.autodoc for filtering members.

Nota

In current release, all var, ivar and cvar are represented as “Variable”. There is no difference at all.

Os nomes dos campos devem consistir em uma dessas palavras-chave e um argumento (exceto para returns e rtype, que não precisam de um argumento). Isso é melhor explicado por um exemplo:

.. py:function:: send_message(sender, recipient, message_body, [priority=1])

   Send a message to a recipient

   :param str sender: The person sending the message
   :param str recipient: The recipient of the message
   :param str message_body: The body of the message
   :param priority: The priority of the message, can be a number 1-5
   :type priority: integer or None
   :return: the message id
   :rtype: int
   :raises ValueError: if the message_body exceeds 160 characters
   :raises TypeError: if the message_body is not a basestring

Isso será renderizado como:

send_message(sender, recipient, message_body[, priority=1])

Envia uma mensagem para um destinatário

Parâmetros:
  • sender (str) – A pessoa enviando a mensagem

  • recipient (str) – O destinatário da mensagem

  • message_body (str) – O corpo da mensagem

  • priority (integer or None) – A prioridade da mensagem, pode ser um número de 1-5

Retorna:

id da mensagem

Tipo de retorno:

int

Levanta:
  • ValueError – se message_body exceder 160 caracteres

  • TypeError – se message_body não for uma basestring

Também é possível combinar o tipo e descrição do parâmetro, se o tipo for uma única palavra, como isso:

:param int priority: The priority of the message, can be a number 1-5

Novo na versão 1.5.

Tipos de contêineres tal como listas e dicionários podem ser vinculados automaticamente usando a seguinte sintaxe:

:type priorities: list(int)
:type priorities: list[int]
:type mapping: dict(str, int)
:type mapping: dict[str, int]
:type point: tuple(float, float)
:type point: tuple[float, float]

Vários tipos em um campo de tipo será vinculado automaticamente se separados pela palavra “or”:

:type an_arg: int or None
:vartype a_var: str or int
:rtype: float or str

Referência cruzada de objetos Python

Os seguintes papéis fazem referência a objetos em módulos e são possivelmente alvos de hiperlink se um identificador correspondente for encontrado:

:py:mod:

Referência a um módulo; um nome pontilhado pode ser usado. Isso também deve ser usado para nomes de pacotes.

:py:func:

Referência a uma função Python; nomes pontilhados podem ser usados. O texto do papel não precisa incluir parênteses ao final para melhorar a legibilidade; eles serão adicionados automaticamente pelo Sphinx se o valor da configuração add_function_parentheses for True (o padrão).

:py:data:

Referência a uma variável a nível de módulo.

:py:const:

Referência a uma constante “definida”. Isso pode ser uma variável Python que não é destinada a ser alterada.

:py:class:

Referência a uma classe; um nome pontilhado pode ser usado.

:py:meth:

Referencia um método de um objeto. O texto do papel pode incluir o nome do tipo e o nome do método; se ocorrer dentro da descrição de um tipo, o nome do tipo pode ser omitido. Um nome pontilhado pode ser usado.

:py:attr:

Referencia um atributo de dados de um objeto.

Nota

The role is also able to refer to property.

:py:exc:

Referencia uma exceção. Um nome pontilhado pode ser usado.

:py:obj:

Referencia um objeto de tipo não especificado. Útil, por exemplo, como default_role.

Novo na versão 0.4.

O nome incluído nesta marcação pode incluir um nome de módulo e/ou um nome de classe. Por exemplo, :py:func:`filter` pode fazer referência a uma função chamada filter no módulo atual, ou a função embutida com esse nome. Em contraste, :py:func:`foo.filter` claramente se refere à função filter no módulo foo.

Normalmente, os nomes nessas funções são pesquisados primeiro sem qualquer qualificação adicional, depois com o nome do módulo atual prefixado e, em seguida, com o módulo atual e o nome da classe (se houver) prefixados. Se você prefixar o nome com um ponto, a ordem será invertida. Por exemplo, na documentação do módulo codecs do Python, :py:func:`open` sempre se refere à função embutida, enquanto :py:func:`.open` refere-se a codecs.open().

Uma heurística semelhante é usada para determinar se o nome é um atributo da classe documentada atualmente.

Also, if the name is prefixed with a dot, and no exact match is found, the target is taken as a suffix and all object names with that suffix are searched. For example, :py:meth:`.TarFile.close` references the tarfile.TarFile.close() function, even if the current module is not tarfile. Since this can get ambiguous, if there is more than one possible match, you will get a warning from Sphinx.

Note que você pode combinar os prefixos ~ e .: :py:meth:`~.TarFile.close` fará referência ao método tarfile.TarFile.close() , mas a legenda do link visível será apenas close().

O domínio C

O domínio C (nome c) é adequado para documentação de API C.

.. c:member:: declaration
.. c:var:: declaration

Describes a C struct member or variable. Example signature:

.. c:member:: PyObject *PyTypeObject.tp_bases

The difference between the two directives is only cosmetic.

.. c:function:: function prototype

Descreve uma função C. A assinatura deve ser dada como em C, por exemplo:

.. c:function:: PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)

Observe que você não precisa fazer a barra invertida para escapar asteriscos na assinatura, pois ela não é analisada pelo reST embutido.

In the description of a function you can use the following info fields (see also Lista Informação Campos).

  • param, parameter, arg, argument, Description of a parameter.

  • type: Type of a parameter, written as if passed to the c:expr role.

  • returns, return: Descrição do valor de retorno.

  • rtype: Return type, written as if passed to the c:expr role.

  • retval, retvals: An alternative to returns for describing the result of the function.

Novo na versão 4.3: The retval field type.

Por exemplo:

.. c:function:: PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)

   :param type: description of the first parameter.
   :param nitems: description of the second parameter.
   :returns: a result.
   :retval NULL: under some conditions.
   :retval NULL: under some other conditions as well.

which renders as

PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Parâmetros:
  • type – description of the first parameter.

  • nitems – description of the second parameter.

Retorna:

a result.

Valores de retorno:
  • NULL – under some conditions.

  • NULL – under some other conditions as well.

.. c:macro:: name
.. c:macro:: name(arg list)

Describes a C macro, i.e., a C-language #define, without the replacement text.

In the description of a macro you can use the same info fields as for the c:function directive.

Novo na versão 3.0: The function style variant.

.. c:struct:: name

Describes a C struct.

Novo na versão 3.0.

.. c:union:: name

Describes a C union.

Novo na versão 3.0.

.. c:enum:: name

Describes a C enum.

Novo na versão 3.0.

.. c:enumerator:: name

Describes a C enumerator.

Novo na versão 3.0.

.. c:type:: typedef-like declaration
.. c:type:: name

Describes a C type, either as a typedef, or the alias for an unspecified type.

Referência cruzadas a construções C

As funções a seguir criam referências cruzadas para construções da linguagem C se forem definidas na documentação:

:c:member:
:c:data:
:c:var:
:c:func:
:c:macro:
:c:struct:
:c:union:
:c:enum:
:c:enumerator:
:c:type:

Reference a C declaration, as defined above. Note that c:member, c:data, and c:var are equivalent.

Novo na versão 3.0: The var, struct, union, enum, and enumerator roles.

Anonymous Entities

C supports anonymous structs, enums, and unions. For the sake of documentation they must be given some name that starts with @, e.g., @42 or @data. These names can also be used in cross-references, though nested symbols will be found even when omitted. The @... name will always be rendered as [anonymous] (possibly as a link).

Exemplo:

.. c:struct:: Data

   .. c:union:: @data

      .. c:var:: int a

      .. c:var:: double b

Explicit ref: :c:var:`Data.@data.a`. Short-hand ref: :c:var:`Data.a`.

This will be rendered as:

struct Data
union [anonymous]
int a
double b

Explicit ref: Data.[anonymous].a. Short-hand ref: Data.a.

Novo na versão 3.0.

Aliasing Declarations

Sometimes it may be helpful list declarations elsewhere than their main documentation, e.g., when creating a synopsis of an interface. The following directive can be used for this purpose.

.. c:alias:: name

Insert one or more alias declarations. Each entity can be specified as they can in the c:any role.

Por exemplo:

.. c:var:: int data
.. c:function:: int f(double k)

.. c:alias:: data
             f

becomes

int data
int f(double k)
int data
int f(double k)

Novo na versão 3.2.

Opções

:maxdepth: int

Insert nested declarations as well, up to the total depth given. Use 0 for infinite depth and 1 for just the mentioned declaration. Defaults to 1.

Novo na versão 3.3.

:noroot:

Skip the mentioned declarations and only render nested declarations. Requires maxdepth either 0 or at least 2.

Novo na versão 3.5.

Inline Expressions and Types

:c:expr:
:c:texpr:

Insert a C expression or type either as inline code (cpp:expr) or inline text (cpp:texpr). For example:

.. c:var:: int a = 42

.. c:function:: int f(int i)

An expression: :c:expr:`a * f(a)` (or as text: :c:texpr:`a * f(a)`).

A type: :c:expr:`const Data*`
(or as text :c:texpr:`const Data*`).

will be rendered as follows:

int a = 42
int f(int i)

An expression: a * f(a) (or as text: a * f(a)).

A type: const Data* (or as text const Data*).

Novo na versão 3.0.

Namespacing

Novo na versão 3.1.

The C language it self does not support namespacing, but it can sometimes be useful to emulate it in documentation, e.g., to show alternate declarations. The feature may also be used to document members of structs/unions/enums separate from their parent declaration.

The current scope can be changed using three namespace directives. They manage a stack declarations where c:namespace resets the stack and changes a given scope.

The c:namespace-push directive changes the scope to a given inner scope of the current one.

The c:namespace-pop directive undoes the most recent c:namespace-push directive.

.. c:namespace:: scope specification

Changes the current scope for the subsequent objects to the given scope, and resets the namespace directive stack. Note that nested scopes can be specified by separating with a dot, e.g.:

.. c:namespace:: Namespace1.Namespace2.SomeStruct.AnInnerStruct

All subsequent objects will be defined as if their name were declared with the scope prepended. The subsequent cross-references will be searched for starting in the current scope.

Using NULL or 0 as the scope will change to global scope.

.. c:namespace-push:: scope specification

Change the scope relatively to the current scope. For example, after:

.. c:namespace:: A.B

.. c:namespace-push:: C.D

the current scope will be A.B.C.D.

.. c:namespace-pop::

Undo the previous c:namespace-push directive (not just pop a scope). For example, after:

.. c:namespace:: A.B

.. c:namespace-push:: C.D

.. c:namespace-pop::

the current scope will be A.B (not A.B.C).

If no previous c:namespace-push directive has been used, but only a c:namespace directive, then the current scope will be reset to global scope. That is, .. c:namespace:: A.B is equivalent to:

.. c:namespace:: NULL

.. c:namespace-push:: A.B

Configuration Variables

See Opções para o domínio C.

O domínio C++

O domínio C++ (nome cpp) oferece suporte a documentar projetos C++.

Directives for Declaring Entities

As seguintes diretivas estão disponíveis. Todas as declarações podem começar com uma declaração de visibilidade (public, private ou protected).

.. cpp:class:: class specifier
.. cpp:struct:: class specifier

Descreva uma classe/struct, possivelmente com especificação de herança, por exemplo:

.. cpp:class:: MyClass : public MyBase, MyOtherBase

The difference between cpp:class and cpp:struct is only cosmetic: the prefix rendered in the output, and the specifier shown in the index.

A classe pode ser declarada diretamente dentro de um escopo aninhado, por exemplo:

.. cpp:class:: OuterScope::MyClass : public MyBase, MyOtherBase

Um modelo de classe pode ser declarado:

.. cpp:class:: template<typename T, std::size_t N> std::array

ou com uma quebra de linha:

.. cpp:class:: template<typename T, std::size_t N> \
               std::array

As especializações de modelo completas e parciais podem ser declaradas:

.. cpp:class:: template<> \
               std::array<bool, 256>

.. cpp:class:: template<typename T> \
               std::array<T, 42>

Novo na versão 2.0: The cpp:struct directive.

.. cpp:function:: (member) function prototype

Descreve uma função ou função-membro, por exemplo:

.. cpp:function:: bool myMethod(int arg1, std::string arg2)

   A function with parameters and types.

.. cpp:function:: bool myMethod(int, double)

   A function with unnamed parameters.

.. cpp:function:: const T &MyClass::operator[](std::size_t i) const

   An overload for the indexing operator.

.. cpp:function:: operator bool() const

   A casting operator.

.. cpp:function:: constexpr void foo(std::string &bar[2]) noexcept

   A constexpr function.

.. cpp:function:: MyClass::MyClass(const MyClass&) = default

   A copy constructor with default implementation.

Os modelos de função também podem ser descritos:

.. cpp:function:: template<typename U> \
                  void print(U &&u)

e especializações de modelo de função:

.. cpp:function:: template<> \
                  void print(int i)
.. cpp:member:: (member) variable declaration
.. cpp:var:: (member) variable declaration

Descreve uma variável ou variável de membro, por exemplo:

.. cpp:member:: std::string MyClass::myMember

.. cpp:var:: std::string MyClass::myOtherMember[N][M]

.. cpp:member:: int a = 42

Os modelos de variáveis também podem ser descritos:

.. cpp:member:: template<class T> \
                constexpr T pi = T(3.1415926535897932385)
.. cpp:type:: typedef declaration
.. cpp:type:: name
.. cpp:type:: type alias declaration

Descreve um tipo como em uma declaração de typedef, uma declaração de alias de tipo ou simplesmente o nome de um tipo com tipo não especificado, por exemplo:

.. cpp:type:: std::vector<int> MyList

   A typedef-like declaration of a type.

.. cpp:type:: MyContainer::const_iterator

   Declaration of a type alias with unspecified type.

.. cpp:type:: MyType = std::unordered_map<int, std::string>

   Declaration of a type alias.

Um alias de tipo também pode ser modelado:

.. cpp:type:: template<typename T> \
              MyContainer = std::vector<T>

Os exemplos são renderizados como demonstrado a seguir.

typedef std::vector<int> MyList

Uma declaração semelhante a typedef de um tipo.

type MyContainer::const_iterator

Declaração de um alias de tipo com tipo não especificado.

using MyType = std::unordered_map<int, std::string>

Declaração de um alias de tipo.

template<typename T>
using MyContainer = std::vector<T>
.. cpp:enum:: unscoped enum declaration
.. cpp:enum-struct:: scoped enum declaration
.. cpp:enum-class:: scoped enum declaration

Describe a (scoped) enum, possibly with the underlying type specified. Any enumerators declared inside an unscoped enum will be declared both in the enum scope and in the parent scope. Examples:

.. cpp:enum:: MyEnum

   An unscoped enum.

.. cpp:enum:: MySpecificEnum : long

   An unscoped enum with specified underlying type.

.. cpp:enum-class:: MyScopedEnum

   A scoped enum.

.. cpp:enum-struct:: protected MyScopedVisibilityEnum : std::underlying_type<MySpecificEnum>::type

   A scoped enum with non-default visibility, and with a specified
   underlying type.
.. cpp:enumerator:: name
.. cpp:enumerator:: name = constant

Descreve um enumerador, opcionalmente com seu valor definido, por exemplo:

.. cpp:enumerator:: MyEnum::myEnumerator

.. cpp:enumerator:: MyEnum::myOtherEnumerator = 42
.. cpp:union:: name

Describe a union.

Novo na versão 1.8.

.. cpp:concept:: template-parameter-list name

Aviso

O suporte para conceitos é experimental. Baseia-se no projeto de padrão atual e na Especificação Técnica dos Conceitos. Os recursos podem mudar à medida que evoluem.

Descreve um conceito. Deve ter exatamente 1 lista de parâmetros de modelo. O nome pode ser um nome aninhado. Exemplo:

.. cpp:concept:: template<typename It> std::Iterator

   Proxy to an element of a notional sequence that can be compared,
   indirected, or incremented.

   **Notation**

   .. cpp:var:: It r

      An lvalue.

   **Valid Expressions**

   - :cpp:expr:`*r`, when :cpp:expr:`r` is dereferenceable.
   - :cpp:expr:`++r`, with return type :cpp:expr:`It&`, when
     :cpp:expr:`r` is incrementable.

Isso será renderizado da seguinte forma:

template<typename It>
concept std::Iterator

Proxy para um elemento de uma sequência nocional que pode ser comparada, indiretamente ou incrementada.

Notation

It r

An lvalue.

Valid Expressions

  • *r, when r is dereferenceable.

  • ++r, with return type It&, when r is incrementable.

Novo na versão 1.5.

Opções

Algumas diretivas oferecem suporte às opções:

  • :noindexentry: and :nocontentsentry:, see Marcação Básica.

  • :tparam-line-spec:, for templated declarations. If specified, each template parameter will be rendered on a separate line.

    Novo na versão 1.6.

Anonymous Entities

C++ supports anonymous namespaces, classes, enums, and unions. For the sake of documentation they must be given some name that starts with @, e.g., @42 or @data. These names can also be used in cross-references and (type) expressions, though nested symbols will be found even when omitted. The @... name will always be rendered as [anonymous] (possibly as a link).

Exemplo:

.. cpp:class:: Data

   .. cpp:union:: @data

      .. cpp:var:: int a

      .. cpp:var:: double b

Explicit ref: :cpp:var:`Data::@data::a`. Short-hand ref: :cpp:var:`Data::a`.

This will be rendered as:

class Data
union [anonymous]
int a
double b

Explicit ref: Data::[anonymous]::a. Short-hand ref: Data::a.

Novo na versão 1.8.

Aliasing Declarations

Sometimes it may be helpful list declarations elsewhere than their main documentation, e.g., when creating a synopsis of a class interface. The following directive can be used for this purpose.

.. cpp:alias:: name or function signature

Insert one or more alias declarations. Each entity can be specified as they can in the cpp:any role. If the name of a function is given (as opposed to the complete signature), then all overloads of the function will be listed.

Por exemplo:

.. cpp:alias:: Data::a
               overload_example::C::f

becomes

int a
void f(double d) const
void f(double d)
void f(int i)
void f()

whereas:

.. cpp:alias:: void overload_example::C::f(double d) const
               void overload_example::C::f(double d)

becomes

void f(double d) const
void f(double d)

Novo na versão 2.0.

Opções

:maxdepth: int

Insert nested declarations as well, up to the total depth given. Use 0 for infinite depth and 1 for just the mentioned declaration. Defaults to 1.

Novo na versão 3.5.

:noroot:

Skip the mentioned declarations and only render nested declarations. Requires maxdepth either 0 or at least 2.

Novo na versão 3.5.

Constrained Templates

Aviso

O suporte para conceitos é experimental. Baseia-se no projeto de padrão atual e na Especificação Técnica dos Conceitos. Os recursos podem mudar à medida que evoluem.

Nota

Sphinx does not currently support requires clauses.

Placeholders

Declarations may use the name of a concept to introduce constrained template parameters, or the keyword auto to introduce unconstrained template parameters:

.. cpp:function:: void f(auto &&arg)

   A function template with a single unconstrained template parameter.

.. cpp:function:: void f(std::Iterator it)

   A function template with a single template parameter, constrained by the
   Iterator concept.

Template Introductions

Simple constrained function or class templates can be declared with a template introduction instead of a template parameter list:

.. cpp:function:: std::Iterator{It} void advance(It &it)

    A function template with a template parameter constrained to be an
    Iterator.

.. cpp:class:: std::LessThanComparable{T} MySortedContainer

    A class template with a template parameter constrained to be
    LessThanComparable.

They are rendered as follows.

std::Iterator{It}
void advance(It &it)

A function template with a template parameter constrained to be an Iterator.

std::LessThanComparable{T}
class MySortedContainer

A class template with a template parameter constrained to be LessThanComparable.

Note however that no checking is performed with respect to parameter compatibility. E.g., Iterator{A, B, C} will be accepted as an introduction even though it would not be valid C++.

Inline Expressions and Types

:cpp:expr:
:cpp:texpr:

Insert a C++ expression or type either as inline code (cpp:expr) or inline text (cpp:texpr). For example:

.. cpp:var:: int a = 42

.. cpp:function:: int f(int i)

An expression: :cpp:expr:`a * f(a)` (or as text: :cpp:texpr:`a * f(a)`).

A type: :cpp:expr:`const MySortedContainer<int>&`
(or as text :cpp:texpr:`const MySortedContainer<int>&`).

will be rendered as follows:

int a = 42
int f(int i)

An expression: a * f(a) (or as text: a * f(a)).

A type: const MySortedContainer<int>& (or as text const MySortedContainer<int>&).

Novo na versão 1.7: The cpp:expr role.

Novo na versão 1.8: The cpp:texpr role.

Namespacing

Declarations in the C++ domain are as default placed in global scope. The current scope can be changed using three namespace directives. They manage a stack declarations where cpp:namespace resets the stack and changes a given scope.

The cpp:namespace-push directive changes the scope to a given inner scope of the current one.

The cpp:namespace-pop directive undoes the most recent cpp:namespace-push directive.

.. cpp:namespace:: scope specification

Changes the current scope for the subsequent objects to the given scope, and resets the namespace directive stack. Note that the namespace does not need to correspond to C++ namespaces, but can end in names of classes, e.g.,:

.. cpp:namespace:: Namespace1::Namespace2::SomeClass::AnInnerClass

All subsequent objects will be defined as if their name were declared with the scope prepended. The subsequent cross-references will be searched for starting in the current scope.

Using NULL, 0, or nullptr as the scope will change to global scope.

A namespace declaration can also be templated, e.g.,:

.. cpp:class:: template<typename T> \
               std::vector

.. cpp:namespace:: template<typename T> std::vector

.. cpp:function:: std::size_t size() const

declares size as a member function of the class template std::vector. Equivalently this could have been declared using:

.. cpp:class:: template<typename T> \
               std::vector

   .. cpp:function:: std::size_t size() const

or:

.. cpp:class:: template<typename T> \
               std::vector
.. cpp:namespace-push:: scope specification

Change the scope relatively to the current scope. For example, after:

.. cpp:namespace:: A::B

.. cpp:namespace-push:: C::D

the current scope will be A::B::C::D.

Novo na versão 1.4.

.. cpp:namespace-pop::

Undo the previous cpp:namespace-push directive (not just pop a scope). For example, after:

.. cpp:namespace:: A::B

.. cpp:namespace-push:: C::D

.. cpp:namespace-pop::

the current scope will be A::B (not A::B::C).

If no previous cpp:namespace-push directive has been used, but only a cpp:namespace directive, then the current scope will be reset to global scope. That is, .. cpp:namespace:: A::B is equivalent to:

.. cpp:namespace:: nullptr

.. cpp:namespace-push:: A::B

Novo na versão 1.4.

Lista Informação Campos

All the C++ directives for declaring entities support the following info fields (see also Lista Informação Campos):

  • tparam: Description of a template parameter.

The cpp:function directive additionally supports the following fields:

  • param, parameter, arg, argument: Description of a parameter.

  • returns, return: Description of a return value.

  • retval, retvals: An alternative to returns for describing the result of the function.

  • throws, throw, exception: Description of a possibly thrown exception.

Novo na versão 4.3: The retval field type.

Cross-referencing

These roles link to the given declaration types:

:cpp:any:
:cpp:class:
:cpp:struct:
:cpp:func:
:cpp:member:
:cpp:var:
:cpp:type:
:cpp:concept:
:cpp:enum:
:cpp:enumerator:

Reference a C++ declaration by name (see below for details). The name must be properly qualified relative to the position of the link.

Novo na versão 2.0: The cpp:struct role as alias for the cpp:class role.

Note on References with Templates Parameters/Arguments

These roles follow the Sphinx Sintaxe de referência cruzada rules. This means care must be taken when referencing a (partial) template specialization, e.g. if the link looks like this: :cpp:class:`MyClass<int>`. This is interpreted as a link to int with a title of MyClass. In this case, escape the opening angle bracket with a backslash, like this: :cpp:class:`MyClass\<int>`.

When a custom title is not needed it may be useful to use the roles for inline expressions, cpp:expr and cpp:texpr, where angle brackets do not need escaping.

Declarations without template parameters and template arguments

For linking to non-templated declarations the name must be a nested name, e.g., f or MyClass::f.

Overloaded (member) functions

When a (member) function is referenced using just its name, the reference will point to an arbitrary matching overload. The cpp:any and cpp:func roles use an alternative format, which simply is a complete function declaration. This will resolve to the exact matching overload. As example, consider the following class declaration:

class C
void f(double d) const
void f(double d)
void f(int i)
void f()

References using the cpp:func role:

Note that the add_function_parentheses configuration variable does not influence specific overload references.

Templated declarations

Assume the following declarations.

class Wrapper
template<typename TOuter>
class Outer
template<typename TInner>
class Inner

In general the reference must include the template parameter declarations, and template arguments for the prefix of qualified names. For example:

  • template\<typename TOuter> Wrapper::Outer (template<typename TOuter> Wrapper::Outer)

  • template\<typename TOuter> template\<typename TInner> Wrapper::Outer<TOuter>::Inner (template<typename TOuter> template<typename TInner> Wrapper::Outer<TOuter>::Inner)

Currently the lookup only succeed if the template parameter identifiers are equal strings. That is, template\<typename UOuter> Wrapper::Outer will not work.

As a shorthand notation, if a template parameter list is omitted, then the lookup will assume either a primary template or a non-template, but not a partial template specialisation. This means the following references work as well:

(Full) Template Specialisations

Assume the following declarations.

template<typename TOuter>
class Outer
template<typename TInner>
class Inner
template<>
class Outer<int>
template<typename TInner>
class Inner
template<>
class Inner<bool>

In general the reference must include a template parameter list for each template argument list. The full specialisation above can therefore be referenced with template\<> Outer\<int> (template<> Outer<int>) and template\<> template\<> Outer\<int>::Inner\<bool> (template<> template<> Outer<int>::Inner<bool>). As a shorthand the empty template parameter list can be omitted, e.g., Outer\<int> (Outer<int>) and Outer\<int>::Inner\<bool> (Outer<int>::Inner<bool>).

Partial Template Specialisations

Assume the following declaration.

template<typename T>
class Outer<T*>

References to partial specialisations must always include the template parameter lists, e.g., template\<typename T> Outer\<T*> (template<typename T> Outer<T*>). Currently the lookup only succeed if the template parameter identifiers are equal strings.

Configuration Variables

See Opções para domínio C++.

The Standard Domain

The so-called “standard” domain collects all markup that doesn’t warrant a domain of its own. Its directives and roles are not prefixed with a domain name.

The standard domain is also where custom object descriptions, added using the add_object_type() API, are placed.

There is a set of directives allowing documenting command-line programs:

.. option:: name args, name args, ...

Describes a command line argument or switch. Option argument names should be enclosed in angle brackets. Examples:

.. option:: dest_dir

   Destination directory.

.. option:: -m <module>, --module <module>

   Run a module as a script.

The directive will create cross-reference targets for the given options, referenceable by option (in the example case, you’d use something like :option:`dest_dir`, :option:`-m`, or :option:`--module`).

Alterado na versão 5.3: One can cross-reference including an option value: :option:`--module=foobar`, ,``:option:–module[=foobar]`` or :option:`--module foobar`.

Use option_emphasise_placeholders for parsing of “variable part” of a literal text (similarly to the samp role).

cmdoption directive is a deprecated alias for the option directive.

.. envvar:: name

Describes an environment variable that the documented code or program uses or defines. Referenceable by envvar.

.. program:: name

Like py:currentmodule, this directive produces no output. Instead, it serves to notify Sphinx that all following option directives document options for the program called name.

If you use program, you have to qualify the references in your option roles by the program name, so if you have the following situation

.. program:: rm

.. option:: -r

   Work recursively.

.. program:: svn

.. option:: -r <revision>

   Specify the revision to work upon.

then :option:`rm -r` would refer to the first option, while :option:`svn -r` would refer to the second one.

If None is passed to the argument, the directive will reset the current program name.

The program name may contain spaces (in case you want to document subcommands like svn add and svn commit separately).

Novo na versão 0.5.

There is also a very generic object description directive, which is not tied to any domain:

.. describe:: text
.. object:: text

This directive produces the same formatting as the specific ones provided by domains, but does not create index entries or cross-referencing targets. Example:

.. describe:: PAPER

   You can set this variable to select a paper size.

The JavaScript Domain

The JavaScript domain (name js) provides the following directives:

.. js:module:: name

This directive sets the module name for object declarations that follow after. The module name is used in the global module index and in cross references. This directive does not create an object heading like py:class would, for example.

By default, this directive will create a linkable entity and will cause an entry in the global module index, unless the noindex option is specified. If this option is specified, the directive will only update the current module name.

Novo na versão 1.6.

Alterado na versão 5.2: Module directives support body content.

.. js:function:: name(signature)

Describes a JavaScript function or method. If you want to describe arguments as optional use square brackets as documented for Python signatures.

You can use fields to give more details about arguments and their expected types, errors which may be thrown by the function, and the value being returned:

.. js:function:: $.getJSON(href, callback[, errback])

   :param string href: An URI to the location of the resource.
   :param callback: Gets called with the object.
   :param errback:
       Gets called in case the request fails. And a lot of other
       text so we need multiple lines.
   :throws SomeError: For whatever reason in that case.
   :returns: Something.

This is rendered as:

$.getJSON(href, callback[, errback])
Argumentos:
  • href (string()) – An URI to the location of the resource.

  • callback – Gets called with the object.

  • errback – Gets called in case the request fails. And a lot of other text so we need multiple lines.

Lança:

SomeError() – For whatever reason in that case.

Retorna:

Something.

.. js:method:: name(signature)

This directive is an alias for js:function, however it describes a function that is implemented as a method on a class object.

Novo na versão 1.6.

.. js:class:: name

Describes a constructor that creates an object. This is basically like a function but will show up with a class prefix:

.. js:class:: MyAnimal(name[, age])

   :param string name: The name of the animal
   :param number age: an optional age for the animal

This is rendered as:

class MyAnimal(name[, age])
Argumentos:
  • name (string()) – The name of the animal

  • age (number()) – an optional age for the animal

.. js:data:: name

Describes a global variable or constant.

.. js:attribute:: object.name

Describes the attribute name of object.

These roles are provided to refer to the described objects:

:js:mod:
:js:func:
:js:meth:
:js:class:
:js:data:
:js:attr:

The reStructuredText domain

The reStructuredText domain (name rst) provides the following directives:

.. rst:directive:: name

Describes a reST directive. The name can be a single directive name or actual directive syntax (.. prefix and :: suffix) with arguments that will be rendered differently. For example:

.. rst:directive:: foo

   Foo description.

.. rst:directive:: .. bar:: baz

   Bar description.

will be rendered as:

.. foo::

Foo description.

.. bar:: baz

Bar description.

.. rst:directive:option:: name

Describes an option for reST directive. The name can be a single option name or option name with arguments which separated with colon (:). For example:

.. rst:directive:: toctree

   .. rst:directive:option:: caption: caption of ToC

   .. rst:directive:option:: glob

will be rendered as:

.. toctree::
:caption: caption of ToC
:glob:

options

:type: description of argument (text)

Describe the type of option value.

Por exemplo:

.. rst:directive:: toctree

   .. rst:directive:option:: maxdepth
      :type: integer or no value

Novo na versão 2.1.

.. rst:role:: name

Describes a reST role. For example:

.. rst:role:: foo

   Foo description.

will be rendered as:

:foo:

Foo description.

These roles are provided to refer to the described objects:

:rst:dir:
:rst:role:

The Math Domain

The math domain (name math) provides the following roles:

:math:numref:

Role for cross-referencing equations defined by math directive via their label. Example:

.. math:: e^{i\pi} + 1 = 0
   :label: euler

Euler's identity, equation :math:numref:`euler`, was elected one of the
most beautiful mathematical formulas.

Novo na versão 1.8.

More domains

The sphinx-contrib repository contains more domains available as extensions; currently Ada, CoffeeScript, Erlang, HTTP, Lasso, MATLAB, PHP, and Ruby domains. Also available are domains for Chapel, Common Lisp, dqn, Go, Jinja, Operation, and Scala.