Skip to content

add save_on_nav so backlinks work automatically #843

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lua/obsidian/config.lua
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ config.CompletionOpts.default = function()
end

---@class obsidian.config.MappingOpts
---@field save_on_nav boolean If true, save the file when navigating to a link
config.MappingOpts = {}

---Get defaults.
Expand All @@ -306,6 +307,7 @@ config.MappingOpts.default = function()
["gf"] = mappings.gf_passthrough(),
["<leader>ch"] = mappings.toggle_checkbox(),
["<cr>"] = mappings.smart_action(),
save_on_nav = false, -- Default to false to maintain backward compatibility
}
end

Expand Down
26 changes: 26 additions & 0 deletions lua/obsidian/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,19 @@ end

util.gf_passthrough = function()
if util.cursor_on_markdown_link(nil, nil, true) then
-- Get the client to check settings
local client = require("obsidian").get_client()
if client and client.opts and client.opts.mappings and client.opts.mappings.save_on_nav then
-- Before following the link, save the current buffer
-- This ensures any new links in the current file are written to disk
if vim.api.nvim_buf_get_option(0, "modified") then
-- Schedule the save to avoid BufWritePre issues
vim.schedule(function()
vim.cmd "write"
end)
end
end

return "<cmd>ObsidianFollowLink<CR>"
else
return "gf"
Expand All @@ -754,6 +767,19 @@ end
util.smart_action = function()
-- follow link if possible
if util.cursor_on_markdown_link(nil, nil, true) then
-- Get the client to check settings
local client = require("obsidian").get_client()
if client and client.opts and client.opts.mappings and client.opts.mappings.save_on_nav then
-- Before following the link, save the current buffer
-- This ensures any new links in the current file are written to disk
if vim.api.nvim_buf_get_option(0, "modified") then
-- Schedule the save to avoid BufWritePre issues
vim.schedule(function()
vim.cmd "write"
end)
end
end

return "<cmd>ObsidianFollowLink<CR>"
end

Expand Down
Loading