| 1 |
completions <- function(code, cursor_pos = nchar(code), fixup = TRUE) { |
| 2 |
|
| 3 |
lines <- strsplit(code, '\n', fixed = TRUE)[[1]] |
| 4 |
chars_before_line <- 0L |
| 5 |
for (line in lines) { |
| 6 |
new_cursor_pos <- cursor_pos - nchar(line) - 1L |
| 7 |
if (new_cursor_pos < 0L) { |
| 8 |
break |
| 9 |
} |
| 10 |
cursor_pos <- new_cursor_pos |
| 11 |
chars_before_line <- chars_before_line + nchar(line) + 1L |
| 12 |
} |
| 13 |
|
| 14 |
|
| 15 |
if (is.null(line)) { |
| 16 |
line <- '' |
| 17 |
} |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
utils_ns <- asNamespace('utils') |
| 24 |
|
| 25 |
get('.assignLinebuffer', utils_ns)(line) |
| 26 |
get('.assignEnd', utils_ns)(cursor_pos) |
| 27 |
|
| 28 |
|
| 29 |
c.info <- get('.guessTokenFromLine', utils_ns)(update = FALSE) |
| 30 |
get('.guessTokenFromLine', utils_ns)() |
| 31 |
get('.completeToken', utils_ns)() |
| 32 |
|
| 33 |
start_position <- chars_before_line + c.info$start |
| 34 |
in_string <- substr(code, start_position, start_position) %in% c("'", '"') |
| 35 |
|
| 36 |
comps <- get('.retrieveCompletions', utils_ns)() |
| 37 |
if (fixup && !in_string && length(comps)) comps <- fixup_comps(comps) |
| 38 |
list( |
| 39 |
comps = comps, |
| 40 |
start = start_position, |
| 41 |
end = start_position + nchar(c.info$token) |
| 42 |
) |
| 43 |
} |
| 44 |
|
| 45 |
fixup_comps <- function(comps) { |
| 46 |
|
| 47 |
re_trail <- '=|::' |
| 48 |
|
| 49 |
|
| 50 |
trailing <- gsub(sprintf('^.*?(%s)?$', re_trail), '\\1', comps, perl = TRUE) |
| 51 |
comps <- gsub(sprintf('(%s)$', re_trail), '', comps, perl = TRUE) |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
lead_matches <- gregexpr("(?<=[$@])|(?<=[^:]::)|(?<=:::)", comps, perl = TRUE) |
| 58 |
last_match <- vapply(lead_matches, tail, n = 1L, integer(1L)) |
| 59 |
has_match <- last_match > 0L |
| 60 |
leading <- rep("", length(comps)) |
| 61 |
comps_with_leading <- comps[has_match] |
| 62 |
leading[has_match] <- substr(comps_with_leading, 1L, last_match - 1L) |
| 63 |
comps[has_match] <- substr(comps_with_leading, last_match, nchar(comps_with_leading)) |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
non_empty <- nzchar(comps) |
| 68 |
comps[non_empty] <- vapply( |
| 69 |
comps[non_empty], |
| 70 |
|
| 71 |
function(nm) paste(deparse(as.name(nm), backtick = TRUE), collapse = " "), |
| 72 |
character(1L) |
| 73 |
) |
| 74 |
|
| 75 |
|
| 76 |
trailing <- gsub('=', ' = ', trailing, fixed = TRUE) |
| 77 |
comps <- paste0(leading, comps, trailing) |
| 78 |
comps[comps == "... = "] <- "..." |
| 79 |
comps |
| 80 |
} |