From 3960cc7448e07c681af5bfafe154f5eb9c410ee2 Mon Sep 17 00:00:00 2001 From: hadley Date: Wed, 31 May 2017 08:34:26 -0500 Subject: [PATCH] Refactor RStudio helpers And flag encoding as UTF-8. Fixes #82 --- R/reprex-addin.R | 37 +++++++++++++++++++++++++++++-------- R/utils.R | 7 ------- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/R/reprex-addin.R b/R/reprex-addin.R index 32c6b491..73fcc8cb 100644 --- a/R/reprex-addin.R +++ b/R/reprex-addin.R @@ -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 ) @@ -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 diff --git a/R/utils.R b/R/utils.R index 2c68577a..7b25243e 100644 --- a/R/utils.R +++ b/R/utils.R @@ -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