# File lib/rdoc/options.rb, line 459
  def parse argv
    ignore_invalid = true

    argv.insert(0, *ENV['RDOCOPT'].split) if ENV['RDOCOPT']

    opts = OptionParser.new do |opt|
      @option_parser = opt
      opt.program_name = File.basename $0
      opt.version = RDoc::VERSION
      opt.release = nil
      opt.summary_indent = ' ' * 4
      opt.banner = "Usage: \#{opt.program_name} [options] [names...]\n\nFiles are parsed, and the information they contain collected, before any\noutput is produced. This allows cross references between all files to be\nresolved. If a name is a directory, it is traversed. If no names are\nspecified, all Ruby files in the current directory (and subdirectories) are\nprocessed.\n\nHow RDoc generates output depends on the output formatter being used, and on\nthe options you give.\n\nOptions can be specified via the RDOCOPT environment variable, which\nfunctions similar to the RUBYOPT environment variable for ruby.\n\n$ export RDOCOPT=\"--show-hash\"\n\nwill make rdoc show hashes in method links by default.  Command-line options\nalways will override those in RDOCOPT.\n\nAvailable formatters:\n\n\#{generator_descriptions}\n\nRDoc understands the following file formats:\n\n"

      parsers = Hash.new { |h,parser| h[parser] = [] }

      RDoc::Parser.parsers.each do |regexp, parser|
        parsers[parser.name.sub('RDoc::Parser::', '')] << regexp.source
      end

      parsers.sort.each do |parser, regexp|
        opt.banner << "  - #{parser}: #{regexp.join ', '}\n"
      end

      opt.banner << "\n  The following options are deprecated:\n\n"

      name_length = DEPRECATED.keys.sort_by { |k| k.length }.last.length

      DEPRECATED.sort_by { |k,| k }.each do |name, reason|
        opt.banner << "    %*1$2$s  %3$s\n" % [-name_length, name, reason]
      end

      opt.accept Template do |template|
        template_dir = template_dir_for template

        unless template_dir then
          $stderr.puts "could not find template #{template}"
          nil
        else
          [template, template_dir]
        end
      end

      opt.accept Path do |directory|
        directory = File.expand_path directory

        raise OptionParser::InvalidArgument unless File.exist? directory

        directory
      end

      opt.accept PathArray do |directories,|
        directories = if directories then
                        directories.split(',').map { |d| d unless d.empty? }
                      end

        directories.map do |directory|
          directory = File.expand_path directory

          raise OptionParser::InvalidArgument unless File.exist? directory

          directory
        end
      end

      opt.separator nil
      opt.separator "Parsing options:"
      opt.separator nil

      if Object.const_defined? :Encoding then
        opt.on("--encoding=ENCODING", "-e", Encoding.list.map { |e| e.name },
               "Specifies the output encoding.  All files",
               "read will be converted to this encoding.",
               "Preferred over --charset") do |value|
                 @encoding = Encoding.find value
                 @charset = @encoding.to_s # may not be valid value
               end

        opt.separator nil
      end

      opt.on("--all", "-a",
             "Synonym for --visibility=private.") do |value|
        @visibility = :private
      end

      opt.separator nil

      opt.on("--exclude=PATTERN", "-x", Regexp,
             "Do not process files or directories",
             "matching PATTERN.") do |value|
        @exclude << value
      end

      opt.separator nil

      opt.on("--extension=NEW=OLD", "-E",
             "Treat files ending with .new as if they",
             "ended with .old. Using '-E cgi=rb' will",
             "cause xxx.cgi to be parsed as a Ruby file.") do |value|
        new, old = value.split(/=/, 2)

        unless new and old then
          raise OptionParser::InvalidArgument, "Invalid parameter to '-E'"
        end

        unless RDoc::Parser.alias_extension old, new then
          raise OptionParser::InvalidArgument, "Unknown extension .#{old} to -E"
        end
      end

      opt.separator nil

      opt.on("--[no-]force-update", "-U",
             "Forces rdoc to scan all sources even if",
             "newer than the flag file.") do |value|
        @force_update = value
      end

      opt.separator nil

      opt.on("--pipe",
             "Convert RDoc on stdin to HTML") do
        @pipe = true
      end

      opt.separator nil

      opt.on("--tab-width=WIDTH", "-w", OptionParser::DecimalInteger,
             "Set the width of tab characters.") do |value|
        @tab_width = value
      end

      opt.separator nil

      opt.on("--visibility=VISIBILITY", "-V", RDoc::VISIBILITIES,
             "Minimum visibility to document a method.",
             "One of 'public', 'protected' (the default)",
             "or 'private'. Can be abbreviated.") do |value|
        @visibility = value
      end

      opt.separator nil

      markup_formats = RDoc::Text::MARKUP_FORMAT.keys.sort

      opt.on("--markup=MARKUP", markup_formats,
             "The markup format for the named files.",
             "The default is rdoc.  Valid values are:",
             markup_formats.join(', ')) do |value|
        @markup = value
      end

      opt.separator nil
      opt.separator "Common generator options:"
      opt.separator nil

      opt.on("--force-output", "-O",
             "Forces rdoc to write the output files,",
             "even if the output directory exists",
             "and does not seem to have been created",
             "by rdoc.") do |value|
        @force_output = value
      end

      opt.separator nil

      generator_text = @generators.keys.map { |name| "  #{name}" }.sort

      opt.on("-f", "--fmt=FORMAT", "--format=FORMAT", @generators.keys,
             "Set the output formatter.  One of:", *generator_text) do |value|
        check_generator

        @generator_name = value.downcase
        setup_generator
      end

      opt.separator nil

      opt.on("--include=DIRECTORIES", "-i", PathArray,
             "Set (or add to) the list of directories to",
             "be searched when satisfying :include:",
             "requests. Can be used more than once.") do |value|
        @rdoc_include.concat value.map { |dir| dir.strip }
      end

      opt.separator nil

      opt.on("--[no-]coverage-report=[LEVEL]", "--[no-]dcov", "-C", Integer,
             "Prints a report on undocumented items.",
             "Does not generate files.") do |value|
        value = 0 if value.nil? # Integer converts -C to nil

        @coverage_report = value
        @force_update = true if value
      end

      opt.separator nil

      opt.on("--output=DIR", "--op", "-o",
             "Set the output directory.") do |value|
        @op_dir = value
      end

      opt.separator nil

      opt.on("-d",
             "Deprecated --diagram option.",
             "Prevents firing debug mode",
             "with legacy invocation.") do |value|
      end

      opt.separator nil
      opt.separator 'HTML generator options:'
      opt.separator nil

      opt.on("--charset=CHARSET", "-c",
             "Specifies the output HTML character-set.",
             "Use --encoding instead of --charset if",
             "available.") do |value|
        @charset = value
      end

      opt.separator nil

      opt.on("--hyperlink-all", "-A",
             "Generate hyperlinks for all words that",
             "correspond to known methods, even if they",
             "do not start with '#' or '::' (legacy",
             "behavior).") do |value|
        @hyperlink_all = value
      end

      opt.separator nil

      opt.on("--main=NAME", "-m",
             "NAME will be the initial page displayed.") do |value|
        @main_page = value
      end

      opt.separator nil

      opt.on("--[no-]line-numbers", "-N",
             "Include line numbers in the source code.",
             "By default, only the number of the first",
             "line is displayed, in a leading comment.") do |value|
        @line_numbers = value
      end

      opt.separator nil

      opt.on("--show-hash", "-H",
             "A name of the form #name in a comment is a",
             "possible hyperlink to an instance method",
             "name. When displayed, the '#' is removed",
             "unless this option is specified.") do |value|
        @show_hash = value
      end

      opt.separator nil

      opt.on("--template=NAME", "-T", Template,
             "Set the template used when generating",
             "output. The default depends on the",
             "formatter used.") do |(template, template_dir)|
        @template     = template
        @template_dir = template_dir
      end

      opt.separator nil

      opt.on("--title=TITLE", "-t",
             "Set TITLE as the title for HTML output.") do |value|
        @title = value
      end

      opt.separator nil

      opt.on("--copy-files=PATH", Path,
             "Specify a file or directory to copy static",
             "files from.",
             "If a file is given it will be copied into",
             "the output dir.  If a directory is given the",
             "entire directory will be copied.",
             "You can use this multiple times") do |value|
        @static_path << value
      end

      opt.separator nil

      opt.on("--webcvs=URL", "-W",
             "Specify a URL for linking to a web frontend",
             "to CVS. If the URL contains a '\%s', the",
             "name of the current file will be",
             "substituted; if the URL doesn't contain a",
             "'\%s', the filename will be appended to it.") do |value|
        @webcvs = value
      end

      opt.separator nil
      opt.separator "ri generator options:"
      opt.separator nil

      opt.on("--ri", "-r",
             "Generate output for use by `ri`. The files",
             "are stored in the '.rdoc' directory under",
             "your home directory unless overridden by a",
             "subsequent --op parameter, so no special",
             "privileges are needed.") do |value|
        check_generator

        @generator_name = "ri"
        @op_dir ||= RDoc::RI::Paths::HOMEDIR
        setup_generator
      end

      opt.separator nil

      opt.on("--ri-site", "-R",
             "Generate output for use by `ri`. The files",
             "are stored in a site-wide directory,",
             "making them accessible to others, so",
             "special privileges are needed.") do |value|
        check_generator

        @generator_name = "ri"
        @op_dir = RDoc::RI::Paths::SITEDIR
        setup_generator
      end

      opt.separator nil
      opt.separator "Generic options:"
      opt.separator nil

      opt.on("--write-options",
             "Write .rdoc_options to the current",
             "directory with the given options.  Not all",
             "options will be used.  See RDoc::Options",
             "for details.") do |value|
        @write_options = true
      end

      opt.separator nil

      opt.on("--[no-]dry-run",
             "Don't write any files") do |value|
        @dry_run = value
      end

      opt.separator nil

      opt.on("-D", "--[no-]debug",
             "Displays lots on internal stuff.") do |value|
        $DEBUG_RDOC = value
      end

      opt.separator nil

      opt.on("--[no-]ignore-invalid",
             "Ignore invalid options and continue",
             "(default true).") do |value|
        ignore_invalid = value
      end

      opt.separator nil

      opt.on("--quiet", "-q",
             "Don't show progress as we parse.") do |value|
        @verbosity = 0
      end

      opt.separator nil

      opt.on("--verbose", "-v",
             "Display extra progress as RDoc parses") do |value|
        @verbosity = 2
      end

      opt.separator nil

      opt.on("--help",
             "Display this help") do
        RDoc::RDoc::GENERATORS.each_key do |generator|
          setup_generator generator
        end

        puts opt.help
        exit
      end

      opt.separator nil
    end

    setup_generator 'darkfish' if
      argv.grep(/\A(-f|--fmt|--format|-r|-R|--ri|--ri-site)\b/).empty?

    deprecated = []
    invalid = []

    begin
      opts.parse! argv
    rescue OptionParser::InvalidArgument, OptionParser::InvalidOption => e
      if DEPRECATED[e.args.first] then
        deprecated << e.args.first
      elsif %w[--format --ri -r --ri-site -R].include? e.args.first then
        raise
      else
        invalid << e.args.join(' ')
      end

      retry
    end

    unless @generator then
      @generator = RDoc::Generator::Darkfish
      @generator_name = 'darkfish'
    end

    if @pipe and not argv.empty? then
      @pipe = false
      invalid << '-p (with files)'
    end

    unless quiet then
      deprecated.each do |opt|
        $stderr.puts 'option ' << opt << ' is deprecated: ' << DEPRECATED[opt]
      end

      unless invalid.empty? then
        invalid = "invalid options: #{invalid.join ', '}"

        if ignore_invalid then
          $stderr.puts invalid
          $stderr.puts '(invalid options are ignored)'
        else
          $stderr.puts opts
          $stderr.puts invalid
          exit 1
        end
      end
    end

    @files = argv.dup

    finish

    if @write_options then
      write_options
      exit
    end

    self
  end