🔍 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.

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