diff --git a/lua/markdown-notes/init.lua b/lua/markdown-notes/init.lua index a134005..4cabf4c 100644 --- a/lua/markdown-notes/init.lua +++ b/lua/markdown-notes/init.lua @@ -10,6 +10,7 @@ local M = {} function M.setup(opts) config.setup(opts) M.setup_keymaps() + M.setup_autocommands() end function M.setup_workspace(name, opts) @@ -147,4 +148,17 @@ function M.setup_keymaps() end, { desc = "Show active workspace" }) end +function M.setup_autocommands() + -- Auto-detect workspace when entering a buffer + local augroup = vim.api.nvim_create_augroup("MarkdownNotesWorkspace", { clear = true }) + vim.api.nvim_create_autocmd({ "BufEnter", "BufRead" }, { + group = augroup, + pattern = "*.md", + callback = function() + workspace.auto_detect_workspace() + end, + desc = "Auto-detect markdown workspace based on file path", + }) +end + return M diff --git a/lua/markdown-notes/workspace.lua b/lua/markdown-notes/workspace.lua index ebfec60..1e3c097 100644 --- a/lua/markdown-notes/workspace.lua +++ b/lua/markdown-notes/workspace.lua @@ -95,4 +95,38 @@ function M.pick_workspace() }) end +-- Auto-detect workspace based on current file path +function M.auto_detect_workspace() + local current_file = vim.fn.expand("%:p") + + -- Only process markdown files + if vim.fn.expand("%:e") ~= "md" then + return + end + + -- Don't process if file path is empty + if current_file == "" then + return + end + + local workspaces = config.get_workspaces() + local current_workspace = config.get_active_workspace() + + -- Check each workspace to see if the file belongs to it + for name, workspace in pairs(workspaces) do + local vault_path = vim.fn.expand(workspace.vault_path) + -- Normalize paths for comparison + vault_path = vim.fn.fnamemodify(vault_path, ":p") + + -- Check if current file is within this workspace's vault + if current_file:sub(1, #vault_path) == vault_path then + -- Only switch if we're not already in this workspace + if current_workspace ~= name then + config.set_active_workspace(name) + end + return + end + end +end + return M