# SPDX-License-Identifier: GPL-2.0-only1# pylint: disable=C0103,C020923"""4The Linux Kernel documentation build configuration file.5"""67import os8import shutil9import sys1011import sphinx1213# If extensions (or modules to document with autodoc) are in another directory,14# add these directories to sys.path here. If the directory is relative to the15# documentation root, use os.path.abspath to make it absolute, like shown here.16sys.path.insert(0, os.path.abspath("sphinx"))1718from load_config import loadConfig # pylint: disable=C0413,E04011920# 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 include/exclude patterns54# ----------------------------------------5556def update_patterns(app, config):57"""58On Sphinx, all directories are relative to what it is passed as59SOURCEDIR parameter for sphinx-build. Due to that, all patterns60that have directory names on it need to be dynamically set, after61converting them to a relative patch.6263As Sphinx doesn't include any patterns outside SOURCEDIR, we should64exclude relative patterns that start with "../".65"""6667# setup include_patterns dynamically68if has_include_patterns:69for p in dyn_include_patterns:70full = os.path.join(doctree, p)7172rel_path = os.path.relpath(full, start=app.srcdir)73if rel_path.startswith("../"):74continue7576config.include_patterns.append(rel_path)7778# setup exclude_patterns dynamically79for p in dyn_exclude_patterns:80full = os.path.join(doctree, p)8182rel_path = os.path.relpath(full, start=app.srcdir)83if rel_path.startswith("../"):84continue8586config.exclude_patterns.append(rel_path)878889# helper90# ------919293def have_command(cmd):94"""Search ``cmd`` in the ``PATH`` environment.9596If found, return True.97If not found, return False.98"""99return shutil.which(cmd) is not None100101102# -- General configuration ------------------------------------------------103104# Add any Sphinx extensions in alphabetic order105extensions = [106"automarkup",107"kernel_abi",108"kerneldoc",109"kernel_feat",110"kernel_include",111"kfigure",112"maintainers_include",113"parser_yaml",114"rstFlatTable",115"sphinx.ext.autosectionlabel",116"sphinx.ext.ifconfig",117"translations",118]119# Since Sphinx version 3, the C function parser is more pedantic with regards120# to type checking. Due to that, having macros at c:function cause problems.121# Those needed to be escaped by using c_id_attributes[] array122c_id_attributes = [123# GCC Compiler types not parsed by Sphinx:124"__restrict__",125126# include/linux/compiler_types.h:127"__iomem",128"__kernel",129"noinstr",130"notrace",131"__percpu",132"__rcu",133"__user",134"__force",135"__counted_by_le",136"__counted_by_be",137138# include/linux/compiler_attributes.h:139"__alias",140"__aligned",141"__aligned_largest",142"__always_inline",143"__assume_aligned",144"__cold",145"__attribute_const__",146"__copy",147"__pure",148"__designated_init",149"__visible",150"__printf",151"__scanf",152"__gnu_inline",153"__malloc",154"__mode",155"__no_caller_saved_registers",156"__noclone",157"__nonstring",158"__noreturn",159"__packed",160"__pure",161"__section",162"__always_unused",163"__maybe_unused",164"__used",165"__weak",166"noinline",167"__fix_address",168"__counted_by",169170# include/linux/memblock.h:171"__init_memblock",172"__meminit",173174# include/linux/init.h:175"__init",176"__ref",177178# include/linux/linkage.h:179"asmlinkage",180181# include/linux/btf.h182"__bpf_kfunc",183]184185# Ensure that autosectionlabel will produce unique names186autosectionlabel_prefix_document = True187autosectionlabel_maxdepth = 2188189# Load math renderer:190# For html builder, load imgmath only when its dependencies are met.191# mathjax is the default math renderer since Sphinx 1.8.192have_latex = have_command("latex")193have_dvipng = have_command("dvipng")194load_imgmath = have_latex and have_dvipng195196# Respect SPHINX_IMGMATH (for html docs only)197if "SPHINX_IMGMATH" in os.environ:198env_sphinx_imgmath = os.environ["SPHINX_IMGMATH"]199if "yes" in env_sphinx_imgmath:200load_imgmath = True201elif "no" in env_sphinx_imgmath:202load_imgmath = False203else:204sys.stderr.write("Unknown env SPHINX_IMGMATH=%s ignored.\n" % env_sphinx_imgmath)205206if load_imgmath:207extensions.append("sphinx.ext.imgmath")208math_renderer = "imgmath"209else:210math_renderer = "mathjax"211212# Add any paths that contain templates here, relative to this directory.213templates_path = ["sphinx/templates"]214215# The suffixes of source filenames that will be automatically parsed216source_suffix = {217".rst": "restructuredtext",218".yaml": "yaml",219}220221# The encoding of source files.222# source_encoding = 'utf-8-sig'223224# The master toctree document.225master_doc = "index"226227# General information about the project.228project = "The Linux Kernel"229copyright = "The kernel development community" # pylint: disable=W0622230author = "The kernel development community"231232# The version info for the project you're documenting, acts as replacement for233# |version| and |release|, also used in various other places throughout the234# built documents.235#236# In a normal build, version and release are are set to KERNELVERSION and237# KERNELRELEASE, respectively, from the Makefile via Sphinx command line238# arguments.239#240# The following code tries to extract the information by reading the Makefile,241# when Sphinx is run directly (e.g. by Read the Docs).242try:243makefile_version = None244makefile_patchlevel = None245with open("../Makefile", encoding="utf=8") as fp:246for line in fp:247key, val = [x.strip() for x in line.split("=", 2)]248if key == "VERSION":249makefile_version = val250elif key == "PATCHLEVEL":251makefile_patchlevel = val252if makefile_version and makefile_patchlevel:253break254except Exception:255pass256finally:257if makefile_version and makefile_patchlevel:258version = release = makefile_version + "." + makefile_patchlevel259else:260version = release = "unknown version"261262263def get_cline_version():264"""265HACK: There seems to be no easy way for us to get at the version and266release information passed in from the makefile...so go pawing through the267command-line options and find it for ourselves.268"""269270c_version = c_release = ""271for arg in sys.argv:272if arg.startswith("version="):273c_version = arg[8:]274elif arg.startswith("release="):275c_release = arg[8:]276if c_version:277if c_release:278return c_version + "-" + c_release279return c_version280return version # Whatever we came up with before281282283# The language for content autogenerated by Sphinx. Refer to documentation284# for a list of supported languages.285#286# This is also used if you do content translation via gettext catalogs.287# Usually you set "language" from the command line for these cases.288language = "en"289290# There are two options for replacing |today|: either, you set today to some291# non-false value, then it is used:292# today = ''293# Else, today_fmt is used as the format for a strftime call.294# today_fmt = '%B %d, %Y'295296# The reST default role (used for this markup: `text`) to use for all297# documents.298# default_role = None299300# If true, '()' will be appended to :func: etc. cross-reference text.301# add_function_parentheses = True302303# If true, the current module name will be prepended to all description304# unit titles (such as .. function::).305# add_module_names = True306307# If true, sectionauthor and moduleauthor directives will be shown in the308# output. They are ignored by default.309# show_authors = False310311# The name of the Pygments (syntax highlighting) style to use.312pygments_style = "sphinx"313314# A list of ignored prefixes for module index sorting.315# modindex_common_prefix = []316317# If true, keep warnings as "system message" paragraphs in the built documents.318# keep_warnings = False319320# If true, `todo` and `todoList` produce output, else they produce nothing.321todo_include_todos = False322323primary_domain = "c"324highlight_language = "none"325326# -- Options for HTML output ----------------------------------------------327328# The theme to use for HTML and HTML Help pages. See the documentation for329# a list of builtin themes.330331# Default theme332html_theme = "alabaster"333html_css_files = []334335if "DOCS_THEME" in os.environ:336html_theme = os.environ["DOCS_THEME"]337338if html_theme in ["sphinx_rtd_theme", "sphinx_rtd_dark_mode"]:339# Read the Docs theme340try:341import sphinx_rtd_theme342343html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]344345# Add any paths that contain custom static files (such as style sheets) here,346# relative to this directory. They are copied after the builtin static files,347# so a file named "default.css" will overwrite the builtin "default.css".348html_css_files = [349"theme_overrides.css",350]351352# Read the Docs dark mode override theme353if html_theme == "sphinx_rtd_dark_mode":354try:355import sphinx_rtd_dark_mode # pylint: disable=W0611356357extensions.append("sphinx_rtd_dark_mode")358except ImportError:359html_theme = "sphinx_rtd_theme"360361if html_theme == "sphinx_rtd_theme":362# Add color-specific RTD normal mode363html_css_files.append("theme_rtd_colors.css")364365html_theme_options = {366"navigation_depth": -1,367}368369except ImportError:370html_theme = "alabaster"371372if "DOCS_CSS" in os.environ:373css = os.environ["DOCS_CSS"].split(" ")374375for l in css:376html_css_files.append(l)377378if html_theme == "alabaster":379html_theme_options = {380"description": get_cline_version(),381"page_width": "65em",382"sidebar_width": "15em",383"fixed_sidebar": "true",384"font_size": "inherit",385"font_family": "serif",386}387388sys.stderr.write("Using %s theme\n" % html_theme)389390# 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".393html_static_path = ["sphinx-static"]394395# If true, Docutils "smart quotes" will be used to convert quotes and dashes396# to typographically correct entities. However, conversion of "--" to "—"397# is not always what we want, so enable only quotes.398smartquotes_action = "q"399400# Custom sidebar templates, maps document names to template names.401# Note that the RTD theme ignores this402html_sidebars = {"**": ["searchbox.html",403"kernel-toc.html",404"sourcelink.html"]}405406# about.html is available for alabaster theme. Add it at the front.407if html_theme == "alabaster":408html_sidebars["**"].insert(0, "about.html")409410# The name of an image file (relative to this directory) to place at the top411# of the sidebar.412html_logo = "images/logo.svg"413414# Output file base name for HTML help builder.415htmlhelp_basename = "TheLinuxKerneldoc"416417# -- Options for LaTeX output ---------------------------------------------418419latex_elements = {420# The paper size ('letterpaper' or 'a4paper').421"papersize": "a4paper",422# The font size ('10pt', '11pt' or '12pt').423"pointsize": "11pt",424# Latex figure (float) alignment425# 'figure_align': 'htbp',426# Don't mangle with UTF-8 chars427"inputenc": "",428"utf8extra": "",429# Set document margins430"sphinxsetup": """431hmargin=0.5in, vmargin=1in,432parsedliteralwraps=true,433verbatimhintsturnover=false,434""",435#436# Some of our authors are fond of deep nesting; tell latex to437# cope.438#439"maxlistdepth": "10",440# For CJK One-half spacing, need to be in front of hyperref441"extrapackages": r"\usepackage{setspace}",442# Additional stuff for the LaTeX preamble.443"preamble": """444% Use some font with UTF-8 support with XeLaTeX445\\usepackage{fontspec}446\\setsansfont{DejaVu Sans}447\\setromanfont{DejaVu Serif}448\\setmonofont{DejaVu Sans Mono}449""",450}451452# Load kerneldoc specific LaTeX settings453latex_elements["preamble"] += """454% Load kerneldoc specific LaTeX settings455\\input{kerneldoc-preamble.sty}456"""457458# Grouping the document tree into LaTeX files. List of tuples459# (source start file, target name, title,460# author, documentclass [howto, manual, or own class]).461# Sorted in alphabetical order462latex_documents = []463464# Add all other index files from Documentation/ subdirectories465for fn in os.listdir("."):466doc = os.path.join(fn, "index")467if os.path.exists(doc + ".rst"):468has = False469for l in latex_documents:470if l[0] == doc:471has = True472break473if not has:474latex_documents.append(475(476doc,477fn + ".tex",478"Linux %s Documentation" % fn.capitalize(),479"The kernel development community",480"manual",481)482)483484# The name of an image file (relative to this directory) to place at the top of485# the title page.486# latex_logo = None487488# For "manual" documents, if this is true, then toplevel headings are parts,489# not chapters.490# latex_use_parts = False491492# If true, show page references after internal links.493# latex_show_pagerefs = False494495# If true, show URL addresses after external links.496# latex_show_urls = False497498# Documents to append as an appendix to all manuals.499# latex_appendices = []500501# If false, no module index is generated.502# latex_domain_indices = True503504# Additional LaTeX stuff to be copied to build directory505latex_additional_files = [506"sphinx/kerneldoc-preamble.sty",507]508509510# -- Options for manual page output ---------------------------------------511512# One entry per manual page. List of tuples513# (source start file, name, description, authors, manual section).514man_pages = [515(master_doc, "thelinuxkernel", "The Linux Kernel Documentation", [author], 1)516]517518# If true, show URL addresses after external links.519# man_show_urls = False520521522# -- Options for Texinfo output -------------------------------------------523524# Grouping the document tree into Texinfo files. List of tuples525# (source start file, target name, title, author,526# dir menu entry, description, category)527texinfo_documents = [(528master_doc,529"TheLinuxKernel",530"The Linux Kernel Documentation",531author,532"TheLinuxKernel",533"One line description of project.",534"Miscellaneous",535),]536537# -- Options for Epub output ----------------------------------------------538539# Bibliographic Dublin Core info.540epub_title = project541epub_author = author542epub_publisher = author543epub_copyright = copyright544545# A list of files that should not be packed into the epub file.546epub_exclude_files = ["search.html"]547548# =======549# rst2pdf550#551# Grouping the document tree into PDF files. List of tuples552# (source start file, target name, title, author, options).553#554# See the Sphinx chapter of https://ralsina.me/static/manual.pdf555#556# FIXME: Do not add the index file here; the result will be too big. Adding557# multiple PDF files here actually tries to get the cross-referencing right558# *between* PDF files.559pdf_documents = [560("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"),561]562563# kernel-doc extension configuration for running Sphinx directly (e.g. by Read564# the Docs). In a normal build, these are supplied from the Makefile via command565# line arguments.566kerneldoc_bin = "../scripts/kernel-doc.py"567kerneldoc_srctree = ".."568569# ------------------------------------------------------------------------------570# Since loadConfig overwrites settings from the global namespace, it has to be571# the last statement in the conf.py file572# ------------------------------------------------------------------------------573loadConfig(globals())574575576def setup(app):577"""Patterns need to be updated at init time on older Sphinx versions"""578579app.connect('config-inited', update_patterns)580581582