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