1# optparse-applicative 2 3[![Continuous Integration status][status-png]][status] 4[![Hackage page (downloads and API reference)][hackage-png]][hackage] 5[![Hackage-Deps][hackage-deps-png]][hackage-deps] 6 7optparse-applicative is a haskell library for parsing options on 8the command line, and providing a powerful [applicative] interface 9for composing them. 10 11optparse-applicative takes care of reading and validating the 12arguments passed to the command line, handling and reporting errors, 13generating a usage line, a comprehensive help screen, and enabling 14context-sensitive bash, zsh, and fish completions. 15 16**Table of Contents** 17 18- [Introduction](#introduction) 19- [Quick Start](#quick-start) 20- [Basics](#basics) 21 - [Parsers](#parsers) 22 - [Applicative](#applicative) 23 - [Alternative](#alternative) 24 - [Running parsers](#running-parsers) 25- [Builders](#builders) 26 - [Regular options](#regular-options) 27 - [Flags](#flags) 28 - [Arguments](#arguments) 29 - [Commands](#commands) 30 - [Modifiers](#modifiers) 31- [Custom parsing and error handling](#custom-parsing-and-error-handling) 32 - [Parser runners](#parser-runners) 33 - [Option readers](#option-readers) 34 - [Preferences](#preferences) 35 - [Disambiguation](#disambiguation) 36 - [Customising the help screen](#customising-the-help-screen) 37 - [Command Groups](#command-groups) 38- [Bash completion](#bash-zsh-and-fish-completions) 39 - [Actions and completers](#actions-and-completers) 40 - [Internals](#internals) 41- [Arrow interface](#arrow-interface) 42- [Applicative Do](#applicative-do) 43- [FAQ](#faq) 44- [How it works](#how-it-works) 45 46## Introduction 47 48The core type in optparse-applicative is a `Parser` 49 50```haskell 51data Parser a 52 53instance Functor Parser 54instance Applicative Parser 55instance Alternative Parser 56``` 57 58A value of type `Parser a` represents a specification for a set of 59options, which will yield a value of type `a` when the command line 60arguments are successfully parsed. 61 62If you are familiar with parser combinator libraries like [parsec], 63[attoparsec], or the json parser [aeson] you will feel right at 64home with optparse-applicative. 65 66If not, don't worry! All you really need to learn are a few basic 67parsers, and how to compose them as instances of `Applicative` and 68`Alternative`. 69 70## Quick Start 71 72Here's a simple example of a parser. 73 74```haskell 75import Options.Applicative 76import Data.Semigroup ((<>)) 77 78data Sample = Sample 79 { hello :: String 80 , quiet :: Bool 81 , enthusiasm :: Int } 82 83sample :: Parser Sample 84sample = Sample 85 <$> strOption 86 ( long "hello" 87 <> metavar "TARGET" 88 <> help "Target for the greeting" ) 89 <*> switch 90 ( long "quiet" 91 <> short 'q' 92 <> help "Whether to be quiet" ) 93 <*> option auto 94 ( long "enthusiasm" 95 <> help "How enthusiastically to greet" 96 <> showDefault 97 <> value 1 98 <> metavar "INT" ) 99``` 100 101The parser is built using an [applicative] style starting from a 102set of basic combinators. In this example, hello is defined as an 103option with a `String` argument, while quiet is a boolean flag 104(called a switch) and enthusiasm gets parsed as an `Int` with help 105of the `Read` type class. 106 107 108The parser can be used like this: 109 110```haskell 111main :: IO () 112main = greet =<< execParser opts 113 where 114 opts = info (sample <**> helper) 115 ( fullDesc 116 <> progDesc "Print a greeting for TARGET" 117 <> header "hello - a test for optparse-applicative" ) 118 119greet :: Sample -> IO () 120greet (Sample h False n) = putStrLn $ "Hello, " ++ h ++ replicate n '!' 121greet _ = return () 122``` 123 124The `greet` function is the entry point of the program, while `opts` 125is a complete description of the program, used when generating a 126help text. The `helper` combinator takes any parser, and adds a 127`help` option to it. 128 129The `hello` option in this example is mandatory since it doesn't 130have a default value, so running the program without any argument 131will display an appropriate error message and a short option summary: 132 133 Missing: --hello TARGET 134 135 Usage: hello --hello TARGET [-q|--quiet] [--enthusiasm INT] 136 Print a greeting for TARGET 137 138Running the program with the `--help` option will display the full help text 139containing a detailed list of options with descriptions 140 141``` 142 hello - a test for optparse-applicative 143 144 Usage: hello --hello TARGET [-q|--quiet] [--enthusiasm INT] 145 Print a greeting for TARGET 146 147 Available options: 148 --hello TARGET Target for the greeting 149 -q,--quiet Whether to be quiet 150 --enthusiasm INT How enthusiastically to greet (default: 1) 151 -h,--help Show this help text 152``` 153 154## Basics 155### Parsers 156 157optparse-applicative provides a number of primitive parsers, 158corresponding to different posix style options, through its *Builder* 159interface. These are detailed in their [own section](#builders) 160below, for now, here's a look at a few more examples to get a feel 161for how parsers can be defined. 162 163 164Here is a parser for a mandatory option with an argument: 165 166```haskell 167target :: Parser String 168target = strOption 169 ( long "hello" 170 <> metavar "TARGET" 171 <> help "Target for the greeting" ) 172``` 173 174One can see that we are defining an option parser for a `String` 175argument, with *long* option name "hello", *metavariable* "TARGET", 176and the given help text. This means that the `target` parser defined 177above will require an option like 178 179 --hello world 180 181on the command line. The metavariable and the help text will appear 182in the generated help text, but don't otherwise affect the behaviour 183of the parser. 184 185The attributes passed to the option are called *modifiers*, and are 186composed using the [semigroup] operation `(<>)`. 187 188Options with an argument such as `target` are referred to as *regular 189options*, and are very common. Another type of option is a *flag*, 190the simplest of which is a boolean *switch*, for example: 191 192```haskell 193quiet :: Parser Bool 194quiet = switch ( long "quiet" <> short 'q' <> help "Whether to be quiet" ) 195``` 196 197Here we used a `short` modifier to specify a one-letter name for 198the option. This means that this switch can be set either with 199`--quiet` or `-q`. 200 201Flags, unlike regular options, have no arguments. They simply return 202a predetermined value. For the simple switch above, this is `True` 203if the user types the flag, and `False` otherwise. 204 205There are other kinds of basic parsers, and several ways to configure 206them. These are covered in the [Builders](#builders) section. 207 208### Applicative 209 210Now we may combine the `target` and `quiet` into a single parser that 211accepts both options and returns a combined value. Given a type 212 213```haskell 214data Options = Options 215 { optTarget :: String 216 , optQuiet :: Bool } 217``` 218 219and now it's just a matter of using `Applicative`'s apply operator `(<*>)` 220to combine the two previously defined parsers 221 222```haskell 223opts :: Parser Options 224opts = Options <$> target <*> quiet 225``` 226 227No matter which parsers appear first in the sequence, options will 228still be parsed in whatever order they appear in the command line. 229A parser with such a property is sometimes called a *permutation 230parser*. 231 232In our example, a command line like: 233 234 --target world -q 235 236will give the same result as 237 238 -q --target world 239 240It is this property which leads us to an Applicative interface 241instead of a Monadic one, as all options must be considered in 242parallel, and can not depend on the output of other options. 243 244Note, however, that the order of sequencing is still somewhat 245significant, in that it affects the generated help text. Customisation 246can be achieved easily through a lambda abstraction, with [Arrow 247notation](#arrow-interface), or by taking advantage of GHC 8's 248[ApplicativeDo](#applicative-do) extension. 249 250### Alternative 251 252It is also common to find programs that can be configured in different 253ways through the command line. A typical example is a program that 254can be given a text file as input, or alternatively read it directly 255from the standard input. 256 257We can model this easily and effectively in Haskell using *sum types*: 258 259```haskell 260data Input 261 = FileInput FilePath 262 | StdInput 263 264run :: Input -> IO () 265run = ... 266``` 267 268We can now define two basic parsers for the components of the sum type: 269 270```haskell 271fileInput :: Parser Input 272fileInput = FileInput <$> strOption 273 ( long "file" 274 <> short 'f' 275 <> metavar "FILENAME" 276 <> help "Input file" ) 277 278stdInput :: Parser Input 279stdInput = flag' StdInput 280 ( long "stdin" 281 <> help "Read from stdin" ) 282``` 283 284As the `Parser` type constructor is an instance of `Alternative`, we can 285compose these parsers with a choice operator `(<|>)` 286 287```haskell 288input :: Parser Input 289input = fileInput <|> stdInput 290``` 291 292Now `--file "foo.txt"` will be parsed as `FileInput "foo.txt"`, `--stdin` 293will be parsed as `StdInput`, but a command line containing both options, 294like 295 296 --file "foo.txt" --stdin 297 298will be rejected. 299 300Having `Applicative` and `Alternative` instances, optparse-applicative 301parsers are also able to be composed with standard combinators. For 302example: `optional :: Alternative f => f a -> f (Maybe a)` will 303mean the user is not required to provide input for the affected 304`Parser`. 305 306### Running parsers 307 308Before we can run a `Parser`, we need to wrap it into a `ParserInfo` 309structure, that specifies a number of properties that only apply 310to top level parsers, such as a header describing what the program 311does, to be displayed in the help screen. 312 313The function `info` will help with this step. In the [Quick Start](#quick-start) 314we saw 315 316```haskell 317opts :: ParserInfo Sample 318opts = info (sample <**> helper) 319 ( fullDesc 320 <> progDesc "Print a greeting for TARGET" 321 <> header "hello - a test for optparse-applicative" ) 322``` 323 324The `helper` parser that we added after `opts` just creates a dummy 325`--help` option that displays the help text. Besides that, we just 326set some of the fields of the `ParserInfo` structure with meaningful 327values. Now that we have a `ParserInfo`, we can finally run the 328parser. The simplest way to do so is to simply call the `execParser` 329function in your `main`: 330 331```haskell 332main :: IO () 333main = do 334 options <- execParser opts 335 ... 336``` 337 338The `execParser` function takes care of everything, including getting 339the arguments from the command line, displaying errors and help 340screens to the user, and exiting with an appropriate exit code. 341 342There are other ways to run a `ParserInfo`, in situations where you 343need finer control over the behaviour of your parser, or if you 344want to use it in pure code. They will be covered in [Custom parsing 345and error handling](#custom-parsing-and-error-handling). 346 347## Builders 348 349Builders allow you to define parsers using a convenient combinator-based 350syntax. We have already seen examples of builders in action, like 351`strOption` and `switch`, which we used to define the `opts` parser 352for our "hello" example. 353 354Builders always take a [modifier](#modifiers) argument, which is 355essentially a composition of functions acting on the option, setting 356values for properties or adding features. 357 358Builders work by building the option from scratch, and eventually 359lifting it to a single-option parser, ready to be combined with 360other parsers using normal `Applicative` and `Alternative` combinators. 361 362See the [haddock documentation][hackage] for `Options.Applicative.Builder` 363for a full list of builders and modifiers. 364 365There are four different kinds of options in `optparse-applicative`: 366regular options, flags, arguments, and commands. In the following, 367we will go over each one of these and describe the builders that 368can be used to create them. 369 370### Regular options 371 372A *regular option* is an option which takes a single argument, 373parses it, and returns a value. 374 375A regular option can have a default value, which is used as the 376result if the option is not found in the command line. An option 377without a default value is considered mandatory, and produces an 378error when not found. 379 380Regular options can have *long* names, or *short* (one-character) 381names, which determine when the option matches and how the argument 382is extracted. 383 384An option with a long name (say "output") is specified on the command 385line as 386 387 388 --output filename.txt 389 390or 391 392 --output=filename.txt 393 394while a short name option (say "o") can be specified with 395 396 -o filename.txt 397 398or 399 400 -ofilename.txt 401 402Options can have more than one name, usually one long and one short, 403although you are free to create options with an arbitrary combination 404of long and short names. 405 406Regular options returning strings are the most common, and they can 407be created using the `strOption` builder. For example, 408 409```haskell 410strOption 411 ( long "output" 412 <> short 'o' 413 <> metavar "FILE" 414 <> value "out.txt" 415 <> help "Write output to FILE" ) 416``` 417 418creates a regular option with a string argument (which can be 419referred to as `FILE` in the help text and documentation), default 420value "out.txt", a long name "output" and a short name "o". 421 422A regular `option` can return an object of any type, and takes a 423*reader* parameter which specifies how the argument should be parsed. 424A common reader is `auto`, which requires a `Read` instance for the 425return type and uses it to parse its argument. For example: 426 427```haskell 428lineCount :: Parser Int 429lineCount = option auto 430 ( long "lines" 431 <> short 'n' 432 <> metavar "K" 433 <> help "Output the last K lines" ) 434``` 435 436specifies a regular option with an `Int` argument. We added an 437explicit type annotation here, since without it the parser would 438have been polymorphic in the output type. There's usually no need 439to add type annotations, however, because the type will be normally 440inferred from the context in which the parser is used. 441 442Further information on *readers* is available [below](#option-readers). 443 444### Flags 445 446A *flag* is just like a regular option, but it doesn't take any 447arguments, it is either present in the command line or not. 448 449A flag has a default value and an *active value*. If the flag is 450found on the command line, the active value is returned, otherwise 451the default value is used. For example: 452 453```haskell 454data Verbosity = Normal | Verbose 455 456flag Normal Verbose 457 ( long "verbose" 458 <> short 'v' 459 <> help "Enable verbose mode" ) 460``` 461 462is a flag parser returning a `Verbosity` value. 463 464Simple boolean flags can be specified using the `switch` builder, like so: 465 466```haskell 467switch 468 ( long "keep-tmp-files" 469 <> help "Retain all intermediate temporary files" ) 470``` 471 472There is also a `flag'` builder, which has no default value. This 473was demonstrated earlier for our `--stdin` flag example, and is 474usually used as one side of an alternative. 475 476Another interesting use for the `flag'` builder is to count the 477number of instances on the command line, for example, verbosity 478settings could be specified on a scale; the following parser will 479count the number of instances of `-v` on the command line. 480 481```haskell 482length <$> many (flag' () (short 'v')) 483``` 484 485Flags can be used together after a single hyphen, so `-vvv` and 486`-v -v -v` will both yield 3 for the above parser. 487 488### Arguments 489 490An *argument* parser specifies a positional command line argument. 491 492The `argument` builder takes a reader parameter, and creates a 493parser which will return the parsed value every time it is passed 494a command line argument for which the reader succeeds. For example 495 496```haskell 497argument str (metavar "FILE") 498``` 499 500creates an argument accepting any string. To accept an arbitrary 501number of arguments, combine the `argument` builder with either the 502`many` or `some` combinator: 503 504```haskell 505some (argument str (metavar "FILES...")) 506``` 507 508Note that arguments starting with `-` are considered options by 509default, and will not be considered by an `argument` parser. 510 511However, parsers always accept a special argument: `--`. When a 512`--` is found on the command line, all the following words are 513considered by `argument` parsers, regardless of whether they start 514with `-` or not. 515 516Arguments use the same *readers* as regular options. 517 518### Commands 519 520A *command* can be used to specify a sub-parser to be used when a 521certain string is encountered in the command line. 522 523Commands are useful to implement command line programs with multiple 524functions, each with its own set of options, and possibly some 525global options that apply to all of them. Typical examples are 526version control systems like `git`, or build tools like `cabal`. 527 528A command can be created using the `subparser` builder (or `hsubparser`, 529which is identical but for an additional `--help` option on each 530command), and commands can be added with the `command` modifier. 531For example 532 533```haskell 534subparser 535 ( command "add" (info addOptions ( progDesc "Add a file to the repository" )) 536 <> command "commit" (info commitOptions ( progDesc "Record changes to the repository" )) 537 ) 538``` 539 540Each command takes a full `ParserInfo` structure, which will be 541used to extract a description for this command when generating a 542help text. 543 544Note that all the parsers appearing in a command need to have the 545same type. For this reason, it is often best to use a sum type 546which has the same structure as the command itself. For example, 547for the parser above, you would define a type like: 548 549```haskell 550data Options = Options 551 { optCommand :: Command 552 , ... } 553 554data Command 555 = Add AddOptions 556 | Commit CommitOptions 557 ... 558``` 559 560Alternatively, you can directly return an `IO` action from a parser, 561and execute it using `join` from `Control.Monad`. 562 563```haskell 564start :: String -> IO () 565stop :: IO () 566 567opts :: Parser (IO ()) 568opts = subparser 569 ( command "start" (info (start <$> argument str idm) idm) 570 <> command "stop" (info (pure stop) idm) ) 571 572main :: IO () 573main = join $ execParser (info opts idm) 574``` 575 576### Modifiers 577 578*Modifiers* are instances of the `Semigroup` and `Monoid` typeclasses, 579so they can be combined using the composition function `mappend` 580(or simply `(<>)`). Since different builders accept different sets 581of modifiers, modifiers have a type parameter that specifies which 582builders support it. 583 584For example, 585 586```haskell 587command :: String -> ParserInfo a -> Mod CommandFields a 588``` 589 590can only be used with [commands](#commands), as the `CommandFields` 591type argument of `Mod` will prevent it from being passed to builders 592for other types of options. 593 594Many modifiers are polymorphic in this type argument, which means 595that they can be used with any builder. 596 597## Custom parsing and error handling 598 599### Parser runners 600Parsers are run with the `execParser` family of functions — from 601easiest to use to most flexible these are: 602 603```haskell 604execParser :: ParserInfo a -> IO a 605customExecParser :: ParserPrefs -> ParserInfo a -> IO a 606execParserPure :: ParserPrefs -> ParserInfo a -> [String] -> ParserResult a 607``` 608 609When using the `IO` functions, retrieving command line arguments 610and handling exit codes and failure will be done automatically. 611When using `execParserPure`, the functions 612 613```haskell 614handleParseResult :: ParserResult a -> IO a 615overFailure :: (ParserHelp -> ParserHelp) -> ParserResult a -> ParserResult a 616``` 617 618can be used to correctly set exit codes and display the help message; 619and modify the help message in the event of a failure (adding 620additional information for example). 621 622### Option readers 623 624Options and Arguments require a way to interpret the string passed 625on the command line to the type desired. The `str` and `auto` 626*readers* are the most common way, but one can also create a custom 627reader that doesn't use the `Read` type class or return a `String`, 628and use it to parse the option. A custom reader is a value in the 629`ReadM` monad. 630 631We provide the `eitherReader :: (String -> Either String a) -> ReadM a` 632convenience function to help create these values, where a `Left` will 633hold the error message for a parse failure. 634 635```haskell 636data FluxCapacitor = ... 637 638parseFluxCapacitor :: ReadM FluxCapacitor 639parseFluxCapacitor = eitherReader $ \s -> ... 640 641option parseFluxCapacitor ( long "flux-capacitor" ) 642``` 643 644One can also use `ReadM` directly, using `readerAsk` to obtain the 645command line string, and `readerAbort` or `readerError` within the 646`ReadM` monad to exit with an error message. 647 648One nice property of `eitherReader` is how well it composes with 649[attoparsec] parsers with 650 651```haskell 652import qualified Data.Attoparsec.Text as A 653attoReadM :: A.Parser a -> ReadM a 654attoReadM p = eitherReader (A.parseOnly p . T.pack) 655``` 656 657### Preferences 658`PrefsMod`s can be used to customise the look of the usage text and 659control when it is displayed; turn off backtracking of subparsers; 660and turn on [disambiguation](#disambiguation). 661 662To use these modifications, provide them to the `prefs` builder, 663and pass the resulting preferences to one of the parser runners 664that take an `ParserPrefs` parameter, like `customExecParser`. 665 666 667### Disambiguation 668 669It is possible to configure optparse-applicative to perform automatic 670disambiguation of prefixes of long options. For example, given a 671program `foo` with options `--filename` and `--filler`, typing 672 673 $ foo --fil test.txt 674 675fails, whereas typing 676 677 $ foo --file test.txt 678 679succeeds, and correctly identifies `"file"` as an unambiguous prefix 680of the `filename` option. 681 682Option disambiguation is *off* by default. To enable it, use the 683`disambiguate` `PrefsMod` modifier as described above. 684 685Here is a minimal example: 686 687```haskell 688import Options.Applicative 689 690sample :: Parser () 691sample = () <$ 692 switch (long "filename") <* 693 switch (long "filler") 694 695main :: IO () 696main = customExecParser p opts 697 where 698 opts = info (helper <*> sample) idm 699 p = prefs disambiguate 700 701``` 702 703### Customising the help screen 704 705optparse-applicative has a number of combinators to help customise 706the usage text, and determine when it should be displayed. 707 708The `progDesc`, `header`, and `footer` functions can be used to 709specify a brief description or tagline for the program, and detailed 710information surrounding the generated option and command descriptions. 711 712Internally we actually use the [ansi-wl-pprint][ansi-wl-pprint] 713library, and one can use the `headerDoc` combinator and friends if 714additional customisation is required. 715 716To display the usage text, the user may type `--help` if the `helper` 717combinator has been applied to the `Parser`. 718 719Authors can also use the preferences `showHelpOnError` or 720`showHelpOnEmpty` to show the help text on any parser failure or 721when a command is not complete and at the beginning of the parse 722of the main program or one of its subcommands respectively. 723 724Even if the help text is not shown for an error, a specific error 725message will be, indicating what's missing, or what was unable to 726be parsed. 727 728```haskell 729myParser :: Parser () 730myParser = ... 731 732main :: IO () 733main = customExecParser p opts 734 where 735 opts = info (myParser <**> helper) idm 736 p = prefs showHelpOnEmpty 737``` 738 739### Command groups 740 741One experimental feature which may be useful for programs with many 742subcommands is command group separation. 743 744```haskell 745data Sample 746 = Hello [String] 747 | Goodbye 748 deriving (Eq, Show) 749 750hello :: Parser Sample 751hello = Hello <$> many (argument str (metavar "TARGET...")) 752 753sample :: Parser Sample 754sample = subparser 755 ( command "hello" (info hello (progDesc "Print greeting")) 756 <> command "goodbye" (info (pure Goodbye) (progDesc "Say goodbye")) 757 ) 758 <|> subparser 759 ( command "bonjour" (info hello (progDesc "Print greeting")) 760 <> command "au-revoir" (info (pure Goodbye) (progDesc "Say goodbye")) 761 <> commandGroup "French commands:" 762 <> hidden 763 ) 764``` 765 766This will logically separate the usage text for the two subparsers 767(these would normally appear together if the `commandGroup` modifier 768was not used). The `hidden` modifier suppresses the metavariable 769for the second subparser being show in the brief usage line, which 770is desirable in some cases. 771 772In this example we have essentially created synonyms for our parser, 773but one could use this to separate common commands from rare ones, 774or safe from dangerous. 775 776The usage text for the preceding example is: 777``` 778Usage: commands COMMAND 779 780Available options: 781 -h,--help Show this help text 782 783Available commands: 784 hello Print greeting 785 goodbye Say goodbye 786 787French commands: 788 bonjour Print greeting 789 au-revoir Say goodbye 790``` 791 792## Bash, Zsh, and Fish Completions 793 794`optparse-applicative` has built-in support for the completion of 795command line options and arguments in bash, zsh, and fish shells. 796Any parser, when run using the `execParser` family of functions, 797is automatically extended with a few (hidden) options for the 798completion system: 799 800 - `--bash-completion-script`: this takes the full path of the program as 801 argument, and prints a bash script, which, when sourced into a bash session, 802 will install the necessary machinery to make bash completion work. For a 803 quick test, you can run something like (for a program called `foo` on the 804 `PATH`): 805 806 ```console 807 $ source <(foo --bash-completion-script `which foo`) 808 ``` 809 810 Normally, the output of `--bash-completion-script` should be shipped with 811 the program and copied to the appropriate directory (usually 812 `/etc/bash_completion.d/`) during installation; 813 814 - `--zsh-completion-script`: which is analogous for zsh; 815 816 - `--fish-completion-script`: which is analogous for fish shell; 817 818 - `--bash-completion-index`, `--bash-completion-word`: internal options used 819 by the completion script to obtain a list of possible completions for a 820 given command line; 821 822 - `--bash-completion-enriched`: a flag to tell the completion system to emit 823 descriptions along with possible completions. This is used to provide help 824 along with the completion for `zsh` and `fish`. 825 826### Actions and completers 827 828By default, options and commands are always completed. So, for example, if the 829program `foo` has an option with a long name `output`, typing 830 831```console 832$ foo --ou<TAB> 833``` 834 835will complete `--output` automatically. 836 837Arguments (either of regular options, or top-level) are not completed by 838default. To enable completion for arguments, use one of the following modifiers 839on a regular option or argument: 840 841 - `completeWith`: specifies a list of possible completions to choose from; 842 - `action`: specifies a completion "action". An action dynamically determines 843 a list of possible completions. Common actions are "file" and "directory"; 844 the full list of actions can be found in the [bash documentation]; 845 - `completer`: a completer is a function `String -> IO [String]`, returning 846 all possible completions for a given string. You can use this modifier to 847 specify a custom completion for an argument. 848 849Completion modifiers can be used multiple times: the resulting completions will 850call all of them and join the results. 851 852### Internals 853 854When running a parser with `execParser`, the parser is extended with 855`bashCompletionParser`, which defines the above options. 856 857When completion is triggered, the completion script calls the executable with 858the special `--bash-completion-index` and `--bash-completion-word` options. 859 860The original parser is therefore run in *completion mode*, i.e. `runParser` is 861called on a different monad, which keeps track of the current state of the 862parser, and exits when all arguments have been processed. 863 864The completion monad returns, on failure, either the last state of the parser 865(if no option could be matched), or the completer associated to an option (if 866it failed while fetching the argument for that option). 867 868From that we generate a list of possible completions, and print them to 869standard output. They are then read by the completion script and put into the 870`COMPREPLY` variable (or an appropriate alternative for the other shells). 871 872## Arrow interface 873 874It is also possible to use the [Arrow syntax][arrows] to combine basic parsers. 875 876This can be particularly useful when the structure holding parse results is 877deeply nested, or when the order of fields differs from the order in which the 878parsers should be applied. 879 880Using functions from the `Options.Applicative.Arrows` module, one can write, 881for example: 882 883```haskell 884data Options = Options 885 { optArgs :: [String] 886 , optVerbose :: Bool } 887 888opts :: Parser Options 889opts = runA $ proc () -> do 890 verbosity <- asA (option auto (short 'v' <> value 0)) -< () 891 let verbose = verbosity > 0 892 args <- asA (many (argument str idm)) -< () 893 returnA -< Options args verbose 894``` 895 896where parsers are converted to arrows using `asA`, and the resulting 897composed arrow is converted back to a `Parser` with `runA`. 898 899See `tests/Examples/Cabal.hs` for a slightly more elaborate example 900using the arrow syntax for defining parsers. 901 902Note that the `Arrow` interface is provided only for convenience. The 903API based on `Applicative` is just as expressive, although it might be 904cumbersome to use in certain cases. 905 906## Applicative do 907 908Some may find using optparse-applicative easier using do notation. 909However, as `Parser` is not an instance of `Monad`, this can only 910be done in recent versions of GHC using the *ApplicativeDo* extension. 911For example, a parser specified in this manner might be 912 913```haskell 914{-# LANGUAGE RecordWildCards #-} 915{-# LANGUAGE ApplicativeDo #-} 916 917data Options = Options 918 { optArgs :: [String] 919 , optVerbose :: Bool } 920 921opts :: Parser Options 922opts = do 923 optVerbose <- switch (short 'v') 924 optArgs <- many (argument str idm) 925 pure Options {..} 926``` 927 928Here we've also used the *RecordWildCards* extension to make the 929parser specification cleaner. Compilation errors referring to `Monad` 930instances not being found are likely because the `Parser` specified 931can not be implemented entirely with `Applicative` (Note however, 932there were a few desugaring bugs regarding ApplicativeDo in GHC 9338.0.1, function application with `($)` in particular may not work, 934and the `pure` value should instead be wrapped parenthetically). 935 936## FAQ 937 938* Monadic parsing? 939 940 If a Monadic style were to be used, there would be no possible 941 way to traverse the parser and generate a usage string, or for 942 us to allow for options to be parsed in any order. Therefore it 943 is intentionally unsupported to write a `Parser` in this manner 944 with optparse-applicative, and the `Parser` type does not have 945 an instance for `Monad`. 946 947* Overlapping flags and options / options with optional arguments? 948 949 This is not supported as it can lead to an ambiguous parse. 950 951 For example, if we supported and had an optional value option 952 "--foo" and a flag "--bar", is "--foo --bar" the option with value 953 "--bar", or the default value with the flag switched on? What if 954 instead of a switch we had many positional string arguments, is 955 the first string the option's value or the first positional? 956 957 It is suggested to instead use the `Alternative` instance of 958 `Parser` and create a flag', an option, and a pure value for the 959 default (with different names for the flag and option). 960 961* Backtracking on `ReadM` errors? 962 963 Parser structures are predetermined at parse time. This means 964 that if a `ReadM` fails, the whole parse must also fail, we can't 965 consider any alternatives, as there can be no guarantee that the 966 remaining structure will fit. One occasionally confusing side 967 effect of this is that two positional arguments for different 968 constructors of a sum type can't be composed at the parser level; 969 rather, this must be done at the `ReadM` level. For example: 970 971 ```haskell 972 import Options.Applicative 973 974 data S3orFile = S3 BucketKey | File FilePath 975 976 s3Read, fileRead :: ReadM S3orFile 977 s3Read = S3 <$> ... 978 fileRead = File <$> ... 979 980 correct :: Parser S3orFile 981 correct = argument (s3Read <|> fileRead) idm 982 983 incorrect :: Parser S3orFile 984 incorrect = argument s3Read idm <|> argument fileRead idm 985 ``` 986 987## How it works 988An applicative `Parser` is essentially a heterogeneous list or tree 989of `Option`s, implemented with existential types. 990 991All options are therefore known statically (i.e. before parsing, 992not necessarily before runtime), and can, for example, be traversed 993to generate a help text. Indeed, when displaying the usage text for 994a parser, we use an intermediate tree structure. 995 996When we examine the user's input, each argument is examined to 997determine if it's an option or flag, or a positional argument. The 998parse tree is then searched for a matching term, and if it finds 999one, that leaf of the tree is replaced with the value itself. When 1000all input has been processed, we see if we can generate the complete 1001value, and if not issue an error. 1002 1003See [this blog post][blog] for a more detailed explanation based on a 1004simplified implementation. 1005 1006 [aeson]: http://hackage.haskell.org/package/aeson 1007 [applicative]: http://hackage.haskell.org/package/base/docs/Control-Applicative.html 1008 [arrows]: http://www.haskell.org/arrows/syntax.html 1009 [attoparsec]: http://hackage.haskell.org/package/attoparsec 1010 [bash documentation]: http://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html 1011 [blog]: http://paolocapriotti.com/blog/2012/04/27/applicative-option-parser/ 1012 [hackage]: http://hackage.haskell.org/package/optparse-applicative 1013 [hackage-png]: http://img.shields.io/hackage/v/optparse-applicative.svg 1014 [hackage-deps]: http://packdeps.haskellers.com/reverse/optparse-applicative 1015 [hackage-deps-png]: https://img.shields.io/hackage-deps/v/optparse-applicative.svg 1016 [monoid]: http://hackage.haskell.org/package/base/docs/Data-Monoid.html 1017 [semigroup]: http://hackage.haskell.org/package/base/docs/Data-Semigroup.html 1018 [parsec]: http://hackage.haskell.org/package/parsec 1019 [status]: http://travis-ci.org/pcapriotti/optparse-applicative?branch=master 1020 [status-png]: https://api.travis-ci.org/pcapriotti/optparse-applicative.svg?branch=master 1021 [ansi-wl-pprint]: http://hackage.haskell.org/package/ansi-wl-pprint 1022