commit e7e762e695076c677b1dbb7d99f406e79e7fd617 Author: Stefan Rakel Date: Thu Oct 30 14:18:55 2025 +0100 Initial commit diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..1c5ffaa --- /dev/null +++ b/Readme.md @@ -0,0 +1,3 @@ +# Bookmark.nvim + +Small plugin to create and delete as well as navigate to bookmarks diff --git a/lua/bookmark.lua b/lua/bookmark.lua new file mode 100644 index 0000000..5d772e5 --- /dev/null +++ b/lua/bookmark.lua @@ -0,0 +1,90 @@ +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 = {} + local path = vim.fs.find(".bookmarks", {upward = true, type="file"})[1] + if not path then + return + end + bookmarksFilePath = path + local fileContent = io.open(bookmarksFilePath, "r"):read("*a") + if fileContent and fileContent ~= "" then + bookmarks = vim.json.decode(fileContent) + end +end + +function M.saveBookmarks() + if #bookmarks > 1 then + local file = io.open(bookmarksFilePath, "w") + if file then + file:write(vim.json.encode(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(on_choice) + if bookmarks and #bookmarks > 0 then + vim.ui.select(bookmarks, {prompt = "Select 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(function(_, idx) + if idx then + table.remove(bookmarks, idx) + end + end) +end + +function M.jumpToBookmark() + M.selectBookmark(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