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

66 lines
2.4KB

  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. #' @describeIn regexplain_gadget Opens file chooser to pick file, reads lines,
  44. #' returns first `regexplain.addin.max_lines` (default 100). Used in the
  45. #' "Regexplain File" [regexplain_addin].
  46. #' @export
  47. regexplain_file <- function(pattern = NULL, start_page = "RegEx") {
  48. fname <- file.choose()
  49. x <- readLines(fname)
  50. max_lines <- getOption("rexeplain.addin.max_lines", 100)
  51. if (length(x) > max_lines) {
  52. message("There were ", format(length(x), big.mark = ","), " lines in ",
  53. fname, "\nUsing only first ", max_lines, ".\n",
  54. "Set options('regexplain.addin.max_lines') to a higher value to ",
  55. "increase the number of lines.")
  56. x <- x[1:max_lines]
  57. }
  58. regexplain_gadget(text = x, pattern = pattern, start_page = start_page)
  59. }