diff --git a/R/formatting.R b/R/formatting.R index c72abea4..667d708b 100644 --- a/R/formatting.R +++ b/R/formatting.R @@ -129,6 +129,10 @@ range_formatting_reply <- function(id, uri, document, range, options) { #' Format on type #' @noRd on_type_formatting_reply <- function(id, uri, document, point, ch, options) { + if (!check_scope(uri, document, point)) { + return(Response$new(id)) + } + content <- document$content end_line <- point$row + 1 use_completer <- FALSE diff --git a/R/utils.R b/R/utils.R index 4cb83a95..124cb2e2 100644 --- a/R/utils.R +++ b/R/utils.R @@ -173,8 +173,7 @@ is_rmarkdown <- function(uri) { check_scope <- function(uri, document, point) { if (document$is_rmarkdown) { row <- point$row - flags <- vapply( - document$content[1:(row + 1)], startsWith, logical(1), "```", USE.NAMES = FALSE) + flags <- startsWith(document$content[1:(row + 1)], "```") if (any(flags)) { last_match <- document$content[max(which(flags))] stringi::stri_detect_regex(last_match, "```+\\s*\\{[rR][ ,\\}]") && diff --git a/tests/testthat/test-formatting.R b/tests/testthat/test-formatting.R index 17697dbd..2d18dd01 100644 --- a/tests/testthat/test-formatting.R +++ b/tests/testthat/test-formatting.R @@ -175,3 +175,43 @@ test_that("Formatting in Rmarkdown works", { expect_equal(result[[1]]$range$end, list(line = 1, character = 29)) expect_equal(result[[1]]$newText, "my_fn <- function(x) {\n x + 1\n x\n}") }) + +test_that("On type formatting works in Rmarkdown", { + skip_on_cran() + client <- language_client() + + temp_file <- withr::local_tempfile(fileext = ".Rmd") + writeLines(c( + "---", + "title: 1+1", + "---", + "", + "1+1", + "", + "```{r}", + "my_fn<-function(x){", # nolint + "f(x+1,x-1)", + "data[x,y]", + "}", + "```" + ), temp_file) + + client %>% did_save(temp_file) + + result <- client %>% respond_on_type_formatting(temp_file, c(1, 10), ")", retry = FALSE) + expect_length(result, 0) + + result <- client %>% respond_on_type_formatting(temp_file, c(4, 3), ")", retry = FALSE) + expect_length(result, 0) + + result <- client %>% respond_on_type_formatting(temp_file, c(10, 1), "}") + expect_length(result, 1) + lines <- strsplit(result[[1]]$newText, "\n")[[1]] + expect_length(lines, 4) + expect_equal(lines, c( + "my_fn <- function(x) {", + " f(x + 1, x - 1)", + " data[x, y]", + "}" + )) +})