Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow long options to be left-aligned in usage help #774

Open
remkop opened this issue Jul 28, 2019 · 3 comments
Open

Allow long options to be left-aligned in usage help #774

remkop opened this issue Jul 28, 2019 · 3 comments

Comments

@remkop
Copy link
Owner

remkop commented Jul 28, 2019

The checkstyle team are not happy (see checkstyle/checkstyle#6924) with the option layout where short options are in a separate column from long options. They prefer a layout where long options appear left-aligned.

UPDATE (Aug 2019): the description of that ticket has been modified; all options in the checkstyle application now have a short name as well as a long name.

@remkop
Copy link
Owner Author

remkop commented Jul 28, 2019

Note that this is already configurable and I will provide an example of how to accomplish this with the current version of picocli.

@remkop
Copy link
Owner Author

remkop commented Jul 30, 2019

The example below demonstrates how to left-align long options in the usage help.

It currently is quite a bit of code. In future versions of picocli it would be nice to provide some API so that applications can accomplish this more easily.

package picocli.examples.layout;

import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Help;
import picocli.CommandLine.Help.ColorScheme;
import picocli.CommandLine.IHelpFactory;
import picocli.CommandLine.Model.ArgSpec;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Option;

import java.util.concurrent.Callable;

@Command(name = "layout-demo", mixinStandardHelpOptions = true, description = "option list layout demo")
public class LayoutDemo implements Callable<Integer> {

    @Option(names = "--large-option",        description = "large option") boolean largeOption;
    @Option(names = {"-l", "--long-option"}, description = "long option")  String longOption;

    @Override
    public Integer call() {
        // run the business logic
        // ...
        int exitCode = 0;
        return exitCode;
    }

    public static void main(String[] args) {
        CommandLine cmd = new CommandLine(new LayoutDemo());

        // customize the usage help to left-align long options
        cmd.setHelpFactory(createCustomizedUsageHelp());

        // instead of cmd.execute, applications can also call cmd.parseArgs
        System.exit(cmd.execute(args));
    }

    private static IHelpFactory createCustomizedUsageHelp() {
        return new IHelpFactory() {
            private static final int COLUMN_REQUIRED_OPTION_MARKER_WIDTH = 2;
            private static final int COLUMN_SHORT_OPTION_NAME_WIDTH = 2;
            private static final int COLUMN_OPTION_NAME_SEPARATOR_WIDTH = 2;
            private static final int COLUMN_LONG_OPTION_NAME_WIDTH = 22;

            private static final int INDEX_REQUIRED_OPTION_MARKER = 0;
            private static final int INDEX_SHORT_OPTION_NAME = 1;
            private static final int INDEX_OPTION_NAME_SEPARATOR = 2;
            private static final int INDEX_LONG_OPTION_NAME = 3;
            private static final int INDEX_OPTION_DESCRIPTION = 4;

            @Override
            public Help create(CommandSpec commandSpec, ColorScheme colorScheme) {
                return new Help(commandSpec, colorScheme) {
                    @Override
                    public Layout createDefaultLayout() {

                        // The default layout creates a TextTable with 5 columns, as follows:
                        // 0: empty text or (if configured) the requiredOptionMarker character
                        // 1: short option name
                        // 2: comma separator (if option has both short and long option)
                        // 3: long option name(s)
                        // 4: option description
                        //
                        // The code below creates a TextTable with 3 columns, as follows:
                        // 0: empty text or (if configured) the requiredOptionMarker character
                        // 1: all option names, comma-separated if necessary
                        // 2: option description

                        int optionNamesColumnWidth = COLUMN_SHORT_OPTION_NAME_WIDTH +
                                                     COLUMN_OPTION_NAME_SEPARATOR_WIDTH +
                                                     COLUMN_LONG_OPTION_NAME_WIDTH;

                        TextTable table = TextTable.forColumnWidths(colorScheme.ansi(),
                                COLUMN_REQUIRED_OPTION_MARKER_WIDTH,
                                optionNamesColumnWidth,
                                commandSpec.usageMessage().width() - (optionNamesColumnWidth + COLUMN_REQUIRED_OPTION_MARKER_WIDTH));
                        Layout result = new Layout(colorScheme,
                                                   table,
                                                   createDefaultOptionRenderer(),
                                                   createDefaultParameterRenderer()) {
                            public void layout(ArgSpec argSpec, Ansi.Text[][] cellValues) {

                                // The default option renderer produces 5 Text values for each option.
                                // Below we combine the short option name, comma separator and long option name
                                // into a single Text object, and we pass 3 Text values to the TextTable.
                                for (Ansi.Text[] original : cellValues) {
                                    if (original[INDEX_OPTION_NAME_SEPARATOR].getCJKAdjustedLength() > 0) {
                                        original[INDEX_OPTION_NAME_SEPARATOR] = original[INDEX_OPTION_NAME_SEPARATOR].concat(" ");
                                    }
                                    Ansi.Text[] threeColumns = new Ansi.Text[] {
                                            original[INDEX_REQUIRED_OPTION_MARKER],
                                            original[INDEX_SHORT_OPTION_NAME]
                                                    .concat(original[INDEX_OPTION_NAME_SEPARATOR])
                                                    .concat(original[INDEX_LONG_OPTION_NAME]),
                                            original[INDEX_OPTION_DESCRIPTION],
                                    };
                                    table.addRowValues(threeColumns);
                                }
                            }
                        };
                        return result;
                    }
                };
            }
        };
    }
}

This produces the following usage help message. Note that the --large-option option is left-aligned:

Usage: layout-demo [-hV] [--large-option] [-l=<longOption>]
option list layout demo
  -h, --help                Show this help message and exit.
  -l, --long-option=<longOption>
                            long option
  --large-option            large option
  -V, --version             Print version information and exit.

remkop added a commit that referenced this issue Jul 30, 2019
@remkop
Copy link
Owner Author

remkop commented Aug 5, 2019

Many commands do left-align long options, but an example of a command whose usage help shows the long options in a separate column is man --help:

Usage: man [OPTION...] [SECTION] PAGE...

  -C, --config-file=FILE     use this user configuration file
  -d, --debug                emit debugging messages
  -D, --default              reset all options to their default values
      --warnings[=WARNINGS]  enable warnings from groff

 Main modes of operation:
  -f, --whatis               equivalent to whatis
  -k, --apropos              equivalent to apropos
  -K, --global-apropos       search for text in all pages
  -l, --local-file           interpret PAGE argument(s) as local filename(s)
  -w, --where, --path, --location
                             print physical location of man page(s)
  -W, --where-cat, --location-cat
                             print physical location of cat file(s)

  -c, --catman               used by catman to reformat out of date cat pages
  -R, --recode=ENCODING      output source page encoded in ENCODING

 Finding manual pages:
  -L, --locale=LOCALE        define the locale for this particular man search
  -m, --systems=SYSTEM       use manual pages from other systems
  -M, --manpath=PATH         set search path for manual pages to PATH

  -S, -s, --sections=LIST    use colon separated section list

  -e, --extension=EXTENSION  limit search to extension type EXTENSION

  -i, --ignore-case          look for pages case-insensitively (default)
  -I, --match-case           look for pages case-sensitively

      --regex                show all pages matching regex
      --wildcard             show all pages matching wildcard

      --names-only           make --regex and --wildcard match page names only,
                             not descriptions

  -a, --all                  find all matching manual pages
  -u, --update               force a cache consistency check

      --no-subpages          don't try subpages, e.g. 'man foo bar' => 'man
                             foo-bar'

 Controlling formatted output:
  -P, --pager=PAGER          use program PAGER to display output
  -r, --prompt=STRING        provide the `less' pager with a prompt

  -7, --ascii                display ASCII translation of certain latin1 chars
  -E, --encoding=ENCODING    use selected output encoding
      --no-hyphenation, --nh turn off hyphenation
      --no-justification,                              --nj   turn off justification
  -p, --preprocessor=STRING  STRING indicates which preprocessors to run:
                             e - [n]eqn, p - pic, t - tbl,
g - grap, r - refer, v - vgrind

  -t, --troff                use groff to format pages
  -T, --troff-device[=DEVICE]   use groff with selected device

  -H, --html[=BROWSER]       use www-browser or BROWSER to display HTML output
  -X, --gxditview[=RESOLUTION]   use groff and display through gxditview
                             (X11):
                             -X = -TX75, -X100 = -TX100, -X100-12 = -TX100-12
  -Z, --ditroff              use groff and force it to produce ditroff

  -?, --help                 give this help list
      --usage                give a short usage message
  -V, --version              print program version

Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.

Report bugs to cjwatson@debian.org.

Another is ls --help:

Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

Mandatory arguments to long options are mandatory for short options too.
  -a, --all                  do not ignore entries starting with .
  -A, --almost-all           do not list implied . and ..
      --author               with -l, print the author of each file
  -b, --escape               print C-style escapes for nongraphic characters
      --block-size=SIZE      scale sizes by SIZE before printing them; e.g.,
                               '--block-size=M' prints sizes in units of
                               1,048,576 bytes; see SIZE format below
  -B, --ignore-backups       do not list implied entries ending with ~
  -c                         with -lt: sort by, and show, ctime (time of last
                               modification of file status information);
                               with -l: show ctime and sort by name;
                               otherwise: sort by ctime, newest first
  -C                         list entries by columns
      --color[=WHEN]         colorize the output; WHEN can be 'always' (default
                               if omitted), 'auto', or 'never'; more info below
  -d, --directory            list directories themselves, not their contents
  -D, --dired                generate output designed for Emacs' dired mode
  -f                         do not sort, enable -aU, disable -ls --color
  -F, --classify             append indicator (one of */=>@|) to entries
      --file-type            likewise, except do not append '*'
      --format=WORD          across -x, commas -m, horizontal -x, long -l,
                               single-column -1, verbose -l, vertical -C
      --full-time            like -l --time-style=full-iso
  -g                         like -l, but do not list owner
      --group-directories-first
                             group directories before files;
                               can be augmented with a --sort option, but any
                               use of --sort=none (-U) disables grouping
  -G, --no-group             in a long listing, don't print group names
  -h, --human-readable       with -l and/or -s, print human readable sizes
                               (e.g., 1K 234M 2G)
      --si                   likewise, but use powers of 1000 not 1024
  -H, --dereference-command-line
                             follow symbolic links listed on the command line
      --dereference-command-line-symlink-to-dir
                             follow each command line symbolic link
                               that points to a directory
      --hide=PATTERN         do not list implied entries matching shell PATTERN
                               (overridden by -a or -A)
      --indicator-style=WORD  append indicator with style WORD to entry names:
                               none (default), slash (-p),
                               file-type (--file-type), classify (-F)
  -i, --inode                print the index number of each file
  -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN
  -k, --kibibytes            default to 1024-byte blocks for disk usage
  -l                         use a long listing format
  -L, --dereference          when showing file information for a symbolic
                               link, show information for the file the link
                               references rather than for the link itself
  -m                         fill width with a comma separated list of entries
  -n, --numeric-uid-gid      like -l, but list numeric user and group IDs
  -N, --literal              print raw entry names (don't treat e.g. control
                               characters specially)
  -o                         like -l, but do not list group information
  -p, --indicator-style=slash
                             append / indicator to directories
  -q, --hide-control-chars   print ? instead of nongraphic characters
      --show-control-chars   show nongraphic characters as-is (the default,
                               unless program is 'ls' and output is a terminal)
  -Q, --quote-name           enclose entry names in double quotes
      --quoting-style=WORD   use quoting style WORD for entry names:
                               literal, locale, shell, shell-always,
                               shell-escape, shell-escape-always, c, escape
  -r, --reverse              reverse order while sorting
  -R, --recursive            list subdirectories recursively
  -s, --size                 print the allocated size of each file, in blocks
  -S                         sort by file size, largest first
      --sort=WORD            sort by WORD instead of name: none (-U), size (-S),
                               time (-t), version (-v), extension (-X)
      --time=WORD            with -l, show time as WORD instead of default
                               modification time: atime or access or use (-u);
                               ctime or status (-c); also use specified time
                               as sort key if --sort=time (newest first)
      --time-style=STYLE     with -l, show times using style STYLE:
                               full-iso, long-iso, iso, locale, or +FORMAT;
                               FORMAT is interpreted like in 'date'; if FORMAT
                               is FORMAT1<newline>FORMAT2, then FORMAT1 applies
                               to non-recent files and FORMAT2 to recent files;
                               if STYLE is prefixed with 'posix-', STYLE
                               takes effect only outside the POSIX locale
  -t                         sort by modification time, newest first
  -T, --tabsize=COLS         assume tab stops at each COLS instead of 8
  -u                         with -lt: sort by, and show, access time;
                               with -l: show access time and sort by name;
                               otherwise: sort by access time, newest first
  -U                         do not sort; list entries in directory order
  -v                         natural sort of (version) numbers within text
  -w, --width=COLS           set output width to COLS.  0 means no limit
  -x                         list entries by lines instead of by columns
  -X                         sort alphabetically by entry extension
  -Z, --context              print any security context of each file
  -1                         list one file per line.  Avoid '\n' with -q or -b
      --help     display this help and exit
      --version  output version information and exit

The SIZE argument is an integer and optional unit (example: 10K is 10*1024).
Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000).

Using color to distinguish file types is disabled both by default and
with --color=never.  With --color=auto, ls emits color codes only when
standard output is connected to a terminal.  The LS_COLORS environment
variable can change the settings.  Use the dircolors command to set it.

Exit status:
 0  if OK,
 1  if minor problems (e.g., cannot access subdirectory),
 2  if serious trouble (e.g., cannot access command-line argument).

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Full documentation at: <http://www.gnu.org/software/coreutils/ls>
or available locally via: info '(coreutils) ls invocation'

tail --help

Usage: tail [OPTION]... [FILE]...
Print the last 10 lines of each FILE to standard output.
With more than one FILE, precede each with a header giving the file name.

With no FILE, or when FILE is -, read standard input.

Mandatory arguments to long options are mandatory for short options too.
  -c, --bytes=[+]NUM       output the last NUM bytes; or use -c +NUM to
                             output starting with byte NUM of each file
  -f, --follow[={name|descriptor}]
                           output appended data as the file grows;
                             an absent option argument means 'descriptor'
  -F                       same as --follow=name --retry
  -n, --lines=[+]NUM       output the last NUM lines, instead of the last 10;
                             or use -n +NUM to output starting with line NUM
      --max-unchanged-stats=N
                           with --follow=name, reopen a FILE which has not
                             changed size after N (default 5) iterations
                             to see if it has been unlinked or renamed
                             (this is the usual case of rotated log files);
                             with inotify, this option is rarely useful
      --pid=PID            with -f, terminate after process ID, PID dies
  -q, --quiet, --silent    never output headers giving file names
      --retry              keep trying to open a file if it is inaccessible
  -s, --sleep-interval=N   with -f, sleep for approximately N seconds
                             (default 1.0) between iterations;
                             with inotify and --pid=P, check process P at
                             least once every N seconds
  -v, --verbose            always output headers giving file names
  -z, --zero-terminated    line delimiter is NUL, not newline
      --help     display this help and exit
      --version  output version information and exit

NUM may have a multiplier suffix:
b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,
GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.

With --follow (-f), tail defaults to following the file descriptor, which
means that even if a tail'ed file is renamed, tail will continue to track
its end.  This default behavior is not desirable when you really want to
track the actual name of the file, not the file descriptor (e.g., log
rotation).  Use --follow=name in that case.  That causes tail to track the
named file in a way that accommodates renaming, removal and creation.

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Full documentation at: <http://www.gnu.org/software/coreutils/tail>
or available locally via: info '(coreutils) tail invocation'

info --help

Usage: info [OPTION]... [MENU-ITEM...]

Read documentation in Info format.

Options:
  -a, --all                    use all matching manuals.
  -k, --apropos=STRING         look up STRING in all indices of all manuals.
  -d, --directory=DIR          add DIR to INFOPATH.
      --dribble=FILE           remember user keystrokes in FILENAME.
  -f, --file=MANUAL            specify Info manual to visit.
  -h, --help                   display this help and exit.
      --index-search=STRING    go to node pointed by index entry STRING.
  -n, --node=NODENAME          specify nodes in first visited Info file.
  -o, --output=FILE            output selected nodes to FILE.
  -R, --raw-escapes            output "raw" ANSI escapes (default).
      --no-raw-escapes         output escapes as literal text.
      --restore=FILE           read initial keystrokes from FILE.
  -O, --show-options, --usage  go to command-line options node.
      --strict-node-location   (for debugging) use Info file pointers as-is.
      --subnodes               recursively output menu items.
  -v, --variable VAR=VALUE     assign VALUE to Info variable VAR.
      --vi-keys                use vi-like and less-like key bindings.
      --version                display version information and exit.
  -w, --where, --location      print physical location of Info file.
  -x, --debug=NUMBER           set debugging level (-1 for all).


The first non-option argument, if present, is the menu entry to start from;
it is searched for in all 'dir' files along INFOPATH.
If it is not present, info merges all 'dir' files and shows the result.
Any remaining arguments are treated as the names of menu
items relative to the initial node visited.

For a summary of key bindings, type H within Info.

Examples:
  info                       show top-level dir menu
  info info                  show the general manual for Info readers
  info info-stnd             show the manual specific to this Info program
  info emacs                 start at emacs node from top-level dir
  info emacs buffers         select buffers menu entry in emacs manual
  info emacs -n Files        start at Files node within emacs manual
  info '(emacs)Files'        alternative way to start at Files node
  info --show-options emacs  start at node with emacs' command line options
  info --subnodes -o out.txt emacs  dump entire manual to out.txt
  info -f ./foo.info         show file ./foo.info, not searching dir

Email bug reports to bug-texinfo@gnu.org,
general questions and discussion to help-texinfo@gnu.org.
Texinfo home page: http://www.gnu.org/software/texinfo/

@remkop remkop modified the milestones: 4.0.2, 4.1 Aug 6, 2019
@remkop remkop removed this from the 4.1 milestone Sep 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant