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

281 line
9.8KB

  1. #' Extract matched groups from regexp
  2. #'
  3. #' @param text Text to search
  4. #' @param pattern regexp
  5. #' @param global If `TRUE`, enables global pattern matching
  6. #' @inheritDotParams base::regexec ignore.case perl fixed useBytes
  7. run_regex <- function(
  8. text,
  9. pattern,
  10. ignore.case = FALSE,
  11. perl = FALSE,
  12. fixed = FALSE,
  13. useBytes = FALSE,
  14. global = TRUE
  15. ) {
  16. # Use regex to get matches by group, gives start index and length
  17. m <- regexec(pattern, text, ignore.case, perl, fixed, useBytes)
  18. m <- purrr::map2(text, m, ~ list(text = .x, idx = expand_matches(.y)))
  19. attr(m, "global") <- global
  20. if (!global) return(m)
  21. mmi <- max_match_index(m)
  22. if (any(!is.na(mmi))) {
  23. subtext <- purrr::map_chr(m, "text") %>% purrr::map2_chr(mmi, substring)
  24. subtext[is.na(subtext)] <- ""
  25. m2 <- run_regex(subtext, pattern, ignore.case, perl, fixed, useBytes)
  26. for (i in seq_along(m2)) {
  27. if (is.null(m2[[i]]$idx[[1]])) next
  28. m2[[i]]$idx[, c(1, 2)] <- m2[[i]]$idx[, c(1, 2)] + mmi[i] - 1L
  29. m[[i]]$idx <- rbind(m[[i]]$idx, m2[[i]]$idx)
  30. }
  31. }
  32. m
  33. }
  34. expand_matches <- function(m) {
  35. if (m[1] == -1) return(list(NULL))
  36. m_length <- attr(m, "match.length")
  37. x <- purrr::map2(m, m_length, ~ c(.x, .x + .y))
  38. x <- as.data.frame(do.call(rbind, x))
  39. names(x) <- c("start", "end")
  40. x$start <- ifelse(x$start == 0L, NA_integer_, x$start)
  41. x$end <- ifelse(x$end == 0L, NA_integer_, x$end)
  42. x$group <- 1:nrow(x) - 1L
  43. x
  44. }
  45. max_match_index <- function(m) {
  46. max_na <- function(x) if (is.null(x)) NA else max(x, na.rm = TRUE)
  47. max_int <- function(x) as.integer(max(x))
  48. purrr::map(m, "idx") %>%
  49. purrr::modify_depth(1, ~c(start = max_na(.x$start), end = max_na(.x$end))) %>%
  50. purrr::map_int(max_int)
  51. }
  52. #' Wrap matches in HTML span tags to colorize via CSS
  53. #'
  54. #' @param x Individual list item in list returned by [run_regex()]
  55. #' @inheritParams view_regex
  56. #' @keywords internal
  57. wrap_result <- function(x, escape = FALSE, exact = FALSE) {
  58. if (is.null(x$idx[[1]])) return(if (escape) escape_html(x$text) else x$text)
  59. text <- x$text
  60. inserts <- x$idx
  61. inserts$class <- sprintf("group g%02d", inserts$group)
  62. inserts$pad <- 0L
  63. names(inserts)[which(names(inserts) == "group")] <- "i"
  64. for (j in seq_len(nrow(inserts))) {
  65. if (inserts$i[j] == 0) next
  66. if (is.na(inserts$start[j]) || is.na(inserts$end[j])) next
  67. overlap <- filter(
  68. inserts[1:(j-1), ],
  69. .data$i != 0,
  70. .data$start <= !!inserts$start[j] & .data$end >= !!inserts$end[j])
  71. inserts[j, 'pad'] <- inserts$pad[j] + nrow(overlap)
  72. }
  73. inserts <- inserts %>%
  74. tidyr::gather(type, loc, start:end) %>%
  75. filter(!is.na(.data$loc)) %>%
  76. dplyr::arrange(loc, class, dplyr::desc(type)) %>%
  77. mutate(
  78. class = ifelse(.data$pad > 0, sprintf("%s pad%02d", .data$class, .data$pad), .data$class),
  79. insert = ifelse(.data$type == 'start', sprintf('<span class="%s">', .data$class), "</span>")
  80. )
  81. inserts_g0 <- filter(inserts, class == "group g00")
  82. inserts_other <- filter(inserts, class != "group g00")
  83. inserts <- dplyr::bind_rows(
  84. filter(inserts_g0, type == "start"),
  85. inserts_other,
  86. filter(inserts_g0, type == "end")
  87. ) %>%
  88. mutate(type = sprintf("%05d%s", 1:nrow(.), type)) %>%
  89. group_by(.data$loc, .data$type) %>%
  90. summarize(insert = paste(.data$insert, collapse = '')) %>%
  91. dplyr::ungroup() %>%
  92. mutate(type = sub("^\\d{5}", "", type))
  93. # inserts now gives html (span open and close) to insert and loc
  94. # first split text at inserts$loc locations,
  95. # then recombine by zipping with inserts$insert text
  96. # start at 0, unless there's a hit on first character
  97. # end at nchar(text) + 1 because window is idx[k] to idx[k+1]-1
  98. idx_split <- c(0 - (inserts$loc[1] == 0), inserts$loc)
  99. if (!(nchar(text) + 1) %in% idx_split)
  100. idx_split <- c(idx_split, nchar(text) + 1)
  101. text_split <- c()
  102. for (k in seq_along(idx_split[-1])) {
  103. text_split <- c(text_split, substr(text, idx_split[k], idx_split[k+1] - 1))
  104. }
  105. out <- c()
  106. for (j in seq_along(text_split)) {
  107. out <- c(
  108. out,
  109. ifelse(escape, escape_html(text_split[j]), text_split[j]),
  110. if (!is.na(inserts$insert[j])) inserts$insert[j]
  111. )
  112. }
  113. if (exact) out <- escape_backslash(out)
  114. paste(out, collapse = '')
  115. }
  116. #' Wraps capture groups in regex pattern in span tags to colorize with CSS
  117. #'
  118. #' @inheritParams view_regex
  119. #' @keywords internal
  120. wrap_regex <- function(pattern, escape = TRUE, exact = TRUE) {
  121. stopifnot(length(pattern) == 1)
  122. if (escape) pattern <- escape_html(pattern)
  123. # 1. walk characters in pattern
  124. # 2. if current is open parens
  125. # 1. walk backwards, counting number of "\\" until first non-"\\" char
  126. # 2. If odd, then not an opening group
  127. # 3. Look forward, if followed by "?" then not a capturing group
  128. # 4. If capturing group then add opening "<span...>(" to out and
  129. # add TRUE for valid capture group to parens stack
  130. # 5. If non-capturing group, add "(" to out and FALSE for non-valid to paren stack
  131. # 3. if close parens, add closing "</span>" to out
  132. out <- c()
  133. paren_stack <- c()
  134. group <- 0
  135. pattern_chars <- strsplit(pattern, "")[[1]]
  136. for (i in seq_along(pattern_chars)) {
  137. is_capture_group <- FALSE
  138. if (pattern_chars[i] == "(") {
  139. backslash_count <- 0
  140. if (i != 1) {
  141. j <- i-1
  142. while (pattern_chars[j] == "\\" && j > 0) {
  143. backslash_count <- backslash_count + 1
  144. j <- j - 1
  145. }
  146. }
  147. if (backslash_count %% 2 == 0) {
  148. if (i != length(pattern_chars) && pattern_chars[i + 1] != "?") {
  149. is_capture_group <- TRUE
  150. }
  151. }
  152. if (is_capture_group) {
  153. group <- group + 1
  154. paren_stack <- c(TRUE, paren_stack) #push
  155. out <- c(out, paste0('<span class="g', sprintf("%02d", group), '">('))
  156. } else {
  157. paren_stack <- c(FALSE, paren_stack) #push
  158. out <- c(out, "(")
  159. }
  160. } else if (pattern_chars[i] == ")") {
  161. closes_capture_group <- paren_stack[1]
  162. paren_stack <- paren_stack[-1] #pop
  163. if (closes_capture_group) {
  164. out <- c(out, ")</span>")
  165. } else {
  166. out <- c(out, ")")
  167. }
  168. } else {
  169. out <- c(out, pattern_chars[i])
  170. }
  171. }
  172. if (exact) out <- escape_backslash(out)
  173. paste(out, collapse = "")
  174. }
  175. #' View grouped regex results
  176. #'
  177. #' View the result of the regular expression when applied to the given text.
  178. #' The default behavior renders the result as HTML and opens the file in
  179. #' the RStudio viewer pane. If `render` is `FALSE`, the HTML itself is returned.
  180. #' If the output is destined for a [knitr] document, set `knitr` to `TRUE`.
  181. #'
  182. #' @examples
  183. #' view_regex("example", "amp", render=FALSE)
  184. #'
  185. #' @param text Text to search
  186. #' @param pattern Regex pattern to look for
  187. #' @param render Render results to an HTML doc and open in RStudio viewer?
  188. #' @param escape Escape HTML-related characters in `text`?
  189. #' @param exact Should the regex pattern be displayed as entered by the user
  190. #' into R console or source (default)? When `TRUE`, regex is displayed with
  191. #' the double `\\\\` required for escaping backslashes in R. When `FALSE`,
  192. #' regex is displayed as interpreted by the regex engine (i.e. double `\\\\`
  193. #' as a single `\\`).
  194. #' @param result_only Should only the result be displayed? If `FALSE`, then
  195. #' the colorized regular expression is also displayed in the output.
  196. #' @inheritDotParams base::regexec ignore.case perl fixed useBytes
  197. #' @export
  198. view_regex <- function(
  199. text,
  200. pattern,
  201. ...,
  202. render = TRUE,
  203. escape = render,
  204. exact = escape,
  205. result_only = FALSE
  206. ) {
  207. knitr <- isTRUE(getOption('knitr.in.progress'))
  208. if (knitr) {
  209. render <- FALSE
  210. escape <- TRUE
  211. }
  212. regex_opts <- deprecate_knitr_option(...)
  213. regex_opts$text <- text
  214. regex_opts$pattern <- pattern
  215. res <- do.call(run_regex, regex_opts)
  216. res <- purrr::map_chr(res, wrap_result, escape = escape, exact = exact)
  217. res <- purrr::map_chr(res, function(resi) {
  218. result_pad <- ""
  219. if (grepl("pad\\d{2}", resi)) {
  220. max_pad <- max(stringr::str_extract_all(resi, "pad\\d{2}")[[1]])
  221. max_pad_level <- as.integer(stringr::str_extract(max_pad, "\\d{2}"))
  222. if (max_pad_level - 3 > 0) {
  223. result_pad <- sprintf("pad%02d", max_pad_level - 3)
  224. }
  225. }
  226. paste("<p class='results", result_pad, "'>", resi, "</p>")
  227. })
  228. res <- paste(res, collapse = "")
  229. if (!nchar(pattern)) res <- paste("<p class='results'>", text, "</p>")
  230. if (knitr) {
  231. # embed css
  232. group_css <- htmltools::htmlDependency(
  233. name = "regexplain-groups", version = packageVersion("regexplain"),
  234. src = system.file("styles", package = "regexplain"),
  235. stylesheet = "groups.css")
  236. res <- htmltools::attachDependencies(htmltools::HTML(res), group_css)
  237. return(res)
  238. }
  239. if (!render) return(res)
  240. head <- if (!result_only) c(
  241. "---", "pagetitle: View Regex", "---",
  242. "<h5>Pattern</h5>",
  243. "<p><pre>", wrap_regex(pattern, escape, exact), "</pre></p>",
  244. "<h5>Matches</h5>"
  245. )
  246. res <- c(head, res)
  247. tmp <- tempfile(fileext = ".Rmd")
  248. cat(res, file = tmp, sep = "\n")
  249. tmp_html <- suppressWarnings(
  250. rmarkdown::render(
  251. tmp,
  252. output_format = rmarkdown::html_document(css = c(system.file("styles", 'skeleton.css', package='regexplain'),
  253. system.file("styles", 'view_regex.css', package='regexplain'),
  254. system.file("styles", 'groups.css', package='regexplain')),
  255. theme = NULL,
  256. md_extensions = "-autolink_bare_uris"),
  257. quiet = TRUE
  258. ))
  259. rstudioapi::viewer(tmp_html)
  260. }
  261. deprecate_knitr_option <- function(...) {
  262. regex_opts <- list(...)
  263. if ("knitr" %in% names(regex_opts)) {
  264. warning("The `knitr` parameter of `view_regex()` has been removed. Running `view_regex()` in R Markdown is automatically detected.")
  265. }
  266. regex_opts[setdiff(names(regex_opts), "knitr")]
  267. }