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

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