Skip to content

Commit

Permalink
fix: compute correct initial portal offset (#39)
Browse files Browse the repository at this point in the history
* fix: compute correct initial window offset based on current cursor location
* refactor: better variable names
  • Loading branch information
cbochs authored Mar 25, 2023
1 parent 849d993 commit e0ef802
Showing 1 changed file with 36 additions and 10 deletions.
46 changes: 36 additions & 10 deletions lua/portal/search.lua
Original file line number Diff line number Diff line change
Expand Up @@ -61,27 +61,53 @@ function Search.open(results, labels, window_options)
log.warn("Search.open: found more results than available labels.")
end

local function window_title(result)
local title = vim.fs.basename(vim.api.nvim_buf_get_name(result.buffer))
if title == "" then
title = "Result"
end
return ("[%s] %s"):format(result.type, title)
end

local function compute_max_index()
return math.min(math.max(unpack(vim.tbl_keys(results))), #labels)
end

local function compute_initial_offset()
local row_offset = 0

local height_step = window_options.height + 2
local total_height = vim.tbl_count(results) * height_step

local current_line = vim.fn.line(".")
local bottom_line = vim.fn.line("w$")
local line_difference = (bottom_line - current_line)

if line_difference < total_height then
row_offset = line_difference - total_height
end

return row_offset
end

local windows = {}

local max_index = math.min(math.max(unpack(vim.tbl_keys(results))), #labels)
local cur_row = 0
local max_index = compute_max_index()
local row_offset = compute_initial_offset()

for i = 1, max_index do
-- stylua: ignore
if not results[i] then goto continue end

local result = results[i]
if not result then
goto continue
end

cur_row = cur_row + 1
window_options = vim.deepcopy(window_options)
window_options.row = (cur_row - 1) * (window_options.height + 2)
window_options.row = row_offset + (cur_row - 1) * (window_options.height + 2)

if vim.fn.has("nvim-0.9") == 1 then
local title = vim.fs.basename(vim.api.nvim_buf_get_name(result.buffer))
if title == "" then
title = "Result"
end
window_options.title = ("[%s] %s"):format(result.type, title)
window_options.title = window_title(result)
end

local window = Window:new(result, window_options)
Expand Down

0 comments on commit e0ef802

Please sign in to comment.