Skip to content

Customizable Indentation in OptionParser Help Messages #14153

@kojix2

Description

@kojix2

Hi!

I am using Crystal to create a command line tool for myself and I've been working with OptionParser. It would be great to have more flexibility in customizing the help messages.

Here's an example:

require "option_parser"

struct Point
  property x : Float64 = 0
  property y : Float64 = 0
end

point = Point.new

OptionParser.parse do |parser|
  parser.on("-x FLOAT", "x-coordinate") { |x| point.x = x.to_f64 }
  parser.on("-y FLOAT", "y-coordinate") { |y| point.y = y.to_f64 }
  parser.on("-h", "--help", "Prints this help") { puts parser; exit }
end

p point

When I use --help, it displays as follows:

    -x FLOAT                         x-coordinate
    -y FLOAT                         y-coordinate
    -h, --help                       Prints this help
              |||||| too wide |||||||

The space between the flag and its description is excessively long.

private def append_flag(flag, description)
indent = " " * 37
description = description.gsub("\n", "\n#{indent}")
if flag.size >= 33
@flags << " #{flag}\n#{indent}#{description}"
else
@flags << " #{flag}#{" " * (33 - flag.size)}#{description}"
end
end

As per my understanding, the indentation is hardcoded to 33 spaces. An alternative could be reducing it to 14, for instance.

class OptionParser
  private def append_flag(flag, description)
    indent = " " * 37
    description = description.gsub("\n", "\n#{indent}")
    if flag.size >= 14
      @flags << "    #{flag}\n#{indent}#{description}"
    else
      @flags << "    #{flag}#{" " * (14 - flag.size)}#{description}"
    end
  end
end

With this change, --help would display as:

    -x FLOAT      x-coordinate
    -y FLOAT      y-coordinate
    -h, --help    Prints this help

Crystal supports open classes, but having a more configurable option would be even better.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions