File: argparse_lexer.py

package info (click to toggle)
tmuxp 1.64.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 3,500 kB
  • sloc: python: 17,788; sh: 21; makefile: 6
file content (429 lines) | stat: -rw-r--r-- 15,942 bytes parent folder | download | duplicates (2)
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
"""Pygments lexers for argparse help output.

This module provides custom Pygments lexers for highlighting argparse-generated
command-line help text, including usage lines, section headers, and full help output.

Three lexer classes are provided:
- ArgparseUsageLexer: For usage lines only
- ArgparseHelpLexer: For full -h output (delegates usage to ArgparseUsageLexer)
- ArgparseLexer: Smart auto-detecting wrapper
"""

from __future__ import annotations

from pygments.lexer import RegexLexer, bygroups, include
from pygments.token import Generic, Name, Operator, Punctuation, Text, Whitespace


class ArgparseUsageLexer(RegexLexer):
    """Lexer for argparse usage lines only.

    Handles patterns like:
    - usage: PROG [-h] [--foo FOO] bar {a,b,c}
    - Mutually exclusive: [-a | -b], (--foo | --bar)
    - Choices: {json,yaml,table}
    - Variadic: FILE ..., [FILE ...], [--foo [FOO]]

    Examples
    --------
    >>> from pygments.token import Token
    >>> lexer = ArgparseUsageLexer()
    >>> tokens = list(lexer.get_tokens("usage: cmd [-h]"))
    >>> tokens[0]
    (Token.Generic.Heading, 'usage:')
    >>> tokens[2]
    (Token.Name.Label, 'cmd')
    """

    name = "Argparse Usage"
    aliases = ["argparse-usage"]  # noqa: RUF012
    filenames: list[str] = []  # noqa: RUF012
    mimetypes = ["text/x-argparse-usage"]  # noqa: RUF012

    tokens = {  # noqa: RUF012
        "root": [
            # "usage:" at start of line - then look for program name
            (
                r"^(usage:)(\s+)",
                bygroups(Generic.Heading, Whitespace),  # type: ignore[no-untyped-call]
                "after_usage",
            ),
            # Continuation lines (leading whitespace for wrapped usage)
            (r"^(\s+)(?=\S)", Whitespace),
            include("inline"),
        ],
        "after_usage": [
            # Whitespace
            (r"\s+", Whitespace),
            # Program name (first lowercase word after usage:)
            (r"\b[a-z][-a-z0-9]*\b", Name.Label, "usage_body"),
            # Fallback to inline if something unexpected
            include("inline"),
        ],
        "usage_body": [
            # Whitespace
            (r"\s+", Whitespace),
            # Ellipsis for variadic args (before other patterns)
            (r"\.\.\.", Punctuation),
            # Long options with = value (e.g., --log-level=VALUE)
            (
                r"(--[a-zA-Z0-9][-a-zA-Z0-9]*)(=)([A-Z][A-Z0-9_]*|[a-z][-a-z0-9]*)",
                bygroups(Name.Tag, Operator, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Long options standalone
            (r"--[a-zA-Z0-9][-a-zA-Z0-9]*", Name.Tag),
            # Short options with space-separated value (e.g., -S socket-path)
            (
                r"(-[a-zA-Z0-9])(\s+)([A-Z][A-Z0-9_]*|[a-z][-a-z0-9]*)",
                bygroups(Name.Attribute, Whitespace, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Short options standalone
            (r"-[a-zA-Z0-9]", Name.Attribute),
            # Opening brace - enter choices state
            (r"\{", Punctuation, "choices"),
            # Opening bracket - enter optional state
            (r"\[", Punctuation, "optional"),
            # Closing bracket (fallback for unmatched)
            (r"\]", Punctuation),
            # Opening paren - enter required mutex state
            (r"\(", Punctuation, "required"),
            # Closing paren (fallback for unmatched)
            (r"\)", Punctuation),
            # Choice separator (pipe) for mutex groups
            (r"\|", Operator),
            # UPPERCASE meta-variables (COMMAND, FILE, PATH)
            (r"\b[A-Z][A-Z0-9_]*\b", Name.Variable),
            # Subcommand/positional names (Name.Function for distinct styling)
            (r"\b[a-z][-a-z0-9]*\b", Name.Function),
            # Catch-all for any other text
            (r"[^\s\[\]|(){},]+", Text),
        ],
        "inline": [
            # Whitespace
            (r"\s+", Whitespace),
            # Ellipsis for variadic args (before other patterns)
            (r"\.\.\.", Punctuation),
            # Long options with = value (e.g., --log-level=VALUE)
            (
                r"(--[a-zA-Z0-9][-a-zA-Z0-9]*)(=)([A-Z][A-Z0-9_]*|[a-z][-a-z0-9]*)",
                bygroups(Name.Tag, Operator, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Long options standalone
            (r"--[a-zA-Z0-9][-a-zA-Z0-9]*", Name.Tag),
            # Short options with space-separated value (e.g., -S socket-path)
            (
                r"(-[a-zA-Z0-9])(\s+)([A-Z][A-Z0-9_]*|[a-z][-a-z0-9]*)",
                bygroups(Name.Attribute, Whitespace, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Short options standalone
            (r"-[a-zA-Z0-9]", Name.Attribute),
            # Opening brace - enter choices state
            (r"\{", Punctuation, "choices"),
            # Opening bracket - enter optional state
            (r"\[", Punctuation, "optional"),
            # Closing bracket (fallback for unmatched)
            (r"\]", Punctuation),
            # Opening paren - enter required mutex state
            (r"\(", Punctuation, "required"),
            # Closing paren (fallback for unmatched)
            (r"\)", Punctuation),
            # Choice separator (pipe) for mutex groups
            (r"\|", Operator),
            # UPPERCASE meta-variables (COMMAND, FILE, PATH)
            (r"\b[A-Z][A-Z0-9_]*\b", Name.Variable),
            # Positional/command names (lowercase with dashes)
            (r"\b[a-z][-a-z0-9]*\b", Name.Label),
            # Catch-all for any other text
            (r"[^\s\[\]|(){},]+", Text),
        ],
        "optional": [
            # Nested optional bracket
            (r"\[", Punctuation, "#push"),
            # End optional
            (r"\]", Punctuation, "#pop"),
            # Contents use usage_body rules (subcommands are green)
            include("usage_body"),
        ],
        "required": [
            # Nested required paren
            (r"\(", Punctuation, "#push"),
            # End required
            (r"\)", Punctuation, "#pop"),
            # Contents use usage_body rules (subcommands are green)
            include("usage_body"),
        ],
        "choices": [
            # Choice values (comma-separated inside braces)
            (r"[a-zA-Z0-9][-a-zA-Z0-9_]*", Name.Constant),
            # Comma separator
            (r",", Punctuation),
            # End choices
            (r"\}", Punctuation, "#pop"),
            # Whitespace
            (r"\s+", Whitespace),
        ],
    }


class ArgparseHelpLexer(RegexLexer):
    """Lexer for full argparse -h help output.

    Handles:
    - Usage lines (delegates to ArgparseUsageLexer patterns)
    - Section headers (positional arguments:, options:, etc.)
    - Option entries with help text
    - Indented descriptions

    Examples
    --------
    >>> from pygments.token import Token
    >>> lexer = ArgparseHelpLexer()
    >>> tokens = list(lexer.get_tokens("positional arguments:"))
    >>> any(t[0] == Token.Generic.Subheading for t in tokens)
    True
    >>> tokens = list(lexer.get_tokens("  -h, --help  show help"))
    >>> any(t[0] == Token.Name.Attribute for t in tokens)
    True
    """

    name = "Argparse Help"
    aliases = ["argparse-help"]  # noqa: RUF012
    filenames: list[str] = []  # noqa: RUF012
    mimetypes = ["text/x-argparse-help"]  # noqa: RUF012

    tokens = {  # noqa: RUF012
        "root": [
            # "usage:" line - switch to after_usage to find program name
            (
                r"^(usage:)(\s+)",
                bygroups(Generic.Heading, Whitespace),  # type: ignore[no-untyped-call]
                "after_usage",
            ),
            # Section headers (e.g., "positional arguments:", "options:")
            (r"^([a-zA-Z][-a-zA-Z0-9_ ]*:)\s*$", Generic.Subheading),
            # Option entry lines (indented with spaces/tabs, not just newlines)
            (r"^([ \t]+)", Whitespace, "option_line"),
            # Continuation of usage (leading spaces/tabs followed by content)
            (r"^([ \t]+)(?=\S)", Whitespace),
            # Anything else (must match at least one char to avoid infinite loop)
            (r".+\n?", Text),
            # Standalone newlines
            (r"\n", Whitespace),
        ],
        "after_usage": [
            # Whitespace
            (r"\s+", Whitespace),
            # Program name (first lowercase word after usage:)
            (r"\b[a-z][-a-z0-9]*\b", Name.Label, "usage"),
            # Fallback to usage if something unexpected
            include("usage_inline"),
        ],
        "usage": [
            # End of usage on blank line or section header
            (r"\n(?=[a-zA-Z][-a-zA-Z0-9_ ]*:\s*$)", Text, "#pop:2"),
            (r"\n(?=\n)", Text, "#pop:2"),
            # Usage content - use usage_inline rules (subcommands are green)
            include("usage_inline"),
            # Line continuation
            (r"\n", Text),
        ],
        "usage_inline": [
            # Whitespace
            (r"\s+", Whitespace),
            # Ellipsis for variadic args
            (r"\.\.\.", Punctuation),
            # Long options with = value
            (
                r"(--[a-zA-Z0-9][-a-zA-Z0-9]*)(=)([A-Z][A-Z0-9_]*|[a-z][-a-z0-9]*)",
                bygroups(Name.Tag, Operator, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Long options standalone
            (r"--[a-zA-Z0-9][-a-zA-Z0-9]*", Name.Tag),
            # Short options with value
            (
                r"(-[a-zA-Z0-9])(\s+)([A-Z][A-Z0-9_]*|[a-z][-a-z0-9]*)",
                bygroups(Name.Attribute, Whitespace, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Short options standalone
            (r"-[a-zA-Z0-9]", Name.Attribute),
            # Choices in braces
            (r"\{", Punctuation, "choices"),
            # Optional brackets
            (r"\[", Punctuation, "optional"),
            (r"\]", Punctuation),
            # Required parens (mutex)
            (r"\(", Punctuation, "required"),
            (r"\)", Punctuation),
            # Pipe for mutex
            (r"\|", Operator),
            # UPPERCASE metavars
            (r"\b[A-Z][A-Z0-9_]*\b", Name.Variable),
            # Subcommand/positional names (Name.Function for distinct styling)
            (r"\b[a-z][-a-z0-9]*\b", Name.Function),
            # Other text
            (r"[^\s\[\]|(){},\n]+", Text),
        ],
        "option_line": [
            # Short option with comma (e.g., "-h, --help")
            (
                r"(-[a-zA-Z0-9])(,)(\s*)(--[a-zA-Z0-9][-a-zA-Z0-9]*)",
                bygroups(Name.Attribute, Punctuation, Whitespace, Name.Tag),  # type: ignore[no-untyped-call]
            ),
            # Long options with = value
            (
                r"(--[a-zA-Z0-9][-a-zA-Z0-9]*)(=)([A-Z][A-Z0-9_]*|[a-z][-a-z0-9]*)",
                bygroups(Name.Tag, Operator, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Long options with space-separated metavar
            (
                r"(--[a-zA-Z0-9][-a-zA-Z0-9]*)(\s+)([A-Z][A-Z0-9_]+)",
                bygroups(Name.Tag, Whitespace, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Long options standalone
            (r"--[a-zA-Z0-9][-a-zA-Z0-9]*", Name.Tag),
            # Short options with metavar
            (
                r"(-[a-zA-Z0-9])(\s+)([A-Z][A-Z0-9_]+)",
                bygroups(Name.Attribute, Whitespace, Name.Variable),  # type: ignore[no-untyped-call]
            ),
            # Short options standalone
            (r"-[a-zA-Z0-9]", Name.Attribute),
            # Choices in braces
            (r"\{", Punctuation, "option_choices"),
            # Help text (everything after double space or large gap)
            (r"([ \t]{2,})(.+)$", bygroups(Whitespace, Text)),  # type: ignore[no-untyped-call]
            # End of line - MUST come before \s+ to properly pop on newlines
            (r"\n", Text, "#pop"),
            # Other whitespace (spaces/tabs only, not newlines)
            (r"[ \t]+", Whitespace),
            # UPPERCASE metavars
            (r"\b[A-Z][A-Z0-9_]*\b", Name.Variable),
            # Anything else on the line
            (r"[^\s\n]+", Text),
        ],
        "optional": [
            (r"\[", Punctuation, "#push"),
            (r"\]", Punctuation, "#pop"),
            include("usage_inline"),
        ],
        "required": [
            (r"\(", Punctuation, "#push"),
            (r"\)", Punctuation, "#pop"),
            include("usage_inline"),
        ],
        "choices": [
            (r"[a-zA-Z0-9][-a-zA-Z0-9_]*", Name.Constant),
            (r",", Punctuation),
            (r"\}", Punctuation, "#pop"),
            (r"\s+", Whitespace),
        ],
        "option_choices": [
            (r"[a-zA-Z0-9][-a-zA-Z0-9_]*", Name.Constant),
            (r",", Punctuation),
            (r"\}", Punctuation, "#pop"),
            (r"\s+", Whitespace),
        ],
    }


class ArgparseLexer(ArgparseHelpLexer):
    """Smart auto-detecting lexer for argparse output.

    Inherits from ArgparseHelpLexer to properly handle Pygments' metaclass
    token processing. Using inheritance (not token dict copying) avoids
    shared mutable state that causes memory corruption.

    This is the recommended lexer for general argparse highlighting.

    Examples
    --------
    >>> from pygments.token import Token
    >>> lexer = ArgparseLexer()

    Usage line detection:

    >>> tokens = list(lexer.get_tokens("usage: cmd [-h]"))
    >>> tokens[0]
    (Token.Generic.Heading, 'usage:')

    Section header detection (Pygments appends newline to input):

    >>> tokens = list(lexer.get_tokens("positional arguments:"))
    >>> any(t[0] == Token.Generic.Subheading for t in tokens)
    True

    Option highlighting in option line context:

    >>> tokens = list(lexer.get_tokens("  -h, --help  show help"))
    >>> any(t[0] == Token.Name.Attribute for t in tokens)
    True
    """

    name = "Argparse"
    aliases = ["argparse"]  # noqa: RUF012
    filenames: list[str] = []  # noqa: RUF012
    mimetypes = ["text/x-argparse"]  # noqa: RUF012

    # Tokens inherited from ArgparseHelpLexer - do NOT redefine or copy


def tokenize_argparse(text: str) -> list[tuple[str, str]]:
    """Tokenize argparse text and return list of (token_type, value) tuples.

    Parameters
    ----------
    text : str
        Argparse help or usage text to tokenize.

    Returns
    -------
    list[tuple[str, str]]
        List of (token_type_name, text_value) tuples.

    Examples
    --------
    >>> result = tokenize_argparse("usage: cmd [-h]")
    >>> result[0]
    ('Token.Generic.Heading', 'usage:')
    >>> result[2]
    ('Token.Name.Label', 'cmd')

    >>> result = tokenize_argparse("positional arguments:")
    >>> any('Token.Generic.Subheading' in t[0] for t in result)
    True
    """
    lexer = ArgparseLexer()
    return [
        (str(tok_type), tok_value) for tok_type, tok_value in lexer.get_tokens(text)
    ]


def tokenize_usage(text: str) -> list[tuple[str, str]]:
    """Tokenize usage text and return list of (token_type, value) tuples.

    Parameters
    ----------
    text : str
        CLI usage text to tokenize.

    Returns
    -------
    list[tuple[str, str]]
        List of (token_type_name, text_value) tuples.

    Examples
    --------
    >>> result = tokenize_usage("usage: cmd [-h]")
    >>> result[0]
    ('Token.Generic.Heading', 'usage:')
    >>> result[2]
    ('Token.Name.Label', 'cmd')
    >>> result[4]
    ('Token.Punctuation', '[')
    >>> result[5]
    ('Token.Name.Attribute', '-h')
    """
    lexer = ArgparseUsageLexer()
    return [
        (str(tok_type), tok_value) for tok_type, tok_value in lexer.get_tokens(text)
    ]