From e619e5122dc4fc898bef6adc2cd93860392cab24 Mon Sep 17 00:00:00 2001 From: Jason Paris Date: Wed, 29 Oct 2025 11:37:07 -0400 Subject: [PATCH] feat: add automatic workspace detection based on file path Automatically switches to the appropriate workspace when opening markdown files based on their file path. This eliminates the need to manually switch workspaces when working across multiple vaults. The plugin now sets up an autocommand that runs on BufEnter and BufRead events for *.md files, detecting which workspace the file belongs to by matching the file path against configured vault paths. --- lua/markdown-notes/init.lua | 14 +++++++++++++ lua/markdown-notes/workspace.lua | 34 ++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) 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