diff --git a/README.md b/README.md index 3d84126..49abeaa 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ Substitute comes with the following defaults: { on_substitute = nil, yank_substituted_text = false, + preserve_cursor_position = false, highlight_substituted_text = { enabled = true, timer = 500, @@ -81,6 +82,7 @@ Substitute comes with the following defaults: exchange = { motion = false, use_esc_to_cancel = true, + preserve_cursor_position = false, }, } ``` @@ -144,6 +146,12 @@ Default : `500` Define the duration of highlight. +### `preserve_cursor_position` + +Default : `false` + +If `true`, the cursor position will be preserved when performing a substitution. + ### 🤝 Integration
@@ -377,6 +385,12 @@ false, consider map the cancel function: vim.keymap.set("n", "sxc", require('substitute.exchange').cancel, { noremap = true }) ``` +### `exchange.preserve_cursor_position` + +Default : `false` + +If `true`, the cursor position will be preserved when performing an exchange. + ## 🎨 Colors | Description | Group | Default | diff --git a/lua/substitute.lua b/lua/substitute.lua index 99b1708..ecd430e 100644 --- a/lua/substitute.lua +++ b/lua/substitute.lua @@ -5,6 +5,8 @@ local substitute = {} substitute.state = { register = nil, + count = nil, + curpos = nil, } function substitute.setup(options) @@ -24,6 +26,9 @@ function substitute.operator(options) options = options or {} substitute.state.register = options.register or vim.v.register substitute.state.count = options.count or (vim.v.count > 0 and vim.v.count or 1) + if config.options.preserve_cursor_position then + substitute.state.curpos = vim.api.nvim_win_get_cursor(0) + end vim.o.operatorfunc = "v:lua.require'substitute'.operator_callback" vim.api.nvim_feedkeys("g@" .. (options.motion or ""), "mi", false) end @@ -50,6 +55,10 @@ function substitute.operator_callback(vmode) vim.fn.setreg(utils.get_default_register(), table.concat(substitued_text, "\n"), utils.get_register_type(vmode)) end + if nil ~= substitute.state.curpos and config.options.preserve_cursor_position then + vim.api.nvim_win_set_cursor(0, substitute.state.curpos) + end + if config.options.on_substitute ~= nil then config.options.on_substitute({ marks = marks, diff --git a/lua/substitute/config.lua b/lua/substitute/config.lua index 8af9000..587172c 100644 --- a/lua/substitute/config.lua +++ b/lua/substitute/config.lua @@ -6,6 +6,7 @@ function config.setup(options) local default_values = { on_substitute = nil, yank_substituted_text = false, + preserve_cursor_position = false, highlight_substituted_text = { enabled = true, timer = 500,