1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
|
"""Custom docutils node types for argparse documentation.
This module defines custom node types that represent the structure of
CLI documentation, along with HTML visitor functions for rendering.
"""
from __future__ import annotations
import typing as t
from docutils import nodes
if t.TYPE_CHECKING:
from sphinx.writers.html5 import HTML5Translator
# Import the lexer - use absolute import from parent package
import pathlib
import sys
# Add parent directory to path for lexer import
_ext_dir = pathlib.Path(__file__).parent.parent
if str(_ext_dir) not in sys.path:
sys.path.insert(0, str(_ext_dir))
from argparse_lexer import ArgparseUsageLexer # noqa: E402
from sphinx_argparse_neo.utils import strip_ansi # noqa: E402
def _token_to_css_class(token_type: t.Any) -> str:
"""Map a Pygments token type to its CSS class abbreviation.
Pygments uses hierarchical token names like Token.Name.Attribute.
These map to CSS classes using abbreviations of the last two parts:
- Token.Name.Attribute → 'na' (Name.Attribute)
- Token.Generic.Heading → 'gh' (Generic.Heading)
- Token.Punctuation → 'p' (just Punctuation)
Parameters
----------
token_type : Any
A Pygments token type (from pygments.token).
Returns
-------
str
CSS class abbreviation, or empty string if not mappable.
Examples
--------
>>> from pygments.token import Token
>>> _token_to_css_class(Token.Name.Attribute)
'na'
>>> _token_to_css_class(Token.Generic.Heading)
'gh'
>>> _token_to_css_class(Token.Punctuation)
'p'
>>> _token_to_css_class(Token.Text.Whitespace)
'tw'
"""
type_str = str(token_type)
# Token string looks like "Token.Name.Attribute" or "Token.Punctuation"
parts = type_str.split(".")
if len(parts) >= 3:
# Token.Name.Attribute -> "na" (first char of each of last two parts)
return parts[-2][0].lower() + parts[-1][0].lower()
elif len(parts) == 2:
# Token.Punctuation -> "p" (first char of last part)
return parts[-1][0].lower()
return ""
def _highlight_usage(usage_text: str, encode: t.Callable[[str], str]) -> str:
"""Tokenize usage text and wrap tokens in highlighted span elements.
Uses ArgparseUsageLexer to tokenize the usage string, then wraps each
token in a <span> with the appropriate CSS class for styling.
Parameters
----------
usage_text : str
The usage string to highlight (should include "usage: " prefix).
encode : Callable[[str], str]
HTML encoding function (typically translator.encode).
Returns
-------
str
HTML string with tokens wrapped in styled <span> elements.
Examples
--------
>>> def mock_encode(s: str) -> str:
... return s.replace("&", "&").replace("<", "<")
>>> html = _highlight_usage("usage: cmd [-h]", mock_encode)
>>> '<span class="gh">usage:</span>' in html
True
>>> '<span class="nl">cmd</span>' in html
True
>>> '<span class="na">-h</span>' in html
True
"""
lexer = ArgparseUsageLexer()
parts: list[str] = []
for tok_type, tok_value in lexer.get_tokens(usage_text):
if not tok_value:
continue
css_class = _token_to_css_class(tok_type)
escaped = encode(tok_value)
type_str = str(tok_type).lower()
# Skip wrapping for whitespace and plain text tokens
if css_class and "whitespace" not in type_str and "text" not in type_str:
parts.append(f'<span class="{css_class}">{escaped}</span>')
else:
parts.append(escaped)
return "".join(parts)
def _highlight_argument_names(
names: list[str], metavar: str | None, encode: t.Callable[[str], str]
) -> str:
"""Highlight argument names and metavar with appropriate CSS classes.
Short options (-h) get class 'na' (Name.Attribute).
Long options (--help) get class 'nt' (Name.Tag).
Positional arguments get class 'nl' (Name.Label).
Metavars get class 'nv' (Name.Variable).
Parameters
----------
names : list[str]
List of argument names (e.g., ["-v", "--verbose"]).
metavar : str | None
Optional metavar (e.g., "FILE", "PATH").
encode : Callable[[str], str]
HTML encoding function.
Returns
-------
str
HTML string with highlighted argument signature.
Examples
--------
>>> def mock_encode(s: str) -> str:
... return s
>>> html = _highlight_argument_names(["-h", "--help"], None, mock_encode)
>>> '<span class="na">-h</span>' in html
True
>>> '<span class="nt">--help</span>' in html
True
>>> html = _highlight_argument_names(["--output"], "FILE", mock_encode)
>>> '<span class="nv">FILE</span>' in html
True
>>> html = _highlight_argument_names(["sync"], None, mock_encode)
>>> '<span class="nl">sync</span>' in html
True
"""
sig_parts: list[str] = []
for name in names:
escaped = encode(name)
if name.startswith("--"):
sig_parts.append(f'<span class="nt">{escaped}</span>')
elif name.startswith("-"):
sig_parts.append(f'<span class="na">{escaped}</span>')
else:
# Positional argument or subcommand
sig_parts.append(f'<span class="nl">{escaped}</span>')
result = ", ".join(sig_parts)
if metavar:
escaped_metavar = encode(metavar)
result = f'{result} <span class="nv">{escaped_metavar}</span>'
return result
class argparse_program(nodes.General, nodes.Element):
"""Root node for an argparse program documentation block.
Attributes
----------
prog : str
The program name.
Examples
--------
>>> node = argparse_program()
>>> node["prog"] = "myapp"
>>> node["prog"]
'myapp'
"""
pass
class argparse_usage(nodes.General, nodes.Element):
"""Node for displaying program usage.
Contains the usage string as a literal block.
Examples
--------
>>> node = argparse_usage()
>>> node["usage"] = "myapp [-h] [--verbose] command"
>>> node["usage"]
'myapp [-h] [--verbose] command'
"""
pass
class argparse_group(nodes.General, nodes.Element):
"""Node for an argument group (positional, optional, or custom).
Attributes
----------
title : str
The group title.
description : str | None
Optional group description.
Examples
--------
>>> node = argparse_group()
>>> node["title"] = "Output Options"
>>> node["title"]
'Output Options'
"""
pass
class argparse_argument(nodes.Part, nodes.Element):
"""Node for a single CLI argument.
Attributes
----------
names : list[str]
Argument names/flags.
help : str | None
Help text.
default : str | None
Default value string.
choices : list[str] | None
Available choices.
required : bool
Whether the argument is required.
metavar : str | None
Metavar for display.
Examples
--------
>>> node = argparse_argument()
>>> node["names"] = ["-v", "--verbose"]
>>> node["names"]
['-v', '--verbose']
"""
pass
class argparse_subcommands(nodes.General, nodes.Element):
"""Container node for subcommands section.
Examples
--------
>>> node = argparse_subcommands()
>>> node["title"] = "Commands"
>>> node["title"]
'Commands'
"""
pass
class argparse_subcommand(nodes.General, nodes.Element):
"""Node for a single subcommand.
Attributes
----------
name : str
Subcommand name.
aliases : list[str]
Subcommand aliases.
help : str | None
Subcommand help text.
Examples
--------
>>> node = argparse_subcommand()
>>> node["name"] = "sync"
>>> node["aliases"] = ["s"]
>>> node["name"]
'sync'
"""
pass
# HTML Visitor Functions
def visit_argparse_program_html(self: HTML5Translator, node: argparse_program) -> None:
"""Visit argparse_program node - start program container.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_program
The program node being visited.
"""
prog = node.get("prog", "")
self.body.append(f'<div class="argparse-program" data-prog="{prog}">\n')
def depart_argparse_program_html(self: HTML5Translator, node: argparse_program) -> None:
"""Depart argparse_program node - close program container.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_program
The program node being departed.
"""
self.body.append("</div>\n")
def visit_argparse_usage_html(self: HTML5Translator, node: argparse_usage) -> None:
"""Visit argparse_usage node - render usage block with syntax highlighting.
The usage text is tokenized using ArgparseUsageLexer and wrapped in
styled <span> elements for semantic highlighting of options, metavars,
commands, and punctuation.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_usage
The usage node being visited.
"""
usage = strip_ansi(node.get("usage", ""))
# Add both argparse-usage class and highlight class for CSS targeting
self.body.append('<pre class="argparse-usage highlight-argparse-usage">')
# Prepend "usage: " and highlight the full usage string
highlighted = _highlight_usage(f"usage: {usage}", self.encode)
self.body.append(highlighted)
def depart_argparse_usage_html(self: HTML5Translator, node: argparse_usage) -> None:
"""Depart argparse_usage node - close usage block.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_usage
The usage node being departed.
"""
self.body.append("</pre>\n")
def visit_argparse_group_html(self: HTML5Translator, node: argparse_group) -> None:
"""Visit argparse_group node - start argument group.
The title is now rendered by the parent section node, so this visitor
only handles the group container and description.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_group
The group node being visited.
"""
title = node.get("title", "")
group_id = title.lower().replace(" ", "-") if title else "arguments"
self.body.append(f'<div class="argparse-group" data-group="{group_id}">\n')
# Title rendering removed - parent section now provides the heading
description = node.get("description")
if description:
self.body.append(
f'<p class="argparse-group-description">{self.encode(description)}</p>\n'
)
self.body.append('<dl class="argparse-arguments">\n')
def depart_argparse_group_html(self: HTML5Translator, node: argparse_group) -> None:
"""Depart argparse_group node - close argument group.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_group
The group node being departed.
"""
self.body.append("</dl>\n")
self.body.append("</div>\n")
def visit_argparse_argument_html(
self: HTML5Translator, node: argparse_argument
) -> None:
"""Visit argparse_argument node - render argument entry with highlighting.
Argument names are highlighted with semantic CSS classes:
- Short options (-h) get class 'na' (Name.Attribute)
- Long options (--help) get class 'nt' (Name.Tag)
- Positional arguments get class 'nl' (Name.Label)
- Metavars get class 'nv' (Name.Variable)
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_argument
The argument node being visited.
"""
names: list[str] = node.get("names", [])
metavar = node.get("metavar")
# Build the argument signature with syntax highlighting
highlighted_sig = _highlight_argument_names(names, metavar, self.encode)
self.body.append(f'<dt class="argparse-argument-name">{highlighted_sig}</dt>\n')
self.body.append('<dd class="argparse-argument-help">')
# Add help text
help_text = node.get("help")
if help_text:
self.body.append(f"<p>{self.encode(help_text)}</p>")
def depart_argparse_argument_html(
self: HTML5Translator, node: argparse_argument
) -> None:
"""Depart argparse_argument node - close argument entry.
Adds default, choices, and type information if present.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_argument
The argument node being departed.
"""
# Add metadata (default, choices, type)
metadata: list[str] = []
default = node.get("default_string")
if default is not None:
metadata.append(f"Default: {self.encode(default)}")
choices = node.get("choices")
if choices:
choices_str = ", ".join(str(c) for c in choices)
metadata.append(f"Choices: {self.encode(choices_str)}")
type_name = node.get("type_name")
if type_name:
metadata.append(f"Type: {self.encode(type_name)}")
required = node.get("required", False)
if required:
metadata.append("Required")
if metadata:
meta_str = " | ".join(metadata)
self.body.append(f'<p class="argparse-argument-meta">{meta_str}</p>')
self.body.append("</dd>\n")
def visit_argparse_subcommands_html(
self: HTML5Translator, node: argparse_subcommands
) -> None:
"""Visit argparse_subcommands node - start subcommands section.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_subcommands
The subcommands node being visited.
"""
title = node.get("title", "Sub-commands")
self.body.append('<div class="argparse-subcommands">\n')
self.body.append(
f'<p class="argparse-subcommands-title">{self.encode(title)}</p>\n'
)
def depart_argparse_subcommands_html(
self: HTML5Translator, node: argparse_subcommands
) -> None:
"""Depart argparse_subcommands node - close subcommands section.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_subcommands
The subcommands node being departed.
"""
self.body.append("</div>\n")
def visit_argparse_subcommand_html(
self: HTML5Translator, node: argparse_subcommand
) -> None:
"""Visit argparse_subcommand node - start subcommand entry.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_subcommand
The subcommand node being visited.
"""
name = node.get("name", "")
aliases: list[str] = node.get("aliases", [])
self.body.append(f'<div class="argparse-subcommand" data-name="{name}">\n')
# Subcommand header
header = name
if aliases:
alias_str = ", ".join(aliases)
header = f"{name} ({alias_str})"
self.body.append(
f'<h4 class="argparse-subcommand-name">{self.encode(header)}</h4>\n'
)
# Help text
help_text = node.get("help")
if help_text:
self.body.append(
f'<p class="argparse-subcommand-help">{self.encode(help_text)}</p>\n'
)
def depart_argparse_subcommand_html(
self: HTML5Translator, node: argparse_subcommand
) -> None:
"""Depart argparse_subcommand node - close subcommand entry.
Parameters
----------
self : HTML5Translator
The Sphinx HTML translator.
node : argparse_subcommand
The subcommand node being departed.
"""
self.body.append("</div>\n")
|