Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Parsing Behaviour

Negative Number Passthrough

By default, tokens starting with - are interpreted as options. This creates a problem when you need to pass negative numbers (like -10.18, -3.14, -1.5e10) as positional values.

ArgMojo provides three complementary approaches to handle this, inspired by Python’s argparse.


Approach 1: Auto-detect (zero configuration)

When no registered short option uses a digit character as its name, ArgMojo automatically recognises numeric-looking tokens and treats them as positional arguments instead of options.

var command = Command("calc", "Calculator")
command.add_argument(Argument("operand", help="A number").positional().required())
calc -9876543        # operand = "-9876543" (auto-detected as a number)
calc -3.14           # operand = "-3.14"
calc -.5             # operand = "-.5"
calc -1.5e10         # operand = "-1.5e10"
calc -2.0e-3         # operand = "-2.0e-3"

This works because -9, -3, etc. do not match any registered short option. The parser sees a numeric pattern and skips the option-dispatch path.

Recognised patterns: -N, -N.N, -.N, -NeX, -N.NeX, -Ne+X, -Ne-X (where N and X are digit sequences).


Approach 2: The -- separator (always works)

The -- stop marker forces everything after it to be treated as positional. This is the most universal approach and works regardless of any configuration.

calc -- -10.18         # operand = "-10.18"
calc -- -3e4         # operand = "-3e4"

See The -- Stop Marker for details. When positional arguments are registered, ArgMojo’s help output includes a Tip line reminding users about this:

tip: Use '--' to pass values that start with '-' (e.g., negative numbers):  calc -- -10.18

Approach 3: allow_negative_numbers() (explicit opt-in)

If you have a registered short option that uses a digit character (e.g., -3 for --triple), the auto-detect is suppressed to avoid ambiguity. In this case, call allow_negative_numbers() to force all numeric-looking tokens to be treated as positionals.

var command = Command("calc", "Calculator")
command.allow_negative_numbers()   # Explicit opt-in
command.add_argument(
    Argument("triple", help="Triple mode").long["triple"]().short["3"]().flag()
)
command.add_argument(Argument("operand", help="A number").positional().required())
calc --triple -3.14   # triple = True, operand = "-3.14"
calc -3               # operand = "-3" (NOT the -3 flag!)

Warning: When allow_negative_numbers() is active, even a bare -3 that exactly matches a registered short option will be consumed as a positional number. Use the long form (--triple) to set the flag.


Approach 4: allow_negative_expressions() (expressions and arbitrary tokens)

When your CLI accepts mathematical expressions that start with - (e.g. -1/3*pi, -sin(2), -e^2), allow_negative_numbers() is not enough because those tokens are not pure numeric literals. Call allow_negative_expressions() to treat any single-hyphen token as a positional argument, provided it doesn’t conflict with a registered short option.

var command = Command("calc", "Expression calculator")
command.allow_negative_expressions()
command.add_argument(Argument("precision", help="Decimal places").long["precision"]().short["p"]())
command.add_argument(Argument("expr", help="Expression").positional().required())
calc "-1/3*pi" -p 10    # expr = "-1/3*pi", precision = "10"
calc "-sin(2)"           # expr = "-sin(2)"
calc -e                  # expr = "-e"   (because -e is not a registered short option)
calc -p 10 hello         # precision = "10", expr = "hello"  (-p IS registered, so it's parsed as the -p short option taking 10 as its value)

Rules:

  • A single-hyphen token is treated as a positional only when its first character after - does not match a registered short option.
    • Examples: -1/3*pi, -sin(2), and -e are positional if -1, -s, and -e are not registered short options.
    • If the first character is a registered short option, the token is parsed normally (merged shorts like -vp and attached values like -p10 continue to work).
  • Long options (--foo) are never affected — they always parse normally.

Note: allow_negative_expressions() is a superset of allow_negative_numbers(). You don’t need to call both.


When to use which approach

ScenarioRecommended approach
No digit short options registeredAuto-detect (nothing to configure)
You have digit short options (-3, -5, etc.) and need negative numbersallow_negative_numbers()
You need to pass arbitrary dash-prefixed expressions (e.g. -1/3*pi)allow_negative_expressions()
One specific argument needs to accept - (stdin) or dash-prefixed valuesallow_hyphen_values() on that argument
You need to pass arbitrary dash-prefixed strings (not just numbers)-- separator
Legacy or defensive: works in all cases-- separator

allow_negative_expressions() vs allow_hyphen_values() — how do they relate?

These two features partially overlap, especially when the command has a single positional argument. Here is a quick comparison:

Aspectallow_negative_expressions()allow_hyphen_values()
ScopePer-command (one call covers all positionals)Per-argument (must be set on each argument individually)
Bare - (stdin)Accepted (bare - never enters short-option parsing)Accepted
Expressions (e.g. -1/3*pi)AcceptedAccepted
Works on optionsNo (positionals only)Yes (also value-taking options like --file)
Parsing behaviorEnables dash-prefixed expression handling for positionalsBroadens one argument to accept hyphen-prefixed values

With a single positional, the two are nearly interchangeable for inputs like -1/pi*sin(3) — and a bare - is already treated as a positional token in both cases (it never enters short-option parsing). allow_hyphen_values() is still the better fit when one specific argument should accept arbitrary hyphen-prefixed values, especially for value-taking options.

Choose allow_negative_expressions() when:

  • Your command has multiple positionals and you want a single switch for all of them.
  • You want to signal intent: “this CLI handles math expressions.”

Choose allow_hyphen_values() when:

  • Only one specific argument should accept dash-prefixed values while others should not.
  • You need the bare - (stdin/stdout convention).
  • The argument is an option (--file), not a positional.

What is NOT a number

Tokens like -1abc, -e5, or -1-2 are not valid numeric patterns. Without allow_negative_expressions(), they will still be parsed as short-option strings and may raise “Unknown option” errors if unregistered. With allow_negative_expressions(), they are consumed as positional arguments.

Long Option Prefix Matching

ArgMojo supports prefix matching (also known as abbreviation) for long options. If a user types a prefix of a long option name that unambiguously matches exactly one registered option, it is automatically resolved.

This mirrors Python argparse’s allow_abbrev behaviour.


command.add_argument(Argument("verbose", help="Verbose output").long["verbose"]().short["v"]().flag())
command.add_argument(Argument("output",  help="Output file").long["output"]().short["o"]())
myapp --verb               # resolves to --verbose
myapp --out file.txt       # resolves to --output file.txt
myapp --out=file.txt       # resolves to --output=file.txt

Ambiguous prefixes

If the prefix matches more than one option, an error is raised:

command.add_argument(Argument("verbose",      help="Verbose").long["verbose"]().flag())
command.add_argument(Argument("version-info", help="Version info").long["version-info"]().flag())
myapp --ver
# Error: Ambiguous option '--ver' could match: '--verbose', '--version-info'

Exact match always wins

If the user’s input is an exact match for one option, it is chosen even if it is also a prefix of another option:

command.add_argument(Argument("color",    help="Color mode").long["color"]().flag())
command.add_argument(Argument("colorize", help="Colorize output").long["colorize"]().flag())
myapp --color       # exact match → color (not ambiguous with colorize)
myapp --col         # ambiguous → error

Works with negatable flags

Prefix matching also applies to --no-X negation:

myapp --no-col      # resolves to --no-color (if color is the only negatable match)

This feature is always enabled — no configuration needed. It is most useful for long option names where typing the full name is cumbersome:

myapp --max 5       # instead of --max-depth 5
myapp --ig          # instead of --ignore-case

Tip: Exact long option names are always accepted. Prefix matching is a convenience that does not change the behaviour of exact matches.

The -- Stop Marker

A bare -- tells the parser to stop interpreting options. Everything after -- is treated as a positional argument, even if it looks like an option.

command.add_argument(Argument("ling", help="Use Lingming encoding").long["ling"]().flag())
command.add_argument(Argument("pattern", help="Search pattern").positional().required())
myapp -- --ling
# ling = False  (the -- stopped option parsing)
# pattern = "--ling"  (treated as a positional value)

This is especially useful for patterns or file paths that look like options:

myapp --ling -- "-v is not a flag here" ./src
# ling = True  (parsed before --)
# pattern = "-v is not a flag here"
# path = "./src"

A common use-case is passing negative numbers as positional arguments:

myapp -- -10.18
# pattern = "-10.18"

Tip: ArgMojo’s Auto-detect can handle most negative-number cases without --. Use -- only when auto-detect is insufficient (e.g., a digit short option is registered without allow_negative_numbers()).

Remainder Positional (.remainder())

A remainder positional consumes all remaining command-line tokens once it starts matching, including tokens that look like options (e.g., --foo, -x, --some-flag). This is useful for wrapper CLIs that forward arguments to another program.

Libraries with similar support: argparse (nargs=argparse.REMAINDER), clap (trailing_var_arg), cobra (TraverseChildren + ArbitraryArgs).

var command = Command("runner", "Run a program with arguments")
command.add_argument(
    Argument("program", help="Program to run").positional().required()
)
command.add_argument(
    Argument("args", help="Arguments to pass through").remainder()
)
runner myapp --verbose -x --output=foo.txt
# program = "myapp"
# args    = ["--verbose", "-x", "--output=foo.txt"]

The remainder positional automatically implies .positional() and .append(). In help output, it is displayed as args... (with trailing ellipsis).

Rules:

  • .remainder() must not have .long() or .short() — it is positional-only.
  • At most one remainder positional is allowed per command.
  • The remainder positional must be the last positional argument.
  • When no trailing tokens are present, the remainder list is empty (not an error).

Allow Hyphen Values (.allow_hyphen_values())

By default, tokens starting with - are interpreted as options. The .allow_hyphen_values() builder method tells the parser that a specific positional argument may accept tokens starting with - as regular values without requiring -- beforehand. This covers both the bare - (Unix stdin/stdout convention) and any other dash-prefixed literal.

A common use case is accepting - as a conventional shorthand for stdin/stdout:

var command = Command("cat", "Concatenate files")
command.add_argument(
    Argument("file", help="Input file (use - for stdin)")
    .positional()
    .required()
    .allow_hyphen_values()
)
cat -        # file = "-"  (stdin convention)
cat input.txt  # file = "input.txt"

Note: .remainder() automatically enables .allow_hyphen_values() — no need to set it separately on remainder positionals.

Values that look like options

An option never takes a registered option as its value. If you write --output --verbose and --verbose is a real flag of your program, the parser reports a missing value rather than storing the string "--verbose" in output:

myapp --output --verbose
# error: Option '--output' requires a value, but found the option '--verbose'

Only registered options and the -- end-of-options marker are refused. A value that merely begins with a hyphen is still accepted, so negative numbers and unknown dash-prefixed literals keep working:

myapp --offset -5        # offset = "-5"
myapp --pattern -foo     # pattern = "-foo"

.allow_hyphen_values() turns the check off for that argument, which is what you want for an option that forwards a flag to another tool:

command.add_argument(
    Argument("pass-through", help="Flag forwarded to the compiler")
    .long["cflag"]()
    .allow_hyphen_values()
)
myapp --cflag --verbose  # pass-through = "--verbose"

Partial Parsing (parse_known_arguments())

parse_known_arguments() works like parse_arguments() but does not raise an error for unrecognised options. Instead, unknown tokens are collected and can be retrieved from the result.

Libraries with similar support: argparse (parse_known_args()), clap (not built-in; use allow_external_subcommands), cobra (FParseErrWhitelist).

var command = Command("wrapper", "Wrapper that forwards unknown flags")
command.add_argument(
    Argument("verbose", help="Verbose output").long["verbose"]().flag()
)
command.add_argument(
    Argument("file", help="Input file").positional().required()
)

var args: List[String] = ["wrapper", "input.txt", "--verbose", "--color", "-x"]
var result = command.parse_known_arguments(args)

# Known arguments are accessed normally:
var verbose = result.get_flag("verbose")
var file = result.get_string("file")

# Unknown arguments are collected separately:
var unknown = result.get_unknown_arguments()
# e.g., ["--color", "-x", "--threads=4"]
wrapper input.txt --verbose --color -x --threads=4
# verbose = True
# file    = "input.txt"
# unknown = ["--color", "-x", "--threads=4"]

All other validation (required arguments, choices, range) still applies. Only the “Unknown option” error is suppressed.

Note: Unknown options using = syntax (e.g., --color=auto) are captured as a single token. For space-separated syntax (--color auto), only --color is recorded as unknown; auto flows to positional arguments because the parser cannot tell whether the unknown option takes a value. Use = syntax when forwarding unknown options reliably.