From patchwork Wed Nov 25 15:45:29 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Trevor Woerner X-Patchwork-Id: 105670 Received: from mail-ej1-f51.google.com (mail-ej1-f51.google.com [209.85.218.51]) by mx.groups.io with SMTP id smtpd.msgproc01-g2.44584.1795621544106644023 for ; Wed, 25 Nov 2026 07:45:44 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@gmail.com header.s=20260707 header.b=D26Z/dxR; spf=pass (domain: gmail.com, ip: 209.85.218.51, mailfrom: twoerner@gmail.com) Received: by mail-ej1-f51.google.com with SMTP id a640c23a62f3a-c513a854320so106003166b.0 for ; Wed, 25 Nov 2026 07:45:43 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1795621542; x=1796226342; darn=lists.yoctoproject.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to:content-type; bh=6Fm5nINAbC3Tgnz6+RoJFnw6h7CDrH9VPBJx6b6JfDA=; b=D26Z/dxREodzSE+WSBpF95JRu26sQFMvLzakEDpgbZf4UA5rT5Xq48AQHOULA8f35u Mxqm7OZT3x0KxcP99dKmLAhYUuV802T31Cxrq/2tm6pcWOJikcCds7aiqHpUQiPryAZp mFJaHxwIsLRzqQakZc8W10prmTqCXxCkdRdPDV0Dl3FoPS3HMYhqk6ydCJxFPc9xQBPb hdiJ4z3AksyoEtPavna9207IO3a1x5A2blTLWp8IM1womDp/gkfZtF8Cl8V119NlYYbB HCMIhGZsWOoxjpRdIVAtCMqS9ksaWFUt/1mGbpyTNnRxb3GomfgTqNm2vfoj11mGN+HL 6ahg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795621542; x=1796226342; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-gg:x-gm-message-state:from:to :cc:subject:date:message-id:reply-to:content-type; bh=6Fm5nINAbC3Tgnz6+RoJFnw6h7CDrH9VPBJx6b6JfDA=; b=yGHQxbj7H5hXwrtzpO+Wz2W69Sdl8HTO0mcumJGwRfO+aFHWenOVgRFcJLkPaCxIOi +SyS8DeV4niZ6NWf6up9NdtTYIFILGCZq7LnuJfd2TZH/eIyCgpLqOnNUtphGXy8TGse ZpNzSYdqU05p0cCVULtutGJa8qoEovioMHcpaGxd7LaIOdlA3iuhLLpvhDV9zjqQOe/c r1R6g6fxJFahFjzc4IAjtPONBL7y/9Dz3vW+XeIuRnRS5lEkHYwagl/2m6ojSsafPcUW XpRpQylySwnGSHOfmApG8lk5d/Lvoh9Wzy0+XSBpsMgNNjQ7ryCC8CemlDsmMHsggCjz 4Zcg== X-Gm-Message-State: APuU4Z8O0BxHq+yavOBynd9IywAW0Tm4vGKP3uFs5POQy0bhqmBW+yOy R3w6JN43Q1Q/ZLLGF2GX2kYqVbRQDDOrHo4447YoK++oleeKKU1RejojUr5s7A== X-Gm-Gg: AZFdTZeX64+jWn0RsPgLh9jUJiCRohOXKnc77N8zRanzKWE0khqDz+2tbLVE7EyFhaX /W3QffoRG7gnqmjoDrnsPoKkQbQ7FZqv3AWsBBodCgsChkI1ec0bgw+OtZ45hkq2pbnX8B/Vl14 HLb93G7D5ZZ4c/z7SvMBBpV8kwvDQGmy6a9Wbu9ZNDfWGF2Mi4aF0eU1ddFDBKzLKwfpjcbSJt1 BaWjsfZK+8Y2agTR07si4QF27AhPaaupOTlQKHSmjXfCQPLUH8LZMtIbx5Zi77RAGFGDGr4OJMM aSt7SAhdwg+z4P16YqynCrf59ivbnVy7S/NmL7pPtKcfXRnHGUqPOKj8LW2YM/Yzz70xydyxTzP LxWARXBJW0LVAQKHL8J5qevXWJvNs7pORHsBceKAySngVi3gcEkkJr7ZFTNHwyCzzx62l+Nk+/X LWjEyHWybql4aIB1KWOXo/GuKzPVhGtJ5fKeeAI0u/xrjZn1WupltKQHom+q0cE5QKml5nYs9Ck UBuR9hChaUhuk7Hvuo/Kf3T7952bqkihW12JpSdDi+Ii2NZuCSbGyNFSpwpDRAc2SDqrAelxkEp zvezg2wPvjFrD8lYFdHLM0jSn8SGlBu57u4QZw7MCd5K0Ua8w1UM/9yOmZgPnKMTYXgrlufEcP6 Gg7c5uWNdE0JSyeph2E9fwsCJobk7Oi8= X-Received: by 2002:a17:907:7f9f:b0:c31:c767:ae0b with SMTP id a640c23a62f3a-c513a274be7mr1655265966b.0.1795621541694; Wed, 25 Nov 2026 07:45:41 -0800 (PST) Return-Path: Received: from localhost.localdomain (pppoe-209-91-167-254.vianet.ca. [209.91.167.254]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-c513aec5115sm651892066b.51.2026.11.25.07.45.40 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 25 Nov 2026 07:45:40 -0800 (PST) From: Trevor Woerner To: docs@lists.yoctoproject.org Subject: [PATCH 1/7] sphinx: carry a BitBake lexer as a local extension Date: Wed, 25 Nov 2026 10:45:29 -0500 Message-ID: <20261125154535.3486104-2-twoerner@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20261125154535.3486104-1-twoerner@gmail.com> References: <20261125154535.3486104-1-twoerner@gmail.com> MIME-Version: 1.0 List-Id: X-Webhook-Received: from 45-33-107-173.ip.linodeusercontent.com [45.33.107.173] by lin-tor-korg-lkml-alma10-1 with HTTPS for ; Wed, 25 Nov 2026 15:45:54 -0000 X-Groupsio-URL: https://lists.yoctoproject.org/g/docs/message/10836 BitBake's syntax changes from release to release, and the manuals describe each change as it lands. Pygments learns it only in its own releases, which builders install later still, so the highlighting of the manuals depends on whichever Pygments happens to be installed. This adds a local Sphinx extension carrying a BitBake lexer built from BitBake's own parser patterns, so the manuals are highlighted the same way wherever they are built and can follow the language as it changes. It performs tests at startup and registers itself only if no BitBake lexer is found, or the one found fails its tests. Otherwise the installed lexer is used. AI-Generated: codex/claude-opus 5.5 (xhigh) Signed-off-by: Trevor Woerner --- documentation/conf.py | 3 +- documentation/sphinx/bitbake-lexer.py | 432 ++++++++++++++++++++++++++ 2 files changed, 434 insertions(+), 1 deletion(-) create mode 100644 documentation/sphinx/bitbake-lexer.py diff --git a/documentation/conf.py b/documentation/conf.py index afa7f8d985f4..cdd554e30c0a 100644 --- a/documentation/conf.py +++ b/documentation/conf.py @@ -79,7 +79,8 @@ extensions = [ 'sphinx_copybutton', 'sphinx_tags', 'sphinxcontrib.rsvgconverter', - 'yocto-vars' + 'yocto-vars', + 'bitbake-lexer' ] # current_version = "dev" diff --git a/documentation/sphinx/bitbake-lexer.py b/documentation/sphinx/bitbake-lexer.py new file mode 100644 index 000000000000..5a323ffb943d --- /dev/null +++ b/documentation/sphinx/bitbake-lexer.py @@ -0,0 +1,432 @@ +"""BitBake lexer, carried with the manuals. + +BitBake's syntax changes from release to release, and the manuals describe +it as it changes. Carrying the lexer here keeps their highlighting in step +with the language, and the same wherever they are built, rather than +dependent on which Pygments happens to be installed. + +The patterns are BitBake's own, taken from its parser. Everything from the +imports to the end of the lexer class is identical to the lexer proposed +to Pygments in https://github.com/pygments/pygments/pull/3284, so a fix +belongs in both. + +setup() tests the installed lexer and registers this one only if no +BitBake lexer is found, or the one found fails its tests. Otherwise the +installed lexer is used. +""" + +import re + +from pygments.lexer import RegexLexer, bygroups, include, using, words +from pygments.lexers.python import PythonLexer +from pygments.lexers.shell import BashLexer +from pygments.token import Comment, Error, Keyword, Name, Operator, \ + Punctuation, String, Text, Whitespace + +__version__ = '2.0' + + +class _FragmentPythonLexer(PythonLexer): + """Lex a ``${@...}`` fragment without reporting its incompleteness. + + An inline Python expression is handed over in pieces, split around any + ``${VAR}`` expansions embedded in it, so a piece routinely begins or ends + mid-string and is not valid Python on its own. The error would be an + artefact of the splitting rather than a defect in the metadata. + + This is deliberately the only place errors are suppressed. Errors in + BitBake's own syntax, and in a complete shell or Python function body, + are reported. + """ + + def get_tokens_unprocessed(self, text, stack=('root',)): + for index, token, value in super().get_tokens_unprocessed(text, stack): + yield index, Text if token is Error else token, value + + +# --------------------------------------------------------------------------- +# Validity is decided by BitBake, never by this file. +# +# Each pattern is BitBake's own statement regex from ``bb.parse.parse_py``, +# mechanically adapted, and used below only as a zero-width guard: a rule +# fires when and only when BitBake's parser would accept the line. The token +# spans are then chosen separately, which is the part a lexer is for. +# +# Three adaptations are applied, each because BitBake matches one +# already-assembled logical line while a lexer sees raw file text: +# +# \s -> [ \t] its \s can never meet a newline, because +# the file has already been split into lines +# . -> (?:[^\n]|\\[ \t]*\n) continuations are joined before BitBake +# sees them, and inline here instead +# $ -> [ \t]*$ the line is rstripped before matching, so +# the anchors tolerate trailing whitespace +# +# The last applies to every anchor including the ones inside the assignment +# rule's negative lookaheads, which are what decide whether the quotes +# balance. Do not hand-edit these; regenerate them and check that the +# verdicts still agree with BitBake's on real metadata. +_BB = { + 'function start': + '^(?:(?:(?:python(?=(?:(?:[ \\t]|\\\\[ \\t]*\\n)|\\()))|(?:fakeroot(?=(?:[ \\t]|\\\\[ \\t]*\\n))))(?:[ \\t]|\\\\[ \\t]*\\n)*)*(?:[\\w\\.\\-\\+\\{\\}\\$:]+)?(?:[ \\t]|\\\\[ \\t]*\\n)*\\((?:[ \\t]|\\\\[ \\t]*\\n)*\\)(?:[ \\t]|\\\\[ \\t]*\\n)*\\{[ \\t]*$', + 'def block': + '^def(?:[ \\t]|\\\\[ \\t]*\\n)+(?:\\w+)(?:[^\\n]|\\\\[ \\t]*\\n)*:', + 'export': + '^export(?:[ \\t]|\\\\[ \\t]*\\n)+(?:[a-zA-Z0-9\\-_+.${}/~]+)[ \\t]*$', + 'unset varflag': + '^unset(?:[ \\t]|\\\\[ \\t]*\\n)+(?:[a-zA-Z0-9\\-_+.${}/~]+)\\[(?:[a-zA-Z0-9\\-_+.][a-zA-Z0-9\\-_+.@]+)\\][ \\t]*$', + 'unset': + '^unset(?:[ \\t]|\\\\[ \\t]*\\n)+(?:[a-zA-Z0-9\\-_+.${}/~]+)[ \\t]*$', + 'addpylib': + '^addpylib(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'addfragments': + '^addfragments(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'inherit_defer': + '^inherit_defer(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'inherit': + '^inherit(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'include_all': + '^include_all(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'include': + '^include(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'require': + '^require(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'EXPORT_FUNCTIONS': + '^EXPORT_FUNCTIONS(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'addtask': + '^addtask(?:[ \\t]|\\\\[ \\t]*\\n)+(?:[^#\\n]+)(?:#(?:[^\\n]|\\\\[ \\t]*\\n)*|(?:[^\\n]|\\\\[ \\t]*\\n)*?)', + 'deltask': + '^deltask(?:[ \\t]|\\\\[ \\t]*\\n)+(?:[^#\\n]+)(?:#(?:[^\\n]|\\\\[ \\t]*\\n)*|(?:[^\\n]|\\\\[ \\t]*\\n)*?)', + 'addhandler': + '^addhandler(?:[ \\t]|\\\\[ \\t]*\\n)+(?:(?:[^\\n]|\\\\[ \\t]*\\n)+)', + 'assignment': + '^(?:export(?:[ \\t]|\\\\[ \\t]*\\n)+)?(?:[a-zA-Z0-9\\-_+.${}/~:]*?)(?:\\[(?:[a-zA-Z0-9\\-_+.][a-zA-Z0-9\\-_+.@/]*)\\])?(?:(?:[ \\t]|\\\\[ \\t]*\\n)*)(?:(?::=)|(?:\\?\\?=)|(?:\\?=)|(?:\\+=)|(?:=\\+)|(?:=\\.)|(?:\\.=)|=)(?:(?:[ \\t]|\\\\[ \\t]*\\n)*)(?!\'[^\'\\n]*\'[^\'\\n]*\'[ \\t]*$)(?!\\"[^\\"\\n]*\\"[^\\"\\n]*\\"[ \\t]*$)(?:\'(?:(?:[^\\n]|\\\\[ \\t]*\\n)*)\'|"(?:(?:[^\\n]|\\\\[ \\t]*\\n)*)")[ \\t]*$', +} + + +def _guard(*names): + """A zero-width assertion that BitBake's parser would accept this line.""" + # The anchor is hoisted out of the alternation rather than repeated in + # each branch, which regexlint flags as suspicious (W114). + return r'(?=^(?:%s))' % '|'.join(_BB[name].lstrip('^') for name in names) + + +_G_FUNC = _guard('function start') +_G_DEF = _guard('def block') +_G_INCLUDE = _guard('inherit_defer', 'inherit', 'include_all', 'include', + 'require') +_G_STATEMENT = _guard('addtask', 'deltask', 'addhandler', 'EXPORT_FUNCTIONS', + 'addpylib', 'addfragments') +_G_ASSIGN = _guard('assignment') +_G_VALUELESS = _guard('export', 'unset varflag', 'unset') + +# None of the guards capture, so they add nothing for ``bygroups`` to number. + + +# A bare BitBake identifier (variable, function or flag name). Allows the +# characters used by OE-Core variable names (digits, ``-``, ``.``, ``+``). +_IDENT = r'[A-Za-z_][A-Za-z0-9_\-.+]*' + +# Optional OE override chain such as ``:append``, ``:remove``, ``:class-target`` +# or ``:${PN}-doc``. Anchored so it only consumes ``:foo`` runs and never +# eats the leading ``:`` of the ``:=`` assignment operator. +_OVERRIDE = r'(?::[A-Za-z0-9_\-.+/~${}]+)*' + +# All BitBake variable assignment operators, ordered so that the longer +# operators win the regex alternation. +_ASSIGN = r'(?:\?\?=|\?=|:=|\+=|=\+|\.=|=\.|=)' + +# A variable or function name, matching what BitBake's own parser accepts +# (``[a-zA-Z0-9\-_+.${}/~:]`` for variables, ``[\w.\-+{}$:]`` for +# functions). Names may begin with a digit, may contain ``/`` as in +# ``PREFERRED_PROVIDER_virtual/kernel``, and may embed an expansion as in +# ``PREFERRED_PROVIDER_virtual/${SDK_PREFIX}libc``. The ``:`` introducing +# an override chain is excluded, since ``_OVERRIDE`` consumes that. +_NAME = r':?(?:\$\{[^{}\s]+\}|[A-Za-z0-9_\-.+/~${}])+' + +# A varflag name, which may also begin with a digit, as in +# ``ESW_BRANCH[2024.1]``. +_FLAG = r'[A-Za-z0-9_\-.+][A-Za-z0-9_\-.+@/]*' + + +class BitBakeLexer(RegexLexer): + """ + Lexer for BitBake recipes, classes, includes and configuration files + used by the Yocto Project and OpenEmbedded build system. + """ + + name = 'BitBake' + url = 'https://docs.yoctoproject.org/bitbake/' + aliases = ['bitbake'] + filenames = ['*.bbclass', '*.bbappend'] + mimetypes = ['text/x-bitbake'] + version_added = '2.21' + + flags = re.MULTILINE + + tokens = { + 'root': [ + (r'[ \t]+$', Whitespace), + (r'\n', Whitespace), + + # ``handle`` tests for a comment at column zero only, and only + # after joining continuations, so an indented ``#`` is not a + # comment and a comment ending in ``\`` swallows the line below. + (r'^#(?:[^\n]|\\[ \t]*\n)*', Comment.Single), + + # ``python [name]() { ... }`` blocks (also ``fakeroot python``). + # Must be tried before the generic shell function rule so the + # ``python`` keyword is not mistaken for a shell function name. + (_G_FUNC + r'(^(?:fakeroot[ \t]+)?)(python)((?:[ \t]+' + _NAME + + _OVERRIDE + r')?)' + r'([ \t]*\([ \t]*\)[ \t]*)(\{[ \t]*\n)' + r'((?:.*\n)*?)' + r'(^\}[ \t]*$)', + bygroups(Keyword.Type, Keyword, Name.Function, Text, + Punctuation, using(PythonLexer), Punctuation)), + + # Shell task bodies: ``[fakeroot ]name[:override]() { ... }``. + (_G_FUNC + r'(^(?:fakeroot[ \t]+)?)(' + _NAME + r')(' + + _OVERRIDE + r')' + r'([ \t]*\([ \t]*\)[ \t]*)(\{[ \t]*\n)' + r'((?:.*\n)*?)' + r'(^\}[ \t]*$)', + bygroups(Keyword.Type, Name.Function, Name.Decorator, Text, + Punctuation, using(BashLexer), Punctuation)), + + # Top-level python ``def`` blocks; the body is any run of + # indented or blank lines following the signature. + # BitBake's rule is ``def\s+(\w+).*:``, which validates little + # and does not require a body, so neither may this. The guard + # has already decided the line is a def. + (_G_DEF + r'^def[ \t]+(?:[^\n]|\\[ \t]*\n)*:(?:[^\n]|\\[ \t]*\n)*(?:\n|$)' + r'(?:[ \t]+.*\n|\n)*', + using(PythonLexer)), + + # ``inherit`` / ``inherit_defer`` / ``include`` / ``include_all`` / + # ``require`` directives. Longer keywords are listed first so the + # regex alternation does not match the shorter prefix. + (_G_INCLUDE + + r'^(inherit_defer|inherit|include_all|include|require)\b', + Keyword.Namespace, 'include-line'), + + # ``addtask`` / ``deltask`` / ``addhandler`` / ``EXPORT_FUNCTIONS`` + # / ``addpylib`` / ``addfragments``. + (_G_STATEMENT + + r'^(addtask|deltask|addhandler|EXPORT_FUNCTIONS|addpylib' + r'|addfragments)\b', + Keyword, 'statement'), + + # ``VAR[flag] = "value"`` (varflag assignment). The variable may + # carry an override chain first, as in + # ``GOARM:arm:class-target[export] = "1"``. + (_G_ASSIGN + r'^(' + _NAME + r')(' + _OVERRIDE + r')(\[)(' + + _FLAG + r')(\])' + r'([ \t]*)(' + _ASSIGN + r')', + bygroups(Name.Variable, Name.Decorator, Punctuation, + Name.Attribute, Punctuation, Whitespace, Operator), + 'value'), + + # ``[export ]VAR[:override...] OP "value"`` assignments. + (_G_ASSIGN + r'^(export[ \t]+)?(' + _NAME + r')(' + + _OVERRIDE + r')' + r'([ \t]*)(' + _ASSIGN + r')', + bygroups(Keyword.Type, Name.Variable, Name.Decorator, + Whitespace, Operator), + 'value'), + + # ``export VAR`` and ``unset VAR`` / ``unset VAR[flag]``, which + # carry no value. These follow the assignment rules so that + # ``export VAR = "value"`` is still matched as an assignment. + (_G_VALUELESS + r'^(export|unset)([ \t]+)(' + _NAME + r')(\[)(' + + _FLAG + r')' + r'(\])([ \t]*)$', + bygroups(Keyword, Whitespace, Name.Variable, Punctuation, + Name.Attribute, Punctuation, Whitespace)), + (_G_VALUELESS + r'^(export|unset)([ \t]+)(' + _NAME + + r')([ \t]*)$', + bygroups(Keyword, Whitespace, Name.Variable, Whitespace)), + + # Nothing above matched, so BitBake's parser would reject this + # line. Report it. A documentation block that is wrong on + # purpose carries ``:force:``, which skips Sphinx's filter for + # that block and leaves the marking visible. + (r'(?:[^\n]|\\[ \t]*\n)+', Error), + ], + + 'include-line': [ + (r'[ \t]+', Whitespace), + (r'\\\n', Text), + (r'\n', Whitespace, '#pop'), + include('interp'), + (r'\$', String), + (r'[^\s$]+', String), + (r'[^\n]', String), + ], + + 'statement': [ + (r'[ \t]+', Whitespace), + (r'\\\n', Text), + (r'\n', Whitespace, '#pop'), + (words(('after', 'before'), suffix=r'\b'), Keyword), + include('interp'), + (r'\$', Name), + (r'[^\s$\\]+', Name), + (r'[^\n]', Name), + ], + + 'value': [ + (r'[ \t]+', Whitespace), + # A backslash is special to BitBake only as the last + # character of a line, where it continues the statement. + # There are no escape sequences in a value, so treating + # \\\\ as an escaped pair would swallow the backslash that + # forms the continuation. + (r'\\[ \t]*\n', String.Escape), + (r'\n', Whitespace, '#pop'), + (r'"', String.Double, 'string-double'), + (r"'", String.Single, 'string-single'), + include('interp'), + (r'\$', String), + (r'[^\s"\'$\\]+', String), + (r'[^\n]', String), + ], + + 'string-double': [ + # A backslash is special to BitBake only as the last + # character of a line, where it continues the statement. + # There are no escape sequences in a value, so treating + # \\\\ as an escaped pair would swallow the backslash that + # forms the continuation. + (r'\\[ \t]*\n', String.Escape), + (r'"', String.Double, '#pop'), + include('interp'), + (r'\$', String.Double), + (r'[^"\\$\n]+', String.Double), + (r'[^\n]', String.Double), + ], + + 'string-single': [ + # A backslash is special to BitBake only as the last + # character of a line, where it continues the statement. + # There are no escape sequences in a value, so treating + # \\\\ as an escaped pair would swallow the backslash that + # forms the continuation. + (r'\\[ \t]*\n', String.Escape), + (r"'", String.Single, '#pop'), + include('interp'), + (r'\$', String.Single), + (r"[^'\\$\n]+", String.Single), + (r'[^\n]', String.Single), + ], + + 'interp': [ + # ``${@ python expression }`` evaluated by BitBake at parse time. + (r'\$\{@', String.Interpol, 'py-interp'), + # ``${VAR}`` variable expansion, which may itself contain further + # expansions such as ``${TUNE_ARCH:tune-${DEFAULTTUNE}}``. + (r'\$\{', String.Interpol, 'var-interp'), + ], + + 'var-interp': [ + (r'\}', String.Interpol, '#pop'), + (r'\\[ \t]*\n', String.Escape), + (r'\$\{@', String.Interpol, 'py-interp'), + (r'\$\{', String.Interpol, '#push'), + (r'[^${}\n\\]+', Name.Variable), + (r'\$', Name.Variable), + (r'[^\n]', Name.Variable), + ], + + 'py-interp': [ + (r'\}', String.Interpol, '#pop'), + (r'\\[ \t]*\n', String.Escape), + # ``${VAR}`` expansions embedded in the Python expression, as in + # ``${@bb.utils.contains('F', 'x', '${A}', '', d)}``. + (r'\$\{', String.Interpol, 'var-interp'), + # The backslash is excluded so that the continuation rule above + # gets the chance to match it. Swallowed here instead, the + # newline ends up matching nothing, the state stack unwinds + # mid-expression, and every following line of a multi-line + # ``${@...}`` is lexed at the top level and reported as invalid. + (r'[^${}\n\\]+', using(_FragmentPythonLexer)), + # A ``$`` that does not open an expansion belongs to the Python + # expression's own text, most often a regular-expression anchor + # inside a quoted string. + (r'\$', String), + (r'\{', using(_FragmentPythonLexer)), + (r'[^\n]', String), + ], + } + +# What the installed lexer must get right to be used instead of this one. +# Testing beats a version check: it judges whatever lexer is installed by +# what it does, and costs one lex of a few short lines. +# +# These assert that an Error IS reported. A lexer that accepts what BitBake +# rejects is invisible to a check looking only for the absence of errors. +_PROBES_MUST_ERROR = ( + # an unquoted value is not an assignment; BitBake rejects the line + 'PV = 0.8.16~rc1', + # neither is one carrying a trailing comment + 'ARCHIVER_MODE[src] = "x" # comment', +) + +# Constructs that must lex cleanly, each paired with what the installed +# lexer must make of one telling character. Asserting what the token IS +# matters, rather than only that no Error was reported: a release could +# suppress errors without fixing the lexing, and an error-only check would +# then stand this extension down while blocks silently went back to being +# mis-highlighted, with a zero exit code. +_PROBES_MUST_BE_CLEAN = ( + # the "$" anchoring a regex belongs to the string, not to an expansion + ('COMPATIBLE_MACHINE = "^mymachine$"', 32, String.Double), + # the inner "${" of a nested expansion is an expansion in its own right + ('TUNE_FEATURES ??= "${TUNE_FEATURES:tune-${DEFAULTTUNE}}"', 40, + String.Interpol), + # a statement carrying no value is still a statement + ('unset DATE', 0, Keyword), +) + + +def _installed_lexer_is_fixed(): + """True only if the installed lexer demonstrably behaves. + + Fails safe: anything unexpected - no bitbake lexer at all, an import + failure, a token type this does not recognise - is reported as not + fixed, so the carried lexer is used. Being wrong that way costs nothing; + being wrong the other way loses the highlighting silently. + """ + try: + from pygments.lexers import get_lexer_by_name + lexer = get_lexer_by_name('bitbake') + except Exception: + return False + for text in _PROBES_MUST_ERROR: + try: + tokens = list(lexer.get_tokens_unprocessed(text)) + except Exception: + return False + if not any(t is Error for _, t, _ in tokens): + return False + for text, offset, expected in _PROBES_MUST_BE_CLEAN: + try: + tokens = list(lexer.get_tokens_unprocessed(text)) + except Exception: + return False + if any(t is Error for _, t, _ in tokens): + return False + at = [t for i, t, _ in tokens if i == offset] + if len(at) != 1 or at[0] is not expected: + return False + return True + + +def setup(app): + if not _installed_lexer_is_fixed(): + app.add_lexer('bitbake', BitBakeLexer) + return { + 'version': __version__, + 'parallel_read_safe': True, + 'parallel_write_safe': True, + } From patchwork Wed Nov 25 15:45:30 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Trevor Woerner X-Patchwork-Id: 105671 Received: from mail-ej1-f46.google.com (mail-ej1-f46.google.com [209.85.218.46]) by mx.groups.io with SMTP id smtpd.msgproc02-g2.44548.1795621545011636236 for ; Wed, 25 Nov 2026 07:45:45 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@gmail.com header.s=20260707 header.b=TzK+g2qL; spf=pass (domain: gmail.com, ip: 209.85.218.46, mailfrom: twoerner@gmail.com) Received: by mail-ej1-f46.google.com with SMTP id a640c23a62f3a-c51bf011392so16211066b.3 for ; Wed, 25 Nov 2026 07:45:44 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1795621543; x=1796226343; darn=lists.yoctoproject.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to:content-type; bh=FEkC46lIva13+mFq2ZY5tdb5p6nmHdqLZVtuP1HBXnI=; b=TzK+g2qL5/OuXPsikjN1FC3RkhY70A93N11KgLiaitG+1YU3wxtUzAHLrN3OC52Gys tVgvCxAJPpkSYh687g++gCWxvYe6ebwW14wPw3+OivjbvNpNk2TGrC7nra3PJQkG+P+e 4cwBJdTFBoLd0NfgPkdXA7pu00WO48mkQKaMLgIT08FVxY8oU1B8+6MY1dAKLcoB/Rju rbOCSFuclYR7N5k+3hEYsMwQps/9qT2ci9j+r1kIApCOcJRC4hD4QDSzSjr2e5as7+VJ VNFtWCzgESzLQad4v5wD0IVnijOAEv0hwdjka743+FsLqkF0jWdMiT1azlIkMxrtr8N3 X9sw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795621543; x=1796226343; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-gg:x-gm-message-state:from:to :cc:subject:date:message-id:reply-to:content-type; bh=FEkC46lIva13+mFq2ZY5tdb5p6nmHdqLZVtuP1HBXnI=; b=xxBhKkCwoqwSTdHTxONkH8NUrDIkHoh6g2WVQ2EtNXbtjmEFMvCWwpQ8GaOy5TwWX1 jpYtmEWd/1jxN1HLI45O9tWyIkPuKbfGZfUYGnVY/xfNznbYY5tqlLv2qSFwpPhLye/l NROsu1Ho7oWIHozClSMdzuDWf5Rn6ghu9aihdQmIV6BrNG89wdKMfiBQ+bevXVCYm+cX BZNgeCgX5XEeaqGsOPyIEZcmf6SIHoQqT0vGbL/GHlZNCIxcIbhTlwsJXw29XaJ0OSQ/ tozG+46PNYCt3BEN9tbQWyrSvG08o4/qO0i4Al9+pSoD7dljEyNc9Q6qPTjavQGNXHnM 5Gig== X-Gm-Message-State: APuU4Z9mQNA/WOGcqsRdBdFnuqktscYpAPy1PSOgfuVom8i6If5WtM+d wNFle13dtqMyIRP4MNjcAf8fUEhdjxrazHYP1vTvpzS7ge2XANdl9VBRv3tEdw== X-Gm-Gg: AZFdTZeEz2gaj09j/uc/h5W0U6pc2saIc9zt/Huwg78aRrOIAuIdXXAd8Sx/29IrJNI uZO6GZgNLfI/+VMhJRB/xLYC+y12TV0kH4+3X3Pgc5R8a9kxkeddOntxbn3VYndNEgyDrl7KWw5 CtoB4Rm798RuwdDdU+aocP+p+rP4gj4bvWBwDrOU1Dq2q+u7Dw+eoNzqEpLrnEjEuCNLoztyFeY v2w/BAvzAI0ZhTc8Fj0Ity7Zl4ZiHD1fCaPGIEduMZHkFBuFNYRrgx/yQYScc4LdhIY6jDf62QD zj0M86lAxS5JB3CpFRA7TzRMl+v8+RtxDkuEgjdfjalxITn9xSJNJZvH5gIUkVMhoc8937BsqFT L12ooYJBGmNXR/V4gLvB2fhGZXcu0IAzgdju6L7oY33XYGjjxtSzJ5+8elvAnvjrTJCMEeaOLk6 hB53Xf9odi5uUiZAyKIQEQiSXogbaX8N8SyEGDIOKV3tfFT1xilnpwwjPgFkRMOXPAQatk51NPo P9ahdlil5Qhng7BY2Mt8mMrwXfsbS1I0ZG1wfxx4VdGuryJQY3PFlbNqT7auz1DcJDdZU4FKRkk mZLvbhVWtS3gGtuqR6WZPT1h7vg7tchJKe9aYhsRP9WxLrDSe2nvIQ6r4U1NCuJuV6d7ncdkqUP yLUc45RmJuEP+k2cmWeAQV57AZqPsLKc= X-Received: by 2002:a17:907:934c:b0:c51:282b:5489 with SMTP id a640c23a62f3a-c513a4aea3bmr1465627866b.3.1795621542989; Wed, 25 Nov 2026 07:45:42 -0800 (PST) Return-Path: Received: from localhost.localdomain (pppoe-209-91-167-254.vianet.ca. [209.91.167.254]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-c513aec5115sm651892066b.51.2026.11.25.07.45.41 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 25 Nov 2026 07:45:42 -0800 (PST) From: Trevor Woerner To: docs@lists.yoctoproject.org Subject: [PATCH 2/7] sphinx: add a lexer for BitBake with placeholders Date: Wed, 25 Nov 2026 10:45:30 -0500 Message-ID: <20261125154535.3486104-3-twoerner@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20261125154535.3486104-1-twoerner@gmail.com> References: <20261125154535.3486104-1-twoerner@gmail.com> MIME-Version: 1.0 List-Id: X-Webhook-Received: from 45-33-107-173.ip.linodeusercontent.com [45.33.107.173] by lin-tor-korg-lkml-alma10-1 with HTTPS for ; Wed, 25 Nov 2026 15:45:54 -0000 X-Groupsio-URL: https://lists.yoctoproject.org/g/docs/message/10837 The manuals write for a value the reader has to replace, and BitBake cannot express that. Inside a quoted value it renders as ordinary string content, indistinguishable from text to type verbatim; in a variable name it is not valid BitBake at all. This adds a bitbake-placeholder lexer that accepts a placeholder where BitBake's charsets do not and marks it wherever it appears. Everything else is inherited from the BitBake lexer, so a block using it still reports a genuine mistake. AI-Generated: codex/claude-opus 5.5 (xhigh) Signed-off-by: Trevor Woerner --- documentation/conf.py | 3 +- .../sphinx-static/theme_overrides.css | 20 +++ documentation/sphinx/bitbake-placeholder.py | 145 ++++++++++++++++++ 3 files changed, 167 insertions(+), 1 deletion(-) create mode 100644 documentation/sphinx/bitbake-placeholder.py diff --git a/documentation/conf.py b/documentation/conf.py index cdd554e30c0a..95bb24002544 100644 --- a/documentation/conf.py +++ b/documentation/conf.py @@ -80,7 +80,8 @@ extensions = [ 'sphinx_tags', 'sphinxcontrib.rsvgconverter', 'yocto-vars', - 'bitbake-lexer' + 'bitbake-lexer', + 'bitbake-placeholder' ] # current_version = "dev" diff --git a/documentation/sphinx-static/theme_overrides.css b/documentation/sphinx-static/theme_overrides.css index 85f01eafbb94..2083ebb5baf4 100644 --- a/documentation/sphinx-static/theme_overrides.css +++ b/documentation/sphinx-static/theme_overrides.css @@ -252,3 +252,23 @@ a.sd-badge { } } + +/* A placeholder in a bitbake-placeholder block: something the reader is + meant to replace, such as in SRCREV:pn-. + + The box is the point. A placeholder usually abuts real text it is not + part of - pn-, / - and an outline is what + shows where one ends and the other begins. Colour alone does not. + + Italic carries the same meaning without any colour at all, so the mark + survives a monochrome printout. The border is #5b8db9 rather than + something paler because it has to clear 3:1 against the code block to + count as a boundary: a lighter blue measured 2:1 and disappeared. */ +.rst-content .highlight-bitbake-placeholder .ge { + color: #144e8c; + font-style: italic; + font-weight: 600; + border: 1px solid #5b8db9; + border-radius: 3px; + padding: 0 2px; +} diff --git a/documentation/sphinx/bitbake-placeholder.py b/documentation/sphinx/bitbake-placeholder.py new file mode 100644 index 000000000000..8141ac7b5687 --- /dev/null +++ b/documentation/sphinx/bitbake-placeholder.py @@ -0,0 +1,145 @@ +"""BitBake with documentation placeholders: the ``bitbake-placeholder`` dialect. + +The manuals write ```` for "replace this with your own value". +BitBake has no way to express that, so the convention behaves differently +depending on where it lands: inside a quoted value it is legal BitBake and +takes ordinary string colour, indistinguishable from a literal; in a +variable name it is not BitBake at all, because ``<`` is not in BitBake's +name charset. + +This lexer differs from plain BitBake in exactly two ways, and in no +others: + +- it **accepts** a placeholder where BitBake's charsets do not, so + ``SRCREV:pn- = "${AUTOREV}"`` lexes as the assignment it is + plainly meant to be +- it **marks** a placeholder wherever it appears, so a reader can tell it + apart from text to be typed verbatim + +Everything else is inherited, so a block tagged ``bitbake-placeholder`` +still fails on a genuine mistake. That is the point of a dialect rather +than a permissive lexer: it admits one convention, not all errors. + +``Generic.Emph`` carries the placeholder. ``Name.Placeholder`` would be +the obvious choice and is a trap: it has no entry in Pygments' +``STANDARD_TYPES``, so the HTML formatter walks up to ``Name`` and emits +``class="n"``, which is indistinguishable from every other name. +""" +import importlib + +from pygments.lexer import bygroups, inherit, this, using +from pygments.token import Generic, Keyword, Name, Operator, String, \ + Whitespace + +__version__ = '1.0' + + +def _base_lexer(): + """The BitBake lexer this dialect extends. + + Prefer the carried one, since it is the lexer the manuals are written + against, and fall back to the stock lexer if ``bitbake-lexer.py`` is + absent, so this file does not depend on it. + + Resolving through ``get_lexer_by_name('bitbake')`` does not work here: + ``app.add_lexer`` registers with Sphinx rather than with Pygments, so + the lookup returns the stock lexer even when the carried one is + registered. + """ + try: + return importlib.import_module('bitbake-lexer').BitBakeLexer + except Exception: + from pygments.lexers.bitbake import BitBakeLexer + return BitBakeLexer + + +_PH = r'<[^<>\n]+>' + +# A variable name that may carry placeholders. Deliberately not derived +# from the base lexer's own pattern: this file has to work against either +# base, and a name is the one thing the two agree on. +_NCHAR = r'(?:\$\{[^{}\s]+\}|[A-Za-z0-9_\-.+/~${}])' +_PNAME = r':?(?:' + _NCHAR + r'|' + _PH + r')+' +_POVERRIDE = r'(?::(?:' + _NCHAR + r'|' + _PH + r')+)*' +_ASSIGN = r'(?:\?\?=|\?=|:=|\+=|=\+|\.=|=\.|=)' + +# Fire only where a placeholder is actually present in the name. Without +# this the dialect would accept ``PV = 1.2.3``, which no BitBake accepts: +# the rules below are unguarded, so anything they match bypasses the +# inherited rules and their checks. A dialect has to admit one convention, +# not all errors, and this is what holds it to that. +_HAS_PH = (r'(?=(?:export[ \t]+)?(?:' + _NCHAR + r'|:)*' + _PH + r')') + + +class BitBakePlaceholderLexer(_base_lexer()): + """BitBake, plus the manuals' ```` convention.""" + + name = 'BitBake with placeholders' + aliases = ['bitbake-placeholder'] + filenames = [] + mimetypes = [] + url = 'https://docs.yoctoproject.org' + + tokens = { + 'root': [ + # An assignment whose name or override chain carries a + # placeholder. This comes first because the inherited rules are + # guarded by BitBake's own regexes, which reject such a name + # outright, so the line would never reach them. + # + # A placeholder inside a varflag, ``FOO[] = "1"``, is not + # handled: the manuals contain none, and supporting a form + # nobody writes is a rule nobody can check. + (r'^' + _HAS_PH + + r'(export[ \t]+)?(' + _PNAME + r')(' + _POVERRIDE + r')' + r'([ \t]*)(' + _ASSIGN + r')', + bygroups(Keyword.Type, using(this, state='placeholder-name'), + using(this, state='placeholder-name'), Whitespace, + Operator), + 'value'), + inherit, + ], + + # Split a name into its placeholder and non-placeholder parts, so + # ``pn-`` shows which half the reader has to replace. + 'placeholder-name': [ + (_PH, Generic.Emph), + (r':', Name.Decorator), + (r'[^<:\n]+', Name.Variable), + (r'[^\n]', Name.Variable), + ], + + # Marking, as opposed to accepting. A placeholder inside a value is + # already valid BitBake; it just looks like a literal. + # + # The second rule in each state is what makes the first one work. + # The inherited states end in a greedy run of "anything that is not + # a quote, dollar or backslash", which swallows a whole value + # including its placeholders as one token, so the rule above never + # gets a position to match at. Stopping at the next "<" hands each + # placeholder back to it. + 'value': [ + (_PH, Generic.Emph), + (r'[^<\s"\'$\\]+', String), + inherit, + ], + 'string-double': [ + (_PH, Generic.Emph), + (r'[^<"\\$\n]+', String.Double), + inherit, + ], + 'string-single': [ + (_PH, Generic.Emph), + (r"[^<'\\$\n]+", String.Single), + inherit, + ], + } + + +def setup(app): + app.add_lexer('bitbake-placeholder', BitBakePlaceholderLexer) + return { + 'version': __version__, + 'parallel_read_safe': True, + 'parallel_write_safe': True, + } From patchwork Wed Nov 25 15:45:31 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Trevor Woerner X-Patchwork-Id: 105672 Received: from mail-ej1-f50.google.com (mail-ej1-f50.google.com [209.85.218.50]) by mx.groups.io with SMTP id smtpd.msgproc02-g2.44549.1795621546520173603 for ; Wed, 25 Nov 2026 07:45:46 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@gmail.com header.s=20260707 header.b=CjtGUANX; spf=pass (domain: gmail.com, ip: 209.85.218.50, mailfrom: twoerner@gmail.com) Received: by mail-ej1-f50.google.com with SMTP id a640c23a62f3a-c4cac7a7d3cso880443766b.3 for ; Wed, 25 Nov 2026 07:45:46 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1795621545; x=1796226345; darn=lists.yoctoproject.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to:content-type; bh=B7gTNQxPBgSRwbFsFtNL/fYO33GHbuwt40VqaM1Layk=; b=CjtGUANXMu+Nm6z1tewt7QdDPvjO4cvojYgN+x96kNwf9jcmu5z0OPp1xRq9WqjysA y2V3d3ljVilZTWh3JFQrjEakKtd6fnYBVfaSp32Uph+OBbzo/XcSxhVCMs7LtDbVKZRl PZPbT4mHhdlgn5DlK5pPNp4WYsvxXrd/A/p6xbJCGlbzSO5V9jgvv2L3Ph5ifQBnAiC4 dFTOMfjxL4X0SwIO67VgN760OLarUxUnAU4refPHHMkmPeQ/nX2GhjbDKtMl3vX6Zpvr NAq/xye7Mt3yTCG65FM6cQ+MnFgBnlUb3+OiQjMWbkuwQza7whf6ctpmaRGkQg+ekN9x JqKg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795621545; x=1796226345; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-gg:x-gm-message-state:from:to :cc:subject:date:message-id:reply-to:content-type; bh=B7gTNQxPBgSRwbFsFtNL/fYO33GHbuwt40VqaM1Layk=; b=NmmIL9at5BY8+blzKSucNtq40YQisdxbox8YH9hyK0wucF2/gDm4M4es+sdMUR73Jp 1waejm8li8XDEjwUWP+JuFxGnv3T9l4KwrSPT0maczL2gxdyjisSzZH767oZxrZIszJD MR2GBffNHVHzqAmZq2Pz6TRcB5Xna/k8UnvmWBsH/hmxLF6yQTybeEZd6YmIulQd9elt 9QNd4ILTwEW9/MGO59kZX0OfCjJ9dzK+pKf/NCnBmwM/ffOOqyEgrcPCkvv9zwJJeniz WSgeviyVDtZe9hDAhJ9Z5K/oRIzAhGzRm/E00y/nhISthmYzdE2FvLOXaCDdQHsmlNd1 34mg== X-Gm-Message-State: APuU4Z82NGLocyKIW4N8/DMpvH4UlVJu9fDraJjn60gPyelIZKCRWNi1 I10LzszQAq/sxMCGdm4uMaBDE6oJ/U5/GJpYVLQyY/cPb8m6E7v+3V7rz4JEkA== X-Gm-Gg: AZFdTZdIhj7mJI/tTXA44R0fwnoj0uWI3ZXtDQx59KRYTR7dDVNSdz0aLhT2ADjTDx9 L/gHDS+j2AeudSNm7FGK0nHkzTRSOrUB19VvC3jeP9BJRjU/YgSdtJQtxm2QEnWOE5j9PQdQoVl qWeM5ahN+lLq9QRBYIMIp4lvRRC3ULx67VAbQ9G9bPRD7QvFlz0BNiP7jkSLza8bWypKJBDrbva baNufZWzAbwFPiG5PtIZcwqfOfJerQHDpSkpzVf/zn/ZIzJyV/HdqnwZNtAIo+Nc4IBH8A7Nat3 0WWJnFkbPcKFta9jq1Y/750GaB4QJ9OS9L8j1XmrRx1UnFvPRiaHJ8FVC+HkeYydA2VjGk8JQkZ vldjP02l4Ieoo5qvi7509V/RLGLsvJ19Dp6PgPRKw2LAgyodFSIlcarEJxsoIUwu1FKTCBu9WrX z2uGEICz3AQWgu5gJ2Q5nrku9H6F/v/4ajuKfiG50pJv3D0hi2skuEOTPKs+tqUuJOSDPhw1h3/ NjeguWyWrCnqc76r1VzmWXF2gvUlfCb5vHNbQTPmp/SjtMWYskILSAlgeSePzEw6WOdAqHlIhO3 2HzKfbd78dKsCZqEui75QwHdU5e3f67zYxh9PsZmmx6Ne4B5WtetzWRs0G/Npn4mD8mck3Jd5eJ NgQLl1fZfdiEezC+8pXJb60dM29pKqEo= X-Received: by 2002:a17:906:b854:b0:c49:cf3a:a324 with SMTP id a640c23a62f3a-c513a9b1c52mr1069649466b.22.1795621544424; Wed, 25 Nov 2026 07:45:44 -0800 (PST) Return-Path: Received: from localhost.localdomain (pppoe-209-91-167-254.vianet.ca. [209.91.167.254]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-c513aec5115sm651892066b.51.2026.11.25.07.45.43 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 25 Nov 2026 07:45:43 -0800 (PST) From: Trevor Woerner To: docs@lists.yoctoproject.org Subject: [PATCH 3/7] sphinx: add a lexer for kernel metadata SCC files Date: Wed, 25 Nov 2026 10:45:31 -0500 Message-ID: <20261125154535.3486104-4-twoerner@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20261125154535.3486104-1-twoerner@gmail.com> References: <20261125154535.3486104-1-twoerner@gmail.com> MIME-Version: 1.0 List-Id: X-Webhook-Received: from 45-33-107-173.ip.linodeusercontent.com [45.33.107.173] by lin-tor-korg-lkml-alma10-1 with HTTPS for ; Wed, 25 Nov 2026 15:45:54 -0000 X-Groupsio-URL: https://lists.yoctoproject.org/g/docs/message/10838 The kernel manual quotes SCC description files throughout, and none of them can say what they are: Pygments has no lexer for the language and is unlikely to want one, so they render as plain text. SCC is bash. spp rewrites a few line-oriented directives, then scc sources the result with one shell function declared per statement and PATH unset. Description files use that freedom - conditionals on KARCH are common in real metadata - so extend the bash lexer and mark the vocabulary, read from the functions the tooling declares rather than from the manual's reference section, which omits several. AI-Generated: codex/claude-opus 5.5 (xhigh) Signed-off-by: Trevor Woerner --- documentation/conf.py | 3 +- documentation/sphinx/scc-lexer.py | 116 ++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 documentation/sphinx/scc-lexer.py diff --git a/documentation/conf.py b/documentation/conf.py index 95bb24002544..210b4ab60595 100644 --- a/documentation/conf.py +++ b/documentation/conf.py @@ -81,7 +81,8 @@ extensions = [ 'sphinxcontrib.rsvgconverter', 'yocto-vars', 'bitbake-lexer', - 'bitbake-placeholder' + 'bitbake-placeholder', + 'scc-lexer' ] # current_version = "dev" diff --git a/documentation/sphinx/scc-lexer.py b/documentation/sphinx/scc-lexer.py new file mode 100644 index 000000000000..dd1166ca7014 --- /dev/null +++ b/documentation/sphinx/scc-lexer.py @@ -0,0 +1,116 @@ +"""Lexer for kernel metadata SCC description files. + +SCC describes a BSP or a kernel feature: which branch to build on, which +patches to apply and which configuration fragments to queue. The tooling +that reads it is ``yocto-kernel-tools``, and the shape of the language +follows from how that tooling works rather than from how it looks. ``spp`` +rewrites a few line-oriented directives, and then ``scc`` *sources the +result as a bash script*, having first defined one shell function per +statement and unset ``PATH`` so nothing else can run. + +So an SCC file is not a dialect of bash but bash itself, under a +preprocessor: the ``spp`` directives have their own, non-shell semantics - +``#define`` is a comment as far as bash is concerned - while everything +surviving that pass is ordinary shell with a fixed vocabulary of commands. +Real metadata relies on it, with conditionals on ``KARCH`` in particular, +and a lexer built from the manual's statement list rejects them. This one +extends the bash lexer and marks the vocabulary, so the shell half is +right by construction and only the command list has to be got right. + +That list comes from the implementation: the functions ``scc`` defines +itself, the functions it sources from ``scc-cmds/*.cmd``, and the +directives ``spp`` matches before any of that runs. It is wider than the +"SCC Description File Reference" section of ``kernel-dev/advanced.rst``, +which omits ``mark``, ``merge``, ``tag``, ``prefix``, and the flags. +""" +from pygments.lexer import bygroups, inherit, words +from pygments.lexers.shell import BashLexer +from pygments.token import Comment, Keyword, Name, Text, Whitespace + +__version__ = '2.0' + +# Statements, as the tooling defines them. ``spp`` handles include, patch +# and kconf itself; the rest are shell functions declared by scc and by +# scc-cmds/*.cmd before the file is sourced. +_COMMANDS = ( + 'branch', 'define', 'git', 'include', 'kconf', 'mark', 'merge', + 'patch', 'prefix', 'reloc_dir', 'set_kernel_version', 'tag', +) + +# spp matches this before bash ever sees the file, so it is a directive +# wearing a comment's clothes and needs its own rule. +_DIRECTIVES = ('#define',) + +# Words that qualify a statement rather than starting one: the kconf +# fragment classes kconf.cmd tests for, and the flags spp looks for on an +# include line. +_FLAGS = ( + 'as_module', 'hardware', 'non-hardware', 'nocfg', 'nopatch', + 'optional', 'required', +) + +# spp recognises these only immediately ahead of kconf, at the margin. +_LEADERS = ('as_module', 'force') + +# A statement sits at the margin. Reaching it reliably needs the rule +# below that stops a run of whitespace at the end of a line. +_MARGIN = r'^[ \t]*' + + +class SccLexer(BashLexer): + """Kernel metadata SCC description files.""" + + name = 'SCC' + aliases = ['scc'] + filenames = ['*.scc'] + mimetypes = [] + url = 'https://docs.yoctoproject.org/kernel-dev/advanced.html' + + tokens = { + 'root': [ + # Both spellings of define name a variable, so mark it. + (r'(' + _MARGIN + r')(' + '|'.join(_DIRECTIVES) + + r')([ \t]+)([A-Za-z_]\w*)', + bygroups(Whitespace, Comment.Preproc, Whitespace, + Name.Variable)), + (r'(' + _MARGIN + r')(define)([ \t]+)([A-Za-z_]\w*)', + bygroups(Whitespace, Keyword, Whitespace, Name.Variable)), + + # A statement only starts a line. Elsewhere the same word is + # an argument: "branch" is a command at the margin and a + # subcommand in "git branch pvr master". + (r'(' + _MARGIN + r')((?:' + '|'.join(_LEADERS) + + r')(?=[ \t]))?([ \t]*)(' + + '|'.join(_COMMANDS) + r')(?=[ \t]|$)', + bygroups(Whitespace, Name.Builtin, Whitespace, Keyword)), + + (words(_FLAGS, prefix=r'(?<=[ \t])', suffix=r'(?=[ \t]|$)'), + Name.Builtin), + + # Keep whitespace runs from crossing a line ending, so the + # next statement is still at the margin when it is reached. + (r'[ \t]*\n', Whitespace), + + # The bash lexer's own copy of this rule swallows the newline + # and the indent behind it, which would leave a statement + # inside a conditional no longer at the margin and so + # unmarked. Match the words alone and leave the rest. + (r'\b(if|fi|else|while|in|do|done|for|then|return|function|' + r'case|select|break|continue|until|esac|elif)\b', Keyword), + + # Cosmetic: patch filenames conventionally lead with a + # sequence number, and bash would colour that as a number. + (r'\d+(?=[\w./+-])', Text), + + inherit, + ], + } + + +def setup(app): + app.add_lexer('scc', SccLexer) + return { + 'version': __version__, + 'parallel_read_safe': True, + 'parallel_write_safe': True, + } From patchwork Wed Nov 25 15:45:32 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Trevor Woerner X-Patchwork-Id: 105673 Received: from mail-ej1-f45.google.com (mail-ej1-f45.google.com [209.85.218.45]) by mx.groups.io with SMTP id smtpd.msgproc02-g2.44550.1795621547890201652 for ; Wed, 25 Nov 2026 07:45:48 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@gmail.com header.s=20260707 header.b=rh34aoaT; spf=pass (domain: gmail.com, ip: 209.85.218.45, mailfrom: twoerner@gmail.com) Received: by mail-ej1-f45.google.com with SMTP id a640c23a62f3a-c40e30c26a4so1308072766b.0 for ; Wed, 25 Nov 2026 07:45:47 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1795621546; x=1796226346; darn=lists.yoctoproject.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to:content-type; bh=3i6iSUgd2MzLFqmIEN9G9gxArQmrtP67tGo6d3Tq/6A=; b=rh34aoaTOfigNLWjs9qIbRO4yyI/ExLCKpz00jZgk4X/AOsTFntiUBd37JdH6W51VA AgJ/hP/Tuq710aHP2AlYaW0jn3pZOwDjxaaBKpFsx8kBpwejkCCPCixmGnCoD+InZOyt gEbiPDg5rZCboHqv1LLXIifjFWNnoMFf4LFdpim9h05+PG5hCQipxymJpK4v53v7BBGi jIqeuPZCMzBt6FW01eK8MEevXRXrO+1wGOLVm0Wi7q5k7OG3JfT9o01frP1bXF3V9OLp HNAz+5BQz3OUv6Gn6ALFpU1P/qzBaBRP8+KpLidiY/x6bUEXYys2IP3CF0bKCVW1cGn6 C3Rw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795621546; x=1796226346; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-gg:x-gm-message-state:from:to :cc:subject:date:message-id:reply-to:content-type; bh=3i6iSUgd2MzLFqmIEN9G9gxArQmrtP67tGo6d3Tq/6A=; b=Og5LolShlVjZWIM4hWtBa9+RrkrbswFqhHRzQRCZug/bREeFx9lFTn+bPQZD5JEEyP IX0bQuQRxBxeX6RasQnkAdTXxfE+PdAUMmzbZnZ5G3wasIgdNnOpXPvtLmH+QJLDzY8a fEMb5vOL9WgWjEnKCMEj8ABAV3VUIFuWERYWHjt9x+Ne3XHytsV2fxNYQHJMeU/QqFUj ggv3CsmwX4k+j1Y0gh/YIaoai6RSFHOoJMuUNLndckMgEiKCyAe1j0sIPLAwYLUjJtP+ RTJ9GHydCJITr/tfdU6FB2RtB7QDrg1I8f0gFRk5Ui9XFU03aygJIZ17QITUpK2I4BNm ShHA== X-Gm-Message-State: APuU4Z/wvxCSzQmpOaHQgev6l74INNJ6LOF/7/wBKSLxmViwePv+tPYk tejXMX/HNA0O8av+kFxRVpVkH8fbZZGQZ8OB9ElPgELPcY78K+MxTYm99D104Q== X-Gm-Gg: AZFdTZeMtjEVgOBHRJDQVW8LHjZUeeX56xt0ruf5LicHs5iN+weNAXXbLtfpclRgA+W iFAKYmANA1g+FYfFdn/ZdpmOt9E6QK0VKolZZNp+HBK5VdsUOGzfVZtnmfriCLxQJAjL6Fo7oRH aXe62vPcNPdTtO4Bh8vZolbROBPLuYD9XE59rucv9kf4r/HJTAdq8hta3yRJcI7UkLC7vlYImDT Ja3i+h0Wt87Z5s/eKqvzuUPF5Lvp8ZbJ/u3JYUr5lHClngwft1u0Mkr8OouE9TLfvmTM42Y4MkC L6wRN+fX6o82bgT/L+bkvKgAE5W4/gxhfFRp0EVxjxDHdYTznx5eSjR+h1Mtd1wMxM110jt6Afw DJF1PziCxZcGheAf3lmqptdt2qgvlYpJibim5F/yszRgDpiSPAHOBHLZR70h3Sj1ed+yqNifzD5 xVuMBrGQw6cRllcxvbcDyGSn6OP4f5kwqMfqzzQw3k1I11tYMrL6rAzWGHblaiyW/VWWvvnCNcZ TryrtG2T8VCaPVTFrzZ0uwFbvrjmlaeVqE+4618GWsd1fRrCfj2VGyUQ9BuJnT7abSF4Fy6AROH 6TrfZfHfgF9hpNqn1m2mtr3aUIOaUMVIEuUyvttp9OKlCkMF7NfNy3d7y6y+8jER9tKalqFcj6M wItbVa5fOyajf4JQy2Gb3pvzQlA22zuc= X-Received: by 2002:a17:906:4fd1:b0:c46:7de7:e41d with SMTP id a640c23a62f3a-c51318a03d9mr1655566966b.18.1795621545976; Wed, 25 Nov 2026 07:45:45 -0800 (PST) Return-Path: Received: from localhost.localdomain (pppoe-209-91-167-254.vianet.ca. [209.91.167.254]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-c513aec5115sm651892066b.51.2026.11.25.07.45.44 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 25 Nov 2026 07:45:44 -0800 (PST) From: Trevor Woerner To: docs@lists.yoctoproject.org Subject: [PATCH 4/7] sphinx: add a lexer for wic kickstart files Date: Wed, 25 Nov 2026 10:45:32 -0500 Message-ID: <20261125154535.3486104-5-twoerner@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20261125154535.3486104-1-twoerner@gmail.com> References: <20261125154535.3486104-1-twoerner@gmail.com> MIME-Version: 1.0 List-Id: X-Webhook-Received: from 45-33-107-173.ip.linodeusercontent.com [45.33.107.173] by lin-tor-korg-lkml-alma10-1 with HTTPS for ; Wed, 25 Nov 2026 15:45:54 -0000 X-Groupsio-URL: https://lists.yoctoproject.org/g/docs/message/10839 The manuals show .wks files in several places and have no language for them, so they are tagged text, tagged shell, or left to the default. Shell comes closest, because wic splits each line with shlex and expands ${VAR} before parsing, but it does not know the vocabulary: the "part" opening a line and every option come out as ordinary text. This extends the bash lexer to mark the statements and long options that wic's own parser registers. AI-Generated: codex/claude-opus 5.5 (xhigh) Signed-off-by: Trevor Woerner --- documentation/conf.py | 3 +- documentation/sphinx/wks-lexer.py | 60 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 documentation/sphinx/wks-lexer.py diff --git a/documentation/conf.py b/documentation/conf.py index 210b4ab60595..f89926549d20 100644 --- a/documentation/conf.py +++ b/documentation/conf.py @@ -82,7 +82,8 @@ extensions = [ 'yocto-vars', 'bitbake-lexer', 'bitbake-placeholder', - 'scc-lexer' + 'scc-lexer', + 'wks-lexer' ] # current_version = "dev" diff --git a/documentation/sphinx/wks-lexer.py b/documentation/sphinx/wks-lexer.py new file mode 100644 index 000000000000..1e5e5ec1e5b9 --- /dev/null +++ b/documentation/sphinx/wks-lexer.py @@ -0,0 +1,60 @@ +"""A lexer for wic kickstart (.wks) files. + +wic reads a .wks file line by line: a line whose first non-blank +character is ``#`` is a comment, and every other line is split with +``shlex.split`` and handed to ``argparse``, after ``${VAR}`` has been +expanded. The quoting is therefore shell quoting, which is why this +extends the bash lexer. What the bash lexer cannot do is mark the +vocabulary: ``part`` is not a shell builtin, so the statement opening +each line comes out as ordinary text, and so does every ``--option``. + +The statements and options below are taken from wic's parser, +``ksparser.py``, rather than from the manual, so update them from there +when wic gains one. ``partition`` is not a statement: it was an alias +while wic bundled pykickstart, and the parser that replaced it in 2016 +kept only ``part``. +""" +from pygments.lexer import bygroups, inherit +from pygments.lexers.shell import BashLexer +from pygments.token import Comment, Keyword, Name, Text, Whitespace + +__version__ = '1.0' + +# The subparsers wic registers. +STATEMENTS = ('part', 'bootloader', 'include') + + +class WksLexer(BashLexer): + """wic kickstart.""" + + name = 'wic kickstart' + aliases = ['wks'] + filenames = ['*.wks', '*.wks.in'] + mimetypes = [] + + tokens = { + 'root': [ + # A statement is only a statement at the start of a line. + # Anchoring matters: "include" is also an ordinary word in + # "--include-path", and "part" appears inside several option + # names, so an unanchored keyword would mark both. + (r'^(\s*)(%s)(\b)' % '|'.join(STATEMENTS), + bygroups(Whitespace, Keyword, Text)), + # Long options carry the meaning on a wic line; bash leaves + # them as plain text because it has no notion of them. + (r'--[\w-]+', Name.Attribute), + # wic tests the first character of the stripped line, so a + # comment may be indented and is never trailing. + (r'^\s*#.*$', Comment.Single), + inherit, + ], + } + + +def setup(app): + app.add_lexer('wks', WksLexer) + return { + 'version': __version__, + 'parallel_read_safe': True, + 'parallel_write_safe': True, + } From patchwork Wed Nov 25 15:45:33 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Trevor Woerner X-Patchwork-Id: 105674 Received: from mail-ej1-f52.google.com (mail-ej1-f52.google.com [209.85.218.52]) by mx.groups.io with SMTP id smtpd.msgproc02-g2.44554.1795621552095457597 for ; Wed, 25 Nov 2026 07:45:52 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@gmail.com header.s=20260707 header.b=oyCOFLcL; spf=pass (domain: gmail.com, ip: 209.85.218.52, mailfrom: twoerner@gmail.com) Received: by mail-ej1-f52.google.com with SMTP id a640c23a62f3a-c513a854320so106047666b.0 for ; Wed, 25 Nov 2026 07:45:51 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1795621550; x=1796226350; darn=lists.yoctoproject.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to:content-type; bh=095YauQbPBD4KFi9Tq8ouZrN6H1Gyzpl3CIotwnN3Uc=; b=oyCOFLcLoNqCLsGPGLcnlBSvzcNXNeo/O3GwJyejjj80v4ggtxXa1QECD3uFMh3EK8 w+zxHqbS6R4AOCAa7z6UQJg2EPM1xrgoydktxpLO1qh3bX2lHB0+ODH/a1H0uxIHRWYx Vc+PIBA6jH/cNKHqEi/pO6mgs9JEO0NDqUMvqcuG+QcJFaFvk+yB9u/0FBV8is1xM92h 0vFfe54LBqGs3ETx7BwBLsVdO64JNbOUCQCcYxJUbS58oTnLvvSAVrhaX0WauRrtw1q6 C7JORwIN+0ZSEDnxMtEIvLSmkLO1pKkFQhKYzn+iWTMmvDtneWxYLkRfueW271P45TUD OSfg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795621550; x=1796226350; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-gg:x-gm-message-state:from:to :cc:subject:date:message-id:reply-to:content-type; bh=095YauQbPBD4KFi9Tq8ouZrN6H1Gyzpl3CIotwnN3Uc=; b=2RQgzvkdoAyBwBOk6p1QiM1opM0qm2XnWJwUAGewKQ+vRADOkzRHMbQXlaE4RnCODv JTNmJTMiUT4R2cshkmD/VOOTrGGt+xWhaK+k2kDNCqlrCQFsvjDwpS9zwKgR7IurLPXh GeRRm+uHOqKrCLBt43B6gXmJZ0w4aaczR57Ysge1UEKHB6au24OpJRXzXRNQSqMMINWN JZ7HsyWbeoX64PODAlurm/o7pElltRR5/vIvav3Pb+mTtcDoubszLWnI0YT96he50DcK dm9cGKwSSwh08ia4EL8RGMlZmvloEj2Aucd0urmmPzdYScZTh3a7jtHy4n7gOXgutQ9V zHCQ== X-Gm-Message-State: APuU4Z+RVVfbsiGCHeeL7fythwrI72pEbrlRfFc1oToMVEa32axNG/qT Gi9I9m4m2Weprbn4s6sROppXeQBju57aUXYaDKmJw/H1le7/AQfjfSa0ox9jjA== X-Gm-Gg: AZFdTZfZP+WnSTLcjdsRcGsS8xSGUN1RE8lQhQb2CxfRpNtk0R6RTGW2gVTN6jThTB4 v9PG+M3Xc+CqSRg4Uvh1FXHSi5NOXGvlB6qBvU1rxVaQMpBmhRoar5sCWGvGP53t51p6DmKZ0zW nd/MeBGA/eK1ghbCc9JG3vcLQkWjh8Amen7FeL/fjEpAp4OSciGgITLKNjkKiItqrwa1gvJhdmN 6p/zkyWWDVNEt9NtZdMDEQ8uH66qKjKaL12DY5FstuKRMm7nJ/RkzctjabhPW8KMmtU3PZlcVyg 0j0z2m8rPXiZg6BfSqEkB0+XQr+YGPJMUZs/qmPXY//UB3QDB31+hWukQOv6fajP+U8hwgvzKwW vlwS9ftCzVMKVQ6170b9jTiS5KHOp9oV2P3u/hau65KW8l/EQthr0o8BAwt6ZBQ+ak2GcxYqMSZ 5YT6WDIbLlPV3wVYwIKdWhx89Jaczz8I9LPtd5cTytcQIBmCUc4zwfFYy4FzOsYZh7OIV+ajcVZ 6fhSXKbBf0fjpzGDZjd7Jbh+SKaMKT4tuLbLlG7zAYF2pjmenT4mseRBzy4BmkxWXJAVCZ7U3O7 NlNrr/jltjjKrAHjxsewZJjtO7ajEmQnGqBDnankr/eGzdxfjlh6OhZWXir/o+VzgG8WWJQE3qq y1sFdgG2VvmYscO1cjKc3hd0pZO4pdNo= X-Received: by 2002:a17:906:2445:b0:c51:257b:6c3e with SMTP id a640c23a62f3a-c513a84d6dbmr1164632166b.10.1795621548546; Wed, 25 Nov 2026 07:45:48 -0800 (PST) Return-Path: Received: from localhost.localdomain (pppoe-209-91-167-254.vianet.ca. [209.91.167.254]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-c513aec5115sm651892066b.51.2026.11.25.07.45.46 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 25 Nov 2026 07:45:46 -0800 (PST) From: Trevor Woerner To: docs@lists.yoctoproject.org Subject: [PATCH 5/7] sphinx: add a lexer for pydevshell sessions Date: Wed, 25 Nov 2026 10:45:33 -0500 Message-ID: <20261125154535.3486104-6-twoerner@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20261125154535.3486104-1-twoerner@gmail.com> References: <20261125154535.3486104-1-twoerner@gmail.com> MIME-Version: 1.0 List-Id: X-Webhook-Received: from 45-33-107-173.ip.linodeusercontent.com [45.33.107.173] by lin-tor-korg-lkml-alma10-1 with HTTPS for ; Wed, 25 Nov 2026 15:45:54 -0000 X-Groupsio-URL: https://lists.yoctoproject.org/g/docs/message/10840 The development manual shows a session in BitBake's Python development shell, and no lexer reads it: console wants a prompt ending in $, #, or %, pycon wants >>>, and both mark the whole block as program output, which the theme greys. The prompt cannot be changed to suit them either, since devshell.bbclass is what sets it. Teach a session lexer the prompt instead, with Python inside it, so the expressions the reader types are highlighted as Python and the results are not. AI-Generated: codex/claude-opus 5.5 (xhigh) Signed-off-by: Trevor Woerner --- documentation/conf.py | 3 +- documentation/sphinx/pydevshell-lexer.py | 48 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 documentation/sphinx/pydevshell-lexer.py diff --git a/documentation/conf.py b/documentation/conf.py index f89926549d20..3a7e3c920fc4 100644 --- a/documentation/conf.py +++ b/documentation/conf.py @@ -83,7 +83,8 @@ extensions = [ 'bitbake-lexer', 'bitbake-placeholder', 'scc-lexer', - 'wks-lexer' + 'wks-lexer', + 'pydevshell-lexer' ] # current_version = "dev" diff --git a/documentation/sphinx/pydevshell-lexer.py b/documentation/sphinx/pydevshell-lexer.py new file mode 100644 index 000000000000..a0dd7c9fa684 --- /dev/null +++ b/documentation/sphinx/pydevshell-lexer.py @@ -0,0 +1,48 @@ +"""Lexer for ``bitbake -c pydevshell`` sessions. + +The development manual shows a session in BitBake's Python development +shell: expressions typed at a ``pydevshell> `` prompt with their results +beneath. No existing lexer reads it. ``console`` is a shell session and +wants a prompt ending in ``$``, ``#``, or ``%``; ``pycon`` wants ``>>>``. +Both mark the whole block as program output, which the theme renders in +grey, so the block ends up dimmer than the prose around it and no better +told apart. + +The prompt is not ours to change: ``devshell.bbclass`` sets +``ps1 = "pydevshell> "``, so what the manual shows is what the reader +sees. That leaves teaching a lexer the prompt as the only way to render +one of these correctly. + +``ShellSessionBaseLexer`` does the work once ``_ps1rgx`` matches: it +splits the typed line from its output and hands the typed part to an inner +lexer, which here is Python. +""" +import re + +from pygments.lexers.python import PythonLexer +from pygments.lexers.shell import ShellSessionBaseLexer + +__version__ = '1.0' + + +class PyDevShellSessionLexer(ShellSessionBaseLexer): + """A session in BitBake's Python development shell.""" + + name = 'BitBake pydevshell session' + aliases = ['pydevshell'] + filenames = [] + mimetypes = [] + url = 'https://docs.yoctoproject.org/dev-manual/python-development-shell.html' + + _innerLexerCls = PythonLexer + _ps1rgx = re.compile(r'^(pydevshell> )(.*\n?)') + _ps2 = '... ' + + +def setup(app): + app.add_lexer('pydevshell', PyDevShellSessionLexer) + return { + 'version': __version__, + 'parallel_read_safe': True, + 'parallel_write_safe': True, + } From patchwork Wed Nov 25 15:45:34 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Trevor Woerner X-Patchwork-Id: 105675 Received: from mail-ej1-f42.google.com (mail-ej1-f42.google.com [209.85.218.42]) by mx.groups.io with SMTP id smtpd.msgproc01-g2.44585.1795621553662626040 for ; Wed, 25 Nov 2026 07:45:53 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@gmail.com header.s=20260707 header.b=Y4dpLUpk; spf=pass (domain: gmail.com, ip: 209.85.218.42, mailfrom: twoerner@gmail.com) Received: by mail-ej1-f42.google.com with SMTP id a640c23a62f3a-c5188e4980fso109396166b.2 for ; Wed, 25 Nov 2026 07:45:53 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1795621552; x=1796226352; darn=lists.yoctoproject.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to:content-type; bh=l/L3pCA0ank4LCLtWIj9065zBYaq4O8cnQa00w7Ma8c=; b=Y4dpLUpklT38GvtUQDnCobv1zc0QBpYcAz5H3ggvOlQD19vAmsJk+zhdU5W18aqsiE 7xYUGLWcggO4aSZu4GcSmY6EslQkFKvn3Ie5vXIfx29FGUJ2cNMCRDelmDYp9Ro89hfS gC/D67YEZLHM3XCcrEg5GgBT+1oiwP0P45CpPEtfCjIMgXX1E9QEJs/H0UYYJDQKg4nR 3WozTH1jobb0sZvO8qcnDV4O1SRk4fHdw4IKPVDPYcla5Lb4BwyePweyZIidf/FMntkQ Ndf4+wOmQOxADROsIiddRW4Q8XemmE9ggYXjoJKbtH9ZxwraLkyC1QrWnztxNoX5Z2U8 bRLQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795621552; x=1796226352; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-gg:x-gm-message-state:from:to :cc:subject:date:message-id:reply-to:content-type; bh=l/L3pCA0ank4LCLtWIj9065zBYaq4O8cnQa00w7Ma8c=; b=OFihEHbrtl6Y0Nr2nEklNCy5/IeoULO07AgM2w/F5SvsULYa9BJMyjagi1CewgAqm2 ZW8Vd3113GifGOLI7OQCRCHsSmhYQVrOxhLcWhK3e9lfC1nq5BFt27fUR7ObYzHyOvuN gLxgqPZL96Zm54F2UAoGg91/XIophxXYNvK50wBunmE3kicGN/0qrRJjP5SOPvDCZ+Qm T8yU7VZQihcbATQz9WfnvzruCYTrsXZ8o4d81Tn46OmwIBbF1nV7Q0w7K52Fkvp4yVQH pYrL08IPZ3iCH3E+4ucZSt4lQpESVqMMsHVuXips95BLfG2xm+CilLWsgZ6otXMakVFR v4uQ== X-Gm-Message-State: APuU4Z8vIkLhlA0iJL83Jz26trs7LWsUq92T91QnGerIu5sM2f6Tsvx0 jVd/saDDQbmPJYbuS+YLaPwe5TDwbGpBhlvXFqO/V5KKIwigw0o3q+0U4ytw5w== X-Gm-Gg: AZFdTZf2x54r28FozJ09CBIPGNmr24XyDrRE1ldrqWjBogAEtBYNsnzTgVUkKCzomSL TcOby6L89P6sE4Jx243kaZWkApfHbJK6Pdy2/P+jRe6oynd3KTJAV/JouJD/pqhIzBUIX9hkglf q8h11zjzpvM8GP0dM26MBRFd/OcbVmE3+iOxfDgK/87lWVtBrRbKB6b5CTaIfT4PocyzNr2fcmX o/TvymbDiZD1PyJ/Kfe1PIgYqOPwqn+7WcOSa43cV6UY0Qr7FIXz6OqTmdu5uRzXQPM3netJyhp +MdYJMm59JixFoz9U3j72XxLEQ2+/bIN7wDMJGTk+rkidIGWwxZKolQc7eiTzA9pLb+POcsDByX oDgGdlQveUuc+YrZR+aCCAw9pKDMoV+Ri6JSkexHDGPMUnukR0Ssjgv706jEaMrD/zxFDoz+hL+ hnLpeJFtDWJmmcxPfDF244tx6KBLmyjdU+ptnBOBezSqGqcConeRwNYQstCgaRRnSC4IuS5Q5kq AyXeXG42ul0EsxtnWnHlLVXftDvZNHrCHMu2PuvNObqsuq3PTd4lLaKoagt7agutr8A3Qui8oUM MbMW12Onwig2tIALqi9M+GikEpjSCodsoKuUJF+5pxeFRqcejJYA3954vYz2avlXUrpEBiK5VWG LbFJ1vQqjHW/amNCPwm8wAtQGwuQUTJE= X-Received: by 2002:a17:906:f8d2:b0:c50:bf14:8eb1 with SMTP id a640c23a62f3a-c513a84d84emr1169668066b.14.1795621551708; Wed, 25 Nov 2026 07:45:51 -0800 (PST) Return-Path: Received: from localhost.localdomain (pppoe-209-91-167-254.vianet.ca. [209.91.167.254]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-c513aec5115sm651892066b.51.2026.11.25.07.45.50 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 25 Nov 2026 07:45:50 -0800 (PST) From: Trevor Woerner To: docs@lists.yoctoproject.org Subject: [PATCH 6/7] sphinx: read a bare "#" in a console block as output Date: Wed, 25 Nov 2026 10:45:34 -0500 Message-ID: <20261125154535.3486104-7-twoerner@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20261125154535.3486104-1-twoerner@gmail.com> References: <20261125154535.3486104-1-twoerner@gmail.com> MIME-Version: 1.0 List-Id: X-Webhook-Received: from 45-33-107-173.ip.linodeusercontent.com [45.33.107.173] by lin-tor-korg-lkml-alma10-1 with HTTPS for ; Wed, 25 Nov 2026 15:45:55 -0000 X-Groupsio-URL: https://lists.yoctoproject.org/g/docs/message/10841 Pygments treats "$", "#", and "%" alike as prompts and lets the preamble before them be empty, so a line opening with "#" is taken for a root prompt and the rest of it is lexed as the command it introduces. Across these manuals that line is a comment or a line of program output every time, never a prompt: a root prompt carries the host preamble saying whose root it is. Require that preamble before a "#". The line then falls through to Generic.Output, which is what it was, and the theme stops showing perf headers and generated-file comments as commands somebody typed. AI-Generated: codex/claude-opus 5.5 (xhigh) Signed-off-by: Trevor Woerner --- documentation/conf.py | 3 +- documentation/sphinx/console-lexer.py | 53 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 documentation/sphinx/console-lexer.py diff --git a/documentation/conf.py b/documentation/conf.py index 3a7e3c920fc4..5db20ff021fc 100644 --- a/documentation/conf.py +++ b/documentation/conf.py @@ -84,7 +84,8 @@ extensions = [ 'bitbake-placeholder', 'scc-lexer', 'wks-lexer', - 'pydevshell-lexer' + 'pydevshell-lexer', + 'console-lexer' ] # current_version = "dev" diff --git a/documentation/sphinx/console-lexer.py b/documentation/sphinx/console-lexer.py new file mode 100644 index 000000000000..0f9eaa4ce33e --- /dev/null +++ b/documentation/sphinx/console-lexer.py @@ -0,0 +1,53 @@ +"""A console session lexer that reads a bare ``#`` as output, not a prompt. + +Pygments treats ``$``, ``#``, and ``%`` alike and allows the preamble +before them to be empty, so a line beginning ``#`` is a root prompt and +the rest of the line is lexed as the command it introduces. In these +manuals that is wrong far more often than it is right: a ``#`` opening a +line is a comment or a line of program output, and a root prompt carries +the ``user@host:path`` preamble that says whose root it is. + +Requiring that preamble before a ``#`` is the whole of the change. +``$`` and ``%`` keep Pygments' behaviour exactly, bare prompt included. +A line that is no longer a prompt falls through to ``Generic.Output``, +which is what it always was. + +This is a local convention rather than a universal one - outside these +manuals a bare ``#`` really is how a root shell prompts - so it belongs +here and not upstream. +""" +import re + +from pygments.lexers.shell import BashSessionLexer + +__version__ = '1.0' + +# Pygments' own preamble alternation, spelled twice: once as it has it, +# and once with the empty branch removed. Keeping its wording rather than +# writing a tidier one means a prompt shape it learns later still works. +_PREAMBLE = (r'(?:\[.*?\])|(?:\(\S+\))?' + r'(?:| |sh\S*?|\w+\S+[@:]\S+(?:\s+\S+)?|\[\S+[@:][^\n]+\].+)') +_NAMED = (r'(?:\[.*?\])|(?:\(\S+\))?' + r'(?:sh\S*?|\w+\S+[@:]\S+(?:\s+\S+)?|\[\S+[@:][^\n]+\].+)') + + +class ConsoleSessionLexer(BashSessionLexer): + """A console session in which a bare ``#`` is not a root prompt.""" + + name = 'Console session' + aliases = ['console'] + filenames = [] + mimetypes = [] + + _ps1rgx = re.compile( + r'^((?:' + _PREAMBLE + r')\s*[$%]\s*' + r'|(?:' + _NAMED + r')\s*#\s*)(.*\n?)') + + +def setup(app): + app.add_lexer('console', ConsoleSessionLexer) + return { + 'version': __version__, + 'parallel_read_safe': True, + 'parallel_write_safe': True, + } From patchwork Wed Nov 25 15:45:35 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Trevor Woerner X-Patchwork-Id: 105676 Received: from mail-ej1-f53.google.com (mail-ej1-f53.google.com [209.85.218.53]) by mx.groups.io with SMTP id smtpd.msgproc01-g2.44586.1795621556657482999 for ; Wed, 25 Nov 2026 07:45:56 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@gmail.com header.s=20260707 header.b=qQUG3AnZ; spf=pass (domain: gmail.com, ip: 209.85.218.53, mailfrom: twoerner@gmail.com) Received: by mail-ej1-f53.google.com with SMTP id a640c23a62f3a-c4d2b741ed9so962592166b.2 for ; Wed, 25 Nov 2026 07:45:56 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1795621555; x=1796226355; darn=lists.yoctoproject.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to:content-type; bh=8xm2pkiBKoAFYcjiRQ32m42vtUPVgV1pqxNkaVwsL3Y=; b=qQUG3AnZc5eCfuD9YXAdLibpKbjDAcTiLB8GF+1Ijw6tGGB+rWyR+x+zv0Y0PryxTX zZpbfTspJoA7V0GDnv9pgVzUDaL+itZtyefP5+20JjTtd/VbcoX3KYnB7RR0YfXN1CEz /WGPtYxNzbym5RLCewrbF85AuTkOb15Mp+02YKJqQaMRuW2i8Kx67aNIktS+8R1zwdOx H5zw6jUuIhYq3kJGKTQ2I8UoIAq6iVGJVqCbx+Ofhjln3JNUFAIozTPqR9NyKA9/9ni8 07cUOOkvtDzF44XA9AaipQnRVH+43pa9s1soX6Ki1aLb3XsWnwHH1vuybVXqDkgYlb2+ 4pfg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795621555; x=1796226355; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-gg:x-gm-message-state:from:to :cc:subject:date:message-id:reply-to:content-type; bh=8xm2pkiBKoAFYcjiRQ32m42vtUPVgV1pqxNkaVwsL3Y=; b=eX9N8CajVkqgfq7l3QOqXUojEkQkdsRbIE00NDiZhlSjGnQ2OmohvXQ1tXEmOTdhlu PZFGjzrTIoY+/diqD2PGO4AqZFkux51sFGCeeJsxHL5U7Y6EMxXlodL5pGojreL4taIT 46dn4vCHlvq7e/ksLz7rPtalhsPA3VfhGryZDjQpiBg7HkG85GhnahuHjFgTdZBHvvbn lYRKiX6qKvlF/t545KTHgW6Z1JT0x6sXQsQQdk6AK3+/P+qmrW7/c8gTOdvyT/Zxrpam 4CkZ0XOrmrOFcS/tAkM99zdgLXMcn4gzmFyjnLnMCDccI4gdoMy4Kl06qotXogQQ3vmM bnJg== X-Gm-Message-State: APuU4Z9KwnbiBZEnuoPqfxTANQ5T6iGyWEKxqVQz6ndXOcjNG5AhRKMJ LS1pA+Jmb4X0CBl/DCVoXM9KIvxqcUA+9E7eqpS4S4cQA54nPiHFO1u3z2MHNQ== X-Gm-Gg: AZFdTZfIfTTyLxac1+24AlEYaj74iUkHgglLrSs9Bv852YUvpQuRfxdqT7gnfW6/Ip5 VjIO2n/goRYoYn8rTIif5Vq9tW6tRxVyX53v0Czx0F9Cm8QrEgHjJzJnLr7BdJd8XqbDRbmK4zT 0MQhIDmYqcRynIYTmDewe6m/p79i3o7P+y+ro3slZy66TahDMa2O9Xp3WDeJHK+nO42Qad3YCYZ N2gNaSz+Lxu4uwdA5DiNvT0YUG1iugYy2Mw3cWILjwmrLXkhJJjREonMa9TxN/EOwXy3spPEB6y 0ipZGa4Jm4kmF9RYay1vfrVIXPwUnjEHKT64ejZrHg/aH+R9CYMQRWOPv2DfM5BzoCAfB1/QxAd f4s24cts4HefduJY2YEpiolz1LoOFmih5rnb9etnSnu4zJp9rXQBfxZlVq8uYgcbZIHKaxHgyRx rEtAAXG81T1G82pmQDwAb/+xXSNk5nzlne9w9AHELKZoBzzc3EENT4/GqBNEE2UYSFlmRJul1zN zHE9KncCLh8GSLdMFnqGbJ2zHInR5svVFWh6zu//763jSQtvpbx0U2b+ReNIEEyJjlUrrGuD0Od DNYjqELLF9dIC4AUdXc54wWmIEYTK15lvS2dVNsO+sqn5TThu350ZxBPiWNb6izDyK9ALi+/VKF hCgmKLt3RJXJaXCa1ZzrKRE2s8TpDYGk= X-Received: by 2002:a17:906:eec9:b0:c51:5589:35a1 with SMTP id a640c23a62f3a-c515589d211mr1157463666b.5.1795621554578; Wed, 25 Nov 2026 07:45:54 -0800 (PST) Return-Path: Received: from localhost.localdomain (pppoe-209-91-167-254.vianet.ca. [209.91.167.254]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-c513aec5115sm651892066b.51.2026.11.25.07.45.51 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 25 Nov 2026 07:45:52 -0800 (PST) From: Trevor Woerner To: docs@lists.yoctoproject.org Subject: [PATCH 7/7] sphinx: mark placeholders in console and plain-text examples Date: Wed, 25 Nov 2026 10:45:35 -0500 Message-ID: <20261125154535.3486104-8-twoerner@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20261125154535.3486104-1-twoerner@gmail.com> References: <20261125154535.3486104-1-twoerner@gmail.com> MIME-Version: 1.0 List-Id: X-Webhook-Received: from 45-33-107-173.ip.linodeusercontent.com [45.33.107.173] by lin-tor-korg-lkml-alma10-1 with HTTPS for ; Wed, 25 Nov 2026 15:46:05 -0000 X-Groupsio-URL: https://lists.yoctoproject.org/g/docs/message/10842 Most of the values a reader has to replace are in the commands the manuals tell them to run, where and look exactly like text to type verbatim. This adds console-placeholder and text-placeholder. A console line containing a placeholder is already valid, so they re-label the run with a filter over the finished token stream rather than a new grammar. The filter works on offsets, because the shell lexer reads "<" as a redirection and splits the run before a filter sees it. Both are opt-in per block, because angle brackets also mean other things, such as the kernel's task in an ftrace listing. A C include is the one case the filter decides for itself, since nobody substitutes the header in "#include ". AI-Generated: codex/claude-opus 5.5 (xhigh) Signed-off-by: Trevor Woerner --- documentation/conf.py | 3 +- .../sphinx-static/theme_overrides.css | 2 +- documentation/sphinx/placeholder-lexers.py | 134 ++++++++++++++++++ 3 files changed, 137 insertions(+), 2 deletions(-) create mode 100644 documentation/sphinx/placeholder-lexers.py diff --git a/documentation/conf.py b/documentation/conf.py index 5db20ff021fc..d56c648d8701 100644 --- a/documentation/conf.py +++ b/documentation/conf.py @@ -85,7 +85,8 @@ extensions = [ 'scc-lexer', 'wks-lexer', 'pydevshell-lexer', - 'console-lexer' + 'console-lexer', + 'placeholder-lexers' ] # current_version = "dev" diff --git a/documentation/sphinx-static/theme_overrides.css b/documentation/sphinx-static/theme_overrides.css index 2083ebb5baf4..2120c43245cc 100644 --- a/documentation/sphinx-static/theme_overrides.css +++ b/documentation/sphinx-static/theme_overrides.css @@ -264,7 +264,7 @@ a.sd-badge { survives a monochrome printout. The border is #5b8db9 rather than something paler because it has to clear 3:1 against the code block to count as a boundary: a lighter blue measured 2:1 and disappeared. */ -.rst-content .highlight-bitbake-placeholder .ge { +.rst-content div[class*="-placeholder"] .ge { color: #144e8c; font-style: italic; font-weight: 600; diff --git a/documentation/sphinx/placeholder-lexers.py b/documentation/sphinx/placeholder-lexers.py new file mode 100644 index 000000000000..668a3b71e992 --- /dev/null +++ b/documentation/sphinx/placeholder-lexers.py @@ -0,0 +1,134 @@ +"""Marking placeholders in languages whose lexers already accept them. + +``bitbake-placeholder`` exists because BitBake *rejects* a placeholder in +a variable name: ``<`` is not in its name charset, so +``SRCREV:pn-`` is not an assignment at all until a rule says so. +Widening a grammar has to be done in the grammar. + +Everywhere else there is nothing to widen. ``$ devtool modify `` +is a perfectly ordinary console line; the placeholder simply looks like +text to type verbatim. All that is needed is to re-label the run, and +that can be done after lexing, for any language, without touching how it +parses. + +So this carries a filter rather than a dialect, and builds the dialects +from it. Most of the manuals' placeholders are in console blocks, so this +is where the convention is most often unreadable. + +The filter works on absolute offsets rather than on token values, because +a base lexer may already have split the run: the shell lexer reads ``<`` +as a redirection operator, so ```` never arrives as one token. + +Output is marked as well as input. A session lexer can tell a typed line +from a printed one, but that does not decide whether a run is a +placeholder: a usage synopsis is printed by the tool and exists precisely +to say what the reader supplies. + +Each dialect is opt-in per block. Angle brackets mean other things, such +as ``-0`` in an ftrace listing, where ```` is the kernel's own +name for the idle task. Apart from a C ``#include``, which is excluded +below, no pattern can tell those from a placeholder, so a person decides +per block, and a block whose printed text should not be marked is simply +left out. + +An address in the angle brackets RFC 822 wants is safe by construction +rather than by exclusion: ``@`` is not in the placeholder charset. +""" +import importlib +import re + +from pygments.filter import Filter +from pygments.lexers.special import TextLexer +from pygments.token import Generic + +# The corrected console lexer, not Pygments' own, so a placeholder block +# reads a bare "#" the same way every other console block does. The +# module name is not an identifier, so it cannot be a plain import. +BashSessionLexer = importlib.import_module('console-lexer').ConsoleSessionLexer + +__version__ = '1.0' + +# Opens with a letter, then word characters, spaces and the punctuation a +# path or a dotted name needs. No "@", so an e-mail address never matches. +PLACEHOLDER = re.compile(r'<[A-Za-z][\w .\'/-]*>') + +# The one bracketed form that is never a placeholder however a block is +# labelled, because it is C rather than prose: the reader does not +# substitute the header in "#include ". This is mechanical +# and needs no per-block judgement, unlike the opt-in itself. +INCLUDE = re.compile(r'#\s*include\s*$') + + +def placeholder_spans(text): + """Offsets of the runs to mark.""" + return [m.span() for m in PLACEHOLDER.finditer(text) + if not INCLUDE.search(text[:m.start()].rsplit('\n', 1)[-1])] + + +class PlaceholderFilter(Filter): + """Re-label placeholder runs in a finished token stream.""" + + def filter(self, lexer, stream): + tokens = list(stream) + text = ''.join(value for _, value in tokens) + spans = placeholder_spans(text) + if not spans: + yield from tokens + return + + split, pos = [], 0 + for ttype, value in tokens: + end = pos + len(value) + cuts = sorted({pos, end} | {edge for span in spans + for edge in span if pos < edge < end}) + for a, b in zip(cuts, cuts[1:]): + inside = any(s <= a and b <= e for s, e in spans) + split.append(((Generic.Emph if inside else ttype), text[a:b])) + pos = end + + # Merge adjacent pieces of the same type. Keeping the base lexer's + # boundaries emits one span per fragment, and an outlined style + # then draws a box around each half of the same placeholder. + merged = [] + for ttype, value in split: + if merged and merged[-1][0] is ttype: + merged[-1] = (ttype, merged[-1][1] + value) + else: + merged.append((ttype, value)) + yield from merged + + +def _filtered(class_name, lexer_name, alias, base): + """A copy of `base` that marks placeholders and changes nothing else.""" + + def __init__(self, **options): + base.__init__(self, **options) + self.add_filter(PlaceholderFilter()) + + return type(class_name, (base,), { + '__init__': __init__, + '__doc__': '%s, with placeholders marked.' % lexer_name, + 'name': lexer_name, + 'aliases': [alias], + 'filenames': [], + 'mimetypes': [], + }) + + +ConsolePlaceholderLexer = _filtered( + 'ConsolePlaceholderLexer', 'Console session with placeholders', + 'console-placeholder', BashSessionLexer) + +TextPlaceholderLexer = _filtered( + 'TextPlaceholderLexer', 'Plain text with placeholders', + 'text-placeholder', TextLexer) + + +def setup(app): + for lexer in (ConsolePlaceholderLexer, TextPlaceholderLexer): + app.add_lexer(lexer.aliases[0], lexer) + return { + 'version': __version__, + 'parallel_read_safe': True, + 'parallel_write_safe': True, + }