🔍 An RStudio addin slash regex utility belt
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

139 lines
4.4KB

  1. #' @export
  2. run_regex <- function(
  3. text,
  4. pattern,
  5. ignore.case = FALSE,
  6. perl = FALSE,
  7. fixed = FALSE,
  8. useBytes = FALSE,
  9. invert = FALSE
  10. ) {
  11. m <- regexec(pattern, text, ignore.case, perl, fixed, useBytes)
  12. x <- purrr::map(purrr::set_names(m, text), function(mi) list('idx' = purrr::map2(mi, attr(mi, "match.length"), ~ if(.x[1] != -1) c(.x, .x + .y - 1L))))
  13. y <- purrr::map(purrr::set_names(text), ~ list(text = .))
  14. z <- purrr::map(purrr::set_names(regmatches(text, m), text), ~ list(m = .))
  15. x <- utils::modifyList(y, x, TRUE)
  16. utils::modifyList(z, x, TRUE)
  17. }
  18. wrap_result <- function(x, escape = FALSE) {
  19. if (is.null(x$idx[[1]])) return(x$text)
  20. text <- x$text
  21. idx <- x$idx
  22. len_idx <- length(idx)
  23. inserts <- data.frame(
  24. i = 1:len_idx - 1,
  25. start = purrr::map_int(idx, ~ .[1]),
  26. end = purrr::map_int(idx, ~ .[2]) + 1
  27. ) %>%
  28. mutate(
  29. class = sprintf("group g%02d", i),
  30. pad = 0
  31. )
  32. for (j in seq_len(nrow(inserts))) {
  33. if (inserts$i[j] == 0) next
  34. overlap <- filter(
  35. inserts[1:(j-1), ],
  36. i != 0,
  37. start <= !!inserts$start[j] & end >= !!inserts$end[j])
  38. inserts[j, 'pad'] <- inserts$pad[j] + nrow(overlap)
  39. }
  40. inserts <- inserts %>%
  41. tidyr::gather(type, loc, start:end) %>%
  42. mutate(
  43. class = ifelse(pad > 0, sprintf("%s pad%02d", class, pad), class),
  44. insert = ifelse(type == 'start', sprintf('<span class="%s">', class), "</span>")
  45. ) %>%
  46. group_by(loc, type) %>%
  47. summarize(insert = paste(insert, collapse = ''))
  48. # inserts now gives html (span open and close) to insert and loc
  49. # first split text at inserts$loc locations,
  50. # then recombine by zipping with inserts$insert text
  51. # start at 0, unless there's a hit on first character
  52. # end at nchar(text) + 1 because window is idx[k] to idx[k+1]-1
  53. idx_split <- c(0 - (inserts$loc[1] == 0), inserts$loc)
  54. if (!(nchar(text) + 1) %in% idx_split)
  55. idx_split <- c(idx_split, nchar(text) + 1)
  56. text_split <- c()
  57. for (k in seq_along(idx_split[-1])) {
  58. text_split <- c(text_split, substr(text, idx_split[k], idx_split[k+1] - 1))
  59. }
  60. out <- c()
  61. for (j in seq_along(text_split)) {
  62. out <- c(
  63. out,
  64. ifelse(escape, escape_html(text_split[j]), text_split[j]),
  65. if (!is.na(inserts$insert[j])) inserts$insert[j]
  66. )
  67. }
  68. paste(out, collapse = '')
  69. }
  70. wrap_regex <- function(pattern, escape = TRUE, exact = TRUE) {
  71. stopifnot(length(pattern) == 1)
  72. if(escape) pattern <- escape_html(pattern)
  73. r_open_parens <- "(?<![\\\\])\\("
  74. x <- strsplit(pattern, r_open_parens, perl = TRUE)[[1]]
  75. first <- x[1]
  76. x <- x[-1]
  77. x <- paste0(
  78. '<span class="g', sprintf("%02d", seq_along(x)), '">(',
  79. x,
  80. collapse = ""
  81. )
  82. x <- gsub("(?<![\\\\])\\)", ")</span>", x, perl = TRUE)
  83. if (exact) x <- gsub("\\\\", "\\\\\\\\", x)
  84. paste0(first, x)
  85. }
  86. #' View grouped regex results
  87. #'
  88. #' @param text Text to search
  89. #' @param pattern Regex pattern to look for
  90. #' @param render Render results to an HTML doc and open in RStudio viewer?
  91. #' @param escape Escape HTML-related characters in `text`?
  92. #' @param knitr Print into knitr doc? If `TRUE`, marks text as `asis_output` and
  93. #' sets `render = FALSE` and `escape = TRUE`.
  94. #' @param exact Should regex be displayed as entered by the user into R console
  95. #' or source (default)? When `TRUE`, regex is displayed with the double `\\`
  96. #' required for escaping backslashes in R. When `FALSE`, regex is displayed
  97. #' as interpreted by the regex engine (i.e. double `\\` as a single `\`).
  98. #' @param ... Passed to [run_regex]
  99. #' @export
  100. view_regex <- function(
  101. text,
  102. pattern,
  103. ...,
  104. render = TRUE,
  105. escape = render,
  106. knitr = FALSE,
  107. exact = escape
  108. ) {
  109. if (knitr) {
  110. render <- FALSE
  111. escape <- TRUE
  112. }
  113. res <- run_regex(text, pattern, ...)
  114. res <- purrr::map_chr(res, wrap_result, escape = escape)
  115. res <- paste("<p class='results'>", res, "</p>")
  116. if (knitr) return(knitr::asis_output(res))
  117. if (!render) return(res)
  118. head <- c(
  119. "---", "pagetitle: View Regex", "---",
  120. "<h5>Regex</h5>",
  121. "<p><pre style = 'font-size: 1em;'>", wrap_regex(pattern, escape, exact), "</pre></p>",
  122. "<h5>Results</h5>"
  123. )
  124. res <- c(head, res)
  125. tmp <- tempfile(fileext = ".Rmd")
  126. cat(res, file = tmp, sep = "\n")
  127. tmp_html <- suppressWarnings(
  128. rmarkdown::render(
  129. tmp,
  130. output_format = rmarkdown::html_document(css = system.file('style.css', package='regexhelp')),
  131. quiet = TRUE
  132. ))
  133. rstudioapi::viewer(tmp_html)
  134. }