reStructuredText (сокращение: ReST, расширение файла: .rst) — облегчённый язык разметки, который может быть преобразован в различные форматы — HTML, ePub, PDF и другие.
Документы с разметкой ReST являются обычными текстовыми файлами. С такими файлами очень легко работать посредством системы управления Git, которая позволяет отслеживать все вносимые изменения, легко принимать или отклонять их.
Помимо этого, документы в формате .rst можно открывать и редактировать в любом простом текстовом редакторе (например, в Блокноте). Это позволяет работать над документацией в любых условиях, на любых платформах, без необходимости использовать специализированное программное обеспечение.
Самое главное, что ReST позволяет сосредоточиться исключительно на структуре документа и не отвлекаться на его оформление.
ReST аналогичен языку разметки Markdown, но обладает более расширенным синтаксисом, особенно вкупе с генератором документации Sphinx. ReST используется во многих проектах, например, на сайте GitHub. Также его используют многие генераторы статических сайтов такие, как: Hyde, Pelican и другие.
Синтаксис reStructuredText опирается на следующие концепции:
ё
и символом ~
. Использование обычных одинарных кавычек в командах не приведет к желаемым результатам.[1] | Не важно как делается отступ — пробелами или клавишей Tab, главное, чтобы они были одинакового размера. |
Абзацы в ReST отделяются друг от друга пустой строкой:
Первый абзац...
Строки параграфов начинаются от левой границы
и отделяются параграфы друг от друга пустой строкой.
ReST поддерживает несколько уровней заголовков. Заголовки первого уровня (главы) подчеркиваются символом равно =
. Заголовки второго уровня (подглавы) подчеркиваются символом короткого тире или минуса -
. Заголовки третьего уровня (подпункта) подчеркиваются символом тильды ~
. Для параграфов допускается использовать подчеркивание символами двойных кавычек "
Заголовки подчеркиваются (или отбиваются сверху и снизу) с помощью небуквенных
и нецифровых 7-битных ASCII символов. Рекомендуется использовать: «= ` : ' " ~ ^ _ * + # < >
». Отбивка должна быть не короче текста заголовка.
Заголовок 1 уровня
==================
Заголовок 2 уровня
------------------
Заголовок 3 уровня
~~~~~~~~~~~~~~~~~~
Заголовок 4 уровня
""""""""""""""""""
Чтобы выделить текст жирным начертанием или курсивным используется обособление звездочками:
**жирный текст**
*курсив текст*
Результат:
жирный текст
курсив текст
Attention
Не допускается наличие пробелов между выделяемым словом и звездочкой, например, команда ** жирный текст**
не даст нужного эффекта.
Начертание текста «как есть»
достигается обособлением двумя обратными кавычками:
``«как есть»``
Нумерованные списки создаются с помощью символа решетки с точкой #.
:
#. Один
#. Два
#. Три
Или:
5. Пять
6. Шесть
#. Семь
Результат:
Или:
Маркированные списки создаются с помощью символа звездочки *
или дефиса -
. Пробелы после маркера обязательны:
* Один
* Два
* Три
Результат:
* Первый уровень
* Второй уровень
* Третий уровень
* Четвертый уровень
* Пятый уровень
Результат:
#. Один
* Маркер
#. Два
#. Номер
Результат:
Верхние и нижние индексы добавляются с помощью команд :sub:
и :sup:
.
H\ :sub:`2`\ O
E = mc\ :sup:`2`
Результат:
Другой способ с помощью автозамены:
Химическая формула воды — |H2O|.
.. |H2O| replace:: H\ :sub:`2`\ O
Химическая формула воды — H2O.
В ReST можно набрать два типа определений:
:Первый: В прямоугольном треугольнике квадрат длины
гипотенузы равен сумме квадратов длин катетов.
Второй
В прямоугольном треугольнике квадрат длины
гипотенузы равен сумме квадратов длин катетов.
Результат:
Первый: | В прямоугольном треугольнике квадрат длины гипотенузы равен сумме квадратов длин катетов. |
---|
Для вставки цитат используется отступ, сделанный с помощью клавиши Tab:
Основной текст:
Цитата неизвестного человека
--Аноним
Результат:
Цитата неизвестного человека
—Аноним
.. epigraph::
*«Если бы двери восприятия были чисты, всё
предстало бы человеку таким, как оно есть — бесконечным»*
-- Уильям Блэйк
Результат:
«Если бы двери восприятия были чисты, всё предстало бы человеку таким, как оно есть — бесконечным»
— Уильям Блэйк
Оформление эпиграфа зависит от настроек HTML-темы или используемого шаблона LaTeX.
В американской типографике, в отличие от европейской, не принято отбивать тире пробелами. Чтобы получить пробел между тире и автором я использовал функцию Автозамены (Подстановки). В моем случае код эпиграфа выглядит так:
.. epigraph::
*«Если бы двери восприятия были чисты, всё
предстало бы человеку таким, как оно есть — бесконечным»*
-- |nbsp| Уильям Блэйк
.. |nbsp| unicode:: U+00A0
Сноски могут быть разного вида:
Числовая сноска [5]_.
.. [5] Сюда ведет числовая сноска.
Сноски с автоматической [#]_ нумерацией [#]_.
.. [#] Это первая сноска.
.. [#] Это вторая сноска.
Автосимвол сносок используйте вот так [*]_ и [*]_.
.. [*] Это первый символ.
.. [*] Это второй символ.
Результаты:
Числовая сноска [5].
[5] | Сюда ведет числовая сноска. |
Сноски с автоматической [2] нумерацией [3].
[2] | Это первая сноска. |
[3] | Это вторая сноска. |
Автосимвол сносок используйте вот так [*] и [†].
[*] | Это первый символ. |
[†] | Это второй символ. |
Ссылки на цитаты выглядят так [CIT2002]_.
.. [CIT2002] Это цитата
(как часто используемая в журналах).
Ссылки на цитаты выглядят так [CIT2002].
[CIT2002] | Это цитата (как часто используемая в журналах). |
При экспорте в PDF сноски автоматически располагаются в конце страницы. Чтобы цитата располагалась в конце HTML-страницы, необходимо команду сноски располагать в конце .rst файла [CIT2003].
В ReST можно оставлять комментарии, которые отображаются только в исходном файле ReST. Комментарии создаются с помощью двух точек в начале предложения ..
. Для создания многострочных комментариев необходимо соблюдать отступ:
.. Это комментарий
Многострочный комментарий
Если обособление обратными кавычками используется для визуального выделения команд в абзацах, то для примеров частей исходного кода используется команда из двух двоеточий ::
:
Посмотрим на исходный код:
::
Пример исходного кода
Warning
Пустая строка между командой ::
и примером кода, а также отступ перед ним, обязательны.
Существуют другие способы ввода команды ::
, например:
Посмотрим на исходный код: ::
Пример исходного кода
Или так:
Посмотрим на исходный код::
Пример исходного кода
В данном случае команда ::
будет верно истолкована, а двоеточие в тексте
поставлено автоматически. Это более лаконичная форма записи.
Для вставки блоков исходного кода с подсветкой синтаксиса и нумерацией строк в Sphinx используются специальные команды, подробнее смотрите раздел
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello(request):
return Response('Hello world!')
if __name__ == '__main__':
config = Configurator()
config.add_route('hello_world', '/')
config.add_view(hello, route_name='hello_world')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
|
from .models import DBSession, Groups
from sacrud.action import CRUD
data = {'name': 'Electronics',
'parent_id': '10',}
group_obj = CRUD(DBSession, Groups).create(data)
print(group_obj.name)
from .models import DBSession, Groups
from sacrud.action import CRUD
data = {'name': 'Electronics',
'parent_id': '10',}
group_obj = CRUD(DBSession, Groups).create(data)
print(group_obj.name)
$ pyvenv myproject
$ cd myproject
$ bin/pip install pyramid
# open file test.data for reading
exec 6<test.data
# read until end of file
while read -u 6 dta
do
echo "$dta"
done
# close file test.data
exec 6<&-
hello.cpp
file.
1 2 3 4 5 6 7 8 | #include <iostream>
using namespace std;
int main ()
{
cout << "Hello world!!!\n";
return 0;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | var net = require('net');
var server = net.createServer(function (stream) {
stream.setEncoding('utf8');
stream.addListener('connect', function () {
stream.write('hello\r\n');
});
stream.addListener('data', function (data) {
stream.write(data);
});
stream.addListener('end', function () {
stream.write('goodbye\r\n');
stream.end();
});
});
server.listen(1337, 'localhost');
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
|
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock %}
{
"firstName": "Иван",
"lastName": "Иванов",
"address": {
"streetAddress": "Московское ш., 101, кв.101",
"city": "Ленинград",
"postalCode": 101101
},
"phoneNumbers": [
"812 123-1234",
"916 123-4567"
]
}
('200 OK', [('Content-Type', 'text/plain; charset=UTF-8'), ('Content-Length', '400')], ["HTTP_HOST: 'localhost:80'\nPATH_INFO: '/test'\nQUERY_STRING: ''\nREQUEST_METHOD: 'GET'\nSCRIPT_NAME: ''\nSERVER_NAME: 'localhost'\nSERVER_PORT: '80'\nSERVER_PROTOCOL: 'HTTP/1.0'\nwsgi.errors: <open file '<stderr>', mode 'w' at 0x7fe3aaca41e0>\nwsgi.input: <_io.BytesIO object at 0x7fe3a8af42f0>\nwsgi.multiprocess: False\nwsgi.multithread: False\nwsgi.run_once: False\nwsgi.url_scheme: 'http'\nwsgi.version: (1, 0)"])
200 OK
Content-Type: text/plain; charset=UTF-8
Content-Length: 400
HTTP_HOST: 'localhost:80'
PATH_INFO: '/test'
QUERY_STRING: ''
REQUEST_METHOD: 'GET'
SCRIPT_NAME: ''
SERVER_NAME: 'localhost'
SERVER_PORT: '80'
SERVER_PROTOCOL: 'HTTP/1.0'
wsgi.errors: <open file '<stderr>', mode 'w' at 0x7fe3aaca41e0>
wsgi.input: <_io.BytesIO object at 0x7fe3a8af42f0>
wsgi.multiprocess: False
wsgi.multithread: False
wsgi.run_once: False
wsgi.url_scheme: 'http'
wsgi.version: (1, 0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | ('200 OK', [('Content-Type', 'text/plain; charset=UTF-8'), ('Content-Length', '400')], ["HTTP_HOST: 'localhost:80'\nPATH_INFO: '/test'\nQUERY_STRING: ''\nREQUEST_METHOD: 'GET'\nSCRIPT_NAME: ''\nSERVER_NAME: 'localhost'\nSERVER_PORT: '80'\nSERVER_PROTOCOL: 'HTTP/1.0'\nwsgi.errors: <open file '<stderr>', mode 'w' at 0x7fe3aaca41e0>\nwsgi.input: <_io.BytesIO object at 0x7fe3a8af42f0>\nwsgi.multiprocess: False\nwsgi.multithread: False\nwsgi.run_once: False\nwsgi.url_scheme: 'http'\nwsgi.version: (1, 0)"])
200 OK
Content-Type: text/plain; charset=UTF-8
Content-Length: 400
HTTP_HOST: 'localhost:80'
PATH_INFO: '/test'
QUERY_STRING: ''
REQUEST_METHOD: 'GET'
SCRIPT_NAME: ''
SERVER_NAME: 'localhost'
SERVER_PORT: '80'
SERVER_PROTOCOL: 'HTTP/1.0'
wsgi.errors: <open file '<stderr>', mode 'w' at 0x7fe3aaca41e0>
wsgi.input: <_io.BytesIO object at 0x7fe3a8af42f0>
wsgi.multiprocess: False
wsgi.multithread: False
wsgi.run_once: False
wsgi.url_scheme: 'http'
wsgi.version: (1, 0)
|
Язык reStructuredText — очень гибкий язык разметки, который поддерживает функцию автозамены (подстановки).
Язык |ReST| — очень гибкий язык разметки (подстановки).
.. |ReST| replace:: *reStructuredText*
Для удобства я в начале каждого файла делаю список автозамен.
С функцией автозамены связана функция вставки символов unicode:
Copyright |copy| 2015, |LibreRussia (TM)| |---| все права защищены.
.. |copy| unicode:: 0xA9 .. знак копирайта
.. |LibreRussia (TM)| unicode:: LibreRussia U+2122 .. символ торговой марки
.. |---| unicode:: U+02014 .. длинное тире
Получится такой результат:
Copyright © 2015, LibreRussia™ — все права защищены.
.. |date| date:: %d.%m.%Y
.. |time| date:: %H:%M
Текущая дата |date| и время |time|
Результат: Текущая дата 05.10.2017 и время 08:38 (на момент генерации документа).
Sphinx добавляет дополнительные команды автозамены, которые не требуют объявления. Подробнее о них написано в следующей главе.
ReST позволяет вставлять текст из других файлов:
.. include:: имя_файла
Иногда возникает необходимость визуально отделить абзац, для этого можно воспользоваться чертой, достаточно поставить подряд несколько дефисов (не меньше 4-х), также можно воспользоваться нижним подчеркиванием:
--------
________
Warning
Символы черты должны быть отбиты пустыми строками до и после.
Warning
Черта не должна завершать документ. Черта, расположенная в самом конце документа может вызывать ошибки при сборке.
Внешние ссылки создаются так:
1. Внешние ссылки выглядят так: ссылка_.
.. _ссылка: http://librerussia.blogspot.ru/
2. Если несколько слов, тогда так: `ссылка в несколько слов`_.
.. _`ссылка в несколько слов`: http://librerussia.blogspot.ru/
3. `Более компактная запись ссылок <http://librerussia.blogspot.ru/>`_
Результат:
Внутренние ссылки делаются так:
Внутренние ссылки делаются так_
.. _так:
Ссылками также являются и заголовки разделов, например, Таблицы :
Ссылка на раздел создается так `Таблицы`_ .
Достаточно в обратных кавычках написать название заголовка.
Вставка изображения между слов осуществляться с помощью функции автозамены:
Вставка изображения между слов |кубик-рубика| осуществляться с помощью функции автозамены:
.. |кубик-рубика| image:: _static/favicon.ico
Вставка изображений между абзацами:
.. figure:: _static/favicon.png
:scale: 300 %
:align: center
:alt: Альтернативный текст
Подпись изображения
Легенда изображения.
Параметр :scale:
устанавливает масштаб изображений.
Параметр :align:
устанавливает обтекание текстом, может принимать опции left
, center
или right
.
Ещё один способ:
.. image:: picture.jpeg
:height: 100px
:width: 200px
:scale: 50%
:alt: alternate text
:align: right
ps_tree is extension for pyramid_sacrud which displays a list of records as tree. This works fine with models from sqlalchemy_mptt.
Look how easy it is to use:
from pyramid_pages.models import BaseSacrudMpttPage
Base = declarative_base()
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
class PageTree(Base, BaseSacrudMpttPage):
__tablename__ = 'pages'
id = Column(Integer, primary_key=True)
config.include('ps_tree')
config.registry.settings['ps_tree.models'] = (PageTree, )
config.include('pyramid_sacrud', route_prefix='admin')
config.registry.settings['pyramid_sacrud.models'] = ('', PageTree)
Создавать таблицы можно несколькими способами:
.. table:: Заголовок таблицы (Внимание! Отступ таблицы относительно
команды ..``table::`` обязателен)
+------------------------+------------+----------+----------+
| Header row, column 1 | Header 2 | Header 3 | Header 4 |
| (header rows optional) | | | |
+========================+============+==========+==========+
| body row 1, column 1 | column 2 | column 3 | column 4 |
+------------------------+------------+----------+----------+
| body row 2 | Cells may span columns. |
+------------------------+------------+---------------------+
| body row 3 | Cells may | - Table cells |
+------------------------+ span rows. | - contain |
| body row 4 | | - body elements. |
+------------------------+------------+---------------------+
Important
Отступ таблицы относительно команды .. table::
обязателен
Результат:
Header row, column 1 (header rows optional) | Header 2 | Header 3 | Header 4 |
---|---|---|---|
body row 1, column 1 | column 2 | column 3 | column 4 |
body row 2 | Cells may span columns. | ||
body row 3 | Cells may span rows. |
|
|
body row 4 |
Простая таблица:
.. table:: Простая таблица
===== ===== =======
A B A and B
===== ===== =======
False False False
True False False
False True False
True True True
===== ===== =======
Результат:
A | B | A and B |
---|---|---|
False | False | False |
True | False | False |
False | True | False |
True | True | True |
Ещё один пример:
.. table:: Простая таблица со сложной шапкой
===== ===== ======
Inputs Output
------------ ------
A B A or B
===== ===== ======
False False False
True False True
False True True
True True True
===== ===== ======
Результат:
Inputs | Output | |
---|---|---|
A | B | A or B |
False | False | False |
True | False | True |
False | True | True |
True | True | True |
Ещё один тип таблицы — CSV-таблица:
.. csv-table:: CSV-таблица
:header: "Treat", "Quantity", "Description"
:widths: 15, 10, 30
"Albatross", 2.99, "On a stick!"
"Crunchy Frog", 1.49, "If we took the bones out, it wouldn't be
crunchy, now would it?"
"Gannet Ripple", 1.99, "On a stick!"
Результат:
Treat | Quantity | Description |
---|---|---|
Albatross | 2.99 | On a stick! |
Crunchy Frog | 1.49 | If we took the bones out, it wouldn’t be crunchy, now would it? |
Gannet Ripple | 1.99 | On a stick! |
Note
Смотрите также статью reStructuredText (ReST): Быстрый способ ввода таблиц
Ещё один тип таблицы — таблица в виде списка:
.. list-table:: Таблица в виде списка
:widths: 15 10 30
:header-rows: 1
* - Treat
- Quantity
- Description
* - Albatross
- 2.99
- On a stick!
* - Crunchy Frog
- 1.49
- If we took the bones out, it wouldn't be
crunchy, now would it?
* - Gannet Ripple
- 1.99
- On a stick!
Treat | Quantity | Description |
---|---|---|
Albatross | 2.99 | On a stick! |
Crunchy Frog | 1.49 | If we took the bones out, it wouldn’t be crunchy, now would it? |
Gannet Ripple | 1.99 | On a stick! |
Вставка формул осуществляется командой .. math::
. Для ввода формул используется синтаксис LaTeX:
.. math::
\alpha_t(i) = P(O_1, O_2, … O_t, q_t = S_i \lambda)
Результат:
Блоки примечаний и предупреждений используются для сообщения дополнительной информации. Локализация заголовков и оформление блоков зависит от используемого шаблона. В стандартном шаблоне, используемом на сайте ReadTheDocs.org все блоки имеют собственное оформление, а локализация заголовков зависит от выбранного языка. Также язык настраивается в файле конфигурации Sphinx conf.py
.
Attention
Блок Внимание, команда: .. attention::
Caution
Блок Осторожно, команда: .. caution::
Danger
Блок Опасно, команда: .. danger::
Error
Блок Ошибка, команда: .. error::
Hint
Блок Подсказка, команда: .. hint::
Important
Блок Важно, команда: .. important::
Note
Блок Примечание, команда: .. note::
Note
Исходный код доступен по адресу:
Tip
Блок Совет, команда: .. tip::
Warning
Блок Предупреждение, команда: .. warning::
Todo
Блок План, команда: .. todo::
See also
Блок См.также, команда: .. seealso::
New in version 0.100.500: bla bla bla
Changed in version 0.100.500: bla bla bla
Deprecated since version 0.100.500: bla bla bla
This directive creates a paragraph heading that is not used to create a table of contents node.
|
|
|
Код блоков выглядит так:
.. tip:: Блок **Совет**, команда: ``.. tip::``
На основе заголовков ReST автоматически создает оглавление, которое вставляется командой .. contents::
:
.. contents:: Оглавление
:depth: 5
или
.. contents:: Содержание
:depth: 5
Параметр :depth:
задает уровни заголовков, которые будут включены в оглавление.
Результат:
Оглавление
или
Содержание
Имеется возможность добавлять метаданные каждой из страниц непосредственно в rst файлы с помощью директивы .. meta::
:
.. meta::
:description: The reStructuredText plaintext markup language
:keywords: plaintext, markup language
Будет преобразовано в:
<meta name="description"
content="The reStructuredText plaintext markup language">
<meta name="keywords" content="plaintext, markup language">
Другие атрибуты:
.. meta::
:description lang=en: An amusing story
:description lang=fr: Une histoire amusante
.. meta::
:http-equiv=Content-Type: text/html; charset=ISO-8859-1
Подробнее смотрите раздел HTML-Specific официальной документации reStructuredText.
[CIT2003] | Код вставки этой цитаты .. [CIT2003] размещен в самом конце .rst файла. |
sphinx.domains.
Domain
(env)¶A Domain is meant to be a group of “object” description directives for objects of a similar nature, and corresponding roles to create references to them. Examples would be Python modules, classes, functions etc., elements of a templating language, Sphinx roles and directives, etc.
Each domain has a separate storage for information about existing objects and how to reference them in self.data, which must be a dictionary. It also must implement several functions that expose the object information in a uniform way to parts of Sphinx that allow the user to reference or search for objects in a domain-agnostic way.
About self.data: since all object and cross-referencing information is
stored on a BuildEnvironment instance, the domain.data object is also
stored in the env.domaindata dict under the key domain.name. Before the
build process starts, every active domain is instantiated and given the
environment object; the domaindata dict must then either be nonexistent or
a dictionary whose ‘version’ key is equal to the domain class’
data_version
attribute. Otherwise, IOError is raised and the
pickled environment is discarded.
clear_doc
(docname)¶Remove traces of a document in the domain-specific inventories.
dangling_warnings
= {}¶role name -> a warning message if reference is missing
data_version
= 0¶data version, bump this when the format of self.data changes
directive
(name)¶Return a directive adapter class that always gives the registered
directive its full name (‘domain:name’) as self.name
.
directives
= {}¶directive name -> directive class
get_objects
()¶Return an iterable of “object descriptions”, which are tuples with five items:
self.object_types
get_type_name
(type, primary=False)¶Return full name for given ObjType.
indices
= []¶a list of Index subclasses
initial_data
= {}¶data value for a fresh environment
label
= ''¶domain label: longer, more descriptive (used in messages)
merge_domaindata
(docnames, otherdata)¶Merge in data regarding docnames from a different domaindata inventory (coming from a subprocess in parallel builds).
name
= ''¶domain name: should be short, but unique
object_types
= {}¶type (usually directive) name -> ObjType instance
process_doc
(env, docname, document)¶Process a document after it is read by the environment.
resolve_any_xref
(env, fromdocname, builder, target, node, contnode)¶Resolve the pending_xref node with the given target.
The reference comes from an “any” or similar role, which means that we
don’t know the type. Otherwise, the arguments are the same as for
resolve_xref()
.
The method must return a list (potentially empty) of tuples
('domain:role', newnode)
, where 'domain:role'
is the name of a
role that could have created the same reference, e.g. 'py:func'
.
newnode
is what resolve_xref()
would return.
New in version 1.3.
resolve_xref
(env, fromdocname, builder, typ, target, node, contnode)¶Resolve the pending_xref node with the given typ and target.
This method should return a new node, to replace the xref node, containing the contnode which is the markup content of the cross-reference.
If no resolution can be found, None can be returned; the xref node will then given to the ‘missing-reference’ event, and if that yields no resolution, replaced by contnode.
The method can also raise sphinx.environment.NoUri
to suppress
the ‘missing-reference’ event being emitted.
role
(name)¶Return a role adapter function that always gives the registered role its full name (‘domain:name’) as the first argument.
roles
= {}¶role name -> role callable
sphinx.domains.
ObjType
(lname, *roles, **attrs)¶An ObjType is the description for a type of object that a domain can document. In the object_types attribute of Domain subclasses, object type names are mapped to instances of this class.
Constructor arguments:
Domain.get_objects()
.sphinx.domains.
Index
(domain)¶An Index is the description for a domain-specific index. To add an index to a domain, subclass Index, overriding the three name attributes:
and providing a generate()
method. Then, add the index class to
your domain’s indices list. Extensions can add indices to existing
domains using add_index_to_domain()
.
generate
(docnames=None)¶Return entries for the index given by name. If docnames is given, restrict to entries referring to these docnames.
The return value is a tuple of (content, collapse)
, where collapse
is a boolean that determines if sub-entries should start collapsed (for
output formats that support collapsing sub-entries).
content is a sequence of (letter, entries)
tuples, where letter
is the “heading” for the given entries, usually the starting letter.
entries is a sequence of single entries, where a single entry is a
sequence [name, subtype, docname, anchor, extra, qualifier, descr]
.
The items in this sequence have the following meaning:
Qualifier and description are not rendered e.g. in LaTeX output.
sphinx.environment.
BuildEnvironment
¶Attributes
srcdir
¶Source directory (the directory containing conf.py
).
doctreedir
¶Directory for storing pickled doctrees.
found_docs
¶A set of all existing docnames.
metadata
¶titles
¶Dictionary mapping docnames to the docutils node for their main title.
docname
¶Returns the docname of the document currently being parsed.
Utility methods
warn
(docname, msg, lineno=None, **kwargs)¶Emit a warning.
This differs from using app.warn()
in that the warning may not
be emitted instantly, but collected for emitting all warnings after
the update of the environment.
doc2path
(docname, base=True, suffix=None)¶Return the filename for the document name.
If base is True, return absolute path under self.srcdir. If base is None, return relative path to self.srcdir. If base is a path string, return absolute path under that. If suffix is not None, add it instead of config.source_suffix.
relfn2path
(filename, docname=None)¶Return paths to a file referenced from a document, relative to documentation root and absolute.
In the input “filename”, absolute filenames are taken as relative to the source dir, while relative filenames are relative to the dir of the containing document.
note_dependency
(filename)¶Add filename as a dependency of the current document.
This means that the document will be rebuilt if this file changes.
filename should be absolute or relative to the source directory.
new_serialno
(category='')¶Return a serial number, e.g. for index entry targets.
The number is guaranteed to be unique in the current document.
note_reread
()¶Add the current document to the list of documents that will automatically be re-read at the next build.
Directives are handled by classes derived from
docutils.parsers.rst.Directive
. They have to be registered by an extension
using Sphinx.add_directive()
or Sphinx.add_directive_to_domain()
.
docutils.parsers.rst.
Directive
¶The markup syntax of the new directive is determined by the follow five class attributes:
required_arguments
= 0¶Number of required directive arguments.
optional_arguments
= 0¶Number of optional arguments after the required arguments.
final_argument_whitespace
= False¶May the final argument contain whitespace?
option_spec
= None¶Mapping of option names to validator functions.
Option validator functions take a single parameter, the option argument
(or None
if not given), and should validate it or convert it to the
proper form. They raise ValueError
or TypeError
to indicate
failure.
There are several predefined and possibly useful validators in the
docutils.parsers.rst.directives
module.
has_content
= False¶May the directive have content?
New directives must implement the run()
method:
run
()¶This method must process the directive arguments, options and content, and return a list of Docutils/Sphinx nodes that will be inserted into the document tree at the point where the directive was encountered.
Instance attributes that are always set on the directive are:
name
¶The directive name (useful when registering the same directive class under multiple names).
arguments
¶The arguments given to the directive, as a list.
options
¶The options given to the directive, as a dictionary mapping option names to validated/converted values.
content
¶The directive content, if given, as a ViewList
.
lineno
¶The absolute line number on which the directive appeared. This is not
always a useful value; use srcline
instead.
src
¶The source file of the directive.
srcline
¶The line number in the source file on which the directive appeared.
content_offset
¶Internal offset of the directive content. Used when calling
nested_parse
(see below).
block_text
¶The string containing the entire directive.
Each Sphinx extension is a Python module with at least a setup()
function.
This function is called at initialization time with one argument, the
application object representing the Sphinx process.
sphinx.application.
Sphinx
¶This application object has the public API described in the following.
These methods are usually called in an extension’s setup()
function.
Examples of using the Sphinx extension API can be seen in the sphinx.ext
package.
Sphinx.
setup_extension
(name)¶Load the extension given by the module name. Use this if your extension needs the features provided by another extension.
Sphinx.
add_builder
(builder)¶Register a new builder. builder must be a class that inherits from
Builder
.
Sphinx.
add_config_value
(name, default, rebuild)¶Register a configuration value. This is necessary for Sphinx to recognize new values and set default values accordingly. The name should be prefixed with the extension name, to avoid clashes. The default value can be any Python object. The string value rebuild must be one of those values:
'env'
if a change in the setting only takes effect when a document is
parsed – this means that the whole environment must be rebuilt.'html'
if a change in the setting needs a full rebuild of HTML
documents.''
if a change in the setting will not need any special rebuild.Changed in version 0.4: If the default value is a callable, it will be called with the config object as its argument in order to get the default value. This can be used to implement config values whose default depends on other values.
Changed in version 0.6: Changed rebuild from a simple boolean (equivalent to ''
or
'env'
) to a string. However, booleans are still accepted and
converted internally.
Sphinx.
add_domain
(domain)¶Make the given domain (which must be a class; more precisely, a subclass of
Domain
) known to Sphinx.
New in version 1.0.
Sphinx.
override_domain
(domain)¶Make the given domain class known to Sphinx, assuming that there is already
a domain with its .name
. The new domain must be a subclass of the
existing one.
New in version 1.0.
Sphinx.
add_index_to_domain
(domain, index)¶Add a custom index class to the domain named domain. index must be a
subclass of Index
.
New in version 1.0.
Sphinx.
add_event
(name)¶Register an event called name. This is needed to be able to emit it.
Sphinx.
set_translator
(name, translator_class)¶Register or override a Docutils translator class. This is used to register
a custom output translator or to replace a builtin translator.
This allows extensions to use custom translator and define custom
nodes for the translator (see add_node()
).
New in version 1.3.
Sphinx.
add_node
(node, **kwds)¶Register a Docutils node class. This is necessary for Docutils internals. It may also be used in the future to validate nodes in the parsed documents.
Node visitor functions for the Sphinx HTML, LaTeX, text and manpage writers
can be given as keyword arguments: the keyword should be one or more of
'html'
, 'latex'
, 'text'
, 'man'
, 'texinfo'
or any other
supported translators, the value a 2-tuple of (visit, depart)
methods.
depart
can be None
if the visit
function raises
docutils.nodes.SkipNode
. Example:
class math(docutils.nodes.Element): pass
def visit_math_html(self, node):
self.body.append(self.starttag(node, 'math'))
def depart_math_html(self, node):
self.body.append('</math>')
app.add_node(math, html=(visit_math_html, depart_math_html))
Obviously, translators for which you don’t specify visitor methods will choke on the node when encountered in a document to translate.
Changed in version 0.5: Added the support for keyword arguments giving visit functions.
Sphinx.
add_directive
(name, func, content, arguments, **options)¶Sphinx.
add_directive
(name, directiveclass)Register a Docutils directive. name must be the prospective directive name. There are two possible ways to write a directive:
In the docutils 0.4 style, obj is the directive function. content, arguments and options are set as attributes on the function and determine whether the directive has content, arguments and options, respectively. This style is deprecated.
In the docutils 0.5 style, directiveclass is the directive class. It must already have attributes named has_content, required_arguments, optional_arguments, final_argument_whitespace and option_spec that correspond to the options for the function way. See the Docutils docs for details.
The directive class must inherit from the class
docutils.parsers.rst.Directive
.
For example, the (already existing) literalinclude
directive would
be added like this:
from docutils.parsers.rst import directives
add_directive('literalinclude', literalinclude_directive,
content = 0, arguments = (1, 0, 0),
linenos = directives.flag,
language = direcitves.unchanged,
encoding = directives.encoding)
Changed in version 0.6: Docutils 0.5-style directive classes are now supported.
Sphinx.
add_directive_to_domain
(domain, name, func, content, arguments, **options)¶Sphinx.
add_directive_to_domain
(domain, name, directiveclass)Like add_directive()
, but the directive is added to the domain named
domain.
New in version 1.0.
Sphinx.
add_role
(name, role)¶Register a Docutils role. name must be the role name that occurs in the source, role the role function (see the Docutils documentation on details).
Sphinx.
add_role_to_domain
(domain, name, role)¶Like add_role()
, but the role is added to the domain named domain.
New in version 1.0.
Sphinx.
add_generic_role
(name, nodeclass)¶Register a Docutils role that does nothing but wrap its contents in the node given by nodeclass.
New in version 0.6.
Sphinx.
add_object_type
(directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', doc_field_types=[])¶can be cross-referenced. It will do this:
%s
. See the example
below for how the template will be interpreted.conf.py
file in the
source for this documentation for an example.For example, if you have this call in a custom Sphinx extension:
app.add_object_type('directive', 'dir', 'pair: %s; directive')
you can use this markup in your documents:
.. rst:directive:: function
Document a function.
<...>
See also the :rst:dir:`function` directive.
For the directive, an index entry will be generated as if you had prepended
.. index:: pair: function; directive
The reference node will be of class literal
(so it will be rendered in a
proportional font, as appropriate for code) unless you give the
ref_nodeclass argument, which must be a docutils node class. Most useful
are docutils.nodes.emphasis
or docutils.nodes.strong
– you can also
use docutils.nodes.generated
if you want no further text decoration. If
the text should be treated as literal (e.g. no smart quote replacement), but
not have typewriter styling, use sphinx.addnodes.literal_emphasis
or
sphinx.addnodes.literal_strong
.
For the role content, you have the same syntactical possibilities as for
This method is also available under the deprecated alias
add_description_unit
.
Sphinx.
add_crossref_type
(directivename, rolename, indextemplate='', ref_nodeclass=None, objname='')¶This method is very similar to add_object_type()
except that the
directive it generates must be empty, and will produce no output.
That means that you can add semantic targets to your sources, and refer to
them using custom roles instead of generic ones (like ref
).
Example call:
app.add_crossref_type('topic', 'topic', 'single: %s', docutils.nodes.emphasis)
Example usage:
.. topic:: application API
The application API
-------------------
<...>
See also :topic:`this section <application API>`.
(Of course, the element following the topic
directive needn’t be a
section.)
Sphinx.
add_transform
(transform)¶Add the standard docutils Transform
subclass transform to the list
of transforms that are applied after Sphinx parses a reST document.
Sphinx.
add_javascript
(filename)¶Add filename to the list of JavaScript files that the default HTML template
will include. The filename must be relative to the HTML static path, see
scheme, like http://example.org/foo.js
, is also supported.
New in version 0.5.
Sphinx.
add_stylesheet
(filename)¶Add filename to the list of CSS files that the default HTML template will
include. Like for add_javascript()
, the filename must be relative to
the HTML static path, or a full URI with scheme.
New in version 1.0.
Sphinx.
add_latex_package
(packagename, options=None)¶Add packagename to the list of packages that LaTeX source code will include. If you provide options, it will be taken to usepackage declaration.
app.add_latex_package('mypackage') # => \usepackage{mypackage}
app.add_latex_package('mypackage', 'foo,bar') # => \usepackage[foo,bar]{mypackage}
New in version 1.3.
Sphinx.
add_lexer
(alias, lexer)¶Use lexer, which must be an instance of a Pygments lexer class, to highlight code blocks with the given language alias.
New in version 0.6.
Sphinx.
add_autodocumenter
(cls)¶Add cls as a new documenter class for the sphinx.ext.autodoc
extension. It must be a subclass of sphinx.ext.autodoc.Documenter
.
This allows to auto-document new types of objects. See the source of the
autodoc module for examples on how to subclass Documenter
.
New in version 0.6.
Sphinx.
add_autodoc_attrgetter
(type, getter)¶Add getter, which must be a function with an interface compatible to the
getattr()
builtin, as the autodoc attribute getter for objects that are
instances of type. All cases where autodoc needs to get an attribute of a
type are then handled by this function instead of getattr()
.
New in version 0.6.
Sphinx.
add_search_language
(cls)¶Add cls, which must be a subclass of sphinx.search.SearchLanguage
,
as a support language for building the HTML full-text search index. The
class must have a lang attribute that indicates the language it should be
New in version 1.1.
Sphinx.
require_sphinx
(version)¶Compare version (which must be a major.minor
version string,
e.g. '1.1'
) with the version of the running Sphinx, and abort the build
when it is too old.
New in version 1.0.
Sphinx.
connect
(event, callback)¶Register callback to be called when event is emitted. For details on available core events and the arguments of callback functions, please see
The method returns a “listener ID” that can be used as an argument to
disconnect()
.
Sphinx.
disconnect
(listener_id)¶Unregister callback listener_id.
sphinx.application.
ExtensionError
¶All these methods raise this exception if something went wrong with the extension API.
Sphinx.
emit
(event, *arguments)¶Emit event and pass arguments to the callback functions. Return the return values of all callbacks as a list. Do not emit core Sphinx events in extensions!
Sphinx.
emit_firstresult
(event, *arguments)¶Emit event and pass arguments to the callback functions. Return the
result of the first callback that doesn’t return None
.
New in version 0.5.
The application object also provides support for emitting leveled messages.
Note
There is no “error” call: in Sphinx, errors are defined as things that stop
the build; just raise an exception (sphinx.errors.SphinxError
or a
custom subclass) to do that.
Sphinx.
warn
(message, location=None, prefix='WARNING: ', type=None, subtype=None, colorfunc=<function inner>)¶Emit a warning.
If location is given, it should either be a tuple of (docname, lineno) or a string describing the location of the warning as well as possible.
prefix usually should not be changed.
type and subtype are used to suppress warnings with :confval:`suppress_warnings`.
Note
For warnings emitted during parsing, you should use
BuildEnvironment.warn()
since that will collect all
warnings during parsing for later output.
Sphinx.
info
(message='', nonl=False)¶Emit an informational message.
If nonl is true, don’t emit a newline at the end (which implies that more info output will follow soon.)
Sphinx.
verbose
(message, *args, **kwargs)¶Emit a verbose informational message.
The message will only be emitted for verbosity levels >= 1 (i.e. at
least one -v
option was given).
The message can contain %-style interpolation placeholders, which is
formatted with either the *args
or **kwargs
when output.
Sphinx.
debug
(message, *args, **kwargs)¶Emit a debug-level informational message.
The message will only be emitted for verbosity levels >= 2 (i.e. at
least two -v
options were given).
The message can contain %-style interpolation placeholders, which is
formatted with either the *args
or **kwargs
when output.
Sphinx.
debug2
(message, *args, **kwargs)¶Emit a lowlevel debug-level informational message.
The message will only be emitted for verbosity level 3 (i.e. three
-v
options were given).
The message can contain %-style interpolation placeholders, which is
formatted with either the *args
or **kwargs
when output.
These events are known to the core. The arguments shown are given to the
registered event handlers. Use connect()
in an extension’s setup
function (note that conf.py
can also have a setup
function) to connect
handlers to the events. Example:
def source_read_handler(app, docname, source):
print('do something here...')
def setup(app):
app.connect('source-read', source_read_handler)
Use this to adapt your extension to API changes in Sphinx.
sphinx.
version_info
¶A tuple of five elements; for Sphinx version 1.2.1 beta 3 this would be
(1, 2, 1, 'beta', 3)
.
New in version 1.2: Before version 1.2, check the string sphinx.__version__
.
sphinx.config.
Config
¶The config object makes the values of all config values available as attributes.
It is available as the config
attribute on the application and
use either app.config.language
or env.config.language
.
sphinx.application.
TemplateBridge
¶This class defines the interface for a “template bridge”, that is, a class that renders templates given a template name and a context.
init
(builder, theme=None, dirs=None)¶Called by the builder to initialize the template system.
builder is the builder object; you’ll probably want to look at the
value of builder.config.templates_path
.
theme is a sphinx.theming.Theme
object or None; in the latter
case, dirs can be list of fixed directories to look for templates.
newest_template_mtime
()¶Called by the builder to determine if output files are outdated
because of template changes. Return the mtime of the newest template
file that was changed. The default implementation returns 0
.
render
(template, context)¶Called by the builder to render a template given as a filename with a specified context (a Python dictionary).
render_string
(template, context)¶Called by the builder to render a template given as a string with a specified context (a Python dictionary).
sphinx.errors.
SphinxError
¶This is the base class for “nice” exceptions. When such an exception is raised, Sphinx will abort the build and present the exception category and message to the user.
Extensions are encouraged to derive from this exception for their custom errors.
Exceptions not derived from SphinxError
are treated as unexpected
and shown to the user with a part of the traceback (and the full traceback
saved in a temporary file).
category
¶Description of the exception “category”, used in converting the exception to a string (“category: message”). Should be set accordingly in subclasses.
sphinx.errors.
ConfigError
¶Used for erroneous values or nonsensical combinations of configuration values.
sphinx.errors.
ExtensionError
¶Used for errors in setting up extensions.
sphinx.errors.
ThemeError
¶Used for errors to do with themes.
sphinx.errors.
VersionRequirementError
¶Raised when the docs require a higher Sphinx version than the current one.