🔍 An RStudio addin slash regex utility belt
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

426 lines
13KB

  1. #' regexplain gadget
  2. #'
  3. #' @import miniUI
  4. #' @import shiny
  5. #' @param text Text to explore in gadget (editable using interface)
  6. #' @param start_page Open gadget to this tab, one of `"Text"`, `"RegEx"`,
  7. #' `"Output"`, or `"Help"`
  8. #' @export
  9. regex_gadget <- function(text = NULL,
  10. start_page = if (is.null(text)) "Text" else "RegEx") {
  11. stopifnot(requireNamespace("miniUI"), requireNamespace("shiny"))
  12. update_available <- check_version()
  13. # ---- UI ----
  14. ui <- miniPage(
  15. shiny::includeCSS(system.file("styles", "style.css", package = "regexplain")),
  16. shiny::includeCSS(system.file("styles", "gadget.css", package = "regexplain")),
  17. gadgetTitleBar(
  18. "regexplain",
  19. right = miniTitleBarButton("done", "Send RegEx To Console", TRUE)
  20. ),
  21. miniTabstripPanel(
  22. selected = match.arg(start_page, c("Text", "RegEx", "Output", "Help")),
  23. # --- UI - Tab - Text ----
  24. miniTabPanel(
  25. "Text", icon = icon('file-text-o'),
  26. miniContentPanel(
  27. fillCol(
  28. textAreaInputAlt('text',
  29. label = "Text to search or parse",
  30. value = paste(text, collapse = "\n"),
  31. resize = "both",
  32. width = "100%",
  33. height="90%",
  34. placeholder = "Paste, enter, or edit your sample text here.")
  35. )
  36. )
  37. ),
  38. # ---- UI - Tab - Regex ----
  39. miniTabPanel(
  40. "RegEx", icon = icon('terminal'),
  41. miniContentPanel(
  42. fillCol(
  43. flex = c(1, 3),
  44. fillCol(
  45. flex = c(1, 1),
  46. textInputCode('pattern', 'RegEx', width = "100%",
  47. placeholder = "Standard RegEx, e.g. \\w+_\\d{2,4}\\s+"),
  48. checkboxGroupInput(
  49. 'regex_options',
  50. label = HTML(
  51. '<div style="font-size: 1.25rem;">',
  52. 'Option Groups: ',
  53. '<span style="color: #337ab7;">regexplain</span>,',
  54. '<span style="color: #5cb85c;">all</span>, ',
  55. '<span style="color: #f0ad4e;">base only</span>',
  56. '</div>'
  57. ),
  58. inline = TRUE,
  59. width = "90%",
  60. choiceValues = list(
  61. "text_break_lines",
  62. "ignore.case",
  63. "fixed",
  64. "perl",
  65. "useBytes"),
  66. choiceNames = list(
  67. HTML('<span style="color: #337ab7;">Break Lines</span>'),
  68. HTML('<span style="color: #5cb85c;">Ignore Case</span>'),
  69. HTML('<span style="color: #5cb85c;">Fixed/Literal</span>'),
  70. HTML('<span style="color: #f0ad4e;">Perl Style</span>'),
  71. HTML('<span style="color: #f0ad4e;">Use Bytes</span>')),
  72. selected = c('text_break_lines')
  73. )
  74. ),
  75. tags$div(
  76. class = "gadget-result",
  77. style = "overflow-y: scroll; height: 100%;",
  78. htmlOutput('result')
  79. )
  80. )
  81. )
  82. ),
  83. # ---- UI - Tab - Output ----
  84. miniTabPanel(
  85. "Output", icon = icon("table"),
  86. miniContentPanel(
  87. fillCol(
  88. flex = c(1, 3),
  89. inputPanel(
  90. tags$div(
  91. width = "100%;",
  92. selectInput('regexFn', label = 'Apply Function',
  93. choices = regexFn_choices),
  94. tags$span(class = "help-block",
  95. style = "font-size:1.25rem; margin-top:-10px; margin-bottom:0px; margin-left:4px;",
  96. "Adjust options in RegEx tab")
  97. ),
  98. uiOutput("output_sub")
  99. ),
  100. # verbatimTextOutput('output_result', placeholder = TRUE)
  101. tags$pre(
  102. id = "output_result",
  103. class = "shiny-text-output",
  104. style = "overflow-y: scroll; height: 100%;"
  105. )
  106. )
  107. )
  108. ),
  109. # ---- UI - Tab - Help ----
  110. miniTabPanel(
  111. "Help", icon = icon("support"),
  112. help_ui("help")
  113. )
  114. )
  115. )
  116. # ---- Server ----
  117. server <- function(input, output, session) {
  118. if (!is.null(update_available)) {
  119. showModal(
  120. modalDialog(
  121. title = "Update Available \U1F389",
  122. easyClose = TRUE,
  123. footer = modalButton("OK"),
  124. tagList(
  125. tags$p(
  126. "Version", update_available$version, "is",
  127. tags$a(href = update_available$link,
  128. "available on GitHub.")
  129. ),
  130. if ("devtools" %in% installed.packages()) tags$p(
  131. "The fastest way to update is with devtools:",
  132. tags$pre(
  133. "devtools::update_packages(\"gadenbuie/regexplain\")"
  134. )
  135. ),
  136. tags$p(
  137. class = 'help-block',
  138. "This message won't be shown again during this R session."
  139. )
  140. )
  141. )
  142. )
  143. }
  144. # ---- Server - Global ----
  145. rtext <- reactive({
  146. x <- if ('text_break_lines' %in% input$regex_options) {
  147. strsplit(input$text, "\n")[[1]]
  148. } else input$text
  149. x
  150. })
  151. pattern <- reactive({
  152. sanitize_text_input(input$pattern)
  153. })
  154. alert_result <- function(msg, type = "danger") {
  155. msg <- gsub("\n", "<br>", msg)
  156. msg <- gsub("\t", "&nbsp;&nbsp;", msg)
  157. paste0("<pre class='alert alert-", type, "' ",
  158. "style='padding: 4px; margin-top: 1px; margin-bottom: 4px;'>",
  159. paste(msg, collapse = "<br>"),
  160. "</pre>")
  161. }
  162. # ---- Server - Tab - Regex ----
  163. output$result <- renderUI({
  164. if (is.null(rtext())) return(NULL)
  165. if (pattern() == "") {
  166. return(toHTML(paste('<p class="results">', escape_html(rtext()), "</p>", collapse = "")))
  167. }
  168. res <- NULL
  169. error_message <- NULL
  170. warning_message <- NULL
  171. tryCatch({
  172. res <- paste(
  173. view_regex(
  174. rtext(),
  175. pattern(),
  176. ignore.case = 'ignore.case' %in% input$regex_options,
  177. perl = 'perl' %in% input$regex_options,
  178. fixed = 'fixed' %in% input$regex_options,
  179. useBytes = 'useBytes' %in% input$regex_options,
  180. # invert = 'invert' %in% input$regex_options,
  181. render = FALSE,
  182. escape = TRUE,
  183. exact = FALSE),
  184. collapse = ""
  185. )
  186. },
  187. error = function(e) {
  188. error_message <<- alert_result(e$message, "danger")
  189. },
  190. warning = function(w) {
  191. warning_message <<- alert_result(w$message, "warning")
  192. })
  193. if (is.null(res)) res <- toHTML(
  194. paste('<p class="results">', escape_html(rtext()), "</p>", collapse = "")
  195. )
  196. toHTML(paste(error_message, warning_message, res))
  197. })
  198. # ---- Server - Tab - Output ----
  199. regexFn_replacement_val <- NULL
  200. output$output_sub <- renderUI({
  201. req(input$regexFn)
  202. if (!input$regexFn %in% regexFn_substitute) return(NULL)
  203. textInputCode('regexFn_replacement', 'Subsitution',
  204. value = regexFn_replacement_val,
  205. placeholder = "Replacement Text")
  206. })
  207. replacement <- reactive({
  208. req(input$regexFn)
  209. if (!input$regexFn %in% regexFn_substitute) {
  210. NULL
  211. } else {
  212. regexFn_replacement_val <<- input$regexFn_replacement
  213. sanitize_text_input(input$regexFn_replacement)
  214. }
  215. })
  216. output$output_result <- renderPrint({
  217. req(input$regexFn)
  218. regexPkg <- get_pkg_namespace(input$regexFn)
  219. if (!requireNamespace(regexPkg, quietly = TRUE)) {
  220. return(cat(
  221. paste0(
  222. "The package `", regexPkg, "` is not installed.\n",
  223. "To preview results from this package, please run\n\n",
  224. " install.packages(\"", regexPkg, "\")"
  225. )
  226. ))
  227. }
  228. regexFn <- getFromNamespace(input$regexFn, regexPkg)
  229. req_sub_arg <- input$regexFn %in% regexFn_substitute
  230. x <- if (regexPkg == "base") {
  231. if (req_sub_arg) {
  232. req(replacement())
  233. regexFn(pattern(), replacement(), rtext(),
  234. ignore.case = 'ignore.case' %in% input$regex_options,
  235. perl = 'perl' %in% input$regex_options,
  236. fixed = 'fixed' %in% input$regex_options,
  237. useBytes = 'useBytes' %in% input$regex_options)
  238. } else {
  239. regexFn(pattern(), rtext(),
  240. ignore.case = 'ignore.case' %in% input$regex_options,
  241. perl = 'perl' %in% input$regex_options,
  242. fixed = 'fixed' %in% input$regex_options,
  243. useBytes = 'useBytes' %in% input$regex_options)
  244. }
  245. } else if (regexPkg == "stringr") {
  246. if (req_sub_arg) {
  247. req(replacement())
  248. regexFn(
  249. rtext(),
  250. stringr::regex(
  251. pattern(),
  252. ignore_case = 'ignore.case' %in% input$regex_options,
  253. literal = 'fixed' %in% input$regex_options
  254. ),
  255. replacement()
  256. )
  257. } else {
  258. regexFn(
  259. rtext(),
  260. stringr::regex(
  261. pattern(),
  262. ignore_case = 'ignore.case' %in% input$regex_options,
  263. literal = 'fixed' %in% input$regex_options
  264. )
  265. )
  266. }
  267. } else if (regexPkg == "rematch2") {
  268. regexFn(rtext(), pattern(),
  269. ignore.case = 'ignore.case' %in% input$regex_options,
  270. perl = 'perl' %in% input$regex_options,
  271. fixed = 'fixed' %in% input$regex_options,
  272. useBytes = 'useBytes' %in% input$regex_options)
  273. } else {
  274. "Um. Not sure how I got here."
  275. }
  276. print(x)
  277. })
  278. # ---- Server - Tab - Help ----
  279. help_text <- callModule(help_server, "help")
  280. # ---- Server - Tab - Exit ----
  281. observeEvent(input$done, {
  282. if (pattern() != "") {
  283. pattern <- paste0('pattern <- "', escape_backslash(pattern()), '"')
  284. if ("regexFn_replacement" %in% names(input) && replacement() != "") {
  285. pattern <- paste0(
  286. pattern, "\n",
  287. 'replacement <- "', escape_backslash(replacement()), '"'
  288. )
  289. }
  290. rstudioapi::sendToConsole(pattern, FALSE)
  291. }
  292. stopApp()
  293. })
  294. observeEvent(input$cancel, {
  295. stopApp()
  296. })
  297. }
  298. viewer <- shiny::paneViewer(minHeight = 1000)
  299. runGadget(ui, server, viewer = viewer)
  300. }
  301. # ---- Gadget Helper Functions and Variables ----
  302. sanitize_text_input <- function(x) {
  303. if (is.null(x) || !nchar(x)) return(x)
  304. if (grepl("\\u[0-9a-f]{4,8}|\\x[0-9a-f]{2}|\\x\\{[0-9a-f]{1,6}\\}|\\N|\\0[0-8]{1,3}", x)) {
  305. try({
  306. y <- stringi::stri_unescape_unicode(x)
  307. }, silent = TRUE)
  308. if (!is.na(y)) x <- y
  309. }
  310. # x <- gsub("\u201C|\u201D", '"', x)
  311. # x <- gsub("\u2018|\u2019", "'", x)
  312. x
  313. }
  314. toHTML <- function(...) {
  315. x <- paste(..., collapse = "")
  316. x <- gsub("\n", "\\\\n", x)
  317. x <- gsub("\t", "\\\\t", x)
  318. x <- gsub("\r", "\\\\r", x)
  319. HTML(x)
  320. }
  321. regexFn_choices <- list(
  322. "Choose a function" = "",
  323. base = c(
  324. "grep",
  325. "grepl",
  326. "sub", #<<
  327. "gsub", #<<
  328. "regexpr",
  329. "gregexpr",
  330. "regexec"
  331. ),
  332. stringr = c(
  333. "str_detect",
  334. "str_locate",
  335. "str_locate_all",
  336. "str_extract",
  337. "str_extract_all",
  338. "str_match",
  339. "str_match_all",
  340. "str_replace", #<<
  341. "str_replace_all", #<<
  342. "str_split"
  343. ),
  344. "rematch2" = c(
  345. "re_match",
  346. "re_match_all",
  347. "re_exec",
  348. "re_exec_all"
  349. )
  350. )
  351. regexFn_substitute <- c(
  352. paste0(c("", "g"), "sub"),
  353. paste0("str_replace", c("", "_all"))
  354. )
  355. get_pkg_namespace <- function(fn) {
  356. x <- names(purrr::keep(regexFn_choices, ~ (fn %in% .)))
  357. if (length(x) > 1) warning(fn, " matches multiple functions in regexFn_choices, please review.")
  358. x
  359. }
  360. #' Check if an updated version is available
  361. #'
  362. #' I included this because it can be difficult to tell if your RStudio Addins
  363. #' are up to date. I may add new features that you want but you won't hear about
  364. #' the updates. This function checks if an update is available, using GitHub
  365. #' tags. If an update is available, a modal dialog is shown when you start
  366. #' the regexplain gadget. This only happens once per R session, though, so feel
  367. #' free to ignore the message.
  368. #'
  369. #' @param gh_user GitHub user account
  370. #' @param gh_repo GitHub repo name
  371. #' @param this_version The currently installed version of the package
  372. #' @keywords internal
  373. check_version <- function(
  374. gh_user = "gadenbuie",
  375. gh_repo = "regexplain",
  376. this_version = packageVersion('regexplain')
  377. ) {
  378. ok_to_check <- getOption("regexplain.no.check.version", TRUE)
  379. if (!ok_to_check) return(NULL)
  380. if (!requireNamespace('jsonlite', quietly = TRUE)) return(NULL)
  381. get_json <- purrr::possibly(jsonlite::fromJSON, NULL)
  382. gh_tags <- get_json(
  383. paste0("https://api.github.com/repos/", gh_user, "/", gh_repo, "/git/refs/tags"),
  384. simplifyDataFrame = TRUE
  385. )
  386. if (!is.null(gh_tags)) {
  387. gh_tags$tag <- sub("refs/tags/", "", gh_tags$ref, fixed = TRUE)
  388. gh_tags$version <- sub("^v\\.?", "", gh_tags$tag)
  389. }
  390. if (!is.null(gh_tags) && any(gh_tags$version > this_version)) {
  391. max_version <- max(gh_tags$version)
  392. max_tag <- gh_tags$tag[gh_tags$version == max_version]
  393. options(regexplain.no.check.version = FALSE)
  394. return(
  395. list(
  396. version = max_version,
  397. link = paste("https://github.com", gh_user, gh_repo, "releases/tag", max_tag, sep = "/")
  398. )
  399. )
  400. } else return(NULL)
  401. }