102 lines
2.4 KiB
Lua
102 lines
2.4 KiB
Lua
local bookmarks = {}
|
|
local bookmarksFilePath = ".bookmarks"
|
|
local M = {}
|
|
|
|
function M.setup()
|
|
local augroup = vim.api.nvim_create_augroup("bookmark.nvim", {clear=true})
|
|
vim.api.nvim_create_autocmd(
|
|
{"DirChanged"},
|
|
{
|
|
pattern = {"global"},
|
|
callback = M.loadBookmarks,
|
|
group = augroup,
|
|
}
|
|
)
|
|
vim.api.nvim_create_autocmd(
|
|
{"SessionWritePost"},
|
|
{
|
|
callback = M.saveBookmarks,
|
|
group = augroup,
|
|
}
|
|
)
|
|
vim.api.nvim_create_autocmd(
|
|
{"VimLeavePre"},
|
|
{
|
|
pattern = {"*"},
|
|
callback = M.saveBookmarks,
|
|
group = augroup,
|
|
}
|
|
)
|
|
end
|
|
|
|
function M.loadBookmarks()
|
|
--clear current bookmarks
|
|
bookmarks = {}
|
|
bookmarksFilePath = ".bookmarks"
|
|
local path = vim.fs.find(".bookmarks", {upward = true, type="file"})[1]
|
|
if not path then
|
|
return
|
|
end
|
|
bookmarksFilePath = path
|
|
local file = io.open(bookmarksFilePath, "r")
|
|
if file then
|
|
local fileContent = file:read("*a")
|
|
file:close()
|
|
if fileContent and fileContent ~= "" then
|
|
bookmarks = vim.json.decode(fileContent)
|
|
end
|
|
else
|
|
vim.notify("Failed to load Bookmarks")
|
|
end
|
|
end
|
|
|
|
function M.saveBookmarks()
|
|
if #bookmarks > 0 or vim.fn.filereadable(bookmarksFilePath) then
|
|
local file = io.open(bookmarksFilePath, "w")
|
|
if file then
|
|
file:write(vim.json.encode(bookmarks))
|
|
file:flush()
|
|
file:close()
|
|
else
|
|
vim.notify("Failed to load Bookmarks")
|
|
end
|
|
end
|
|
end
|
|
|
|
function M.addBookmark()
|
|
vim.ui.input({prompt= "Name of bookmark", default= vim.fn.bufname()}, function(input)
|
|
if input and input ~= "" then
|
|
local file = vim.api.nvim_buf_get_name(0)
|
|
local cursor = vim.api.nvim_win_get_cursor(0)
|
|
table.insert(bookmarks, {name = input, file = file, cursor = cursor})
|
|
end
|
|
end)
|
|
end
|
|
|
|
function M.selectBookmark(action, on_choice)
|
|
if bookmarks and #bookmarks > 0 then
|
|
vim.ui.select(bookmarks, {prompt = action .." Bookmark", format_item = function(item) return item.name end}, on_choice)
|
|
else
|
|
vim.notify("No bookmarks set or loaded")
|
|
end
|
|
end
|
|
|
|
function M.deleteBookmark()
|
|
M.selectBookmark("Delete", function(_, idx)
|
|
if idx then
|
|
table.remove(bookmarks, idx)
|
|
end
|
|
end)
|
|
end
|
|
|
|
function M.jumpToBookmark()
|
|
M.selectBookmark("Jump to",vim.schedule_wrap(function(item)
|
|
if item then
|
|
vim.cmd("edit " .. item.file)
|
|
vim.api.nvim_win_set_cursor(0, item.cursor)
|
|
end
|
|
end))
|
|
end
|
|
|
|
return M
|