Skip to content

Commit

Permalink
Add align by cursor using multiple cursors
Browse files Browse the repository at this point in the history
Supports multiple cursors per line
  • Loading branch information
gadenbuie committed Aug 13, 2019
1 parent 207bbc0 commit 71f3030
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
39 changes: 39 additions & 0 deletions R/align_assign.R
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,42 @@ guess_operator <- function(area = captureArea(capture())) {
return("<-")
}
}

alignCursor <- function() {
context <- rstudioapi::getActiveDocumentContext()

cursors <- lapply(context$selection, function(x) unclass(x$range$start))

if (length(cursors) < 2) {
message("Nothing to align, did you place multiple cursors in the document?")
return()
}

x <- as.data.frame(do.call("rbind", cursors))
x <- x[order(x$row), ]

# used to keep track of added space if multiple cursors per line
added_spaces <- data.frame(row = unique(x$row), nt = 0L)

x$group <- sequence(rle(x$row)$lengths)
x <- split(x, x$group)
for (xg in x) {
xg <- merge(xg, added_spaces, by = "row")
xg$column <- xg$column + xg$nt
xg$n <- max(xg$column) - xg$column
added_spaces <- update_spaces(added_spaces, xg)
spaces_to_add <- make_space(xg$n)
locs <- Map(c, xg$row, xg$column)
rstudioapi::insertText(locs, spaces_to_add, id = context$id)
}
}

make_space <- function(n) {
vapply(n, function(nn) strrep(' ', nn), " ")
}

update_spaces <- function(a, x) {
a <- merge(a, x[, c("row", "n")], by = "row")
a$nt <- a$nt + x$n
a[, c("row", "nt")]
}
5 changes: 5 additions & 0 deletions inst/rstudio/addins.dcf
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ Description: Aligns '<-' or '=' assignment operators within a highlighted area.
Binding: alignAssign
Interactive: false

Name: Align Cursors
Description: Aligns all cursors. Use Ctrl/Cmd + Alt + click to insert multiple cursors.
Binding: alignCursor
Interactive: false

Name: Align Assign Arrow
Description: Aligns '<-' assignment operators within a highlighted area.
Binding: alignAssignArrow
Expand Down

0 comments on commit 71f3030

Please sign in to comment.