xref: /linux/Documentation/doc-guide/sphinx.rst (revision d4f42b71e816b19dd44b373e1006ca64da75c192)
1.. _sphinxdoc:
2
3=====================================
4Using Sphinx for kernel documentation
5=====================================
6
7The Linux kernel uses `Sphinx`_ to generate pretty documentation from
8`reStructuredText`_ files under ``Documentation``. To build the documentation in
9HTML or PDF formats, use ``make htmldocs`` or ``make pdfdocs``. The generated
10documentation is placed in ``Documentation/output``.
11
12.. _Sphinx: http://www.sphinx-doc.org/
13.. _reStructuredText: http://docutils.sourceforge.net/rst.html
14
15The reStructuredText files may contain directives to include structured
16documentation comments, or kernel-doc comments, from source files. Usually these
17are used to describe the functions and types and design of the code. The
18kernel-doc comments have some special structure and formatting, but beyond that
19they are also treated as reStructuredText.
20
21Finally, there are thousands of plain text documentation files scattered around
22``Documentation``. Some of these will likely be converted to reStructuredText
23over time, but the bulk of them will remain in plain text.
24
25.. _sphinx_install:
26
27Sphinx Install
28==============
29
30The ReST markups currently used by the Documentation/ files are meant to be
31built with ``Sphinx`` version 2.4.4 or higher.
32
33There's a script that checks for the Sphinx requirements. Please see
34:ref:`sphinx-pre-install` for further details.
35
36Most distributions are shipped with Sphinx, but its toolchain is fragile,
37and it is not uncommon that upgrading it or some other Python packages
38on your machine would cause the documentation build to break.
39
40A way to avoid that is to use a different version than the one shipped
41with your distributions. In order to do so, it is recommended to install
42Sphinx inside a virtual environment, using ``virtualenv-3``
43or ``virtualenv``, depending on how your distribution packaged Python 3.
44
45.. note::
46
47   #) It is recommended to use the RTD theme for html output. Depending
48      on the Sphinx version, it should be installed separately,
49      with ``pip install sphinx_rtd_theme``.
50
51In summary, if you want to install Sphinx version 2.4.4, you should do::
52
53       $ virtualenv sphinx_2.4.4
54       $ . sphinx_2.4.4/bin/activate
55       (sphinx_2.4.4) $ pip install -r Documentation/sphinx/requirements.txt
56
57After running ``. sphinx_2.4.4/bin/activate``, the prompt will change,
58in order to indicate that you're using the new environment. If you
59open a new shell, you need to rerun this command to enter again at
60the virtual environment before building the documentation.
61
62Image output
63------------
64
65The kernel documentation build system contains an extension that
66handles images in both GraphViz and SVG formats (see :ref:`sphinx_kfigure`).
67
68For it to work, you need to install both GraphViz and ImageMagick
69packages. If those packages are not installed, the build system will
70still build the documentation, but won't include any images at the
71output.
72
73PDF and LaTeX builds
74--------------------
75
76Such builds are currently supported only with Sphinx versions 2.4 and higher.
77
78For PDF and LaTeX output, you'll also need ``XeLaTeX`` version 3.14159265.
79
80Depending on the distribution, you may also need to install a series of
81``texlive`` packages that provide the minimal set of functionalities
82required for ``XeLaTeX`` to work.
83
84Math Expressions in HTML
85------------------------
86
87Some ReST pages contain math expressions. Due to the way Sphinx works,
88those expressions are written using LaTeX notation.
89There are two options for Sphinx to render math expressions in html output.
90One is an extension called `imgmath`_ which converts math expressions into
91images and embeds them in html pages.
92The other is an extension called `mathjax`_ which delegates math rendering
93to JavaScript capable web browsers.
94The former was the only option for pre-6.1 kernel documentation and it
95requires quite a few texlive packages including amsfonts and amsmath among
96others.
97
98Since kernel release 6.1, html pages with math expressions can be built
99without installing any texlive packages. See `Choice of Math Renderer`_ for
100further info.
101
102.. _imgmath: https://www.sphinx-doc.org/en/master/usage/extensions/math.html#module-sphinx.ext.imgmath
103.. _mathjax: https://www.sphinx-doc.org/en/master/usage/extensions/math.html#module-sphinx.ext.mathjax
104
105.. _sphinx-pre-install:
106
107Checking for Sphinx dependencies
108--------------------------------
109
110There's a script that automatically checks for Sphinx dependencies. If it can
111recognize your distribution, it will also give a hint about the install
112command line options for your distro::
113
114	$ ./scripts/sphinx-pre-install
115	Checking if the needed tools for Fedora release 26 (Twenty Six) are available
116	Warning: better to also install "texlive-luatex85".
117	You should run:
118
119		sudo dnf install -y texlive-luatex85
120		/usr/bin/virtualenv sphinx_2.4.4
121		. sphinx_2.4.4/bin/activate
122		pip install -r Documentation/sphinx/requirements.txt
123
124	Can't build as 1 mandatory dependency is missing at ./scripts/sphinx-pre-install line 468.
125
126By default, it checks all the requirements for both html and PDF, including
127the requirements for images, math expressions and LaTeX build, and assumes
128that a virtual Python environment will be used. The ones needed for html
129builds are assumed to be mandatory; the others to be optional.
130
131It supports two optional parameters:
132
133``--no-pdf``
134	Disable checks for PDF;
135
136``--no-virtualenv``
137	Use OS packaging for Sphinx instead of Python virtual environment.
138
139
140Sphinx Build
141============
142
143The usual way to generate the documentation is to run ``make htmldocs`` or
144``make pdfdocs``. There are also other formats available: see the documentation
145section of ``make help``. The generated documentation is placed in
146format-specific subdirectories under ``Documentation/output``.
147
148To generate documentation, Sphinx (``sphinx-build``) must obviously be
149installed.  For PDF output you'll also need ``XeLaTeX`` and ``convert(1)``
150from ImageMagick (https://www.imagemagick.org).\ [#ink]_ All of these are
151widely available and packaged in distributions.
152
153To pass extra options to Sphinx, you can use the ``SPHINXOPTS`` make
154variable. For example, use ``make SPHINXOPTS=-v htmldocs`` to get more verbose
155output.
156
157It is also possible to pass an extra DOCS_CSS overlay file, in order to customize
158the html layout, by using the ``DOCS_CSS`` make variable.
159
160By default, the "Alabaster" theme is used to build the HTML documentation;
161this theme is bundled with Sphinx and need not be installed separately.
162The Sphinx theme can be overridden by using the ``DOCS_THEME`` make variable.
163
164There is another make variable ``SPHINXDIRS``, which is useful when test
165building a subset of documentation.  For example, you can build documents
166under ``Documentation/doc-guide`` by running
167``make SPHINXDIRS=doc-guide htmldocs``.
168The documentation section of ``make help`` will show you the list of
169subdirectories you can specify.
170
171To remove the generated documentation, run ``make cleandocs``.
172
173.. [#ink] Having ``inkscape(1)`` from Inkscape (https://inkscape.org)
174	  as well would improve the quality of images embedded in PDF
175	  documents, especially for kernel releases 5.18 and later.
176
177Choice of Math Renderer
178-----------------------
179
180Since kernel release 6.1, mathjax works as a fallback math renderer for
181html output.\ [#sph1_8]_
182
183Math renderer is chosen depending on available commands as shown below:
184
185.. table:: Math Renderer Choices for HTML
186
187    ============= ================= ============
188    Math renderer Required commands Image format
189    ============= ================= ============
190    imgmath       latex, dvipng     PNG (raster)
191    mathjax
192    ============= ================= ============
193
194The choice can be overridden by setting an environment variable
195``SPHINX_IMGMATH`` as shown below:
196
197.. table:: Effect of Setting ``SPHINX_IMGMATH``
198
199    ====================== ========
200    Setting                Renderer
201    ====================== ========
202    ``SPHINX_IMGMATH=yes`` imgmath
203    ``SPHINX_IMGMATH=no``  mathjax
204    ====================== ========
205
206.. [#sph1_8] Fallback of math renderer requires Sphinx >=1.8.
207
208
209Writing Documentation
210=====================
211
212Adding new documentation can be as simple as:
213
2141. Add a new ``.rst`` file somewhere under ``Documentation``.
2152. Refer to it from the Sphinx main `TOC tree`_ in ``Documentation/index.rst``.
216
217.. _TOC tree: http://www.sphinx-doc.org/en/stable/markup/toctree.html
218
219This is usually good enough for simple documentation (like the one you're
220reading right now), but for larger documents it may be advisable to create a
221subdirectory (or use an existing one). For example, the graphics subsystem
222documentation is under ``Documentation/gpu``, split to several ``.rst`` files,
223and has a separate ``index.rst`` (with a ``toctree`` of its own) referenced from
224the main index.
225
226See the documentation for `Sphinx`_ and `reStructuredText`_ on what you can do
227with them. In particular, the Sphinx `reStructuredText Primer`_ is a good place
228to get started with reStructuredText. There are also some `Sphinx specific
229markup constructs`_.
230
231.. _reStructuredText Primer: http://www.sphinx-doc.org/en/stable/rest.html
232.. _Sphinx specific markup constructs: http://www.sphinx-doc.org/en/stable/markup/index.html
233
234Specific guidelines for the kernel documentation
235------------------------------------------------
236
237Here are some specific guidelines for the kernel documentation:
238
239* Please don't go overboard with reStructuredText markup. Keep it
240  simple. For the most part the documentation should be plain text with
241  just enough consistency in formatting that it can be converted to
242  other formats.
243
244* Please keep the formatting changes minimal when converting existing
245  documentation to reStructuredText.
246
247* Also update the content, not just the formatting, when converting
248  documentation.
249
250* Please stick to this order of heading adornments:
251
252  1. ``=`` with overline for document title::
253
254       ==============
255       Document title
256       ==============
257
258  2. ``=`` for chapters::
259
260       Chapters
261       ========
262
263  3. ``-`` for sections::
264
265       Section
266       -------
267
268  4. ``~`` for subsections::
269
270       Subsection
271       ~~~~~~~~~~
272
273  Although RST doesn't mandate a specific order ("Rather than imposing a fixed
274  number and order of section title adornment styles, the order enforced will be
275  the order as encountered."), having the higher levels the same overall makes
276  it easier to follow the documents.
277
278* For inserting fixed width text blocks (for code examples, use case
279  examples, etc.), use ``::`` for anything that doesn't really benefit
280  from syntax highlighting, especially short snippets. Use
281  ``.. code-block:: <language>`` for longer code blocks that benefit
282  from highlighting. For a short snippet of code embedded in the text, use \`\`.
283
284
285The C domain
286------------
287
288The **Sphinx C Domain** (name c) is suited for documentation of C API. E.g. a
289function prototype:
290
291.. code-block:: rst
292
293    .. c:function:: int ioctl( int fd, int request )
294
295The C domain of the kernel-doc has some additional features. E.g. you can
296*rename* the reference name of a function with a common name like ``open`` or
297``ioctl``:
298
299.. code-block:: rst
300
301     .. c:function:: int ioctl( int fd, int request )
302        :name: VIDIOC_LOG_STATUS
303
304The func-name (e.g. ioctl) remains in the output but the ref-name changed from
305``ioctl`` to ``VIDIOC_LOG_STATUS``. The index entry for this function is also
306changed to ``VIDIOC_LOG_STATUS``.
307
308Please note that there is no need to use ``c:func:`` to generate cross
309references to function documentation.  Due to some Sphinx extension magic,
310the documentation build system will automatically turn a reference to
311``function()`` into a cross reference if an index entry for the given
312function name exists.  If you see ``c:func:`` use in a kernel document,
313please feel free to remove it.
314
315Tables
316------
317
318ReStructuredText provides several options for table syntax. Kernel style for
319tables is to prefer *simple table* syntax or *grid table* syntax. See the
320`reStructuredText user reference for table syntax`_ for more details.
321
322.. _reStructuredText user reference for table syntax:
323   https://docutils.sourceforge.io/docs/user/rst/quickref.html#tables
324
325list tables
326~~~~~~~~~~~
327
328The list-table formats can be useful for tables that are not easily laid
329out in the usual Sphinx ASCII-art formats.  These formats are nearly
330impossible for readers of the plain-text documents to understand, though,
331and should be avoided in the absence of a strong justification for their
332use.
333
334The ``flat-table`` is a double-stage list similar to the ``list-table`` with
335some additional features:
336
337* column-span: with the role ``cspan`` a cell can be extended through
338  additional columns
339
340* row-span: with the role ``rspan`` a cell can be extended through
341  additional rows
342
343* auto span rightmost cell of a table row over the missing cells on the right
344  side of that table-row.  With Option ``:fill-cells:`` this behavior can
345  changed from *auto span* to *auto fill*, which automatically inserts (empty)
346  cells instead of spanning the last cell.
347
348options:
349
350* ``:header-rows:``   [int] count of header rows
351* ``:stub-columns:``  [int] count of stub columns
352* ``:widths:``        [[int] [int] ... ] widths of columns
353* ``:fill-cells:``    instead of auto-spanning missing cells, insert missing cells
354
355roles:
356
357* ``:cspan:`` [int] additional columns (*morecols*)
358* ``:rspan:`` [int] additional rows (*morerows*)
359
360The example below shows how to use this markup.  The first level of the staged
361list is the *table-row*. In the *table-row* there is only one markup allowed,
362the list of the cells in this *table-row*. Exceptions are *comments* ( ``..`` )
363and *targets* (e.g. a ref to ``:ref:`last row <last row>``` / :ref:`last row
364<last row>`).
365
366.. code-block:: rst
367
368   .. flat-table:: table title
369      :widths: 2 1 1 3
370
371      * - head col 1
372        - head col 2
373        - head col 3
374        - head col 4
375
376      * - row 1
377        - field 1.1
378        - field 1.2 with autospan
379
380      * - row 2
381        - field 2.1
382        - :rspan:`1` :cspan:`1` field 2.2 - 3.3
383
384      * .. _`last row`:
385
386        - row 3
387
388Rendered as:
389
390   .. flat-table:: table title
391      :widths: 2 1 1 3
392
393      * - head col 1
394        - head col 2
395        - head col 3
396        - head col 4
397
398      * - row 1
399        - field 1.1
400        - field 1.2 with autospan
401
402      * - row 2
403        - field 2.1
404        - :rspan:`1` :cspan:`1` field 2.2 - 3.3
405
406      * .. _`last row`:
407
408        - row 3
409
410Cross-referencing
411-----------------
412
413Cross-referencing from one documentation page to another can be done simply by
414writing the path to the document file, no special syntax required. The path can
415be either absolute or relative. For absolute paths, start it with
416"Documentation/". For example, to cross-reference to this page, all the
417following are valid options, depending on the current document's directory (note
418that the ``.rst`` extension is required)::
419
420    See Documentation/doc-guide/sphinx.rst. This always works.
421    Take a look at sphinx.rst, which is at this same directory.
422    Read ../sphinx.rst, which is one directory above.
423
424If you want the link to have a different rendered text other than the document's
425title, you need to use Sphinx's ``doc`` role. For example::
426
427    See :doc:`my custom link text for document sphinx <sphinx>`.
428
429For most use cases, the former is preferred, as it is cleaner and more suited
430for people reading the source files. If you come across a ``:doc:`` usage that
431isn't adding any value, please feel free to convert it to just the document
432path.
433
434For information on cross-referencing to kernel-doc functions or types, see
435Documentation/doc-guide/kernel-doc.rst.
436
437Referencing commits
438~~~~~~~~~~~~~~~~~~~
439
440References to git commits are automatically hyperlinked given that they are
441written in one of these formats::
442
443    commit 72bf4f1767f0
444    commit 72bf4f1767f0 ("net: do not leave an empty skb in write queue")
445
446.. _sphinx_kfigure:
447
448Figures & Images
449================
450
451If you want to add an image, you should use the ``kernel-figure`` and
452``kernel-image`` directives. E.g. to insert a figure with a scalable
453image format, use SVG (:ref:`svg_image_example`)::
454
455    .. kernel-figure::  svg_image.svg
456       :alt:    simple SVG image
457
458       SVG image example
459
460.. _svg_image_example:
461
462.. kernel-figure::  svg_image.svg
463   :alt:    simple SVG image
464
465   SVG image example
466
467The kernel figure (and image) directive supports **DOT** formatted files, see
468
469* DOT: http://graphviz.org/pdf/dotguide.pdf
470* Graphviz: http://www.graphviz.org/content/dot-language
471
472A simple example (:ref:`hello_dot_file`)::
473
474  .. kernel-figure::  hello.dot
475     :alt:    hello world
476
477     DOT's hello world example
478
479.. _hello_dot_file:
480
481.. kernel-figure::  hello.dot
482   :alt:    hello world
483
484   DOT's hello world example
485
486Embedded *render* markups (or languages) like Graphviz's **DOT** are provided by the
487``kernel-render`` directives.::
488
489  .. kernel-render:: DOT
490     :alt: foobar digraph
491     :caption: Embedded **DOT** (Graphviz) code
492
493     digraph foo {
494      "bar" -> "baz";
495     }
496
497How this will be rendered depends on the installed tools. If Graphviz is
498installed, you will see a vector image. If not, the raw markup is inserted as
499*literal-block* (:ref:`hello_dot_render`).
500
501.. _hello_dot_render:
502
503.. kernel-render:: DOT
504   :alt: foobar digraph
505   :caption: Embedded **DOT** (Graphviz) code
506
507   digraph foo {
508      "bar" -> "baz";
509   }
510
511The *render* directive has all the options known from the *figure* directive,
512plus option ``caption``.  If ``caption`` has a value, a *figure* node is
513inserted. If not, an *image* node is inserted. A ``caption`` is also needed, if
514you want to refer to it (:ref:`hello_svg_render`).
515
516Embedded **SVG**::
517
518  .. kernel-render:: SVG
519     :caption: Embedded **SVG** markup
520     :alt: so-nw-arrow
521
522     <?xml version="1.0" encoding="UTF-8"?>
523     <svg xmlns="http://www.w3.org/2000/svg" version="1.1" ...>
524        ...
525     </svg>
526
527.. _hello_svg_render:
528
529.. kernel-render:: SVG
530   :caption: Embedded **SVG** markup
531   :alt: so-nw-arrow
532
533   <?xml version="1.0" encoding="UTF-8"?>
534   <svg xmlns="http://www.w3.org/2000/svg"
535     version="1.1" baseProfile="full" width="70px" height="40px" viewBox="0 0 700 400">
536   <line x1="180" y1="370" x2="500" y2="50" stroke="black" stroke-width="15px"/>
537   <polygon points="585 0 525 25 585 50" transform="rotate(135 525 25)"/>
538   </svg>
539