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

68 lines
2.3KB

  1. #' RegExplain Addin
  2. #'
  3. #' Addin for regexplain. If the selection does not contain multiple lines, the
  4. #' addin tries to evaluate the selection and coerce the result to a character
  5. #' string. Only unique lines are passed to the gadget to maximize screen space.
  6. #' The max number of lines returned is set by the option
  7. #' `regexplain.addin.max_lines`, with a default value of 100 lines.
  8. #' If evaluating the selection does not produce a character vector without
  9. #' errors, the original selection is returned.
  10. #'
  11. #' @keywords internal
  12. regexplain_addin <- function() {
  13. # Get the document context.
  14. context <- rstudioapi::getActiveDocumentContext()
  15. # Get context text
  16. ctx_text <- context$selection[[1]]$text
  17. max_lines <- getOption("rexeplain.addin.max_lines", 100)
  18. # If it is one line and evaluates to something, use that
  19. # Otherwise treat as text
  20. obj <- tryCatch({
  21. if (grepl("\n", ctx_text)) {
  22. ctx_text[1:min(length(ctx_text), max_lines)]
  23. } else {
  24. x <- eval(parse(text = ctx_text))
  25. if (inherits(x, "list")) x <- unlist(x)
  26. x <- as.character(x)
  27. if (length(x) == 1 && grepl("\n", x))
  28. x <- strsplit(x, "\n")[[1]]
  29. x <- unique(x)
  30. if (length(x) > max_lines) {
  31. message(ctx_text, " gave ", length(x), " lines, limiting to first ",
  32. max_lines, " unique lines. Set ",
  33. "options('regexplain.addin.max_lines') to a higher value to ",
  34. "increase the number of lines.")
  35. x <- unique(x)
  36. x[1:min(length(x), max_lines)]
  37. } else x
  38. }
  39. },
  40. error = function(e) {as.character(ctx_text[1:min(length(ctx_text), max_lines)])})
  41. regexplain_gadget(if (length(obj) && obj != "") obj)
  42. }
  43. #' Regexplain File Addin
  44. #'
  45. #' See [regexplain_addin]. Opens file chooser to pick file, reads lines, returns
  46. #' first `regexplain.addin.max_lines` (default 100).
  47. #'
  48. #' @keywords internal
  49. regexplain_file <- function() {
  50. fname <- file.choose()
  51. x <- readLines(fname)
  52. max_lines <- getOption("rexeplain.addin.max_lines", 100)
  53. if (length(x) > max_lines) {
  54. message("There were ", format(length(x), big.mark = ","), " lines in ",
  55. fname, "\nUsing only first ", max_lines, ".\n",
  56. "Set options('regexplain.addin.max_lines') to a higher value to ",
  57. "increase the number of lines.")
  58. x <- x[1:max_lines]
  59. }
  60. regexplain_gadget(x, "RegEx")
  61. }