Skip to content

Instantly share code, notes, and snippets.

@AdamSpannbauer
Created June 9, 2020 10:38
Show Gist options
  • Save AdamSpannbauer/162de91ee37e78ddbb88401629daf4fa to your computer and use it in GitHub Desktop.
Save AdamSpannbauer/162de91ee37e78ddbb88401629daf4fa to your computer and use it in GitHub Desktop.
An extension of R's `help()` / `?` to work with roxygen style documentation written in a Pythonic / docstring style for non-packaged functions.
# An extension of help / `?` to work with roxygen documentation in a
# Pythonic / docstring style for non-packaged functions.
.fun_body = function(fun) {
#' Get body of function (including comments) as a character vector
#'
#' @param fun name of function obj to return body of
#'
#' @return character vector of function body (1 element per line)
#'
#' @examples
#' .fun_body(c)
#' .fun_body(.fun_body)
capture.output(
print.function(fun, useSource = TRUE)
)
}
.print_docstring = function(fun) {
#' Show 'docstring' style documentation in function body
#'
#' @param fun function to search and print docstring for
#'
#' @return NULL; output
#' @export
#'
#' @examples
#' .print_docstring(.print_docstring)
doc_pattern = "^\\s+#'"
fb = .fun_body(fun)
doc_lines = fb[grep(doc_pattern, fb)]
doc_lines = gsub(doc_pattern, "", doc_lines)
print_doc = paste(doc_lines, collapse = "\n")
cat(paste(print_doc, "\n"))
invisible(print_doc)
}
help2 = function(topic, ...) {
#' Extend help to try and print docstring style roxygen style docs in fun body
#'
#' @param topic name of topic/function to show help for
#' @param ... additional params to be passed to help()
#'
#' @return NULL
#'
#' @examples
#' help2(help2)
#' help2(c)
str_topic = as.character(substitute(topic))
help_output = capture.output(help(str_topic, ...))
if (length(help_output) != 0) {
topic_obj = NULL
try(expr = {
topic_obj = get(str_topic)
}, silent = TRUE)
if (!is.null(topic_obj) & is.function(topic_obj)) {
docs_out = .print_docstring(topic_obj)
if (docs_out != "") return(invisible(NULL))
}
}
cat(paste(help_output, collapse = "\n"))
return(invisible(NULL))
}
`?` = help2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment