🔍 An RStudio addin slash regex utility belt
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

78 lines
2.6KB

  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. {
  22. if (grepl("\n", ctx_text)) {
  23. ctx_text[1:min(length(ctx_text), max_lines)]
  24. } else {
  25. x <- eval(parse(text = ctx_text))
  26. if (inherits(x, "list")) x <- unlist(x)
  27. x <- as.character(x)
  28. if (length(x) == 1 && grepl("\n", x)) {
  29. x <- strsplit(x, "\n")[[1]]
  30. }
  31. x <- unique(x)
  32. if (length(x) > max_lines) {
  33. message(
  34. ctx_text,
  35. " gave ",
  36. length(x),
  37. " lines, limiting to first ",
  38. max_lines,
  39. " unique lines. Set ",
  40. "options('regexplain.addin.max_lines') to a higher value to ",
  41. "increase the number of lines."
  42. )
  43. x <- unique(x)
  44. x[1:min(length(x), max_lines)]
  45. } else {
  46. x
  47. }
  48. }
  49. },
  50. error = function(e) {
  51. as.character(ctx_text[1:min(length(ctx_text), max_lines)])
  52. }
  53. )
  54. regexplain_gadget(if (length(obj) && obj != "") obj)
  55. }
  56. #' @describeIn regexplain_gadget Opens file chooser to pick file, reads lines,
  57. #' returns first `regexplain.addin.max_lines` (default 100). Used in the
  58. #' "Regexplain File" [regexplain_addin].
  59. #' @export
  60. regexplain_file <- function(pattern = NULL, start_page = "RegEx") {
  61. fname <- file.choose()
  62. x <- readLines(fname)
  63. max_lines <- getOption("rexeplain.addin.max_lines", 100)
  64. if (length(x) > max_lines) {
  65. message("There were ", format(length(x), big.mark = ","), " lines in ",
  66. fname, "\nUsing only first ", max_lines, ".\n",
  67. "Set options('regexplain.addin.max_lines') to a higher value to ",
  68. "increase the number of lines.")
  69. x <- x[1:max_lines]
  70. }
  71. regexplain_gadget(text = x, pattern = pattern, start_page = start_page)
  72. }