trevorld / r-optparse

command-line optional argument parser
http://trevorldavis.com/R/optparse/dev/
GNU General Public License v2.0
146 stars 11 forks source link

Wrap long help text #30

Closed nh3 closed 3 years ago

nh3 commented 5 years ago

Would it be possible to make the following changes to wrap long help text?

https://github.com/trevorld/r-optparse/blob/26b6627c0b48dfbcfe1c3556fe55cd800c9dee19/R/optparse.R#L338-L339

cat('\n')
cat(paste(strwrap(sub("%default", .as_string(option@default), option@help), prefix='\t\t'), collapse='\n'))

Of course, one can supply pre-formatted text to help, but it seems laborious to call a formatter for every option compared with this change of two lines of code here?

nh3 commented 5 years ago

Alternatively, perhaps do something like this to achieve both flexibility and backward compatibility?

default_formatter <- function(text) {
    paste0("\t\t", text)
}
...
...
parse_args <- function(object, args = commandArgs(trailingOnly = TRUE), 
                    print_help_and_exit = TRUE, positional_arguments = FALSE,
                    convert_hyphens_to_underscores = FALSE,
                    help_formatter=default_formatter) {
...
...
           print_help(object, help_formatter)
...
...
}
...
...
print_help <- function(object, formatter) {
...
...
        cat("\n")
        cat(formatter(sub("%default", .as_string(option@default), option@help)))
        cat("\n\n")
...
...
}
trevorld commented 5 years ago

Looking at Python's optparse documentation it'd be more idiomatic to make it an argument to OptionParser and have the default function (to format all the help) be called IndentedHelpFormatter) (but putting the new formatter argument at the end so as to not break reverse compatibility):

OptionParser <- function(usage = "usage: %prog [options]", option_list=list(),
                            add_help_option=TRUE, prog=NULL, 
                            description="", epilogue="", formatter=IndentedHelpFormatter) {
    ....
} 
print_help <- function(object) { object@formatter(object) }