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

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