From f762ad498ef8c47ef8f65bf6029bf3907d09e87e Mon Sep 17 00:00:00 2001 From: Steven Xu Date: Sun, 25 Feb 2024 19:00:49 +1100 Subject: [PATCH] feat: add `slide_to()`, to slide the buffer to position --- lua/bufferline.lua | 1 + lua/bufferline/commands.lua | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lua/bufferline.lua b/lua/bufferline.lua index 1930a88a..8114e6c2 100644 --- a/lua/bufferline.lua +++ b/lua/bufferline.lua @@ -23,6 +23,7 @@ local api = vim.api local M = { move = commands.move, move_to = commands.move_to, + slide_to = commands.slide_to, exec = commands.exec, go_to = commands.go_to, cycle = commands.cycle, diff --git a/lua/bufferline/commands.lua b/lua/bufferline/commands.lua index 55a07152..3860bd34 100644 --- a/lua/bufferline/commands.lua +++ b/lua/bufferline/commands.lua @@ -155,7 +155,7 @@ function M.move_to(to_index, from_index) if not index then return utils.notify("Unable to find buffer to move, sorry", "warn") end -- Calculate next index depending on the sign of `to_index` local next_index = to_index > 0 and to_index or #state.components + 1 + to_index - if next_index >= 1 and next_index <= #state.components then + if next_index >= 1 and next_index <= #state.components and next_index ~= from_index then local item = state.components[index] local destination_buf = state.components[next_index] state.components[next_index] = item @@ -167,6 +167,26 @@ function M.move_to(to_index, from_index) end end +--- Slide the buffer at index `from_index` (or current index if not specified) to position `to_index` +--- @param to_index number negative indices are accepted (counting from the right instead of the left, e.g. -1 for the last position, -2 for the second-last, etc.) +--- @param from_index number? +function M.slide_to(to_index, from_index) + -- Calculate next index depending on the sign of `to_index` + local next_index = to_index > 0 and to_index or #state.components + 1 + to_index + if next_index >= 1 and next_index <= #state.components and next_index ~= from_index then + local step = (from_index < next_index and 1) or -1 + local from_buf = state.components[from_index] + for cur_index = from_index, next_index - step, step do + state.components[cur_index] = state.components[cur_index + step] + end + state.components[next_index] = from_buf + state.custom_sort = utils.get_ids(state.components) + local opts = config.options + if opts.persist_buffer_sort then utils.save_positions(state.custom_sort) end + ui.refresh() + end +end + --- @param direction number function M.move(direction) local index, element = M.get_current_element_index(state)