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

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