HelpFormatter.java

  1. /*
  2.   Licensed to the Apache Software Foundation (ASF) under one or more
  3.   contributor license agreements.  See the NOTICE file distributed with
  4.   this work for additional information regarding copyright ownership.
  5.   The ASF licenses this file to You under the Apache License, Version 2.0
  6.   (the "License"); you may not use this file except in compliance with
  7.   the License.  You may obtain a copy of the License at

  8.       http://www.apache.org/licenses/LICENSE-2.0

  9.   Unless required by applicable law or agreed to in writing, software
  10.   distributed under the License is distributed on an "AS IS" BASIS,
  11.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12.   See the License for the specific language governing permissions and
  13.   limitations under the License.
  14.  */

  15. package org.apache.commons.cli;

  16. import java.io.BufferedReader;
  17. import java.io.IOException;
  18. import java.io.PrintWriter;
  19. import java.io.Serializable;
  20. import java.io.StringReader;
  21. import java.io.UncheckedIOException;
  22. import java.util.ArrayList;
  23. import java.util.Arrays;
  24. import java.util.Collection;
  25. import java.util.Collections;
  26. import java.util.Comparator;
  27. import java.util.Iterator;
  28. import java.util.List;
  29. import java.util.Objects;
  30. import java.util.function.Function;
  31. import java.util.function.Supplier;

  32. /**
  33.  * A formatter of help messages for command line options.
  34.  * <p>
  35.  * Example:
  36.  * </p>
  37.  * <pre>
  38.  * Options options = new Options();
  39.  * options.addOption(OptionBuilder.withLongOpt("file").withDescription("The file to be processed").hasArg().withArgName("FILE").isRequired().create('f'));
  40.  * options.addOption(OptionBuilder.withLongOpt("version").withDescription("Print the version of the application").create('v'));
  41.  * options.addOption(OptionBuilder.withLongOpt("help").create('h'));
  42.  *
  43.  * String header = "Do something useful with an input file\n\n";
  44.  * String footer = "\nPlease report issues at https://example.com/issues";
  45.  *
  46.  * HelpFormatter formatter = new HelpFormatter();
  47.  * formatter.printHelp("myapp", header, options, footer, true);
  48.  * </pre>
  49.  * <p>
  50.  * This produces the following output:
  51.  * </p>
  52.  * <pre>
  53.  * usage: myapp -f &lt;FILE&gt; [-h] [-v]
  54.  * Do something useful with an input file
  55.  *
  56.  *  -f,--file &lt;FILE&gt;   The file to be processed
  57.  *  -h,--help
  58.  *  -v,--version       Print the version of the application
  59.  *
  60.  * Please report issues at https://example.com/issues
  61.  * </pre>
  62.  */
  63. public class HelpFormatter {

  64.     /**
  65.      * Builds {@link HelpFormatter}.
  66.      *
  67.      * @since 1.7.0
  68.      */
  69.     public static class Builder implements Supplier<HelpFormatter> {
  70.         // TODO All other instance HelpFormatter instance variables.
  71.         // Make HelpFormatter immutable for 2.0

  72.         /**
  73.          * A function to convert a description (not null) and a deprecated Option (not null) to help description
  74.          */
  75.         private static final Function<Option, String> DEFAULT_DEPRECATED_FORMAT = o -> "[Deprecated] " + getDescription(o);

  76.         /**
  77.          * Formatter for deprecated options.
  78.          */
  79.         private Function<Option, String> deprecatedFormatFunction = DEFAULT_DEPRECATED_FORMAT;

  80.         /**
  81.          * The output PrintWriter, defaults to wrapping {@link System#out}.
  82.          */
  83.         private PrintWriter printStream = createDefaultPrintWriter();

  84.         /** The flag to determine if the since values should be dispalyed */
  85.         private boolean showSince;

  86.         @Override
  87.         public HelpFormatter get() {
  88.             return new HelpFormatter(deprecatedFormatFunction, printStream, showSince);
  89.         }

  90.         /**
  91.          * Sets the output PrintWriter, defaults to wrapping {@link System#out}.
  92.          *
  93.          * @param printWriter the output PrintWriter, not null.
  94.          * @return {@code this} instance.
  95.          */
  96.         public Builder setPrintWriter(final PrintWriter printWriter) {
  97.             this.printStream = Objects.requireNonNull(printWriter, "printWriter");
  98.             return this;
  99.         }

  100.         /**
  101.          * Sets whether to show deprecated options.
  102.          *
  103.          * @param useDefaultFormat if {@code true} use the default format, otherwise clear the formatter.
  104.          * @return {@code this} instance.
  105.          */
  106.         public Builder setShowDeprecated(final boolean useDefaultFormat) {
  107.             return setShowDeprecated(useDefaultFormat ? DEFAULT_DEPRECATED_FORMAT : null);
  108.         }

  109.         /**
  110.          * Sets whether to show deprecated options.
  111.          *
  112.          * @param deprecatedFormatFunction Specify the format for the deprecated options.
  113.          * @return {@code this} instance.
  114.          * @since 1.8.0
  115.          */
  116.         public Builder setShowDeprecated(final Function<Option, String> deprecatedFormatFunction) {
  117.             this.deprecatedFormatFunction = deprecatedFormatFunction;
  118.             return this;
  119.         }

  120.         /**
  121.          * Sets whether to show the date the option was first added.
  122.          * @param showSince if @{code true} the date the options was first added will be shown.
  123.          * @return this builder.
  124.          * @since 1.9.0
  125.          */
  126.         public Builder setShowSince(final boolean showSince) {
  127.             this.showSince = showSince;
  128.             return this;
  129.         }
  130.     }

  131.     /**
  132.      * This class implements the {@code Comparator} interface for comparing Options.
  133.      */
  134.     private static final class OptionComparator implements Comparator<Option>, Serializable {

  135.         /** The serial version UID. */
  136.         private static final long serialVersionUID = 5305467873966684014L;

  137.         /**
  138.          * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument
  139.          * is less than, equal to, or greater than the second.
  140.          *
  141.          * @param opt1 The first Option to be compared.
  142.          * @param opt2 The second Option to be compared.
  143.          * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than
  144.          *         the second.
  145.          */
  146.         @Override
  147.         public int compare(final Option opt1, final Option opt2) {
  148.             return opt1.getKey().compareToIgnoreCase(opt2.getKey());
  149.         }
  150.     }
  151.     /** "Options" text for options header */
  152.     private static final String HEADER_OPTIONS = "Options";

  153.     /** "Since" text for options header */
  154.     private static final String HEADER_SINCE = "Since";

  155.     /** "Description" test for options header */
  156.     private static final String HEADER_DESCRIPTION = "Description";

  157.     /** Default number of characters per line */
  158.     public static final int DEFAULT_WIDTH = 74;

  159.     /** Default padding to the left of each line */
  160.     public static final int DEFAULT_LEFT_PAD = 1;

  161.     /** Number of space characters to be prefixed to each description line */
  162.     public static final int DEFAULT_DESC_PAD = 3;

  163.     /** The string to display at the beginning of the usage statement */
  164.     public static final String DEFAULT_SYNTAX_PREFIX = "usage: ";

  165.     /** Default prefix for shortOpts */
  166.     public static final String DEFAULT_OPT_PREFIX = "-";

  167.     /** Default prefix for long Option */
  168.     public static final String DEFAULT_LONG_OPT_PREFIX = "--";

  169.     /**
  170.      * Default separator displayed between a long Option and its value
  171.      *
  172.      * @since 1.3
  173.      */
  174.     public static final String DEFAULT_LONG_OPT_SEPARATOR = " ";

  175.     /** Default name for an argument */
  176.     public static final String DEFAULT_ARG_NAME = "arg";

  177.     /**
  178.      * Creates a new builder.
  179.      *
  180.      * @return a new builder.
  181.      * @since 1.7.0
  182.      */
  183.     public static Builder builder() {
  184.         return new Builder();
  185.     }

  186.     private static PrintWriter createDefaultPrintWriter() {
  187.         return new PrintWriter(System.out);
  188.     }

  189.     /**
  190.      * Gets the option description or an empty string if the description is {@code null}.
  191.      * @param option The option to get the description from.
  192.      * @return the option description or an empty string if the description is {@code null}.
  193.      * @since 1.8.0
  194.      */
  195.     public static String getDescription(final Option option) {
  196.         final String desc = option.getDescription();
  197.         return desc == null ? "" : desc;
  198.     }

  199.     /**
  200.      * Number of characters per line
  201.      *
  202.      * @deprecated Scope will be made private for next major version - use get/setWidth methods instead.
  203.      */
  204.     @Deprecated
  205.     public int defaultWidth = DEFAULT_WIDTH;

  206.     /**
  207.      * Amount of padding to the left of each line
  208.      *
  209.      * @deprecated Scope will be made private for next major version - use get/setLeftPadding methods instead.
  210.      */
  211.     @Deprecated
  212.     public int defaultLeftPad = DEFAULT_LEFT_PAD;

  213.     /**
  214.      * The number of characters of padding to be prefixed to each description line
  215.      *
  216.      * @deprecated Scope will be made private for next major version - use get/setDescPadding methods instead.
  217.      */
  218.     @Deprecated
  219.     public int defaultDescPad = DEFAULT_DESC_PAD;

  220.     /**
  221.      * The string to display at the beginning of the usage statement
  222.      *
  223.      * @deprecated Scope will be made private for next major version - use get/setSyntaxPrefix methods instead.
  224.      */
  225.     @Deprecated
  226.     public String defaultSyntaxPrefix = DEFAULT_SYNTAX_PREFIX;

  227.     /**
  228.      * The new line string
  229.      *
  230.      * @deprecated Scope will be made private for next major version - use get/setNewLine methods instead.
  231.      */
  232.     @Deprecated
  233.     public String defaultNewLine = System.lineSeparator();

  234.     /**
  235.      * The shortOpt prefix
  236.      *
  237.      * @deprecated Scope will be made private for next major version - use get/setOptPrefix methods instead.
  238.      */
  239.     @Deprecated
  240.     public String defaultOptPrefix = DEFAULT_OPT_PREFIX;

  241.     /**
  242.      * The long Opt prefix
  243.      *
  244.      * @deprecated Scope will be made private for next major version - use get/setLongOptPrefix methods instead.
  245.      */
  246.     @Deprecated
  247.     public String defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX;

  248.     /**
  249.      * The name of the argument
  250.      *
  251.      * @deprecated Scope will be made private for next major version - use get/setArgName methods instead.
  252.      */
  253.     @Deprecated
  254.     public String defaultArgName = DEFAULT_ARG_NAME;

  255.     /**
  256.      * Comparator used to sort the options when they output in help text
  257.      *
  258.      * Defaults to case-insensitive alphabetical sorting by option key
  259.      */
  260.     protected Comparator<Option> optionComparator = new OptionComparator();

  261.     /**
  262.      * Function to format the description for a deprecated option.
  263.      */
  264.     private final Function<Option, String> deprecatedFormatFunction;

  265.     /**
  266.      * Where to print help.
  267.      */
  268.     private final PrintWriter printWriter;

  269.     /** Flag to determine if since field should be displayed */
  270.     private final boolean showSince;

  271.     /**
  272.      * The separator displayed between the long option and its value.
  273.      */
  274.     private String longOptSeparator = DEFAULT_LONG_OPT_SEPARATOR;

  275.     /**
  276.      * Constructs a new instance.
  277.      */
  278.     public HelpFormatter() {
  279.         this(null, createDefaultPrintWriter(), false);
  280.     }

  281.     /**
  282.      * Constructs a new instance.
  283.      * @param printWriter TODO
  284.      */
  285.     private HelpFormatter(final Function<Option, String> deprecatedFormatFunction, final PrintWriter printWriter, final boolean showSince) {
  286.         // TODO All other instance HelpFormatter instance variables.
  287.         // Make HelpFormatter immutable for 2.0
  288.         this.deprecatedFormatFunction = deprecatedFormatFunction;
  289.         this.printWriter = printWriter;
  290.         this.showSince = showSince;
  291.     }

  292.     /**
  293.      * Appends the usage clause for an Option to a StringBuffer.
  294.      *
  295.      * @param buff the StringBuffer to append to
  296.      * @param option the Option to append
  297.      * @param required whether the Option is required or not
  298.      */
  299.     private void appendOption(final StringBuilder buff, final Option option, final boolean required) {
  300.         if (!required) {
  301.             buff.append("[");
  302.         }
  303.         if (option.getOpt() != null) {
  304.             buff.append("-").append(option.getOpt());
  305.         } else {
  306.             buff.append("--").append(option.getLongOpt());
  307.         }
  308.         // if the Option has a value and a non blank argname
  309.         if (option.hasArg() && (option.getArgName() == null || !option.getArgName().isEmpty())) {
  310.             buff.append(option.getOpt() == null ? longOptSeparator : " ");
  311.             buff.append("<").append(option.getArgName() != null ? option.getArgName() : getArgName()).append(">");
  312.         }
  313.         // if the Option is not a required option
  314.         if (!required) {
  315.             buff.append("]");
  316.         }
  317.     }

  318.     /**
  319.      * Appends the usage clause for an OptionGroup to a StringBuffer. The clause is wrapped in square brackets if the group
  320.      * is required. The display of the options is handled by appendOption
  321.      *
  322.      * @param buff the StringBuilder to append to
  323.      * @param group the group to append
  324.      * @see #appendOption(StringBuilder,Option,boolean)
  325.      */
  326.     private void appendOptionGroup(final StringBuilder buff, final OptionGroup group) {
  327.         if (!group.isRequired()) {
  328.             buff.append("[");
  329.         }
  330.         final List<Option> optList = new ArrayList<>(group.getOptions());
  331.         if (getOptionComparator() != null) {
  332.             Collections.sort(optList, getOptionComparator());
  333.         }
  334.         // for each option in the OptionGroup
  335.         for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
  336.             // whether the option is required or not is handled at group level
  337.             appendOption(buff, it.next(), true);

  338.             if (it.hasNext()) {
  339.                 buff.append(" | ");
  340.             }
  341.         }
  342.         if (!group.isRequired()) {
  343.             buff.append("]");
  344.         }
  345.     }

  346.     /**
  347.      * Renders the specified Options and return the rendered Options in a StringBuffer.
  348.      *
  349.      * @param sb The StringBuffer to place the rendered Options into.
  350.      * @param width The number of characters to display per line
  351.      * @param options The command line Options
  352.      * @param leftPad the number of characters of padding to be prefixed to each line
  353.      * @param descPad the number of characters of padding to be prefixed to each description line
  354.      * @return the StringBuffer with the rendered Options contents.
  355.      * @throws IOException if an I/O error occurs.
  356.      */
  357.     <A extends Appendable> A appendOptions(final A sb, final int width, final Options options, final int leftPad, final int descPad) throws IOException {
  358.         final String lpad = createPadding(leftPad);
  359.         final String dpad = createPadding(descPad);
  360.         // first create list containing only <lpad>-a,--aaa where
  361.         // -a is opt and --aaa is long opt; in parallel look for
  362.         // the longest opt string this list will be then used to
  363.         // sort options ascending
  364.         int max = 0;
  365.         final int maxSince = showSince ? determineMaxSinceLength(options) + leftPad : 0;
  366.         final List<StringBuilder> prefixList = new ArrayList<>();
  367.         final List<Option> optList = options.helpOptions();
  368.         if (getOptionComparator() != null) {
  369.             Collections.sort(optList, getOptionComparator());
  370.         }
  371.         for (final Option option : optList) {
  372.             final StringBuilder optBuf = new StringBuilder();
  373.             if (option.getOpt() == null) {
  374.                 optBuf.append(lpad).append("   ").append(getLongOptPrefix()).append(option.getLongOpt());
  375.             } else {
  376.                 optBuf.append(lpad).append(getOptPrefix()).append(option.getOpt());
  377.                 if (option.hasLongOpt()) {
  378.                     optBuf.append(',').append(getLongOptPrefix()).append(option.getLongOpt());
  379.                 }
  380.             }
  381.             if (option.hasArg()) {
  382.                 final String argName = option.getArgName();
  383.                 if (argName != null && argName.isEmpty()) {
  384.                     // if the option has a blank argname
  385.                     optBuf.append(' ');
  386.                 } else {
  387.                     optBuf.append(option.hasLongOpt() ? longOptSeparator : " ");
  388.                     optBuf.append("<").append(argName != null ? option.getArgName() : getArgName()).append(">");
  389.                 }
  390.             }

  391.             prefixList.add(optBuf);
  392.             max = Math.max(optBuf.length() + maxSince, max);
  393.         }
  394.         final int nextLineTabStop = max + descPad;
  395.         if (showSince) {
  396.             final StringBuilder optHeader = new StringBuilder(HEADER_OPTIONS).append(createPadding(max - maxSince - HEADER_OPTIONS.length() + leftPad))
  397.                     .append(HEADER_SINCE);
  398.             optHeader.append(createPadding(max - optHeader.length())).append(lpad).append(HEADER_DESCRIPTION);
  399.             appendWrappedText(sb, width, nextLineTabStop, optHeader.toString());
  400.             sb.append(getNewLine());
  401.         }

  402.         int x = 0;
  403.         for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
  404.             final Option option = it.next();
  405.             final StringBuilder optBuf = new StringBuilder(prefixList.get(x++).toString());
  406.             if (optBuf.length() < max) {
  407.                 optBuf.append(createPadding(max - maxSince - optBuf.length()));
  408.                 if (showSince) {
  409.                     optBuf.append(lpad).append(option.getSince() == null ? "-" : option.getSince());
  410.                 }
  411.                 optBuf.append(createPadding(max - optBuf.length()));
  412.             }
  413.             optBuf.append(dpad);

  414.             if (deprecatedFormatFunction != null && option.isDeprecated()) {
  415.                 optBuf.append(deprecatedFormatFunction.apply(option).trim());
  416.             } else if (option.getDescription() != null) {
  417.                 optBuf.append(option.getDescription());
  418.             }
  419.             appendWrappedText(sb, width, nextLineTabStop, optBuf.toString());
  420.             if (it.hasNext()) {
  421.                 sb.append(getNewLine());
  422.             }
  423.         }
  424.         return sb;
  425.     }

  426.     /**
  427.      * Renders the specified text and return the rendered Options in a StringBuffer.
  428.      *
  429.      * @param <A> The Appendable implementation.
  430.      * @param appendable The StringBuffer to place the rendered text into.
  431.      * @param width The number of characters to display per line
  432.      * @param nextLineTabStop The position on the next line for the first tab.
  433.      * @param text The text to be rendered.
  434.      * @return the StringBuffer with the rendered Options contents.
  435.      * @throws IOException if an I/O error occurs.
  436.      */
  437.     <A extends Appendable> A appendWrappedText(final A appendable, final int width, final int nextLineTabStop, final String text) throws IOException {
  438.         String render = text;
  439.         int nextLineTabStopPos = nextLineTabStop;
  440.         int pos = findWrapPos(render, width, 0);
  441.         if (pos == -1) {
  442.             appendable.append(rtrim(render));
  443.             return appendable;
  444.         }
  445.         appendable.append(rtrim(render.substring(0, pos))).append(getNewLine());
  446.         if (nextLineTabStopPos >= width) {
  447.             // stops infinite loop happening
  448.             nextLineTabStopPos = 1;
  449.         }
  450.         // all following lines must be padded with nextLineTabStop space characters
  451.         final String padding = createPadding(nextLineTabStopPos);
  452.         while (true) {
  453.             render = padding + render.substring(pos).trim();
  454.             pos = findWrapPos(render, width, 0);
  455.             if (pos == -1) {
  456.                 appendable.append(render);
  457.                 return appendable;
  458.             }
  459.             if (render.length() > width && pos == nextLineTabStopPos - 1) {
  460.                 pos = width;
  461.             }
  462.             appendable.append(rtrim(render.substring(0, pos))).append(getNewLine());
  463.         }
  464.     }

  465.     /**
  466.      * Creates a String of padding of length {@code len}.
  467.      *
  468.      * @param len The length of the String of padding to create.
  469.      *
  470.      * @return The String of padding
  471.      */
  472.     protected String createPadding(final int len) {
  473.         final char[] padding = new char[len];
  474.         Arrays.fill(padding, ' ');
  475.         return new String(padding);
  476.     }

  477.     private int determineMaxSinceLength(final Options options) {
  478.         final int minLen = HEADER_SINCE.length();
  479.         final int len = options.getOptions().stream().map(o -> o.getSince() == null ? minLen : o.getSince().length()).max(Integer::compareTo).orElse(minLen);
  480.         return len < minLen ? minLen : len;
  481.     }

  482.     /**
  483.      * Finds the next text wrap position after {@code startPos} for the text in {@code text} with the column width
  484.      * {@code width}. The wrap point is the last position before startPos+width having a whitespace character (space,
  485.      * \n, \r). If there is no whitespace character before startPos+width, it will return startPos+width.
  486.      *
  487.      * @param text The text being searched for the wrap position
  488.      * @param width width of the wrapped text
  489.      * @param startPos position from which to start the lookup whitespace character
  490.      * @return position on which the text must be wrapped or -1 if the wrap position is at the end of the text
  491.      */
  492.     protected int findWrapPos(final String text, final int width, final int startPos) {
  493.         // the line ends before the max wrap pos or a new line char found
  494.         int pos = text.indexOf(Char.LF, startPos);
  495.         if (pos != -1 && pos <= width) {
  496.             return pos + 1;
  497.         }
  498.         pos = text.indexOf(Char.TAB, startPos);
  499.         if (pos != -1 && pos <= width) {
  500.             return pos + 1;
  501.         }
  502.         if (startPos + width >= text.length()) {
  503.             return -1;
  504.         }
  505.         // look for the last whitespace character before startPos+width
  506.         for (pos = startPos + width; pos >= startPos; --pos) {
  507.             final char c = text.charAt(pos);
  508.             if (c == Char.SP || c == Char.LF || c == Char.CR) {
  509.                 break;
  510.             }
  511.         }
  512.         // if we found it - just return
  513.         if (pos > startPos) {
  514.             return pos;
  515.         }
  516.         // if we didn't find one, simply chop at startPos+width
  517.         pos = startPos + width;
  518.         return pos == text.length() ? -1 : pos;
  519.     }

  520.     /**
  521.      * Gets the 'argName'.
  522.      *
  523.      * @return the 'argName'
  524.      */
  525.     public String getArgName() {
  526.         return defaultArgName;
  527.     }

  528.     /**
  529.      * Gets the 'descPadding'.
  530.      *
  531.      * @return the 'descPadding'
  532.      */
  533.     public int getDescPadding() {
  534.         return defaultDescPad;
  535.     }

  536.     /**
  537.      * Gets the 'leftPadding'.
  538.      *
  539.      * @return the 'leftPadding'
  540.      */
  541.     public int getLeftPadding() {
  542.         return defaultLeftPad;
  543.     }

  544.     /**
  545.      * Gets the 'longOptPrefix'.
  546.      *
  547.      * @return the 'longOptPrefix'
  548.      */
  549.     public String getLongOptPrefix() {
  550.         return defaultLongOptPrefix;
  551.     }

  552.     /**
  553.      * Gets the separator displayed between a long option and its value.
  554.      *
  555.      * @return the separator
  556.      * @since 1.3
  557.      */
  558.     public String getLongOptSeparator() {
  559.         return longOptSeparator;
  560.     }

  561.     /**
  562.      * Gets the 'newLine'.
  563.      *
  564.      * @return the 'newLine'
  565.      */
  566.     public String getNewLine() {
  567.         return defaultNewLine;
  568.     }

  569.     /**
  570.      * Comparator used to sort the options when they output in help text. Defaults to case-insensitive alphabetical sorting
  571.      * by option key.
  572.      *
  573.      * @return the {@link Comparator} currently in use to sort the options
  574.      * @since 1.2
  575.      */
  576.     public Comparator<Option> getOptionComparator() {
  577.         return optionComparator;
  578.     }

  579.     /**
  580.      * Gets the 'optPrefix'.
  581.      *
  582.      * @return the 'optPrefix'
  583.      */
  584.     public String getOptPrefix() {
  585.         return defaultOptPrefix;
  586.     }

  587.     /**
  588.      * Gets the 'syntaxPrefix'.
  589.      *
  590.      * @return the 'syntaxPrefix'
  591.      */
  592.     public String getSyntaxPrefix() {
  593.         return defaultSyntaxPrefix;
  594.     }

  595.     /**
  596.      * Gets the 'width'.
  597.      *
  598.      * @return the 'width'
  599.      */
  600.     public int getWidth() {
  601.         return defaultWidth;
  602.     }

  603.     /**
  604.      * Prints the help for {@code options} with the specified command line syntax. This method prints help information
  605.      * to  {@link System#out}  by default.
  606.      *
  607.      * @param width the number of characters to be displayed on each line
  608.      * @param cmdLineSyntax the syntax for this application
  609.      * @param header the banner to display at the beginning of the help
  610.      * @param options the Options instance
  611.      * @param footer the banner to display at the end of the help
  612.      */
  613.     public void printHelp(final int width, final String cmdLineSyntax, final String header, final Options options, final String footer) {
  614.         printHelp(width, cmdLineSyntax, header, options, footer, false);
  615.     }

  616.     /**
  617.      * Prints the help for {@code options} with the specified command line syntax. This method prints help information
  618.      * to {@link System#out} by default.
  619.      *
  620.      * @param width the number of characters to be displayed on each line
  621.      * @param cmdLineSyntax the syntax for this application
  622.      * @param header the banner to display at the beginning of the help
  623.      * @param options the Options instance
  624.      * @param footer the banner to display at the end of the help
  625.      * @param autoUsage whether to print an automatically generated usage statement
  626.      */
  627.     public void printHelp(final int width, final String cmdLineSyntax, final String header, final Options options, final String footer,
  628.         final boolean autoUsage) {
  629.         final PrintWriter pw = new PrintWriter(printWriter);
  630.         printHelp(pw, width, cmdLineSyntax, header, options, getLeftPadding(), getDescPadding(), footer, autoUsage);
  631.         pw.flush();
  632.     }

  633.     /**
  634.      * Prints the help for {@code options} with the specified command line syntax.
  635.      *
  636.      * @param pw the writer to which the help will be written
  637.      * @param width the number of characters to be displayed on each line
  638.      * @param cmdLineSyntax the syntax for this application
  639.      * @param header the banner to display at the beginning of the help
  640.      * @param options the Options instance
  641.      * @param leftPad the number of characters of padding to be prefixed to each line
  642.      * @param descPad the number of characters of padding to be prefixed to each description line
  643.      * @param footer the banner to display at the end of the help
  644.      *
  645.      * @throws IllegalStateException if there is no room to print a line
  646.      */
  647.     public void printHelp(final PrintWriter pw, final int width, final String cmdLineSyntax, final String header, final Options options, final int leftPad,
  648.         final int descPad, final String footer) {
  649.         printHelp(pw, width, cmdLineSyntax, header, options, leftPad, descPad, footer, false);
  650.     }

  651.     /**
  652.      * Prints the help for {@code options} with the specified command line syntax.
  653.      *
  654.      * @param pw the writer to which the help will be written
  655.      * @param width the number of characters to be displayed on each line
  656.      * @param cmdLineSyntax the syntax for this application
  657.      * @param header the banner to display at the beginning of the help
  658.      * @param options the Options instance
  659.      * @param leftPad the number of characters of padding to be prefixed to each line
  660.      * @param descPad the number of characters of padding to be prefixed to each description line
  661.      * @param footer the banner to display at the end of the help
  662.      * @param autoUsage whether to print an automatically generated usage statement
  663.      * @throws IllegalStateException if there is no room to print a line
  664.      */
  665.     public void printHelp(final PrintWriter pw, final int width, final String cmdLineSyntax, final String header, final Options options, final int leftPad,
  666.         final int descPad, final String footer, final boolean autoUsage) {
  667.         if (Util.isEmpty(cmdLineSyntax)) {
  668.             throw new IllegalArgumentException("cmdLineSyntax not provided");
  669.         }
  670.         if (autoUsage) {
  671.             printUsage(pw, width, cmdLineSyntax, options);
  672.         } else {
  673.             printUsage(pw, width, cmdLineSyntax);
  674.         }
  675.         if (header != null && !header.isEmpty()) {
  676.             printWrapped(pw, width, header);
  677.         }
  678.         printOptions(pw, width, options, leftPad, descPad);
  679.         if (footer != null && !footer.isEmpty()) {
  680.             printWrapped(pw, width, footer);
  681.         }
  682.     }

  683.     /**
  684.      * Prints the help for {@code options} with the specified command line syntax. This method prints help information
  685.      * to {@link System#out} by default.
  686.      *
  687.      * @param cmdLineSyntax the syntax for this application
  688.      * @param options the Options instance
  689.      */
  690.     public void printHelp(final String cmdLineSyntax, final Options options) {
  691.         printHelp(getWidth(), cmdLineSyntax, null, options, null, false);
  692.     }

  693.     /**
  694.      * Prints the help for {@code options} with the specified command line syntax. This method prints help information
  695.      * to {@link System#out} by default.
  696.      *
  697.      * @param cmdLineSyntax the syntax for this application
  698.      * @param options the Options instance
  699.      * @param autoUsage whether to print an automatically generated usage statement
  700.      */
  701.     public void printHelp(final String cmdLineSyntax, final Options options, final boolean autoUsage) {
  702.         printHelp(getWidth(), cmdLineSyntax, null, options, null, autoUsage);
  703.     }

  704.     /**
  705.      * Prints the help for {@code options} with the specified command line syntax. This method prints help information
  706.      * to {@link System#out} by default.
  707.      *
  708.      * @param cmdLineSyntax the syntax for this application
  709.      * @param header the banner to display at the beginning of the help
  710.      * @param options the Options instance
  711.      * @param footer the banner to display at the end of the help
  712.      */
  713.     public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer) {
  714.         printHelp(cmdLineSyntax, header, options, footer, false);
  715.     }

  716.     /**
  717.      * Prints the help for {@code options} with the specified command line syntax. This method prints help information
  718.      * to {@link System#out} by default.
  719.      *
  720.      * @param cmdLineSyntax the syntax for this application
  721.      * @param header the banner to display at the beginning of the help
  722.      * @param options the Options instance
  723.      * @param footer the banner to display at the end of the help
  724.      * @param autoUsage whether to print an automatically generated usage statement
  725.      */
  726.     public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer, final boolean autoUsage) {
  727.         printHelp(getWidth(), cmdLineSyntax, header, options, footer, autoUsage);
  728.     }

  729.     /**
  730.      * Prints the help for the specified Options to the specified writer, using the specified width, left padding and
  731.      * description padding.
  732.      *
  733.      * @param pw The printWriter to write the help to
  734.      * @param width The number of characters to display per line
  735.      * @param options The command line Options
  736.      * @param leftPad the number of characters of padding to be prefixed to each line
  737.      * @param descPad the number of characters of padding to be prefixed to each description line
  738.      */
  739.     public void printOptions(final PrintWriter pw, final int width, final Options options, final int leftPad, final int descPad) {
  740.         try {
  741.             pw.println(appendOptions(new StringBuilder(), width, options, leftPad, descPad));
  742.         } catch (final IOException e) {
  743.             // Cannot happen
  744.             throw new UncheckedIOException(e);
  745.         }
  746.     }

  747.     /**
  748.      * Prints the cmdLineSyntax to the specified writer, using the specified width.
  749.      *
  750.      * @param pw The printWriter to write the help to
  751.      * @param width The number of characters per line for the usage statement.
  752.      * @param cmdLineSyntax The usage statement.
  753.      */
  754.     public void printUsage(final PrintWriter pw, final int width, final String cmdLineSyntax) {
  755.         final int argPos = cmdLineSyntax.indexOf(' ') + 1;
  756.         printWrapped(pw, width, getSyntaxPrefix().length() + argPos, getSyntaxPrefix() + cmdLineSyntax);
  757.     }

  758.     /**
  759.      * Prints the usage statement for the specified application.
  760.      *
  761.      * @param pw The PrintWriter to print the usage statement
  762.      * @param width The number of characters to display per line
  763.      * @param app The application name
  764.      * @param options The command line Options
  765.      */
  766.     public void printUsage(final PrintWriter pw, final int width, final String app, final Options options) {
  767.         // initialize the string buffer
  768.         final StringBuilder buff = new StringBuilder(getSyntaxPrefix()).append(app).append(Char.SP);
  769.         // create a list for processed option groups
  770.         final Collection<OptionGroup> processedGroups = new ArrayList<>();
  771.         final List<Option> optList = new ArrayList<>(options.getOptions());
  772.         if (getOptionComparator() != null) {
  773.             Collections.sort(optList, getOptionComparator());
  774.         }
  775.         // iterate over the options
  776.         for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
  777.             // get the next Option
  778.             final Option option = it.next();
  779.             // check if the option is part of an OptionGroup
  780.             final OptionGroup group = options.getOptionGroup(option);
  781.             // if the option is part of a group
  782.             if (group != null) {
  783.                 // and if the group has not already been processed
  784.                 if (!processedGroups.contains(group)) {
  785.                     // add the group to the processed list
  786.                     processedGroups.add(group);
  787.                     // add the usage clause
  788.                     appendOptionGroup(buff, group);
  789.                 }
  790.                 // otherwise the option was displayed in the group
  791.                 // previously so ignore it.
  792.             }
  793.             // if the Option is not part of an OptionGroup
  794.             else {
  795.                 appendOption(buff, option, option.isRequired());
  796.             }
  797.             if (it.hasNext()) {
  798.                 buff.append(Char.SP);
  799.             }
  800.         }

  801.         // call printWrapped
  802.         printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString());
  803.     }

  804.     /**
  805.      * Prints the specified text to the specified PrintWriter.
  806.      *
  807.      * @param pw The printWriter to write the help to
  808.      * @param width The number of characters to display per line
  809.      * @param nextLineTabStop The position on the next line for the first tab.
  810.      * @param text The text to be written to the PrintWriter
  811.      */
  812.     public void printWrapped(final PrintWriter pw, final int width, final int nextLineTabStop, final String text) {
  813.         pw.println(renderWrappedTextBlock(new StringBuilder(text.length()), width, nextLineTabStop, text));
  814.     }

  815.     /**
  816.      * Prints the specified text to the specified PrintWriter.
  817.      *
  818.      * @param pw The printWriter to write the help to
  819.      * @param width The number of characters to display per line
  820.      * @param text The text to be written to the PrintWriter
  821.      */
  822.     public void printWrapped(final PrintWriter pw, final int width, final String text) {
  823.         printWrapped(pw, width, 0, text);
  824.     }

  825.     /**
  826.      * Renders the specified Options and return the rendered Options in a StringBuffer.
  827.      *
  828.      * @param sb The StringBuffer to place the rendered Options into.
  829.      * @param width The number of characters to display per line
  830.      * @param options The command line Options
  831.      * @param leftPad the number of characters of padding to be prefixed to each line
  832.      * @param descPad the number of characters of padding to be prefixed to each description line
  833.      *
  834.      * @return the StringBuffer with the rendered Options contents.
  835.      */
  836.     protected StringBuffer renderOptions(final StringBuffer sb, final int width, final Options options, final int leftPad, final int descPad) {
  837.         try {
  838.             return appendOptions(sb, width, options, leftPad, descPad);
  839.         } catch (final IOException e) {
  840.             // Cannot happen
  841.             throw new UncheckedIOException(e);
  842.         }
  843.     }

  844.     /**
  845.      * Renders the specified text and return the rendered Options in a StringBuffer.
  846.      *
  847.      * @param sb The StringBuffer to place the rendered text into.
  848.      * @param width The number of characters to display per line
  849.      * @param nextLineTabStop The position on the next line for the first tab.
  850.      * @param text The text to be rendered.
  851.      *
  852.      * @return the StringBuffer with the rendered Options contents.
  853.      */
  854.     protected StringBuffer renderWrappedText(final StringBuffer sb, final int width, final int nextLineTabStop, final String text) {
  855.         try {
  856.             return appendWrappedText(sb, width, nextLineTabStop, text);
  857.         } catch (final IOException e) {
  858.             // Cannot happen.
  859.             throw new UncheckedIOException(e);
  860.         }
  861.     }

  862.     /**
  863.      * Renders the specified text width a maximum width. This method differs from renderWrappedText by not removing leading
  864.      * spaces after a new line.
  865.      *
  866.      * @param appendable The StringBuffer to place the rendered text into.
  867.      * @param width The number of characters to display per line
  868.      * @param nextLineTabStop The position on the next line for the first tab.
  869.      * @param text The text to be rendered.
  870.      */
  871.     private <A extends Appendable> A renderWrappedTextBlock(final A appendable, final int width, final int nextLineTabStop, final String text) {
  872.         try {
  873.             final BufferedReader in = new BufferedReader(new StringReader(text));
  874.             String line;
  875.             boolean firstLine = true;
  876.             while ((line = in.readLine()) != null) {
  877.                 if (!firstLine) {
  878.                     appendable.append(getNewLine());
  879.                 } else {
  880.                     firstLine = false;
  881.                 }
  882.                 appendWrappedText(appendable, width, nextLineTabStop, line);
  883.             }
  884.         } catch (final IOException e) { // NOPMD
  885.             // cannot happen
  886.         }
  887.         return appendable;
  888.     }

  889.     /**
  890.      * Removes the trailing whitespace from the specified String.
  891.      *
  892.      * @param s The String to remove the trailing padding from.
  893.      * @return The String of without the trailing padding
  894.      */
  895.     protected String rtrim(final String s) {
  896.         if (Util.isEmpty(s)) {
  897.             return s;
  898.         }
  899.         int pos = s.length();
  900.         while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) {
  901.             --pos;
  902.         }
  903.         return s.substring(0, pos);
  904.     }

  905.     /**
  906.      * Sets the 'argName'.
  907.      *
  908.      * @param name the new value of 'argName'
  909.      */
  910.     public void setArgName(final String name) {
  911.         this.defaultArgName = name;
  912.     }

  913.     /**
  914.      * Sets the 'descPadding'.
  915.      *
  916.      * @param padding the new value of 'descPadding'
  917.      */
  918.     public void setDescPadding(final int padding) {
  919.         this.defaultDescPad = padding;
  920.     }

  921.     /**
  922.      * Sets the 'leftPadding'.
  923.      *
  924.      * @param padding the new value of 'leftPadding'
  925.      */
  926.     public void setLeftPadding(final int padding) {
  927.         this.defaultLeftPad = padding;
  928.     }

  929.     /**
  930.      * Sets the 'longOptPrefix'.
  931.      *
  932.      * @param prefix the new value of 'longOptPrefix'
  933.      */
  934.     public void setLongOptPrefix(final String prefix) {
  935.         this.defaultLongOptPrefix = prefix;
  936.     }

  937.     /**
  938.      * Sets the separator displayed between a long option and its value. Ensure that the separator specified is supported by
  939.      * the parser used, typically ' ' or '='.
  940.      *
  941.      * @param longOptSeparator the separator, typically ' ' or '='.
  942.      * @since 1.3
  943.      */
  944.     public void setLongOptSeparator(final String longOptSeparator) {
  945.         this.longOptSeparator = longOptSeparator;
  946.     }

  947.     /**
  948.      * Sets the 'newLine'.
  949.      *
  950.      * @param newline the new value of 'newLine'
  951.      */
  952.     public void setNewLine(final String newline) {
  953.         this.defaultNewLine = newline;
  954.     }

  955.     /**
  956.      * Sets the comparator used to sort the options when they output in help text. Passing in a null comparator will keep the
  957.      * options in the order they were declared.
  958.      *
  959.      * @param comparator the {@link Comparator} to use for sorting the options
  960.      * @since 1.2
  961.      */
  962.     public void setOptionComparator(final Comparator<Option> comparator) {
  963.         this.optionComparator = comparator;
  964.     }

  965.     /**
  966.      * Sets the 'optPrefix'.
  967.      *
  968.      * @param prefix the new value of 'optPrefix'
  969.      */
  970.     public void setOptPrefix(final String prefix) {
  971.         this.defaultOptPrefix = prefix;
  972.     }

  973.     /**
  974.      * Sets the 'syntaxPrefix'.
  975.      *
  976.      * @param prefix the new value of 'syntaxPrefix'
  977.      */
  978.     public void setSyntaxPrefix(final String prefix) {
  979.         this.defaultSyntaxPrefix = prefix;
  980.     }

  981.     /**
  982.      * Sets the 'width'.
  983.      *
  984.      * @param width the new value of 'width'
  985.      */
  986.     public void setWidth(final int width) {
  987.         this.defaultWidth = width;
  988.     }

  989. }