요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. _sphinxdoc:
=====================================
Using Sphinx for kernel documentation
=====================================
The Linux kernel uses `Sphinx`_ to generate pretty documentation from
`reStructuredText`_ files under ``Documentation``. To build the documentation in
HTML or PDF formats, use ``make htmldocs`` or ``make pdfdocs``. The generated
documentation is placed in ``Documentation/output``.
.. _Sphinx: http://www.sphinx-doc.org/
.. _reStructuredText: http://docutils.sourceforge.net/rst.html
The reStructuredText files may contain directives to include structured
documentation comments, or kernel-doc comments, from source files. Usually these
are used to describe the functions and types and design of the code. The
kernel-doc comments have some special structure and formatting, but beyond that
they are also treated as reStructuredText.
Finally, there are thousands of plain text documentation files scattered around
``Documentation``. Some of these will likely be converted to reStructuredText
over time, but the bulk of them will remain in plain text.
.. _sphinx_install:
Sphinx Install
==============
The ReST markups currently used by the Documentation/ files are meant to be
built with ``Sphinx`` version 3.4.3 or higher.
There's a script that checks for the Sphinx requirements. Please see
:ref:`sphinx-pre-install` for further details.
Most distributions are shipped with Sphinx, but its toolchain is fragile,
and it is not uncommon that upgrading it or some other Python packages
on your machine would cause the documentation build to break.
A way to avoid that is to use a different version than the one shipped
with your distributions. In order to do so, it is recommended to install
Sphinx inside a virtual environment, using ``virtualenv-3``
or ``virtualenv``, depending on how your distribution packaged Python 3.
In summary, if you want to install the latest version of Sphinx, you
should do::
$ virtualenv sphinx_latest
$ . sphinx_latest/bin/activate
(sphinx_latest) $ pip install -r Documentation/sphinx/requirements.txt
After running ``. sphinx_latest/bin/activate``, the prompt will change,
in order to indicate that you're using the new environment. If you
open a new shell, you need to rerun this command to enter again at
the virtual environment before building the documentation.
Image output
------------
The kernel documentation build system contains an extension that
handles images in both GraphViz and SVG formats (see :ref:`sphinx_kfigure`).
For it to work, you need to install both GraphViz and ImageMagick
packages. If those packages are not installed, the build system will
still build the documentation, but won't include any images at the
output.
PDF and LaTeX builds
--------------------
Such builds are currently supported only with Sphinx versions 2.4 and higher.
For PDF and LaTeX output, you'll also need ``XeLaTeX`` version 3.14159265.
Depending on the distribution, you may also need to install a series of
``texlive`` packages that provide the minimal set of functionalities
required for ``XeLaTeX`` to work.
Math Expressions in HTML
------------------------
Some ReST pages contain math expressions. Due to the way Sphinx works,
those expressions are written using LaTeX notation.
There are two options for Sphinx to render math expressions in html output.
One is an extension called `imgmath`_ which converts math expressions into
images and embeds them in html pages.
The other is an extension called `mathjax`_ which delegates math rendering
to JavaScript capable web browsers.
The former was the only option for pre-6.1 kernel documentation and it
requires quite a few texlive packages including amsfonts and amsmath among
others.
Since kernel release 6.1, html pages with math expressions can be built
without installing any texlive packages. See `Choice of Math Renderer`_ for
further info.
.. _imgmath: https://www.sphinx-doc.org/en/master/usage/extensions/math.html#module-sphinx.ext.imgmath
.. _mathjax: https://www.sphinx-doc.org/en/master/usage/extensions/math.html#module-sphinx.ext.mathjax
.. _sphinx-pre-install:
Checking for Sphinx dependencies
--------------------------------
There's a script that automatically checks for Sphinx dependencies. If it can
recognize your distribution, it will also give a hint about the install
command line options for your distro::
$ ./scripts/sphinx-pre-install
Checking if the needed tools for Fedora release 26 (Twenty Six) are available
Warning: better to also install "texlive-luatex85".
You should run:
sudo dnf install -y texlive-luatex85
/usr/bin/virtualenv sphinx_2.4.4
. sphinx_2.4.4/bin/activate
pip install -r Documentation/sphinx/requirements.txt
Can't build as 1 mandatory dependency is missing at ./scripts/sphinx-pre-install line 468.
By default, it checks all the requirements for both html and PDF, including
the requirements for images, math expressions and LaTeX build, and assumes
that a virtual Python environment will be used. The ones needed for html
builds are assumed to be mandatory; the others to be optional.
It supports two optional parameters:
``--no-pdf``
Disable checks for PDF;
``--no-virtualenv``
Use OS packaging for Sphinx instead of Python virtual environment.
Installing Sphinx Minimal Version
---------------------------------
When changing Sphinx build system, it is important to ensure that
the minimal version will still be supported. Nowadays, it is
becoming harder to do that on modern distributions, as it is not
possible to install with Python 3.13 and above.
Testing with the lowest supported Python version as defined at
Documentation/process/changes.rst can be done by creating
a venv with it with, and install minimal requirements with::
/usr/bin/python3.9 -m venv sphinx_min
. sphinx_min/bin/activate
pip install -r Documentation/sphinx/min_requirements.txt
A more comprehensive test can be done by using:
scripts/test_doc_build.py
Such script create one Python venv per supported version,
optionally building documentation for a range of Sphinx versions.
Sphinx Build
============
The usual way to generate the documentation is to run ``make htmldocs`` or
``make pdfdocs``. There are also other formats available: see the documentation
section of ``make help``. The generated documentation is placed in
format-specific subdirectories under ``Documentation/output``.
To generate documentation, Sphinx (``sphinx-build``) must obviously be
installed. For PDF output you'll also need ``XeLaTeX`` and ``convert(1)``
from ImageMagick (https://www.imagemagick.org).\ [#ink]_ All of these are
widely available and packaged in distributions.
To pass extra options to Sphinx, you can use the ``SPHINXOPTS`` make
variable. For example, use ``make SPHINXOPTS=-v htmldocs`` to get more verbose
output.
It is also possible to pass an extra DOCS_CSS overlay file, in order to customize
the html layout, by using the ``DOCS_CSS`` make variable.
By default, the "Alabaster" theme is used to build the HTML documentation;
this theme is bundled with Sphinx and need not be installed separately.
The Sphinx theme can be overridden by using the ``DOCS_THEME`` make variable.
.. note::
Some people might prefer to use the RTD theme for html output.
Depending on the Sphinx version, it should be installed separately,
with ``pip install sphinx_rtd_theme``.
There is another make variable ``SPHINXDIRS``, which is useful when test
building a subset of documentation. For example, you can build documents
under ``Documentation/doc-guide`` by running
``make SPHINXDIRS=doc-guide htmldocs``.
The documentation section of ``make help`` will show you the list of
subdirectories you can specify.
To remove the generated documentation, run ``make cleandocs``.
.. [#ink] Having ``inkscape(1)`` from Inkscape (https://inkscape.org)
as well would improve the quality of images embedded in PDF
documents, especially for kernel releases 5.18 and later.
Choice of Math Renderer
-----------------------
Since kernel release 6.1, mathjax works as a fallback math renderer for
html output.\ [#sph1_8]_
Math renderer is chosen depending on available commands as shown below:
.. table:: Math Renderer Choices for HTML
============= ================= ============
Math renderer Required commands Image format
============= ================= ============
imgmath latex, dvipng PNG (raster)
mathjax
============= ================= ============
The choice can be overridden by setting an environment variable
``SPHINX_IMGMATH`` as shown below:
.. table:: Effect of Setting ``SPHINX_IMGMATH``
====================== ========
Setting Renderer
====================== ========
``SPHINX_IMGMATH=yes`` imgmath
``SPHINX_IMGMATH=no`` mathjax
====================== ========
.. [#sph1_8] Fallback of math renderer requires Sphinx >=1.8.
Writing Documentation
=====================
Adding new documentation can be as simple as:
1. Add a new ``.rst`` file somewhere under ``Documentation``.
2. Refer to it from the Sphinx main `TOC tree`_ in ``Documentation/index.rst``.
.. _TOC tree: http://www.sphinx-doc.org/en/stable/markup/toctree.html
This is usually good enough for simple documentation (like the one you're
reading right now), but for larger documents it may be advisable to create a
subdirectory (or use an existing one). For example, the graphics subsystem
documentation is under ``Documentation/gpu``, split to several ``.rst`` files,
and has a separate ``index.rst`` (with a ``toctree`` of its own) referenced from
the main index.
See the documentation for `Sphinx`_ and `reStructuredText`_ on what you can do
with them. In particular, the Sphinx `reStructuredText Primer`_ is a good place
to get started with reStructuredText. There are also some `Sphinx specific
markup constructs`_.
.. _reStructuredText Primer: http://www.sphinx-doc.org/en/stable/rest.html
.. _Sphinx specific markup constructs: http://www.sphinx-doc.org/en/stable/markup/index.html
Specific guidelines for the kernel documentation
------------------------------------------------
Here are some specific guidelines for the kernel documentation:
* Please don't go overboard with reStructuredText markup. Keep it
simple. For the most part the documentation should be plain text with
just enough consistency in formatting that it can be converted to
other formats.
* Please keep the formatting changes minimal when converting existing
documentation to reStructuredText.
* Also update the content, not just the formatting, when converting
documentation.
* Please stick to this order of heading adornments:
1. ``=`` with overline for document title::
==============
Document title
==============
2. ``=`` for chapters::
Chapters
========
3. ``-`` for sections::
Section
-------
4. ``~`` for subsections::
Subsection
~~~~~~~~~~
Although RST doesn't mandate a specific order ("Rather than imposing a fixed
number and order of section title adornment styles, the order enforced will be
the order as encountered."), having the higher levels the same overall makes
it easier to follow the documents.
* For inserting fixed width text blocks (for code examples, use case
examples, etc.), use ``::`` for anything that doesn't really benefit
from syntax highlighting, especially short snippets. Use
``.. code-block:: <language>`` for longer code blocks that benefit
from highlighting. For a short snippet of code embedded in the text, use \`\`.
The C domain
------------
The **Sphinx C Domain** (name c) is suited for documentation of C API. E.g. a
function prototype:
.. code-block:: rst
.. c:function:: int ioctl( int fd, int request )
The C domain of the kernel-doc has some additional features. E.g. you can
*rename* the reference name of a function with a common name like ``open`` or
``ioctl``:
.. code-block:: rst
.. c:function:: int ioctl( int fd, int request )
:name: VIDIOC_LOG_STATUS
The func-name (e.g. ioctl) remains in the output but the ref-name changed from
``ioctl`` to ``VIDIOC_LOG_STATUS``. The index entry for this function is also
changed to ``VIDIOC_LOG_STATUS``.
Please note that there is no need to use ``c:func:`` to generate cross
references to function documentation. Due to some Sphinx extension magic,
the documentation build system will automatically turn a reference to
``function()`` into a cross reference if an index entry for the given
function name exists. If you see ``c:func:`` use in a kernel document,
please feel free to remove it.
Tables
------
ReStructuredText provides several options for table syntax. Kernel style for
tables is to prefer *simple table* syntax or *grid table* syntax. See the
`reStructuredText user reference for table syntax`_ for more details.
.. _reStructuredText user reference for table syntax:
https://docutils.sourceforge.io/docs/user/rst/quickref.html#tables
list tables
~~~~~~~~~~~
The list-table formats can be useful for tables that are not easily laid
out in the usual Sphinx ASCII-art formats. These formats are nearly
impossible for readers of the plain-text documents to understand, though,
and should be avoided in the absence of a strong justification for their
use.
The ``flat-table`` is a double-stage list similar to the ``list-table`` with
some additional features:
* column-span: with the role ``cspan`` a cell can be extended through
additional columns
* row-span: with the role ``rspan`` a cell can be extended through
additional rows
* auto span rightmost cell of a table row over the missing cells on the right
side of that table-row. With Option ``:fill-cells:`` this behavior can
changed from *auto span* to *auto fill*, which automatically inserts (empty)
cells instead of spanning the last cell.
options:
* ``:header-rows:`` [int] count of header rows
* ``:stub-columns:`` [int] count of stub columns
* ``:widths:`` [[int] [int] ... ] widths of columns
* ``:fill-cells:`` instead of auto-spanning missing cells, insert missing cells
roles:
* ``:cspan:`` [int] additional columns (*morecols*)
* ``:rspan:`` [int] additional rows (*morerows*)
The example below shows how to use this markup. The first level of the staged
list is the *table-row*. In the *table-row* there is only one markup allowed,
the list of the cells in this *table-row*. Exceptions are *comments* ( ``..`` )
and *targets* (e.g. a ref to ``:ref:`last row <last row>``` / :ref:`last row
<last row>`).
.. code-block:: rst
.. flat-table:: table title
:widths: 2 1 1 3
* - head col 1
- head col 2
- head col 3
- head col 4
* - row 1
- field 1.1
- field 1.2 with autospan
* - row 2
- field 2.1
- :rspan:`1` :cspan:`1` field 2.2 - 3.3
* .. _`last row`:
- row 3
Rendered as:
.. flat-table:: table title
:widths: 2 1 1 3
* - head col 1
- head col 2
- head col 3
- head col 4
* - row 1
- field 1.1
- field 1.2 with autospan
* - row 2
- field 2.1
- :rspan:`1` :cspan:`1` field 2.2 - 3.3
* .. _`last row`:
- row 3
Cross-referencing
-----------------
Cross-referencing from one documentation page to another can be done simply by
writing the path to the document file, no special syntax required. The path can
be either absolute or relative. For absolute paths, start it with
"Documentation/". For example, to cross-reference to this page, all the
following are valid options, depending on the current document's directory (note
that the ``.rst`` extension is required)::
See Documentation/doc-guide/sphinx.rst. This always works.
Take a look at sphinx.rst, which is at this same directory.
Read ../sphinx.rst, which is one directory above.
If you want the link to have a different rendered text other than the document's
title, you need to use Sphinx's ``doc`` role. For example::
See :doc:`my custom link text for document sphinx <sphinx>`.
For most use cases, the former is preferred, as it is cleaner and more suited
for people reading the source files. If you come across a ``:doc:`` usage that
isn't adding any value, please feel free to convert it to just the document
path.
For information on cross-referencing to kernel-doc functions or types, see
Documentation/doc-guide/kernel-doc.rst.
Referencing commits
~~~~~~~~~~~~~~~~~~~
References to git commits are automatically hyperlinked given that they are
written in one of these formats::
commit 72bf4f1767f0
commit 72bf4f1767f0 ("net: do not leave an empty skb in write queue")
.. _sphinx_kfigure:
Figures & Images
================
If you want to add an image, you should use the ``kernel-figure`` and
``kernel-image`` directives. E.g. to insert a figure with a scalable
image format, use SVG (:ref:`svg_image_example`)::
.. kernel-figure:: svg_image.svg
:alt: simple SVG image
SVG image example
.. _svg_image_example:
.. kernel-figure:: svg_image.svg
:alt: simple SVG image
SVG image example
The kernel figure (and image) directive supports **DOT** formatted files, see
* DOT: http://graphviz.org/pdf/dotguide.pdf
* Graphviz: http://www.graphviz.org/content/dot-language
A simple example (:ref:`hello_dot_file`)::
.. kernel-figure:: hello.dot
:alt: hello world
DOT's hello world example
.. _hello_dot_file:
.. kernel-figure:: hello.dot
:alt: hello world
DOT's hello world example
Embedded *render* markups (or languages) like Graphviz's **DOT** are provided by the
``kernel-render`` directives.::
.. kernel-render:: DOT
:alt: foobar digraph
:caption: Embedded **DOT** (Graphviz) code
digraph foo {
"bar" -> "baz";
}
How this will be rendered depends on the installed tools. If Graphviz is
installed, you will see a vector image. If not, the raw markup is inserted as
*literal-block* (:ref:`hello_dot_render`).
.. _hello_dot_render:
.. kernel-render:: DOT
:alt: foobar digraph
:caption: Embedded **DOT** (Graphviz) code
digraph foo {
"bar" -> "baz";
}
The *render* directive has all the options known from the *figure* directive,
plus option ``caption``. If ``caption`` has a value, a *figure* node is
inserted. If not, an *image* node is inserted. A ``caption`` is also needed, if
you want to refer to it (:ref:`hello_svg_render`).
Embedded **SVG**::
.. kernel-render:: SVG
:caption: Embedded **SVG** markup
:alt: so-nw-arrow
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ...>
...
</svg>
.. _hello_svg_render:
.. kernel-render:: SVG
:caption: Embedded **SVG** markup
:alt: so-nw-arrow
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
version="1.1" baseProfile="full" width="70px" height="40px" viewBox="0 0 700 400">
<line x1="180" y1="370" x2="500" y2="50" stroke="black" stroke-width="15px"/>
<polygon points="585 0 525 25 585 50" transform="rotate(135 525 25)"/>
</svg>
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
커널 문서에서 Sphinx를 사용하는 방식
1-24Linux kernel은 `Documentation` 아래의 `reStructuredText` 파일에서 보기 좋은 문서를 생성하기 위해 `Sphinx`를 사용합니다. HTML 또는 PDF 문서를 build하려면 `make htmldocs` 또는 `make pdfdocs`를 실행합니다. 생성 결과는 `Documentation/output`에 저장됩니다.
Sphinx 문서는 `http://www.sphinx-doc.org/`, reStructuredText 문서는 `http://docutils.sourceforge.net/rst.html`에서 확인할 수 있습니다.
reStructuredText 파일에는 소스 파일의 구조화된 문서 주석, 즉 kernel-doc 주석을 포함하는 directive를 넣을 수 있습니다. 보통 함수, 타입, 코드 설계를 설명하는 데 사용합니다. kernel-doc 주석에는 전용 구조와 formatting이 있지만 그 밖의 내용은 reStructuredText로 처리됩니다.
`Documentation` 여러 위치에는 일반 text 문서도 수천 개 있습니다. 일부는 시간이 지나면서 reStructuredText로 변환되겠지만 대부분은 plain text로 남을 가능성이 큽니다.
Sphinx 설치와 virtual environment
25-56현재 `Documentation/` 파일에서 사용하는 ReST markup은 Sphinx 3.4.3 이상으로 build하도록 작성되어 있습니다. Sphinx 요구 사항을 검사하는 script가 있으며 자세한 내용은 `sphinx-pre-install` 절을 참고합니다.
대부분의 distribution은 Sphinx를 제공하지만 toolchain이 민감해서 Sphinx나 다른 Python package를 upgrade한 뒤 문서 build가 깨지는 일이 드물지 않습니다. distribution 제공 버전과 다른 Sphinx를 사용하면 이 문제를 줄일 수 있습니다.
Python 3 packaging 방식에 따라 `virtualenv-3` 또는 `virtualenv`를 이용해 virtual environment 안에 Sphinx를 설치하는 방법을 권장합니다. 최신 Sphinx 설치 절차는 다음과 같습니다.
$ virtualenv sphinx_latest
$ . sphinx_latest/bin/activate
(sphinx_latest) $ pip install -r Documentation/sphinx/requirements.txt
`. sphinx_latest/bin/activate`를 실행하면 새 environment를 사용 중임을 나타내도록 prompt가 바뀝니다. 새 shell을 열었다면 문서를 build하기 전에 이 명령을 다시 실행해 virtual environment에 들어가야 합니다.
이미지 출력과 PDF·LaTeX build
57-78커널 문서 build system에는 GraphViz와 SVG 형식의 이미지를 처리하는 확장이 들어 있습니다. 자세한 내용은 `sphinx_kfigure` 절을 참고합니다.
이미지를 출력하려면 GraphViz와 ImageMagick package를 모두 설치해야 합니다. 설치하지 않아도 문서는 build되지만 출력에 이미지가 포함되지 않습니다.
PDF와 LaTeX build는 Sphinx 2.4 이상에서만 지원됩니다. 이 출력에는 `XeLaTeX` 3.14159265도 필요합니다. distribution에 따라 XeLaTeX가 동작하는 데 필요한 최소 기능을 제공하는 여러 `texlive` package를 추가로 설치해야 할 수 있습니다.
HTML의 수학 표현식
79-99일부 ReST page에는 수학 표현식이 있으며 Sphinx의 동작 방식 때문에 LaTeX 표기법으로 작성합니다. HTML 출력에서 수식을 렌더링하는 방법은 두 가지입니다.
- `imgmath` 확장은 수학 표현식을 이미지로 변환해 HTML page에 삽입합니다.
- `mathjax` 확장은 JavaScript를 실행할 수 있는 web browser에 수학 렌더링을 맡깁니다.
kernel 6.1 이전 문서에서는 imgmath만 사용할 수 있었고 amsfonts, amsmath를 비롯한 많은 texlive package가 필요했습니다. kernel 6.1부터는 texlive package를 설치하지 않고도 수학 표현식이 포함된 HTML page를 build할 수 있습니다. 자세한 내용은 `Choice of Math Renderer` 절을 참고합니다.
두 확장의 공식 문서는 Sphinx의 `sphinx.ext.imgmath`와 `sphinx.ext.mathjax` 항목에 연결되어 있습니다.
Sphinx dependency 자동 검사
100-133`./scripts/sphinx-pre-install`은 Sphinx dependency를 자동으로 검사합니다. distribution을 인식하면 해당 환경에서 사용할 설치 명령도 안내합니다.
$ ./scripts/sphinx-pre-install
Checking if the needed tools for Fedora release 26 (Twenty Six) are available
Warning: better to also install "texlive-luatex85".
You should run:
sudo dnf install -y texlive-luatex85
/usr/bin/virtualenv sphinx_2.4.4
. sphinx_2.4.4/bin/activate
pip install -r Documentation/sphinx/requirements.txt
Can't build as 1 mandatory dependency is missing at ./scripts/sphinx-pre-install line 468.
기본적으로 HTML과 PDF의 모든 요구 사항을 검사하며 이미지, 수학 표현식, LaTeX build 요구 사항도 포함합니다. Python virtual environment를 사용할 것으로 가정하고, HTML build에 필요한 항목은 mandatory, 나머지는 optional로 판단합니다.
- `--no-pdf`는 PDF 요구 사항 검사를 끕니다.
- `--no-virtualenv`는 Python virtual environment 대신 OS package로 Sphinx를 사용합니다.
최소 지원 Sphinx 버전 검사
134-157Sphinx build system을 변경할 때는 최소 지원 버전이 계속 동작하는지 확인해야 합니다. Python 3.13 이상에서는 그 버전을 설치할 수 없으므로 최신 distribution에서 이 검사가 점점 어려워지고 있습니다.
`Documentation/process/changes.rst`에 정의된 가장 낮은 지원 Python 버전으로 venv를 만들고 최소 요구 사항을 설치해 검사할 수 있습니다.
/usr/bin/python3.9 -m venv sphinx_min
. sphinx_min/bin/activate
pip install -r Documentation/sphinx/min_requirements.txt
더 포괄적인 검사는 다음 script로 수행합니다.
scripts/test_doc_build.py
`scripts/test_doc_build.py`는 지원 버전마다 Python venv 하나를 만들며, 선택적으로 일정 범위의 Sphinx 버전으로 문서를 build합니다.
문서 build 명령과 make 변수
158-200일반적인 문서 생성 방법은 `make htmldocs` 또는 `make pdfdocs`입니다. 다른 형식은 `make help`의 documentation 절에서 확인할 수 있습니다. 출력은 `Documentation/output` 아래의 형식별 subdirectory에 저장됩니다.
문서 생성에는 `sphinx-build`가 필요합니다. PDF 출력에는 `XeLaTeX`와 ImageMagick의 `convert(1)`도 필요합니다. 이러한 도구는 널리 배포되며 distribution package로 제공됩니다. Inkscape의 `inkscape(1)`도 설치하면 특히 kernel 5.18 이후 PDF에 삽입되는 이미지 품질이 좋아집니다.
- `SPHINXOPTS` make variable로 Sphinx option을 추가합니다. 예를 들어 `make SPHINXOPTS=-v htmldocs`는 더 자세한 출력을 표시합니다.
- `DOCS_CSS` make variable로 추가 CSS overlay 파일을 전달해 HTML layout을 사용자 정의합니다.
- 기본 HTML theme는 Sphinx에 포함된 `Alabaster`입니다. `DOCS_THEME` make variable로 다른 theme을 선택할 수 있습니다.
- RTD theme을 사용하려면 Sphinx 버전에 따라 `pip install sphinx_rtd_theme`으로 별도 설치해야 합니다.
- `SPHINXDIRS`는 일부 문서만 시험 build할 때 사용합니다. `make SPHINXDIRS=doc-guide htmldocs`는 `Documentation/doc-guide` 아래만 build합니다. 지정 가능한 subdirectory는 `make help`에서 확인합니다.
- `make cleandocs`는 생성한 문서를 제거합니다.
수학 renderer 선택
201-232kernel 6.1부터 `mathjax`는 HTML 출력의 fallback 수학 renderer로 동작합니다. 이 fallback에는 Sphinx 1.8 이상이 필요합니다.
사용 가능한 명령에 따라 renderer를 다음과 같이 선택합니다.
사용 가능한 명령에 따라 imgmath 또는 mathjax를 선택합니다.
`SPHINX_IMGMATH` environment variable을 설정하면 자동 선택을 덮어쓸 수 있습니다.
environment variable 값으로 자동 renderer 선택을 덮어씁니다.
새 문서 추가하기
233-257새 문서를 추가하는 기본 절차는 `Documentation` 아래에 `.rst` 파일을 만들고 `Documentation/index.rst`의 Sphinx main `TOC tree`에서 그 파일을 참조하는 것입니다.
간단한 문서에는 이 절차만으로 충분합니다. 더 큰 문서는 새 subdirectory를 만들거나 기존 것을 사용하는 편이 좋습니다. 예를 들어 graphics subsystem 문서는 `Documentation/gpu` 아래의 여러 `.rst` 파일로 나뉘며 자체 `toctree`를 가진 별도 `index.rst`가 main index에서 참조됩니다.
사용 가능한 기능은 Sphinx와 reStructuredText 문서를 참고합니다. Sphinx `reStructuredText Primer`는 ReST 입문에 적합하며, Sphinx 전용 markup construct 문서도 함께 확인할 수 있습니다.
커널 문서 작성 지침
258-308- reStructuredText markup을 지나치게 사용하지 말고 단순하게 유지합니다. 문서는 대체로 plain text여야 하며 다른 형식으로 변환할 수 있을 만큼만 formatting을 일관되게 적용합니다.
- 기존 문서를 reStructuredText로 바꿀 때 formatting 변경을 최소화합니다.
- 변환할 때 formatting만 바꾸지 말고 내용도 최신화합니다.
heading 장식은 다음 순서를 따릅니다. 문서 title은 위아래에 `=`를 둡니다.
==============
Document title
==============
chapter는 아래에 `=`를 둡니다.
Chapters
========
section은 아래에 `-`를 둡니다.
Section
-------
subsection은 아래에 `~`를 둡니다.
Subsection
~~~~~~~~~~
RST 자체는 고정된 장식 순서를 강제하지 않고 문서에서 처음 나타난 순서를 따릅니다. 그래도 상위 수준의 순서를 전체 문서에서 통일하면 구조를 파악하기 쉽습니다.
syntax highlighting이 필요하지 않은 고정 폭 text block, 특히 짧은 code나 use-case 예제에는 `::`를 사용합니다. highlighting이 유용한 긴 code에는 `.. code-block:: <language>`를 사용합니다. 문장 안의 짧은 code snippet은 이중 backtick으로 감쌉니다.
Sphinx C Domain
309-338`c`라는 이름의 Sphinx C Domain은 C API 문서에 적합합니다. 함수 prototype은 다음과 같이 작성합니다.
.. code-block:: rst
.. c:function:: int ioctl( int fd, int request )
kernel-doc의 C domain에는 추가 기능이 있습니다. `open`이나 `ioctl`처럼 흔한 함수 이름의 reference name을 바꿀 수 있습니다.
.. code-block:: rst
.. c:function:: int ioctl( int fd, int request )
:name: VIDIOC_LOG_STATUS
출력에는 함수 이름 `ioctl`이 그대로 남지만 reference name은 `ioctl`에서 `VIDIOC_LOG_STATUS`로 바뀝니다. 이 함수의 index entry도 `VIDIOC_LOG_STATUS`로 변경됩니다.
함수 문서의 교차 참조를 만들기 위해 `c:func:`를 직접 사용할 필요는 없습니다. 문서 build system의 Sphinx 확장이 해당 함수 이름의 index entry가 있으면 `function()` 표기를 자동으로 교차 참조로 바꿉니다. kernel 문서에 불필요한 `c:func:`가 있다면 제거해도 됩니다.
표 형식과 flat-table 기능
339-389reStructuredText에는 여러 table 문법이 있습니다. 커널 스타일은 `simple table` 또는 `grid table` 문법을 우선합니다. 자세한 내용은 docutils의 reStructuredText table syntax 문서를 참고합니다.
`list-table` 형식은 일반적인 Sphinx ASCII-art 형식으로 배치하기 어려운 표에 유용할 수 있습니다. 하지만 plain-text 문서 독자가 이해하기는 거의 불가능하므로 강한 근거가 없으면 피해야 합니다.
`flat-table`은 `list-table`과 비슷한 2단계 list이며 다음 기능을 추가합니다.
- `cspan` role은 cell을 추가 column까지 확장합니다.
- `rspan` role은 cell을 추가 row까지 확장합니다.
- table row의 오른쪽에 cell이 부족하면 마지막 cell을 자동으로 span합니다. `:fill-cells:` option을 사용하면 span 대신 빈 cell을 자동 삽입합니다.
option에는 header row 수를 지정하는 `:header-rows:`, stub column 수를 지정하는 `:stub-columns:`, column 폭 목록인 `:widths:`, 누락 cell을 채우는 `:fill-cells:`가 있습니다. role에는 추가 column 수인 `:cspan:`과 추가 row 수인 `:rspan:`이 있습니다.
단계형 list의 첫 번째 수준은 table row입니다. 각 row 안에서는 cell list만 허용되며 comment `..`와 target, 예를 들어 `:ref:`last row <last row>`` 같은 참조는 예외입니다.
flat-table 예제와 렌더 결과
390-433다음 markup은 네 column의 `flat-table`을 만들고, 자동 span과 `rspan`·`cspan`, 마지막 row target을 사용합니다.
.. code-block:: rst
.. flat-table:: table title
:widths: 2 1 1 3
* - head col 1
- head col 2
- head col 3
- head col 4
* - row 1
- field 1.1
- field 1.2 with autospan
* - row 2
- field 2.1
- :rspan:`1` :cspan:`1` field 2.2 - 3.3
* .. _`last row`:
- row 3
원문은 이어서 같은 directive를 실제 렌더 결과로 삽입합니다. 첫 row의 `field 1.2`는 오른쪽 빈 cell로 자동 확장되고, `field 2.2 - 3.3`은 두 row와 두 column을 차지하며 마지막 row에는 `last row` target이 붙습니다.
.. flat-table:: table title
:widths: 2 1 1 3
* - head col 1
- head col 2
- head col 3
- head col 4
* - row 1
- field 1.1
- field 1.2 with autospan
* - row 2
- field 2.1
- :rspan:`1` :cspan:`1` field 2.2 - 3.3
* .. _`last row`:
- row 3
문서 간 교차 참조
434-460한 문서 page에서 다른 page를 참조할 때는 별도 문법 없이 문서 파일 경로를 적으면 됩니다. 절대 또는 상대 경로를 사용할 수 있고, 절대 경로는 `Documentation/`으로 시작합니다. `.rst` 확장자는 반드시 포함해야 합니다.
See Documentation/doc-guide/sphinx.rst. This always works.
Take a look at sphinx.rst, which is at this same directory.
Read ../sphinx.rst, which is one directory above.
링크 표시 text를 문서 title과 다르게 하고 싶다면 Sphinx의 `doc` role을 사용합니다.
See :doc:`my custom link text for document sphinx <sphinx>`.
대부분의 경우 단순 경로 방식이 더 깔끔하고 source file 독자에게도 적합합니다. 가치가 없는 `:doc:` 사용은 문서 경로로 바꿔도 됩니다. kernel-doc 함수나 타입을 교차 참조하는 방법은 `Documentation/doc-guide/kernel-doc.rst`를 참고합니다.
commit 참조
461-469git commit 참조는 다음 형식 중 하나로 작성하면 자동으로 hyperlink가 생성됩니다. 짧은 hash만 적거나 hash 뒤에 괄호와 commit subject를 함께 적을 수 있습니다.
commit 72bf4f1767f0
commit 72bf4f1767f0 ("net: do not leave an empty skb in write queue")
figure와 image directive
470-509이미지를 추가할 때는 `kernel-figure`와 `kernel-image` directive를 사용합니다. 확장 가능한 SVG figure를 넣는 예는 다음과 같습니다.
.. kernel-figure:: svg_image.svg
:alt: simple SVG image
SVG image example
외부 SVG 파일, alt text와 caption의 연결을 구조화해 표시합니다.
원문에서 실제로 렌더하는 같은 SVG directive는 다음과 같습니다.
.. kernel-figure:: svg_image.svg
:alt: simple SVG image
SVG image example
실제 kernel-figure directive가 SVG asset을 확장 가능한 figure로 렌더합니다.
kernel figure와 image directive는 DOT 형식 파일도 지원합니다. DOT 언어는 Graphviz의 dot guide와 DOT language 문서를 참고합니다.
`hello.dot`을 삽입하는 간단한 예는 다음과 같습니다.
.. kernel-figure:: hello.dot
:alt: hello world
DOT's hello world example
외부 DOT 파일, alt text와 caption의 연결을 구조화해 표시합니다.
원문에서 실제로 렌더하는 같은 DOT directive는 다음과 같습니다.
.. kernel-figure:: hello.dot
:alt: hello world
DOT's hello world example
실제 kernel-figure directive가 DOT asset을 Graphviz figure로 렌더합니다.
내장 DOT markup 렌더링
510-539Graphviz DOT처럼 문서에 직접 넣는 render markup은 `kernel-render` directive로 제공합니다. 다음 digraph는 `bar`에서 `baz`로 향하는 edge 하나를 정의합니다.
.. kernel-render:: DOT
:alt: foobar digraph
:caption: Embedded **DOT** (Graphviz) code
digraph foo {
"bar" -> "baz";
}
`digraph foo`에 정의된 단일 방향 edge를 구조화해 표시합니다.
렌더 결과는 설치된 도구에 따라 달라집니다. Graphviz가 있으면 vector image가 표시되고, 없으면 raw markup이 literal block으로 삽입됩니다. 원문에서 실제 렌더하는 directive는 다음과 같습니다.
.. kernel-render:: DOT
:alt: foobar digraph
:caption: Embedded **DOT** (Graphviz) code
digraph foo {
"bar" -> "baz";
}
`kernel-render`는 figure directive의 모든 option과 `caption` option을 지원합니다. caption 값이 있으면 figure node를, 없으면 image node를 삽입합니다. 해당 결과를 참조하려면 caption도 필요합니다.
내장 SVG markup 렌더링
540-562SVG markup도 `kernel-render:: SVG` 안에 직접 넣을 수 있습니다. 다음 축약 예는 caption과 alt text, XML·SVG element를 포함합니다.
.. kernel-render:: SVG
:caption: Embedded **SVG** markup
:alt: so-nw-arrow
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ...>
...
</svg>
원문에서 실제로 렌더하는 전체 예는 700×400 viewBox 안에 대각선과 polygon arrowhead를 그려 북서 방향 화살표를 만듭니다.
.. kernel-render:: SVG
:caption: Embedded **SVG** markup
:alt: so-nw-arrow
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
version="1.1" baseProfile="full" width="70px" height="40px" viewBox="0 0 700 400">
<line x1="180" y1="370" x2="500" y2="50" stroke="black" stroke-width="15px"/>
<polygon points="585 0 525 25 585 50" transform="rotate(135 525 25)"/>
</svg>
line과 polygon으로 구성된 북서 방향 화살표의 의미를 구조화해 표시합니다.
요약과 해설
sphinx.rst:1-562Sphinx 설치·build, 수학 renderer, 커널 ReST 작성 규칙, C domain, 표, 교차 참조와 image·render directive를 설명합니다. 영어 원문 전체와 한국어 전문 번역을 함께 제공하며 명령, version, make variable, source path, 표, 역할, directive, footnote와 원문 줄 좌표를 보존합니다.