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