98 lines
2.4 KiB
Lua
98 lines
2.4 KiB
Lua
local Bookmarks = {}
|
|
local H = {
|
|
state = {
|
|
bookmarks = {},
|
|
},
|
|
}
|
|
|
|
function Bookmarks.setup()
|
|
_G.Bookmarks = Bookmarks
|
|
|
|
local augroup = vim.api.nvim_create_augroup("bookmark.nvim", {clear=true})
|
|
vim.api.nvim_create_autocmd(
|
|
{"DirChanged"},
|
|
{
|
|
pattern = {"*"},
|
|
callback = function()
|
|
H.loadBookmarks()
|
|
end,
|
|
group = augroup,
|
|
}
|
|
)
|
|
end
|
|
|
|
function H.getSavePath()
|
|
local cwd = vim.fs.normalize(vim.fn.getcwd())
|
|
local filename = string.gsub(cwd, "[/:]", "%%")
|
|
local statePath = vim.fs.normalize(vim.fn.stdpath("state"))
|
|
statePath = vim.fs.joinpath(statePath, "bookmark")
|
|
vim.fn.mkdir(statePath, "p")
|
|
local filePath = vim.fs.joinpath(statePath, filename)
|
|
return filePath
|
|
end
|
|
|
|
function H.loadBookmarks()
|
|
H.state = {bookmarks = {}}
|
|
local path = H.getSavePath()
|
|
local file = io.open(path, "r")
|
|
if not file then
|
|
return
|
|
end
|
|
local content = file:read("*a")
|
|
file:close()
|
|
H.state = vim.json.decode(content)
|
|
end
|
|
|
|
function H.saveBookmarks()
|
|
local path = H.getSavePath()
|
|
local file = io.open(path, "w")
|
|
if not file then
|
|
return
|
|
end
|
|
file:write(vim.json.encode(H.state))
|
|
file:close()
|
|
end
|
|
|
|
function Bookmarks.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(H.state.bookmarks, {name = input, file = file, cursor = cursor})
|
|
H.saveBookmarks()
|
|
vim.notify("Bookmark \"" .. input .. "\" added")
|
|
end
|
|
end)
|
|
end
|
|
|
|
function Bookmarks.selectBookmark(action, on_choice)
|
|
if H.state.bookmarks and #H.state.bookmarks > 0 then
|
|
vim.ui.select(H.state.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 Bookmarks.deleteBookmark()
|
|
Bookmarks.selectBookmark("Delete", function(bookmark, idx)
|
|
if idx then
|
|
table.remove(H.state.bookmarks, idx)
|
|
H.saveBookmark()
|
|
vim.notify("Deleted bookmark \"".. bookmark.name .. "\"")
|
|
end
|
|
end)
|
|
end
|
|
|
|
function Bookmarks.jumpToBookmark()
|
|
Bookmarks.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)
|
|
--set jump in jumplist
|
|
vim.cmd("normal! m'")
|
|
end
|
|
end))
|
|
end
|
|
|
|
return Bookmarks
|