🔍 An RStudio addin slash regex utility belt
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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