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