# SPDX-License-Identifier: GPL-2.0-only1# pylint: disable=C0103,C020923"""4The Linux Kernel documentation build configuration file.5"""67import os8import shutil9import sys1011from textwrap import dedent1213import sphinx1415# If extensions (or modules to document with autodoc) are in another directory,16# add these directories to sys.path here. If the directory is relative to the17# documentation root, use os.path.abspath to make it absolute, like shown here.18sys.path.insert(0, os.path.abspath("sphinx"))1920from load_config import loadConfig # pylint: disable=C0413,E04012122# Minimal supported version23needs_sphinx = "3.4.3"2425# Get Sphinx version26major, minor, patch = sphinx.version_info[:3] # pylint: disable=I11012728# Include_patterns were added on Sphinx 5.129if (major < 5) or (major == 5 and minor < 1):30has_include_patterns = False31else:32has_include_patterns = True33# Include patterns that don't contain directory names, in glob format34include_patterns = ["**.rst"]3536# Location of Documentation/ directory37doctree = os.path.abspath(".")3839# Exclude of patterns that don't contain directory names, in glob format.40exclude_patterns = []4142# List of patterns that contain directory names in glob format.43dyn_include_patterns = []44dyn_exclude_patterns = ["output"]4546# Currently, only netlink/specs has a parser for yaml.47# Prefer using include patterns if available, as it is faster48if has_include_patterns:49dyn_include_patterns.append("netlink/specs/*.yaml")50else:51dyn_exclude_patterns.append("netlink/*.yaml")52dyn_exclude_patterns.append("devicetree/bindings/**.yaml")53dyn_exclude_patterns.append("core-api/kho/bindings/**.yaml")5455# Properly handle directory patterns and LaTeX docs56# -------------------------------------------------5758def config_init(app, config):59"""60Initialize path-dependent variabled6162On Sphinx, all directories are relative to what it is passed as63SOURCEDIR parameter for sphinx-build. Due to that, all patterns64that have directory names on it need to be dynamically set, after65converting them to a relative patch.6667As Sphinx doesn't include any patterns outside SOURCEDIR, we should68exclude relative patterns that start with "../".69"""7071# setup include_patterns dynamically72if has_include_patterns:73for p in dyn_include_patterns:74full = os.path.join(doctree, p)7576rel_path = os.path.relpath(full, start=app.srcdir)77if rel_path.startswith("../"):78continue7980config.include_patterns.append(rel_path)8182# setup exclude_patterns dynamically83for p in dyn_exclude_patterns:84full = os.path.join(doctree, p)8586rel_path = os.path.relpath(full, start=app.srcdir)87if rel_path.startswith("../"):88continue8990config.exclude_patterns.append(rel_path)9192# LaTeX and PDF output require a list of documents with are dependent93# of the app.srcdir. Add them here9495# When SPHINXDIRS is used, we just need to get index.rst, if it exists96if not os.path.samefile(doctree, app.srcdir):97doc = os.path.basename(app.srcdir)98fname = "index"99if os.path.exists(os.path.join(app.srcdir, fname + ".rst")):100latex_documents.append((fname, doc + ".tex",101"Linux %s Documentation" % doc.capitalize(),102"The kernel development community",103"manual"))104return105106# When building all docs, or when a main index.rst doesn't exist, seek107# for it on subdirectories108for doc in os.listdir(app.srcdir):109fname = os.path.join(doc, "index")110if not os.path.exists(os.path.join(app.srcdir, fname + ".rst")):111continue112113has = False114for l in latex_documents:115if l[0] == fname:116has = True117break118119if not has:120latex_documents.append((fname, doc + ".tex",121"Linux %s Documentation" % doc.capitalize(),122"The kernel development community",123"manual"))124125# helper126# ------127128129def have_command(cmd):130"""Search ``cmd`` in the ``PATH`` environment.131132If found, return True.133If not found, return False.134"""135return shutil.which(cmd) is not None136137138# -- General configuration ------------------------------------------------139140# Add any Sphinx extensions in alphabetic order141extensions = [142"automarkup",143"kernel_abi",144"kerneldoc",145"kernel_feat",146"kernel_include",147"kfigure",148"maintainers_include",149"parser_yaml",150"rstFlatTable",151"sphinx.ext.autosectionlabel",152"sphinx.ext.ifconfig",153"translations",154]155# Since Sphinx version 3, the C function parser is more pedantic with regards156# to type checking. Due to that, having macros at c:function cause problems.157# Those needed to be escaped by using c_id_attributes[] array158c_id_attributes = [159# GCC Compiler types not parsed by Sphinx:160"__restrict__",161162# include/linux/compiler_types.h:163"__iomem",164"__kernel",165"noinstr",166"notrace",167"__percpu",168"__rcu",169"__user",170"__force",171"__counted_by_le",172"__counted_by_be",173174# include/linux/compiler_attributes.h:175"__alias",176"__aligned",177"__aligned_largest",178"__always_inline",179"__assume_aligned",180"__cold",181"__attribute_const__",182"__copy",183"__pure",184"__designated_init",185"__visible",186"__printf",187"__scanf",188"__gnu_inline",189"__malloc",190"__mode",191"__no_caller_saved_registers",192"__noclone",193"__nonstring",194"__noreturn",195"__packed",196"__pure",197"__section",198"__always_unused",199"__maybe_unused",200"__used",201"__weak",202"noinline",203"__fix_address",204"__counted_by",205206# include/linux/memblock.h:207"__init_memblock",208"__meminit",209210# include/linux/init.h:211"__init",212"__ref",213214# include/linux/linkage.h:215"asmlinkage",216217# include/linux/btf.h218"__bpf_kfunc",219]220221# Ensure that autosectionlabel will produce unique names222autosectionlabel_prefix_document = True223autosectionlabel_maxdepth = 2224225# Load math renderer:226# For html builder, load imgmath only when its dependencies are met.227# mathjax is the default math renderer since Sphinx 1.8.228have_latex = have_command("latex")229have_dvipng = have_command("dvipng")230load_imgmath = have_latex and have_dvipng231232# Respect SPHINX_IMGMATH (for html docs only)233if "SPHINX_IMGMATH" in os.environ:234env_sphinx_imgmath = os.environ["SPHINX_IMGMATH"]235if "yes" in env_sphinx_imgmath:236load_imgmath = True237elif "no" in env_sphinx_imgmath:238load_imgmath = False239else:240sys.stderr.write("Unknown env SPHINX_IMGMATH=%s ignored.\n" % env_sphinx_imgmath)241242if load_imgmath:243extensions.append("sphinx.ext.imgmath")244math_renderer = "imgmath"245else:246math_renderer = "mathjax"247248# Add any paths that contain templates here, relative to this directory.249templates_path = ["sphinx/templates"]250251# The suffixes of source filenames that will be automatically parsed252source_suffix = {253".rst": "restructuredtext",254".yaml": "yaml",255}256257# The encoding of source files.258# source_encoding = 'utf-8-sig'259260# The master toctree document.261master_doc = "index"262263# General information about the project.264project = "The Linux Kernel"265copyright = "The kernel development community" # pylint: disable=W0622266author = "The kernel development community"267268# The version info for the project you're documenting, acts as replacement for269# |version| and |release|, also used in various other places throughout the270# built documents.271#272# In a normal build, version and release are set to KERNELVERSION and273# KERNELRELEASE, respectively, from the Makefile via Sphinx command line274# arguments.275#276# The following code tries to extract the information by reading the Makefile,277# when Sphinx is run directly (e.g. by Read the Docs).278try:279makefile_version = None280makefile_patchlevel = None281with open("../Makefile", encoding="utf=8") as fp:282for line in fp:283key, val = [x.strip() for x in line.split("=", 2)]284if key == "VERSION":285makefile_version = val286elif key == "PATCHLEVEL":287makefile_patchlevel = val288if makefile_version and makefile_patchlevel:289break290except Exception:291pass292finally:293if makefile_version and makefile_patchlevel:294version = release = makefile_version + "." + makefile_patchlevel295else:296version = release = "unknown version"297298299def get_cline_version():300"""301HACK: There seems to be no easy way for us to get at the version and302release information passed in from the makefile...so go pawing through the303command-line options and find it for ourselves.304"""305306c_version = c_release = ""307for arg in sys.argv:308if arg.startswith("version="):309c_version = arg[8:]310elif arg.startswith("release="):311c_release = arg[8:]312if c_version:313if c_release:314return c_version + "-" + c_release315return c_version316return version # Whatever we came up with before317318319# The language for content autogenerated by Sphinx. Refer to documentation320# for a list of supported languages.321#322# This is also used if you do content translation via gettext catalogs.323# Usually you set "language" from the command line for these cases.324language = "en"325326# There are two options for replacing |today|: either, you set today to some327# non-false value, then it is used:328# today = ''329# Else, today_fmt is used as the format for a strftime call.330# today_fmt = '%B %d, %Y'331332# The reST default role (used for this markup: `text`) to use for all333# documents.334# default_role = None335336# If true, '()' will be appended to :func: etc. cross-reference text.337# add_function_parentheses = True338339# If true, the current module name will be prepended to all description340# unit titles (such as .. function::).341# add_module_names = True342343# If true, sectionauthor and moduleauthor directives will be shown in the344# output. They are ignored by default.345# show_authors = False346347# The name of the Pygments (syntax highlighting) style to use.348pygments_style = "sphinx"349350# A list of ignored prefixes for module index sorting.351# modindex_common_prefix = []352353# If true, keep warnings as "system message" paragraphs in the built documents.354# keep_warnings = False355356# If true, `todo` and `todoList` produce output, else they produce nothing.357todo_include_todos = False358359primary_domain = "c"360highlight_language = "none"361362# -- Options for HTML output ----------------------------------------------363364# The theme to use for HTML and HTML Help pages. See the documentation for365# a list of builtin themes.366367# Default theme368html_theme = "alabaster"369html_css_files = []370371if "DOCS_THEME" in os.environ:372html_theme = os.environ["DOCS_THEME"]373374if html_theme in ["sphinx_rtd_theme", "sphinx_rtd_dark_mode"]:375# Read the Docs theme376try:377import sphinx_rtd_theme378379html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]380381# Add any paths that contain custom static files (such as style sheets) here,382# relative to this directory. They are copied after the builtin static files,383# so a file named "default.css" will overwrite the builtin "default.css".384html_css_files = [385"theme_overrides.css",386]387388# Read the Docs dark mode override theme389if html_theme == "sphinx_rtd_dark_mode":390try:391import sphinx_rtd_dark_mode # pylint: disable=W0611392393extensions.append("sphinx_rtd_dark_mode")394except ImportError:395html_theme = "sphinx_rtd_theme"396397if html_theme == "sphinx_rtd_theme":398# Add color-specific RTD normal mode399html_css_files.append("theme_rtd_colors.css")400401html_theme_options = {402"navigation_depth": -1,403}404405except ImportError:406html_theme = "alabaster"407408if "DOCS_CSS" in os.environ:409css = os.environ["DOCS_CSS"].split(" ")410411for l in css:412html_css_files.append(l)413414if html_theme == "alabaster":415html_theme_options = {416"description": get_cline_version(),417"page_width": "65em",418"sidebar_width": "15em",419"fixed_sidebar": "true",420"font_size": "inherit",421"font_family": "serif",422}423424sys.stderr.write("Using %s theme\n" % html_theme)425426# Add any paths that contain custom static files (such as style sheets) here,427# relative to this directory. They are copied after the builtin static files,428# so a file named "default.css" will overwrite the builtin "default.css".429html_static_path = ["sphinx-static"]430431# If true, Docutils "smart quotes" will be used to convert quotes and dashes432# to typographically correct entities. However, conversion of "--" to "—"433# is not always what we want, so enable only quotes.434smartquotes_action = "q"435436# Custom sidebar templates, maps document names to template names.437# Note that the RTD theme ignores this438html_sidebars = {"**": ["searchbox.html",439"kernel-toc.html",440"sourcelink.html"]}441442# about.html is available for alabaster theme. Add it at the front.443if html_theme == "alabaster":444html_sidebars["**"].insert(0, "about.html")445446# The name of an image file (relative to this directory) to place at the top447# of the sidebar.448html_logo = "images/logo.svg"449450# Output file base name for HTML help builder.451htmlhelp_basename = "TheLinuxKerneldoc"452453# -- Options for LaTeX output ---------------------------------------------454455latex_elements = {456# The paper size ('letterpaper' or 'a4paper').457"papersize": "a4paper",458"passoptionstopackages": dedent(r"""459\PassOptionsToPackage{svgnames}{xcolor}460"""),461# The font size ('10pt', '11pt' or '12pt').462"pointsize": "11pt",463# Needed to generate a .ind file464"printindex": r"\footnotesize\raggedright\printindex",465# Latex figure (float) alignment466# 'figure_align': 'htbp',467# Don't mangle with UTF-8 chars468"fontenc": "",469"inputenc": "",470"utf8extra": "",471# Set document margins472"sphinxsetup": dedent(r"""473hmargin=0.5in, vmargin=1in,474parsedliteralwraps=true,475verbatimhintsturnover=false,476"""),477#478# Some of our authors are fond of deep nesting; tell latex to479# cope.480#481"maxlistdepth": "10",482# For CJK One-half spacing, need to be in front of hyperref483"extrapackages": r"\usepackage{setspace}",484"fontpkg": dedent(r"""485\usepackage{fontspec}486\setmainfont{DejaVu Serif}487\setsansfont{DejaVu Sans}488\setmonofont{DejaVu Sans Mono}489\newfontfamily\headingfont{DejaVu Serif}490"""),491"preamble": dedent(r"""492% Load kerneldoc specific LaTeX settings493\input{kerneldoc-preamble.sty}494""")495}496497# This will be filled up by config-inited event498latex_documents = []499500# The name of an image file (relative to this directory) to place at the top of501# the title page.502# latex_logo = None503504# For "manual" documents, if this is true, then toplevel headings are parts,505# not chapters.506# latex_use_parts = False507508# If true, show page references after internal links.509# latex_show_pagerefs = False510511# If true, show URL addresses after external links.512# latex_show_urls = False513514# Documents to append as an appendix to all manuals.515# latex_appendices = []516517# If false, no module index is generated.518# latex_domain_indices = True519520# Additional LaTeX stuff to be copied to build directory521latex_additional_files = [522"sphinx/kerneldoc-preamble.sty",523]524525526# -- Options for manual page output ---------------------------------------527528# One entry per manual page. List of tuples529# (source start file, name, description, authors, manual section).530man_pages = [531(master_doc, "thelinuxkernel", "The Linux Kernel Documentation", [author], 1)532]533534# If true, show URL addresses after external links.535# man_show_urls = False536537538# -- Options for Texinfo output -------------------------------------------539540# Grouping the document tree into Texinfo files. List of tuples541# (source start file, target name, title, author,542# dir menu entry, description, category)543texinfo_documents = [(544master_doc,545"TheLinuxKernel",546"The Linux Kernel Documentation",547author,548"TheLinuxKernel",549"One line description of project.",550"Miscellaneous",551),]552553# -- Options for Epub output ----------------------------------------------554555# Bibliographic Dublin Core info.556epub_title = project557epub_author = author558epub_publisher = author559epub_copyright = copyright560561# A list of files that should not be packed into the epub file.562epub_exclude_files = ["search.html"]563564# =======565# rst2pdf566#567# Grouping the document tree into PDF files. List of tuples568# (source start file, target name, title, author, options).569#570# See the Sphinx chapter of https://ralsina.me/static/manual.pdf571#572# FIXME: Do not add the index file here; the result will be too big. Adding573# multiple PDF files here actually tries to get the cross-referencing right574# *between* PDF files.575pdf_documents = [576("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"),577]578579# kernel-doc extension configuration for running Sphinx directly (e.g. by Read580# the Docs). In a normal build, these are supplied from the Makefile via command581# line arguments.582kerneldoc_bin = "../scripts/kernel-doc.py"583kerneldoc_srctree = ".."584585# ------------------------------------------------------------------------------586# Since loadConfig overwrites settings from the global namespace, it has to be587# the last statement in the conf.py file588# ------------------------------------------------------------------------------589loadConfig(globals())590591592def setup(app):593"""Patterns need to be updated at init time on older Sphinx versions"""594595app.connect('config-inited', config_init)596597598