Documentation/doc-guide/sphinx.rst GitHub 원문 ↗

Linux 6.18.37 · Documentation Guide

Using Sphinx for Kernel Documentation

Sphinx 설치·build, 수학 renderer, 커널 ReST 작성 규칙, C domain, 표, 교차 참조와 image·render directive를 설명합니다.

Source pathDocumentation/doc-guide/sphinx.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

sphinx.rst:1-562

Sphinx 설치·build, 수학 renderer, 커널 ReST 작성 규칙, C domain, 표, 교차 참조와 image·render directive를 설명합니다. 영어 원문 전체와 한국어 전문 번역을 함께 제공하며 명령, version, make variable, source path, 표, 역할, directive, footnote와 원문 줄 좌표를 보존합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

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

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

커널 문서에서 Sphinx를 사용하는 방식

1-24

Linux 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-157

Sphinx 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-232

kernel 6.1부터 `mathjax`는 HTML 출력의 fallback 수학 renderer로 동작합니다. 이 fallback에는 Sphinx 1.8 이상이 필요합니다.

사용 가능한 명령에 따라 renderer를 다음과 같이 선택합니다.

HTML 수학 renderer 선택표
수학 renderer필수 명령이미지 형식
imgmathlatex, dvipngPNG (raster)
mathjax없음browser 렌더링

사용 가능한 명령에 따라 imgmath 또는 mathjax를 선택합니다.

`SPHINX_IMGMATH` environment variable을 설정하면 자동 선택을 덮어쓸 수 있습니다.

SPHINX_IMGMATH 설정 효과
설정renderer
SPHINX_IMGMATH=yesimgmath
SPHINX_IMGMATH=nomathjax

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-389

reStructuredText에는 여러 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-469

git 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 figure directive 구조
svg_image.svgalt: simple SVG imagecaption: SVG image example

외부 SVG 파일, alt text와 caption의 연결을 구조화해 표시합니다.

원문에서 실제로 렌더하는 같은 SVG directive는 다음과 같습니다.

.. kernel-figure::  svg_image.svg
   :alt:    simple SVG image

   SVG image example
SVG figure 렌더 경로
svg_image.svgkernel-figurescalable SVG figure

실제 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 파일 figure directive 구조
hello.dotalt: hello worldcaption: DOT hello world example

외부 DOT 파일, alt text와 caption의 연결을 구조화해 표시합니다.

원문에서 실제로 렌더하는 같은 DOT directive는 다음과 같습니다.

.. kernel-figure::  hello.dot
   :alt:    hello world

   DOT's hello world example
DOT figure 렌더 경로
hello.dotkernel-figureGraphviz figure

실제 kernel-figure directive가 DOT asset을 Graphviz figure로 렌더합니다.

내장 DOT markup 렌더링

510-539

Graphviz 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";
   }
DOT hello world 구조
barbaz

`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-562

SVG 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>
SVG 대각선 화살표
오른쪽 아래왼쪽 위 화살표 끝

line과 polygon으로 구성된 북서 방향 화살표의 의미를 구조화해 표시합니다.