# 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"))1920# Minimal supported version21needs_sphinx = "3.4.3"2223# Get Sphinx version24major, minor, patch = sphinx.version_info[:3] # pylint: disable=I11012526# Include_patterns were added on Sphinx 5.127if (major < 5) or (major == 5 and minor < 1):28has_include_patterns = False29else:30has_include_patterns = True31# Include patterns that don't contain directory names, in glob format32include_patterns = ["**.rst"]3334# Location of Documentation/ directory35doctree = os.path.abspath(".")3637# Exclude of patterns that don't contain directory names, in glob format.38exclude_patterns = []3940# List of patterns that contain directory names in glob format.41dyn_include_patterns = []42dyn_exclude_patterns = ["output"]4344# Currently, only netlink/specs has a parser for yaml.45# Prefer using include patterns if available, as it is faster46if has_include_patterns:47dyn_include_patterns.append("netlink/specs/*.yaml")48else:49dyn_exclude_patterns.append("netlink/*.yaml")50dyn_exclude_patterns.append("devicetree/bindings/**.yaml")51dyn_exclude_patterns.append("core-api/kho/bindings/**.yaml")5253# Properly handle directory patterns and LaTeX docs54# -------------------------------------------------5556def config_init(app, config):57"""58Initialize path-dependent variabled5960On Sphinx, all directories are relative to what it is passed as61SOURCEDIR parameter for sphinx-build. Due to that, all patterns62that have directory names on it need to be dynamically set, after63converting them to a relative patch.6465As Sphinx doesn't include any patterns outside SOURCEDIR, we should66exclude relative patterns that start with "../".67"""6869# setup include_patterns dynamically70if has_include_patterns:71for p in dyn_include_patterns:72full = os.path.join(doctree, p)7374rel_path = os.path.relpath(full, start=app.srcdir)75if rel_path.startswith("../"):76continue7778config.include_patterns.append(rel_path)7980# setup exclude_patterns dynamically81for p in dyn_exclude_patterns:82full = os.path.join(doctree, p)8384rel_path = os.path.relpath(full, start=app.srcdir)85if rel_path.startswith("../"):86continue8788config.exclude_patterns.append(rel_path)8990# LaTeX and PDF output require a list of documents with are dependent91# of the app.srcdir. Add them here9293# Handle the case where SPHINXDIRS is used94if not os.path.samefile(doctree, app.srcdir):95# Add a tag to mark that the build is actually a subproject96tags.add("subproject")9798# get index.rst, if it exists99doc = os.path.basename(app.srcdir)100fname = "index"101if os.path.exists(os.path.join(app.srcdir, fname + ".rst")):102latex_documents.append((fname, doc + ".tex",103"Linux %s Documentation" % doc.capitalize(),104"The kernel development community",105"manual"))106return107108# When building all docs, or when a main index.rst doesn't exist, seek109# for it on subdirectories110for doc in os.listdir(app.srcdir):111fname = os.path.join(doc, "index")112if not os.path.exists(os.path.join(app.srcdir, fname + ".rst")):113continue114115has = False116for l in latex_documents:117if l[0] == fname:118has = True119break120121if not has:122latex_documents.append((fname, doc + ".tex",123"Linux %s Documentation" % doc.capitalize(),124"The kernel development community",125"manual"))126127# helper128# ------129130131def have_command(cmd):132"""Search ``cmd`` in the ``PATH`` environment.133134If found, return True.135If not found, return False.136"""137return shutil.which(cmd) is not None138139140# -- General configuration ------------------------------------------------141142# Add any Sphinx extensions in alphabetic order143extensions = [144"automarkup",145"kernel_abi",146"kerneldoc",147"kernel_feat",148"kernel_include",149"kfigure",150"maintainers_include",151"parser_yaml",152"rstFlatTable",153"sphinx.ext.autosectionlabel",154"sphinx.ext.ifconfig",155"translations",156]157# Since Sphinx version 3, the C function parser is more pedantic with regards158# to type checking. Due to that, having macros at c:function cause problems.159# Those needed to be escaped by using c_id_attributes[] array160c_id_attributes = [161# GCC Compiler types not parsed by Sphinx:162"__restrict__",163164# include/linux/compiler_types.h:165"__iomem",166"__kernel",167"noinstr",168"notrace",169"__percpu",170"__rcu",171"__user",172"__force",173"__counted_by_le",174"__counted_by_be",175176# include/linux/compiler_attributes.h:177"__alias",178"__aligned",179"__aligned_largest",180"__always_inline",181"__assume_aligned",182"__cold",183"__attribute_const__",184"__copy",185"__pure",186"__designated_init",187"__visible",188"__printf",189"__scanf",190"__gnu_inline",191"__malloc",192"__mode",193"__no_caller_saved_registers",194"__noclone",195"__nonstring",196"__noreturn",197"__packed",198"__pure",199"__section",200"__always_unused",201"__maybe_unused",202"__used",203"__weak",204"noinline",205"__fix_address",206"__counted_by",207208# include/linux/memblock.h:209"__init_memblock",210"__meminit",211212# include/linux/init.h:213"__init",214"__ref",215216# include/linux/linkage.h:217"asmlinkage",218219# include/linux/btf.h220"__bpf_kfunc",221]222223# Ensure that autosectionlabel will produce unique names224autosectionlabel_prefix_document = True225autosectionlabel_maxdepth = 2226227# Load math renderer:228# For html builder, load imgmath only when its dependencies are met.229# mathjax is the default math renderer since Sphinx 1.8.230have_latex = have_command("latex")231have_dvipng = have_command("dvipng")232load_imgmath = have_latex and have_dvipng233234# Respect SPHINX_IMGMATH (for html docs only)235if "SPHINX_IMGMATH" in os.environ:236env_sphinx_imgmath = os.environ["SPHINX_IMGMATH"]237if "yes" in env_sphinx_imgmath:238load_imgmath = True239elif "no" in env_sphinx_imgmath:240load_imgmath = False241else:242sys.stderr.write("Unknown env SPHINX_IMGMATH=%s ignored.\n" % env_sphinx_imgmath)243244if load_imgmath:245extensions.append("sphinx.ext.imgmath")246math_renderer = "imgmath"247else:248math_renderer = "mathjax"249250# Add any paths that contain templates here, relative to this directory.251templates_path = ["sphinx/templates"]252253# The suffixes of source filenames that will be automatically parsed254source_suffix = {255".rst": "restructuredtext",256".yaml": "yaml",257}258259# The encoding of source files.260# source_encoding = 'utf-8-sig'261262# The master toctree document.263master_doc = "index"264265# General information about the project.266project = "The Linux Kernel"267copyright = "The kernel development community" # pylint: disable=W0622268author = "The kernel development community"269270# The version info for the project you're documenting, acts as replacement for271# |version| and |release|, also used in various other places throughout the272# built documents.273#274# In a normal build, version and release are set to KERNELVERSION and275# KERNELRELEASE, respectively, from the Makefile via Sphinx command line276# arguments.277#278# The following code tries to extract the information by reading the Makefile,279# when Sphinx is run directly (e.g. by Read the Docs).280try:281makefile_version = None282makefile_patchlevel = None283with open("../Makefile", encoding="utf=8") as fp:284for line in fp:285key, val = [x.strip() for x in line.split("=", 2)]286if key == "VERSION":287makefile_version = val288elif key == "PATCHLEVEL":289makefile_patchlevel = val290if makefile_version and makefile_patchlevel:291break292except Exception:293pass294finally:295if makefile_version and makefile_patchlevel:296version = release = makefile_version + "." + makefile_patchlevel297else:298version = release = "unknown version"299300301def get_cline_version():302"""303HACK: There seems to be no easy way for us to get at the version and304release information passed in from the makefile...so go pawing through the305command-line options and find it for ourselves.306"""307308c_version = c_release = ""309for arg in sys.argv:310if arg.startswith("version="):311c_version = arg[8:]312elif arg.startswith("release="):313c_release = arg[8:]314if c_version:315if c_release:316return c_version + "-" + c_release317return c_version318return version # Whatever we came up with before319320321# The language for content autogenerated by Sphinx. Refer to documentation322# for a list of supported languages.323#324# This is also used if you do content translation via gettext catalogs.325# Usually you set "language" from the command line for these cases.326language = "en"327328# There are two options for replacing |today|: either, you set today to some329# non-false value, then it is used:330# today = ''331# Else, today_fmt is used as the format for a strftime call.332# today_fmt = '%B %d, %Y'333334# The reST default role (used for this markup: `text`) to use for all335# documents.336# default_role = None337338# If true, '()' will be appended to :func: etc. cross-reference text.339# add_function_parentheses = True340341# If true, the current module name will be prepended to all description342# unit titles (such as .. function::).343# add_module_names = True344345# If true, sectionauthor and moduleauthor directives will be shown in the346# output. They are ignored by default.347# show_authors = False348349# The name of the Pygments (syntax highlighting) style to use.350pygments_style = "sphinx"351352# A list of ignored prefixes for module index sorting.353# modindex_common_prefix = []354355# If true, keep warnings as "system message" paragraphs in the built documents.356# keep_warnings = False357358# If true, `todo` and `todoList` produce output, else they produce nothing.359todo_include_todos = False360361primary_domain = "c"362highlight_language = "none"363364# -- Options for HTML output ----------------------------------------------365366# The theme to use for HTML and HTML Help pages. See the documentation for367# a list of builtin themes.368369# Default theme370html_theme = "alabaster"371html_css_files = []372373if "DOCS_THEME" in os.environ:374html_theme = os.environ["DOCS_THEME"]375376if html_theme in ["sphinx_rtd_theme", "sphinx_rtd_dark_mode"]:377# Read the Docs theme378try:379import sphinx_rtd_theme380381html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]382383# Add any paths that contain custom static files (such as style sheets) here,384# relative to this directory. They are copied after the builtin static files,385# so a file named "default.css" will overwrite the builtin "default.css".386html_css_files = [387"theme_overrides.css",388]389390# Read the Docs dark mode override theme391if html_theme == "sphinx_rtd_dark_mode":392try:393import sphinx_rtd_dark_mode # pylint: disable=W0611394395extensions.append("sphinx_rtd_dark_mode")396except ImportError:397html_theme = "sphinx_rtd_theme"398399if html_theme == "sphinx_rtd_theme":400# Add color-specific RTD normal mode401html_css_files.append("theme_rtd_colors.css")402403html_theme_options = {404"navigation_depth": -1,405}406407except ImportError:408html_theme = "alabaster"409410if "DOCS_CSS" in os.environ:411css = os.environ["DOCS_CSS"].split(" ")412413for l in css:414html_css_files.append(l)415416if html_theme == "alabaster":417html_theme_options = {418"description": get_cline_version(),419"page_width": "65em",420"sidebar_width": "15em",421"fixed_sidebar": "true",422"font_size": "inherit",423"font_family": "serif",424}425426sys.stderr.write("Using %s theme\n" % html_theme)427428# Add any paths that contain custom static files (such as style sheets) here,429# relative to this directory. They are copied after the builtin static files,430# so a file named "default.css" will overwrite the builtin "default.css".431html_static_path = ["sphinx-static"]432433# If true, Docutils "smart quotes" will be used to convert quotes and dashes434# to typographically correct entities. However, conversion of "--" to "—"435# is not always what we want, so enable only quotes.436smartquotes_action = "q"437438# Custom sidebar templates, maps document names to template names.439# Note that the RTD theme ignores this440html_sidebars = {"**": ["searchbox.html",441"kernel-toc.html",442"sourcelink.html"]}443444# about.html is available for alabaster theme. Add it at the front.445if html_theme == "alabaster":446html_sidebars["**"].insert(0, "about.html")447448# The name of an image file (relative to this directory) to place at the top449# of the sidebar.450html_logo = "images/logo.svg"451452# Output file base name for HTML help builder.453htmlhelp_basename = "TheLinuxKerneldoc"454455# -- Options for LaTeX output ---------------------------------------------456457latex_elements = {458# The paper size ('letterpaper' or 'a4paper').459"papersize": "a4paper",460"passoptionstopackages": dedent(r"""461\PassOptionsToPackage{svgnames}{xcolor}462"""),463# The font size ('10pt', '11pt' or '12pt').464"pointsize": "11pt",465# Needed to generate a .ind file466"printindex": r"\footnotesize\raggedright\printindex",467# Latex figure (float) alignment468# 'figure_align': 'htbp',469# Don't mangle with UTF-8 chars470"fontenc": "",471"inputenc": "",472"utf8extra": "",473# Set document margins474"sphinxsetup": dedent(r"""475hmargin=0.5in, vmargin=1in,476parsedliteralwraps=true,477verbatimhintsturnover=false,478"""),479#480# Some of our authors are fond of deep nesting; tell latex to481# cope.482#483"maxlistdepth": "10",484# For CJK One-half spacing, need to be in front of hyperref485"extrapackages": r"\usepackage{setspace}",486"fontpkg": dedent(r"""487\usepackage{fontspec}488\setmainfont{DejaVu Serif}489\setsansfont{DejaVu Sans}490\setmonofont{DejaVu Sans Mono}491\newfontfamily\headingfont{DejaVu Serif}492"""),493"preamble": dedent(r"""494% Load kerneldoc specific LaTeX settings495\input{kerneldoc-preamble.sty}496""")497}498499# This will be filled up by config-inited event500latex_documents = []501502# The name of an image file (relative to this directory) to place at the top of503# the title page.504# latex_logo = None505506# For "manual" documents, if this is true, then toplevel headings are parts,507# not chapters.508# latex_use_parts = False509510# If true, show page references after internal links.511# latex_show_pagerefs = False512513# If true, show URL addresses after external links.514# latex_show_urls = False515516# Documents to append as an appendix to all manuals.517# latex_appendices = []518519# If false, no module index is generated.520# latex_domain_indices = True521522# Additional LaTeX stuff to be copied to build directory523latex_additional_files = [524"sphinx/kerneldoc-preamble.sty",525]526527528# -- Options for manual page output ---------------------------------------529530# One entry per manual page. List of tuples531# (source start file, name, description, authors, manual section).532man_pages = [533(master_doc, "thelinuxkernel", "The Linux Kernel Documentation", [author], 1)534]535536# If true, show URL addresses after external links.537# man_show_urls = False538539540# -- Options for Texinfo output -------------------------------------------541542# Grouping the document tree into Texinfo files. List of tuples543# (source start file, target name, title, author,544# dir menu entry, description, category)545texinfo_documents = [(546master_doc,547"TheLinuxKernel",548"The Linux Kernel Documentation",549author,550"TheLinuxKernel",551"One line description of project.",552"Miscellaneous",553),]554555# -- Options for Epub output ----------------------------------------------556557# Bibliographic Dublin Core info.558epub_title = project559epub_author = author560epub_publisher = author561epub_copyright = copyright562563# A list of files that should not be packed into the epub file.564epub_exclude_files = ["search.html"]565566# =======567# rst2pdf568#569# Grouping the document tree into PDF files. List of tuples570# (source start file, target name, title, author, options).571#572# See the Sphinx chapter of https://ralsina.me/static/manual.pdf573#574# FIXME: Do not add the index file here; the result will be too big. Adding575# multiple PDF files here actually tries to get the cross-referencing right576# *between* PDF files.577pdf_documents = [578("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"),579]580581# kernel-doc extension configuration for running Sphinx directly (e.g. by Read582# the Docs). In a normal build, these are supplied from the Makefile via command583# line arguments.584kerneldoc_bin = "../scripts/kernel-doc.py"585kerneldoc_srctree = ".."586587def setup(app):588"""Patterns need to be updated at init time on older Sphinx versions"""589590app.connect('config-inited', config_init)591592593