R/utils.R

Defines functions get_input get_selection

Documented in get_input

#' Get input text
#' @param input character.
#' @param clip logical.
#' @param collapse logical.
#' @importFrom clipr read_clip
#' @export
#' @examples
#' get_input("xxx")
get_input <- function(input = NULL,
                      clip = FALSE,
                      collapse = TRUE) {
    if (!is.null(input)) {
        return(input)
    }

    selection <- get_selection(collapse = collapse)
    if (selection == "") {
        return(clipr::read_clip())
    }
    if (is.null(input) & selection != "") {
        return(selection)
    }


}

get_selection <- function(collapse = TRUE) {
    text <- rstudioapi::getSourceEditorContext() %>%
        rstudioapi::primary_selection() %>%
        .[["text"]]
    if (collapse == FALSE) {
        text %>%
            str_split("\n") %>%
            .[[1]] %>%
            .[stringr::str_length(.) > 0]
        # drop empty lines
    } else {
        text
    }
}

lines2one <- function(input) {
    input %>%
        stringr::str_flatten("\n")
}

insert_lines <- function(input) {
    input %>%
        lines2one() %>%
        rstudioapi::insertText()
}

#' Bottom line
#'
#' @author Jiaxiang Li
#'
#' @importFrom cli rule
#'
tips <- function() {
    cli::rule(left = "The text is already pasted on your system clipboard!", col = "red")
}

write_bottom_line <- function(output) {
    cat("\n\n")
    cat("output: ")
    cat("\n\n")
    cat(output)
    cat("\n\n")
    cat(tips())
    invisible(output)
}

glue_lines <-
    function(input, glue_obj = glue::glue("- [ ] {input}")) {
        glue_obj %>%
            glue::glue_collapse(sep = "\n")
    }

#' @importFrom glue glue
get_html <-
    function(input, style) {
        text <- glue::glue('<{style}>{input}</{style}>')
        invisible(text)
    }
JiaxiangBU/add2md documentation built on Jan. 31, 2020, 7:46 p.m.