Skip to content

Commit

Permalink
Refactor RStudio helpers
Browse files Browse the repository at this point in the history
And flag encoding as UTF-8. Fixes #82
  • Loading branch information
hadley committed May 31, 2017
1 parent a638fdb commit 3960cc7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
37 changes: 29 additions & 8 deletions R/reprex-addin.R
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,11 @@ reprex_addin <- function() { # nocov start

reprex_guess <- function(source, venue = "gh", source_file = NULL,
si = FALSE, show = FALSE) {
context <- rstudioapi::getSourceEditorContext()

reprex_input <- switch(
source,
clipboard = NULL,
cur_sel = newlined(rstudioapi::primary_selection(context)[["text"]]),
cur_file = newlined(context$contents),
cur_sel = rstudio_selection(),
cur_file = rstudio_file(),
input_file = source_file$datapath
)

Expand All @@ -125,14 +123,37 @@ reprex_selection <- function(
si = getOption("reprex.si", FALSE),
show = getOption("reprex.show", TRUE)
) {
context <- rstudioapi::getSourceEditorContext()
selection <- newlined(rstudioapi::primary_selection(context)[["text"]])

reprex(
input = selection,
input = rstudio_selection(),
venue = venue,
si = si,
show = show
)
}

# RStudio helpers ---------------------------------------------------------

rstudio_file <- function(context = rstudio_context()) {
rstudio_text_tidy(context$contents)
}

rstudio_selection <- function(context = rstudio_context()) {
text <- rstudioapi::primary_selection(context)[["text"]]
rstudio_text_tidy(text)
}

rstudio_context <- function() {
rstudioapi::getSourceEditorContext()
}

rstudio_text_tidy <- function(x) {
Encoding(x) <- "UTF-8"

n <- length(x)
if (!grepl("\n$", x[[n]])) {
x[[n]] <- paste0(x[[n]], "\n")
}
x
}

# nocov end
7 changes: 0 additions & 7 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,6 @@ add_ext <- function(x, ext = "R", force = FALSE) {
}
}

newlined <- function(x) {
if (!grepl("\n$", x[[length(x)]])) {
x[[length(x)]] <- paste0(x[[length(x)]], "\n")
}
x
}

## read from
## 1 clipboard
## 2 `input`, which could be
Expand Down

0 comments on commit 3960cc7

Please sign in to comment.