Skip to content
This repository has been archived by the owner on Sep 18, 2023. It is now read-only.

Commit

Permalink
feat: basic duplication within a line
Browse files Browse the repository at this point in the history
  • Loading branch information
smjonas committed Jan 18, 2023
1 parent 2d8762c commit f085344
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# duplicate.nvim
A tiny Neovim plugin used to duplicate a textobject. E.g. use `ydip` to duplicate the current paragraph.
Requires Neovim
A tiny Neovim plugin used to duplicate a textobject (works in both normal and visual mode). E.g. use `ydip` to duplicate the current paragraph.

Requires Neovim ≥ 0.6.

## Installation
Install it just like any other Neovim plugin. Make sure to call the `setup` function.
Expand Down
23 changes: 19 additions & 4 deletions lua/duplicate/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,28 @@ Duplicate.operator = function(mode)
-- Using `vim.cmd()` wrapper to allow usage of `lockmarks` command, because
-- raw execution will delete marks inside region (due to
-- `vim.api.nvim_buf_set_lines()`).
vim.cmd(string.format("lockmarks lua Duplicate.duplicate_lines(%d, %d)", line_left, line_right))
vim.cmd(
string.format("lockmarks lua Duplicate.duplicate_lines(%d, %d, %d, %d)", line_left, line_right, col_left, col_right)
)
return ""
end

Duplicate.duplicate_lines = function(line_start, line_end)
local lines = vim.api.nvim_buf_get_lines(0, line_start - 1, line_end, false)
vim.api.nvim_buf_set_lines(0, line_end, line_end, false, lines)
-- Line indices are 1-based, columns are 0-based
Duplicate.duplicate_lines = function(line_start, line_end, col_start, col_end)
if line_start == line_end then
assert(col_start and col_end)
-- Duplicate within a line
local line = vim.api.nvim_buf_get_lines(0, line_start - 1, line_start, false)[1]
-- Make columns 1-based
col_start, col_end = col_start + 1, col_end + 1
local chars = line:sub(col_start, col_end)
local updated_line = line:sub(1, col_start - 1) .. chars .. line:sub(col_start)
vim.api.nvim_buf_set_lines(0, line_start - 1, line_start, false, { updated_line })
else
-- Duplicate multiple lines
local lines = vim.api.nvim_buf_get_lines(0, line_start - 1, line_end, false)
vim.api.nvim_buf_set_lines(0, line_end, line_end, false, lines)
end
end

local default_config = {
Expand Down

0 comments on commit f085344

Please sign in to comment.