Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "Align Cursor" addin #7

Merged
merged 3 commits into from
Aug 13, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add align by cursor using multiple cursors
Supports multiple cursors per line
  • Loading branch information
gadenbuie committed Aug 13, 2019
commit 71f3030e929eab851d108d6b47531804d3d48bde
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