🔍 An RStudio addin slash regex utility belt
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

298 lines
10KB

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