xref: /linux/Documentation/conf.py (revision a592a36e49372172d7c7551ec19ed18184c935e1)
1# SPDX-License-Identifier: GPL-2.0-only
2# pylint: disable=C0103,C0209
3
4"""
5The Linux Kernel documentation build configuration file.
6"""
7
8import os
9import shutil
10import sys
11
12from  textwrap import dedent
13
14import sphinx
15
16# Location of Documentation/ directory
17kern_doc_dir = os.path.dirname(os.path.abspath(__file__))
18
19# Add location of Sphinx extensions
20sys.path.insert(0, os.path.join(kern_doc_dir, "sphinx"))
21
22# Allow sphinx.ext.autodoc to document files at tools and scripts
23sys.path.append(os.path.join(kern_doc_dir, "..", "tools"))
24sys.path.append(os.path.join(kern_doc_dir, "..", "scripts"))
25
26# Minimal supported version
27needs_sphinx = "3.4.3"
28
29# Get Sphinx version
30major, minor, patch = sphinx.version_info[:3]          # pylint: disable=I1101
31
32# Include_patterns were added on Sphinx 5.1
33if (major < 5) or (major == 5 and minor < 1):
34    has_include_patterns = False
35else:
36    has_include_patterns = True
37    # Include patterns that don't contain directory names, in glob format
38    include_patterns = ["**.rst"]
39
40# Exclude of patterns that don't contain directory names, in glob format.
41exclude_patterns = []
42
43# List of patterns that contain directory names in glob format.
44dyn_include_patterns = []
45dyn_exclude_patterns = ["output", "sphinx-includes"]
46
47# Currently, only netlink/specs has a parser for yaml.
48# Prefer using include patterns if available, as it is faster
49if has_include_patterns:
50    dyn_include_patterns.append("netlink/specs/*.yaml")
51else:
52    dyn_exclude_patterns.append("netlink/*.yaml")
53    dyn_exclude_patterns.append("devicetree/bindings/**.yaml")
54    dyn_exclude_patterns.append("core-api/kho/bindings/**.yaml")
55
56# Link to man pages
57manpages_url = 'https://man7.org/linux/man-pages/man{section}/{page}.{section}.html'
58
59# Properly handle directory patterns and LaTeX docs
60# -------------------------------------------------
61
62def config_init(app, config):
63    """
64    Initialize path-dependent variabled
65
66    On Sphinx, all directories are relative to what it is passed as
67    SOURCEDIR parameter for sphinx-build. Due to that, all patterns
68    that have directory names on it need to be dynamically set, after
69    converting them to a relative patch.
70
71    As Sphinx doesn't include any patterns outside SOURCEDIR, we should
72    exclude relative patterns that start with "../".
73    """
74
75    # setup include_patterns dynamically
76    if has_include_patterns:
77        for p in dyn_include_patterns:
78            full = os.path.join(kern_doc_dir, p)
79
80            rel_path = os.path.relpath(full, start=app.srcdir)
81            if rel_path.startswith("../"):
82                continue
83
84            config.include_patterns.append(rel_path)
85
86    # setup exclude_patterns dynamically
87    for p in dyn_exclude_patterns:
88        full = os.path.join(kern_doc_dir, p)
89
90        rel_path = os.path.relpath(full, start=app.srcdir)
91        if rel_path.startswith("../"):
92            continue
93
94        config.exclude_patterns.append(rel_path)
95
96    # LaTeX and PDF output require a list of documents with are dependent
97    # of the app.srcdir. Add them here
98
99    # Handle the case where SPHINXDIRS is used
100    if not os.path.samefile(kern_doc_dir, app.srcdir):
101        # Add a tag to mark that the build is actually a subproject
102        tags.add("subproject")
103
104        # get index.rst, if it exists
105        doc = os.path.basename(app.srcdir)
106        fname = "index"
107        if os.path.exists(os.path.join(app.srcdir, fname + ".rst")):
108            latex_documents.append((fname, doc + ".tex",
109                                    "Linux %s Documentation" % doc.capitalize(),
110                                    "The kernel development community",
111                                    "manual"))
112            return
113
114    # When building all docs, or when a main index.rst doesn't exist, seek
115    # for it on subdirectories
116    for doc in os.listdir(app.srcdir):
117        fname = os.path.join(doc, "index")
118        if not os.path.exists(os.path.join(app.srcdir, fname + ".rst")):
119            continue
120
121        has = False
122        for l in latex_documents:
123            if l[0] == fname:
124                has = True
125                break
126
127        if not has:
128            latex_documents.append((fname, doc + ".tex",
129                                    "Linux %s Documentation" % doc.capitalize(),
130                                    "The kernel development community",
131                                    "manual"))
132
133# helper
134# ------
135
136
137def have_command(cmd):
138    """Search ``cmd`` in the ``PATH`` environment.
139
140    If found, return True.
141    If not found, return False.
142    """
143    return shutil.which(cmd) is not None
144
145
146# -- General configuration ------------------------------------------------
147
148# Add any Sphinx extensions in alphabetic order
149extensions = [
150    "automarkup",
151    "kernel_abi",
152    "kerneldoc",
153    "kernel_feat",
154    "kernel_include",
155    "kfigure",
156    "maintainers_include",
157    "parser_yaml",
158    "rstFlatTable",
159    "sphinx.ext.autodoc",
160    "sphinx.ext.autosectionlabel",
161    "sphinx.ext.ifconfig",
162    "translations",
163]
164# Since Sphinx version 3, the C function parser is more pedantic with regards
165# to type checking. Due to that, having macros at c:function cause problems.
166# Those needed to be escaped by using c_id_attributes[] array
167c_id_attributes = [
168    # GCC Compiler types not parsed by Sphinx:
169    "__restrict__",
170
171    # include/linux/compiler_types.h:
172    "__iomem",
173    "__kernel",
174    "noinstr",
175    "notrace",
176    "__percpu",
177    "__rcu",
178    "__user",
179    "__force",
180    "__counted_by_le",
181    "__counted_by_be",
182
183    # include/linux/compiler_attributes.h:
184    "__alias",
185    "__aligned",
186    "__aligned_largest",
187    "__always_inline",
188    "__assume_aligned",
189    "__cold",
190    "__attribute_const__",
191    "__copy",
192    "__pure",
193    "__designated_init",
194    "__visible",
195    "__printf",
196    "__scanf",
197    "__gnu_inline",
198    "__malloc",
199    "__mode",
200    "__no_caller_saved_registers",
201    "__noclone",
202    "__nonstring",
203    "__noreturn",
204    "__packed",
205    "__pure",
206    "__section",
207    "__always_unused",
208    "__maybe_unused",
209    "__used",
210    "__weak",
211    "noinline",
212    "__fix_address",
213    "__counted_by",
214
215    # include/linux/memblock.h:
216    "__init_memblock",
217    "__meminit",
218
219    # include/linux/init.h:
220    "__init",
221    "__ref",
222
223    # include/linux/linkage.h:
224    "asmlinkage",
225
226    # include/linux/btf.h
227    "__bpf_kfunc",
228]
229
230# Ensure that autosectionlabel will produce unique names
231autosectionlabel_prefix_document = True
232autosectionlabel_maxdepth = 2
233
234# Load math renderer:
235# For html builder, load imgmath only when its dependencies are met.
236# mathjax is the default math renderer since Sphinx 1.8.
237have_latex = have_command("latex")
238have_dvipng = have_command("dvipng")
239load_imgmath = have_latex and have_dvipng
240
241# Respect SPHINX_IMGMATH (for html docs only)
242if "SPHINX_IMGMATH" in os.environ:
243    env_sphinx_imgmath = os.environ["SPHINX_IMGMATH"]
244    if "yes" in env_sphinx_imgmath:
245        load_imgmath = True
246    elif "no" in env_sphinx_imgmath:
247        load_imgmath = False
248    else:
249        sys.stderr.write("Unknown env SPHINX_IMGMATH=%s ignored.\n" % env_sphinx_imgmath)
250
251if load_imgmath:
252    extensions.append("sphinx.ext.imgmath")
253    math_renderer = "imgmath"
254else:
255    math_renderer = "mathjax"
256
257# Add any paths that contain templates here, relative to this directory.
258templates_path = ["sphinx/templates"]
259
260# The suffixes of source filenames that will be automatically parsed
261source_suffix = {
262    ".rst": "restructuredtext",
263    ".yaml": "yaml",
264}
265
266# The encoding of source files.
267# source_encoding = 'utf-8-sig'
268
269# The master toctree document.
270master_doc = "index"
271
272# General information about the project.
273project = "The Linux Kernel"
274copyright = "The kernel development community"         # pylint: disable=W0622
275author = "The kernel development community"
276
277# The version info for the project you're documenting, acts as replacement for
278# |version| and |release|, also used in various other places throughout the
279# built documents.
280#
281# In a normal build, version and release are set to KERNELVERSION and
282# KERNELRELEASE, respectively, from the Makefile via Sphinx command line
283# arguments.
284#
285# The following code tries to extract the information by reading the Makefile,
286# when Sphinx is run directly (e.g. by Read the Docs).
287try:
288    makefile_version = None
289    makefile_patchlevel = None
290    with open("../Makefile", encoding="utf=8") as fp:
291        for line in fp:
292            key, val = [x.strip() for x in line.split("=", 2)]
293            if key == "VERSION":
294                makefile_version = val
295            elif key == "PATCHLEVEL":
296                makefile_patchlevel = val
297            if makefile_version and makefile_patchlevel:
298                break
299except Exception:
300    pass
301finally:
302    if makefile_version and makefile_patchlevel:
303        version = release = makefile_version + "." + makefile_patchlevel
304    else:
305        version = release = "unknown version"
306
307
308def get_cline_version():
309    """
310    HACK: There seems to be no easy way for us to get at the version and
311    release information passed in from the makefile...so go pawing through the
312    command-line options and find it for ourselves.
313    """
314
315    c_version = c_release = ""
316    for arg in sys.argv:
317        if arg.startswith("version="):
318            c_version = arg[8:]
319        elif arg.startswith("release="):
320            c_release = arg[8:]
321    if c_version:
322        if c_release:
323            return c_version + "-" + c_release
324        return c_version
325    return version  # Whatever we came up with before
326
327
328# The language for content autogenerated by Sphinx. Refer to documentation
329# for a list of supported languages.
330#
331# This is also used if you do content translation via gettext catalogs.
332# Usually you set "language" from the command line for these cases.
333language = "en"
334
335# There are two options for replacing |today|: either, you set today to some
336# non-false value, then it is used:
337# today = ''
338# Else, today_fmt is used as the format for a strftime call.
339# today_fmt = '%B %d, %Y'
340
341# The reST default role (used for this markup: `text`) to use for all
342# documents.
343# default_role = None
344
345# If true, '()' will be appended to :func: etc. cross-reference text.
346# add_function_parentheses = True
347
348# If true, the current module name will be prepended to all description
349# unit titles (such as .. function::).
350# add_module_names = True
351
352# If true, sectionauthor and moduleauthor directives will be shown in the
353# output. They are ignored by default.
354# show_authors = False
355
356# The name of the Pygments (syntax highlighting) style to use.
357pygments_style = "sphinx"
358
359# A list of ignored prefixes for module index sorting.
360# modindex_common_prefix = []
361
362# If true, keep warnings as "system message" paragraphs in the built documents.
363# keep_warnings = False
364
365# If true, `todo` and `todoList` produce output, else they produce nothing.
366todo_include_todos = False
367
368primary_domain = "c"
369highlight_language = "none"
370
371# -- Options for HTML output ----------------------------------------------
372
373# The theme to use for HTML and HTML Help pages.  See the documentation for
374# a list of builtin themes.
375
376# Default theme
377html_theme = "alabaster"
378html_css_files = []
379
380if "DOCS_THEME" in os.environ:
381    html_theme = os.environ["DOCS_THEME"]
382
383if html_theme in ["sphinx_rtd_theme", "sphinx_rtd_dark_mode"]:
384    # Read the Docs theme
385    try:
386        import sphinx_rtd_theme
387
388        html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
389
390        # Add any paths that contain custom static files (such as style sheets) here,
391        # relative to this directory. They are copied after the builtin static files,
392        # so a file named "default.css" will overwrite the builtin "default.css".
393        html_css_files = [
394            "theme_overrides.css",
395        ]
396
397        # Read the Docs dark mode override theme
398        if html_theme == "sphinx_rtd_dark_mode":
399            try:
400                import sphinx_rtd_dark_mode            # pylint: disable=W0611
401
402                extensions.append("sphinx_rtd_dark_mode")
403            except ImportError:
404                html_theme = "sphinx_rtd_theme"
405
406        if html_theme == "sphinx_rtd_theme":
407            # Add color-specific RTD normal mode
408            html_css_files.append("theme_rtd_colors.css")
409
410        html_theme_options = {
411            "navigation_depth": -1,
412        }
413
414    except ImportError:
415        html_theme = "alabaster"
416
417if "DOCS_CSS" in os.environ:
418    css = os.environ["DOCS_CSS"].split(" ")
419
420    for l in css:
421        html_css_files.append(l)
422
423if html_theme == "alabaster":
424    html_theme_options = {
425        "description": get_cline_version(),
426        "page_width": "65em",
427        "sidebar_width": "15em",
428        "fixed_sidebar": "true",
429        "font_size": "inherit",
430        "font_family": "serif",
431    }
432
433sys.stderr.write("Using %s theme\n" % html_theme)
434
435# Add any paths that contain custom static files (such as style sheets) here,
436# relative to this directory. They are copied after the builtin static files,
437# so a file named "default.css" will overwrite the builtin "default.css".
438html_static_path = ["sphinx-static"]
439
440# If true, Docutils "smart quotes" will be used to convert quotes and dashes
441# to typographically correct entities.  However, conversion of "--" to "—"
442# is not always what we want, so enable only quotes.
443smartquotes_action = "q"
444
445# Custom sidebar templates, maps document names to template names.
446# Note that the RTD theme ignores this
447html_sidebars = {"**": ["searchbox.html",
448                        "kernel-toc.html",
449                        "sourcelink.html"]}
450
451# about.html is available for alabaster theme. Add it at the front.
452if html_theme == "alabaster":
453    html_sidebars["**"].insert(0, "about.html")
454
455# The name of an image file (relative to this directory) to place at the top
456# of the sidebar.
457html_logo = "images/logo.svg"
458
459# Output file base name for HTML help builder.
460htmlhelp_basename = "TheLinuxKerneldoc"
461
462# -- Options for LaTeX output ---------------------------------------------
463
464latex_elements = {
465    # The paper size ('letterpaper' or 'a4paper').
466    "papersize": "a4paper",
467    "passoptionstopackages": dedent(r"""
468        \PassOptionsToPackage{svgnames}{xcolor}
469    """),
470    # The font size ('10pt', '11pt' or '12pt').
471    "pointsize": "11pt",
472    # Needed to generate a .ind file
473    "printindex": r"\footnotesize\raggedright\printindex",
474    # Latex figure (float) alignment
475    # 'figure_align': 'htbp',
476    # Don't mangle with UTF-8 chars
477    "fontenc": "",
478    "inputenc": "",
479    "utf8extra": "",
480    # Set document margins
481    "sphinxsetup": dedent(r"""
482        hmargin=0.5in, vmargin=1in,
483        parsedliteralwraps=true,
484        verbatimhintsturnover=false,
485    """),
486    #
487    # Some of our authors are fond of deep nesting; tell latex to
488    # cope.
489    #
490    "maxlistdepth": "10",
491    # For CJK One-half spacing, need to be in front of hyperref
492    "extrapackages": r"\usepackage{setspace}",
493    "fontpkg": dedent(r"""
494        \usepackage{fontspec}
495        \setmainfont{DejaVu Serif}
496        \setsansfont{DejaVu Sans}
497        \setmonofont{DejaVu Sans Mono}
498        \newfontfamily\headingfont{DejaVu Serif}
499    """),
500    "preamble": dedent(r"""
501        % Load kerneldoc specific LaTeX settings
502        \input{kerneldoc-preamble.sty}
503    """)
504}
505
506# This will be filled up by config-inited event
507latex_documents = []
508
509# The name of an image file (relative to this directory) to place at the top of
510# the title page.
511# latex_logo = None
512
513# For "manual" documents, if this is true, then toplevel headings are parts,
514# not chapters.
515# latex_use_parts = False
516
517# If true, show page references after internal links.
518# latex_show_pagerefs = False
519
520# If true, show URL addresses after external links.
521# latex_show_urls = False
522
523# Documents to append as an appendix to all manuals.
524# latex_appendices = []
525
526# If false, no module index is generated.
527# latex_domain_indices = True
528
529# Additional LaTeX stuff to be copied to build directory
530latex_additional_files = [
531    "sphinx/kerneldoc-preamble.sty",
532]
533
534
535# -- Options for manual page output ---------------------------------------
536
537# One entry per manual page. List of tuples
538# (source start file, name, description, authors, manual section).
539man_pages = [
540    (master_doc, "thelinuxkernel", "The Linux Kernel Documentation", [author], 1)
541]
542
543# If true, show URL addresses after external links.
544# man_show_urls = False
545
546
547# -- Options for Texinfo output -------------------------------------------
548
549# Grouping the document tree into Texinfo files. List of tuples
550# (source start file, target name, title, author,
551#  dir menu entry, description, category)
552texinfo_documents = [(
553        master_doc,
554        "TheLinuxKernel",
555        "The Linux Kernel Documentation",
556        author,
557        "TheLinuxKernel",
558        "One line description of project.",
559        "Miscellaneous",
560    ),]
561
562# -- Options for Epub output ----------------------------------------------
563
564# Bibliographic Dublin Core info.
565epub_title = project
566epub_author = author
567epub_publisher = author
568epub_copyright = copyright
569
570# A list of files that should not be packed into the epub file.
571epub_exclude_files = ["search.html"]
572
573# =======
574# rst2pdf
575#
576# Grouping the document tree into PDF files. List of tuples
577# (source start file, target name, title, author, options).
578#
579# See the Sphinx chapter of https://ralsina.me/static/manual.pdf
580#
581# FIXME: Do not add the index file here; the result will be too big. Adding
582# multiple PDF files here actually tries to get the cross-referencing right
583# *between* PDF files.
584pdf_documents = [
585    ("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"),
586]
587
588kerneldoc_srctree = ".."
589
590# Add index link at the end of the root document for SPHINXDIRS builds.
591def add_subproject_index(app, docname, content):
592    # Only care about root documents
593    if docname != master_doc:
594        return
595
596    # Add the index link at the root of translations, but not at the root of
597    # individual translations. They have their own language specific links.
598    rel = os.path.relpath(app.srcdir, start=kern_doc_dir).split('/')
599    if rel[0] == 'translations' and len(rel) > 1:
600        return
601
602    # Only add the link for SPHINXDIRS HTML builds
603    if not app.builder.tags.has('subproject') or not app.builder.tags.has('html'):
604        return
605
606    # The include directive needs a relative path from the srcdir
607    rel = os.path.relpath(os.path.join(kern_doc_dir, 'sphinx-includes/subproject-index.rst'),
608                          start=app.srcdir)
609
610    content[0] += f'\n.. include:: {rel}\n\n'
611
612def setup(app):
613    """Patterns need to be updated at init time on older Sphinx versions"""
614
615    app.connect('config-inited', config_init)
616    app.connect('source-read', add_subproject_index)
617