W3cubDocs

/Nim

Module parseopt

This module provides the standard Nim command line parser. It supports one convenience iterator over all command line options and some lower-level features.

Supported syntax:

  1. short options - -abcd, where a, b, c, d are names
  2. long option - --foo:bar, --foo=bar or --foo
  3. argument - everything else

Imports

os, strutils

Types

CmdLineKind = enum
  cmdEnd,                     ## end of command line reached
  cmdArgument,                ## argument detected
  cmdLongOption,              ## a long option ``--option`` detected
  cmdShortOption              ## a short option ``-c`` detected
the detected command line token
OptParser = object of RootObj
  cmd: string
  pos: int
  inShortState: bool
  kind*: CmdLineKind           ## the dected command line token
  key*, val*: TaintedString     ## key and value pair; ``key`` is the option
                         ## or the argument, ``value`` is not "" if
                         ## the option was given a value
this object implements the command line parser

Procs

proc initOptParser(cmdline = ""): OptParser {.raises: [], tags: [ReadIOEffect].}
inits the option parser. If cmdline == "", the real command line (as provided by the OS module) is taken.
proc next(p: var OptParser) {.gcsafe, extern: "npo$1", raises: [], tags: [].}
parses the first or next option; p.kind describes what token has been parsed. p.key and p.val are set accordingly.
proc cmdLineRest(p: OptParser): TaintedString {.gcsafe, extern: "npo$1", raises: [],
    tags: [].}
retrieves the rest of the command line that has not been parsed yet.

Iterators

iterator getopt(p: var OptParser): tuple[kind: CmdLineKind, key, val: TaintedString] {.
    raises: [], tags: [].}
This is an convenience iterator for iterating over the given OptParser object. Example:
var p = initOptParser("--left --debug:3 -l=4 -r:2")
for kind, key, val in p.getopt():
  case kind
  of cmdArgument:
    filename = key
  of cmdLongOption, cmdShortOption:
    case key
    of "help", "h": writeHelp()
    of "version", "v": writeVersion()
  of cmdEnd: assert(false) # cannot happen
if filename == "":
  # no filename has been given, so we show the help:
  writeHelp()
iterator getopt(): tuple[kind: CmdLineKind, key, val: TaintedString] {.raises: [],
    tags: [ReadIOEffect].}
This is an convenience iterator for iterating over the command line arguments. This create a new OptParser object. See above for a more detailed example
for kind, key, val in getopt():
  # this will iterate over all arguments passed to the cmdline.
  continue

© 2006–2017 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/parseopt.html