summaryrefslogtreecommitdiffstats
path: root/.config/nvim/plugin/50-transform_text.lua
blob: 9ec74d5717d7a215ecdb6e6876f62b35f45a6c2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
local function get_visual_selection_text()
	return table.concat(vim.fn.getregion(vim.fn.getpos("v"), vim.fn.getpos("."), { type = vim.fn.mode() }), "\n")
end

local function delete_visual_selection()
	local mode = vim.fn.mode()
	local eovisual_pos, cur_pos = vim.fn.getpos("v"), vim.fn.getpos(".")
	local region = vim.fn.getregionpos(eovisual_pos, cur_pos, { type = mode })[1]
	local start_row, start_col = unpack(region[1], 2, 3)
	local end_row, end_col = mode == "v" and region[2][2] or math.max(eovisual_pos[2], cur_pos[2]), region[2][3]
	vim.api.nvim_buf_set_text(0, start_row - 1, start_col - 1, end_row - 1, end_col, {})
end

local function transform_visual_selection(transform)
	local selection = get_visual_selection_text()
	delete_visual_selection()
	vim.api.nvim_put({ transform(selection) }, "c", true, true)
end

vim.keymap.set("x", "<Leader>tue", function()
	transform_visual_selection(vim.uri_encode)
end, { desc = "URL-encode selection" })
vim.keymap.set("x", "<Leader>tud", function()
	transform_visual_selection(vim.uri_decode)
end, { desc = "URL-decode selection" })