🔍 An RStudio addin slash regex utility belt
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

823 lines
33KB

  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. fillRow(
  47. flex = c(5, 1),
  48. textInputCode('pattern', 'RegEx', width = "100%",
  49. placeholder = "Standard RegEx, e.g. \\w+_\\d{2,4}\\s+"),
  50. tags$div(style = "margin-top: 23px; margin-left:6px;",
  51. actionButton("show_templates", "Templates", class = "btn-success"))
  52. ),
  53. checkboxGroupInput(
  54. 'regex_options',
  55. label = HTML(
  56. '<div style="font-size: 1.25rem;">',
  57. 'Option Groups: ',
  58. '<span style="color: #337ab7;">RegExplain</span>,',
  59. '<span style="color: #5cb85c;">All</span>, ',
  60. '<span style="color: #f0ad4e;">Base only</span>',
  61. '</div>'
  62. ),
  63. inline = TRUE,
  64. width = "90%",
  65. choiceValues = list(
  66. "text_break_lines",
  67. "ignore.case",
  68. "fixed",
  69. "perl",
  70. "useBytes"),
  71. choiceNames = list(
  72. HTML('<span style="color: #337ab7;">Break Lines</span>'),
  73. HTML('<span style="color: #5cb85c;">Ignore Case</span>'),
  74. HTML('<span style="color: #5cb85c;">Fixed/Literal</span>'),
  75. HTML('<span style="color: #f0ad4e;">Perl Style</span>'),
  76. HTML('<span style="color: #f0ad4e;">Use Bytes</span>')),
  77. selected = c('text_break_lines')
  78. )
  79. ),
  80. tags$div(
  81. class = "gadget-result",
  82. style = "overflow-y: scroll; height: 100%;",
  83. htmlOutput('result')
  84. )
  85. )
  86. )
  87. ),
  88. # ---- UI - Tab - Output ----
  89. miniTabPanel(
  90. "Output", icon = icon("table"),
  91. miniContentPanel(
  92. fillCol(
  93. flex = c(1, 3),
  94. inputPanel(
  95. tags$div(
  96. width = "100%;",
  97. selectInput('regexFn', label = 'Apply Function',
  98. choices = regexFn_choices),
  99. tags$span(class = "help-block",
  100. style = "font-size:1.25rem; margin-top:-10px; margin-bottom:0px; margin-left:4px;",
  101. "Adjust options in RegEx tab")
  102. ),
  103. uiOutput("output_sub")
  104. ),
  105. # verbatimTextOutput('output_result', placeholder = TRUE)
  106. tags$pre(
  107. id = "output_result",
  108. class = "shiny-text-output",
  109. style = "overflow-y: scroll; height: 100%;"
  110. )
  111. )
  112. )
  113. ),
  114. # ---- UI - Tab - Help ----
  115. miniTabPanel(
  116. "Help", icon = icon("support"),
  117. generate_help_ui(cheatsheet_only = FALSE)
  118. )
  119. )
  120. )
  121. # ---- Server ----
  122. server <- function(input, output, session) {
  123. if (!is.null(update_available)) {
  124. showModal(
  125. modalDialog(
  126. title = "Update Available \U1F389",
  127. easyClose = TRUE,
  128. footer = modalButton("OK"),
  129. tagList(
  130. tags$p(
  131. "Version", update_available$version, "is",
  132. tags$a(href = update_available$link,
  133. "available on GitHub.")
  134. ),
  135. if ("devtools" %in% installed.packages()) tags$p(
  136. "The fastest way to update is with devtools:",
  137. tags$pre(
  138. "devtools::update_packages(\"gadenbuie/regexplain\")"
  139. )
  140. ),
  141. tags$p(
  142. class = 'help-block',
  143. "This message won't be shown again during this R session."
  144. )
  145. )
  146. )
  147. )
  148. }
  149. # ---- Server - Global ----
  150. rtext <- reactive({
  151. x <- if ('text_break_lines' %in% input$regex_options) {
  152. strsplit(input$text, "\n")[[1]]
  153. } else input$text
  154. x
  155. })
  156. pattern <- reactive({
  157. sanitize_text_input(input$pattern)
  158. })
  159. alert_result <- function(msg, type = "danger") {
  160. msg <- gsub("\n", "<br>", msg)
  161. msg <- gsub("\t", "&nbsp;&nbsp;", msg)
  162. paste0("<pre class='alert alert-", type, "' ",
  163. "style='padding: 4px; margin-top: 1px; margin-bottom: 4px;'>",
  164. paste(msg, collapse = "<br>"),
  165. "</pre>")
  166. }
  167. # ---- Server - Tab - Regex ----
  168. output$result <- renderUI({
  169. if (is.null(rtext())) return(NULL)
  170. if (pattern() == "") {
  171. return(toHTML(paste('<p class="results">', escape_html(rtext()), "</p>", collapse = "")))
  172. }
  173. res <- NULL
  174. error_message <- NULL
  175. warning_message <- NULL
  176. tryCatch({
  177. res <- paste(
  178. view_regex(
  179. rtext(),
  180. pattern(),
  181. ignore.case = 'ignore.case' %in% input$regex_options,
  182. perl = 'perl' %in% input$regex_options,
  183. fixed = 'fixed' %in% input$regex_options,
  184. useBytes = 'useBytes' %in% input$regex_options,
  185. # invert = 'invert' %in% input$regex_options,
  186. render = FALSE,
  187. escape = TRUE,
  188. exact = FALSE),
  189. collapse = ""
  190. )
  191. },
  192. error = function(e) {
  193. error_message <<- alert_result(e$message, "danger")
  194. },
  195. warning = function(w) {
  196. warning_message <<- alert_result(w$message, "warning")
  197. })
  198. if (is.null(res)) res <- toHTML(
  199. paste('<p class="results">', escape_html(rtext()), "</p>", collapse = "")
  200. )
  201. toHTML(paste(error_message, warning_message, res))
  202. })
  203. # ---- Server - Tab - RegEx - Templates ----
  204. templates <- get_templates()
  205. this_template <- reactive({
  206. req(input$template)
  207. purrr::keep(templates, ~ .$name == input$template) %>%
  208. purrr::flatten()
  209. })
  210. observeEvent(input$show_templates, {
  211. showModal(
  212. modalDialog(
  213. title = "Templates",
  214. footer = tagList(
  215. modalButton("Cancel"),
  216. actionButton("apply_template", "Use Template", class = "btn-success")
  217. ),
  218. selectInput("template", "Template",
  219. choices = c("Choose template" = "",
  220. purrr::set_names(purrr::map_chr(templates, 'name')))),
  221. uiOutput("template_info")
  222. )
  223. )
  224. })
  225. output$template_info <- renderUI({
  226. req(this_template())
  227. tagList(
  228. tags$h5("Description"),
  229. tags$p(this_template()$description),
  230. tags$h5("Pattern"),
  231. tags$pre(
  232. tags$code(
  233. this_template()$regex
  234. )
  235. )
  236. )
  237. })
  238. observeEvent(input$apply_template, {
  239. updateTextInput(session, "pattern", value = this_template()$regex)
  240. updateSelectInput(session, "template", selected = "")
  241. removeModal()
  242. })
  243. # ---- Server - Tab - Output ----
  244. regexFn_replacement_val <- NULL
  245. output$output_sub <- renderUI({
  246. req(input$regexFn)
  247. if (!input$regexFn %in% regexFn_substitute) return(NULL)
  248. textInputCode('regexFn_replacement', 'Subsitution',
  249. value = regexFn_replacement_val,
  250. placeholder = "Replacement Text")
  251. })
  252. replacement <- reactive({
  253. req(input$regexFn)
  254. if (!input$regexFn %in% regexFn_substitute) {
  255. NULL
  256. } else {
  257. regexFn_replacement_val <<- input$regexFn_replacement
  258. sanitize_text_input(input$regexFn_replacement)
  259. }
  260. })
  261. output$output_result <- renderPrint({
  262. req(input$regexFn)
  263. regexPkg <- get_pkg_namespace(input$regexFn)
  264. if (!requireNamespace(regexPkg, quietly = TRUE)) {
  265. return(cat(
  266. paste0(
  267. "The package `", regexPkg, "` is not installed.\n",
  268. "To preview results from this package, please run\n\n",
  269. " install.packages(\"", regexPkg, "\")"
  270. )
  271. ))
  272. }
  273. regexFn <- getFromNamespace(input$regexFn, regexPkg)
  274. req_sub_arg <- input$regexFn %in% regexFn_substitute
  275. x <- if (regexPkg == "base") {
  276. if (req_sub_arg) {
  277. req(replacement())
  278. regexFn(pattern(), replacement(), rtext(),
  279. ignore.case = 'ignore.case' %in% input$regex_options,
  280. perl = 'perl' %in% input$regex_options,
  281. fixed = 'fixed' %in% input$regex_options,
  282. useBytes = 'useBytes' %in% input$regex_options)
  283. } else {
  284. regexFn(pattern(), rtext(),
  285. ignore.case = 'ignore.case' %in% input$regex_options,
  286. perl = 'perl' %in% input$regex_options,
  287. fixed = 'fixed' %in% input$regex_options,
  288. useBytes = 'useBytes' %in% input$regex_options)
  289. }
  290. } else if (regexPkg == "stringr") {
  291. if (req_sub_arg) {
  292. req(replacement())
  293. regexFn(
  294. rtext(),
  295. stringr::regex(
  296. pattern(),
  297. ignore_case = 'ignore.case' %in% input$regex_options,
  298. literal = 'fixed' %in% input$regex_options
  299. ),
  300. replacement()
  301. )
  302. } else {
  303. regexFn(
  304. rtext(),
  305. stringr::regex(
  306. pattern(),
  307. ignore_case = 'ignore.case' %in% input$regex_options,
  308. literal = 'fixed' %in% input$regex_options
  309. )
  310. )
  311. }
  312. } else if (regexPkg == "rematch2") {
  313. regexFn(rtext(), pattern(),
  314. ignore.case = 'ignore.case' %in% input$regex_options,
  315. perl = 'perl' %in% input$regex_options,
  316. fixed = 'fixed' %in% input$regex_options,
  317. useBytes = 'useBytes' %in% input$regex_options)
  318. } else {
  319. "Um. Not sure how I got here."
  320. }
  321. print(x)
  322. })
  323. # ---- Server - Tab - Help ----
  324. HELP_DEFAULT_TEXT <- c(
  325. "<h3>Welcome to RegExplain</h3>",
  326. "<p>If you’re new to regular expressions, one of the best places to start is <a href=\"http://stringr.tidyverse.org/articles/regular-expressions.html\">the regular expressions vignette</a> from <code>stringr</code>. The chapter on strings in <a href=\"http://r4ds.had.co.nz/strings.html\">R for Data Science</a> is also an excellent first resource.</p>",
  327. "<p><strong>Exploring or looking for a challenge?</strong> Click on <i>Try These Examples</i> to see what you can do with this addin.</p>",
  328. "<h4>Getting Started</h4>",
  329. "<ul>",
  330. "<li><p><i class=\"fa fa-file-text-o\"></i> Enter or edit the <strong>Text</strong> you want to search.</p></li>",
  331. "<li><p><i class=\"fa fa-terminal\"></i> Edit your <strong>RegEx</strong> and view matches in real time.</p></li>",
  332. "<li><p><i class=\"fa fa-table\"></i> Test the <strong>Output</strong> of your regular expression with common functions, including <i>search and replace</i> functions.</p></li>",
  333. "<li><p><i class=\"fa fa-support\"></i> Get <strong>Help</strong> and look up the regular expression syntax.</p></li>",
  334. "</ul>",
  335. "<h4>Escaping characters</h4>",
  336. "<p>In order to store a backslash (<code>\\</code>) as a character in R, backslashes need to be escaped…with another backslash! To write a literal <code>\\</code> in an R character string, you need to actually store <code>&quot;\\\\&quot;</code>.</p>",
  337. "<p>In regular expressions, <code>\\w</code> stands for any alphabetical character, but to store it in a string in R you need <code>&quot;\\w&quot;</code>.</p>",
  338. "<p>Inside <strong>RegExplain</strong>, however, standard regular expressions can be used so that you can easily copy patterns from other places. When you click on the <span class=\"btn btn-xs btn-primary\">Send RegEX to Console</span> button, the necessary extra <code>\\</code> will be included.</p>",
  339. "<p>An extra backslash is still needed to match a literal <code>\\</code> in standard regular expressions. This means that you will need to enter <code>\\\\</code> in the <strong>RegEx</strong> tab, and the output to R will be <code>&quot;\\\\\\\\&quot;</code>.</p>"
  340. )
  341. source(system.file("shiny", "help_server.R", package = "regexplain"), local = TRUE)
  342. observeEvent(input$help_resources, {
  343. tagList(
  344. tags$h3("Resources"),
  345. tags$p("There are lots of great resources available for learning and working with regular expressions."),
  346. tags$h4("Regular Expressions in R"),
  347. tags$ul(
  348. tags$li(tags$p("The", tags$a(href = "http://stringr.tidyverse.org/articles/regular-expressions.html", "Regular Expressions vignette"),
  349. "from", tags$code("stringr"), "is an excellent first introduction to regular expressions in R.")),
  350. tags$li(tags$p("The", tags$a(href = "http://r4ds.had.co.nz/strings.html", "chapter on strings"),
  351. "in", tags$a(href = "http://r4ds.had.co.nz/", "R for Data Science"),
  352. "is also a great overall introduction.")),
  353. tags$li(tags$p("RStudio's",
  354. tags$a(href = "https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf", "RegEx CheatSheet"),
  355. "is a good pocket reference.")),
  356. tags$li(tags$p("Or try the", tags$strong("Regexplain Cheatsheet"), "addin installed with this package."))
  357. ),
  358. tags$h4("Online Resources"),
  359. tags$ul(
  360. tags$li(tags$a(href = "https://github.com/aloisdg/awesome-regex", "Awesome RegEx")),
  361. tags$li(tags$a(href = "https://www.regular-expressions.info", "Regular-Expressions.info")),
  362. tags$li(tags$a(href = "https://projects.lukehaas.me/regexhub", "Regex Hub"), "- common regex patterns"),
  363. tags$li(tags$a(href = "http://regexlib.com/DisplayPatterns.aspx", "RegExLib.com"), "- large collection of searchable patterns")
  364. ),
  365. tags$h4("Live Preview and Explanations"),
  366. tags$ul(
  367. tags$li(tags$a(href = "https://regexr.com", "https://regexr.com")),
  368. tags$li(tags$a(href = "https://debuggex.com", "https://debuggex.com")),
  369. tags$li(tags$a(href = "https://regex101.com", "https://regex101.com")),
  370. tags$li(tags$a(href = "http://www.mactechnologies.com/index.php?page=downloads#regexrx", "RegexRx"), "(app)"),
  371. tags$li(tags$a(href = "https://www.regexbuddy.com/", "Regex Buddy"), "(paid app)")
  372. ),
  373. tags$h4("Regex and String R Packages"),
  374. tags$dl(
  375. tags$dt(tags$a(href = "https://stringr.tidyverse.org/", "stringr")),
  376. tags$dd("A cohesive set of functions designed to make working with strings as easy as possible"),
  377. tags$dt(tags$a(href = "http://www.gagolewski.com/software/stringi/", "stringi")),
  378. tags$dd("THE R package for very fast, correct, consistent, and convenient string/text processing"),
  379. tags$dt(tags$a(href = "https://github.com/trinker/regexr", "regexr")),
  380. tags$dd("An R framework for constructing and managing human readable regular expressions"),
  381. tags$dt(tags$a(href = "https://github.com/kevinushey/rex", "rex")),
  382. tags$dd("Friendly Regular Expressions: complex regular expressions from human readable expressions"),
  383. tags$dt(tags$a(href = "https://github.com/richierocks/rebus", "rebus")),
  384. tags$dd("Build regular expressions in a human readable way"),
  385. tags$dt(tags$a(href = "https://github.com/AdamSpannbauer/r_regex_tester_app", "R Regex Tester")),
  386. tags$dd("A Shiny app for testing regular expressions")
  387. )
  388. ) %>%
  389. as.character() %>%
  390. help_text()
  391. })
  392. load_buttons <- function(..., extra_btns = NULL) {
  393. prefix <- paste(..., sep = "_")
  394. btns <- c(
  395. list(c("text", "Load Text", "btn-success"),
  396. c("pattern", "Load Pattern", "btn-primary")),
  397. extra_btns
  398. )
  399. tags$span(
  400. style = "display: inline-block;",
  401. purrr::map(
  402. btns,
  403. ~ actionButton(paste0(prefix, "_", .[1]), .[2], class = paste("btn-xs", if (!is.na(.[3])) .[3]))
  404. )
  405. )
  406. }
  407. observeEvent(input$help_try_this, {
  408. tagList(
  409. tags$h3("Try These Examples"),
  410. tags$p("Here are a couple interesting text extraction challenges you can try",
  411. "with this gadget."),
  412. tags$h4("Harvard Sentences"),
  413. tags$p("These examples come from the",
  414. tags$a(href = "http://r4ds.had.co.nz/strings.html", "R for Data Science"),
  415. "book and are based on a collection of short sentences called the Harvard Sentences."),
  416. tags$ol(
  417. tags$li(tags$p(
  418. "Find sentences that contain a color (i.e. red, orange, yellow, green, blue, purple).",
  419. load_buttons("help_try_this", "hs", "colors"))),
  420. tags$li(tags$p(
  421. "Use the text from Exercise 1 and make sure that only full words that are colors are found.",
  422. HTML("E.g. <code>red</code> and not <code>flickered</code>."),
  423. tags$span(style = "display: inline-block;",
  424. actionButton("help_try_this_hs_colors_word", "Load Pattern", class = "btn-xs btn-primary"),
  425. actionButton("help_try_this_hs_colors_hint", "Show Hint", class = "btn-xs"))
  426. )),
  427. tags$li(tags$p(
  428. "Extract nouns from sentences by finding any word that comes after \"a\" or \"the\".",
  429. "Use", actionLink("help_try_this_hs_words_go2_groups", "Groups"),
  430. "to extract the article and possible noun separately and check your results with",
  431. HTML("<code>stringr::str_match()</code>:"),
  432. load_buttons("help_try_this", "hs", "words",
  433. extra_btns = list(c("output", "Check str_match()")))
  434. )),
  435. tags$li(tags$p(
  436. "Switch the order of the two words following the articles", '"a" or "the"',
  437. "using", actionLink("help_try_this_hs_refs_go2_groups", "backreferences,"),
  438. "so that", tags$code("the birch canoe"), "would read",
  439. HTML("<code>the canoe birch</code>. Use <code>sub</code>"),
  440. "in the", tags$strong("Output"), "tab to replace the matched pattern.",
  441. load_buttons("help_try_this", "hs", "refs",
  442. extra_btns = list(c("output", "Load Replacement")))
  443. ))
  444. ),
  445. tags$h4("Phone Numbers"),
  446. tags$p("This example is also from the",
  447. tags$a(href = "http://r4ds.had.co.nz/strings.html#other-types-of-pattern",
  448. "R for Data Science"),
  449. "book. Phone numbers in the United States start with a 3-digit area code,",
  450. "followed by another 3 digits and a final 4-digit group.",
  451. "Sometimes the area code is wrapped in parenthesis, or sometimes dots or dashes",
  452. "are used to separate the digit groups. Try to extract each digit group from these phone numbers:",
  453. load_buttons("help_try_this", "phone",
  454. extra_btns = list(c("output", "Check str_match()")))),
  455. tags$h4("CSS Unit Validation"),
  456. tags$p("This example is used in", tags$code("validateCssUnit()"),
  457. "in the", tags$a(href="https://www.r-pkg.org/pkg/htmltools", "htmltools package."),
  458. "CSS units can be integer or decimal numbers with units such as",
  459. "in, cm, mm, em, ex, pt, px, etc. (see the list",
  460. HTML('<a href="https://www.w3.org/Style/Examples/007/units.en.html">here</a>).'),
  461. "Try to extract the number and unit from these units:",
  462. load_buttons("help_try_this", "css")),
  463. tags$h4("Parse Github Repos"),
  464. tags$p("This example is from the",
  465. tags$a(href = "https://www.r-pkg.org/pkg/rematch2", "rematch2 package."),
  466. "Github repositories are often specified in like",
  467. HTML("<code>user/repo/subdir@ref*release</code> or <code>user/repo/subdir#PR</code>"),
  468. "where only", tags$code("user"), "and", tags$code("repo"), "are required elements.",
  469. "Try to extract each piece of the repo text and use",
  470. tags$code("rematch2::re_match()"), "to extract a tidy tibble of matches:",
  471. load_buttons("help_try_this", "github",
  472. extra_btns = list(c("output", "Check re_match()"))))
  473. ) %>%
  474. as.character() %>%
  475. help_text()
  476. })
  477. observeEvent(input$help_try_this_hs_colors_text, {
  478. color_match <- "\\b(red|orange|yellow|green|blue|purple)\\b|red"
  479. color_text <- stringr::sentences[grepl(color_match, stringr::sentences)]
  480. color_text <- sample(color_text, 25)
  481. updateTextAreaInput(session, "text", value = paste(color_text, collapse = "\n"))
  482. showNotification("Text loaded! View it in Text tab", type = 'message')
  483. })
  484. observeEvent(input$help_try_this_hs_colors_pattern, {
  485. color_match <- "red|orange|yellow|green|blue|purple"
  486. updateTextInput(session, 'pattern', value = color_match)
  487. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines', 'perl'))
  488. showNotification("Pattern loaded! View it in RegEx tab", type = 'message')
  489. })
  490. observeEvent(input$help_try_this_hs_colors_word, {
  491. color_match <- "\\b(red|orange|yellow|green|blue|purple)\\b"
  492. updateTextInput(session, 'pattern', value = color_match)
  493. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines', 'perl'))
  494. showNotification("Pattern loaded! View it in RegEx tab", type = 'message')
  495. })
  496. observeEvent(input$help_try_this_hs_colors_hint, {
  497. showModal(
  498. modalDialog(title = "Hint \U0001f575", footer = NULL, easyClose = TRUE,
  499. tags$p("Try using the", tags$strong("word boundary"), "anchor."))
  500. )
  501. })
  502. observeEvent(input$help_try_this_hs_words_go2_groups, {
  503. make_help_tab_text("groups")
  504. })
  505. observeEvent(input$help_try_this_hs_words_output, {
  506. updateSelectInput(session, 'regexFn', selected = 'str_match')
  507. showNotification("Go to Output tab to see results from str_match()", type = "message")
  508. })
  509. observeEvent(input$help_try_this_hs_words_text, {
  510. hs_text <- sample(stringr::sentences, 25)
  511. updateTextAreaInput(session, "text", value = paste(hs_text, collapse = "\n"))
  512. showNotification("Text loaded! View it in Text tab", type = 'message')
  513. })
  514. observeEvent(input$help_try_this_hs_words_pattern, {
  515. noun_pattern <- "(a|the) ([^ ]+)"
  516. updateTextInput(session, 'pattern', value = noun_pattern)
  517. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines'))
  518. updateSelectInput(session, 'regexFn', selected = "str_match")
  519. showNotification("Pattern loaded! View it in RegEx and Output tabs", type = 'message')
  520. })
  521. observeEvent(input$help_try_this_hs_refs_go2_groups, {
  522. make_help_tab_text("groups")
  523. })
  524. observeEvent(input$help_try_this_hs_refs_output, {
  525. regexFn_replacement_val <<- "\\1 \\3 \\2"
  526. updateSelectInput(session, 'regexFn', selected = 'sub')
  527. showNotification("Replacement loaded! Go to Output tab to see results", type = "message")
  528. })
  529. observeEvent(input$help_try_this_hs_refs_text, {
  530. hs_text <- sample(stringr::sentences, 25)
  531. updateTextAreaInput(session, "text", value = paste(hs_text, collapse = "\n"))
  532. showNotification("Text loaded! View it in Text tab", type = 'message')
  533. })
  534. observeEvent(input$help_try_this_hs_refs_pattern, {
  535. noun_pattern <- "(a|the) ([^ ]+) ([^ ]+)"
  536. updateTextInput(session, 'pattern', value = noun_pattern)
  537. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines'))
  538. showNotification("Pattern loaded! View it in RegEx tab", type = 'message')
  539. })
  540. observeEvent(input$help_try_this_phone_output, {
  541. updateSelectInput(session, 'regexFn', selected = 'str_match')
  542. showNotification("Go to Output tab to see results from str_match()", type = "message")
  543. })
  544. observeEvent(input$help_try_this_phone_text, {
  545. phone_number <- function() {
  546. first <- function() sample(2:9, 1)
  547. others <- function(n) sample(1:9, n, replace = TRUE)
  548. wrap_types <- c("parens", "dash", "space", "dot", "nothing")
  549. wrap <- function(x, type) {
  550. switch(
  551. match.arg(type, choices = wrap_types),
  552. parens = paste0("(", x, ")"),
  553. dash = paste0(x, "-"),
  554. space = paste0(x, " "),
  555. dot = paste0(x, "."),
  556. x
  557. )
  558. }
  559. area_code <- paste0(c(first(), others(2)), collapse = "")
  560. group1 <- paste0(c(first(), others(2)), collapse = "")
  561. group2 <- paste0(c(first(), others(3)), collapse = "")
  562. area_wrap <- sample(wrap_types, 1)
  563. other_wrap <- if (area_wrap == "parens") sample(wrap_types[-1], 1) else area_wrap
  564. paste0(wrap(area_code, area_wrap), wrap(group1, other_wrap), group2)
  565. }
  566. phone_numbers <- replicate(25, phone_number())
  567. updateTextAreaInput(session, "text", value = paste(phone_numbers, collapse = "\n"))
  568. showNotification("Text loaded! View it in Text tab", type = 'message')
  569. })
  570. observeEvent(input$help_try_this_phone_pattern, {
  571. phone_pattern <- "\\(?(\\d{3})[-). ]?(\\d{3})[- .]?(\\d{4})"
  572. updateTextInput(session, 'pattern', value = phone_pattern)
  573. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines'))
  574. showNotification("Pattern loaded! View it in RegEx tab", type = 'message')
  575. })
  576. observeEvent(input$help_try_this_github_text, {
  577. github_repos <- c(
  578. "metacran/crandb",
  579. "jeroenooms/curl@v0.9.3",
  580. "jimhester/covr#47",
  581. "hadley/dplyr@*release",
  582. "r-lib/remotes@550a3c7d3f9e1493a2ba"
  583. )
  584. updateTextAreaInput(session, "text", value = paste(github_repos, collapse = "\n"))
  585. showNotification("Text loaded! Go to RegEx Tab", type = 'message')
  586. })
  587. observeEvent(input$help_try_this_github_pattern, {
  588. owner_rx <- "(?:(?<owner>[^/]+)/)?"
  589. repo_rx <- "(?<repo>[^/@#]+)"
  590. subdir_rx <- "(?:/(?<subdir>[^@#]*[^@#/]))?"
  591. ref_rx <- "(?:@(?<ref>[^*].*))"
  592. pull_rx <- "(?:#(?<pull>[0-9]+))"
  593. release_rx <- "(?:@(?<release>[*]release))"
  594. subtype_rx <- sprintf("(?:%s|%s|%s)?", ref_rx, pull_rx, release_rx)
  595. github_rx <- sprintf(
  596. "^(?:%s%s%s%s|(?<catchall>.*))$",
  597. owner_rx, repo_rx, subdir_rx, subtype_rx
  598. )
  599. updateTextInput(session, 'pattern', value = github_rx)
  600. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines', 'perl'))
  601. showNotification("Pattern loaded! Go to RegEx Tab", type = 'message')
  602. })
  603. observeEvent(input$help_try_this_github_output, {
  604. updateSelectInput(session, 'regexFn', selected = 're_match')
  605. showNotification("Go to Output tab to see results from re_match()", type = "message")
  606. })
  607. observeEvent(input$help_try_this_css_text, {
  608. css_units <- c(
  609. "125%","16pt","2cm","7em","3ex","24pt",
  610. ".15in","20pc","5.9vw","3.0vh","2vmin"
  611. )
  612. showNotification("Example text loaded! Go to RegEx tab", type = "message")
  613. updateTextAreaInput(session, "text", value = paste(css_units, collapse = "\n"))
  614. })
  615. observeEvent(input$help_try_this_css_pattern, {
  616. pattern <- "^(auto|inherit|((\\.\\d+)|(\\d+(\\.\\d+)?))(%|in|cm|mm|em|ex|pt|pc|px|vh|vw|vmin|vmax))$"
  617. updateTextInput(session, "pattern", value = pattern)
  618. updateCheckboxGroupInput(session, 'regex_options', selected = c('text_break_lines', 'perl'))
  619. showNotification("Pattern loaded! Go to RegEx tab", type = "message")
  620. })
  621. # ---- Server - Tab - Exit ----
  622. observeEvent(input$done, {
  623. if (pattern() != "") {
  624. pattern <- paste0('pattern <- "', escape_backslash(pattern()), '"')
  625. if ("regexFn_replacement" %in% names(input) && replacement() != "") {
  626. pattern <- paste0(
  627. pattern, "\n",
  628. 'replacement <- "', escape_backslash(replacement()), '"'
  629. )
  630. }
  631. rstudioapi::sendToConsole(pattern, FALSE)
  632. }
  633. stopApp()
  634. })
  635. observeEvent(input$cancel, {
  636. stopApp()
  637. })
  638. }
  639. viewer <- shiny::paneViewer(minHeight = 1000)
  640. runGadget(ui, server, viewer = viewer)
  641. }
  642. # ---- Gadget Helper Functions and Variables ----
  643. sanitize_text_input <- function(x) {
  644. if (is.null(x) || !nchar(x)) return(x)
  645. rx_unicode <- "\\\\u[0-9a-f]{4,8}"
  646. rx_hex <- "\\\\x[0-9a-f]{2}|\\\\x\\{[0-9a-f]{1,6}\\}"
  647. rx_octal <- "\\\\[0][0-7]{1,3}"
  648. rx_escape <- paste(rx_unicode, rx_hex, rx_octal, sep = "|")
  649. if (grepl(rx_escape, x, ignore.case = TRUE)) {
  650. try({
  651. y <- stringi::stri_unescape_unicode(x)
  652. }, silent = TRUE)
  653. if (!is.na(y)) x <- y
  654. }
  655. # x <- gsub("\u201C|\u201D", '"', x)
  656. # x <- gsub("\u2018|\u2019", "'", x)
  657. x
  658. }
  659. toHTML <- function(...) {
  660. x <- paste(..., collapse = "")
  661. x <- gsub("\n", "\\\\n", x)
  662. x <- gsub("\t", "\\\\t", x)
  663. x <- gsub("\r", "\\\\r", x)
  664. HTML(x)
  665. }
  666. regexFn_choices <- list(
  667. "Choose a function" = "",
  668. base = c(
  669. "grep",
  670. "grepl",
  671. "sub", #<<
  672. "gsub", #<<
  673. "regexpr",
  674. "gregexpr",
  675. "regexec"
  676. ),
  677. stringr = c(
  678. "str_detect",
  679. "str_locate",
  680. "str_locate_all",
  681. "str_extract",
  682. "str_extract_all",
  683. "str_match",
  684. "str_match_all",
  685. "str_replace", #<<
  686. "str_replace_all", #<<
  687. "str_split"
  688. ),
  689. "rematch2" = c(
  690. "re_match",
  691. "re_match_all",
  692. "re_exec",
  693. "re_exec_all"
  694. )
  695. )
  696. regexFn_substitute <- c(
  697. paste0(c("", "g"), "sub"),
  698. paste0("str_replace", c("", "_all"))
  699. )
  700. get_pkg_namespace <- function(fn) {
  701. x <- names(purrr::keep(regexFn_choices, ~ (fn %in% .)))
  702. if (length(x) > 1) warning(fn, " matches multiple functions in regexFn_choices, please review.")
  703. x
  704. }
  705. #' Check if an updated version is available
  706. #'
  707. #' I included this because it can be difficult to tell if your RStudio Addins
  708. #' are up to date. I may add new features that you want but you won't hear about
  709. #' the updates. This function checks if an update is available, using GitHub
  710. #' tags. If an update is available, a modal dialog is shown when you start
  711. #' the regexplain gadget. This only happens once per R session, though, so feel
  712. #' free to ignore the message.
  713. #'
  714. #' @param gh_user GitHub user account
  715. #' @param gh_repo GitHub repo name
  716. #' @param this_version The currently installed version of the package
  717. #' @keywords internal
  718. check_version <- function(
  719. gh_user = "gadenbuie",
  720. gh_repo = "regexplain",
  721. this_version = packageVersion('regexplain')
  722. ) {
  723. ok_to_check <- getOption("regexplain.no.check.version", TRUE)
  724. if (!ok_to_check) return(NULL)
  725. if (!requireNamespace('jsonlite', quietly = TRUE)) return(NULL)
  726. get_json <- purrr::possibly(jsonlite::fromJSON, NULL)
  727. gh_tags <- get_json(
  728. paste0("https://api.github.com/repos/", gh_user, "/", gh_repo, "/git/refs/tags"),
  729. simplifyDataFrame = TRUE
  730. )
  731. if (!is.null(gh_tags)) {
  732. gh_tags$tag <- sub("refs/tags/", "", gh_tags$ref, fixed = TRUE)
  733. gh_tags$version <- sub("^v\\.?", "", gh_tags$tag)
  734. }
  735. if (!is.null(gh_tags) && any(gh_tags$version > this_version)) {
  736. max_version <- max(gh_tags$version)
  737. max_tag <- gh_tags$tag[gh_tags$version == max_version]
  738. options(regexplain.no.check.version = FALSE)
  739. return(
  740. list(
  741. version = max_version,
  742. link = paste("https://github.com", gh_user, gh_repo, "releases/tag", max_tag, sep = "/")
  743. )
  744. )
  745. } else return(NULL)
  746. }
  747. #' Loads Regex Pattern Templates
  748. #'
  749. #' Sourced from [Regex Hub](https://projects.lukehaas.me/regexhub)
  750. #' and available at <https://github.com/lukehaas/RegexHub>. Copyright
  751. #' Luke Haas licensed under the MIT license available at
  752. #' <https://github.com/lukehaas/RegexHub/commit/3ab87b5a4fd2817b42e2e45dcf040d4f0164ea37>.
  753. #'
  754. #' @keywords internal
  755. get_templates <- function() {
  756. if (!requireNamespace("jsonlite")) {
  757. warning("Please install the `jsonlite` package to use template features")
  758. return(NULL)
  759. }
  760. f_patterns <- system.file("extdata", "patterns.json", package = "regexplain")
  761. if (!file.exists(f_patterns)) return(NULL)
  762. jsonlite::fromJSON(f_patterns, simplifyVector = FALSE, simplifyDataFrame = FALSE, simplifyMatrix = FALSE)
  763. }