{"repo_name": "obsidian.nvim", "file_name": "/obsidian.nvim/lua/obsidian/commands/links.lua", "inference_info": {"prefix_code": "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local picker = Obsidian.picker\n if not picker then\n return log.err \"No picker configured\"\n end\n\n local note = api.current_note(0)\n assert(note, \"not in a note\")\n\n search.find_links(note, {}, ", "suffix_code": ")\nend\n", "middle_code": "function(entries)\n entries = vim.tbl_map(function(match)\n return match.link\n end, entries)\n picker:pick(entries, {\n prompt_title = \"Links\",\n callback = function(link)\n api.follow_link(link)\n end,\n })\n end", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/obsidian.nvim/lua/obsidian/commands/backlinks.lua", "local util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal RefTypes = require(\"obsidian.search\").RefTypes\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param note obsidian.Note\n---@param opts { anchor: string|?, block: string|? }|?\nlocal function collect_backlinks(client, picker, note, opts)\n opts = opts or {}\n\n client:find_backlinks_async(note, function(backlinks)\n if vim.tbl_isempty(backlinks) then\n if opts.anchor then\n log.info(\"No backlinks found for anchor '%s' in note '%s'\", opts.anchor, note.id)\n elseif opts.block then\n log.info(\"No backlinks found for block '%s' in note '%s'\", opts.block, note.id)\n else\n log.info(\"No backlinks found for note '%s'\", note.id)\n end\n return\n end\n\n local entries = {}\n for _, matches in ipairs(backlinks) do\n for _, match in ipairs(matches.matches) do\n entries[#entries + 1] = {\n value = { path = matches.path, line = match.line },\n filename = tostring(matches.path),\n lnum = match.line,\n }\n end\n end\n\n ---@type string\n local prompt_title\n if opts.anchor then\n prompt_title = string.format(\"Backlinks to '%s%s'\", note.id, opts.anchor)\n elseif opts.block then\n prompt_title = string.format(\"Backlinks to '%s#%s'\", note.id, util.standardize_block(opts.block))\n else\n prompt_title = string.format(\"Backlinks to '%s'\", note.id)\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = prompt_title,\n callback = function(value)\n api.open_buffer(value.path, { line = value.line })\n end,\n })\n end)\n end, { search = { sort = true }, anchor = opts.anchor, block = opts.block })\nend\n\n---@param client obsidian.Client\nreturn function(client)\n local picker = assert(Obsidian.picker)\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local cur_link, link_type = api.cursor_link()\n\n if\n cur_link ~= nil\n and link_type ~= RefTypes.NakedUrl\n and link_type ~= RefTypes.FileUrl\n and link_type ~= RefTypes.BlockID\n then\n local location = util.parse_link(cur_link, { include_block_ids = true })\n assert(location, \"cursor on a link but failed to parse, please report to repo\")\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n location = vim.api.nvim_buf_get_name(0)\n end\n\n local opts = { anchor = anchor_link, block = block_link }\n\n search.resolve_note_async(location, function(...)\n ---@type obsidian.Note[]\n local notes = { ... }\n\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", location)\n return\n elseif #notes == 1 then\n return collect_backlinks(client, picker, notes[1], opts)\n else\n return vim.schedule(function()\n picker:pick_note(notes, {\n prompt_title = \"Select note\",\n callback = function(note)\n collect_backlinks(client, picker, note, opts)\n end,\n })\n end)\n end\n end)\n else\n ---@type { anchor: string|?, block: string|? }\n local opts = {}\n ---@type obsidian.note.LoadOpts\n local load_opts = {}\n\n if cur_link and link_type == RefTypes.BlockID then\n opts.block = util.parse_link(cur_link, { include_block_ids = true })\n else\n load_opts.collect_anchor_links = true\n end\n\n local note = api.current_note(0, load_opts)\n\n -- Check if cursor is on a header, if so and header parsing is enabled, use that anchor.\n if Obsidian.opts.backlinks.parse_headers then\n local header_match = util.parse_header(vim.api.nvim_get_current_line())\n if header_match then\n opts.anchor = header_match.anchor\n end\n end\n\n if note == nil then\n log.err \"Current buffer does not appear to be a note inside the vault\"\n else\n collect_backlinks(client, picker, note, opts)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/pickers/picker.lua", "local abc = require \"obsidian.abc\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal strings = require \"plenary.strings\"\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---@class obsidian.Picker : obsidian.ABC\n---\n---@field calling_bufnr integer\nlocal Picker = abc.new_class()\n\nPicker.new = function()\n local self = Picker.init()\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n return self\nend\n\n-------------------------------------------------------------------\n--- Abstract methods that need to be implemented by subclasses. ---\n-------------------------------------------------------------------\n\n---@class obsidian.PickerMappingOpts\n---\n---@field desc string\n---@field callback fun(...)\n---@field fallback_to_query boolean|?\n---@field keep_open boolean|?\n---@field allow_multiple boolean|?\n\n---@alias obsidian.PickerMappingTable table\n\n---@class obsidian.PickerFindOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Find files in a directory.\n---\n---@param opts obsidian.PickerFindOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `callback`: Callback to run with the selected entry.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.find_files = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerGrepOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field query string|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable\n---@field selection_mappings obsidian.PickerMappingTable\n\n--- Grep for a string.\n---\n---@param opts obsidian.PickerGrepOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.grep = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerEntry\n---\n---@field value any\n---@field ordinal string|?\n---@field display string|?\n---@field filename string|?\n---@field valid boolean|?\n---@field lnum integer|?\n---@field col integer|?\n---@field icon string|?\n---@field icon_hl string|?\n\n---@class obsidian.PickerPickOpts\n---\n---@field prompt_title string|?\n---@field callback fun(value: any, ...: any)|?\n---@field allow_multiple boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Pick from a list of items.\n---\n---@param values string[]|obsidian.PickerEntry[] Items to pick from.\n---@param opts obsidian.PickerPickOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected item(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.pick = function(self, values, opts)\n error \"not implemented\"\nend\n\n------------------------------------------------------------------\n--- Concrete methods with a default implementation subclasses. ---\n------------------------------------------------------------------\n\n--- Find notes by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.find_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Notes\",\n dir = Obsidian.dir,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Find templates by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string) }|? Options.\n---\n--- Options:\n--- `callback`: Callback to run with the selected template path.\nPicker.find_templates = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local templates_dir = api.templates_dir()\n\n if templates_dir == nil then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Templates\",\n callback = opts.callback,\n dir = templates_dir,\n no_default_mappings = true,\n }\nend\n\n--- Grep search in notes.\n---\n---@param opts { prompt_title: string|?, query: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.grep_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n self:grep {\n prompt_title = opts.prompt_title or \"Grep notes\",\n dir = Obsidian.dir,\n query = opts.query,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Open picker with a list of notes.\n---\n---@param notes obsidian.Note[]\n---@param opts { prompt_title: string|?, callback: fun(note: obsidian.Note, ...: obsidian.Note), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_note = function(self, notes, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n -- Launch picker with results.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, note in ipairs(notes) do\n assert(note.path)\n local rel_path = assert(note.path:vault_relative_path { strict = true })\n local display_name = note:display_name()\n entries[#entries + 1] = {\n value = note,\n display = display_name,\n ordinal = rel_path .. \" \" .. display_name,\n filename = tostring(note.path),\n }\n end\n\n self:pick(entries, {\n prompt_title = opts.prompt_title or \"Notes\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--- Open picker with a list of tags.\n---\n---@param tags string[]\n---@param opts { prompt_title: string|?, callback: fun(tag: string, ...: string), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected tag(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_tag = function(self, tags, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local selection_mappings\n if not opts.no_default_mappings then\n selection_mappings = self:_tag_selection_mappings()\n end\n\n self:pick(tags, {\n prompt_title = opts.prompt_title or \"Tags\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--------------------------------\n--- Concrete helper methods. ---\n--------------------------------\n\n---@param key string|?\n---@return boolean\nlocal function key_is_set(key)\n if key ~= nil and string.len(key) > 0 then\n return true\n else\n return false\n end\nend\n\n--- Get query mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_query_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.new) then\n mappings[Obsidian.opts.picker.note_mappings.new] = {\n desc = \"new\",\n callback = function(query)\n ---@diagnostic disable-next-line: missing-fields\n require \"obsidian.commands.new\"(require(\"obsidian\").get_client(), { args = query })\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.insert_link) then\n mappings[Obsidian.opts.picker.note_mappings.insert_link] = {\n desc = \"insert link\",\n callback = function(note_or_path)\n ---@type obsidian.Note\n local note\n if Note.is_note_obj(note_or_path) then\n note = note_or_path\n else\n note = Note.from_file(note_or_path)\n end\n local link = api.format_link(note, {})\n vim.api.nvim_put({ link }, \"\", false, true)\n require(\"obsidian.ui\").update(0)\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `pick_tag()`.\n---@return obsidian.PickerMappingTable\nPicker._tag_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.tag_mappings then\n if key_is_set(Obsidian.opts.picker.tag_mappings.tag_note) then\n mappings[Obsidian.opts.picker.tag_mappings.tag_note] = {\n desc = \"tag note\",\n callback = function(...)\n local tags = { ... }\n\n local note = api.current_note(self.calling_bufnr)\n if not note then\n log.warn(\"'%s' is not a note in your workspace\", vim.api.nvim_buf_get_name(self.calling_bufnr))\n return\n end\n\n -- Add the tag and save the new frontmatter to the buffer.\n local tags_added = {}\n local tags_not_added = {}\n for _, tag in ipairs(tags) do\n if note:add_tag(tag) then\n table.insert(tags_added, tag)\n else\n table.insert(tags_not_added, tag)\n end\n end\n\n if #tags_added > 0 then\n if note:update_frontmatter(self.calling_bufnr) then\n log.info(\"Added tags %s to frontmatter\", tags_added)\n else\n log.warn \"Frontmatter unchanged\"\n end\n end\n\n if #tags_not_added > 0 then\n log.warn(\"Note already has tags %s\", tags_not_added)\n end\n end,\n fallback_to_query = true,\n keep_open = true,\n allow_multiple = true,\n }\n end\n\n if key_is_set(Obsidian.opts.picker.tag_mappings.insert_tag) then\n mappings[Obsidian.opts.picker.tag_mappings.insert_tag] = {\n desc = \"insert tag\",\n callback = function(tag)\n vim.api.nvim_put({ \"#\" .. tag }, \"\", false, true)\n end,\n fallback_to_query = true,\n }\n end\n end\n\n return mappings\nend\n\n---@param opts { prompt_title: string, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|? }|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nPicker._build_prompt = function(self, opts)\n opts = opts or {}\n\n ---@type string\n local prompt = opts.prompt_title or \"Find\"\n if string.len(prompt) > 50 then\n prompt = string.sub(prompt, 1, 50) .. \"…\"\n end\n\n prompt = prompt .. \" | confirm\"\n\n if opts.query_mappings then\n local keys = vim.tbl_keys(opts.query_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.query_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n if opts.selection_mappings then\n local keys = vim.tbl_keys(opts.selection_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.selection_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n return prompt\nend\n\n---@param entry obsidian.PickerEntry\n---\n---@return string, { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n---@diagnostic disable-next-line: unused-local\nPicker._make_display = function(self, entry)\n ---@type string\n local display = \"\"\n ---@type { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n local highlights = {}\n\n if entry.filename ~= nil then\n local icon, icon_hl\n if entry.icon then\n icon = entry.icon\n icon_hl = entry.icon_hl\n else\n icon, icon_hl = api.get_icon(entry.filename)\n end\n\n if icon ~= nil then\n display = display .. icon .. \" \"\n if icon_hl ~= nil then\n highlights[#highlights + 1] = { { 0, strings.strdisplaywidth(icon) }, icon_hl }\n end\n end\n\n display = display .. Path.new(entry.filename):vault_relative_path { strict = true }\n\n if entry.lnum ~= nil then\n display = display .. \":\" .. entry.lnum\n\n if entry.col ~= nil then\n display = display .. \":\" .. entry.col\n end\n end\n\n if entry.display ~= nil then\n display = display .. \":\" .. entry.display\n end\n elseif entry.display ~= nil then\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. entry.display\n else\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. tostring(entry.value)\n end\n\n return assert(display), highlights\nend\n\n---@return string[]\nPicker._build_find_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = { sort_by = Obsidian.opts.sort_by, sort_reversed = Obsidian.opts.sort_reversed }\n return search.build_find_cmd(\".\", nil, search_opts)\nend\n\nPicker._build_grep_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = {\n sort_by = Obsidian.opts.sort_by,\n sort_reversed = Obsidian.opts.sort_reversed,\n smart_case = true,\n fixed_strings = true,\n }\n return search.build_grep_cmd(search_opts)\nend\n\nreturn Picker\n"], ["/obsidian.nvim/lua/obsidian/commands/tags.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param tags string[]\nlocal function gather_tag_picker_list(client, picker, tags)\n client:find_tags_async(tags, function(tag_locations)\n -- Format results into picker entries, filtering out results that aren't exact matches or sub-tags.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, tag_loc in ipairs(tag_locations) do\n for _, tag in ipairs(tags) do\n if tag_loc.tag:lower() == tag:lower() or vim.startswith(tag_loc.tag:lower(), tag:lower() .. \"/\") then\n local display = string.format(\"%s [%s] %s\", tag_loc.note:display_name(), tag_loc.line, tag_loc.text)\n entries[#entries + 1] = {\n value = { path = tag_loc.path, line = tag_loc.line, col = tag_loc.tag_start },\n display = display,\n ordinal = display,\n filename = tostring(tag_loc.path),\n lnum = tag_loc.line,\n col = tag_loc.tag_start,\n }\n break\n end\n end\n end\n\n if vim.tbl_isempty(entries) then\n if #tags == 1 then\n log.warn \"Tag not found\"\n else\n log.warn \"Tags not found\"\n end\n return\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = \"#\" .. table.concat(tags, \", #\"),\n callback = function(value)\n api.open_buffer(value.path, { line = value.line, col = value.col })\n end,\n })\n end)\n end, { search = { sort = true } })\nend\n\n---@param client obsidian.Client\n---@param data CommandArgs\nreturn function(client, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local tags = data.fargs or {}\n\n if vim.tbl_isempty(tags) then\n local tag = api.cursor_tag()\n if tag then\n tags = { tag }\n end\n end\n\n if not vim.tbl_isempty(tags) then\n return gather_tag_picker_list(client, picker, util.tbl_unique(tags))\n else\n client:list_tags_async(nil, function(all_tags)\n vim.schedule(function()\n -- Open picker with tags.\n picker:pick_tag(all_tags, {\n callback = function(...)\n gather_tag_picker_list(client, picker, { ... })\n end,\n allow_multiple = true,\n })\n end)\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/api.lua", "local M = {}\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal iter, string, table = vim.iter, string, table\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\n\n---@param dir string | obsidian.Path\n---@return Iter\nM.dir = function(dir)\n dir = tostring(dir)\n local dir_opts = {\n depth = 10,\n skip = function(p)\n return not vim.startswith(p, \".\") and p ~= vim.fs.basename(tostring(M.templates_dir()))\n end,\n follow = true,\n }\n\n return vim\n .iter(vim.fs.dir(dir, dir_opts))\n :filter(function(path)\n return vim.endswith(path, \".md\")\n end)\n :map(function(path)\n return vim.fs.joinpath(dir, path)\n end)\nend\n\n--- Get the templates folder.\n---\n---@return obsidian.Path|?\nM.templates_dir = function(workspace)\n local opts = Obsidian.opts\n\n local Workspace = require \"obsidian.workspace\"\n\n if workspace and workspace ~= Obsidian.workspace then\n opts = Workspace.normalize_opts(workspace)\n end\n\n if opts.templates == nil or opts.templates.folder == nil then\n return nil\n end\n\n local paths_to_check = { Obsidian.workspace.root / opts.templates.folder, Path.new(opts.templates.folder) }\n for _, path in ipairs(paths_to_check) do\n if path:is_dir() then\n return path\n end\n end\n\n log.err_once(\"'%s' is not a valid templates directory\", opts.templates.folder)\n return nil\nend\n\n--- Check if a path represents a note in the workspace.\n---\n---@param path string|obsidian.Path\n---@param workspace obsidian.Workspace|?\n---\n---@return boolean\nM.path_is_note = function(path, workspace)\n path = Path.new(path):resolve()\n workspace = workspace or Obsidian.workspace\n\n local in_vault = path.filename:find(vim.pesc(tostring(workspace.root))) ~= nil\n if not in_vault then\n return false\n end\n\n -- Notes have to be markdown file.\n if path.suffix ~= \".md\" then\n return false\n end\n\n -- Ignore markdown files in the templates directory.\n local templates_dir = M.templates_dir(workspace)\n if templates_dir ~= nil then\n if templates_dir:is_parent_of(path) then\n return false\n end\n end\n\n return true\nend\n\n--- Get the current note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note|?\n---@diagnostic disable-next-line: unused-local\nM.current_note = function(bufnr, opts)\n bufnr = bufnr or 0\n local Note = require \"obsidian.note\"\n if not M.path_is_note(vim.api.nvim_buf_get_name(bufnr)) then\n return nil\n end\n\n opts = opts or {}\n if not opts.max_lines then\n opts.max_lines = Obsidian.opts.search_max_lines\n end\n return Note.from_buffer(bufnr, opts)\nend\n\n---builtin functions that are impure, interacts with editor state, like vim.api\n\n---Toggle the checkbox on the current line.\n---\n---@param states table|nil Optional table containing checkbox states (e.g., {\" \", \"x\"}).\n---@param line_num number|nil Optional line number to toggle the checkbox on. Defaults to the current line.\nM.toggle_checkbox = function(states, line_num)\n if not util.in_node { \"list\", \"paragraph\" } or util.in_node \"block_quote\" then\n return\n end\n line_num = line_num or unpack(vim.api.nvim_win_get_cursor(0))\n local line = vim.api.nvim_buf_get_lines(0, line_num - 1, line_num, false)[1]\n\n local checkboxes = states or { \" \", \"x\" }\n\n if util.is_checkbox(line) then\n for i, check_char in ipairs(checkboxes) do\n if string.match(line, \"^.* %[\" .. vim.pesc(check_char) .. \"%].*\") then\n i = i % #checkboxes\n line = string.gsub(line, vim.pesc(\"[\" .. check_char .. \"]\"), \"[\" .. checkboxes[i + 1] .. \"]\", 1)\n break\n end\n end\n elseif Obsidian.opts.checkbox.create_new then\n local unordered_list_pattern = \"^(%s*)[-*+] (.*)\"\n if string.match(line, unordered_list_pattern) then\n line = string.gsub(line, unordered_list_pattern, \"%1- [ ] %2\")\n else\n line = string.gsub(line, \"^(%s*)\", \"%1- [ ] \")\n end\n else\n goto out\n end\n\n vim.api.nvim_buf_set_lines(0, line_num - 1, line_num, true, { line })\n ::out::\nend\n\n---@return [number, number, number, number] tuple containing { buf, win, row, col }\nM.get_active_window_cursor_location = function()\n local buf = vim.api.nvim_win_get_buf(0)\n local win = vim.api.nvim_get_current_win()\n local row, col = unpack(vim.api.nvim_win_get_cursor(win))\n local location = { buf, win, row, col }\n return location\nend\n\n--- Create a formatted markdown / wiki link for a note.\n---\n---@param note obsidian.Note|obsidian.Path|string The note/path to link to.\n---@param opts { label: string|?, link_style: obsidian.config.LinkStyle|?, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|? Options.\n---\n---@return string\nM.format_link = function(note, opts)\n local config = require \"obsidian.config\"\n opts = opts or {}\n\n ---@type string, string, string|integer|?\n local rel_path, label, note_id\n if type(note) == \"string\" or Path.is_path_obj(note) then\n ---@cast note string|obsidian.Path\n -- rel_path = tostring(self:vault_relative_path(note, { strict = true }))\n rel_path = assert(Path.new(note):vault_relative_path { strict = true })\n label = opts.label or tostring(note)\n note_id = opts.id\n else\n ---@cast note obsidian.Note\n -- rel_path = tostring(self:vault_relative_path(note.path, { strict = true }))\n rel_path = assert(note.path:vault_relative_path { strict = true })\n label = opts.label or note:display_name()\n note_id = opts.id or note.id\n end\n\n local link_style = opts.link_style\n if link_style == nil then\n link_style = Obsidian.opts.preferred_link_style\n end\n\n local new_opts = { path = rel_path, label = label, id = note_id, anchor = opts.anchor, block = opts.block }\n\n if link_style == config.LinkStyle.markdown then\n return Obsidian.opts.markdown_link_func(new_opts)\n elseif link_style == config.LinkStyle.wiki or link_style == nil then\n return Obsidian.opts.wiki_link_func(new_opts)\n else\n error(string.format(\"Invalid link style '%s'\", link_style))\n end\nend\n\n---Return the full link under cursror\n---\n---@return string? link\n---@return obsidian.search.RefTypes? link_type\nM.cursor_link = function()\n local line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- 0-indexed column to 1-indexed lua string position\n\n local refs = search.find_refs(line, { include_naked_urls = true, include_file_urls = true, include_block_ids = true })\n\n local match = iter(refs):find(function(match)\n local open, close = unpack(match)\n return cur_col >= open and cur_col <= close\n end)\n if match then\n return line:sub(match[1], match[2]), match[3]\n end\nend\n\n---Get the tag under the cursor, if there is one.\n---@return string?\nM.cursor_tag = function()\n local current_line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- nvim_win_get_cursor returns 0-indexed column\n\n for match in iter(search.find_tags(current_line)) do\n local open, close, _ = unpack(match)\n if open <= cur_col and cur_col <= close then\n return string.sub(current_line, open + 1, close)\n end\n end\n\n return nil\nend\n\n--- Get the heading under the cursor, if there is one.\n---@return { header: string, level: integer, anchor: string }|?\nM.cursor_heading = function()\n return util.parse_header(vim.api.nvim_get_current_line())\nend\n\n------------------\n--- buffer api ---\n------------------\n\n--- Check if a buffer is empty.\n---\n---@param bufnr integer|?\n---\n---@return boolean\nM.buffer_is_empty = function(bufnr)\n bufnr = bufnr or 0\n if vim.api.nvim_buf_line_count(bufnr) > 1 then\n return false\n else\n local first_text = vim.api.nvim_buf_get_text(bufnr, 0, 0, 0, 0, {})\n if vim.tbl_isempty(first_text) or first_text[1] == \"\" then\n return true\n else\n return false\n end\n end\nend\n\n--- Open a buffer for the corresponding path.\n---\n---@param path string|obsidian.Path\n---@param opts { line: integer|?, col: integer|?, cmd: string|? }|?\n---@return integer bufnr\nM.open_buffer = function(path, opts)\n path = Path.new(path):resolve()\n opts = opts and opts or {}\n local cmd = vim.trim(opts.cmd and opts.cmd or \"e\")\n\n ---@type integer|?\n local result_bufnr\n\n -- Check for buffer in windows and use 'drop' command if one is found.\n for _, winnr in ipairs(vim.api.nvim_list_wins()) do\n local bufnr = vim.api.nvim_win_get_buf(winnr)\n local bufname = vim.api.nvim_buf_get_name(bufnr)\n if bufname == tostring(path) then\n cmd = \"drop\"\n result_bufnr = bufnr\n break\n end\n end\n\n vim.cmd(string.format(\"%s %s\", cmd, vim.fn.fnameescape(tostring(path))))\n if opts.line then\n vim.api.nvim_win_set_cursor(0, { tonumber(opts.line), opts.col and opts.col or 0 })\n end\n\n if not result_bufnr then\n result_bufnr = vim.api.nvim_get_current_buf()\n end\n\n return result_bufnr\nend\n\n---Get an iterator of (bufnr, bufname) over all named buffers. The buffer names will be absolute paths.\n---\n---@return function () -> (integer, string)|?\nM.get_named_buffers = function()\n local idx = 0\n local buffers = vim.api.nvim_list_bufs()\n\n ---@return integer|?\n ---@return string|?\n return function()\n while idx < #buffers do\n idx = idx + 1\n local bufnr = buffers[idx]\n if vim.api.nvim_buf_is_loaded(bufnr) then\n return bufnr, vim.api.nvim_buf_get_name(bufnr)\n end\n end\n end\nend\n\n----------------\n--- text api ---\n----------------\n\n--- Get the current visual selection of text and exit visual mode.\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return { lines: string[], selection: string, csrow: integer, cscol: integer, cerow: integer, cecol: integer }|?\nM.get_visual_selection = function(opts)\n opts = opts or {}\n -- Adapted from fzf-lua:\n -- https://github.com/ibhagwan/fzf-lua/blob/6ee73fdf2a79bbd74ec56d980262e29993b46f2b/lua/fzf-lua/utils.lua#L434-L466\n -- this will exit visual mode\n -- use 'gv' to reselect the text\n local _, csrow, cscol, cerow, cecol\n local mode = vim.fn.mode()\n if opts.strict and not vim.endswith(string.lower(mode), \"v\") then\n return\n end\n\n if mode == \"v\" or mode == \"V\" or mode == \"\u0016\" then\n -- if we are in visual mode use the live position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \".\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"v\")\n if mode == \"V\" then\n -- visual line doesn't provide columns\n cscol, cecol = 0, 999\n end\n -- exit visual mode\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", true)\n else\n -- otherwise, use the last known visual position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \"'<\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"'>\")\n end\n\n -- Swap vars if needed\n if cerow < csrow then\n csrow, cerow = cerow, csrow\n cscol, cecol = cecol, cscol\n elseif cerow == csrow and cecol < cscol then\n cscol, cecol = cecol, cscol\n end\n\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n if vim.tbl_isempty(lines) then\n return\n end\n\n -- When the whole line is selected via visual line mode (\"V\"), cscol / cecol will be equal to \"v:maxcol\"\n -- for some odd reason. So change that to what they should be here. See ':h getpos' for more info.\n local maxcol = vim.api.nvim_get_vvar \"maxcol\"\n if cscol == maxcol then\n cscol = string.len(lines[1])\n end\n if cecol == maxcol then\n cecol = string.len(lines[#lines])\n end\n\n ---@type string\n local selection\n local n = #lines\n if n <= 0 then\n selection = \"\"\n elseif n == 1 then\n selection = string.sub(lines[1], cscol, cecol)\n elseif n == 2 then\n selection = string.sub(lines[1], cscol) .. \"\\n\" .. string.sub(lines[n], 1, cecol)\n else\n selection = string.sub(lines[1], cscol)\n .. \"\\n\"\n .. table.concat(lines, \"\\n\", 2, n - 1)\n .. \"\\n\"\n .. string.sub(lines[n], 1, cecol)\n end\n\n return {\n lines = lines,\n selection = selection,\n csrow = csrow,\n cscol = cscol,\n cerow = cerow,\n cecol = cecol,\n }\nend\n\n------------------\n--- UI helpers ---\n------------------\n\n---Get the strategy for opening notes\n---\n---@param opt obsidian.config.OpenStrategy\n---@return string\nM.get_open_strategy = function(opt)\n local OpenStrategy = require(\"obsidian.config\").OpenStrategy\n\n -- either 'leaf', 'row' for vertically split windows, or 'col' for horizontally split windows\n local cur_layout = vim.fn.winlayout()[1]\n\n if vim.startswith(OpenStrategy.hsplit, opt) then\n if cur_layout ~= \"col\" then\n return \"split \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit, opt) then\n if cur_layout ~= \"row\" then\n return \"vsplit \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit_force, opt) then\n return \"vsplit \"\n elseif vim.startswith(OpenStrategy.hsplit_force, opt) then\n return \"hsplit \"\n elseif vim.startswith(OpenStrategy.current, opt) then\n return \"e \"\n else\n log.err(\"undefined open strategy '%s'\", opt)\n return \"e \"\n end\nend\n\n----------------------------\n--- Integration helpers ----\n----------------------------\n\n--- Get the path to where a plugin is installed.\n---\n---@param name string\n---@return string|?\nlocal get_src_root = function(name)\n return vim.iter(vim.api.nvim_list_runtime_paths()):find(function(path)\n return vim.endswith(path, name)\n end)\nend\n\n--- Get info about a plugin.\n---\n---@param name string\n---\n---@return { commit: string|?, path: string }|?\nM.get_plugin_info = function(name)\n local src_root = get_src_root(name)\n if not src_root then\n return\n end\n local out = { path = src_root }\n local obj = vim.system({ \"git\", \"rev-parse\", \"HEAD\" }, { cwd = src_root }):wait(1000)\n if obj.code == 0 then\n out.commit = vim.trim(obj.stdout)\n else\n out.commit = \"unknown\"\n end\n return out\nend\n\n--- Get info about a external dependency.\n---\n---@param cmd string\n---@return string|?\nM.get_external_dependency_info = function(cmd)\n local obj = vim.system({ cmd, \"--version\" }, {}):wait(1000)\n if obj.code ~= 0 then\n return\n end\n local version = vim.version.parse(obj.stdout)\n if version then\n return (\"%d.%d.%d\"):format(version.major, version.minor, version.patch)\n end\nend\n\n------------------\n--- UI helpers ---\n------------------\n\nlocal INPUT_CANCELLED = \"~~~INPUT-CANCELLED~~~\"\n\n--- Prompt user for an input. Returns nil if canceled, otherwise a string (possibly empty).\n---\n---@param prompt string\n---@param opts { completion: string|?, default: string|? }|?\n---\n---@return string|?\nM.input = function(prompt, opts)\n opts = opts or {}\n\n if not vim.endswith(prompt, \" \") then\n prompt = prompt .. \" \"\n end\n\n local input = vim.trim(\n vim.fn.input { prompt = prompt, completion = opts.completion, default = opts.default, cancelreturn = INPUT_CANCELLED }\n )\n\n if input ~= INPUT_CANCELLED then\n return input\n else\n return nil\n end\nend\n\n--- Prompt user for a confirmation.\n---\n---@param prompt string\n---\n---@return boolean\nM.confirm = function(prompt)\n if not vim.endswith(util.rstrip_whitespace(prompt), \"[Y/n]\") then\n prompt = util.rstrip_whitespace(prompt) .. \" [Y/n] \"\n end\n\n local confirmation = M.input(prompt)\n if confirmation == nil then\n return false\n end\n\n confirmation = string.lower(confirmation)\n\n if confirmation == \"\" or confirmation == \"y\" or confirmation == \"yes\" then\n return true\n else\n return false\n end\nend\n\n---@enum OSType\nM.OSType = {\n Linux = \"Linux\",\n Wsl = \"Wsl\",\n Windows = \"Windows\",\n Darwin = \"Darwin\",\n FreeBSD = \"FreeBSD\",\n}\n\nM._current_os = nil\n\n---Get the running operating system.\n---Reference https://vi.stackexchange.com/a/2577/33116\n---@return OSType\nM.get_os = function()\n if M._current_os ~= nil then\n return M._current_os\n end\n\n local this_os\n if vim.fn.has \"win32\" == 1 then\n this_os = M.OSType.Windows\n else\n local sysname = vim.uv.os_uname().sysname\n local release = vim.uv.os_uname().release:lower()\n if sysname:lower() == \"linux\" and string.find(release, \"microsoft\") then\n this_os = M.OSType.Wsl\n else\n this_os = sysname\n end\n end\n\n assert(this_os)\n M._current_os = this_os\n return this_os\nend\n\n--- Get a nice icon for a file or URL, if possible.\n---\n---@param path string\n---\n---@return string|?, string|? (icon, hl_group) The icon and highlight group.\nM.get_icon = function(path)\n if util.is_url(path) then\n local icon = \"\"\n local _, hl_group = M.get_icon \"blah.html\"\n return icon, hl_group\n else\n local ok, res = pcall(function()\n local icon, hl_group = require(\"nvim-web-devicons\").get_icon(path, nil, { default = true })\n return { icon, hl_group }\n end)\n if ok and type(res) == \"table\" then\n local icon, hlgroup = unpack(res)\n return icon, hlgroup\n elseif vim.endswith(path, \".md\") then\n return \"\"\n end\n end\n return nil\nend\n\n--- Resolve a basename to full path inside the vault.\n---\n---@param src string\n---@return string\nM.resolve_image_path = function(src)\n local img_folder = Obsidian.opts.attachments.img_folder\n\n ---@cast img_folder -nil\n if vim.startswith(img_folder, \".\") then\n local dirname = Path.new(vim.fs.dirname(vim.api.nvim_buf_get_name(0)))\n return tostring(dirname / img_folder / src)\n else\n return tostring(Obsidian.dir / img_folder / src)\n end\nend\n\n--- Follow a link. If the link argument is `nil` we attempt to follow a link under the cursor.\n---\n---@param link string\n---@param opts { open_strategy: obsidian.config.OpenStrategy|? }|?\nM.follow_link = function(link, opts)\n opts = opts and opts or {}\n local Note = require \"obsidian.note\"\n\n search.resolve_link_async(link, function(results)\n if #results == 0 then\n return\n end\n\n ---@param res obsidian.ResolveLinkResult\n local function follow_link(res)\n if res.url ~= nil then\n Obsidian.opts.follow_url_func(res.url)\n return\n end\n\n if util.is_img(res.location) then\n local path = Obsidian.dir / res.location\n Obsidian.opts.follow_img_func(tostring(path))\n return\n end\n\n if res.note ~= nil then\n -- Go to resolved note.\n return res.note:open { line = res.line, col = res.col, open_strategy = opts.open_strategy }\n end\n\n if res.link_type == search.RefTypes.Wiki or res.link_type == search.RefTypes.WikiWithAlias then\n -- Prompt to create a new note.\n if M.confirm(\"Create new note '\" .. res.location .. \"'?\") then\n -- Create a new note.\n ---@type string|?, string[]\n local id, aliases\n if res.name == res.location then\n aliases = {}\n else\n aliases = { res.name }\n id = res.location\n end\n\n local note = Note.create { title = res.name, id = id, aliases = aliases }\n return note:open {\n open_strategy = opts.open_strategy,\n callback = function(bufnr)\n note:write_to_buffer { bufnr = bufnr }\n end,\n }\n else\n log.warn \"Aborted\"\n return\n end\n end\n\n return log.err(\"Failed to resolve file '\" .. res.location .. \"'\")\n end\n\n if #results == 1 then\n return vim.schedule(function()\n follow_link(results[1])\n end)\n else\n return vim.schedule(function()\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple matches to '%s', but no picker is configured\", link)\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, res in ipairs(results) do\n local icon, icon_hl\n if res.url ~= nil then\n icon, icon_hl = M.get_icon(res.url)\n end\n table.insert(entries, {\n value = res,\n display = res.name,\n filename = res.path and tostring(res.path) or nil,\n icon = icon,\n icon_hl = icon_hl,\n })\n end\n\n picker:pick(entries, {\n prompt_title = \"Follow link\",\n callback = function(res)\n follow_link(res)\n end,\n })\n end)\n end\n end)\nend\n--------------------------\n---- Mapping functions ---\n--------------------------\n\n---@param direction \"next\" | \"prev\"\nM.nav_link = function(direction)\n vim.validate(\"direction\", direction, \"string\", false, \"nav_link must be called with a direction\")\n local cursor_line, cursor_col = unpack(vim.api.nvim_win_get_cursor(0))\n local Note = require \"obsidian.note\"\n\n search.find_links(Note.from_buffer(0), {}, function(matches)\n if direction == \"next\" then\n for i = 1, #matches do\n local match = matches[i]\n if (match.line > cursor_line) or (cursor_line == match.line and cursor_col < match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n\n if direction == \"prev\" then\n for i = #matches, 1, -1 do\n local match = matches[i]\n if (match.line < cursor_line) or (cursor_line == match.line and cursor_col > match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n end)\nend\n\nM.smart_action = function()\n local legacy = Obsidian.opts.legacy_commands\n -- follow link if possible\n if M.cursor_link() then\n return legacy and \"ObsidianFollowLink\" or \"Obsidian follow_link\"\n end\n\n -- show notes with tag if possible\n if M.cursor_tag() then\n return legacy and \"ObsidianTags\" or \"Obsidian tags\"\n end\n\n if M.cursor_heading() then\n return \"za\"\n end\n\n -- toggle task if possible\n -- cycles through your custom UI checkboxes, default: [ ] [~] [>] [x]\n return legacy and \"ObsidianToggleCheckbox\" or \"Obsidian toggle_checkbox\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/search.lua", "local Path = require \"obsidian.path\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\nlocal run_job_async = require(\"obsidian.async\").run_job_async\nlocal compat = require \"obsidian.compat\"\nlocal log = require \"obsidian.log\"\nlocal block_on = require(\"obsidian.async\").block_on\n\nlocal M = {}\n\nM._BASE_CMD = { \"rg\", \"--no-config\", \"--type=md\" }\nM._SEARCH_CMD = compat.flatten { M._BASE_CMD, \"--json\" }\nM._FIND_CMD = compat.flatten { M._BASE_CMD, \"--files\" }\n\n---@enum obsidian.search.RefTypes\nM.RefTypes = {\n WikiWithAlias = \"WikiWithAlias\",\n Wiki = \"Wiki\",\n Markdown = \"Markdown\",\n NakedUrl = \"NakedUrl\",\n FileUrl = \"FileUrl\",\n MailtoUrl = \"MailtoUrl\",\n Tag = \"Tag\",\n BlockID = \"BlockID\",\n Highlight = \"Highlight\",\n}\n\n---@enum obsidian.search.Patterns\nM.Patterns = {\n -- Tags\n TagCharsOptional = \"[A-Za-z0-9_/-]*\",\n TagCharsRequired = \"[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\", -- assumes tag is at least 2 chars\n Tag = \"#[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\",\n\n -- Miscellaneous\n Highlight = \"==[^=]+==\", -- ==text==\n\n -- References\n WikiWithAlias = \"%[%[[^][%|]+%|[^%]]+%]%]\", -- [[xxx|yyy]]\n Wiki = \"%[%[[^][%|]+%]%]\", -- [[xxx]]\n Markdown = \"%[[^][]+%]%([^%)]+%)\", -- [yyy](xxx)\n NakedUrl = \"https?://[a-zA-Z0-9._-@]+[a-zA-Z0-9._#/=&?:+%%-@]+[a-zA-Z0-9/]\", -- https://xyz.com\n FileUrl = \"file:/[/{2}]?.*\", -- file:///\n MailtoUrl = \"mailto:.*\", -- mailto:emailaddress\n BlockID = util.BLOCK_PATTERN .. \"$\", -- ^hello-world\n}\n\n---@type table\nM.PatternConfig = {\n [M.RefTypes.Tag] = { ignore_if_escape_prefix = true },\n}\n\n--- Find all matches of a pattern\n---\n---@param s string\n---@param pattern_names obsidian.search.RefTypes[]\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_matches = function(s, pattern_names)\n -- First find all inline code blocks so we can skip reference matches inside of those.\n local inline_code_blocks = {}\n for m_start, m_end in util.gfind(s, \"`[^`]*`\") do\n inline_code_blocks[#inline_code_blocks + 1] = { m_start, m_end }\n end\n\n local matches = {}\n for pattern_name in iter(pattern_names) do\n local pattern = M.Patterns[pattern_name]\n local pattern_cfg = M.PatternConfig[pattern_name]\n local search_start = 1\n while search_start < #s do\n local m_start, m_end = string.find(s, pattern, search_start)\n if m_start ~= nil and m_end ~= nil then\n -- Check if we're inside a code block.\n local inside_code_block = false\n for code_block_boundary in iter(inline_code_blocks) do\n if code_block_boundary[1] < m_start and m_end < code_block_boundary[2] then\n inside_code_block = true\n break\n end\n end\n\n if not inside_code_block then\n -- Check if this match overlaps with any others (e.g. a naked URL match would be contained in\n -- a markdown URL).\n local overlap = false\n for match in iter(matches) do\n if (match[1] <= m_start and m_start <= match[2]) or (match[1] <= m_end and m_end <= match[2]) then\n overlap = true\n break\n end\n end\n\n -- Check if we should skip to an escape sequence before the pattern.\n local skip_due_to_escape = false\n if\n pattern_cfg ~= nil\n and pattern_cfg.ignore_if_escape_prefix\n and string.sub(s, m_start - 1, m_start - 1) == [[\\]]\n then\n skip_due_to_escape = true\n end\n\n if not overlap and not skip_due_to_escape then\n matches[#matches + 1] = { m_start, m_end, pattern_name }\n end\n end\n\n search_start = m_end\n else\n break\n end\n end\n end\n\n -- Sort results by position.\n table.sort(matches, function(a, b)\n return a[1] < b[1]\n end)\n\n return matches\nend\n\n--- Find inline highlights\n---\n---@param s string\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_highlight = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Highlight })) do\n -- Remove highlights that begin/end with whitespace\n local match_start, match_end, _ = unpack(match)\n local text = string.sub(s, match_start + 2, match_end - 2)\n if vim.trim(text) == text then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n---@class obsidian.search.FindRefsOpts\n---\n---@field include_naked_urls boolean|?\n---@field include_tags boolean|?\n---@field include_file_urls boolean|?\n---@field include_block_ids boolean|?\n\n--- Find refs and URLs.\n---@param s string the string to search\n---@param opts obsidian.search.FindRefsOpts|?\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_refs = function(s, opts)\n opts = opts and opts or {}\n\n local pattern_names = { M.RefTypes.WikiWithAlias, M.RefTypes.Wiki, M.RefTypes.Markdown }\n if opts.include_naked_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.NakedUrl\n end\n if opts.include_tags then\n pattern_names[#pattern_names + 1] = M.RefTypes.Tag\n end\n if opts.include_file_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.FileUrl\n end\n if opts.include_block_ids then\n pattern_names[#pattern_names + 1] = M.RefTypes.BlockID\n end\n\n return M.find_matches(s, pattern_names)\nend\n\n--- Find all tags in a string.\n---@param s string the string to search\n---\n---@return {[1]: integer, [2]: integer, [3]: obsidian.search.RefTypes}[]\nM.find_tags = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Tag })) do\n local st, ed, m_type = unpack(match)\n local match_string = s:sub(st, ed)\n if m_type == M.RefTypes.Tag and not util.is_hex_color(match_string) then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n--- Replace references of the form '[[xxx|xxx]]', '[[xxx]]', or '[xxx](xxx)' with their title.\n---\n---@param s string\n---\n---@return string\nM.replace_refs = function(s)\n local out, _ = string.gsub(s, \"%[%[[^%|%]]+%|([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[%[([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[([^%]]+)%]%([^%)]+%)\", \"%1\")\n return out\nend\n\n--- Find all refs in a string and replace with their titles.\n---\n---@param s string\n--\n---@return string\n---@return table\n---@return string[]\nM.find_and_replace_refs = function(s)\n local pieces = {}\n local refs = {}\n local is_ref = {}\n local matches = M.find_refs(s)\n local last_end = 1\n for _, match in pairs(matches) do\n local m_start, m_end, _ = unpack(match)\n assert(type(m_start) == \"number\")\n if last_end < m_start then\n table.insert(pieces, string.sub(s, last_end, m_start - 1))\n table.insert(is_ref, false)\n end\n local ref_str = string.sub(s, m_start, m_end)\n table.insert(pieces, M.replace_refs(ref_str))\n table.insert(refs, ref_str)\n table.insert(is_ref, true)\n last_end = m_end + 1\n end\n\n local indices = {}\n local length = 0\n for i, piece in ipairs(pieces) do\n local i_end = length + string.len(piece)\n if is_ref[i] then\n table.insert(indices, { length + 1, i_end })\n end\n length = i_end\n end\n\n return table.concat(pieces, \"\"), indices, refs\nend\n\n--- Find all code block boundaries in a list of lines.\n---\n---@param lines string[]\n---\n---@return { [1]: integer, [2]: integer }[]\nM.find_code_blocks = function(lines)\n ---@type { [1]: integer, [2]: integer }[]\n local blocks = {}\n ---@type integer|?\n local start_idx\n for i, line in ipairs(lines) do\n if string.match(line, \"^%s*```.*```%s*$\") then\n table.insert(blocks, { i, i })\n start_idx = nil\n elseif string.match(line, \"^%s*```\") then\n if start_idx ~= nil then\n table.insert(blocks, { start_idx, i })\n start_idx = nil\n else\n start_idx = i\n end\n end\n end\n return blocks\nend\n\n---@class obsidian.search.SearchOpts\n---\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field fixed_strings boolean|?\n---@field ignore_case boolean|?\n---@field smart_case boolean|?\n---@field exclude string[]|? paths to exclude\n---@field max_count_per_file integer|?\n---@field escape_path boolean|?\n---@field include_non_markdown boolean|?\n\nlocal SearchOpts = {}\nM.SearchOpts = SearchOpts\n\nSearchOpts.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\nend\n\n---@param one obsidian.search.SearchOpts|table\n---@param other obsidian.search.SearchOpts|table\n---@return obsidian.search.SearchOpts\nSearchOpts.merge = function(one, other)\n return vim.tbl_extend(\"force\", SearchOpts.as_tbl(one), SearchOpts.as_tbl(other))\nend\n\n---@param opts obsidian.search.SearchOpts\n---@param path string\nSearchOpts.add_exclude = function(opts, path)\n if opts.exclude == nil then\n opts.exclude = {}\n end\n opts.exclude[#opts.exclude + 1] = path\nend\n\n---@param opts obsidian.search.SearchOpts\n---@return string[]\nSearchOpts.to_ripgrep_opts = function(opts)\n local ret = {}\n\n if opts.sort_by ~= nil then\n local sort = \"sortr\" -- default sort is reverse\n if opts.sort_reversed == false then\n sort = \"sort\"\n end\n ret[#ret + 1] = \"--\" .. sort .. \"=\" .. opts.sort_by\n end\n\n if opts.fixed_strings then\n ret[#ret + 1] = \"--fixed-strings\"\n end\n\n if opts.ignore_case then\n ret[#ret + 1] = \"--ignore-case\"\n end\n\n if opts.smart_case then\n ret[#ret + 1] = \"--smart-case\"\n end\n\n if opts.exclude ~= nil then\n assert(type(opts.exclude) == \"table\")\n for path in iter(opts.exclude) do\n ret[#ret + 1] = \"-g!\" .. path\n end\n end\n\n if opts.max_count_per_file ~= nil then\n ret[#ret + 1] = \"-m=\" .. opts.max_count_per_file\n end\n\n return ret\nend\n\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_search_cmd = function(dir, term, opts)\n opts = opts and opts or {}\n\n local search_terms\n if type(term) == \"string\" then\n search_terms = { \"-e\", term }\n else\n search_terms = {}\n for t in iter(term) do\n search_terms[#search_terms + 1] = \"-e\"\n search_terms[#search_terms + 1] = t\n end\n end\n\n local path = tostring(Path.new(dir):resolve { strict = true })\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(path))\n end\n\n return compat.flatten {\n M._SEARCH_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n search_terms,\n path,\n }\nend\n\n--- Build the 'rg' command for finding files.\n---\n---@param path string|?\n---@param term string|?\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_find_cmd = function(path, term, opts)\n opts = opts and opts or {}\n\n local additional_opts = {}\n\n if term ~= nil then\n if opts.include_non_markdown then\n term = \"*\" .. term .. \"*\"\n elseif not vim.endswith(term, \".md\") then\n term = \"*\" .. term .. \"*.md\"\n else\n term = \"*\" .. term\n end\n additional_opts[#additional_opts + 1] = \"-g\"\n additional_opts[#additional_opts + 1] = term\n end\n\n if opts.ignore_case then\n additional_opts[#additional_opts + 1] = \"--glob-case-insensitive\"\n end\n\n if path ~= nil and path ~= \".\" then\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(tostring(path)))\n end\n additional_opts[#additional_opts + 1] = path\n end\n\n return compat.flatten { M._FIND_CMD, SearchOpts.to_ripgrep_opts(opts), additional_opts }\nend\n\n--- Build the 'rg' grep command for pickers.\n---\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_grep_cmd = function(opts)\n opts = opts and opts or {}\n\n return compat.flatten {\n M._BASE_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n \"--column\",\n \"--line-number\",\n \"--no-heading\",\n \"--with-filename\",\n \"--color=never\",\n }\nend\n\n---@class MatchPath\n---\n---@field text string\n\n---@class MatchText\n---\n---@field text string\n\n---@class SubMatch\n---\n---@field match MatchText\n---@field start integer\n---@field end integer\n\n---@class MatchData\n---\n---@field path MatchPath\n---@field lines MatchText\n---@field line_number integer 0-indexed\n---@field absolute_offset integer\n---@field submatches SubMatch[]\n\n--- Search markdown files in a directory for a given term. Each match is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(match: MatchData)\n---@param on_exit fun(exit_code: integer)|?\nM.search_async = function(dir, term, opts, on_match, on_exit)\n local cmd = M.build_search_cmd(dir, term, opts)\n run_job_async(cmd, function(line)\n local data = vim.json.decode(line)\n if data[\"type\"] == \"match\" then\n local match_data = data.data\n on_match(match_data)\n end\n end, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\n--- Find markdown files in a directory matching a given term. Each matching path is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(path: string)\n---@param on_exit fun(exit_code: integer)|?\nM.find_async = function(dir, term, opts, on_match, on_exit)\n local norm_dir = Path.new(dir):resolve { strict = true }\n local cmd = M.build_find_cmd(tostring(norm_dir), term, opts)\n run_job_async(cmd, on_match, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\nlocal search_defualts = {\n sort = false,\n include_templates = false,\n ignore_case = false,\n}\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nlocal _prepare_search_opts = function(opts, additional_opts)\n opts = opts or search_defualts\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n M.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = M.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---@param callback fun(path: obsidian.Path)\n---@param exit_callback fun(paths: obsidian.Path[])\nlocal _search_async = function(term, search_opts, find_opts, callback, exit_callback)\n local found = {}\n local result = {}\n local cmds_done = 0\n\n local function dedup_send(path)\n local key = tostring(path:resolve { strict = true })\n if not found[key] then\n found[key] = true\n result[#result + 1] = path\n callback(path)\n end\n end\n\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text)\n dedup_send(path)\n end\n\n local function on_find_match(path_match)\n local path = Path.new(path_match)\n dedup_send(path)\n end\n\n local function on_exit()\n cmds_done = cmds_done + 1\n if cmds_done == 2 then\n exit_callback(result)\n end\n end\n\n M.search_async(\n Obsidian.dir,\n term,\n _prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n M.find_async(Obsidian.dir, term, _prepare_search_opts(find_opts, { ignore_case = true }), on_find_match, on_exit)\nend\n\n--- An async version of `find_notes()` that runs the callback with an array of all matching notes.\n---\n---@param term string The term to search for\n---@param callback fun(notes: obsidian.Note[])\n---@param opts { search: obsidian.SearchOpts|?, notes: obsidian.note.LoadOpts|? }|?\nM.find_notes_async = function(term, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n\n ---@type table\n local paths = {}\n local num_results = 0\n local err_count = 0\n local first_err\n local first_err_path\n local notes = {}\n local Note = require \"obsidian.note\"\n\n ---@param path obsidian.Path\n local function on_path(path)\n local ok, res = pcall(Note.from_file, path, opts.notes)\n\n if ok then\n num_results = num_results + 1\n paths[tostring(path)] = num_results\n notes[#notes + 1] = res\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n end\n end\n\n local on_exit = function()\n -- Then sort by original order.\n table.sort(notes, function(a, b)\n return paths[tostring(a.path)] < paths[tostring(b.path)]\n end)\n\n -- Check for errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n callback(notes)\n end\n\n _search_async(term, opts.search, nil, on_path, on_exit)\nend\n\nM.find_notes = function(term, opts)\n opts = opts or {}\n opts.timeout = opts.timeout or 1000\n return block_on(function(cb)\n return M.find_notes_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n---@param query string\n---@param callback fun(results: obsidian.Note[])\n---@param opts { notes: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note|?\nlocal _resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n local Note = require \"obsidian.note\"\n\n -- Autocompletion for command args will have this format.\n local note_path, count = string.gsub(query, \"^.*  \", \"\")\n if count > 0 then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n local full_path = Obsidian.dir / note_path\n callback { Note.from_file(full_path, opts.notes) }\n end\n\n -- Query might be a path.\n local fname = query\n if not vim.endswith(fname, \".md\") then\n fname = fname .. \".md\"\n end\n\n local paths_to_check = { Path.new(fname), Obsidian.dir / fname }\n\n if Obsidian.opts.notes_subdir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.notes_subdir / fname\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.daily_notes.folder / fname\n end\n\n if Obsidian.buf_dir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.buf_dir / fname\n end\n\n for _, path in pairs(paths_to_check) do\n if path:is_file() then\n return callback { Note.from_file(path, opts.notes) }\n end\n end\n\n M.find_notes_async(query, function(results)\n local query_lwr = string.lower(query)\n\n -- We'll gather both exact matches (of ID, filename, and aliases) and fuzzy matches.\n -- If we end up with any exact matches, we'll return those. Otherwise we fall back to fuzzy\n -- matches.\n ---@type obsidian.Note[]\n local exact_matches = {}\n ---@type obsidian.Note[]\n local fuzzy_matches = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local reference_ids = note:reference_ids { lowercase = true }\n\n -- Check for exact match.\n if vim.list_contains(reference_ids, query_lwr) then\n table.insert(exact_matches, note)\n else\n -- Fall back to fuzzy match.\n for ref_id in iter(reference_ids) do\n if util.string_contains(ref_id, query_lwr) then\n table.insert(fuzzy_matches, note)\n break\n end\n end\n end\n end\n\n if #exact_matches > 0 then\n return callback(exact_matches)\n else\n return callback(fuzzy_matches)\n end\n end, { search = { sort = true, ignore_case = true }, notes = opts.notes })\nend\n\n--- Resolve a note, opens a picker to choose a single note when there are multiple matches.\n---\n---@param query string\n---@param callback fun(obsidian.Note)\n---@param opts { notes: obsidian.note.LoadOpts|?, prompt_title: string|?, pick: boolean }|?\n---\n---@return obsidian.Note|?\nM.resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.pick = vim.F.if_nil(opts.pick, true)\n\n _resolve_note_async(query, function(notes)\n if opts.pick then\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", query)\n return\n elseif #notes == 1 then\n return callback(notes[1])\n end\n\n -- Fall back to picker.\n vim.schedule(function()\n -- Otherwise run the preferred picker to search for notes.\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple notes matching '%s', but no picker is configured\", query)\n return\n end\n\n picker:pick_note(notes, {\n prompt_title = opts.prompt_title,\n callback = callback,\n })\n end)\n else\n callback(notes)\n end\n end, { notes = opts.notes })\nend\n\n---@class obsidian.ResolveLinkResult\n---\n---@field location string\n---@field name string\n---@field link_type obsidian.search.RefTypes\n---@field path obsidian.Path|?\n---@field note obsidian.Note|?\n---@field url string|?\n---@field line integer|?\n---@field col integer|?\n---@field anchor obsidian.note.HeaderAnchor|?\n---@field block obsidian.note.Block|?\n\n--- Resolve a link.\n---\n---@param link string\n---@param callback fun(results: obsidian.ResolveLinkResult[])\nM.resolve_link_async = function(link, callback)\n local Note = require \"obsidian.note\"\n\n local location, name, link_type\n location, name, link_type = util.parse_link(link, { include_naked_urls = true, include_file_urls = true })\n\n if location == nil or name == nil or link_type == nil then\n return callback {}\n end\n\n ---@type obsidian.ResolveLinkResult\n local res = { location = location, name = name, link_type = link_type }\n\n if util.is_url(location) then\n res.url = location\n return callback { res }\n end\n\n -- The Obsidian app will follow URL-encoded links, so we should to.\n location = vim.uri_decode(location)\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n --- Finalize the `obsidian.ResolveLinkResult` for a note while resolving block or anchor link to line.\n ---\n ---@param note obsidian.Note\n ---@return obsidian.ResolveLinkResult\n local function finalize_result(note)\n ---@type integer|?, obsidian.note.Block|?, obsidian.note.HeaderAnchor|?\n local line, block_match, anchor_match\n if block_link ~= nil then\n block_match = note:resolve_block(block_link)\n if block_match then\n line = block_match.line\n end\n elseif anchor_link ~= nil then\n anchor_match = note:resolve_anchor_link(anchor_link)\n if anchor_match then\n line = anchor_match.line\n end\n end\n\n return vim.tbl_extend(\n \"force\",\n res,\n { path = note.path, note = note, line = line, block = block_match, anchor = anchor_match }\n )\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = anchor_link and true or false,\n collect_blocks = block_link and true or false,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n res.location = vim.api.nvim_buf_get_name(0)\n local note = Note.from_buffer(0, load_opts)\n return callback { finalize_result(note) }\n end\n\n res.location = location\n\n M.resolve_note_async(location, function(notes)\n if #notes == 0 then\n local path = Path.new(location)\n if path:exists() then\n res.path = path\n return callback { res }\n else\n return callback { res }\n end\n end\n\n local matches = {}\n for _, note in ipairs(notes) do\n table.insert(matches, finalize_result(note))\n end\n\n return callback(matches)\n end, { notes = load_opts, pick = false })\nend\n\n---@class obsidian.LinkMatch\n---@field link string\n---@field line integer\n---@field start integer 0-indexed\n---@field end integer 0-indexed\n\n-- Gather all unique links from the a note.\n--\n---@param note obsidian.Note\n---@param opts { on_match: fun(link: obsidian.LinkMatch) }\n---@param callback fun(links: obsidian.LinkMatch[])\nM.find_links = function(note, opts, callback)\n ---@type obsidian.LinkMatch[]\n local matches = {}\n ---@type table\n local found = {}\n local lines = io.lines(tostring(note.path))\n\n for lnum, line in util.enumerate(lines) do\n for ref_match in vim.iter(M.find_refs(line, { include_naked_urls = true, include_file_urls = true })) do\n local m_start, m_end = unpack(ref_match)\n local link = string.sub(line, m_start, m_end)\n if not found[link] then\n local match = {\n link = link,\n line = lnum,\n start = m_start - 1,\n [\"end\"] = m_end - 1,\n }\n matches[#matches + 1] = match\n found[link] = true\n if opts.on_match then\n opts.on_match(match)\n end\n end\n end\n end\n\n callback(matches)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/_snacks.lua", "local snacks_picker = require \"snacks.picker\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\nlocal function debug_once(msg, ...)\n -- vim.notify(msg .. vim.inspect(...))\nend\n\n---@param mapping table\n---@return table\nlocal function notes_mappings(mapping)\n if type(mapping) == \"table\" then\n local opts = { win = { input = { keys = {} } }, actions = {} }\n for k, v in pairs(mapping) do\n local name = string.gsub(v.desc, \" \", \"_\")\n opts.win.input.keys = {\n [k] = { name, mode = { \"n\", \"i\" }, desc = v.desc },\n }\n opts.actions[name] = function(picker, item)\n debug_once(\"mappings :\", item)\n picker:close()\n vim.schedule(function()\n v.callback(item.value or item._path)\n end)\n end\n end\n return opts\n end\n return {}\nend\n\n---@class obsidian.pickers.SnacksPicker : obsidian.Picker\nlocal SnacksPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"SnacksPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nSnacksPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"files\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"find files callback: \", item)\n opts.callback(item._path)\n else\n debug_once(\"find files jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nSnacksPicker.grep = function(self, opts)\n opts = opts or {}\n\n debug_once(\"grep opts : \", opts)\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"grep\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"grep callback: \", item)\n opts.callback(item._path or item.filename)\n else\n debug_once(\"grep jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nSnacksPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n debug_once(\"pick opts: \", opts)\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n table.insert(entries, {\n text = value,\n value = value,\n })\n elseif value.valid ~= false then\n local name = self:_make_display(value)\n table.insert(entries, {\n text = name,\n buf = self.calling_bufnr,\n filename = value.filename,\n value = value.value,\n pos = { value.lnum, value.col or 0 },\n })\n end\n end\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n tilte = opts.prompt_title,\n items = entries,\n layout = {\n preview = false,\n },\n format = \"text\",\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"pick callback: \", item)\n opts.callback(item.value)\n else\n debug_once(\"pick jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n\n snacks_picker.pick(pick_opts)\nend\n\nreturn SnacksPicker\n"], ["/obsidian.nvim/lua/obsidian/pickers/_telescope.lua", "local telescope = require \"telescope.builtin\"\nlocal telescope_actions = require \"telescope.actions\"\nlocal actions_state = require \"telescope.actions.state\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.pickers.TelescopePicker : obsidian.Picker\nlocal TelescopePicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"TelescopePicker()\"\n end,\n}, Picker)\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@return table|?\nlocal function get_entry(prompt_bufnr, keep_open)\n local entry = actions_state.get_selected_entry()\n if entry and not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return entry\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param allow_multiple boolean|?\n---@return table[]|?\nlocal function get_selected(prompt_bufnr, keep_open, allow_multiple)\n local picker = actions_state.get_current_picker(prompt_bufnr)\n local entries = picker:get_multi_selection()\n if entries and #entries > 0 then\n if #entries > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n\n return entries\n else\n local entry = get_entry(prompt_bufnr, keep_open)\n\n if entry then\n return { entry }\n end\n end\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param initial_query string|?\n---@return string|?\nlocal function get_query(prompt_bufnr, keep_open, initial_query)\n local query = actions_state.get_current_line()\n if not query or string.len(query) == 0 then\n query = initial_query\n end\n if query and string.len(query) > 0 then\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return query\n else\n return nil\n end\nend\n\n---@param opts { entry_key: string|?, callback: fun(path: string)|?, allow_multiple: boolean|?, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|?, initial_query: string|? }\nlocal function attach_picker_mappings(map, opts)\n -- Docs for telescope actions:\n -- https://github.com/nvim-telescope/telescope.nvim/blob/master/lua/telescope/actions/init.lua\n\n local function entry_to_value(entry)\n if opts.entry_key then\n return entry[opts.entry_key]\n else\n return entry\n end\n end\n\n if opts.query_mappings then\n for key, mapping in pairs(opts.query_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local query = get_query(prompt_bufnr, false, opts.initial_query)\n if query then\n mapping.callback(query)\n end\n end)\n end\n end\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, mapping.keep_open, mapping.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n mapping.callback(unpack(values))\n elseif mapping.fallback_to_query then\n local query = get_query(prompt_bufnr, mapping.keep_open)\n if query then\n mapping.callback(query)\n end\n end\n end)\n end\n end\n\n if opts.callback then\n map({ \"i\", \"n\" }, \"\", function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, false, opts.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n opts.callback(unpack(values))\n end\n end)\n end\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nTelescopePicker.find_files = function(self, opts)\n opts = opts or {}\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n telescope.find_files {\n prompt_title = prompt_title,\n cwd = opts.dir and tostring(opts.dir) or tostring(Obsidian.dir),\n find_command = self:_build_find_cmd(),\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nTelescopePicker.grep = function(self, opts)\n opts = opts or {}\n\n local cwd = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n initial_query = opts.query,\n })\n return true\n end\n\n if opts.query and string.len(opts.query) > 0 then\n telescope.grep_string {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n search = opts.query,\n attach_mappings = attach_mappings,\n }\n else\n telescope.live_grep {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n attach_mappings = attach_mappings,\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\nTelescopePicker.pick = function(self, values, opts)\n local pickers = require \"telescope.pickers\"\n local finders = require \"telescope.finders\"\n local conf = require \"telescope.config\"\n local make_entry = require \"telescope.make_entry\"\n\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local picker_opts = {\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"value\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\n\n local displayer = function(entry)\n return self:_make_display(entry.raw)\n end\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local previewer\n if type(values[1]) == \"table\" then\n previewer = conf.values.grep_previewer(picker_opts)\n -- Get theme to use.\n if conf.pickers then\n for _, picker_name in ipairs { \"grep_string\", \"live_grep\", \"find_files\" } do\n local picker_conf = conf.pickers[picker_name]\n if picker_conf and picker_conf.theme then\n picker_opts =\n vim.tbl_extend(\"force\", picker_opts, require(\"telescope.themes\")[\"get_\" .. picker_conf.theme] {})\n break\n end\n end\n end\n end\n\n local make_entry_from_string = make_entry.gen_from_string(picker_opts)\n\n pickers\n .new(picker_opts, {\n prompt_title = prompt_title,\n finder = finders.new_table {\n results = values,\n entry_maker = function(v)\n if type(v) == \"string\" then\n return make_entry_from_string(v)\n else\n local ordinal = v.ordinal\n if ordinal == nil then\n ordinal = \"\"\n if type(v.display) == \"string\" then\n ordinal = ordinal .. v.display\n end\n if v.filename ~= nil then\n ordinal = ordinal .. \" \" .. v.filename\n end\n end\n\n return {\n value = v.value,\n display = displayer,\n ordinal = ordinal,\n filename = v.filename,\n valid = v.valid,\n lnum = v.lnum,\n col = v.col,\n raw = v,\n }\n end\n end,\n },\n sorter = conf.values.generic_sorter(picker_opts),\n previewer = previewer,\n })\n :find()\nend\n\nreturn TelescopePicker\n"], ["/obsidian.nvim/lua/obsidian/commands/dailies.lua", "local log = require \"obsidian.log\"\nlocal daily = require \"obsidian.daily\"\n\n---@param arg string\n---@return number\nlocal function parse_offset(arg)\n if vim.startswith(arg, \"+\") then\n return assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%'\", arg))\n elseif vim.startswith(arg, \"-\") then\n return -assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%s'\", arg))\n else\n return assert(tonumber(arg), string.format(\"invalid offset '%s'\", arg))\n end\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_start = -5\n local offset_end = 0\n\n if data.fargs and #data.fargs > 0 then\n if #data.fargs == 1 then\n local offset = parse_offset(data.fargs[1])\n if offset >= 0 then\n offset_end = offset\n else\n offset_start = offset\n end\n elseif #data.fargs == 2 then\n local offsets = vim.tbl_map(parse_offset, data.fargs)\n table.sort(offsets)\n offset_start = offsets[1]\n offset_end = offsets[2]\n else\n error \":Obsidian dailies expected at most 2 arguments\"\n end\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local dailies = {}\n for offset = offset_end, offset_start, -1 do\n local datetime = os.time() + (offset * 3600 * 24)\n local daily_note_path = daily.daily_note_path(datetime)\n local daily_note_alias = tostring(os.date(Obsidian.opts.daily_notes.alias_format or \"%A %B %-d, %Y\", datetime))\n if offset == 0 then\n daily_note_alias = daily_note_alias .. \" @today\"\n elseif offset == -1 then\n daily_note_alias = daily_note_alias .. \" @yesterday\"\n elseif offset == 1 then\n daily_note_alias = daily_note_alias .. \" @tomorrow\"\n end\n if not daily_note_path:is_file() then\n daily_note_alias = daily_note_alias .. \" ➡️ create\"\n end\n dailies[#dailies + 1] = {\n value = offset,\n display = daily_note_alias,\n ordinal = daily_note_alias,\n filename = tostring(daily_note_path),\n }\n end\n\n picker:pick(dailies, {\n prompt_title = \"Dailies\",\n callback = function(offset)\n local note = daily.daily(offset, {})\n note:open()\n end,\n })\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/toc.lua", "local util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local note = assert(api.current_note(0, { collect_anchor_links = true }))\n\n ---@type obsidian.PickerEntry[]\n local picker_entries = {}\n for _, anchor in pairs(note.anchor_links) do\n local display = string.rep(\"#\", anchor.level) .. \" \" .. anchor.header\n table.insert(\n picker_entries,\n { value = display, display = display, filename = tostring(note.path), lnum = anchor.line }\n )\n end\n\n -- De-duplicate and sort.\n picker_entries = util.tbl_unique(picker_entries)\n table.sort(picker_entries, function(a, b)\n return a.lnum < b.lnum\n end)\n\n local picker = assert(Obsidian.picker)\n picker:pick(picker_entries, { prompt_title = \"Table of Contents\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/refs.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.RefsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field in_buffer_only boolean\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\n---@field block_link string|?\n---@field anchor_link string|?\n---@field new_text_to_option table\nlocal RefsSourceCompletionContext = abc.new_class()\n\nRefsSourceCompletionContext.new = function()\n return RefsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.RefsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal RefsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.RefsSourceBase\nRefsSourceBase.new = function()\n return RefsSourceBase.init()\nend\n\nRefsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = RefsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n completion_context.in_buffer_only = false\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n self:strip_links(cc)\n self:determine_buffer_only_search_scope(cc)\n\n if cc.in_buffer_only then\n local note = api.current_note(0, { collect_anchor_links = true, collect_blocks = true })\n if note then\n self:process_search_results(cc, { note })\n else\n cc.completion_resolve_callback(self.incomplete_response)\n end\n else\n local search_ops = cc.client.search_defaults()\n search_ops.ignore_case = true\n\n search.find_notes_async(cc.search, function(results)\n self:process_search_results(cc, results)\n end, {\n search = search_ops,\n notes = { collect_anchor_links = cc.anchor_link ~= nil, collect_blocks = cc.block_link ~= nil },\n })\n end\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction RefsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\n---Collect matching block links.\n---@param note obsidian.Note\n---@param block_link string?\n---@return obsidian.note.Block[]|?\nfunction RefsSourceBase:collect_matching_blocks(note, block_link)\n ---@type obsidian.note.Block[]|?\n local matching_blocks\n if block_link then\n assert(note.blocks)\n matching_blocks = {}\n for block_id, block_data in pairs(note.blocks) do\n if vim.startswith(\"#\" .. block_id, block_link) then\n table.insert(matching_blocks, block_data)\n end\n end\n\n if #matching_blocks == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_blocks, { id = util.standardize_block(block_link), line = 1 })\n end\n end\n\n return matching_blocks\nend\n\n---Collect matching anchor links.\n---@param note obsidian.Note\n---@param anchor_link string?\n---@return obsidian.note.HeaderAnchor[]?\nfunction RefsSourceBase:collect_matching_anchors(note, anchor_link)\n ---@type obsidian.note.HeaderAnchor[]|?\n local matching_anchors\n if anchor_link then\n assert(note.anchor_links)\n matching_anchors = {}\n for anchor, anchor_data in pairs(note.anchor_links) do\n if vim.startswith(anchor, anchor_link) then\n table.insert(matching_anchors, anchor_data)\n end\n end\n\n if #matching_anchors == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_anchors, { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 })\n end\n end\n\n return matching_anchors\nend\n\n--- Strips block and anchor links from the current search string\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:strip_links(cc)\n cc.search, cc.block_link = util.strip_block_links(cc.search)\n cc.search, cc.anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, we'll match against all block links.\n if not cc.block_link and vim.endswith(cc.search, \"#^\") then\n cc.block_link = \"#^\"\n cc.search = string.sub(cc.search, 1, -3)\n end\n\n -- If anchor link is incomplete, we'll match against all anchor links.\n if not cc.anchor_link and vim.endswith(cc.search, \"#\") then\n cc.anchor_link = \"#\"\n cc.search = string.sub(cc.search, 1, -2)\n end\nend\n\n--- Determines whatever the in_buffer_only should be enabled\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:determine_buffer_only_search_scope(cc)\n if (cc.anchor_link or cc.block_link) and string.len(cc.search) == 0 then\n -- Search over headers/blocks in current buffer only.\n cc.in_buffer_only = true\n end\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param results obsidian.Note[]\nfunction RefsSourceBase:process_search_results(cc, results)\n assert(cc)\n assert(results)\n\n local completion_items = {}\n\n cc.new_text_to_option = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local matching_blocks = self:collect_matching_blocks(note, cc.block_link)\n local matching_anchors = self:collect_matching_anchors(note, cc.anchor_link)\n\n if cc.in_buffer_only then\n self:update_completion_options(cc, nil, nil, matching_anchors, matching_blocks, note)\n else\n -- Collect all valid aliases for the note, including ID, title, and filename.\n ---@type string[]\n local aliases\n if not cc.in_buffer_only then\n aliases = util.tbl_unique { tostring(note.id), note:display_name(), unpack(note.aliases) }\n if note.title ~= nil then\n table.insert(aliases, note.title)\n end\n end\n\n for alias in iter(aliases) do\n self:update_completion_options(cc, alias, nil, matching_anchors, matching_blocks, note)\n local alias_case_matched = util.match_case(cc.search, alias)\n\n if\n alias_case_matched ~= nil\n and alias_case_matched ~= alias\n and not vim.list_contains(note.aliases, alias_case_matched)\n and Obsidian.opts.completion.match_case\n then\n self:update_completion_options(cc, alias_case_matched, nil, matching_anchors, matching_blocks, note)\n end\n end\n\n if note.alt_alias ~= nil then\n self:update_completion_options(cc, note:display_name(), note.alt_alias, matching_anchors, matching_blocks, note)\n end\n end\n end\n\n for _, option in pairs(cc.new_text_to_option) do\n -- TODO: need a better label, maybe just the note's display name?\n ---@type string\n local label\n if cc.ref_type == completion.RefType.Wiki then\n label = string.format(\"[[%s]]\", option.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n label = string.format(\"[%s](…)\", option.label)\n else\n error \"not implemented\"\n end\n\n table.insert(completion_items, {\n documentation = option.documentation,\n sortText = option.sort_text,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = option.new_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n })\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = completion_items }))\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param label string|?\n---@param alt_label string|?\n---@param note obsidian.Note\nfunction RefsSourceBase:update_completion_options(cc, label, alt_label, matching_anchors, matching_blocks, note)\n ---@type { label: string|?, alt_label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }[]\n local new_options = {}\n if matching_anchors ~= nil then\n for anchor in iter(matching_anchors) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor })\n end\n elseif matching_blocks ~= nil then\n for block in iter(matching_blocks) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block })\n end\n else\n if label then\n table.insert(new_options, { label = label, alt_label = alt_label })\n end\n\n -- Add all blocks and anchors, let cmp sort it out.\n for _, anchor_data in pairs(note.anchor_links or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor_data })\n end\n for _, block_data in pairs(note.blocks or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block_data })\n end\n end\n\n -- De-duplicate options relative to their `new_text`.\n for _, option in ipairs(new_options) do\n ---@type obsidian.config.LinkStyle\n local link_style\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n else\n error \"not implemented\"\n end\n\n ---@type string, string, string, table|?\n local final_label, sort_text, new_text, documentation\n if option.label then\n new_text = api.format_link(\n note,\n { label = option.label, link_style = link_style, anchor = option.anchor, block = option.block }\n )\n\n final_label = assert(option.alt_label or option.label)\n if option.anchor then\n final_label = final_label .. option.anchor.anchor\n elseif option.block then\n final_label = final_label .. \"#\" .. option.block.id\n end\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = note:display_info {\n label = new_text,\n anchor = option.anchor,\n block = option.block,\n },\n }\n elseif option.anchor then\n -- In buffer anchor link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.anchor.header .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.anchor.header .. \"](\" .. option.anchor.anchor .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = option.anchor.anchor\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n elseif option.block then\n -- In buffer block link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.block.id .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.block.id .. \"](#\" .. option.block.id .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = \"#\" .. option.block.id\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n else\n error \"should not happen\"\n end\n\n if cc.new_text_to_option[new_text] then\n cc.new_text_to_option[new_text].sort_text = cc.new_text_to_option[new_text].sort_text .. \" \" .. sort_text\n else\n cc.new_text_to_option[new_text] =\n { label = final_label, new_text = new_text, sort_text = sort_text, documentation = documentation }\n end\n end\nend\n\nreturn RefsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/pickers/_fzf.lua", "local fzf = require \"fzf-lua\"\nlocal fzf_actions = require \"fzf-lua.actions\"\nlocal entry_to_file = require(\"fzf-lua.path\").entry_to_file\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@param prompt_title string|?\n---@return string|?\nlocal function format_prompt(prompt_title)\n if not prompt_title then\n return\n else\n return prompt_title .. \" ❯ \"\n end\nend\n\n---@param keymap string\n---@return string\nlocal function format_keymap(keymap)\n keymap = string.lower(keymap)\n keymap = string.gsub(keymap, vim.pesc \"\", \"\")\n return keymap\nend\n\n---@class obsidian.pickers.FzfPicker : obsidian.Picker\nlocal FzfPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"FzfPicker()\"\n end,\n}, Picker)\n\n---@param opts { callback: fun(path: string)|?, no_default_mappings: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_path_actions(opts)\n local actions = {\n default = function(selected, fzf_opts)\n if not opts.no_default_mappings then\n fzf_actions.file_edit_or_qf(selected, fzf_opts)\n end\n\n if opts.callback then\n local path = entry_to_file(selected[1], fzf_opts).path\n opts.callback(path)\n end\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected, fzf_opts)\n local path = entry_to_file(selected[1], fzf_opts).path\n mapping.callback(path)\n end\n end\n end\n\n return actions\nend\n\n---@param display_to_value_map table\n---@param opts { callback: fun(path: string)|?, allow_multiple: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_value_actions(display_to_value_map, opts)\n ---@param allow_multiple boolean|?\n ---@return any[]|?\n local function get_values(selected, allow_multiple)\n if not selected then\n return\n end\n\n local values = vim.tbl_map(function(k)\n return display_to_value_map[k]\n end, selected)\n\n values = vim.tbl_filter(function(v)\n return v ~= nil\n end, values)\n\n if #values > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if #values > 0 then\n return values\n else\n return nil\n end\n end\n\n local actions = {\n default = function(selected)\n if not opts.callback then\n return\n end\n\n local values = get_values(selected, opts.allow_multiple)\n if not values then\n return\n end\n\n opts.callback(unpack(values))\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected)\n local values = get_values(selected, mapping.allow_multiple)\n if not values then\n return\n end\n\n mapping.callback(unpack(values))\n end\n end\n end\n\n return actions\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nFzfPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path.new(opts.dir) or Obsidian.dir\n\n fzf.files {\n cwd = tostring(dir),\n cmd = table.concat(self:_build_find_cmd(), \" \"),\n actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n },\n prompt = format_prompt(opts.prompt_title),\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nFzfPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n local cmd = table.concat(self:_build_grep_cmd(), \" \")\n local actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n if opts.query and string.len(opts.query) > 0 then\n fzf.grep {\n cwd = tostring(dir),\n search = opts.query,\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n else\n fzf.live_grep {\n cwd = tostring(dir),\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nFzfPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n ---@type table\n local display_to_value_map = {}\n\n ---@type string[]\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n display_to_value_map[value] = value\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n local display = self:_make_display(value)\n display_to_value_map[display] = value.value\n entries[#entries + 1] = display\n end\n end\n\n fzf.fzf_exec(entries, {\n prompt = format_prompt(\n self:_build_prompt { prompt_title = opts.prompt_title, selection_mappings = opts.selection_mappings }\n ),\n actions = get_value_actions(display_to_value_map, {\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n selection_mappings = opts.selection_mappings,\n }),\n })\nend\n\nreturn FzfPicker\n"], ["/obsidian.nvim/lua/obsidian/client.lua", "--- *obsidian-api*\n---\n--- The Obsidian.nvim Lua API.\n---\n--- ==============================================================================\n---\n--- Table of contents\n---\n---@toc\n\nlocal Path = require \"obsidian.path\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal Note = require \"obsidian.note\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal block_on = require(\"obsidian.async\").block_on\nlocal iter = vim.iter\n\n---@class obsidian.SearchOpts\n---\n---@field sort boolean|?\n---@field include_templates boolean|?\n---@field ignore_case boolean|?\n---@field default function?\n\n--- The Obsidian client is the main API for programmatically interacting with obsidian.nvim's features\n--- in Lua. To get the client instance, run:\n---\n--- `local client = require(\"obsidian\").get_client()`\n---\n---@toc_entry obsidian.Client\n---\n---@class obsidian.Client : obsidian.ABC\nlocal Client = {}\n\nlocal depreacted_lookup = {\n dir = \"dir\",\n buf_dir = \"buf_dir\",\n current_workspace = \"workspace\",\n opts = \"opts\",\n}\n\nClient.__index = function(_, k)\n if depreacted_lookup[k] then\n local msg = string.format(\n [[client.%s is depreacted, use Obsidian.%s instead.\nclient is going to be removed in the future as well.]],\n k,\n depreacted_lookup[k]\n )\n log.warn(msg)\n return Obsidian[depreacted_lookup[k]]\n elseif rawget(Client, k) then\n return rawget(Client, k)\n end\nend\n\n--- Create a new Obsidian client without additional setup.\n--- This is mostly used for testing. In practice you usually want to obtain the existing\n--- client through:\n---\n--- `require(\"obsidian\").get_client()`\n---\n---@return obsidian.Client\nClient.new = function()\n return setmetatable({}, Client)\nend\n\n--- Get the default search options.\n---\n---@return obsidian.SearchOpts\nClient.search_defaults = function()\n return {\n sort = false,\n include_templates = false,\n ignore_case = false,\n }\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---\n---@return obsidian.SearchOpts\n---\n---@private\nClient._search_opts_from_arg = function(self, opts)\n if opts == nil then\n opts = self:search_defaults()\n elseif type(opts) == \"boolean\" then\n local sort = opts\n opts = self:search_defaults()\n opts.sort = sort\n end\n return opts\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nClient._prepare_search_opts = function(self, opts, additional_opts)\n opts = self:_search_opts_from_arg(opts)\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n search.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = search.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---\n---@return function\n---\n---@private\nClient._search_iter_async = function(self, term, search_opts, find_opts)\n local tx, rx = channel.mpsc()\n local found = {}\n\n local function on_exit(_)\n tx.send(nil)\n end\n\n ---@param content_match MatchData\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n ---@param path_match string\n local function on_find_match(path_match)\n local path = Path.new(path_match):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n local cmds_done = 0 -- out of the two, one for 'search' and one for 'find'\n\n search.search_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n search.find_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(find_opts, { ignore_case = true }),\n on_find_match,\n on_exit\n )\n\n return function()\n while cmds_done < 2 do\n local value = rx.recv()\n if value == nil then\n cmds_done = cmds_done + 1\n else\n return value\n end\n end\n return nil\n end\nend\n\n---@class obsidian.TagLocation\n---\n---@field tag string The tag found.\n---@field note obsidian.Note The note instance where the tag was found.\n---@field path string|obsidian.Path The path to the note where the tag was found.\n---@field line integer The line number (1-indexed) where the tag was found.\n---@field text string The text (with whitespace stripped) of the line where the tag was found.\n---@field tag_start integer|? The index within 'text' where the tag starts.\n---@field tag_end integer|? The index within 'text' where the tag ends.\n\n--- Find all tags starting with the given search term(s).\n---\n---@param term string|string[] The search term.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|? }|?\n---\n---@return obsidian.TagLocation[]\nClient.find_tags = function(self, term, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_tags_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n--- An async version of 'find_tags()'.\n---\n---@param term string|string[] The search term.\n---@param callback fun(tags: obsidian.TagLocation[])\n---@param opts { search: obsidian.SearchOpts }|?\nClient.find_tags_async = function(self, term, callback, opts)\n opts = opts or {}\n\n ---@type string[]\n local terms\n if type(term) == \"string\" then\n terms = { term }\n else\n terms = term\n end\n\n for i, t in ipairs(terms) do\n if vim.startswith(t, \"#\") then\n terms[i] = string.sub(t, 2)\n end\n end\n\n terms = util.tbl_unique(terms)\n\n -- Maps paths to tag locations.\n ---@type table\n local path_to_tag_loc = {}\n -- Caches note objects.\n ---@type table\n local path_to_note = {}\n -- Caches code block locations.\n ---@type table\n local path_to_code_blocks = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n ---@param tag string\n ---@param path string|obsidian.Path\n ---@param note obsidian.Note\n ---@param lnum integer\n ---@param text string\n ---@param col_start integer|?\n ---@param col_end integer|?\n local add_match = function(tag, path, note, lnum, text, col_start, col_end)\n if vim.startswith(tag, \"#\") then\n tag = string.sub(tag, 2)\n end\n if not path_to_tag_loc[path] then\n path_to_tag_loc[path] = {}\n end\n path_to_tag_loc[path][#path_to_tag_loc[path] + 1] = {\n tag = tag,\n path = path,\n note = note,\n line = lnum,\n text = text,\n tag_start = col_start,\n tag_end = col_end,\n }\n end\n\n -- Wraps `Note.from_file_with_contents_async()` to return a table instead of a tuple and\n -- find the code blocks.\n ---@param path obsidian.Path\n ---@return { [1]: obsidian.Note, [2]: {[1]: integer, [2]: integer}[] }\n local load_note = function(path)\n local note, contents = Note.from_file_with_contents_async(path, { max_lines = Obsidian.opts.search_max_lines })\n return { note, search.find_code_blocks(contents) }\n end\n\n ---@param match_data MatchData\n local on_match = function(match_data)\n local path = Path.new(match_data.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local note = path_to_note[path]\n local code_blocks = path_to_code_blocks[path]\n if not note or not code_blocks then\n local ok, res = pcall(load_note, path)\n if ok then\n note, code_blocks = unpack(res)\n path_to_note[path] = note\n path_to_code_blocks[path] = code_blocks\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n local line_number = match_data.line_number + 1 -- match_data.line_number is 0-indexed\n\n -- check if the match was inside a code block.\n for block in iter(code_blocks) do\n if block[1] <= line_number and line_number <= block[2] then\n return\n end\n end\n\n local line = vim.trim(match_data.lines.text)\n local n_matches = 0\n\n -- check for tag in the wild of the form '#{tag}'\n for match in iter(search.find_tags(line)) do\n local m_start, m_end, _ = unpack(match)\n local tag = string.sub(line, m_start + 1, m_end)\n if string.match(tag, \"^\" .. search.Patterns.TagCharsRequired .. \"$\") then\n add_match(tag, path, note, match_data.line_number, line, m_start, m_end)\n end\n end\n\n -- check for tags in frontmatter\n if n_matches == 0 and note.tags ~= nil and (vim.startswith(line, \"tags:\") or string.match(line, \"%s*- \")) then\n for tag in iter(note.tags) do\n tag = tostring(tag)\n for _, t in ipairs(terms) do\n if string.len(t) == 0 or util.string_contains(tag:lower(), t:lower()) then\n add_match(tag, path, note, match_data.line_number, line)\n end\n end\n end\n end\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n local search_terms = {}\n for t in iter(terms) do\n if string.len(t) > 0 then\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsOptional .. t .. search.Patterns.TagCharsOptional\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n else\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsRequired\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \" .. search.Patterns.TagCharsRequired .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\" .. search.Patterns.TagCharsRequired\n end\n end\n\n search.search_async(\n Obsidian.dir,\n search_terms,\n self:_prepare_search_opts(opts.search, { ignore_case = true }),\n on_match,\n function(_)\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.TagLocation[]\n local tags_list = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results in path order.\n for _, path in ipairs(paths) do\n local tag_locs = path_to_tag_loc[path]\n if tag_locs ~= nil then\n table.sort(tag_locs, function(a, b)\n return a.line < b.line\n end)\n for _, tag_loc in ipairs(tag_locs) do\n tags_list[#tags_list + 1] = tag_loc\n end\n end\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return tags_list\n end, callback)\nend\n\n---@class obsidian.BacklinkMatches\n---\n---@field note obsidian.Note The note instance where the backlinks were found.\n---@field path string|obsidian.Path The path to the note where the backlinks were found.\n---@field matches obsidian.BacklinkMatch[] The backlinks within the note.\n\n---@class obsidian.BacklinkMatch\n---\n---@field line integer The line number (1-indexed) where the backlink was found.\n---@field text string The text of the line where the backlink was found.\n\n--- Find all backlinks to a note.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|?, anchor: string|?, block: string|? }|?\n---\n---@return obsidian.BacklinkMatches[]\nClient.find_backlinks = function(self, note, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_backlinks_async(note, cb, { search = opts.search, anchor = opts.anchor, block = opts.block })\n end, opts.timeout)\nend\n\n--- An async version of 'find_backlinks()'.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param callback fun(backlinks: obsidian.BacklinkMatches[])\n---@param opts { search: obsidian.SearchOpts, anchor: string|?, block: string|? }|?\nClient.find_backlinks_async = function(self, note, callback, opts)\n opts = opts or {}\n\n ---@type string|?\n local block = opts.block and util.standardize_block(opts.block) or nil\n local anchor = opts.anchor and util.standardize_anchor(opts.anchor) or nil\n ---@type obsidian.note.HeaderAnchor|?\n local anchor_obj\n if anchor then\n anchor_obj = note:resolve_anchor_link(anchor)\n end\n\n -- Maps paths (string) to note object and a list of matches.\n ---@type table\n local backlink_matches = {}\n ---@type table\n local path_to_note = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n -- Prepare search terms.\n local search_terms = {}\n local note_path = Path.new(note.path)\n for raw_ref in iter { tostring(note.id), note_path.name, note_path.stem, note.path:vault_relative_path() } do\n for ref in\n iter(util.tbl_unique {\n raw_ref,\n util.urlencode(tostring(raw_ref)),\n util.urlencode(tostring(raw_ref), { keep_path_sep = true }),\n })\n do\n if ref ~= nil then\n if anchor == nil and block == nil then\n -- Wiki links without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", ref)\n search_terms[#search_terms + 1] = string.format(\"[[%s|\", ref)\n -- Markdown link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s)\", ref)\n -- Markdown link without anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s)\", ref)\n -- Wiki links with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif anchor then\n -- Note: Obsidian allow a lot of different forms of anchor links, so we can't assume\n -- it's the standardized form here.\n -- Wiki links with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif block then\n -- Wiki links with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", ref, block)\n -- Markdown link with block.\n search_terms[#search_terms + 1] = string.format(\"(%s#%s\", ref, block)\n -- Markdown link with block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#%s\", ref, block)\n end\n end\n end\n end\n for alias in iter(note.aliases) do\n if anchor == nil and block == nil then\n -- Wiki link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", alias)\n -- Wiki link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif anchor then\n -- Wiki link with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif block then\n -- Wiki link with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", alias, block)\n end\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = opts.anchor ~= nil,\n collect_blocks = opts.block ~= nil,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n ---@param match MatchData\n local function on_match(match)\n local path = Path.new(match.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local n = path_to_note[path]\n if not n then\n local ok, res = pcall(Note.from_file_async, path, load_opts)\n if ok then\n n = res\n path_to_note[path] = n\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n if anchor then\n -- Check for a match with the anchor.\n -- NOTE: no need to do this with blocks, since blocks are standardized.\n local match_text = string.sub(match.lines.text, match.submatches[1].start)\n local link_location = util.parse_link(match_text)\n if not link_location then\n log.error(\"Failed to parse reference from '%s' ('%s')\", match_text, match)\n return\n end\n\n local anchor_link = select(2, util.strip_anchor_links(link_location))\n if not anchor_link then\n return\n end\n\n if anchor_link ~= anchor and anchor_obj ~= nil then\n local resolved_anchor = note:resolve_anchor_link(anchor_link)\n if resolved_anchor == nil or resolved_anchor.header ~= anchor_obj.header then\n return\n end\n end\n end\n\n ---@type obsidian.BacklinkMatch[]\n local line_matches = backlink_matches[path]\n if line_matches == nil then\n line_matches = {}\n backlink_matches[path] = line_matches\n end\n\n line_matches[#line_matches + 1] = {\n line = match.line_number,\n text = util.rstrip_whitespace(match.lines.text),\n }\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n -- Execute search.\n search.search_async(\n Obsidian.dir,\n util.tbl_unique(search_terms),\n self:_prepare_search_opts(opts.search, { fixed_strings = true, ignore_case = true }),\n on_match,\n function()\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.BacklinkMatches[]\n local results = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results.\n for i, path in ipairs(paths) do\n results[i] = { note = path_to_note[path], path = path, matches = backlink_matches[path] }\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return vim.tbl_filter(function(bl)\n return bl.matches ~= nil\n end, results)\n end, callback)\nend\n\n--- Gather a list of all tags in the vault. If 'term' is provided, only tags that partially match the search\n--- term will be included.\n---\n---@param term string|? An optional search term to match tags\n---@param timeout integer|? Timeout in milliseconds\n---\n---@return string[]\nClient.list_tags = function(self, term, timeout)\n local tags = {}\n for _, tag_loc in ipairs(self:find_tags(term and term or \"\", { timeout = timeout })) do\n tags[tag_loc.tag] = true\n end\n return vim.tbl_keys(tags)\nend\n\n--- An async version of 'list_tags()'.\n---\n---@param term string|?\n---@param callback fun(tags: string[])\nClient.list_tags_async = function(self, term, callback)\n self:find_tags_async(term and term or \"\", function(tag_locations)\n local tags = {}\n for _, tag_loc in ipairs(tag_locations) do\n local tag = tag_loc.tag:lower()\n if not tags[tag] then\n tags[tag] = true\n end\n end\n callback(vim.tbl_keys(tags))\n end)\nend\n\nreturn Client\n"], ["/obsidian.nvim/lua/obsidian/commands/init-legacy.lua", "local util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal command_lookups = {\n ObsidianCheck = \"obsidian.commands.check\",\n ObsidianToggleCheckbox = \"obsidian.commands.toggle_checkbox\",\n ObsidianToday = \"obsidian.commands.today\",\n ObsidianYesterday = \"obsidian.commands.yesterday\",\n ObsidianTomorrow = \"obsidian.commands.tomorrow\",\n ObsidianDailies = \"obsidian.commands.dailies\",\n ObsidianNew = \"obsidian.commands.new\",\n ObsidianOpen = \"obsidian.commands.open\",\n ObsidianBacklinks = \"obsidian.commands.backlinks\",\n ObsidianSearch = \"obsidian.commands.search\",\n ObsidianTags = \"obsidian.commands.tags\",\n ObsidianTemplate = \"obsidian.commands.template\",\n ObsidianNewFromTemplate = \"obsidian.commands.new_from_template\",\n ObsidianQuickSwitch = \"obsidian.commands.quick_switch\",\n ObsidianLinkNew = \"obsidian.commands.link_new\",\n ObsidianLink = \"obsidian.commands.link\",\n ObsidianLinks = \"obsidian.commands.links\",\n ObsidianFollowLink = \"obsidian.commands.follow_link\",\n ObsidianWorkspace = \"obsidian.commands.workspace\",\n ObsidianRename = \"obsidian.commands.rename\",\n ObsidianPasteImg = \"obsidian.commands.paste_img\",\n ObsidianExtractNote = \"obsidian.commands.extract_note\",\n ObsidianTOC = \"obsidian.commands.toc\",\n}\n\nlocal M = setmetatable({\n commands = {},\n}, {\n __index = function(t, k)\n local require_path = command_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@class obsidian.CommandConfigLegacy\n---@field opts table\n---@field complete function|?\n---@field func function|? (obsidian.Client, table) -> nil\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfigLegacy\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n return M[name](client, data)\n end\n end\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n for command_name, command_config in pairs(M.commands) do\n local func = function(data)\n command_config.func(client, data)\n end\n\n if command_config.complete ~= nil then\n command_config.opts.complete = function(arg_lead, cmd_line, cursor_pos)\n return command_config.complete(client, arg_lead, cmd_line, cursor_pos)\n end\n end\n\n vim.api.nvim_create_user_command(command_name, func, command_config.opts)\n end\nend\n\n---@param client obsidian.Client\n---@return string[]\nM.complete_args_search = function(client, _, cmd_line, _)\n local query\n local cmd_arg, _ = util.lstrip_whitespace(string.gsub(cmd_line, \"^.*Obsidian[A-Za-z0-9]+\", \"\"))\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\nM.register(\"ObsidianCheck\", { opts = { nargs = 0, desc = \"Check for issues in your vault\" } })\n\nM.register(\"ObsidianToday\", { opts = { nargs = \"?\", desc = \"Open today's daily note\" } })\n\nM.register(\"ObsidianYesterday\", { opts = { nargs = 0, desc = \"Open the daily note for the previous working day\" } })\n\nM.register(\"ObsidianTomorrow\", { opts = { nargs = 0, desc = \"Open the daily note for the next working day\" } })\n\nM.register(\"ObsidianDailies\", { opts = { nargs = \"*\", desc = \"Open a picker with daily notes\" } })\n\nM.register(\"ObsidianNew\", { opts = { nargs = \"?\", desc = \"Create a new note\" } })\n\nM.register(\n \"ObsidianOpen\",\n { opts = { nargs = \"?\", desc = \"Open in the Obsidian app\" }, complete = M.complete_args_search }\n)\n\nM.register(\"ObsidianBacklinks\", { opts = { nargs = 0, desc = \"Collect backlinks\" } })\n\nM.register(\"ObsidianTags\", { opts = { nargs = \"*\", range = true, desc = \"Find tags\" } })\n\nM.register(\"ObsidianSearch\", { opts = { nargs = \"?\", desc = \"Search vault\" } })\n\nM.register(\"ObsidianTemplate\", { opts = { nargs = \"?\", desc = \"Insert a template\" } })\n\nM.register(\"ObsidianNewFromTemplate\", { opts = { nargs = \"*\", desc = \"Create a new note from a template\" } })\n\nM.register(\"ObsidianQuickSwitch\", { opts = { nargs = \"?\", desc = \"Switch notes\" } })\n\nM.register(\"ObsidianLinkNew\", { opts = { nargs = \"?\", range = true, desc = \"Link selected text to a new note\" } })\n\nM.register(\"ObsidianLink\", {\n opts = { nargs = \"?\", range = true, desc = \"Link selected text to an existing note\" },\n complete = M.complete_args_search,\n})\n\nM.register(\"ObsidianLinks\", { opts = { nargs = 0, desc = \"Collect all links within the current buffer\" } })\n\nM.register(\"ObsidianFollowLink\", { opts = { nargs = \"?\", desc = \"Follow reference or link under cursor\" } })\n\nM.register(\"ObsidianToggleCheckbox\", { opts = { nargs = 0, desc = \"Toggle checkbox\", range = true } })\n\nM.register(\"ObsidianWorkspace\", { opts = { nargs = \"?\", desc = \"Check or switch workspace\" } })\n\nM.register(\"ObsidianRename\", { opts = { nargs = \"?\", desc = \"Rename note and update all references to it\" } })\n\nM.register(\"ObsidianPasteImg\", { opts = { nargs = \"?\", desc = \"Paste an image from the clipboard\" } })\n\nM.register(\n \"ObsidianExtractNote\",\n { opts = { nargs = \"?\", range = true, desc = \"Extract selected text to a new note and link to it\" } }\n)\n\nM.register(\"ObsidianTOC\", { opts = { nargs = 0, desc = \"Load the table of contents into a picker\" } })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/link.lua", "local search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n ---@type string\n local search_term\n if data.args ~= nil and string.len(data.args) > 0 then\n search_term = data.args\n else\n search_term = viz.selection\n end\n\n ---@param note obsidian.Note\n local function insert_ref(note)\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = viz.selection })\n .. string.sub(line, viz.cecol + 1)\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\n require(\"obsidian.ui\").update(0)\n end\n\n search.resolve_note_async(search_term, function(note)\n vim.schedule(function()\n insert_ref(note)\n end)\n end, { prompt_title = \"Select note to link\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/quick_switch.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_notes()\n else\n search.resolve_note_async(data.args, function(note)\n note:open()\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/rename.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal util = require \"obsidian.util\"\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal enumerate, zip = util.enumerate, util.zip\n\nlocal resolve_note = function(query, opts)\n opts = opts or {}\n return require(\"obsidian.async\").block_on(function(cb)\n print(query)\n return search.resolve_note_async(query, cb, { notes = opts.notes })\n end, 5000)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n -- Resolve the note to rename.\n ---@type boolean\n local is_current_buf\n ---@type integer|?\n local cur_note_bufnr\n ---@type obsidian.Path\n local cur_note_path\n ---@type obsidian.Note\n local cur_note, cur_note_id\n\n local cur_link = api.cursor_link()\n if not cur_link then\n -- rename current note\n is_current_buf = true\n cur_note_bufnr = assert(vim.fn.bufnr())\n cur_note_path = Path.buffer(cur_note_bufnr)\n cur_note = Note.from_file(cur_note_path)\n cur_note_id = tostring(cur_note.id)\n else\n -- rename note under the cursor\n local link_id = util.parse_link(cur_link)\n local notes = { resolve_note(link_id) }\n if #notes == 0 then\n log.err(\"Failed to resolve '%s' to a note\", cur_link)\n return\n elseif #notes > 1 then\n log.err(\"Failed to resolve '%s' to a single note, found %d matches\", cur_link, #notes)\n return\n else\n cur_note = notes[1]\n end\n\n is_current_buf = false\n cur_note_id = tostring(cur_note.id)\n cur_note_path = cur_note.path\n for bufnr, bufpath in api.get_named_buffers() do\n if bufpath == cur_note_path then\n cur_note_bufnr = bufnr\n break\n end\n end\n end\n\n -- Validate args.\n local dry_run = false\n ---@type string|?\n local arg\n\n if data.args == \"--dry-run\" then\n dry_run = true\n data.args = nil\n end\n\n if data.args ~= nil and string.len(data.args) > 0 then\n arg = vim.trim(data.args)\n else\n arg = api.input(\"Enter new note ID/name/path: \", { completion = \"file\", default = cur_note_id })\n if not arg or string.len(arg) == 0 then\n log.warn \"Rename aborted\"\n return\n end\n end\n\n if vim.endswith(arg, \" --dry-run\") then\n dry_run = true\n arg = vim.trim(string.sub(arg, 1, -string.len \" --dry-run\" - 1))\n end\n\n assert(cur_note_path)\n local dirname = assert(cur_note_path:parent(), string.format(\"failed to resolve parent of '%s'\", cur_note_path))\n\n -- Parse new note ID / path from args.\n local parts = vim.split(arg, \"/\", { plain = true })\n local new_note_id = parts[#parts]\n if new_note_id == \"\" then\n log.err \"Invalid new note ID\"\n return\n elseif vim.endswith(new_note_id, \".md\") then\n new_note_id = string.sub(new_note_id, 1, -4)\n end\n\n ---@type obsidian.Path\n local new_note_path\n if #parts > 1 then\n parts[#parts] = nil\n new_note_path = Obsidian.dir:joinpath(unpack(compat.flatten { parts, new_note_id })):with_suffix \".md\"\n else\n new_note_path = (dirname / new_note_id):with_suffix \".md\"\n end\n\n if new_note_id == cur_note_id then\n log.warn \"New note ID is the same, doing nothing\"\n return\n end\n\n -- Get confirmation before continuing.\n local confirmation\n if not dry_run then\n confirmation = api.confirm(\n \"Renaming '\"\n .. cur_note_id\n .. \"' to '\"\n .. new_note_id\n .. \"'...\\n\"\n .. \"This will write all buffers and potentially modify a lot of files. If you're using version control \"\n .. \"with your vault it would be a good idea to commit the current state of your vault before running this.\\n\"\n .. \"You can also do a dry run of this by running ':Obsidian rename \"\n .. arg\n .. \" --dry-run'.\\n\"\n .. \"Do you want to continue?\"\n )\n else\n confirmation = api.confirm(\n \"Dry run: renaming '\" .. cur_note_id .. \"' to '\" .. new_note_id .. \"'...\\n\" .. \"Do you want to continue?\"\n )\n end\n\n if not confirmation then\n log.warn \"Rename aborted\"\n return\n end\n\n ---@param fn function\n local function quietly(fn, ...)\n local ok, res = pcall(fn, ...)\n if not ok then\n error(res)\n end\n end\n\n -- Write all buffers.\n quietly(vim.cmd.wall)\n\n -- Rename the note file and remove or rename the corresponding buffer, if there is one.\n if cur_note_bufnr ~= nil then\n if is_current_buf then\n -- If we're renaming the note of a current buffer, save as the new path.\n if not dry_run then\n quietly(vim.cmd.saveas, tostring(new_note_path))\n local new_bufnr_current_note = vim.fn.bufnr(tostring(cur_note_path))\n quietly(vim.cmd.bdelete, new_bufnr_current_note)\n vim.fn.delete(tostring(cur_note_path))\n else\n log.info(\"Dry run: saving current buffer as '\" .. tostring(new_note_path) .. \"' and removing old file\")\n end\n else\n -- For the non-current buffer the best we can do is delete the buffer (we've already saved it above)\n -- and then make a file-system call to rename the file.\n if not dry_run then\n quietly(vim.cmd.bdelete, cur_note_bufnr)\n cur_note_path:rename(new_note_path)\n else\n log.info(\n \"Dry run: removing buffer '\"\n .. tostring(cur_note_path)\n .. \"' and renaming file to '\"\n .. tostring(new_note_path)\n .. \"'\"\n )\n end\n end\n else\n -- When the note is not loaded into a buffer we just need to rename the file.\n if not dry_run then\n cur_note_path:rename(new_note_path)\n else\n log.info(\"Dry run: renaming file '\" .. tostring(cur_note_path) .. \"' to '\" .. tostring(new_note_path) .. \"'\")\n end\n end\n\n -- We need to update its frontmatter note_id\n -- to account for the rename.\n cur_note.id = new_note_id\n cur_note.path = Path.new(new_note_path)\n if not dry_run then\n cur_note:save()\n else\n log.info(\"Dry run: updating frontmatter of '\" .. tostring(new_note_path) .. \"'\")\n end\n\n local cur_note_rel_path = assert(cur_note_path:vault_relative_path { strict = true })\n local new_note_rel_path = assert(new_note_path:vault_relative_path { strict = true })\n\n -- Search notes on disk for any references to `cur_note_id`.\n -- We look for the following forms of references:\n -- * '[[cur_note_id]]'\n -- * '[[cur_note_id|ALIAS]]'\n -- * '[[cur_note_id\\|ALIAS]]' (a wiki link within a table)\n -- * '[ALIAS](cur_note_id)'\n -- And all of the above with relative paths (from the vault root) to the note instead of just the note ID,\n -- with and without the \".md\" suffix.\n -- Another possible form is [[ALIAS]], but we don't change the note's aliases when renaming\n -- so those links will still be valid.\n ---@param ref_link string\n ---@return string[]\n local function get_ref_forms(ref_link)\n return {\n \"[[\" .. ref_link .. \"]]\",\n \"[[\" .. ref_link .. \"|\",\n \"[[\" .. ref_link .. \"\\\\|\",\n \"[[\" .. ref_link .. \"#\",\n \"](\" .. ref_link .. \")\",\n \"](\" .. ref_link .. \"#\",\n }\n end\n\n local reference_forms = compat.flatten {\n get_ref_forms(cur_note_id),\n get_ref_forms(cur_note_rel_path),\n get_ref_forms(string.sub(cur_note_rel_path, 1, -4)),\n }\n local replace_with = compat.flatten {\n get_ref_forms(new_note_id),\n get_ref_forms(new_note_rel_path),\n get_ref_forms(string.sub(new_note_rel_path, 1, -4)),\n }\n\n local executor = AsyncExecutor.new()\n\n local file_count = 0\n local replacement_count = 0\n local all_tasks_submitted = false\n\n ---@param path string\n ---@return integer\n local function replace_refs(path)\n --- Read lines, replacing refs as we go.\n local count = 0\n local lines = {}\n local f = io.open(path, \"r\")\n assert(f)\n for line_num, line in enumerate(f:lines \"*L\") do\n for ref, replacement in zip(reference_forms, replace_with) do\n local n\n line, n = string.gsub(line, vim.pesc(ref), replacement)\n if dry_run and n > 0 then\n log.info(\n \"Dry run: '\"\n .. tostring(path)\n .. \"':\"\n .. line_num\n .. \" Replacing \"\n .. n\n .. \" occurrence(s) of '\"\n .. ref\n .. \"' with '\"\n .. replacement\n .. \"'\"\n )\n end\n count = count + n\n end\n lines[#lines + 1] = line\n end\n f:close()\n\n --- Write the new lines back.\n if not dry_run and count > 0 then\n f = io.open(path, \"w\")\n assert(f)\n f:write(unpack(lines))\n f:close()\n end\n\n return count\n end\n\n local function on_search_match(match)\n local path = tostring(Path.new(match.path.text):resolve { strict = true })\n file_count = file_count + 1\n executor:submit(replace_refs, function(count)\n replacement_count = replacement_count + count\n end, path)\n end\n\n search.search_async(\n Obsidian.dir,\n reference_forms,\n { fixed_strings = true, max_count_per_file = 1 },\n on_search_match,\n function(_)\n all_tasks_submitted = true\n end\n )\n\n -- Wait for all tasks to get submitted.\n vim.wait(2000, function()\n return all_tasks_submitted\n end, 50, false)\n\n -- Then block until all tasks are finished.\n executor:join(2000)\n\n local prefix = dry_run and \"Dry run: replaced \" or \"Replaced \"\n log.info(prefix .. replacement_count .. \" reference(s) across \" .. file_count .. \" file(s)\")\n\n -- In case the files of any current buffers were changed.\n vim.cmd.checktime()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/template.lua", "local templates = require \"obsidian.templates\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local templates_dir = api.templates_dir()\n if not templates_dir then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n -- We need to get this upfront before the picker hijacks the current window.\n local insert_location = api.get_active_window_cursor_location()\n\n local function insert_template(name)\n templates.insert_template {\n type = \"insert_template\",\n template_name = name,\n template_opts = Obsidian.opts.templates,\n templates_dir = templates_dir,\n location = insert_location,\n }\n end\n\n if string.len(data.args) > 0 then\n local template_name = vim.trim(data.args)\n insert_template(template_name)\n return\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_templates {\n callback = function(path)\n insert_template(path)\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/note.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal yaml = require \"obsidian.yaml\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\nlocal enumerate = util.enumerate\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal config = require \"obsidian.config\"\n\nlocal SKIP_UPDATING_FRONTMATTER = { \"README.md\", \"CONTRIBUTING.md\", \"CHANGELOG.md\" }\n\nlocal DEFAULT_MAX_LINES = 500\n\nlocal CODE_BLOCK_PATTERN = \"^%s*```[%w_-]*$\"\n\n--- @class obsidian.note.NoteCreationOpts\n--- @field notes_subdir string\n--- @field note_id_func fun()\n--- @field new_notes_location string\n\n--- @class obsidian.note.NoteOpts\n--- @field title string|? The note's title\n--- @field id string|? An ID to assign the note. If not specified one will be generated.\n--- @field dir string|obsidian.Path|? An optional directory to place the note in. Relative paths will be interpreted\n--- relative to the workspace / vault root. If the directory doesn't exist it will\n--- be created, regardless of the value of the `should_write` option.\n--- @field aliases string[]|? Aliases for the note\n--- @field tags string[]|? Tags for this note\n--- @field should_write boolean|? Don't write the note to disk\n--- @field template string|? The name of the template\n\n---@class obsidian.note.NoteSaveOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- Whether to insert/update frontmatter. Defaults to `true`.\n---@field insert_frontmatter? boolean\n--- Override the frontmatter. Defaults to the result of `self:frontmatter()`.\n---@field frontmatter? table\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload the updated file.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.NoteWriteOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- The name of a template to use if the note file doesn't already exist.\n---@field template? string\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload each buffer's content.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.HeaderAnchor\n---\n---@field anchor string\n---@field header string\n---@field level integer\n---@field line integer\n---@field parent obsidian.note.HeaderAnchor|?\n\n---@class obsidian.note.Block\n---\n---@field id string\n---@field line integer\n---@field block string\n\n--- A class that represents a note within a vault.\n---\n---@toc_entry obsidian.Note\n---\n---@class obsidian.Note : obsidian.ABC\n---\n---@field id string\n---@field aliases string[]\n---@field title string|?\n---@field tags string[]\n---@field path obsidian.Path|?\n---@field metadata table|?\n---@field has_frontmatter boolean|?\n---@field frontmatter_end_line integer|?\n---@field contents string[]|?\n---@field anchor_links table|?\n---@field blocks table?\n---@field alt_alias string|?\n---@field bufnr integer|?\nlocal Note = abc.new_class {\n __tostring = function(self)\n return string.format(\"Note('%s')\", self.id)\n end,\n}\n\nNote.is_note_obj = function(note)\n if getmetatable(note) == Note.mt then\n return true\n else\n return false\n end\nend\n\n--- Generate a unique ID for a new note. This respects the user's `note_id_func` if configured,\n--- otherwise falls back to generated a Zettelkasten style ID.\n---\n--- @param title? string\n--- @param path? obsidian.Path\n--- @param alt_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n---@return string\nlocal function generate_id(title, path, alt_id_func)\n if alt_id_func ~= nil then\n local new_id = alt_id_func(title, path)\n if new_id == nil or string.len(new_id) == 0 then\n error(string.format(\"Your 'note_id_func' must return a non-empty string, got '%s'!\", tostring(new_id)))\n end\n -- Remote '.md' suffix if it's there (we add that later).\n new_id = new_id:gsub(\"%.md$\", \"\", 1)\n return new_id\n else\n return require(\"obsidian.builtin\").zettel_id()\n end\nend\n\n--- Generate the file path for a new note given its ID, parent directory, and title.\n--- This respects the user's `note_path_func` if configured, otherwise essentially falls back to\n--- `note_opts.dir / (note_opts.id .. \".md\")`.\n---\n--- @param title string|? The title for the note\n--- @param id string The note ID\n--- @param dir obsidian.Path The note path\n---@return obsidian.Path\n---@private\nNote._generate_path = function(title, id, dir)\n ---@type obsidian.Path\n local path\n\n if Obsidian.opts.note_path_func ~= nil then\n path = Path.new(Obsidian.opts.note_path_func { id = id, dir = dir, title = title })\n -- Ensure path is either absolute or inside `opts.dir`.\n -- NOTE: `opts.dir` should always be absolute, but for extra safety we handle the case where\n -- it's not.\n if not path:is_absolute() and (dir:is_absolute() or not dir:is_parent_of(path)) then\n path = dir / path\n end\n else\n path = dir / tostring(id)\n end\n\n -- Ensure there is only one \".md\" suffix. This might arise if `note_path_func`\n -- supplies an unusual implementation returning something like /bad/note/id.md.md.md\n while path.filename:match \"%.md$\" do\n path.filename = path.filename:gsub(\"%.md$\", \"\")\n end\n\n return path:with_suffix(\".md\", true)\nend\n\n--- Selects the strategy to use when resolving the note title, id, and path\n--- @param opts obsidian.note.NoteOpts The note creation options\n--- @return obsidian.note.NoteCreationOpts The strategy to use for creating the note\n--- @private\nNote._get_creation_opts = function(opts)\n --- @type obsidian.note.NoteCreationOpts\n local default = {\n notes_subdir = Obsidian.opts.notes_subdir,\n note_id_func = Obsidian.opts.note_id_func,\n new_notes_location = Obsidian.opts.new_notes_location,\n }\n\n local resolve_template = require(\"obsidian.templates\").resolve_template\n local success, template_path = pcall(resolve_template, opts.template, api.templates_dir())\n\n if not success then\n return default\n end\n\n local stem = template_path.stem:lower()\n\n -- Check if the configuration has a custom key for this template\n for key, cfg in pairs(Obsidian.opts.templates.customizations) do\n if key:lower() == stem then\n return {\n notes_subdir = cfg.notes_subdir,\n note_id_func = cfg.note_id_func,\n new_notes_location = config.NewNotesLocation.notes_subdir,\n }\n end\n end\n return default\nend\n\n--- Resolves the title, ID, and path for a new note.\n---\n---@param title string|?\n---@param id string|?\n---@param dir string|obsidian.Path|? The directory for the note\n---@param strategy obsidian.note.NoteCreationOpts Strategy for resolving note path and title\n---@return string|?,string,obsidian.Path\n---@private\nNote._resolve_title_id_path = function(title, id, dir, strategy)\n if title then\n title = vim.trim(title)\n if title == \"\" then\n title = nil\n end\n end\n\n if id then\n id = vim.trim(id)\n if id == \"\" then\n id = nil\n end\n end\n\n ---@param s string\n ---@param strict_paths_only boolean\n ---@return string|?, boolean, string|?\n local parse_as_path = function(s, strict_paths_only)\n local is_path = false\n ---@type string|?\n local parent\n\n if s:match \"%.md\" then\n -- Remove suffix.\n s = s:sub(1, s:len() - 3)\n is_path = true\n end\n\n -- Pull out any parent dirs from title.\n local parts = vim.split(s, \"/\")\n if #parts > 1 then\n s = parts[#parts]\n if not strict_paths_only then\n is_path = true\n end\n parent = table.concat(parts, \"/\", 1, #parts - 1)\n end\n\n if s == \"\" then\n return nil, is_path, parent\n else\n return s, is_path, parent\n end\n end\n\n local parent, _, title_is_path\n if id then\n id, _, parent = parse_as_path(id, false)\n elseif title then\n title, title_is_path, parent = parse_as_path(title, true)\n if title_is_path then\n id = title\n end\n end\n\n -- Resolve base directory.\n ---@type obsidian.Path\n local base_dir\n if parent then\n base_dir = Obsidian.dir / parent\n elseif dir ~= nil then\n base_dir = Path.new(dir)\n if not base_dir:is_absolute() then\n base_dir = Obsidian.dir / base_dir\n else\n base_dir = base_dir:resolve()\n end\n else\n local bufpath = Path.buffer(0):resolve()\n if\n strategy.new_notes_location == config.NewNotesLocation.current_dir\n -- note is actually in the workspace.\n and Obsidian.dir:is_parent_of(bufpath)\n -- note is not in dailies folder\n and (\n Obsidian.opts.daily_notes.folder == nil\n or not (Obsidian.dir / Obsidian.opts.daily_notes.folder):is_parent_of(bufpath)\n )\n then\n base_dir = Obsidian.buf_dir or assert(bufpath:parent())\n else\n base_dir = Obsidian.dir\n if strategy.notes_subdir then\n base_dir = base_dir / strategy.notes_subdir\n end\n end\n end\n\n -- Make sure `base_dir` is absolute at this point.\n assert(base_dir:is_absolute(), (\"failed to resolve note directory '%s'\"):format(base_dir))\n\n -- Generate new ID if needed.\n if not id then\n id = generate_id(title, base_dir, strategy.note_id_func)\n end\n\n dir = base_dir\n\n -- Generate path.\n local path = Note._generate_path(title, id, dir)\n\n return title, id, path\nend\n\n--- Creates a new note\n---\n--- @param opts obsidian.note.NoteOpts Options\n--- @return obsidian.Note\nNote.create = function(opts)\n local new_title, new_id, path =\n Note._resolve_title_id_path(opts.title, opts.id, opts.dir, Note._get_creation_opts(opts))\n opts = vim.tbl_extend(\"keep\", opts, { aliases = {}, tags = {} })\n\n -- Add the title as an alias.\n --- @type string[]\n local aliases = opts.aliases\n if new_title ~= nil and new_title:len() > 0 and not vim.list_contains(aliases, new_title) then\n aliases[#aliases + 1] = new_title\n end\n\n local note = Note.new(new_id, aliases, opts.tags, path)\n\n if new_title then\n note.title = new_title\n end\n\n -- Ensure the parent directory exists.\n local parent = path:parent()\n assert(parent)\n parent:mkdir { parents = true, exist_ok = true }\n\n -- Write to disk.\n if opts.should_write then\n note:write { template = opts.template }\n end\n\n return note\nend\n\n--- Instantiates a new Note object\n---\n--- Keep in mind that you have to call `note:save(...)` to create/update the note on disk.\n---\n--- @param id string|number\n--- @param aliases string[]\n--- @param tags string[]\n--- @param path string|obsidian.Path|?\n--- @return obsidian.Note\nNote.new = function(id, aliases, tags, path)\n local self = Note.init()\n self.id = id\n self.aliases = aliases and aliases or {}\n self.tags = tags and tags or {}\n self.path = path and Path.new(path) or nil\n self.metadata = nil\n self.has_frontmatter = nil\n self.frontmatter_end_line = nil\n return self\nend\n\n--- Get markdown display info about the note.\n---\n---@param opts { label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|?\n---\n---@return string\nNote.display_info = function(self, opts)\n opts = opts and opts or {}\n\n ---@type string[]\n local info = {}\n\n if opts.label ~= nil and string.len(opts.label) > 0 then\n info[#info + 1] = (\"%s\"):format(opts.label)\n info[#info + 1] = \"--------\"\n end\n\n if self.path ~= nil then\n info[#info + 1] = (\"**path:** `%s`\"):format(self.path)\n end\n\n info[#info + 1] = (\"**id:** `%s`\"):format(self.id)\n\n if #self.aliases > 0 then\n info[#info + 1] = (\"**aliases:** '%s'\"):format(table.concat(self.aliases, \"', '\"))\n end\n\n if #self.tags > 0 then\n info[#info + 1] = (\"**tags:** `#%s`\"):format(table.concat(self.tags, \"`, `#\"))\n end\n\n if opts.anchor or opts.block then\n info[#info + 1] = \"--------\"\n\n if opts.anchor then\n info[#info + 1] = (\"...\\n%s %s\\n...\"):format(string.rep(\"#\", opts.anchor.level), opts.anchor.header)\n elseif opts.block then\n info[#info + 1] = (\"...\\n%s\\n...\"):format(opts.block.block)\n end\n end\n\n return table.concat(info, \"\\n\")\nend\n\n--- Check if the note exists on the file system.\n---\n---@return boolean\nNote.exists = function(self)\n ---@diagnostic disable-next-line: return-type-mismatch\n return self.path ~= nil and self.path:is_file()\nend\n\n--- Get the filename associated with the note.\n---\n---@return string|?\nNote.fname = function(self)\n if self.path == nil then\n return nil\n else\n return vim.fs.basename(tostring(self.path))\n end\nend\n\n--- Get a list of all of the different string that can identify this note via references,\n--- including the ID, aliases, and filename.\n---@param opts { lowercase: boolean|? }|?\n---@return string[]\nNote.reference_ids = function(self, opts)\n opts = opts or {}\n ---@type string[]\n local ref_ids = { tostring(self.id), self:display_name() }\n if self.path then\n table.insert(ref_ids, self.path.name)\n table.insert(ref_ids, self.path.stem)\n end\n\n vim.list_extend(ref_ids, self.aliases)\n\n if opts.lowercase then\n ref_ids = vim.tbl_map(string.lower, ref_ids)\n end\n\n return util.tbl_unique(ref_ids)\nend\n\n--- Check if a note has a given alias.\n---\n---@param alias string\n---\n---@return boolean\nNote.has_alias = function(self, alias)\n return vim.list_contains(self.aliases, alias)\nend\n\n--- Check if a note has a given tag.\n---\n---@param tag string\n---\n---@return boolean\nNote.has_tag = function(self, tag)\n return vim.list_contains(self.tags, tag)\nend\n\n--- Add an alias to the note.\n---\n---@param alias string\n---\n---@return boolean added True if the alias was added, false if it was already present.\nNote.add_alias = function(self, alias)\n if not self:has_alias(alias) then\n table.insert(self.aliases, alias)\n return true\n else\n return false\n end\nend\n\n--- Add a tag to the note.\n---\n---@param tag string\n---\n---@return boolean added True if the tag was added, false if it was already present.\nNote.add_tag = function(self, tag)\n if not self:has_tag(tag) then\n table.insert(self.tags, tag)\n return true\n else\n return false\n end\nend\n\n--- Add or update a field in the frontmatter.\n---\n---@param key string\n---@param value any\nNote.add_field = function(self, key, value)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Updating field '%s' this way is not allowed. Please update the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n self.metadata = {}\n end\n\n self.metadata[key] = value\nend\n\n--- Get a field in the frontmatter.\n---\n---@param key string\n---\n---@return any result\nNote.get_field = function(self, key)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Getting field '%s' this way is not allowed. Please use the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n return nil\n end\n\n return self.metadata[key]\nend\n\n---@class obsidian.note.LoadOpts\n---@field max_lines integer|?\n---@field load_contents boolean|?\n---@field collect_anchor_links boolean|?\n---@field collect_blocks boolean|?\n\n--- Initialize a note from a file.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file = function(path, opts)\n if path == nil then\n error \"note path cannot be nil\"\n end\n path = tostring(Path.new(path):resolve { strict = true })\n return Note.from_lines(io.lines(path), path, opts)\nend\n\n--- An async version of `.from_file()`, i.e. it needs to be called in an async context.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file_async = function(path, opts)\n path = Path.new(path):resolve { strict = true }\n local f = io.open(tostring(path), \"r\")\n assert(f)\n local ok, res = pcall(Note.from_lines, f:lines \"*l\", path, opts)\n f:close()\n if ok then\n return res\n else\n error(res)\n end\nend\n\n--- Like `.from_file_async()` but also returns the contents of the file as a list of lines.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note,string[]\nNote.from_file_with_contents_async = function(path, opts)\n opts = vim.tbl_extend(\"force\", opts or {}, { load_contents = true })\n local note = Note.from_file_async(path, opts)\n assert(note.contents ~= nil)\n return note, note.contents\nend\n\n--- Initialize a note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_buffer = function(bufnr, opts)\n bufnr = bufnr or vim.api.nvim_get_current_buf()\n local path = vim.api.nvim_buf_get_name(bufnr)\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)\n local note = Note.from_lines(iter(lines), path, opts)\n note.bufnr = bufnr\n return note\nend\n\n--- Get the display name for note.\n---\n---@return string\nNote.display_name = function(self)\n if self.title then\n return self.title\n elseif #self.aliases > 0 then\n return self.aliases[#self.aliases]\n end\n return tostring(self.id)\nend\n\n--- Initialize a note from an iterator of lines.\n---\n---@param lines fun(): string|? | Iter\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_lines = function(lines, path, opts)\n opts = opts or {}\n path = Path.new(path):resolve()\n\n local max_lines = opts.max_lines or DEFAULT_MAX_LINES\n\n local id = nil\n local title = nil\n local aliases = {}\n local tags = {}\n\n ---@type string[]|?\n local contents\n if opts.load_contents then\n contents = {}\n end\n\n ---@type table|?\n local anchor_links\n ---@type obsidian.note.HeaderAnchor[]|?\n local anchor_stack\n if opts.collect_anchor_links then\n anchor_links = {}\n anchor_stack = {}\n end\n\n ---@type table|?\n local blocks\n if opts.collect_blocks then\n blocks = {}\n end\n\n ---@param anchor_data obsidian.note.HeaderAnchor\n ---@return obsidian.note.HeaderAnchor|?\n local function get_parent_anchor(anchor_data)\n assert(anchor_links)\n assert(anchor_stack)\n for i = #anchor_stack, 1, -1 do\n local parent = anchor_stack[i]\n if parent.level < anchor_data.level then\n return parent\n end\n end\n end\n\n ---@param anchor string\n ---@param data obsidian.note.HeaderAnchor|?\n local function format_nested_anchor(anchor, data)\n local out = anchor\n if not data then\n return out\n end\n\n local parent = data.parent\n while parent ~= nil do\n out = parent.anchor .. out\n data = get_parent_anchor(parent)\n if data then\n parent = data.parent\n else\n parent = nil\n end\n end\n\n return out\n end\n\n -- Iterate over lines in the file, collecting frontmatter and parsing the title.\n local frontmatter_lines = {}\n local has_frontmatter, in_frontmatter, at_boundary = false, false, false -- luacheck: ignore (false positive)\n local frontmatter_end_line = nil\n local in_code_block = false\n for line_idx, line in enumerate(lines) do\n line = util.rstrip_whitespace(line)\n\n if line_idx == 1 and Note._is_frontmatter_boundary(line) then\n has_frontmatter = true\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n frontmatter_end_line = line_idx\n else\n at_boundary = false\n end\n\n if string.match(line, CODE_BLOCK_PATTERN) then\n in_code_block = not in_code_block\n end\n\n if in_frontmatter and not at_boundary then\n table.insert(frontmatter_lines, line)\n elseif not in_frontmatter and not at_boundary and not in_code_block then\n -- Check for title/header and collect anchor link.\n local header_match = util.parse_header(line)\n if header_match then\n if not title and header_match.level == 1 then\n title = header_match.header\n end\n\n -- Collect anchor link.\n if opts.collect_anchor_links then\n assert(anchor_links)\n assert(anchor_stack)\n -- We collect up to two anchor for each header. One standalone, e.g. '#header1', and\n -- one with the parents, e.g. '#header1#header2'.\n -- This is our standalone one:\n ---@type obsidian.note.HeaderAnchor\n local data = {\n anchor = header_match.anchor,\n line = line_idx,\n header = header_match.header,\n level = header_match.level,\n }\n data.parent = get_parent_anchor(data)\n\n anchor_links[header_match.anchor] = data\n table.insert(anchor_stack, data)\n\n -- Now if there's a parent we collect the nested version. All of the data will be the same\n -- except the anchor key.\n if data.parent ~= nil then\n local nested_anchor = format_nested_anchor(header_match.anchor, data)\n anchor_links[nested_anchor] = vim.tbl_extend(\"force\", data, { anchor = nested_anchor })\n end\n end\n end\n\n -- Check for block.\n if opts.collect_blocks then\n local block = util.parse_block(line)\n if block then\n blocks[block] = { id = block, line = line_idx, block = line }\n end\n end\n end\n\n -- Collect contents.\n if contents ~= nil then\n table.insert(contents, line)\n end\n\n -- Check if we can stop reading lines now.\n if\n line_idx > max_lines\n or (title and not opts.load_contents and not opts.collect_anchor_links and not opts.collect_blocks)\n then\n break\n end\n end\n\n if title ~= nil then\n -- Remove references and links from title\n title = search.replace_refs(title)\n end\n\n -- Parse the frontmatter YAML.\n local metadata = nil\n if #frontmatter_lines > 0 then\n local frontmatter = table.concat(frontmatter_lines, \"\\n\")\n local ok, data = pcall(yaml.loads, frontmatter)\n if type(data) ~= \"table\" then\n data = {}\n end\n if ok then\n ---@diagnostic disable-next-line: param-type-mismatch\n for k, v in pairs(data) do\n if k == \"id\" then\n if type(v) == \"string\" or type(v) == \"number\" then\n id = v\n else\n log.warn(\"Invalid 'id' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"aliases\" then\n if type(v) == \"table\" then\n for alias in iter(v) do\n if type(alias) == \"string\" then\n table.insert(aliases, alias)\n else\n log.warn(\n \"Invalid alias value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(alias)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n table.insert(aliases, v)\n else\n log.warn(\"Invalid 'aliases' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"tags\" then\n if type(v) == \"table\" then\n for tag in iter(v) do\n if type(tag) == \"string\" then\n table.insert(tags, tag)\n else\n log.warn(\n \"Invalid tag value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(tag)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n tags = vim.split(v, \" \")\n else\n log.warn(\"Invalid 'tags' in frontmatter for '%s'\", path)\n end\n else\n if metadata == nil then\n metadata = {}\n end\n metadata[k] = v\n end\n end\n end\n end\n\n -- ID should default to the filename without the extension.\n if id == nil or id == path.name then\n id = path.stem\n end\n assert(id)\n\n local n = Note.new(id, aliases, tags, path)\n n.title = title\n n.metadata = metadata\n n.has_frontmatter = has_frontmatter\n n.frontmatter_end_line = frontmatter_end_line\n n.contents = contents\n n.anchor_links = anchor_links\n n.blocks = blocks\n return n\nend\n\n--- Check if a line matches a frontmatter boundary.\n---\n---@param line string\n---\n---@return boolean\n---\n---@private\nNote._is_frontmatter_boundary = function(line)\n return line:match \"^---+$\" ~= nil\nend\n\n--- Get the frontmatter table to save.\n---\n---@return table\nNote.frontmatter = function(self)\n local out = { id = self.id, aliases = self.aliases, tags = self.tags }\n if self.metadata ~= nil and not vim.tbl_isempty(self.metadata) then\n for k, v in pairs(self.metadata) do\n out[k] = v\n end\n end\n return out\nend\n\n--- Get frontmatter lines that can be written to a buffer.\n---\n---@param eol boolean|?\n---@param frontmatter table|?\n---\n---@return string[]\nNote.frontmatter_lines = function(self, eol, frontmatter)\n local new_lines = { \"---\" }\n\n local frontmatter_ = frontmatter and frontmatter or self:frontmatter()\n if vim.tbl_isempty(frontmatter_) then\n return {}\n end\n\n for line in\n iter(yaml.dumps_lines(frontmatter_, function(a, b)\n local a_idx = nil\n local b_idx = nil\n for i, k in ipairs { \"id\", \"aliases\", \"tags\" } do\n if a == k then\n a_idx = i\n end\n if b == k then\n b_idx = i\n end\n end\n if a_idx ~= nil and b_idx ~= nil then\n return a_idx < b_idx\n elseif a_idx ~= nil then\n return true\n elseif b_idx ~= nil then\n return false\n else\n return a < b\n end\n end))\n do\n table.insert(new_lines, line)\n end\n\n table.insert(new_lines, \"---\")\n if not self.has_frontmatter then\n -- Make sure there's an empty line between end of the frontmatter and the contents.\n table.insert(new_lines, \"\")\n end\n\n if eol then\n return vim.tbl_map(function(l)\n return l .. \"\\n\"\n end, new_lines)\n else\n return new_lines\n end\nend\n\n--- Update the frontmatter in a buffer for the note.\n---\n---@param bufnr integer|?\n---\n---@return boolean updated If the the frontmatter was updated.\nNote.update_frontmatter = function(self, bufnr)\n if not self:should_save_frontmatter() then\n return false\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n return self:save_to_buffer { bufnr = bufnr, frontmatter = frontmatter }\nend\n\n--- Checks if the parameter note is in the blacklist of files which shouldn't have\n--- frontmatter applied\n---\n--- @param note obsidian.Note The note\n--- @return boolean true if so\nlocal is_in_frontmatter_blacklist = function(note)\n local fname = note:fname()\n return (fname ~= nil and vim.list_contains(SKIP_UPDATING_FRONTMATTER, fname))\nend\n\n--- Determines whether a note's frontmatter is managed by obsidian.nvim.\n---\n---@return boolean\nNote.should_save_frontmatter = function(self)\n -- Check if the note is a template.\n local templates_dir = api.templates_dir()\n if templates_dir ~= nil then\n templates_dir = templates_dir:resolve()\n for _, parent in ipairs(self.path:parents()) do\n if parent == templates_dir then\n return false\n end\n end\n end\n\n if is_in_frontmatter_blacklist(self) then\n return false\n elseif type(Obsidian.opts.disable_frontmatter) == \"boolean\" then\n return not Obsidian.opts.disable_frontmatter\n elseif type(Obsidian.opts.disable_frontmatter) == \"function\" then\n return not Obsidian.opts.disable_frontmatter(self.path:vault_relative_path { strict = true })\n else\n return true\n end\nend\n\n--- Write the note to disk.\n---\n---@param opts? obsidian.note.NoteWriteOpts\n---@return obsidian.Note\nNote.write = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n local path = assert(self.path, \"A path must be provided\")\n path = Path.new(path)\n\n ---@type string\n local verb\n if path:is_file() then\n verb = \"Updated\"\n else\n verb = \"Created\"\n if opts.template ~= nil then\n self = Template.clone_template {\n type = \"clone_template\",\n template_name = opts.template,\n destination_path = path,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n partial_note = self,\n }\n end\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n self:save {\n path = path,\n insert_frontmatter = self:should_save_frontmatter(),\n frontmatter = frontmatter,\n update_content = opts.update_content,\n check_buffers = opts.check_buffers,\n }\n\n log.info(\"%s note '%s' at '%s'\", verb, self.id, self.path:vault_relative_path(self.path) or self.path)\n\n return self\nend\n\n--- Save the note to a file.\n--- In general this only updates the frontmatter and header, leaving the rest of the contents unchanged\n--- unless you use the `update_content()` callback.\n---\n---@param opts? obsidian.note.NoteSaveOpts\nNote.save = function(self, opts)\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n if self.path == nil then\n error \"a path is required\"\n end\n\n local save_path = Path.new(assert(opts.path or self.path)):resolve()\n assert(save_path:parent()):mkdir { parents = true, exist_ok = true }\n\n -- Read contents from existing file or buffer, if there is one.\n -- TODO: check for open buffer?\n ---@type string[]\n local content = {}\n ---@type string[]\n local existing_frontmatter = {}\n if self.path ~= nil and self.path:is_file() then\n -- with(open(tostring(self.path)), function(reader)\n local in_frontmatter, at_boundary = false, false -- luacheck: ignore (false positive)\n for idx, line in enumerate(io.lines(tostring(self.path))) do\n if idx == 1 and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n else\n at_boundary = false\n end\n\n if not in_frontmatter and not at_boundary then\n table.insert(content, line)\n else\n table.insert(existing_frontmatter, line)\n end\n end\n -- end)\n elseif self.title ~= nil then\n -- Add a header.\n table.insert(content, \"# \" .. self.title)\n end\n\n -- Pass content through callback.\n if opts.update_content then\n content = opts.update_content(content)\n end\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n -- Replace frontmatter.\n new_lines = compat.flatten { self:frontmatter_lines(false, opts.frontmatter), content }\n else\n -- Use existing frontmatter.\n new_lines = compat.flatten { existing_frontmatter, content }\n end\n\n util.write_file(tostring(save_path), table.concat(new_lines, \"\\n\"))\n\n if opts.check_buffers then\n -- `vim.fn.bufnr` returns the **max** bufnr loaded from the same path.\n if vim.fn.bufnr(save_path.filename) ~= -1 then\n -- But we want to call |checktime| on **all** buffers loaded from the path.\n vim.cmd.checktime(save_path.filename)\n end\n end\nend\n\n--- Write the note to a buffer.\n---\n---@param opts { bufnr: integer|?, template: string|? }|? Options.\n---\n--- Options:\n--- - `bufnr`: Override the buffer to write to. Defaults to current buffer.\n--- - `template`: The name of a template to use if the buffer is empty.\n---\n---@return boolean updated If the buffer was updated.\nNote.write_to_buffer = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = opts or {}\n\n if opts.template and api.buffer_is_empty(opts.bufnr) then\n self = Template.insert_template {\n type = \"insert_template\",\n template_name = opts.template,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n location = api.get_active_window_cursor_location(),\n partial_note = self,\n }\n end\n\n local frontmatter = nil\n local should_save_frontmatter = self:should_save_frontmatter()\n if should_save_frontmatter and Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n return self:save_to_buffer {\n bufnr = opts.bufnr,\n insert_frontmatter = should_save_frontmatter,\n frontmatter = frontmatter,\n }\nend\n\n--- Save the note to the buffer\n---\n---@param opts { bufnr: integer|?, insert_frontmatter: boolean|?, frontmatter: table|? }|? Options.\n---\n---@return boolean updated True if the buffer lines were updated, false otherwise.\nNote.save_to_buffer = function(self, opts)\n opts = opts or {}\n\n local bufnr = opts.bufnr\n if not bufnr then\n bufnr = self.bufnr or 0\n end\n\n local cur_buf_note = Note.from_buffer(bufnr)\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n new_lines = self:frontmatter_lines(nil, opts.frontmatter)\n else\n new_lines = {}\n end\n\n if api.buffer_is_empty(bufnr) and self.title ~= nil then\n table.insert(new_lines, \"# \" .. self.title)\n end\n\n ---@type string[]\n local cur_lines = {}\n if cur_buf_note.frontmatter_end_line ~= nil then\n cur_lines = vim.api.nvim_buf_get_lines(bufnr, 0, cur_buf_note.frontmatter_end_line, false)\n end\n\n if not vim.deep_equal(cur_lines, new_lines) then\n vim.api.nvim_buf_set_lines(\n bufnr,\n 0,\n cur_buf_note.frontmatter_end_line and cur_buf_note.frontmatter_end_line or 0,\n false,\n new_lines\n )\n return true\n else\n return false\n end\nend\n\n--- Try to resolve an anchor link to a line number in the note's file.\n---\n---@param anchor_link string\n---@return obsidian.note.HeaderAnchor|?\nNote.resolve_anchor_link = function(self, anchor_link)\n anchor_link = util.standardize_anchor(anchor_link)\n\n if self.anchor_links ~= nil then\n return self.anchor_links[anchor_link]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_anchor_links = true })\n self.anchor_links = n.anchor_links\n return n:resolve_anchor_link(anchor_link)\nend\n\n--- Try to resolve a block identifier.\n---\n---@param block_id string\n---\n---@return obsidian.note.Block|?\nNote.resolve_block = function(self, block_id)\n block_id = util.standardize_block(block_id)\n\n if self.blocks ~= nil then\n return self.blocks[block_id]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_blocks = true })\n self.blocks = n.blocks\n return self.blocks[block_id]\nend\n\n--- Open a note in a buffer.\n---@param opts { line: integer|?, col: integer|?, open_strategy: obsidian.config.OpenStrategy|?, sync: boolean|?, callback: fun(bufnr: integer)|? }|?\nNote.open = function(self, opts)\n opts = opts or {}\n\n local path = self.path\n\n local function open_it()\n local open_cmd = api.get_open_strategy(opts.open_strategy and opts.open_strategy or Obsidian.opts.open_notes_in)\n ---@cast path obsidian.Path\n local bufnr = api.open_buffer(path, { line = opts.line, col = opts.col, cmd = open_cmd })\n if opts.callback then\n opts.callback(bufnr)\n end\n end\n\n if opts.sync then\n open_it()\n else\n vim.schedule(open_it)\n end\nend\n\nreturn Note\n"], ["/obsidian.nvim/lua/obsidian/commands/new_from_template.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type string?\n local title = table.concat(data.fargs, \" \", 1, #data.fargs - 1)\n local template = data.fargs[#data.fargs]\n\n if title ~= nil and template ~= nil then\n local note = Note.create { title = title, template = template, should_write = true }\n note:open { sync = true }\n return\n end\n\n picker:find_templates {\n callback = function(template_name)\n if title == nil or title == \"\" then\n -- Must use pcall in case of KeyboardInterrupt\n -- We cannot place `title` where `safe_title` is because it would be redeclaring it\n local success, safe_title = pcall(util.input, \"Enter title or path (optional): \", { completion = \"file\" })\n title = safe_title\n if not success or not safe_title then\n log.warn \"Aborted\"\n return\n elseif safe_title == \"\" then\n title = nil\n end\n end\n\n if template_name == nil or template_name == \"\" then\n log.warn \"Aborted\"\n return\n end\n\n ---@type obsidian.Note\n local note = Note.create { title = title, template = template_name, should_write = true }\n note:open { sync = false }\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/init.lua", "local iter = vim.iter\nlocal log = require \"obsidian.log\"\nlocal legacycommands = require \"obsidian.commands.init-legacy\"\nlocal search = require \"obsidian.search\"\n\nlocal M = { commands = {} }\n\nlocal function in_note()\n return vim.bo.filetype == \"markdown\"\nend\n\n---@param commands obsidian.CommandConfig[]\n---@param is_visual boolean\n---@param is_note boolean\n---@return string[]\nlocal function get_commands_by_context(commands, is_visual, is_note)\n local choices = vim.tbl_values(commands)\n return vim\n .iter(choices)\n :filter(function(config)\n if is_visual then\n return config.range ~= nil\n else\n return config.range == nil\n end\n end)\n :filter(function(config)\n if is_note then\n return true\n else\n return not config.note_action\n end\n end)\n :map(function(config)\n return config.name\n end)\n :totable()\nend\n\nlocal function show_menu(data)\n local is_visual, is_note = data.range ~= 0, in_note()\n local choices = get_commands_by_context(M.commands, is_visual, is_note)\n\n vim.ui.select(choices, { prompt = \"Obsidian Commands\" }, function(item)\n if item then\n return vim.cmd.Obsidian(item)\n else\n vim.notify(\"Aborted\", 3)\n end\n end)\nend\n\n---@class obsidian.CommandConfig\n---@field complete function|string|?\n---@field nargs string|integer|?\n---@field range boolean|?\n---@field func function|? (obsidian.Client, table) -> nil\n---@field name string?\n---@field note_action boolean?\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfig\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n local mod = require(\"obsidian.commands.\" .. name)\n return mod(client, data)\n end\n end\n config.name = name\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n vim.api.nvim_create_user_command(\"Obsidian\", function(data)\n if #data.fargs == 0 then\n show_menu(data)\n return\n end\n M.handle_command(client, data)\n end, {\n nargs = \"*\",\n complete = function(_, cmdline, _)\n return M.get_completions(client, cmdline)\n end,\n range = 2,\n })\nend\n\nM.install_legacy = legacycommands.install\n\n---@param client obsidian.Client\nM.handle_command = function(client, data)\n local cmd = data.fargs[1]\n table.remove(data.fargs, 1)\n data.args = table.concat(data.fargs, \" \")\n local nargs = #data.fargs\n\n local cmdconfig = M.commands[cmd]\n if cmdconfig == nil then\n log.err(\"Command '\" .. cmd .. \"' not found\")\n return\n end\n\n local exp_nargs = cmdconfig.nargs\n local range_allowed = cmdconfig.range\n\n if exp_nargs == \"?\" then\n if nargs > 1 then\n log.err(\"Command '\" .. cmd .. \"' expects 0 or 1 arguments, but \" .. nargs .. \" were provided\")\n return\n end\n elseif exp_nargs == \"+\" then\n if nargs == 0 then\n log.err(\"Command '\" .. cmd .. \"' expects at least one argument, but none were provided\")\n return\n end\n elseif exp_nargs ~= \"*\" and exp_nargs ~= nargs then\n log.err(\"Command '\" .. cmd .. \"' expects \" .. exp_nargs .. \" arguments, but \" .. nargs .. \" were provided\")\n return\n end\n\n if not range_allowed and data.range > 0 then\n log.error(\"Command '\" .. cmd .. \"' does not accept a range\")\n return\n end\n\n cmdconfig.func(client, data)\nend\n\n---@param client obsidian.Client\n---@param cmdline string\nM.get_completions = function(client, cmdline)\n local obspat = \"^['<,'>]*Obsidian[!]?\"\n local splitcmd = vim.split(cmdline, \" \", { plain = true, trimempty = true })\n local obsidiancmd = splitcmd[2]\n if cmdline:match(obspat .. \"%s$\") then\n local is_visual = vim.startswith(cmdline, \"'<,'>\")\n return get_commands_by_context(M.commands, is_visual, in_note())\n end\n if cmdline:match(obspat .. \"%s%S+$\") then\n return vim.tbl_filter(function(s)\n return s:sub(1, #obsidiancmd) == obsidiancmd\n end, vim.tbl_keys(M.commands))\n end\n local cmdconfig = M.commands[obsidiancmd]\n if cmdconfig == nil then\n return\n end\n if cmdline:match(obspat .. \"%s%S*%s%S*$\") then\n local cmd_arg = table.concat(vim.list_slice(splitcmd, 3), \" \")\n local complete_type = type(cmdconfig.complete)\n if complete_type == \"function\" then\n return cmdconfig.complete(cmd_arg)\n end\n if complete_type == \"string\" then\n return vim.fn.getcompletion(cmd_arg, cmdconfig.complete)\n end\n end\nend\n\n--TODO: Note completion is currently broken (see: https://github.com/epwalsh/obsidian.nvim/issues/753)\n---@return string[]\nM.note_complete = function(cmd_arg)\n local query\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\n------------------------\n---- general action ----\n------------------------\n\nM.register(\"check\", { nargs = 0 })\n\nM.register(\"today\", { nargs = \"?\" })\n\nM.register(\"yesterday\", { nargs = 0 })\n\nM.register(\"tomorrow\", { nargs = 0 })\n\nM.register(\"dailies\", { nargs = \"*\" })\n\nM.register(\"new\", { nargs = \"?\" })\n\nM.register(\"open\", { nargs = \"?\", complete = M.note_complete })\n\nM.register(\"tags\", { nargs = \"*\" })\n\nM.register(\"search\", { nargs = \"?\" })\n\nM.register(\"new_from_template\", { nargs = \"*\" })\n\nM.register(\"quick_switch\", { nargs = \"?\" })\n\nM.register(\"workspace\", { nargs = \"?\" })\n\n---------------------\n---- note action ----\n---------------------\n\nM.register(\"backlinks\", { nargs = 0, note_action = true })\n\nM.register(\"template\", { nargs = \"?\", note_action = true })\n\nM.register(\"link_new\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"link\", { nargs = \"?\", range = true, complete = M.note_complete, note_action = true })\n\nM.register(\"links\", { nargs = 0, note_action = true })\n\nM.register(\"follow_link\", { nargs = \"?\", note_action = true })\n\nM.register(\"toggle_checkbox\", { nargs = 0, range = true, note_action = true })\n\nM.register(\"rename\", { nargs = \"?\", note_action = true })\n\nM.register(\"paste_img\", { nargs = \"?\", note_action = true })\n\nM.register(\"extract_note\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"toc\", { nargs = 0, note_action = true })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/init.lua", "local log = require \"obsidian.log\"\n\nlocal module_lookups = {\n abc = \"obsidian.abc\",\n api = \"obsidian.api\",\n async = \"obsidian.async\",\n Client = \"obsidian.client\",\n commands = \"obsidian.commands\",\n completion = \"obsidian.completion\",\n config = \"obsidian.config\",\n log = \"obsidian.log\",\n img_paste = \"obsidian.img_paste\",\n Note = \"obsidian.note\",\n Path = \"obsidian.path\",\n pickers = \"obsidian.pickers\",\n search = \"obsidian.search\",\n templates = \"obsidian.templates\",\n ui = \"obsidian.ui\",\n util = \"obsidian.util\",\n VERSION = \"obsidian.version\",\n Workspace = \"obsidian.workspace\",\n yaml = \"obsidian.yaml\",\n}\n\nlocal obsidian = setmetatable({}, {\n __index = function(t, k)\n local require_path = module_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@type obsidian.Client|?\nobsidian._client = nil\n\n---Get the current obsidian client.\n---@return obsidian.Client\nobsidian.get_client = function()\n if obsidian._client == nil then\n error \"Obsidian client has not been set! Did you forget to call 'setup()'?\"\n else\n return obsidian._client\n end\nend\n\nobsidian.register_command = require(\"obsidian.commands\").register\n\n--- Setup a new Obsidian client. This should only be called once from an Nvim session.\n---\n---@param opts obsidian.config.ClientOpts | table\n---\n---@return obsidian.Client\nobsidian.setup = function(opts)\n opts = obsidian.config.normalize(opts)\n\n ---@class obsidian.state\n ---@field picker obsidian.Picker The picker instance to use.\n ---@field workspace obsidian.Workspace The current workspace.\n ---@field dir obsidian.Path The root of the vault for the current workspace.\n ---@field buf_dir obsidian.Path|? The parent directory of the current buffer.\n ---@field opts obsidian.config.ClientOpts current options\n ---@field _opts obsidian.config.ClientOpts default options\n _G.Obsidian = {} -- init a state table\n\n local client = obsidian.Client.new(opts)\n\n Obsidian._opts = opts\n\n obsidian.Workspace.set(assert(obsidian.Workspace.get_from_opts(opts)), {})\n\n log.set_level(Obsidian.opts.log_level)\n\n -- Install commands.\n -- These will be available across all buffers, not just note buffers in the vault.\n obsidian.commands.install(client)\n\n if opts.legacy_commands then\n obsidian.commands.install_legacy(client)\n end\n\n if opts.statusline.enabled then\n require(\"obsidian.statusline\").start(client)\n end\n\n if opts.footer.enabled then\n require(\"obsidian.footer\").start(client)\n end\n\n -- Register completion sources, providers\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").register_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").register_providers(opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_setup\", { clear = true })\n\n -- wrapper for creating autocmd events\n ---@param pattern string\n ---@param buf integer\n local function exec_autocmds(pattern, buf)\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = pattern,\n data = {\n note = require(\"obsidian.note\").from_buffer(buf),\n },\n })\n end\n\n -- Complete setup and update workspace (if needed) when entering a markdown buffer.\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Set the current directory of the buffer.\n local buf_dir = vim.fs.dirname(ev.match)\n if buf_dir then\n Obsidian.buf_dir = obsidian.Path.new(buf_dir)\n end\n\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n if opts.comment.enabled then\n vim.o.commentstring = \"%%%s%%\"\n end\n\n -- Switch to the workspace and complete the workspace setup.\n if not Obsidian.workspace.locked and workspace ~= Obsidian.workspace then\n log.debug(\"Switching to workspace '%s' @ '%s'\", workspace.name, workspace.path)\n obsidian.Workspace.set(workspace)\n require(\"obsidian.ui\").update(ev.buf)\n end\n\n -- Register keymap.\n vim.keymap.set(\n \"n\",\n \"\",\n obsidian.api.smart_action,\n { expr = true, buffer = true, desc = \"Obsidian Smart Action\" }\n )\n\n vim.keymap.set(\"n\", \"]o\", function()\n obsidian.api.nav_link \"next\"\n end, { buffer = true, desc = \"Obsidian Next Link\" })\n\n vim.keymap.set(\"n\", \"[o\", function()\n obsidian.api.nav_link \"prev\"\n end, { buffer = true, desc = \"Obsidian Previous Link\" })\n\n -- Inject completion sources, providers to their plugin configurations\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").inject_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").inject_sources(opts)\n end\n\n -- Run enter-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"enter_note\", Obsidian.opts.callbacks.enter_note, client, note)\n\n exec_autocmds(\"ObsidianNoteEnter\", ev.buf)\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufLeave\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(vim.fs.dirname(ev.match), Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Run leave-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"leave_note\", Obsidian.opts.callbacks.leave_note, client, note)\n\n exec_autocmds(\"ObsidianNoteLeave\", ev.buf)\n end,\n })\n\n -- Add/update frontmatter for notes before writing.\n vim.api.nvim_create_autocmd({ \"BufWritePre\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Initialize note.\n local bufnr = ev.buf\n local note = obsidian.Note.from_buffer(bufnr)\n\n -- Run pre-write-note callback.\n obsidian.util.fire_callback(\"pre_write_note\", Obsidian.opts.callbacks.pre_write_note, client, note)\n\n exec_autocmds(\"ObsidianNoteWritePre\", ev.buf)\n\n -- Update buffer with new frontmatter.\n if note:update_frontmatter(bufnr) then\n log.info \"Updated frontmatter\"\n end\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufWritePost\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n exec_autocmds(\"ObsidianNoteWritePost\", ev.buf)\n end,\n })\n\n -- Set global client.\n obsidian._client = client\n\n obsidian.util.fire_callback(\"post_setup\", Obsidian.opts.callbacks.post_setup, client)\n\n return client\nend\n\nreturn obsidian\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/new.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.NewNoteSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\nlocal NewNoteSourceCompletionContext = abc.new_class()\n\nNewNoteSourceCompletionContext.new = function()\n return NewNoteSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.NewNoteSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal NewNoteSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.NewNoteSourceBase\nNewNoteSourceBase.new = function()\n return NewNoteSourceBase.init()\nend\n\nNewNoteSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = NewNoteSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n ---@type string|?\n local block_link\n cc.search, block_link = util.strip_block_links(cc.search)\n\n ---@type string|?\n local anchor_link\n cc.search, anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, do nothing.\n if not block_link and vim.endswith(cc.search, \"#^\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- If anchor link is incomplete, do nothing.\n if not anchor_link and vim.endswith(cc.search, \"#\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Probably just a block/anchor link within current note.\n if string.len(cc.search) == 0 then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Create a mock block.\n ---@type obsidian.note.Block|?\n local block\n if block_link then\n block = { block = \"\", id = util.standardize_block(block_link), line = 1 }\n end\n\n -- Create a mock anchor.\n ---@type obsidian.note.HeaderAnchor|?\n local anchor\n if anchor_link then\n anchor = { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 }\n end\n\n ---@type { label: string, note: obsidian.Note, template: string|? }[]\n local new_notes_opts = {}\n\n local note = Note.create { title = cc.search }\n if note.title and string.len(note.title) > 0 then\n new_notes_opts[#new_notes_opts + 1] = { label = cc.search, note = note }\n end\n\n -- Check for datetime macros.\n for _, dt_offset in ipairs(util.resolve_date_macro(cc.search)) do\n if dt_offset.cadence == \"daily\" then\n note = require(\"obsidian.daily\").daily(dt_offset.offset, { no_write = true })\n if not note:exists() then\n new_notes_opts[#new_notes_opts + 1] =\n { label = dt_offset.macro, note = note, template = Obsidian.opts.daily_notes.template }\n end\n end\n end\n\n -- Completion items.\n local items = {}\n\n for _, new_note_opts in ipairs(new_notes_opts) do\n local new_note = new_note_opts.note\n\n assert(new_note.path)\n\n ---@type obsidian.config.LinkStyle, string\n local link_style, label\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n label = string.format(\"[[%s]] (create)\", new_note_opts.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n label = string.format(\"[%s](…) (create)\", new_note_opts.label)\n else\n error \"not implemented\"\n end\n\n local new_text = api.format_link(new_note, { link_style = link_style, anchor = anchor, block = block })\n local documentation = {\n kind = \"markdown\",\n value = new_note:display_info {\n label = \"Create: \" .. new_text,\n },\n }\n\n items[#items + 1] = {\n documentation = documentation,\n sortText = new_note_opts.label,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = new_text,\n range = {\n start = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n data = {\n note = new_note,\n template = new_note_opts.template,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction NewNoteSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if cc.search ~= nil then\n cc.search = util.lstrip_whitespace(cc.search)\n end\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n return true\nend\n\n--- Runs a generalized version of the execute method\n---@param item any\n---@return table|? callback_return_value\nfunction NewNoteSourceBase:process_execute(item)\n local data = item.data\n\n if data == nil then\n return nil\n end\n\n -- Make sure `data.note` is actually an `obsidian.Note` object. If it gets serialized at some\n -- point (seems to happen on Linux), it will lose its metatable.\n if not Note.is_note_obj(data.note) then\n data.note = setmetatable(data.note, Note.mt)\n data.note.path = setmetatable(data.note.path, Path.mt)\n end\n\n data.note:write { template = data.template }\n return {}\nend\n\nreturn NewNoteSourceBase\n"], ["/obsidian.nvim/lua/obsidian/config.lua", "local log = require \"obsidian.log\"\n\nlocal config = {}\n\n---@class obsidian.config\n---@field workspaces obsidian.workspace.WorkspaceSpec[]\n---@field log_level? integer\n---@field notes_subdir? string\n---@field templates? obsidian.config.TemplateOpts\n---@field new_notes_location? obsidian.config.NewNotesLocation\n---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func? fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path\n---@field wiki_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field markdown_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field preferred_link_style? obsidian.config.LinkStyle\n---@field follow_url_func? fun(url: string)\n---@field follow_img_func? fun(img: string)\n---@field note_frontmatter_func? (fun(note: obsidian.Note): table)\n---@field disable_frontmatter? (fun(fname: string?): boolean)|boolean\n---@field backlinks? obsidian.config.BacklinkOpts\n---@field completion? obsidian.config.CompletionOpts\n---@field picker? obsidian.config.PickerOpts\n---@field daily_notes? obsidian.config.DailyNotesOpts\n---@field sort_by? obsidian.config.SortBy\n---@field sort_reversed? boolean\n---@field search_max_lines? integer\n---@field open_notes_in? obsidian.config.OpenStrategy\n---@field ui? obsidian.config.UIOpts | table\n---@field attachments? obsidian.config.AttachmentsOpts\n---@field callbacks? obsidian.config.CallbackConfig\n---@field legacy_commands? boolean\n---@field statusline? obsidian.config.StatuslineOpts\n---@field footer? obsidian.config.FooterOpts\n---@field open? obsidian.config.OpenOpts\n---@field checkbox? obsidian.config.CheckboxOpts\n---@field comment? obsidian.config.CommentOpts\n\n---@class obsidian.config.ClientOpts\n---@field dir string|?\n---@field workspaces obsidian.workspace.WorkspaceSpec[]|?\n---@field log_level integer\n---@field notes_subdir string|?\n---@field templates obsidian.config.TemplateOpts\n---@field new_notes_location obsidian.config.NewNotesLocation\n---@field note_id_func (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func (fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path)|?\n---@field wiki_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field markdown_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field preferred_link_style obsidian.config.LinkStyle\n---@field follow_url_func fun(url: string)|?\n---@field follow_img_func fun(img: string)|?\n---@field note_frontmatter_func (fun(note: obsidian.Note): table)|?\n---@field disable_frontmatter (fun(fname: string?): boolean)|boolean|?\n---@field backlinks obsidian.config.BacklinkOpts\n---@field completion obsidian.config.CompletionOpts\n---@field picker obsidian.config.PickerOpts\n---@field daily_notes obsidian.config.DailyNotesOpts\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field search_max_lines integer\n---@field open_notes_in obsidian.config.OpenStrategy\n---@field ui obsidian.config.UIOpts | table\n---@field attachments obsidian.config.AttachmentsOpts\n---@field callbacks obsidian.config.CallbackConfig\n---@field legacy_commands boolean\n---@field statusline obsidian.config.StatuslineOpts\n---@field footer obsidian.config.FooterOpts\n---@field open obsidian.config.OpenOpts\n---@field checkbox obsidian.config.CheckboxOpts\n---@field comment obsidian.config.CommentOpts\n\n---@enum obsidian.config.OpenStrategy\nconfig.OpenStrategy = {\n current = \"current\",\n vsplit = \"vsplit\",\n hsplit = \"hsplit\",\n vsplit_force = \"vsplit_force\",\n hsplit_force = \"hsplit_force\",\n}\n\n---@enum obsidian.config.SortBy\nconfig.SortBy = {\n path = \"path\",\n modified = \"modified\",\n accessed = \"accessed\",\n created = \"created\",\n}\n\n---@enum obsidian.config.NewNotesLocation\nconfig.NewNotesLocation = {\n current_dir = \"current_dir\",\n notes_subdir = \"notes_subdir\",\n}\n\n---@enum obsidian.config.LinkStyle\nconfig.LinkStyle = {\n wiki = \"wiki\",\n markdown = \"markdown\",\n}\n\n---@enum obsidian.config.Picker\nconfig.Picker = {\n telescope = \"telescope.nvim\",\n fzf_lua = \"fzf-lua\",\n mini = \"mini.pick\",\n snacks = \"snacks.pick\",\n}\n\n--- Get defaults.\n---\n---@return obsidian.config.ClientOpts\nconfig.default = {\n legacy_commands = true,\n workspaces = {},\n log_level = vim.log.levels.INFO,\n notes_subdir = nil,\n new_notes_location = config.NewNotesLocation.current_dir,\n note_id_func = nil,\n wiki_link_func = require(\"obsidian.builtin\").wiki_link_id_prefix,\n markdown_link_func = require(\"obsidian.builtin\").markdown_link,\n preferred_link_style = config.LinkStyle.wiki,\n follow_url_func = vim.ui.open,\n follow_img_func = vim.ui.open,\n note_frontmatter_func = nil,\n disable_frontmatter = false,\n sort_by = \"modified\",\n sort_reversed = true,\n search_max_lines = 1000,\n open_notes_in = \"current\",\n\n ---@class obsidian.config.TemplateOpts\n ---\n ---@field folder string|obsidian.Path|?\n ---@field date_format string|?\n ---@field time_format string|?\n --- A map for custom variables, the key should be the variable and the value a function.\n --- Functions are called with obsidian.TemplateContext objects as their sole parameter.\n --- See: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Template#substitutions\n ---@field substitutions table|?\n ---@field customizations table|?\n templates = {\n folder = nil,\n date_format = nil,\n time_format = nil,\n substitutions = {},\n\n ---@class obsidian.config.CustomTemplateOpts\n ---\n ---@field notes_subdir? string\n ---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n customizations = {},\n },\n\n ---@class obsidian.config.BacklinkOpts\n ---\n ---@field parse_headers boolean\n backlinks = {\n parse_headers = true,\n },\n\n ---@class obsidian.config.CompletionOpts\n ---\n ---@field nvim_cmp? boolean\n ---@field blink? boolean\n ---@field min_chars? integer\n ---@field match_case? boolean\n ---@field create_new? boolean\n completion = (function()\n local has_nvim_cmp, _ = pcall(require, \"cmp\")\n return {\n nvim_cmp = has_nvim_cmp,\n min_chars = 2,\n match_case = true,\n create_new = true,\n }\n end)(),\n\n ---@class obsidian.config.PickerNoteMappingOpts\n ---\n ---@field new? string\n ---@field insert_link? string\n\n ---@class obsidian.config.PickerTagMappingOpts\n ---\n ---@field tag_note? string\n ---@field insert_tag? string\n\n ---@class obsidian.config.PickerOpts\n ---\n ---@field name obsidian.config.Picker|?\n ---@field note_mappings? obsidian.config.PickerNoteMappingOpts\n ---@field tag_mappings? obsidian.config.PickerTagMappingOpts\n picker = {\n name = nil,\n note_mappings = {\n new = \"\",\n insert_link = \"\",\n },\n tag_mappings = {\n tag_note = \"\",\n insert_tag = \"\",\n },\n },\n\n ---@class obsidian.config.DailyNotesOpts\n ---\n ---@field folder? string\n ---@field date_format? string\n ---@field alias_format? string\n ---@field template? string\n ---@field default_tags? string[]\n ---@field workdays_only? boolean\n daily_notes = {\n folder = nil,\n date_format = nil,\n alias_format = nil,\n default_tags = { \"daily-notes\" },\n workdays_only = true,\n },\n\n ---@class obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.CheckboxSpec : obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.UIStyleSpec\n ---@field hl_group string\n\n ---@class obsidian.config.UIOpts\n ---\n ---@field enable boolean\n ---@field ignore_conceal_warn boolean\n ---@field update_debounce integer\n ---@field max_file_length integer|?\n ---@field checkboxes table\n ---@field bullets obsidian.config.UICharSpec|?\n ---@field external_link_icon obsidian.config.UICharSpec\n ---@field reference_text obsidian.config.UIStyleSpec\n ---@field highlight_text obsidian.config.UIStyleSpec\n ---@field tags obsidian.config.UIStyleSpec\n ---@field block_ids obsidian.config.UIStyleSpec\n ---@field hl_groups table\n ui = {\n enable = true,\n ignore_conceal_warn = false,\n update_debounce = 200,\n max_file_length = 5000,\n checkboxes = {\n [\" \"] = { char = \"󰄱\", hl_group = \"obsidiantodo\" },\n [\"~\"] = { char = \"󰰱\", hl_group = \"obsidiantilde\" },\n [\"!\"] = { char = \"\", hl_group = \"obsidianimportant\" },\n [\">\"] = { char = \"\", hl_group = \"obsidianrightarrow\" },\n [\"x\"] = { char = \"\", hl_group = \"obsidiandone\" },\n },\n bullets = { char = \"•\", hl_group = \"ObsidianBullet\" },\n external_link_icon = { char = \"\", hl_group = \"ObsidianExtLinkIcon\" },\n reference_text = { hl_group = \"ObsidianRefText\" },\n highlight_text = { hl_group = \"ObsidianHighlightText\" },\n tags = { hl_group = \"ObsidianTag\" },\n block_ids = { hl_group = \"ObsidianBlockID\" },\n hl_groups = {\n ObsidianTodo = { bold = true, fg = \"#f78c6c\" },\n ObsidianDone = { bold = true, fg = \"#89ddff\" },\n ObsidianRightArrow = { bold = true, fg = \"#f78c6c\" },\n ObsidianTilde = { bold = true, fg = \"#ff5370\" },\n ObsidianImportant = { bold = true, fg = \"#d73128\" },\n ObsidianBullet = { bold = true, fg = \"#89ddff\" },\n ObsidianRefText = { underline = true, fg = \"#c792ea\" },\n ObsidianExtLinkIcon = { fg = \"#c792ea\" },\n ObsidianTag = { italic = true, fg = \"#89ddff\" },\n ObsidianBlockID = { italic = true, fg = \"#89ddff\" },\n ObsidianHighlightText = { bg = \"#75662e\" },\n },\n },\n\n ---@class obsidian.config.AttachmentsOpts\n ---\n ---Default folder to save images to, relative to the vault root (/) or current dir (.), see https://github.com/obsidian-nvim/obsidian.nvim/wiki/Images#change-image-save-location\n ---@field img_folder? string\n ---\n ---Default name for pasted images\n ---@field img_name_func? fun(): string\n ---\n ---Default text to insert for pasted images\n ---@field img_text_func? fun(path: obsidian.Path): string\n ---\n ---Whether to confirm the paste or not. Defaults to true.\n ---@field confirm_img_paste? boolean\n attachments = {\n img_folder = \"assets/imgs\",\n img_text_func = require(\"obsidian.builtin\").img_text_func,\n img_name_func = function()\n return string.format(\"Pasted image %s\", os.date \"%Y%m%d%H%M%S\")\n end,\n confirm_img_paste = true,\n },\n\n ---@class obsidian.config.CallbackConfig\n ---\n ---Runs right after the `obsidian.Client` is initialized.\n ---@field post_setup? fun(client: obsidian.Client)\n ---\n ---Runs when entering a note buffer.\n ---@field enter_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs when leaving a note buffer.\n ---@field leave_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs right before writing a note buffer.\n ---@field pre_write_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs anytime the workspace is set/changed.\n ---@field post_set_workspace? fun(client: obsidian.Client, workspace: obsidian.Workspace)\n callbacks = {},\n\n ---@class obsidian.config.StatuslineOpts\n ---\n ---@field format? string\n ---@field enabled? boolean\n statusline = {\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n enabled = true,\n },\n\n ---@class obsidian.config.FooterOpts\n ---\n ---@field enabled? boolean\n ---@field format? string\n ---@field hl_group? string\n ---@field separator? string|false Set false to disable separator; set an empty string to insert a blank line separator.\n footer = {\n enabled = true,\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n hl_group = \"Comment\",\n separator = string.rep(\"-\", 80),\n },\n\n ---@class obsidian.config.OpenOpts\n ---\n ---Opens the file with current line number\n ---@field use_advanced_uri? boolean\n ---\n ---Function to do the opening, default to vim.ui.open\n ---@field func? fun(uri: string)\n open = {\n use_advanced_uri = false,\n func = vim.ui.open,\n },\n\n ---@class obsidian.config.CheckboxOpts\n ---\n ---@field enabled? boolean\n ---\n ---Order of checkbox state chars, e.g. { \" \", \"x\" }\n ---@field order? string[]\n ---\n ---Whether to create new checkbox on paragraphs\n ---@field create_new? boolean\n checkbox = {\n enabled = true,\n create_new = true,\n order = { \" \", \"~\", \"!\", \">\", \"x\" },\n },\n\n ---@class obsidian.config.CommentOpts\n ---@field enabled boolean\n comment = {\n enabled = false,\n },\n}\n\nlocal tbl_override = function(defaults, overrides)\n local out = vim.tbl_extend(\"force\", defaults, overrides)\n for k, v in pairs(out) do\n if v == vim.NIL then\n out[k] = nil\n end\n end\n return out\nend\n\nlocal function deprecate(name, alternative, version)\n vim.deprecate(name, alternative, version, \"obsidian.nvim\", false)\nend\n\n--- Normalize options.\n---\n---@param opts table\n---@param defaults obsidian.config.ClientOpts|?\n---\n---@return obsidian.config.ClientOpts\nconfig.normalize = function(opts, defaults)\n local builtin = require \"obsidian.builtin\"\n local util = require \"obsidian.util\"\n\n if not defaults then\n defaults = config.default\n end\n\n -------------------------------------------------------------------------------------\n -- Rename old fields for backwards compatibility and warn about deprecated fields. --\n -------------------------------------------------------------------------------------\n\n if opts.ui and opts.ui.tick then\n opts.ui.update_debounce = opts.ui.tick\n opts.ui.tick = nil\n end\n\n if not opts.picker then\n opts.picker = {}\n if opts.finder then\n opts.picker.name = opts.finder\n opts.finder = nil\n end\n if opts.finder_mappings then\n opts.picker.note_mappings = opts.finder_mappings\n opts.finder_mappings = nil\n end\n if opts.picker.mappings and not opts.picker.note_mappings then\n opts.picker.note_mappings = opts.picker.mappings\n opts.picker.mappings = nil\n end\n end\n\n if opts.wiki_link_func == nil and opts.completion ~= nil then\n local warn = false\n\n if opts.completion.prepend_note_id then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n opts.completion.prepend_note_id = nil\n warn = true\n elseif opts.completion.prepend_note_path then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n opts.completion.prepend_note_path = nil\n warn = true\n elseif opts.completion.use_path_only then\n opts.wiki_link_func = builtin.wiki_link_path_only\n opts.completion.use_path_only = nil\n warn = true\n end\n\n if warn then\n log.warn_once(\n \"The config options 'completion.prepend_note_id', 'completion.prepend_note_path', and 'completion.use_path_only' \"\n .. \"are deprecated. Please use 'wiki_link_func' instead.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/406\"\n )\n end\n end\n\n if opts.wiki_link_func == \"prepend_note_id\" then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n elseif opts.wiki_link_func == \"prepend_note_path\" then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n elseif opts.wiki_link_func == \"use_path_only\" then\n opts.wiki_link_func = builtin.wiki_link_path_only\n elseif opts.wiki_link_func == \"use_alias_only\" then\n opts.wiki_link_func = builtin.wiki_link_alias_only\n elseif type(opts.wiki_link_func) == \"string\" then\n error(string.format(\"invalid option '%s' for 'wiki_link_func'\", opts.wiki_link_func))\n end\n\n if opts.completion ~= nil and opts.completion.preferred_link_style ~= nil then\n opts.preferred_link_style = opts.completion.preferred_link_style\n opts.completion.preferred_link_style = nil\n log.warn_once(\n \"The config option 'completion.preferred_link_style' is deprecated, please use the top-level \"\n .. \"'preferred_link_style' instead.\"\n )\n end\n\n if opts.completion ~= nil and opts.completion.new_notes_location ~= nil then\n opts.new_notes_location = opts.completion.new_notes_location\n opts.completion.new_notes_location = nil\n log.warn_once(\n \"The config option 'completion.new_notes_location' is deprecated, please use the top-level \"\n .. \"'new_notes_location' instead.\"\n )\n end\n\n if opts.detect_cwd ~= nil then\n opts.detect_cwd = nil\n log.warn_once(\n \"The 'detect_cwd' field is deprecated and no longer has any affect.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/366 for more details.\"\n )\n end\n\n if opts.open_app_foreground ~= nil then\n opts.open_app_foreground = nil\n log.warn_once [[The config option 'open_app_foreground' is deprecated, please use the `func` field in `open` module:\n\n```lua\n{\n open = {\n func = function(uri)\n vim.ui.open(uri, { cmd = { \"open\", \"-a\", \"/Applications/Obsidian.app\" } })\n end\n }\n}\n```]]\n end\n\n if opts.use_advanced_uri ~= nil then\n opts.use_advanced_uri = nil\n log.warn_once [[The config option 'use_advanced_uri' is deprecated, please use in `open` module instead]]\n end\n\n if opts.overwrite_mappings ~= nil then\n log.warn_once \"The 'overwrite_mappings' config option is deprecated and no longer has any affect.\"\n opts.overwrite_mappings = nil\n end\n\n if opts.mappings ~= nil then\n log.warn_once [[The 'mappings' config option is deprecated and no longer has any affect.\nSee: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Keymaps]]\n opts.overwrite_mappings = nil\n end\n\n if opts.tags ~= nil then\n log.warn_once \"The 'tags' config option is deprecated and no longer has any affect.\"\n opts.tags = nil\n end\n\n if opts.templates and opts.templates.subdir then\n opts.templates.folder = opts.templates.subdir\n opts.templates.subdir = nil\n end\n\n if opts.image_name_func then\n if opts.attachments == nil then\n opts.attachments = {}\n end\n opts.attachments.img_name_func = opts.image_name_func\n opts.image_name_func = nil\n end\n\n if opts.statusline and opts.statusline.enabled then\n deprecate(\"statusline.{enabled,format} and vim.g.obsidian\", \"footer.{enabled,format}\", \"4.0\")\n end\n\n --------------------------\n -- Merge with defaults. --\n --------------------------\n\n ---@type obsidian.config.ClientOpts\n opts = tbl_override(defaults, opts)\n\n opts.backlinks = tbl_override(defaults.backlinks, opts.backlinks)\n opts.completion = tbl_override(defaults.completion, opts.completion)\n opts.picker = tbl_override(defaults.picker, opts.picker)\n opts.daily_notes = tbl_override(defaults.daily_notes, opts.daily_notes)\n opts.templates = tbl_override(defaults.templates, opts.templates)\n opts.ui = tbl_override(defaults.ui, opts.ui)\n opts.attachments = tbl_override(defaults.attachments, opts.attachments)\n opts.statusline = tbl_override(defaults.statusline, opts.statusline)\n opts.footer = tbl_override(defaults.footer, opts.footer)\n opts.open = tbl_override(defaults.open, opts.open)\n opts.checkbox = tbl_override(defaults.checkbox, opts.checkbox)\n opts.comment = tbl_override(defaults.comment, opts.comment)\n\n ---------------\n -- Validate. --\n ---------------\n\n if opts.legacy_commands then\n deprecate(\n \"legacy_commands\",\n [[move from commands like `ObsidianBacklinks` to `Obsidian backlinks`\nand set `opts.legacy_commands` to false to get rid of this warning.\nsee https://github.com/obsidian-nvim/obsidian.nvim/wiki/Commands for details.\n ]],\n \"4.0\"\n )\n end\n\n if opts.sort_by ~= nil and not vim.tbl_contains(vim.tbl_values(config.SortBy), opts.sort_by) then\n error(\"Invalid 'sort_by' option '\" .. opts.sort_by .. \"' in obsidian.nvim config.\")\n end\n\n if not util.islist(opts.workspaces) then\n error \"Invalid obsidian.nvim config, the 'config.workspaces' should be an array/list.\"\n elseif vim.tbl_isempty(opts.workspaces) then\n error \"At least one workspace is required!\\nPlease specify a workspace \"\n end\n\n for i, workspace in ipairs(opts.workspaces) do\n local path = type(workspace.path) == \"function\" and workspace.path() or workspace.path\n ---@cast path -function\n opts.workspaces[i].path = vim.fn.resolve(vim.fs.normalize(path))\n end\n\n -- Convert dir to workspace format.\n if opts.dir ~= nil then\n table.insert(opts.workspaces, 1, { path = opts.dir })\n end\n\n return opts\nend\n\nreturn config\n"], ["/obsidian.nvim/lua/obsidian/commands/workspace.lua", "local log = require \"obsidian.log\"\nlocal Workspace = require \"obsidian.workspace\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.info(\"Current workspace: '%s' @ '%s'\", Obsidian.workspace.name, Obsidian.workspace.path)\n return\n end\n\n local options = {}\n for i, spec in ipairs(Obsidian.opts.workspaces) do\n local workspace = Workspace.new_from_spec(spec)\n if workspace == Obsidian.workspace then\n options[#options + 1] = string.format(\"*[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n else\n options[#options + 1] = string.format(\"[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n end\n end\n\n picker:pick(options, {\n prompt_title = \"Workspaces\",\n callback = function(workspace_str)\n local idx = tonumber(string.match(workspace_str, \"%*?%[(%d+)]\"))\n Workspace.switch(Obsidian.opts.workspaces[idx].name, { lock = true })\n end,\n })\n else\n Workspace.switch(data.args, { lock = true })\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/footer/init.lua", "local M = {}\nlocal api = require \"obsidian.api\"\n\nlocal ns_id = vim.api.nvim_create_namespace \"ObsidianFooter\"\n\n--- Register buffer-specific variables\nM.start = function(client)\n local refresh_info = function(buf)\n local note = api.current_note(buf)\n if not note then\n return\n end\n local info = {}\n local wc = vim.fn.wordcount()\n info.words = wc.words\n info.chars = wc.chars\n info.properties = vim.tbl_count(note:frontmatter())\n info.backlinks = #client:find_backlinks(note)\n return info\n end\n\n local function update_obsidian_footer(buf)\n local info = refresh_info(buf)\n if info == nil then\n return\n end\n local footer_text = assert(Obsidian.opts.footer.format)\n for k, v in pairs(info) do\n footer_text = footer_text:gsub(\"{{\" .. k .. \"}}\", v)\n end\n local row0 = #vim.api.nvim_buf_get_lines(buf, 0, -2, false)\n local col0 = 0\n local separator = Obsidian.opts.footer.separator\n local hl_group = Obsidian.opts.footer.hl_group\n local footer_contents = { { footer_text, hl_group } }\n local footer_chunks\n if separator then\n local footer_separator = { { separator, hl_group } }\n footer_chunks = { footer_separator, footer_contents }\n else\n footer_chunks = { footer_contents }\n end\n local opts = { virt_lines = footer_chunks }\n vim.api.nvim_buf_clear_namespace(buf, ns_id, 0, -1)\n vim.api.nvim_buf_set_extmark(buf, ns_id, row0, col0, opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_footer\", {})\n local attached_bufs = {}\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n desc = \"Initialize obsidian footer\",\n pattern = \"ObsidianNoteEnter\",\n callback = function(ev)\n if attached_bufs[ev.buf] then\n return\n end\n vim.schedule(function()\n update_obsidian_footer(ev.buf)\n end)\n local id = vim.api.nvim_create_autocmd({\n \"FileChangedShellPost\",\n \"TextChanged\",\n \"TextChangedI\",\n \"TextChangedP\",\n }, {\n group = group,\n desc = \"Update obsidian footer\",\n buffer = ev.buf,\n callback = vim.schedule_wrap(function()\n update_obsidian_footer(ev.buf)\n end),\n })\n attached_bufs[ev.buf] = id\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/open.lua", "local api = require \"obsidian.api\"\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\nlocal log = require \"obsidian.log\"\n\n---@param path? string|obsidian.Path\nlocal function open_in_app(path)\n local vault_name = vim.fs.basename(tostring(Obsidian.workspace.root))\n if not path then\n return Obsidian.opts.open.func(\"obsidian://open?vault=\" .. vim.uri_encode(vault_name))\n end\n path = tostring(path)\n local this_os = api.get_os()\n\n -- Normalize path for windows.\n if this_os == api.OSType.Windows then\n path = string.gsub(path, \"/\", \"\\\\\")\n end\n\n local encoded_vault = vim.uri_encode(vault_name)\n local encoded_path = vim.uri_encode(path)\n\n local uri\n if Obsidian.opts.open.use_advanced_uri then\n local line = vim.api.nvim_win_get_cursor(0)[1] or 1\n uri = (\"obsidian://advanced-uri?vault=%s&filepath=%s&line=%i\"):format(encoded_vault, encoded_path, line)\n else\n uri = (\"obsidian://open?vault=%s&file=%s\"):format(encoded_vault, encoded_path)\n end\n print(uri)\n\n Obsidian.opts.open.func(uri)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type string|?\n local search_term\n\n if data.args and data.args:len() > 0 then\n search_term = data.args\n else\n -- Check for a note reference under the cursor.\n local link_string, _ = api.cursor_link()\n search_term = link_string\n end\n\n if search_term then\n search.resolve_link_async(search_term, function(results)\n if vim.tbl_isempty(results) then\n return log.err \"Note under cusros is not resolved\"\n end\n vim.schedule(function()\n open_in_app(results[1].path)\n end)\n end)\n else\n -- Otherwise use the path of the current buffer.\n local bufname = vim.api.nvim_buf_get_name(0)\n local path = Path.new(bufname):vault_relative_path()\n open_in_app(path)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/util.lua", "local compat = require \"obsidian.compat\"\nlocal ts, string, table = vim.treesitter, string, table\nlocal util = {}\n\nsetmetatable(util, {\n __index = function(_, k)\n return require(\"obsidian.api\")[k] or require(\"obsidian.builtin\")[k]\n end,\n})\n\n-------------------\n--- File tools ----\n-------------------\n\n---@param file string\n---@param contents string\nutil.write_file = function(file, contents)\n local fd = assert(io.open(file, \"w+\"))\n fd:write(contents)\n fd:close()\nend\n\n-------------------\n--- Iter tools ----\n-------------------\n\n---Create an enumeration iterator over an iterable.\n---@param iterable table|string|function\n---@return function\nutil.enumerate = function(iterable)\n local iterator = vim.iter(iterable)\n local i = 0\n\n return function()\n local next = iterator()\n if next == nil then\n return nil, nil\n else\n i = i + 1\n return i, next\n end\n end\nend\n\n---Zip two iterables together.\n---@param iterable1 table|string|function\n---@param iterable2 table|string|function\n---@return function\nutil.zip = function(iterable1, iterable2)\n local iterator1 = vim.iter(iterable1)\n local iterator2 = vim.iter(iterable2)\n\n return function()\n local next1 = iterator1()\n local next2 = iterator2()\n if next1 == nil or next2 == nil then\n return nil\n else\n return next1, next2\n end\n end\nend\n\n-------------------\n--- Table tools ---\n-------------------\n\n---Check if an object is an array-like table.\n--- TODO: after 0.12 replace with vim.islist\n---\n---@param t any\n---@return boolean\nutil.islist = function(t)\n return compat.is_list(t)\nend\n\n---Return a new list table with only the unique values of the original table.\n---\n---@param t table\n---@return any[]\nutil.tbl_unique = function(t)\n local found = {}\n for _, val in pairs(t) do\n found[val] = true\n end\n return vim.tbl_keys(found)\nend\n\n--------------------\n--- String Tools ---\n--------------------\n\n---Iterate over all matches of 'pattern' in 's'. 'gfind' is to 'find' as 'gsub' is to 'sub'.\n---@param s string\n---@param pattern string\n---@param init integer|?\n---@param plain boolean|?\nutil.gfind = function(s, pattern, init, plain)\n init = init and init or 1\n\n return function()\n if init < #s then\n local m_start, m_end = string.find(s, pattern, init, plain)\n if m_start ~= nil and m_end ~= nil then\n init = m_end + 1\n return m_start, m_end\n end\n end\n return nil\n end\nend\n\nlocal char_to_hex = function(c)\n return string.format(\"%%%02X\", string.byte(c))\nend\n\n--- Encode a string into URL-safe version.\n---\n---@param str string\n---@param opts { keep_path_sep: boolean|? }|?\n---\n---@return string\nutil.urlencode = function(str, opts)\n opts = opts or {}\n local url = str\n url = url:gsub(\"\\n\", \"\\r\\n\")\n url = url:gsub(\"([%(%)%*%?%[%]%$\\\"':<>|\\\\'{}])\", char_to_hex)\n if not opts.keep_path_sep then\n url = url:gsub(\"/\", char_to_hex)\n end\n\n -- Spaces in URLs are always safely encoded with `%20`, but not always safe\n -- with `+`. For example, `+` in a query param's value will be interpreted\n -- as a literal plus-sign if the decoder is using JavaScript's `decodeURI`\n -- function.\n url = url:gsub(\" \", \"%%20\")\n return url\nend\n\nutil.is_hex_color = function(s)\n return (s:match \"^#%x%x%x$\" or s:match \"^#%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x%x%x$\")\n ~= nil\nend\n\n---Match the case of 'key' to the given 'prefix' of the key.\n---\n---@param prefix string\n---@param key string\n---@return string|?\nutil.match_case = function(prefix, key)\n local out_chars = {}\n for i = 1, string.len(key) do\n local c_key = string.sub(key, i, i)\n local c_pre = string.sub(prefix, i, i)\n if c_pre:lower() == c_key:lower() then\n table.insert(out_chars, c_pre)\n elseif c_pre:len() > 0 then\n return nil\n else\n table.insert(out_chars, c_key)\n end\n end\n return table.concat(out_chars, \"\")\nend\n\n---Check if a string is a checkbox list item\n---\n---Supported checboox lists:\n--- - [ ] foo\n--- - [x] foo\n--- + [x] foo\n--- * [ ] foo\n--- 1. [ ] foo\n--- 1) [ ] foo\n---\n---@param s string\n---@return boolean\nutil.is_checkbox = function(s)\n -- - [ ] and * [ ] and + [ ]\n if string.match(s, \"^%s*[-+*]%s+%[.%]\") ~= nil then\n return true\n end\n -- 1. [ ] and 1) [ ]\n if string.match(s, \"^%s*%d+[%.%)]%s+%[.%]\") ~= nil then\n return true\n end\n return false\nend\n\n---Check if a string is a valid URL.\n---@param s string\n---@return boolean\nutil.is_url = function(s)\n local search = require \"obsidian.search\"\n\n if\n string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.NakedUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.FileUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.MailtoUrl] .. \"$\")\n then\n return true\n else\n return false\n end\nend\n\n---Checks if a given string represents an image file based on its suffix.\n---\n---@param s string: The input string to check.\n---@return boolean: Returns true if the string ends with a supported image suffix, false otherwise.\nutil.is_img = function(s)\n for _, suffix in ipairs { \".png\", \".jpg\", \".jpeg\", \".heic\", \".gif\", \".svg\", \".ico\" } do\n if vim.endswith(s, suffix) then\n return true\n end\n end\n return false\nend\n\n-- This function removes a single backslash within double square brackets\nutil.unescape_single_backslash = function(text)\n return text:gsub(\"(%[%[[^\\\\]+)\\\\(%|[^\\\\]+]])\", \"%1%2\")\nend\n\nutil.string_enclosing_chars = { [[\"]], [[']] }\n\n---Count the indentation of a line.\n---@param str string\n---@return integer\nutil.count_indent = function(str)\n local indent = 0\n for i = 1, #str do\n local c = string.sub(str, i, i)\n -- space or tab both count as 1 indent\n if c == \" \" or c == \"\t\" then\n indent = indent + 1\n else\n break\n end\n end\n return indent\nend\n\n---Check if a string is only whitespace.\n---@param str string\n---@return boolean\nutil.is_whitespace = function(str)\n return string.match(str, \"^%s+$\") ~= nil\nend\n\n---Get the substring of `str` starting from the first character and up to the stop character,\n---ignoring any enclosing characters (like double quotes) and stop characters that are within the\n---enclosing characters. For example, if `str = [=[\"foo\", \"bar\"]=]` and `stop_char = \",\"`, this\n---would return the string `[=[foo]=]`.\n---\n---@param str string\n---@param stop_chars string[]\n---@param keep_stop_char boolean|?\n---@return string|?, string\nutil.next_item = function(str, stop_chars, keep_stop_char)\n local og_str = str\n\n -- Check for enclosing characters.\n local enclosing_char = nil\n local first_char = string.sub(str, 1, 1)\n for _, c in ipairs(util.string_enclosing_chars) do\n if first_char == c then\n enclosing_char = c\n str = string.sub(str, 2)\n break\n end\n end\n\n local result\n local hits\n\n for _, stop_char in ipairs(stop_chars) do\n -- First check for next item when `stop_char` is present.\n if enclosing_char ~= nil then\n result, hits = string.gsub(\n str,\n \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*\" .. stop_char .. \".*\",\n \"%1%2\"\n )\n result = enclosing_char .. result .. enclosing_char\n else\n result, hits = string.gsub(str, \"([^\" .. stop_char .. \"]+)\" .. stop_char .. \".*\", \"%1\")\n end\n if hits ~= 0 then\n local i = string.find(str, stop_char, string.len(result), true)\n if keep_stop_char then\n return result .. stop_char, string.sub(str, i + 1)\n else\n return result, string.sub(str, i + 1)\n end\n end\n\n -- Now check for next item without the `stop_char` after.\n if not keep_stop_char and enclosing_char ~= nil then\n result, hits = string.gsub(str, \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*$\", \"%1%2\")\n result = enclosing_char .. result .. enclosing_char\n elseif not keep_stop_char then\n result = str\n hits = 1\n else\n result = nil\n hits = 0\n end\n if hits ~= 0 then\n if keep_stop_char then\n result = result .. stop_char\n end\n return result, \"\"\n end\n end\n\n return nil, og_str\nend\n\n---Strip whitespace from the right end of a string.\n---@param str string\n---@return string\nutil.rstrip_whitespace = function(str)\n str = string.gsub(str, \"%s+$\", \"\")\n return str\nend\n\n---Strip whitespace from the left end of a string.\n---@param str string\n---@param limit integer|?\n---@return string\nutil.lstrip_whitespace = function(str, limit)\n if limit ~= nil then\n local num_found = 0\n while num_found < limit do\n str = string.gsub(str, \"^%s\", \"\")\n num_found = num_found + 1\n end\n else\n str = string.gsub(str, \"^%s+\", \"\")\n end\n return str\nend\n\n---Strip enclosing characters like quotes from a string.\n---@param str string\n---@return string\nutil.strip_enclosing_chars = function(str)\n local c_start = string.sub(str, 1, 1)\n local c_end = string.sub(str, #str, #str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if c_start == enclosing_char and c_end == enclosing_char then\n str = string.sub(str, 2, #str - 1)\n break\n end\n end\n return str\nend\n\n---Check if a string has enclosing characters like quotes.\n---@param str string\n---@return boolean\nutil.has_enclosing_chars = function(str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if vim.startswith(str, enclosing_char) and vim.endswith(str, enclosing_char) then\n return true\n end\n end\n return false\nend\n\n---Strip YAML comments from a string.\n---@param str string\n---@return string\nutil.strip_comments = function(str)\n if vim.startswith(str, \"# \") then\n return \"\"\n elseif not util.has_enclosing_chars(str) then\n return select(1, string.gsub(str, [[%s+#%s.*$]], \"\"))\n else\n return str\n end\nend\n\n---Check if a string contains a substring.\n---@param str string\n---@param substr string\n---@return boolean\nutil.string_contains = function(str, substr)\n local i = string.find(str, substr, 1, true)\n return i ~= nil\nend\n\n--------------------\n--- Date helpers ---\n--------------------\n\n---Determines if the given date is a working day (not weekend)\n---\n---@param time integer\n---\n---@return boolean\nutil.is_working_day = function(time)\n local is_saturday = (os.date(\"%w\", time) == \"6\")\n local is_sunday = (os.date(\"%w\", time) == \"0\")\n return not (is_saturday or is_sunday)\nend\n\n--- Returns the previous day from given time\n---\n--- @param time integer\n--- @return integer\nutil.previous_day = function(time)\n return time - (24 * 60 * 60)\nend\n---\n--- Returns the next day from given time\n---\n--- @param time integer\n--- @return integer\nutil.next_day = function(time)\n return time + (24 * 60 * 60)\nend\n\n---Determines the last working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_before = function(time)\n local previous_day = util.previous_day(time)\n if util.is_working_day(previous_day) then\n return previous_day\n else\n return util.working_day_before(previous_day)\n end\nend\n\n---Determines the next working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_after = function(time)\n local next_day = util.next_day(time)\n if util.is_working_day(next_day) then\n return next_day\n else\n return util.working_day_after(next_day)\n end\nend\n\n---@param link string\n---@param opts { include_naked_urls: boolean|?, include_file_urls: boolean|?, include_block_ids: boolean|?, link_type: obsidian.search.RefTypes|? }|?\n---\n---@return string|?, string|?, obsidian.search.RefTypes|?\nutil.parse_link = function(link, opts)\n local search = require \"obsidian.search\"\n\n opts = opts and opts or {}\n\n local link_type = opts.link_type\n if link_type == nil then\n for match in\n vim.iter(search.find_refs(link, {\n include_naked_urls = opts.include_naked_urls,\n include_file_urls = opts.include_file_urls,\n include_block_ids = opts.include_block_ids,\n }))\n do\n local _, _, m_type = unpack(match)\n if m_type then\n link_type = m_type\n break\n end\n end\n end\n\n if link_type == nil then\n return nil\n end\n\n local link_location, link_name\n if link_type == search.RefTypes.Markdown then\n link_location = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%2\")\n link_name = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%1\")\n elseif link_type == search.RefTypes.NakedUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.FileUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.WikiWithAlias then\n link = util.unescape_single_backslash(link)\n -- remove boundary brackets, e.g. '[[XXX|YYY]]' -> 'XXX|YYY'\n link = link:sub(3, #link - 2)\n -- split on the \"|\"\n local split_idx = link:find \"|\"\n link_location = link:sub(1, split_idx - 1)\n link_name = link:sub(split_idx + 1)\n elseif link_type == search.RefTypes.Wiki then\n -- remove boundary brackets, e.g. '[[YYY]]' -> 'YYY'\n link = link:sub(3, #link - 2)\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.BlockID then\n link_location = util.standardize_block(link)\n link_name = link\n else\n error(\"not implemented for \" .. link_type)\n end\n\n return link_location, link_name, link_type\nend\n\n------------------------------------\n-- Miscellaneous helper functions --\n------------------------------------\n---@param anchor obsidian.note.HeaderAnchor\n---@return string\nutil.format_anchor_label = function(anchor)\n return string.format(\" ❯ %s\", anchor.header)\nend\n\n-- We are very loose here because obsidian allows pretty much anything\nutil.ANCHOR_LINK_PATTERN = \"#[%w%d\\128-\\255][^#]*\"\n\nutil.BLOCK_PATTERN = \"%^[%w%d][%w%d-]*\"\n\nutil.BLOCK_LINK_PATTERN = \"#\" .. util.BLOCK_PATTERN\n\n--- Strip anchor links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_anchor_links = function(line)\n ---@type string|?\n local anchor\n\n while true do\n local anchor_match = string.match(line, util.ANCHOR_LINK_PATTERN .. \"$\")\n if anchor_match then\n anchor = anchor or \"\"\n anchor = anchor_match .. anchor\n line = string.sub(line, 1, -anchor_match:len() - 1)\n else\n break\n end\n end\n\n return line, anchor and util.standardize_anchor(anchor)\nend\n\n--- Parse a block line from a line.\n---\n---@param line string\n---\n---@return string|?\nutil.parse_block = function(line)\n local block_match = string.match(line, util.BLOCK_PATTERN .. \"$\")\n return block_match\nend\n\n--- Strip block links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_block_links = function(line)\n local block_match = string.match(line, util.BLOCK_LINK_PATTERN .. \"$\")\n if block_match then\n line = string.sub(line, 1, -block_match:len() - 1)\n end\n return line, block_match\nend\n\n--- Standardize a block identifier.\n---@param block_id string\n---@return string\nutil.standardize_block = function(block_id)\n if vim.startswith(block_id, \"#\") then\n block_id = string.sub(block_id, 2)\n end\n\n if not vim.startswith(block_id, \"^\") then\n block_id = \"^\" .. block_id\n end\n\n return block_id\nend\n\n--- Check if a line is a markdown header.\n---@param line string\n---@return boolean\nutil.is_header = function(line)\n if string.match(line, \"^#+%s+[%w]+\") then\n return true\n else\n return false\n end\nend\n\n--- Get the header level of a line.\n---@param line string\n---@return integer\nutil.header_level = function(line)\n local headers, match_count = string.gsub(line, \"^(#+)%s+[%w]+.*\", \"%1\")\n if match_count > 0 then\n return string.len(headers)\n else\n return 0\n end\nend\n\n---@param line string\n---@return { header: string, level: integer, anchor: string }|?\nutil.parse_header = function(line)\n local header_start, header = string.match(line, \"^(#+)%s+([^%s]+.*)$\")\n if header_start and header then\n header = vim.trim(header)\n return {\n header = vim.trim(header),\n level = string.len(header_start),\n anchor = util.header_to_anchor(header),\n }\n else\n return nil\n end\nend\n\n--- Standardize a header anchor link.\n---\n---@param anchor string\n---\n---@return string\nutil.standardize_anchor = function(anchor)\n -- Lowercase everything.\n anchor = string.lower(anchor)\n -- Replace whitespace with \"-\".\n anchor = string.gsub(anchor, \"%s\", \"-\")\n -- Remove every non-alphanumeric character.\n anchor = string.gsub(anchor, \"[^#%w\\128-\\255_-]\", \"\")\n return anchor\nend\n\n--- Transform a markdown header into an link, e.g. \"# Hello World\" -> \"#hello-world\".\n---\n---@param header string\n---\n---@return string\nutil.header_to_anchor = function(header)\n -- Remove leading '#' and strip whitespace.\n local anchor = vim.trim(string.gsub(header, [[^#+%s+]], \"\"))\n return util.standardize_anchor(\"#\" .. anchor)\nend\n\n---@alias datetime_cadence \"daily\"\n\n--- Parse possible relative date macros like '@tomorrow'.\n---\n---@param macro string\n---\n---@return { macro: string, offset: integer, cadence: datetime_cadence }[]\nutil.resolve_date_macro = function(macro)\n ---@type { macro: string, offset: integer, cadence: datetime_cadence }[]\n local out = {}\n for m, offset_days in pairs { today = 0, tomorrow = 1, yesterday = -1 } do\n m = \"@\" .. m\n if vim.startswith(m, macro) then\n out[#out + 1] = { macro = m, offset = offset_days, cadence = \"daily\" }\n end\n end\n return out\nend\n\n--- Check if a string contains invalid characters.\n---\n--- @param fname string\n---\n--- @return boolean\nutil.contains_invalid_characters = function(fname)\n local invalid_chars = \"#^%[%]|\"\n return string.find(fname, \"[\" .. invalid_chars .. \"]\") ~= nil\nend\n\n---Check if a string is NaN\n---\n---@param v any\n---@return boolean\nutil.isNan = function(v)\n return tostring(v) == tostring(0 / 0)\nend\n\n---Higher order function, make sure a function is called with complete lines\n---@param fn fun(string)?\n---@return fun(string)\nutil.buffer_fn = function(fn)\n if not fn then\n return function() end\n end\n local buffer = \"\"\n return function(data)\n buffer = buffer .. data\n local lines = vim.split(buffer, \"\\n\")\n if #lines > 1 then\n for i = 1, #lines - 1 do\n fn(lines[i])\n end\n buffer = lines[#lines] -- Store remaining partial line\n end\n end\nend\n\n---@param event string\n---@param callback fun(...)\n---@param ... any\n---@return boolean success\nutil.fire_callback = function(event, callback, ...)\n local log = require \"obsidian.log\"\n if not callback then\n return false\n end\n local ok, err = pcall(callback, ...)\n if ok then\n return true\n else\n log.error(\"Error running %s callback: %s\", event, err)\n return false\n end\nend\n\n---@param node_type string | string[]\n---@return boolean\nutil.in_node = function(node_type)\n local function in_node(t)\n local node = ts.get_node()\n while node do\n if node:type() == t then\n return true\n end\n node = node:parent()\n end\n return false\n end\n if type(node_type) == \"string\" then\n return in_node(node_type)\n elseif type(node_type) == \"table\" then\n for _, t in ipairs(node_type) do\n local is_in_node = in_node(t)\n if is_in_node then\n return true\n end\n end\n end\n return false\nend\n\nreturn util\n"], ["/obsidian.nvim/lua/obsidian/statusline/init.lua", "local M = {}\nlocal uv = vim.uv\nlocal api = require \"obsidian.api\"\n\n--- Register the global variable that updates itself\nM.start = function(client)\n local current_note\n\n local refresh = function()\n local note = api.current_note()\n if not note then -- no note\n return \"\"\n elseif current_note == note then -- no refresh\n return\n else -- refresh\n current_note = note\n end\n\n client:find_backlinks_async(\n note,\n vim.schedule_wrap(function(backlinks)\n local format = assert(Obsidian.opts.statusline.format)\n local wc = vim.fn.wordcount()\n local info = {\n words = wc.words,\n chars = wc.chars,\n backlinks = #backlinks,\n properties = vim.tbl_count(note:frontmatter()),\n }\n for k, v in pairs(info) do\n format = format:gsub(\"{{\" .. k .. \"}}\", v)\n end\n vim.g.obsidian = format\n end)\n )\n end\n\n local timer = uv:new_timer()\n assert(timer, \"Failed to create timer\")\n timer:start(0, 1000, vim.schedule_wrap(refresh))\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/extract_note.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---Extract the selected text into a new note\n---and replace the selection with a link to the new note.\n---\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"Obsidian extract_note must be called with visual selection\"\n return\n end\n\n local content = vim.split(viz.selection, \"\\n\", { plain = true })\n\n ---@type string|?\n local title\n if data.args ~= nil and string.len(data.args) > 0 then\n title = vim.trim(data.args)\n else\n title = api.input \"Enter title (optional): \"\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n end\n\n -- create the new note.\n local note = Note.create { title = title }\n\n -- replace selection with link to new note\n local link = api.format_link(note)\n vim.api.nvim_buf_set_text(0, viz.csrow - 1, viz.cscol - 1, viz.cerow - 1, viz.cecol, { link })\n\n require(\"obsidian.ui\").update(0)\n\n -- add the selected text to the end of the new note\n note:open { sync = true }\n vim.api.nvim_buf_set_lines(0, -1, -1, false, content)\nend\n"], ["/obsidian.nvim/lua/obsidian/templates.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nlocal M = {}\n\n--- Resolve a template name to a path.\n---\n---@param template_name string|obsidian.Path\n---@param templates_dir obsidian.Path\n---\n---@return obsidian.Path\nM.resolve_template = function(template_name, templates_dir)\n ---@type obsidian.Path|?\n local template_path\n local paths_to_check = { templates_dir / tostring(template_name), Path:new(template_name) }\n for _, path in ipairs(paths_to_check) do\n if path:is_file() then\n template_path = path\n break\n elseif not vim.endswith(tostring(path), \".md\") then\n local path_with_suffix = Path:new(tostring(path) .. \".md\")\n if path_with_suffix:is_file() then\n template_path = path_with_suffix\n break\n end\n end\n end\n\n if template_path == nil then\n error(string.format(\"Template '%s' not found\", template_name))\n end\n\n return template_path\nend\n\n--- Substitute variables inside the given text.\n---\n---@param text string\n---@param ctx obsidian.TemplateContext\n---\n---@return string\nM.substitute_template_variables = function(text, ctx)\n local methods = vim.deepcopy(ctx.template_opts.substitutions or {})\n\n if not methods[\"date\"] then\n methods[\"date\"] = function()\n local date_format = ctx.template_opts.date_format or \"%Y-%m-%d\"\n return tostring(os.date(date_format))\n end\n end\n\n if not methods[\"time\"] then\n methods[\"time\"] = function()\n local time_format = ctx.template_opts.time_format or \"%H:%M\"\n return tostring(os.date(time_format))\n end\n end\n\n if not methods[\"title\"] and ctx.partial_note then\n methods[\"title\"] = ctx.partial_note.title or ctx.partial_note:display_name()\n end\n\n if not methods[\"id\"] and ctx.partial_note then\n methods[\"id\"] = tostring(ctx.partial_note.id)\n end\n\n if not methods[\"path\"] and ctx.partial_note and ctx.partial_note.path then\n methods[\"path\"] = tostring(ctx.partial_note.path)\n end\n\n -- Replace known variables.\n for key, subst in pairs(methods) do\n while true do\n local m_start, m_end = string.find(text, \"{{\" .. key .. \"}}\", nil, true)\n if not m_start or not m_end then\n break\n end\n ---@type string\n local value\n if type(subst) == \"string\" then\n value = subst\n else\n value = subst(ctx)\n -- cache the result\n methods[key] = value\n end\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n -- Find unknown variables and prompt for them.\n for m_start, m_end in util.gfind(text, \"{{[^}]+}}\") do\n local key = vim.trim(string.sub(text, m_start + 2, m_end - 2))\n local value = api.input(string.format(\"Enter value for '%s' ( to skip): \", key))\n if value and string.len(value) > 0 then\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n return text\nend\n\n--- Clone template to a new note.\n---\n---@param ctx obsidian.CloneTemplateContext\n---\n---@return obsidian.Note\nM.clone_template = function(ctx)\n local note_path = Path.new(ctx.destination_path)\n assert(note_path:parent()):mkdir { parents = true, exist_ok = true }\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local template_file, read_err = io.open(tostring(template_path), \"r\")\n if not template_file then\n error(string.format(\"Unable to read template at '%s': %s\", template_path, tostring(read_err)))\n end\n\n local note_file, write_err = io.open(tostring(note_path), \"w\")\n if not note_file then\n error(string.format(\"Unable to write note at '%s': %s\", note_path, tostring(write_err)))\n end\n\n for line in template_file:lines \"L\" do\n line = M.substitute_template_variables(line, ctx)\n note_file:write(line)\n end\n\n assert(template_file:close())\n assert(note_file:close())\n\n local new_note = Note.from_file(note_path)\n\n if ctx.partial_note then\n -- Transfer fields from `ctx.partial_note`.\n new_note.id = ctx.partial_note.id\n if new_note.title == nil then\n new_note.title = ctx.partial_note.title\n end\n for _, alias in ipairs(ctx.partial_note.aliases) do\n new_note:add_alias(alias)\n end\n for _, tag in ipairs(ctx.partial_note.tags) do\n new_note:add_tag(tag)\n end\n end\n\n return new_note\nend\n\n---Insert a template at the given location.\n---\n---@param ctx obsidian.InsertTemplateContext\n---\n---@return obsidian.Note\nM.insert_template = function(ctx)\n local buf, win, row, _ = unpack(ctx.location)\n if ctx.partial_note == nil then\n ctx.partial_note = Note.from_buffer(buf)\n end\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local insert_lines = {}\n local template_file = io.open(tostring(template_path), \"r\")\n if template_file then\n local lines = template_file:lines()\n for line in lines do\n local new_lines = M.substitute_template_variables(line, ctx)\n if string.find(new_lines, \"[\\r\\n]\") then\n local line_start = 1\n for line_end in util.gfind(new_lines, \"[\\r\\n]\") do\n local new_line = string.sub(new_lines, line_start, line_end - 1)\n table.insert(insert_lines, new_line)\n line_start = line_end + 1\n end\n local last_line = string.sub(new_lines, line_start)\n if string.len(last_line) > 0 then\n table.insert(insert_lines, last_line)\n end\n else\n table.insert(insert_lines, new_lines)\n end\n end\n template_file:close()\n else\n error(string.format(\"Template file '%s' not found\", template_path))\n end\n\n vim.api.nvim_buf_set_lines(buf, row - 1, row - 1, false, insert_lines)\n local new_cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(win))\n vim.api.nvim_win_set_cursor(0, { new_cursor_row, 0 })\n\n require(\"obsidian.ui\").update(0)\n\n return Note.from_buffer(buf)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/img_paste.lua", "local Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal run_job = require(\"obsidian.async\").run_job\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\n\nlocal M = {}\n\n-- Image pasting adapted from https://github.com/ekickx/clipboard-image.nvim\n\n---@return string\nlocal function get_clip_check_command()\n local check_cmd\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n check_cmd = \"xclip -selection clipboard -o -t TARGETS\"\n elseif display_server == \"wayland\" then\n check_cmd = \"wl-paste --list-types\"\n end\n elseif this_os == api.OSType.Darwin then\n check_cmd = \"pngpaste -b 2>&1\"\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n check_cmd = 'powershell.exe \"Get-Clipboard -Format Image\"'\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return check_cmd\nend\n\n--- Check if clipboard contains image data.\n---\n---@return boolean\nfunction M.clipboard_is_img()\n local check_cmd = get_clip_check_command()\n local result_string = vim.fn.system(check_cmd)\n local content = vim.split(result_string, \"\\n\")\n\n local is_img = false\n -- See: [Data URI scheme](https://en.wikipedia.org/wiki/Data_URI_scheme)\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n if vim.tbl_contains(content, \"image/png\") then\n is_img = true\n elseif vim.tbl_contains(content, \"text/uri-list\") then\n local success =\n os.execute \"wl-paste --type text/uri-list | sed 's|file://||' | head -n1 | tr -d '[:space:]' | xargs -I{} sh -c 'wl-copy < \\\"$1\\\"' _ {}\"\n is_img = success == 0\n end\n elseif this_os == api.OSType.Darwin then\n is_img = string.sub(content[1], 1, 9) == \"iVBORw0KG\" -- Magic png number in base64\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n is_img = content ~= nil\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return is_img\nend\n\n--- TODO: refactor with run_job?\n\n--- Save image from clipboard to `path`.\n---@param path string\n---\n---@return boolean|integer|? result\nlocal function save_clipboard_image(path)\n local this_os = api.get_os()\n\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local cmd\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n cmd = string.format(\"xclip -selection clipboard -t image/png -o > '%s'\", path)\n elseif display_server == \"wayland\" then\n cmd = string.format(\"wl-paste --no-newline --type image/png > %s\", vim.fn.shellescape(path))\n return run_job { \"bash\", \"-c\", cmd }\n end\n\n local result = os.execute(cmd)\n if type(result) == \"number\" and result > 0 then\n return false\n else\n return result\n end\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n local cmd = 'powershell.exe -c \"'\n .. string.format(\"(get-clipboard -format image).save('%s', 'png')\", string.gsub(path, \"/\", \"\\\\\"))\n .. '\"'\n return os.execute(cmd)\n elseif this_os == api.OSType.Darwin then\n return run_job { \"pngpaste\", path }\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\nend\n\n--- @param path string image_path The absolute path to the image file.\nM.paste = function(path)\n if util.contains_invalid_characters(path) then\n log.warn \"Links will not work with file names containing any of these characters in Obsidian: # ^ [ ] |\"\n end\n\n ---@diagnostic disable-next-line: cast-local-type\n path = Path.new(path)\n\n -- Make sure fname ends with \".png\"\n if not path.suffix then\n ---@diagnostic disable-next-line: cast-local-type\n path = path:with_suffix \".png\"\n elseif path.suffix ~= \".png\" then\n return log.err(\"invalid suffix for image name '%s', must be '.png'\", path.suffix)\n end\n\n if Obsidian.opts.attachments.confirm_img_paste then\n -- Get confirmation from user.\n if not api.confirm(\"Saving image to '\" .. tostring(path) .. \"'. Do you want to continue?\") then\n return log.warn \"Paste aborted\"\n end\n end\n\n -- Ensure parent directory exists.\n assert(path:parent()):mkdir { exist_ok = true, parents = true }\n\n -- Paste image.\n local result = save_clipboard_image(tostring(path))\n if result == false then\n log.err \"Failed to save image\"\n return\n end\n\n local img_text = Obsidian.opts.attachments.img_text_func(path)\n vim.api.nvim_put({ img_text }, \"c\", true, false)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/link_new.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n local title\n if string.len(data.args) > 0 then\n title = data.args\n else\n title = viz.selection\n end\n\n local note = Note.create { title = title }\n\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = title })\n .. string.sub(line, viz.cecol + 1)\n\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\nend\n"], ["/obsidian.nvim/lua/obsidian/pickers/_mini.lua", "local mini_pick = require \"mini.pick\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\n---@param entry string\n---@return string\nlocal function clean_path(entry)\n local path_end = assert(string.find(entry, \":\", 1, true))\n return string.sub(entry, 1, path_end - 1)\nend\n\n---@class obsidian.pickers.MiniPicker : obsidian.Picker\nlocal MiniPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"MiniPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nMiniPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local path = mini_pick.builtin.cli({\n command = self:_build_find_cmd(),\n }, {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n })\n\n if path and opts.callback then\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nMiniPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local pick_opts = {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n }\n\n ---@type string|?\n local result\n if opts.query and string.len(opts.query) > 0 then\n result = mini_pick.builtin.grep({ pattern = opts.query }, pick_opts)\n else\n result = mini_pick.builtin.grep_live({}, pick_opts)\n end\n\n if result and opts.callback then\n local path = clean_path(result)\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nMiniPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n entries[#entries + 1] = {\n value = value.value,\n text = self:_make_display(value),\n path = value.filename,\n lnum = value.lnum,\n col = value.col,\n }\n end\n end\n\n local entry = mini_pick.start {\n source = {\n name = opts.prompt_title,\n items = entries,\n choose = function() end,\n },\n }\n\n if entry and opts.callback then\n if type(entry) == \"string\" then\n opts.callback(entry)\n else\n opts.callback(entry.value)\n end\n end\nend\n\nreturn MiniPicker\n"], ["/obsidian.nvim/lua/obsidian/ui.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal M = {}\n\nlocal NAMESPACE = \"ObsidianUI\"\n\n---@param ui_opts obsidian.config.UIOpts\nlocal function install_hl_groups(ui_opts)\n for group_name, opts in pairs(ui_opts.hl_groups) do\n vim.api.nvim_set_hl(0, group_name, opts)\n end\nend\n\n-- We cache marks locally to help avoid redrawing marks when its not necessary. The main reason\n-- we need to do this is because the conceal char we get back from `nvim_buf_get_extmarks()` gets mangled.\n-- For example, \"󰄱\" is turned into \"1\\1\\15\".\n-- TODO: if we knew how to un-mangle the conceal char we wouldn't need the cache.\n\nM._buf_mark_cache = vim.defaulttable()\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\n---@return ExtMark|?\nlocal function cache_get(bufnr, ns_id, mark_id)\n local buf_ns_cache = M._buf_mark_cache[bufnr][ns_id]\n return buf_ns_cache[mark_id]\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark ExtMark\n---@return ExtMark|?\nlocal function cache_set(bufnr, ns_id, mark)\n assert(mark.id ~= nil)\n M._buf_mark_cache[bufnr][ns_id][mark.id] = mark\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\nlocal function cache_evict(bufnr, ns_id, mark_id)\n M._buf_mark_cache[bufnr][ns_id][mark_id] = nil\nend\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function cache_clear(bufnr, ns_id)\n M._buf_mark_cache[bufnr][ns_id] = {}\nend\n\n---@class ExtMark : obsidian.ABC\n---@field id integer|? ID of the mark, only set for marks that are actually materialized in the buffer.\n---@field row integer 0-based row index to place the mark.\n---@field col integer 0-based col index to place the mark.\n---@field opts ExtMarkOpts Optional parameters passed directly to `nvim_buf_set_extmark()`.\nlocal ExtMark = abc.new_class {\n __eq = function(a, b)\n return a.row == b.row and a.col == b.col and a.opts == b.opts\n end,\n}\n\nM.ExtMark = ExtMark\n\n---@class ExtMarkOpts : obsidian.ABC\n---@field end_row integer\n---@field end_col integer\n---@field conceal string|?\n---@field hl_group string|?\n---@field spell boolean|?\nlocal ExtMarkOpts = abc.new_class()\n\nM.ExtMarkOpts = ExtMarkOpts\n\n---@param data table\n---@return ExtMarkOpts\nExtMarkOpts.from_tbl = function(data)\n local self = ExtMarkOpts.init()\n self.end_row = data.end_row\n self.end_col = data.end_col\n self.conceal = data.conceal\n self.hl_group = data.hl_group\n self.spell = data.spell\n return self\nend\n\n---@param self ExtMarkOpts\n---@return table\nExtMarkOpts.to_tbl = function(self)\n return {\n end_row = self.end_row,\n end_col = self.end_col,\n conceal = self.conceal,\n hl_group = self.hl_group,\n spell = self.spell,\n }\nend\n\n---@param id integer|?\n---@param row integer\n---@param col integer\n---@param opts ExtMarkOpts\n---@return ExtMark\nExtMark.new = function(id, row, col, opts)\n local self = ExtMark.init()\n self.id = id\n self.row = row\n self.col = col\n self.opts = opts\n return self\nend\n\n---Materialize the ExtMark if needed. After calling this the 'id' will be set if it wasn't already.\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return ExtMark\nExtMark.materialize = function(self, bufnr, ns_id)\n if self.id == nil then\n self.id = vim.api.nvim_buf_set_extmark(bufnr, ns_id, self.row, self.col, self.opts:to_tbl())\n end\n cache_set(bufnr, ns_id, self)\n return self\nend\n\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return boolean\nExtMark.clear = function(self, bufnr, ns_id)\n if self.id ~= nil then\n cache_evict(bufnr, ns_id, self.id)\n return vim.api.nvim_buf_del_extmark(bufnr, ns_id, self.id)\n else\n return false\n end\nend\n\n---Collect all existing (materialized) marks within a region.\n---@param bufnr integer\n---@param ns_id integer\n---@param region_start integer|integer[]|?\n---@param region_end integer|integer[]|?\n---@return ExtMark[]\nExtMark.collect = function(bufnr, ns_id, region_start, region_end)\n region_start = region_start and region_start or 0\n region_end = region_end and region_end or -1\n local marks = {}\n for data in iter(vim.api.nvim_buf_get_extmarks(bufnr, ns_id, region_start, region_end, { details = true })) do\n local mark = ExtMark.new(data[1], data[2], data[3], ExtMarkOpts.from_tbl(data[4]))\n -- NOTE: since the conceal char we get back from `nvim_buf_get_extmarks()` is mangled, e.g.\n -- \"󰄱\" is turned into \"1\\1\\15\", we used the cached version.\n local cached_mark = cache_get(bufnr, ns_id, mark.id)\n if cached_mark ~= nil then\n mark.opts.conceal = cached_mark.opts.conceal\n end\n cache_set(bufnr, ns_id, mark)\n marks[#marks + 1] = mark\n end\n return marks\nend\n\n---Clear all existing (materialized) marks with a line region.\n---@param bufnr integer\n---@param ns_id integer\n---@param line_start integer\n---@param line_end integer\nExtMark.clear_range = function(bufnr, ns_id, line_start, line_end)\n return vim.api.nvim_buf_clear_namespace(bufnr, ns_id, line_start, line_end)\nend\n\n---Clear all existing (materialized) marks on a line.\n---@param bufnr integer\n---@param ns_id integer\n---@param line integer\nExtMark.clear_line = function(bufnr, ns_id, line)\n return ExtMark.clear_range(bufnr, ns_id, line, line + 1)\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_check_extmarks(marks, line, lnum, ui_opts)\n for char, opts in pairs(ui_opts.checkboxes) do\n if string.match(line, \"^%s*- %[\" .. vim.pesc(char) .. \"%]\") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 5,\n conceal = opts.char,\n hl_group = opts.hl_group,\n }\n )\n return marks\n end\n end\n\n if ui_opts.bullets ~= nil and string.match(line, \"^%s*[-%*%+] \") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 1,\n conceal = ui_opts.bullets.char,\n hl_group = ui_opts.bullets.hl_group,\n }\n )\n end\n\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_ref_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_refs(line, { include_naked_urls = true, include_tags = true, include_block_ids = true })\n for match in iter(matches) do\n local m_start, m_end, m_type = unpack(match)\n if m_type == search.RefTypes.WikiWithAlias then\n -- Reference of the form [[xxx|yyy]]\n local pipe_loc = string.find(line, \"|\", m_start, true)\n assert(pipe_loc)\n -- Conceal everything from '[[' up to '|'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = pipe_loc,\n conceal = \"\",\n }\n )\n -- Highlight the alias 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n pipe_loc,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Wiki then\n -- Reference of the form [[xxx]]\n -- Conceal the opening '[['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'xxx'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Markdown then\n -- Reference of the form [yyy](xxx)\n local closing_bracket_loc = string.find(line, \"]\", m_start, true)\n assert(closing_bracket_loc)\n local is_url = util.is_url(string.sub(line, closing_bracket_loc + 2, m_end - 1))\n -- Conceal the opening '['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc - 1,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the ']('\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc + 1,\n conceal = is_url and \" \" or \"\",\n }\n )\n -- Conceal the URL part 'xxx' with the external URL character\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 1,\n conceal = is_url and ui_opts.external_link_icon.char or \"\",\n hl_group = ui_opts.external_link_icon.hl_group,\n }\n )\n -- Conceal the closing ')'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = is_url and \" \" or \"\",\n }\n )\n elseif m_type == search.RefTypes.NakedUrl then\n -- A \"naked\" URL is just a URL by itself, like 'https://github.com/'\n local domain_start_loc = string.find(line, \"://\", m_start, true)\n assert(domain_start_loc)\n domain_start_loc = domain_start_loc + 3\n -- Conceal the \"https?://\" part\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = domain_start_loc - 1,\n conceal = \"\",\n }\n )\n -- Highlight the whole thing.\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.Tag then\n -- A tag is like '#tag'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.tags.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.BlockID then\n -- A block ID, like '^hello-world'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.block_ids.hl_group,\n spell = false,\n }\n )\n end\n end\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_highlight(line)\n for match in iter(matches) do\n local m_start, m_end, _ = unpack(match)\n -- Conceal opening '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight text in the middle\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.highlight_text.hl_group,\n spell = false,\n }\n )\n -- Conceal closing '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n end\n return marks\nend\n\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal get_line_marks = function(line, lnum, ui_opts)\n local marks = {}\n get_line_check_extmarks(marks, line, lnum, ui_opts)\n get_line_ref_extmarks(marks, line, lnum, ui_opts)\n get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n return marks\nend\n\n---@param bufnr integer\n---@param ui_opts obsidian.config.UIOpts\nlocal function update_extmarks(bufnr, ns_id, ui_opts)\n local start_time = vim.uv.hrtime()\n local n_marks_added = 0\n local n_marks_cleared = 0\n\n -- Collect all current marks, grouped by line.\n local cur_marks_by_line = vim.defaulttable()\n for mark in iter(ExtMark.collect(bufnr, ns_id)) do\n local cur_line_marks = cur_marks_by_line[mark.row]\n cur_line_marks[#cur_line_marks + 1] = mark\n end\n\n -- Iterate over lines (skipping code blocks) and update marks.\n local inside_code_block = false\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, true)\n for i, line in ipairs(lines) do\n local lnum = i - 1\n local cur_line_marks = cur_marks_by_line[lnum]\n\n local function clear_line()\n ExtMark.clear_line(bufnr, ns_id, lnum)\n n_marks_cleared = n_marks_cleared + #cur_line_marks\n for mark in iter(cur_line_marks) do\n cache_evict(bufnr, ns_id, mark.id)\n end\n end\n\n -- Check if inside a code block or at code block boundary. If not, update marks.\n if string.match(line, \"^%s*```[^`]*$\") then\n inside_code_block = not inside_code_block\n -- Remove any existing marks here on the boundary of a code block.\n clear_line()\n elseif not inside_code_block then\n -- Get all marks that should be materialized.\n -- Some of these might already be materialized, which we'll check below and avoid re-drawing\n -- if that's the case.\n local new_line_marks = get_line_marks(line, lnum, ui_opts)\n if #new_line_marks > 0 then\n -- Materialize new marks.\n for mark in iter(new_line_marks) do\n if not vim.list_contains(cur_line_marks, mark) then\n mark:materialize(bufnr, ns_id)\n n_marks_added = n_marks_added + 1\n end\n end\n\n -- Clear old marks.\n for mark in iter(cur_line_marks) do\n if not vim.list_contains(new_line_marks, mark) then\n mark:clear(bufnr, ns_id)\n n_marks_cleared = n_marks_cleared + 1\n end\n end\n else\n -- Remove any existing marks here since there are no new marks.\n clear_line()\n end\n else\n -- Remove any existing marks here since we're inside a code block.\n clear_line()\n end\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n log.debug(\"Added %d new marks, cleared %d old marks in %dms\", n_marks_added, n_marks_cleared, runtime)\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param bufnr integer|?\n---@return boolean\nlocal function should_update(ui_opts, bufnr)\n if ui_opts.enable == false then\n return false\n end\n\n bufnr = bufnr or 0\n\n if not vim.endswith(vim.api.nvim_buf_get_name(bufnr), \".md\") then\n return false\n end\n\n if ui_opts.max_file_length ~= nil and vim.fn.line \"$\" > ui_opts.max_file_length then\n return false\n end\n\n return true\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param throttle boolean\n---@return function\nlocal function get_extmarks_autocmd_callback(ui_opts, throttle)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n\n local callback = function(ev)\n if not should_update(ui_opts, ev.bufnr) then\n return\n end\n update_extmarks(ev.buf, ns_id, ui_opts)\n end\n\n if throttle then\n return require(\"obsidian.async\").throttle(callback, ui_opts.update_debounce)\n else\n return callback\n end\nend\n\n---Manually update extmarks.\n---\n---@param bufnr integer|?\nM.update = function(bufnr)\n bufnr = bufnr or 0\n local ui_opts = Obsidian.opts.ui\n if not should_update(ui_opts, bufnr) then\n return\n end\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n update_extmarks(bufnr, ns_id, ui_opts)\nend\n\n---@param workspace obsidian.Workspace\n---@param ui_opts obsidian.config.UIOpts\nM.setup = function(workspace, ui_opts)\n if ui_opts.enable == false then\n return\n end\n\n local group = vim.api.nvim_create_augroup(\"ObsidianUI\" .. workspace.name, { clear = true })\n\n install_hl_groups(ui_opts)\n\n local pattern = tostring(workspace.root) .. \"/**.md\"\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = function()\n local conceallevel = vim.opt_local.conceallevel:get()\n\n if (conceallevel < 1 or conceallevel > 2) and not ui_opts.ignore_conceal_warn then\n log.warn_once(\n \"Obsidian additional syntax features require 'conceallevel' to be set to 1 or 2, \"\n .. \"but you have 'conceallevel' set to '%s'.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/issues/286 for more details.\\n\"\n .. \"If you don't want Obsidian's additional UI features, you can disable them and suppress \"\n .. \"this warning by setting 'ui.enable = false' in your Obsidian nvim config.\",\n conceallevel\n )\n end\n\n -- delete the autocommand\n return true\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, false),\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\", \"TextChanged\", \"TextChangedI\", \"TextChangedP\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, true),\n })\n\n vim.api.nvim_create_autocmd({ \"BufUnload\" }, {\n group = group,\n pattern = pattern,\n callback = function(ev)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n cache_clear(ev.buf, ns_id)\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/workspace.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\nlocal config = require \"obsidian.config\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.workspace.WorkspaceSpec\n---\n---@field path string|(fun(): string)\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts?\n\n---@class obsidian.workspace.WorkspaceOpts\n---\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts|?\n\n--- Each workspace represents a working directory (usually an Obsidian vault) along with\n--- a set of configuration options specific to the workspace.\n---\n--- Workspaces are a little more general than Obsidian vaults as you can have a workspace\n--- outside of a vault or as a subdirectory of a vault.\n---\n---@toc_entry obsidian.Workspace\n---\n---@class obsidian.Workspace : obsidian.ABC\n---\n---@field name string An arbitrary name for the workspace.\n---@field path obsidian.Path The normalized path to the workspace.\n---@field root obsidian.Path The normalized path to the vault root of the workspace. This usually matches 'path'.\n---@field overrides table|obsidian.config.ClientOpts|?\n---@field locked boolean|?\nlocal Workspace = abc.new_class {\n __tostring = function(self)\n return string.format(\"Workspace(name='%s', path='%s', root='%s')\", self.name, self.path, self.root)\n end,\n __eq = function(a, b)\n local a_fields = a:as_tbl()\n a_fields.locked = nil\n local b_fields = b:as_tbl()\n b_fields.locked = nil\n return vim.deep_equal(a_fields, b_fields)\n end,\n}\n\n--- Find the vault root from a given directory.\n---\n--- This will traverse the directory tree upwards until a '.obsidian/' folder is found to\n--- indicate the root of a vault, otherwise the given directory is used as-is.\n---\n---@param base_dir string|obsidian.Path\n---\n---@return obsidian.Path|?\nlocal function find_vault_root(base_dir)\n local vault_indicator_folder = \".obsidian\"\n base_dir = Path.new(base_dir)\n local dirs = Path.new(base_dir):parents()\n table.insert(dirs, 1, base_dir)\n\n for _, dir in ipairs(dirs) do\n local maybe_vault = dir / vault_indicator_folder\n if maybe_vault:is_dir() then\n return dir\n end\n end\n\n return nil\nend\n\n--- Create a new 'Workspace' object. This assumes the workspace already exists on the filesystem.\n---\n---@param path string|obsidian.Path Workspace path.\n---@param opts obsidian.workspace.WorkspaceOpts|?\n---\n---@return obsidian.Workspace\nWorkspace.new = function(path, opts)\n opts = opts and opts or {}\n\n local self = Workspace.init()\n self.path = Path.new(path):resolve { strict = true }\n self.name = assert(opts.name or self.path.name)\n self.overrides = opts.overrides\n\n if opts.strict then\n self.root = self.path\n else\n local vault_root = find_vault_root(self.path)\n if vault_root then\n self.root = vault_root\n else\n self.root = self.path\n end\n end\n\n return self\nend\n\n--- Initialize a new 'Workspace' object from a workspace spec.\n---\n---@param spec obsidian.workspace.WorkspaceSpec\n---\n---@return obsidian.Workspace\nWorkspace.new_from_spec = function(spec)\n ---@type string|obsidian.Path\n local path\n if type(spec.path) == \"function\" then\n path = spec.path()\n else\n ---@diagnostic disable-next-line: cast-local-type\n path = spec.path\n end\n\n ---@diagnostic disable-next-line: param-type-mismatch\n return Workspace.new(path, {\n name = spec.name,\n strict = spec.strict,\n overrides = spec.overrides,\n })\nend\n\n--- Lock the workspace.\nWorkspace.lock = function(self)\n self.locked = true\nend\n\n--- Unlock the workspace.\nWorkspace._unlock = function(self)\n self.locked = false\nend\n\n--- Get the workspace corresponding to the directory (or a parent of), if there\n--- is one.\n---\n---@param cur_dir string|obsidian.Path\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_dir = function(cur_dir, workspaces)\n local ok\n ok, cur_dir = pcall(function()\n return Path.new(cur_dir):resolve { strict = true }\n end)\n\n if not ok then\n return\n end\n\n for _, spec in ipairs(workspaces) do\n local w = Workspace.new_from_spec(spec)\n if w.path == cur_dir or w.path:is_parent_of(cur_dir) then\n return w\n end\n end\nend\n\n--- Get the workspace corresponding to the current working directory (or a parent of), if there\n--- is one.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_cwd = function(workspaces)\n local cwd = assert(vim.fn.getcwd())\n return Workspace.get_workspace_for_dir(cwd, workspaces)\nend\n\n--- Returns the default workspace.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|nil\nWorkspace.get_default_workspace = function(workspaces)\n if not vim.tbl_isempty(workspaces) then\n return Workspace.new_from_spec(workspaces[1])\n else\n return nil\n end\nend\n\n--- Resolves current workspace from the client config.\n---\n---@param opts obsidian.config.ClientOpts\n---\n---@return obsidian.Workspace|?\nWorkspace.get_from_opts = function(opts)\n local current_workspace = Workspace.get_workspace_for_cwd(opts.workspaces)\n\n if not current_workspace then\n current_workspace = Workspace.get_default_workspace(opts.workspaces)\n end\n\n return current_workspace\nend\n\n--- Get the normalize opts for a given workspace.\n---\n---@param workspace obsidian.Workspace|?\n---\n---@return obsidian.config.ClientOpts\nWorkspace.normalize_opts = function(workspace)\n if workspace then\n return config.normalize(workspace.overrides and workspace.overrides or {}, Obsidian._opts)\n else\n return Obsidian.opts\n end\nend\n\n---@param workspace obsidian.Workspace\n---@param opts { lock: boolean|? }|?\nWorkspace.set = function(workspace, opts)\n opts = opts and opts or {}\n\n local dir = workspace.root\n local options = Workspace.normalize_opts(workspace) -- TODO: test\n\n Obsidian.workspace = workspace\n Obsidian.dir = dir\n Obsidian.opts = options\n\n -- Ensure directories exist.\n dir:mkdir { parents = true, exists_ok = true }\n\n if options.notes_subdir ~= nil then\n local notes_subdir = dir / Obsidian.opts.notes_subdir\n notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n local daily_notes_subdir = Obsidian.dir / Obsidian.opts.daily_notes.folder\n daily_notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n -- Setup UI add-ons.\n local has_no_renderer = not (api.get_plugin_info \"render-markdown.nvim\" or api.get_plugin_info \"markview.nvim\")\n if has_no_renderer and Obsidian.opts.ui.enable then\n require(\"obsidian.ui\").setup(Obsidian.workspace, Obsidian.opts.ui)\n end\n\n if opts.lock then\n Obsidian.workspace:lock()\n end\n\n Obsidian.picker = require(\"obsidian.pickers\").get(Obsidian.opts.picker.name)\n\n util.fire_callback(\"post_set_workspace\", Obsidian.opts.callbacks.post_set_workspace, workspace)\n\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = \"ObsidianWorkpspaceSet\",\n data = { workspace = workspace },\n })\nend\n\n---@param workspace obsidian.Workspace|string The workspace object or the name of an existing workspace.\n---@param opts { lock: boolean|? }|?\nWorkspace.switch = function(workspace, opts)\n opts = opts and opts or {}\n\n if workspace == Obsidian.workspace.name then\n log.info(\"Already in workspace '%s' @ '%s'\", workspace, Obsidian.workspace.path)\n return\n end\n\n for _, ws in ipairs(Obsidian.opts.workspaces) do\n if ws.name == workspace then\n return Workspace.set(Workspace.new_from_spec(ws), opts)\n end\n end\n\n error(string.format(\"Workspace '%s' not found\", workspace))\nend\n\nreturn Workspace\n"], ["/obsidian.nvim/lua/obsidian/commands/search.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n picker:grep_notes { query = data.args }\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/tags.lua", "local Note = require \"obsidian.note\"\nlocal Patterns = require(\"obsidian.search\").Patterns\n\nlocal M = {}\n\n---@type { pattern: string, offset: integer }[]\nlocal TAG_PATTERNS = {\n { pattern = \"[%s%(]#\" .. Patterns.TagCharsOptional .. \"$\", offset = 2 },\n { pattern = \"^#\" .. Patterns.TagCharsOptional .. \"$\", offset = 1 },\n}\n\nM.find_tags_start = function(input)\n for _, pattern in ipairs(TAG_PATTERNS) do\n local match = string.match(input, pattern.pattern)\n if match then\n return string.sub(match, pattern.offset + 1)\n end\n end\nend\n\n--- Find the boundaries of the YAML frontmatter within the buffer.\n---@param bufnr integer\n---@return integer|?, integer|?\nlocal get_frontmatter_boundaries = function(bufnr)\n local note = Note.from_buffer(bufnr)\n if note.frontmatter_end_line ~= nil then\n return 1, note.frontmatter_end_line\n end\nend\n\n---@return boolean, string|?, boolean|?\nM.can_complete = function(request)\n local search = M.find_tags_start(request.context.cursor_before_line)\n if not search or string.len(search) == 0 then\n return false\n end\n\n -- Check if we're inside frontmatter.\n local in_frontmatter = false\n local line = request.context.cursor.line\n local frontmatter_start, frontmatter_end = get_frontmatter_boundaries(request.context.bufnr)\n if\n frontmatter_start ~= nil\n and frontmatter_start <= (line + 1)\n and frontmatter_end ~= nil\n and line <= frontmatter_end\n then\n in_frontmatter = true\n end\n\n return true, search, in_frontmatter\nend\n\nM.get_trigger_characters = function()\n return { \"#\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n -- return [=[\\%(^\\|[^#]\\)\\zs#[a-zA-Z0-9_/-]\\+]=]\n return \"#[a-zA-Z0-9_/-]\\\\+\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/init.lua", "local PickerName = require(\"obsidian.config\").Picker\n\nlocal M = {}\n\n--- Get the default Picker.\n---\n---@param picker_name obsidian.config.Picker|?\n---\n---@return obsidian.Picker|?\nM.get = function(picker_name)\n picker_name = picker_name and picker_name or Obsidian.opts.picker.name\n if picker_name then\n picker_name = string.lower(picker_name)\n else\n for _, name in ipairs { PickerName.telescope, PickerName.fzf_lua, PickerName.mini, PickerName.snacks } do\n local ok, res = pcall(M.get, name)\n if ok then\n return res\n end\n end\n return nil\n end\n\n if picker_name == string.lower(PickerName.telescope) then\n return require(\"obsidian.pickers._telescope\").new()\n elseif picker_name == string.lower(PickerName.mini) then\n return require(\"obsidian.pickers._mini\").new()\n elseif picker_name == string.lower(PickerName.fzf_lua) then\n return require(\"obsidian.pickers._fzf\").new()\n elseif picker_name == string.lower(PickerName.snacks) then\n return require(\"obsidian.pickers._snacks\").new()\n elseif picker_name then\n error(\"not implemented for \" .. picker_name)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/tags.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal iter = vim.iter\nlocal obsidian = require \"obsidian\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.TagsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field in_frontmatter boolean|?\nlocal TagsSourceCompletionContext = abc.new_class()\n\nTagsSourceCompletionContext.new = function()\n return TagsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.TagsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal TagsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.TagsSourceBase\nTagsSourceBase.new = function()\n return TagsSourceBase.init()\nend\n\nTagsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = TagsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n local search_opts = cc.client.search_defaults()\n search_opts.sort = false\n\n cc.client:find_tags_async(cc.search, function(tag_locs)\n local tags = {}\n for tag_loc in iter(tag_locs) do\n tags[tag_loc.tag] = true\n end\n\n local items = {}\n for tag, _ in pairs(tags) do\n -- Generate context-appropriate text\n local insert_text, label_text\n if cc.in_frontmatter then\n -- Frontmatter: insert tag without # (YAML format)\n insert_text = tag\n label_text = \"Tag: \" .. tag\n else\n -- Document body: insert tag with # (Obsidian format)\n insert_text = \"#\" .. tag\n label_text = \"Tag: #\" .. tag\n end\n\n -- Calculate the range to replace (the entire #tag pattern)\n local cursor_before = cc.request.context.cursor_before_line\n local hash_start = string.find(cursor_before, \"#[^%s]*$\")\n local insert_start = hash_start and (hash_start - 1) or #cursor_before\n local insert_end = #cursor_before\n\n items[#items + 1] = {\n sortText = \"#\" .. tag,\n label = label_text,\n kind = vim.lsp.protocol.CompletionItemKind.Text,\n textEdit = {\n newText = insert_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_end,\n },\n },\n },\n data = {\n bufnr = cc.request.context.bufnr,\n in_frontmatter = cc.in_frontmatter,\n line = cc.request.context.cursor.line,\n tag = tag,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\n end, { search = search_opts })\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction TagsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.in_frontmatter = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\nreturn TagsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/commands/paste_img.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal img = require \"obsidian.img_paste\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not img.clipboard_is_img() then\n return log.err \"There is no image data in the clipboard\"\n end\n\n ---@type string|?\n local default_name = Obsidian.opts.attachments.img_name_func()\n\n local should_confirm = Obsidian.opts.attachments.confirm_img_paste\n\n ---@type string\n local fname = vim.trim(data.args)\n\n -- Get filename to save to.\n if fname == nil or fname == \"\" then\n if default_name and not should_confirm then\n fname = default_name\n else\n local input = api.input(\"Enter file name: \", { default = default_name, completion = \"file\" })\n if not input then\n return log.warn \"Paste aborted\"\n end\n fname = input\n end\n end\n\n local path = api.resolve_image_path(fname)\n\n img.paste(path)\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/blink.lua", "local util = require \"obsidian.util\"\nlocal obsidian = require \"obsidian\"\n\nlocal M = {}\n\nM.injected_once = false\n\nM.providers = {\n { name = \"obsidian\", module = \"obsidian.completion.sources.blink.refs\" },\n { name = \"obsidian_tags\", module = \"obsidian.completion.sources.blink.tags\" },\n}\n\nlocal function add_provider(blink, provider_name, proivder_module)\n local add_source_provider = blink.add_source_provider or blink.add_provider\n add_source_provider(provider_name, {\n name = provider_name,\n module = proivder_module,\n async = true,\n opts = {},\n enabled = function()\n -- Enable only in markdown buffers.\n return vim.tbl_contains({ \"markdown\" }, vim.bo.filetype)\n and vim.bo.buftype ~= \"prompt\"\n and vim.b.completion ~= false\n end,\n })\nend\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_providers(opts)\n local blink = require \"blink.cmp\"\n\n if opts.completion.create_new then\n table.insert(M.providers, { name = \"obsidian_new\", module = \"obsidian.completion.sources.blink.new\" })\n end\n\n for _, provider in pairs(M.providers) do\n add_provider(blink, provider.name, provider.module)\n end\nend\n\nlocal function add_element_to_list_if_not_exists(list, element)\n if not vim.tbl_contains(list, element) then\n table.insert(list, 1, element)\n end\nend\n\nlocal function should_return_if_not_in_workspace()\n local current_file_path = vim.api.nvim_buf_get_name(0)\n local buf_dir = vim.fs.dirname(current_file_path)\n\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return true\n else\n return false\n end\nend\n\nlocal function log_unexpected_type(config_path, unexpected_type, expected_type)\n vim.notify(\n \"blink.cmp's `\"\n .. config_path\n .. \"` configuration appears to be an '\"\n .. unexpected_type\n .. \"' type, but it \"\n .. \"should be '\"\n .. expected_type\n .. \"'. Obsidian won't update this configuration, and \"\n .. \"completion won't work with blink.cmp\",\n vim.log.levels.ERROR\n )\nend\n\n---Attempts to inject the Obsidian sources into per_filetype if that's what the user seems to use for markdown\n---@param blink_sources_per_filetype table\n---@return boolean true if it obsidian sources were injected into the sources.per_filetype\nlocal function try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype)\n -- If the per_filetype is an empty object, then it's probably not utilized by the user\n if vim.deep_equal(blink_sources_per_filetype, {}) then\n return false\n end\n\n local markdown_config = blink_sources_per_filetype[\"markdown\"]\n\n -- If the markdown key is not used, then per_filetype it's probably not utilized by the user\n if markdown_config == nil then\n return false\n end\n\n local markdown_config_type = type(markdown_config)\n if markdown_config_type == \"table\" and util.islist(markdown_config) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(markdown_config, provider.name)\n end\n return true\n elseif markdown_config_type == \"function\" then\n local original_func = markdown_config\n markdown_config = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.per_filetype[\"markdown\"] = markdown_config\n return true\n else\n log_unexpected_type(\n \".sources.per_filetype['markdown']\",\n markdown_config_type,\n \"a list or a function that returns a list of sources\"\n )\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n---Attempts to inject the Obsidian sources into default if that's what the user seems to use for markdown\n---@param blink_sources_default (fun():string[])|(string[])\n---@return boolean true if it obsidian sources were injected into the sources.default\nlocal function try_inject_blink_sources_into_default(blink_sources_default)\n local blink_default_type = type(blink_sources_default)\n if blink_default_type == \"function\" then\n local original_func = blink_sources_default\n blink_sources_default = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.default = blink_sources_default\n return true\n elseif blink_default_type == \"table\" and util.islist(blink_sources_default) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(blink_sources_default, provider.name)\n end\n\n return true\n elseif blink_default_type == \"table\" then\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n else\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list or a function that returns a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace. nvm_cmp had the capability to configure the sources\n-- per buffer, but blink.cmp doesn't have that capability. Instead, we have to inject the sources into the global\n-- configuration and set a boolean on the module to return early the next time this function is called.\n--\n-- In-case the user used functions to configure their sources, the completion will properly work just for the markdown\n-- files that are in a workspace. Otherwise, the completion will work for all markdown files.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n if M.injected_once then\n return\n end\n\n M.injected_once = true\n\n local blink_config = require \"blink.cmp.config\"\n -- 'per_filetype' sources has priority over 'default' sources.\n -- 'per_filetype' can be a table or a function which returns a table ([\"filetype\"] = { \"a\", \"b\" })\n -- 'per_filetype' has the default value of {} (even if it's not configured by the user)\n local blink_sources_per_filetype = blink_config.sources.per_filetype\n if try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype) then\n return\n end\n\n -- 'default' can be a list/array or a function which returns a list/array ({ \"a\", \"b\"})\n local blink_sources_default = blink_config.sources[\"default\"]\n if try_inject_blink_sources_into_default(blink_sources_default) then\n return\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/async.lua", "local abc = require \"obsidian.abc\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal uv = vim.uv\n\nlocal M = {}\n\n---An abstract class that mimics Python's `concurrent.futures.Executor` class.\n---@class obsidian.Executor : obsidian.ABC\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal Executor = abc.new_class()\n\n---@return obsidian.Executor\nExecutor.new = function()\n local self = Executor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback for the executor to run.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local,unused-vararg\nExecutor.submit = function(self, fn, callback, ...)\n error \"not implemented\"\nend\n\n---Map a function over a generator or array of task args, or the keys and values in a regular table.\n---The callback is called with an array of the results once all tasks have finished.\n---The order of the results passed to the callback will be the same as the order of the corresponding task args.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param task_args table[]|table|function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nExecutor.map = function(self, fn, task_args, callback)\n local results = {}\n local num_tasks = 0\n local tasks_completed = 0\n local all_submitted = false\n local tx, rx = channel.oneshot()\n\n local function collect_results()\n rx()\n return results\n end\n\n local function get_task_done_fn(i)\n return function(...)\n tasks_completed = tasks_completed + 1\n results[i] = { ... }\n if all_submitted and tasks_completed == num_tasks then\n tx()\n end\n end\n end\n\n if type(task_args) == \"table\" and util.islist(task_args) then\n num_tasks = #task_args\n for i, args in ipairs(task_args) do\n if i == #task_args then\n all_submitted = true\n end\n if type(args) ~= \"table\" then\n args = { args }\n end\n self:submit(fn, get_task_done_fn(i), unpack(args))\n end\n elseif type(task_args) == \"table\" then\n num_tasks = vim.tbl_count(task_args)\n local i = 0\n for k, v in pairs(task_args) do\n i = i + 1\n if i == #task_args then\n all_submitted = true\n end\n self:submit(fn, get_task_done_fn(i), k, v)\n end\n elseif type(task_args) == \"function\" then\n local i = 0\n local args = { task_args() }\n local next_args = { task_args() }\n while args[1] ~= nil do\n if next_args[1] == nil then\n all_submitted = true\n end\n i = i + 1\n num_tasks = num_tasks + 1\n self:submit(fn, get_task_done_fn(i), unpack(args))\n args = next_args\n next_args = { task_args() }\n end\n else\n error(string.format(\"unexpected type '%s' for 'task_args'\", type(task_args)))\n end\n\n if num_tasks == 0 then\n if callback ~= nil then\n callback {}\n end\n else\n async.run(collect_results, callback and callback or function(_) end)\n end\nend\n\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param pause_fn function(integer)\nExecutor._join = function(self, timeout, pause_fn)\n local start_time = uv.hrtime() / 1000000 -- ns -> ms\n local pause_for = 100\n if timeout ~= nil then\n pause_for = math.min(timeout / 2, pause_for)\n end\n while self.tasks_pending > 0 or self.tasks_running > 0 do\n pause_fn(pause_for)\n if timeout ~= nil and (uv.hrtime() / 1000000) - start_time > timeout then\n error \"Timeout error from Executor.join()\"\n end\n end\nend\n\n---Block Neovim until all currently running tasks have completed, waiting at most `timeout` milliseconds\n---before raising a timeout error.\n---\n---This is useful in testing, but in general you want to avoid blocking Neovim.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join = function(self, timeout)\n self:_join(timeout, vim.wait)\nend\n\n---An async version of `.join()`.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join_async = function(self, timeout)\n self:_join(timeout, async.util.sleep)\nend\n\n---Run the callback when the executor finishes all tasks.\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param callback function\nExecutor.join_and_then = function(self, timeout, callback)\n async.run(function()\n self:join_async(timeout)\n end, callback)\nend\n\n---An Executor that uses coroutines to run user functions concurrently.\n---@class obsidian.AsyncExecutor : obsidian.Executor\n---@field max_workers integer|?\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal AsyncExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"AsyncExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.AsyncExecutor = AsyncExecutor\n\n---@param max_workers integer|?\n---@return obsidian.AsyncExecutor\nAsyncExecutor.new = function(max_workers)\n local self = AsyncExecutor.init()\n if max_workers == nil then\n max_workers = 10\n elseif max_workers < 0 then\n max_workers = nil\n elseif max_workers == 0 then\n max_workers = 1\n end\n self.max_workers = max_workers\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.AsyncExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nAsyncExecutor.submit = function(self, fn, callback, ...)\n self.tasks_pending = self.tasks_pending + 1\n local args = { ... }\n async.run(function()\n if self.max_workers ~= nil then\n while self.tasks_running >= self.max_workers do\n async.util.sleep(20)\n end\n end\n self.tasks_pending = self.tasks_pending - 1\n self.tasks_running = self.tasks_running + 1\n return fn(unpack(args))\n end, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\nend\n\n---A multi-threaded Executor which uses the Libuv threadpool.\n---@class obsidian.ThreadPoolExecutor : obsidian.Executor\n---@field tasks_running integer\nlocal ThreadPoolExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"ThreadPoolExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.ThreadPoolExecutor = ThreadPoolExecutor\n\n---@return obsidian.ThreadPoolExecutor\nThreadPoolExecutor.new = function()\n local self = ThreadPoolExecutor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.ThreadPoolExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nThreadPoolExecutor.submit = function(self, fn, callback, ...)\n self.tasks_running = self.tasks_running + 1\n local ctx = uv.new_work(fn, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\n ctx:queue(...)\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@param sync boolean\nlocal init_job = function(cmds, on_stdout, on_exit, sync)\n local stderr_lines = false\n\n local on_obj = function(obj)\n --- NOTE: commands like `rg` return a non-zero exit code when there are no matches, which is okay.\n --- So we only log no-zero exit codes as errors when there's also stderr lines.\n if obj.code > 0 and stderr_lines then\n log.err(\"Command '%s' exited with non-zero code %s. See logs for stderr.\", cmds, obj.code)\n elseif stderr_lines then\n log.warn(\"Captured stderr output while running command '%s'. See logs for details.\", cmds)\n end\n if on_exit ~= nil then\n on_exit(obj.code)\n end\n end\n\n on_stdout = util.buffer_fn(on_stdout)\n\n local function stdout(err, data)\n if err ~= nil then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n end\n if data ~= nil then\n on_stdout(data)\n end\n end\n\n local function stderr(err, data)\n if err then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n elseif data ~= nil then\n if not stderr_lines then\n log.err(\"Captured stderr output while running command '%s'\", cmds)\n stderr_lines = true\n end\n log.err(\"[stderr] %s\", data)\n end\n end\n\n return function()\n log.debug(\"Initializing job '%s'\", cmds)\n\n if sync then\n local obj = vim.system(cmds, { stdout = stdout, stderr = stderr }):wait()\n on_obj(obj)\n return obj\n else\n vim.system(cmds, { stdout = stdout, stderr = stderr }, on_obj)\n end\n end\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@return integer exit_code\nM.run_job = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, true)\n return job().code\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\nM.run_job_async = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, false)\n job()\nend\n\n---@param fn function\n---@param timeout integer (milliseconds)\nM.throttle = function(fn, timeout)\n ---@type integer\n local last_call = 0\n ---@type uv.uv_timer_t?\n local timer = nil\n\n return function(...)\n if timer ~= nil then\n timer:stop()\n end\n\n local ms_remaining = timeout - (vim.uv.now() - last_call)\n\n if ms_remaining > 0 then\n if timer == nil then\n timer = assert(vim.uv.new_timer())\n end\n\n local args = { ... }\n\n timer:start(\n ms_remaining,\n 0,\n vim.schedule_wrap(function()\n if timer ~= nil then\n timer:stop()\n timer:close()\n timer = nil\n end\n\n last_call = vim.uv.now()\n fn(unpack(args))\n end)\n )\n else\n last_call = vim.uv.now()\n fn(...)\n end\n end\nend\n\n---Run an async function in a non-async context. The async function is expected to take a single\n---callback parameters with the results. This function returns those results.\n---@param async_fn_with_callback function (function,) -> any\n---@param timeout integer|?\n---@return ...any results\nM.block_on = function(async_fn_with_callback, timeout)\n local done = false\n local result\n timeout = timeout and timeout or 2000\n\n local function collect_result(...)\n result = { ... }\n done = true\n end\n\n async_fn_with_callback(collect_result)\n\n vim.wait(timeout, function()\n return done\n end, 20, false)\n\n return unpack(result)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/health.lua", "local M = {}\nlocal VERSION = require \"obsidian.version\"\nlocal api = require \"obsidian.api\"\n\nlocal error = vim.health.error\nlocal warn = vim.health.warn\nlocal ok = vim.health.ok\n\nlocal function info(...)\n local t = { ... }\n local format = table.remove(t, 1)\n local str = #t == 0 and format or string.format(format, unpack(t))\n return ok(str)\nend\n\n---@private\n---@param name string\nlocal function start(name)\n vim.health.start(string.format(\"obsidian.nvim [%s]\", name))\nend\n\n---@param plugin string\n---@param optional boolean\n---@return boolean\nlocal function has_plugin(plugin, optional)\n local plugin_info = api.get_plugin_info(plugin)\n if plugin_info then\n info(\"%s: %s\", plugin, plugin_info.commit or \"unknown\")\n return true\n else\n if not optional then\n vim.health.error(\" \" .. plugin .. \" not installed\")\n end\n return false\n end\nend\n\nlocal function has_executable(name, optional)\n if vim.fn.executable(name) == 1 then\n local version = api.get_external_dependency_info(name)\n if version then\n info(\"%s: %s\", name, version)\n else\n info(\"%s: found\", name)\n end\n return true\n else\n if not optional then\n error(string.format(\"%s not found\", name))\n end\n return false\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_plugin(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of_executable(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_executable(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param minimum string\n---@param recommended string\nlocal function neovim(minimum, recommended)\n if vim.fn.has(\"nvim-\" .. minimum) == 0 then\n error(\"neovim < \" .. minimum)\n elseif vim.fn.has(\"nvim-\" .. recommended) == 0 then\n warn(\"neovim < \" .. recommended .. \" some features will not work\")\n else\n ok(\"neovim >= \" .. recommended)\n end\nend\n\nfunction M.check()\n local os = api.get_os()\n neovim(\"0.10\", \"0.11\")\n start \"Version\"\n info(\"obsidian.nvim v%s (%s)\", VERSION, api.get_plugin_info(\"obsidian.nvim\").commit)\n\n start \"Environment\"\n info(\"operating system: %s\", os)\n\n start \"Config\"\n info(\" • dir: %s\", Obsidian.dir)\n\n start \"Pickers\"\n\n has_one_of {\n \"telescope.nvim\",\n \"fzf-lua\",\n \"mini.nvim\",\n \"mini.pick\",\n \"snacks.nvim\",\n }\n\n start \"Completion\"\n\n has_one_of {\n \"nvim-cmp\",\n \"blink.cmp\",\n }\n\n start \"Dependencies\"\n has_executable(\"rg\", false)\n has_plugin(\"plenary.nvim\", false)\n\n if os == api.OSType.Wsl then\n has_executable(\"wsl-open\", true)\n elseif os == api.OSType.Linux then\n has_one_of_executable {\n \"xclip\",\n \"wl-paste\",\n }\n elseif os == api.OSType.Darwin then\n has_executable(\"pngpaste\", true)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/new.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type obsidian.Note\n local note\n if data.args:len() > 0 then\n note = Note.create { title = data.args }\n else\n local title = api.input(\"Enter title or path (optional): \", { completion = \"file\" })\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n note = Note.create { title = title }\n end\n\n -- Open the note in a new buffer.\n note:open { sync = true }\n note:write_to_buffer()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/follow_link.lua", "local api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local opts = {}\n if data.args and string.len(data.args) > 0 then\n opts.open_strategy = data.args\n end\n\n local link = api.cursor_link()\n\n if link then\n api.follow_link(link, opts)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/check.lua", "local Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal iter = vim.iter\n\nreturn function()\n local start_time = vim.uv.hrtime()\n local count = 0\n local errors = {}\n local warnings = {}\n\n for path in api.dir(Obsidian.dir) do\n local relative_path = Path.new(path):vault_relative_path { strict = true }\n local ok, res = pcall(Note.from_file, path)\n\n if not ok then\n errors[#errors + 1] = string.format(\"Failed to parse note '%s': \", relative_path, res)\n elseif res.has_frontmatter == false then\n warnings[#warnings + 1] = string.format(\"'%s' missing frontmatter\", relative_path)\n end\n count = count + 1\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n local messages = { \"Checked \" .. tostring(count) .. \" notes in \" .. runtime .. \"ms\" }\n local log_level = vim.log.levels.INFO\n\n if #warnings > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#warnings) .. \" warning(s):\"\n log_level = vim.log.levels.WARN\n for warning in iter(warnings) do\n messages[#messages + 1] = \"  \" .. warning\n end\n end\n\n if #errors > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#errors) .. \" error(s):\"\n for err in iter(errors) do\n messages[#messages + 1] = \"  \" .. err\n end\n log_level = vim.log.levels.ERROR\n end\n\n log.log(table.concat(messages, \"\\n\"), log_level)\nend\n"], ["/obsidian.nvim/lua/obsidian/yaml/parser.lua", "local Line = require \"obsidian.yaml.line\"\nlocal abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\n\nlocal m = {}\n\n---@class obsidian.yaml.ParserOpts\n---@field luanil boolean\nlocal ParserOpts = {}\n\nm.ParserOpts = ParserOpts\n\n---@return obsidian.yaml.ParserOpts\nParserOpts.default = function()\n return {\n luanil = true,\n }\nend\n\n---@param opts table\n---@return obsidian.yaml.ParserOpts\nParserOpts.normalize = function(opts)\n ---@type obsidian.yaml.ParserOpts\n opts = vim.tbl_extend(\"force\", ParserOpts.default(), opts)\n return opts\nend\n\n---@class obsidian.yaml.Parser : obsidian.ABC\n---@field opts obsidian.yaml.ParserOpts\nlocal Parser = abc.new_class()\n\nm.Parser = Parser\n\n---@enum YamlType\nlocal YamlType = {\n Scalar = \"Scalar\", -- a boolean, string, number, or NULL\n Mapping = \"Mapping\",\n Array = \"Array\",\n ArrayItem = \"ArrayItem\",\n EmptyLine = \"EmptyLine\",\n}\n\nm.YamlType = YamlType\n\n---@class vim.NIL\n\n---Create a new Parser.\n---@param opts obsidian.yaml.ParserOpts|?\n---@return obsidian.yaml.Parser\nm.new = function(opts)\n local self = Parser.init()\n self.opts = ParserOpts.normalize(opts and opts or {})\n return self\nend\n\n---Parse a YAML string.\n---@param str string\n---@return any\nParser.parse = function(self, str)\n -- Collect and pre-process lines.\n local lines = {}\n local base_indent = 0\n for raw_line in str:gmatch \"[^\\r\\n]+\" do\n local ok, result = pcall(Line.new, raw_line, base_indent)\n if ok then\n local line = result\n if #lines == 0 then\n base_indent = line.indent\n line.indent = 0\n end\n table.insert(lines, line)\n else\n local err = result\n error(self:_error_msg(tostring(err), #lines + 1))\n end\n end\n\n -- Now iterate over the root elements, differing to `self:_parse_next()` to recurse into child elements.\n ---@type any\n local root_value = nil\n ---@type table|?\n local parent = nil\n local current_indent = 0\n local i = 1\n while i <= #lines do\n local line = lines[i]\n\n if line:is_empty() then\n -- Empty line, skip it.\n i = i + 1\n elseif line.indent == current_indent then\n local value\n local value_type\n i, value, value_type = self:_parse_next(lines, i)\n assert(value_type ~= YamlType.EmptyLine)\n if root_value == nil and line.indent == 0 then\n -- Set the root value.\n if value_type == YamlType.ArrayItem then\n root_value = { value }\n else\n root_value = value\n end\n\n -- The parent must always be a table (array or mapping), so set that to the root value now\n -- if we have a table.\n if type(root_value) == \"table\" then\n parent = root_value\n end\n elseif util.islist(parent) and value_type == YamlType.ArrayItem then\n -- Add value to parent array.\n parent[#parent + 1] = value\n elseif type(parent) == \"table\" and value_type == YamlType.Mapping then\n assert(parent ~= nil) -- for type checking\n -- Add value to parent mapping.\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if parent[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i, line.content))\n else\n parent[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value\", i, line.content))\n end\n else\n error(self:_error_msg(\"invalid indentation\", i))\n end\n current_indent = line.indent\n end\n\n return root_value\nend\n\n---Parse the next single item, recursing to child blocks if necessary.\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@param text string|?\n---@return integer, any, string\nParser._parse_next = function(self, lines, i, text)\n local line = lines[i]\n if text == nil then\n -- Skip empty lines.\n while line:is_empty() and i <= #lines do\n i = i + 1\n line = lines[i]\n end\n if line:is_empty() then\n return i, nil, YamlType.EmptyLine\n end\n text = util.strip_comments(line.content)\n end\n\n local _, ok, value\n\n -- First just check for a string enclosed in quotes.\n if util.has_enclosing_chars(text) then\n _, _, value = self:_parse_string(i, text)\n return i + 1, value, YamlType.Scalar\n end\n\n -- Check for array item, like `- foo`.\n ok, i, value = self:_try_parse_array_item(lines, i, text)\n if ok then\n return i, value, YamlType.ArrayItem\n end\n\n -- Check for a block string field, like `foo: |`.\n ok, i, value = self:_try_parse_block_string(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Check for any other `key: value` fields.\n ok, i, value = self:_try_parse_field(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Otherwise we have an inline value.\n local value_type\n value, value_type = self:_parse_inline_value(i, text)\n return i + 1, value, value_type\nend\n\n---@return vim.NIL|nil\nParser._new_null = function(self)\n if self.opts.luanil then\n return nil\n else\n return vim.NIL\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param msg string\n---@param line_num integer\n---@param line_text string|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nParser._error_msg = function(self, msg, line_num, line_text)\n local full_msg = \"[line=\" .. tostring(line_num) .. \"] \" .. msg\n if line_text ~= nil then\n full_msg = full_msg .. \" (text='\" .. line_text .. \"')\"\n end\n return full_msg\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_field = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n\n local _, key, value\n\n -- First look for start of mapping, array, block, etc, e.g. 'foo:'\n _, _, key = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*):$\")\n if not key then\n -- Then try inline field, e.g. 'foo: bar'\n _, _, key, value = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*): (.*)\")\n end\n\n value = value and vim.trim(value) or nil\n if value == \"\" then\n value = nil\n end\n\n if key ~= nil and value ~= nil then\n -- This is a mapping, e.g. `foo: 1`.\n local out = {}\n value = self:_parse_inline_value(i, value)\n local j = i + 1\n -- Check for multi-line string here.\n local next_line = lines[j]\n if type(value) == \"string\" and next_line ~= nil and next_line.indent > line.indent then\n local next_indent = next_line.indent\n while next_line ~= nil and next_line.indent == next_indent do\n local next_value_str = util.strip_comments(next_line.content)\n if string.len(next_value_str) > 0 then\n local next_value = self:_parse_inline_value(j, next_line.content)\n if type(next_value) ~= \"string\" then\n error(self:_error_msg(\"expected a string, found \" .. type(next_value), j, next_line.content))\n end\n value = value .. \" \" .. next_value\n end\n j = j + 1\n next_line = lines[j]\n end\n end\n out[key] = value\n return true, j, out\n elseif key ~= nil then\n local out = {}\n local next_line = lines[i + 1]\n local j = i + 1\n if next_line ~= nil and next_line.indent >= line.indent and vim.startswith(next_line.content, \"- \") then\n -- This is the start of an array.\n local array\n j, array = self:_parse_array(lines, j)\n out[key] = array\n elseif next_line ~= nil and next_line.indent > line.indent then\n -- This is the start of a mapping.\n local mapping\n j, mapping = self:_parse_mapping(j, lines)\n out[key] = mapping\n else\n -- This is an implicit null field.\n out[key] = self:_new_null()\n end\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_block_string = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n local _, _, block_key = string.find(text, \"([a-zA-Z0-9_-]+):%s?|\")\n if block_key ~= nil then\n local block_lines = {}\n local j = i + 1\n local next_line = lines[j]\n if next_line == nil then\n error(self:_error_msg(\"expected another line\", i, text))\n end\n local item_indent = next_line.indent\n while j <= #lines do\n next_line = lines[j]\n if next_line ~= nil and next_line.indent >= item_indent then\n j = j + 1\n table.insert(block_lines, util.lstrip_whitespace(next_line.raw_content, item_indent))\n else\n break\n end\n end\n local out = {}\n out[block_key] = table.concat(block_lines, \"\\n\")\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_array_item = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n if vim.startswith(text, \"- \") then\n local _, _, array_item_str = string.find(text, \"- (.*)\")\n local value\n -- Check for null entry.\n if array_item_str == \"\" then\n value = self:_new_null()\n i = i + 1\n else\n i, value = self:_parse_next(lines, i, array_item_str)\n end\n return true, i, value\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@return integer, any[]\nParser._parse_array = function(self, lines, i)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent and vim.startswith(line.content, \"- \") then\n local is_array_item, value\n is_array_item, i, value = self:_try_parse_array_item(lines, i)\n assert(is_array_item)\n out[#out + 1] = value\n elseif line:is_empty() then\n i = i + 1\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse an array but didn't find any entries\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@return integer, table\nParser._parse_mapping = function(self, i, lines)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent then\n local value, value_type\n i, value, value_type = self:_parse_next(lines, i)\n if value_type == YamlType.Mapping then\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if out[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i))\n else\n out[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value found found in table\", i))\n end\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse a mapping but didn't find any entries to parse\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return any, string\nParser._parse_inline_value = function(self, i, text)\n for parse_func_and_type in iter {\n { self._parse_number, YamlType.Scalar },\n { self._parse_null, YamlType.Scalar },\n { self._parse_boolean, YamlType.Scalar },\n { self._parse_inline_array, YamlType.Array },\n { self._parse_inline_mapping, YamlType.Mapping },\n { self._parse_string, YamlType.Scalar },\n } do\n local parse_func, parse_type = unpack(parse_func_and_type)\n local ok, errmsg, res = parse_func(self, i, text)\n if ok then\n return res, parse_type\n elseif errmsg ~= nil then\n error(errmsg)\n end\n end\n -- Should never get here because we always fall back to parsing as a string.\n error(self:_error_msg(\"unable to parse\", i))\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, any[]|?\nParser._parse_inline_array = function(self, i, text)\n local str\n if vim.startswith(text, \"[\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"]\") then\n str = string.sub(str, 1, -2)\n else\n return false, nil, nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n local item_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n item_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n item_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n item_str, str = util.next_item(str, { \",\" }, false)\n end\n if item_str == nil then\n return false, self:_error_msg(\"invalid inline array\", i, text), nil\n end\n out[#out + 1] = self:_parse_inline_value(i, item_str)\n\n if vim.startswith(str, \",\") then\n str = string.sub(str, 2)\n end\n str = util.lstrip_whitespace(str)\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, table|?\nParser._parse_inline_mapping = function(self, i, text)\n local str\n if vim.startswith(text, \"{\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"}\") then\n str = string.sub(str, 1, -2)\n else\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n -- Parse the key.\n local key_str\n key_str, str = util.next_item(str, { \":\" }, false)\n if key_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local _, _, key = self:_parse_string(i, key_str)\n\n -- Parse the value.\n str = util.lstrip_whitespace(str)\n local value_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n value_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n value_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n value_str, str = util.next_item(str, { \",\" }, false)\n end\n if value_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local value = self:_parse_inline_value(i, value_str)\n if out[key] == nil then\n out[key] = value\n else\n return false, self:_error_msg(\"duplicate key '\" .. key .. \"' found in inline mapping\", i, text), nil\n end\n\n if vim.startswith(str, \",\") then\n str = util.lstrip_whitespace(string.sub(str, 2))\n end\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, string\n---@diagnostic disable-next-line: unused-local\nParser._parse_string = function(self, i, text)\n if vim.startswith(text, [[\"]]) and vim.endswith(text, [[\"]]) then\n -- when the text is enclosed with double-quotes we need to un-escape certain characters.\n text = string.gsub(text, vim.pesc [[\\\"]], [[\"]])\n end\n return true, nil, util.strip_enclosing_chars(vim.trim(text))\nend\n\n---Parse a string value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return string\nParser.parse_string = function(self, text)\n local _, _, str = self:_parse_string(1, util.strip_comments(text))\n return str\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, number|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_number = function(self, i, text)\n local out = tonumber(text)\n if out == nil or util.isNan(out) then\n return false, nil, nil\n else\n return true, nil, out\n end\nend\n\n---Parse a number value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return number\nParser.parse_number = function(self, text)\n local ok, errmsg, res = self:_parse_number(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a number\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, boolean|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_boolean = function(self, i, text)\n if text == \"true\" then\n return true, nil, true\n elseif text == \"false\" then\n return true, nil, false\n else\n return false, nil, nil\n end\nend\n\n---Parse a boolean value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean\nParser.parse_boolean = function(self, text)\n local ok, errmsg, res = self:_parse_boolean(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a boolean\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean, string|?, vim.NIL|nil\n---@diagnostic disable-next-line: unused-local\nParser._parse_null = function(self, i, text)\n if text == \"null\" or text == \"\" then\n return true, nil, self:_new_null()\n else\n return false, nil, nil\n end\nend\n\n---Parse a NULL value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return vim.NIL|nil\nParser.parse_null = function(self, text)\n local ok, errmsg, res = self:_parse_null(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a null value\", 1, text)\n error(errmsg)\n else\n return res\n end\nend\n\n---Deserialize a YAML string.\nm.loads = function(str)\n local parser = m.new()\n return parser:parse(str)\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/daily/init.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\n\n--- Get the path to a daily note.\n---\n---@param datetime integer|?\n---\n---@return obsidian.Path, string (Path, ID) The path and ID of the note.\nlocal daily_note_path = function(datetime)\n datetime = datetime and datetime or os.time()\n\n ---@type obsidian.Path\n local path = Path:new(Obsidian.dir)\n\n local options = Obsidian.opts\n\n if options.daily_notes.folder ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.daily_notes.folder\n elseif options.notes_subdir ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.notes_subdir\n end\n\n local id\n if options.daily_notes.date_format ~= nil then\n id = tostring(os.date(options.daily_notes.date_format, datetime))\n else\n id = tostring(os.date(\"%Y-%m-%d\", datetime))\n end\n\n path = path / (id .. \".md\")\n\n -- ID may contain additional path components, so make sure we use the stem.\n id = path.stem\n\n return path, id\nend\n\n--- Open (or create) the daily note.\n---\n---@param datetime integer\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\n---\nlocal _daily = function(datetime, opts)\n opts = opts or {}\n\n local path, id = daily_note_path(datetime)\n\n local options = Obsidian.opts\n\n ---@type string|?\n local alias\n if options.daily_notes.alias_format ~= nil then\n alias = tostring(os.date(options.daily_notes.alias_format, datetime))\n end\n\n ---@type obsidian.Note\n local note\n if path:exists() then\n note = Note.from_file(path, opts.load)\n else\n note = Note.create {\n id = id,\n aliases = {},\n tags = options.daily_notes.default_tags or {},\n dir = path:parent(),\n }\n\n if alias then\n note:add_alias(alias)\n note.title = alias\n end\n\n if not opts.no_write then\n note:write { template = options.daily_notes.template }\n end\n end\n\n return note\nend\n\n--- Open (or create) the daily note for today.\n---\n---@return obsidian.Note\nlocal today = function()\n return _daily(os.time(), {})\nend\n\n--- Open (or create) the daily note from the last day.\n---\n---@return obsidian.Note\nlocal yesterday = function()\n local now = os.time()\n local yesterday\n\n if Obsidian.opts.daily_notes.workdays_only then\n yesterday = util.working_day_before(now)\n else\n yesterday = util.previous_day(now)\n end\n\n return _daily(yesterday, {})\nend\n\n--- Open (or create) the daily note for the next day.\n---\n---@return obsidian.Note\nlocal tomorrow = function()\n local now = os.time()\n local tomorrow\n\n if Obsidian.opts.daily_notes.workdays_only then\n tomorrow = util.working_day_after(now)\n else\n tomorrow = util.next_day(now)\n end\n\n return _daily(tomorrow, {})\nend\n\n--- Open (or create) the daily note for today + `offset_days`.\n---\n---@param offset_days integer|?\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\nlocal daily = function(offset_days, opts)\n return _daily(os.time() + (offset_days * 3600 * 24), opts)\nend\n\nreturn {\n daily_note_path = daily_note_path,\n daily = daily,\n tomorrow = tomorrow,\n yesterday = yesterday,\n today = today,\n}\n"], ["/obsidian.nvim/lua/obsidian/log.lua", "---@class obsidian.Logger\nlocal log = {}\n\nlog._log_level = vim.log.levels.INFO\n\n---@param t table\n---@return boolean\nlocal function has_tostring(t)\n local mt = getmetatable(t)\n return mt ~= nil and mt.__tostring ~= nil\nend\n\n---@param msg string\n---@return any[]\nlocal function message_args(msg, ...)\n local args = { ... }\n local num_directives = select(2, string.gsub(msg, \"%%\", \"\")) - 2 * select(2, string.gsub(msg, \"%%%%\", \"\"))\n\n -- Some elements might be nil, so we can't use 'ipairs'.\n local out = {}\n for i = 1, #args do\n local v = args[i]\n if v == nil then\n out[i] = tostring(v)\n elseif type(v) == \"table\" and not has_tostring(v) then\n out[i] = vim.inspect(v)\n else\n out[i] = v\n end\n end\n\n -- If were short formatting args relative to the number of directives, add \"nil\" strings on.\n if #out < num_directives then\n for i = #out + 1, num_directives do\n out[i] = \"nil\"\n end\n end\n\n return out\nend\n\n---@param level integer\nlog.set_level = function(level)\n log._log_level = level\nend\n\n--- Log a message.\n---\n---@param msg any\n---@param level integer|?\nlog.log = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---Log a message only once.\n---\n---@param msg any\n---@param level integer|?\nlog.log_once = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---@param msg string\nlog.debug = function(msg, ...)\n log.log(msg, vim.log.levels.DEBUG, ...)\nend\n\n---@param msg string\nlog.info = function(msg, ...)\n log.log(msg, vim.log.levels.INFO, ...)\nend\n\n---@param msg string\nlog.warn = function(msg, ...)\n log.log(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.warn_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.err = function(msg, ...)\n log.log(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error = log.err\n\n---@param msg string\nlog.err_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error_once = log.err\n\nreturn log\n"], ["/obsidian.nvim/lua/obsidian/path.lua", "local abc = require \"obsidian.abc\"\n\nlocal function coerce(v)\n if v == vim.NIL then\n return nil\n else\n return v\n end\nend\n\n---@param path table\n---@param k string\n---@param factory fun(obsidian.Path): any\nlocal function cached_get(path, k, factory)\n local cache_key = \"__\" .. k\n local v = rawget(path, cache_key)\n if v == nil then\n v = factory(path)\n if v == nil then\n v = vim.NIL\n end\n path[cache_key] = v\n end\n return coerce(v)\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_name(path)\n local name = vim.fs.basename(path.filename)\n if not name or string.len(name) == 0 then\n return\n else\n return name\n end\nend\n\n---@param path obsidian.Path\n---@return string[]\n---@private\nlocal function get_suffixes(path)\n ---@type string[]\n local suffixes = {}\n local name = path.name\n while name and string.len(name) > 0 do\n local s, e, suffix = string.find(name, \"(%.[^%.]+)$\")\n if s and e and suffix then\n name = string.sub(name, 1, s - 1)\n table.insert(suffixes, suffix)\n else\n break\n end\n end\n\n -- reverse the list.\n ---@type string[]\n local out = {}\n for i = #suffixes, 1, -1 do\n table.insert(out, suffixes[i])\n end\n return out\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_suffix(path)\n local suffixes = path.suffixes\n if #suffixes > 0 then\n return suffixes[#suffixes]\n else\n return nil\n end\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_stem(path)\n local name, suffix = path.name, path.suffix\n if not name then\n return\n elseif not suffix then\n return name\n else\n return string.sub(name, 1, string.len(name) - string.len(suffix))\n end\nend\n\n--- A `Path` class that provides a subset of the functionality of the Python `pathlib` library while\n--- staying true to its API. It improves on a number of bugs in `plenary.path`.\n---\n---@toc_entry obsidian.Path\n---\n---@class obsidian.Path : obsidian.ABC\n---\n---@field filename string The underlying filename as a string.\n---@field name string|? The final path component, if any.\n---@field suffix string|? The final extension of the path, if any.\n---@field suffixes string[] A list of all of the path's extensions.\n---@field stem string|? The final path component, without its suffix.\nlocal Path = abc.new_class()\n\nPath.mt = {\n __tostring = function(self)\n return self.filename\n end,\n __eq = function(a, b)\n return a.filename == b.filename\n end,\n __div = function(self, other)\n return self:joinpath(other)\n end,\n __index = function(self, k)\n local raw = rawget(Path, k)\n if raw then\n return raw\n end\n\n local factory\n if k == \"name\" then\n factory = get_name\n elseif k == \"suffix\" then\n factory = get_suffix\n elseif k == \"suffixes\" then\n factory = get_suffixes\n elseif k == \"stem\" then\n factory = get_stem\n end\n\n if factory then\n return cached_get(self, k, factory)\n end\n end,\n}\n\n--- Check if an object is an `obsidian.Path` object.\n---\n---@param path any\n---\n---@return boolean\nPath.is_path_obj = function(path)\n if getmetatable(path) == Path.mt then\n return true\n else\n return false\n end\nend\n\n-------------------------------------------------------------------------------\n--- Constructors.\n-------------------------------------------------------------------------------\n\n--- Create a new path from a string.\n---\n---@param ... string|obsidian.Path\n---\n---@return obsidian.Path\nPath.new = function(...)\n local self = Path.init()\n\n local args = { ... }\n local arg\n if #args == 1 then\n arg = tostring(args[1])\n elseif #args == 2 and args[1] == Path then\n arg = tostring(args[2])\n else\n error \"expected one argument\"\n end\n\n if Path.is_path_obj(arg) then\n ---@cast arg obsidian.Path\n return arg\n end\n\n self.filename = vim.fs.normalize(tostring(arg))\n\n return self\nend\n\n--- Get a temporary path with a unique name.\n---\n---@param opts { suffix: string|? }|?\n---\n---@return obsidian.Path\nPath.temp = function(opts)\n opts = opts or {}\n local tmpname = vim.fn.tempname()\n if opts.suffix then\n tmpname = tmpname .. opts.suffix\n end\n return Path.new(tmpname)\nend\n\n--- Get a path corresponding to the current working directory as given by `vim.uv.cwd()`.\n---\n---@return obsidian.Path\nPath.cwd = function()\n return assert(Path.new(vim.uv.cwd()))\nend\n\n--- Get a path corresponding to a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buffer = function(bufnr)\n return Path.new(vim.api.nvim_buf_get_name(bufnr or 0))\nend\n\n--- Get a path corresponding to the parent of a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buf_dir = function(bufnr)\n return assert(Path.buffer(bufnr):parent())\nend\n\n-------------------------------------------------------------------------------\n--- Pure path methods.\n-------------------------------------------------------------------------------\n\n--- Return a new path with the suffix changed.\n---\n---@param suffix string\n---@param should_append boolean|? should the suffix append a suffix instead of replacing one which may be there?\n---\n---@return obsidian.Path\nPath.with_suffix = function(self, suffix, should_append)\n if not vim.startswith(suffix, \".\") and string.len(suffix) > 1 then\n error(string.format(\"invalid suffix '%s'\", suffix))\n elseif self.stem == nil then\n error(string.format(\"path '%s' has no stem\", self.filename))\n end\n\n local new_name = ((should_append == true) and self.name or self.stem) .. suffix\n\n ---@type obsidian.Path|?\n local parent = nil\n if self.name ~= self.filename then\n parent = self:parent()\n end\n\n if parent then\n return parent / new_name\n else\n return Path.new(new_name)\n end\nend\n\n--- Returns true if the path is already in absolute form.\n---\n---@return boolean\nPath.is_absolute = function(self)\n local api = require \"obsidian.api\"\n if\n vim.startswith(self.filename, \"/\")\n or (\n (api.get_os() == api.OSType.Windows or api.get_os() == api.OSType.Wsl)\n and string.match(self.filename, \"^[%a]:/.*$\")\n )\n then\n return true\n else\n return false\n end\nend\n\n---@param ... obsidian.Path|string\n---@return obsidian.Path\nPath.joinpath = function(self, ...)\n local args = vim.iter({ ... }):map(tostring):totable()\n return Path.new(vim.fs.joinpath(self.filename, unpack(args)))\nend\n\n--- Try to resolve a version of the path relative to the other.\n--- An error is raised when it's not possible.\n---\n---@param other obsidian.Path|string\n---\n---@return obsidian.Path\nPath.relative_to = function(self, other)\n other = Path.new(other)\n\n local other_fname = other.filename\n if not vim.endswith(other_fname, \"/\") then\n other_fname = other_fname .. \"/\"\n end\n\n if vim.startswith(self.filename, other_fname) then\n return Path.new(string.sub(self.filename, string.len(other_fname) + 1))\n end\n\n -- Edge cases when the paths are relative or under-specified, see tests.\n if not self:is_absolute() and not vim.startswith(self.filename, \"./\") and vim.startswith(other_fname, \"./\") then\n if other_fname == \"./\" then\n return self\n end\n\n local self_rel_to_cwd = Path.new \"./\" / self\n if vim.startswith(self_rel_to_cwd.filename, other_fname) then\n return Path.new(string.sub(self_rel_to_cwd.filename, string.len(other_fname) + 1))\n end\n end\n\n error(string.format(\"'%s' is not in the subpath of '%s'\", self.filename, other.filename))\nend\n\n--- The logical parent of the path.\n---\n---@return obsidian.Path|?\nPath.parent = function(self)\n local parent = vim.fs.dirname(self.filename)\n if parent ~= nil then\n return Path.new(parent)\n else\n return nil\n end\nend\n\n--- Get a list of the parent directories.\n---\n---@return obsidian.Path[]\nPath.parents = function(self)\n return vim.iter(vim.fs.parents(self.filename)):map(Path.new):totable()\nend\n\n--- Check if the path is a parent of other. This is a pure path method, so it only checks by\n--- comparing strings. Therefore in practice you probably want to `:resolve()` each path before\n--- using this.\n---\n---@param other obsidian.Path|string\n---\n---@return boolean\nPath.is_parent_of = function(self, other)\n other = Path.new(other)\n for _, parent in ipairs(other:parents()) do\n if parent == self then\n return true\n end\n end\n return false\nend\n\n---@return string?\n---@private\nPath.abspath = function(self)\n local path = vim.loop.fs_realpath(vim.fn.resolve(self.filename))\n return path\nend\n\n-------------------------------------------------------------------------------\n--- Concrete path methods.\n-------------------------------------------------------------------------------\n\n--- Make the path absolute, resolving any symlinks.\n--- If `strict` is true and the path doesn't exist, an error is raised.\n---\n---@param opts { strict: boolean }|?\n---\n---@return obsidian.Path\nPath.resolve = function(self, opts)\n opts = opts or {}\n\n local realpath = self:abspath()\n if realpath then\n return Path.new(realpath)\n elseif opts.strict then\n error(\"FileNotFoundError: \" .. self.filename)\n end\n\n -- File doesn't exist, but some parents might. Traverse up until we find a parent that\n -- does exist, and then put the path back together from there.\n local parents = self:parents()\n for _, parent in ipairs(parents) do\n local parent_realpath = parent:abspath()\n if parent_realpath then\n return Path.new(parent_realpath) / self:relative_to(parent)\n end\n end\n\n return self\nend\n\n--- Get OS stat results.\n---\n---@return table|?\nPath.stat = function(self)\n local realpath = self:abspath()\n if realpath then\n local stat, _ = vim.uv.fs_stat(realpath)\n return stat\n end\nend\n\n--- Check if the path points to an existing file or directory.\n---\n---@return boolean\nPath.exists = function(self)\n local stat = self:stat()\n return stat ~= nil\nend\n\n--- Check if the path points to an existing file.\n---\n---@return boolean\nPath.is_file = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"file\"\n end\nend\n\n--- Check if the path points to an existing directory.\n---\n---@return boolean\nPath.is_dir = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"directory\"\n end\nend\n\n--- Create a new directory at the given path.\n---\n---@param opts { mode: integer|?, parents: boolean|?, exist_ok: boolean|? }|?\nPath.mkdir = function(self, opts)\n opts = opts or {}\n\n local mode = opts.mode or 448 -- 0700 -> decimal\n ---@diagnostic disable-next-line: undefined-field\n if opts.exists_ok then -- for compat with the plenary.path API.\n opts.exist_ok = true\n end\n\n if self:is_dir() then\n if not opts.exist_ok then\n error(\"FileExistsError: \" .. self.filename)\n else\n return\n end\n end\n\n if vim.uv.fs_mkdir(self.filename, mode) then\n return\n end\n\n if not opts.parents then\n error(\"FileNotFoundError: \" .. tostring(self:parent()))\n end\n\n local parents = self:parents()\n for i = #parents, 1, -1 do\n if not parents[i]:is_dir() then\n parents[i]:mkdir { exist_ok = true, mode = mode }\n end\n end\n\n self:mkdir { mode = mode }\nend\n\n--- Remove the corresponding directory. This directory must be empty.\nPath.rmdir = function(self)\n local resolved = self:resolve { strict = false }\n\n if not resolved:is_dir() then\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_rmdir(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n-- TODO: not implemented and not used, after we get to 0.11 we can simply use vim.fs.rm\n--- Recursively remove an entire directory and its contents.\nPath.rmtree = function(self) end\n\n--- Create a file at this given path.\n---\n---@param opts { mode: integer|?, exist_ok: boolean|? }|?\nPath.touch = function(self, opts)\n opts = opts or {}\n local mode = opts.mode or 420\n\n local resolved = self:resolve { strict = false }\n if resolved:exists() then\n local new_time = os.time()\n vim.uv.fs_utime(resolved.filename, new_time, new_time)\n return\n end\n\n local parent = resolved:parent()\n if parent and not parent:exists() then\n error(\"FileNotFoundError: \" .. parent.filename)\n end\n\n local fd, err_name, err_msg = vim.uv.fs_open(resolved.filename, \"w\", mode)\n if not fd then\n error(err_name .. \": \" .. err_msg)\n end\n vim.uv.fs_close(fd)\nend\n\n--- Rename this file or directory to the given target.\n---\n---@param target obsidian.Path|string\n---\n---@return obsidian.Path\nPath.rename = function(self, target)\n local resolved = self:resolve { strict = false }\n target = Path.new(target)\n\n local ok, err_name, err_msg = vim.uv.fs_rename(resolved.filename, target.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\n\n return target\nend\n\n--- Remove the file.\n---\n---@param opts { missing_ok: boolean|? }|?\nPath.unlink = function(self, opts)\n opts = opts or {}\n\n local resolved = self:resolve { strict = false }\n\n if not resolved:exists() then\n if not opts.missing_ok then\n error(\"FileNotFoundError: \" .. resolved.filename)\n end\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_unlink(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n--- Make a path relative to the vault root, if possible, return a string\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return string?\nPath.vault_relative_path = function(self, opts)\n opts = opts or {}\n\n -- NOTE: we don't try to resolve the `path` here because that would make the path absolute,\n -- which may result in the wrong relative path if the current working directory is not within\n -- the vault.\n\n local ok, relative_path = pcall(function()\n return self:relative_to(Obsidian.workspace.root)\n end)\n\n if ok and relative_path then\n return tostring(relative_path)\n elseif not self:is_absolute() then\n return tostring(self)\n elseif opts.strict then\n error(string.format(\"failed to resolve '%s' relative to vault root '%s'\", self, Obsidian.workspace.root))\n end\nend\n\nreturn Path\n"], ["/obsidian.nvim/minimal.lua", "vim.env.LAZY_STDPATH = \".repro\"\nload(vim.fn.system \"curl -s https://raw.githubusercontent.com/folke/lazy.nvim/main/bootstrap.lua\")()\n\nvim.fn.mkdir(\".repro/vault\", \"p\")\n\nvim.o.conceallevel = 2\n\nlocal plugins = {\n {\n \"obsidian-nvim/obsidian.nvim\",\n dependencies = { \"nvim-lua/plenary.nvim\" },\n opts = {\n completion = {\n blink = true,\n nvim_cmp = false,\n },\n workspaces = {\n {\n name = \"test\",\n path = vim.fs.joinpath(vim.uv.cwd(), \".repro\", \"vault\"),\n },\n },\n },\n },\n\n -- **Choose your renderer**\n -- { \"MeanderingProgrammer/render-markdown.nvim\", dependencies = { \"echasnovski/mini.icons\" }, opts = {} },\n -- { \"OXY2DEV/markview.nvim\", lazy = false },\n\n -- **Choose your picker**\n -- \"nvim-telescope/telescope.nvim\",\n -- \"folke/snacks.nvim\",\n -- \"ibhagwan/fzf-lua\",\n -- \"echasnovski/mini.pick\",\n\n -- **Choose your completion engine**\n -- {\n -- \"hrsh7th/nvim-cmp\",\n -- config = function()\n -- local cmp = require \"cmp\"\n -- cmp.setup {\n -- mapping = cmp.mapping.preset.insert {\n -- [\"\"] = cmp.mapping.abort(),\n -- [\"\"] = cmp.mapping.confirm { select = true },\n -- },\n -- }\n -- end,\n -- },\n -- {\n -- \"saghen/blink.cmp\",\n -- opts = {\n -- fuzzy = { implementation = \"lua\" }, -- no need to build binary\n -- keymap = {\n -- preset = \"default\",\n -- },\n -- },\n -- },\n}\n\nrequire(\"lazy.minit\").repro { spec = plugins }\n\nvim.cmd \"checkhealth obsidian\"\n"], ["/obsidian.nvim/lua/obsidian/commands/today.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_days = 0\n local arg = string.gsub(data.args, \" \", \"\")\n if string.len(arg) > 0 then\n local offset = tonumber(arg)\n if offset == nil then\n log.err \"Invalid argument, expected an integer offset\"\n return\n else\n offset_days = offset\n end\n end\n local note = require(\"obsidian.daily\").daily(offset_days, {})\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/refs.lua", "local util = require \"obsidian.util\"\n\nlocal M = {}\n\n---@enum obsidian.completion.RefType\nM.RefType = {\n Wiki = 1,\n Markdown = 2,\n}\n\n---Backtrack through a string to find the first occurrence of '[['.\n---\n---@param input string\n---@return string|?, string|?, obsidian.completion.RefType|?\nlocal find_search_start = function(input)\n for i = string.len(input), 1, -1 do\n local substr = string.sub(input, i)\n if vim.startswith(substr, \"]\") or vim.endswith(substr, \"]\") then\n return nil\n elseif vim.startswith(substr, \"[[\") then\n return substr, string.sub(substr, 3)\n elseif vim.startswith(substr, \"[\") and string.sub(input, i - 1, i - 1) ~= \"[\" then\n return substr, string.sub(substr, 2)\n end\n end\n return nil\nend\n\n---Check if a completion request can/should be carried out. Returns a boolean\n---and, if true, the search string and the column indices of where the completion\n---items should be inserted.\n---\n---@return boolean, string|?, integer|?, integer|?, obsidian.completion.RefType|?\nM.can_complete = function(request)\n local input, search = find_search_start(request.context.cursor_before_line)\n if input == nil or search == nil then\n return false\n elseif string.len(search) == 0 or util.is_whitespace(search) then\n return false\n end\n\n if vim.startswith(input, \"[[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 2)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]]\" and 1 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Wiki\n elseif vim.startswith(input, \"[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 1)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]\" and 0 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Markdown\n else\n return false\n end\nend\n\nM.get_trigger_characters = function()\n return { \"[\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n return [=[\\%(^\\|[^\\[]\\)\\zs\\[\\{1,2}[^\\]]\\+\\]\\{,2}]=]\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/abc.lua", "local M = {}\n\n---@class obsidian.ABC\n---@field init function an init function which essentially calls 'setmetatable({}, mt)'.\n---@field as_tbl function get a raw table with only the instance's fields\n---@field mt table the metatable\n\n---Create a new class.\n---\n---This handles the boilerplate of setting up metatables correctly and consistently when defining new classes,\n---and comes with some better default metamethods, like '.__eq' which will recursively compare all fields\n---that don't start with a double underscore.\n---\n---When you use this you should call `.init()` within your constructors instead of `setmetatable()`.\n---For example:\n---\n---```lua\n--- local Foo = new_class()\n---\n--- Foo.new = function(x)\n--- local self = Foo.init()\n--- self.x = x\n--- return self\n--- end\n---```\n---\n---The metatable for classes created this way is accessed with the field `.mt`. This way you can easily\n---add/override metamethods to your classes. Continuing the example above:\n---\n---```lua\n--- Foo.mt.__tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end\n---\n--- local foo = Foo.new(1)\n--- print(foo)\n---```\n---\n---Alternatively you can pass metamethods directly to 'new_class()'. For example:\n---\n---```lua\n--- local Foo = new_class {\n--- __tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end,\n--- }\n---```\n---\n---@param metamethods table|? {string, function} - Metamethods\n---@param base_class table|? A base class to start from\n---@return obsidian.ABC\nM.new_class = function(metamethods, base_class)\n local class = base_class and base_class or {}\n\n -- Metatable for the class so that all instances have the same metatable.\n class.mt = vim.tbl_extend(\"force\", {\n __index = class,\n __eq = function(a, b)\n -- In order to use 'vim.deep_equal' we need to pull out the raw fields first.\n -- If we passed 'a' and 'b' directly to 'vim.deep_equal' we'd get a stack overflow due\n -- to infinite recursion, since 'vim.deep_equal' calls the '.__eq' metamethod.\n local a_fields = a:as_tbl()\n local b_fields = b:as_tbl()\n return vim.deep_equal(a_fields, b_fields)\n end,\n }, metamethods and metamethods or {})\n\n class.init = function(t)\n local self = setmetatable(t and t or {}, class.mt)\n return self\n end\n\n class.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\n end\n\n return class\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/yaml/init.lua", "local util = require \"obsidian.util\"\nlocal parser = require \"obsidian.yaml.parser\"\n\nlocal yaml = {}\n\n---Deserialize a YAML string.\n---@param str string\n---@return any\nyaml.loads = function(str)\n return parser.loads(str)\nend\n\n---@param s string\n---@return boolean\nlocal should_quote = function(s)\n -- TODO: this probably doesn't cover all edge cases.\n -- See https://www.yaml.info/learn/quote.html\n -- Check if it starts with a special character.\n if string.match(s, [[^[\"'\\\\[{&!-].*]]) then\n return true\n -- Check if it has a colon followed by whitespace.\n elseif string.find(s, \": \", 1, true) then\n return true\n -- Check if it's an empty string.\n elseif s == \"\" or string.match(s, \"^[%s]+$\") then\n return true\n else\n return false\n end\nend\n\n---@return string[]\nlocal dumps\ndumps = function(x, indent, order)\n local indent_str = string.rep(\" \", indent)\n\n if type(x) == \"string\" then\n if should_quote(x) then\n x = string.gsub(x, '\"', '\\\\\"')\n return { indent_str .. [[\"]] .. x .. [[\"]] }\n else\n return { indent_str .. x }\n end\n end\n\n if type(x) == \"boolean\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"number\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"table\" then\n local out = {}\n\n if util.islist(x) then\n for _, v in ipairs(x) do\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. \"- \" .. util.lstrip_whitespace(item_lines[1]))\n for i = 2, #item_lines do\n table.insert(out, item_lines[i])\n end\n end\n else\n -- Gather and sort keys so we can keep the order deterministic.\n local keys = {}\n for k, _ in pairs(x) do\n table.insert(keys, k)\n end\n table.sort(keys, order)\n for _, k in ipairs(keys) do\n local v = x[k]\n if type(v) == \"string\" or type(v) == \"boolean\" or type(v) == \"number\" then\n table.insert(out, indent_str .. tostring(k) .. \": \" .. dumps(v, 0)[1])\n elseif type(v) == \"table\" and vim.tbl_isempty(v) then\n table.insert(out, indent_str .. tostring(k) .. \": []\")\n else\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. tostring(k) .. \":\")\n for _, line in ipairs(item_lines) do\n table.insert(out, line)\n end\n end\n end\n end\n\n return out\n end\n\n error(\"Can't convert object with type \" .. type(x) .. \" to YAML\")\nend\n\n---Dump an object to YAML lines.\n---@param x any\n---@param order function\n---@return string[]\nyaml.dumps_lines = function(x, order)\n return dumps(x, 0, order)\nend\n\n---Dump an object to a YAML string.\n---@param x any\n---@param order function|?\n---@return string\nyaml.dumps = function(x, order)\n return table.concat(dumps(x, 0, order), \"\\n\")\nend\n\nreturn yaml\n"], ["/obsidian.nvim/lua/obsidian/builtin.lua", "---builtin functions that are default values for config options\nlocal M = {}\nlocal util = require \"obsidian.util\"\n\n---Create a new unique Zettel ID.\n---\n---@return string\nM.zettel_id = function()\n local suffix = \"\"\n for _ = 1, 4 do\n suffix = suffix .. string.char(math.random(65, 90))\n end\n return tostring(os.time()) .. \"-\" .. suffix\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_alias_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = string.format(\"#%s\", opts.anchor.header)\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.label, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = opts.anchor.anchor\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.path, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.label ~= opts.path then\n return string.format(\"[[%s%s|%s%s]]\", opts.path, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.path, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_id_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.id == nil then\n return string.format(\"[[%s%s]]\", opts.label, anchor)\n elseif opts.label ~= opts.id then\n return string.format(\"[[%s%s|%s%s]]\", opts.id, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.id, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.markdown_link = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n local path = util.urlencode(opts.path, { keep_path_sep = true })\n return string.format(\"[%s%s](%s%s)\", opts.label, header, path, anchor)\nend\n\n---@param path string\n---@return string\nM.img_text_func = function(path)\n local format_string = {\n markdown = \"![](%s)\",\n wiki = \"![[%s]]\",\n }\n local style = Obsidian.opts.preferred_link_style\n local name = vim.fs.basename(tostring(path))\n\n if style == \"markdown\" then\n name = require(\"obsidian.util\").urlencode(name)\n end\n\n return string.format(format_string[style], name)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/yaml/line.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\n\n---@class obsidian.yaml.Line : obsidian.ABC\n---@field content string\n---@field raw_content string\n---@field indent integer\nlocal Line = abc.new_class {\n __tostring = function(self)\n return string.format(\"Line('%s')\", self.raw_content)\n end,\n}\n\n---Create a new Line instance from a raw line string.\n---@param raw_line string\n---@param base_indent integer|?\n---@return obsidian.yaml.Line\nLine.new = function(raw_line, base_indent)\n local self = Line.init()\n self.indent = util.count_indent(raw_line)\n if base_indent ~= nil then\n if base_indent > self.indent then\n error \"relative indentation for line is less than base indentation\"\n end\n self.indent = self.indent - base_indent\n end\n self.raw_content = util.lstrip_whitespace(raw_line, base_indent)\n self.content = vim.trim(self.raw_content)\n return self\nend\n\n---Check if a line is empty.\n---@param self obsidian.yaml.Line\n---@return boolean\nLine.is_empty = function(self)\n if util.strip_comments(self.content) == \"\" then\n return true\n else\n return false\n end\nend\n\nreturn Line\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/nvim_cmp.lua", "local M = {}\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_sources(opts)\n local cmp = require \"cmp\"\n\n cmp.register_source(\"obsidian\", require(\"obsidian.completion.sources.nvim_cmp.refs\").new())\n cmp.register_source(\"obsidian_tags\", require(\"obsidian.completion.sources.nvim_cmp.tags\").new())\n if opts.completion.create_new then\n cmp.register_source(\"obsidian_new\", require(\"obsidian.completion.sources.nvim_cmp.new\").new())\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace and configures nvim_cmp sources for the current buffer.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n local cmp = require \"cmp\"\n\n local sources = {\n { name = \"obsidian\" },\n { name = \"obsidian_tags\" },\n }\n if opts.completion.create_new then\n table.insert(sources, { name = \"obsidian_new\" })\n end\n for _, source in pairs(cmp.get_config().sources) do\n if source.name ~= \"obsidian\" and source.name ~= \"obsidian_new\" and source.name ~= \"obsidian_tags\" then\n table.insert(sources, source)\n end\n end\n ---@diagnostic disable-next-line: missing-fields\n cmp.setup.buffer { sources = sources }\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/toggle_checkbox.lua", "local toggle_checkbox = require(\"obsidian.api\").toggle_checkbox\n\n---@param data CommandArgs\nreturn function(_, data)\n local start_line, end_line\n local checkboxes = Obsidian.opts.checkbox.order\n start_line = data.line1\n end_line = data.line2\n\n local buf = vim.api.nvim_get_current_buf()\n\n for line_nb = start_line, end_line do\n local current_line = vim.api.nvim_buf_get_lines(buf, line_nb - 1, line_nb, false)[1]\n if current_line and current_line:match \"%S\" then\n toggle_checkbox(checkboxes, line_nb)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.new = function()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\nNewNoteSource.get_keyword_pattern = completion.get_keyword_pattern\n\nNewNoteSource.incomplete_response = nvim_cmp_util.incomplete_response\nNewNoteSource.complete_response = nvim_cmp_util.complete_response\n\n---Invoke completion (required).\n---@param request cmp.SourceCompletionApiParams\n---@param callback fun(response: lsp.CompletionResponse|nil)\nfunction NewNoteSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\n---Creates a new note using the default template for the completion item.\n---Executed after the item was selected.\n---@param completion_item lsp.CompletionItem\n---@param callback fun(completion_item: lsp.CompletionItem|nil)\nfunction NewNoteSource:execute(completion_item, callback)\n return callback(self:process_execute(completion_item))\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/util.lua", "local M = {}\n\n---Generates the completion request from a blink context\n---@param context blink.cmp.Context\n---@return obsidian.completion.sources.base.Request\nM.generate_completion_request_from_editor_state = function(context)\n local row = context.cursor[1]\n local col = context.cursor[2] + 1\n local cursor_before_line = context.line:sub(1, col - 1)\n local cursor_after_line = context.line:sub(col)\n\n return {\n context = {\n bufnr = context.bufnr,\n cursor_before_line = cursor_before_line,\n cursor_after_line = cursor_after_line,\n cursor = {\n row = row,\n col = col,\n line = row + 1,\n },\n },\n }\nend\n\nM.incomplete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = true,\n items = {},\n}\n\nM.complete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = false,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/compat.lua", "local compat = {}\n\nlocal has_nvim_0_11 = false\nif vim.fn.has \"nvim-0.11\" == 1 then\n has_nvim_0_11 = true\nend\n\ncompat.is_list = function(t)\n if has_nvim_0_11 then\n return vim.islist(t)\n else\n return vim.tbl_islist(t)\n end\nend\n\ncompat.flatten = function(t)\n if has_nvim_0_11 then\n ---@diagnostic disable-next-line: undefined-field\n return vim.iter(t):flatten():totable()\n else\n return vim.tbl_flatten(t)\n end\nend\n\nreturn compat\n"], ["/obsidian.nvim/after/ftplugin/markdown.lua", "local obsidian = require \"obsidian\"\nlocal buf = vim.api.nvim_get_current_buf()\nlocal buf_dir = vim.fs.dirname(vim.api.nvim_buf_get_name(buf))\n\nlocal workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\nif not workspace then\n return -- if not in any workspace.\nend\n\nlocal win = vim.api.nvim_get_current_win()\n\nvim.treesitter.start(buf, \"markdown\") -- for when user don't use nvim-treesitter\nvim.wo[win].foldmethod = \"expr\"\nvim.wo[win].foldexpr = \"v:lua.vim.treesitter.foldexpr()\"\nvim.wo[win].foldlevel = 99\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.nvim_cmp.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.new = function()\n return RefsSource.init(RefsSourceBase)\nend\n\nRefsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nRefsSource.incomplete_response = nvim_cmp_util.incomplete_response\nRefsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction RefsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.new = function()\n return TagsSource.init(TagsSourceBase)\nend\n\nTagsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nTagsSource.incomplete_response = nvim_cmp_util.incomplete_response\nTagsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction TagsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.incomplete_response = blink_util.incomplete_response\nNewNoteSource.complete_response = blink_util.complete_response\n\nfunction NewNoteSource.new()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction NewNoteSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\n---Implements the execute method of the completion provider\n---@param _ blink.cmp.Context\n---@param item blink.cmp.CompletionItem\n---@param callback fun(),\n---@param default_implementation fun(context?: blink.cmp.Context, item?: blink.cmp.CompletionItem)): ((fun(): nil) | nil)\nfunction NewNoteSource:execute(_, item, callback, default_implementation)\n self:process_execute(item)\n default_implementation() -- Ensure completion is still executed\n callback() -- Required (as per blink documentation)\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/types.lua", "-- Useful type definitions go here.\n\n---@class CommandArgs\n---The table passed to user commands.\n---For details see `:help nvim_create_user_command()` and the command attribute docs\n---\n---@field name string Command name\n---@field args string The args passed to the command, if any \n---@field fargs table The args split by unescaped whitespace (when more than one argument is allowed), if any \n---@field nargs string Number of arguments |:command-nargs|\n---@field bang boolean \"true\" if the command was executed with a ! modifier \n---@field line1 number The starting line of the command range \n---@field line2 number The final line of the command range \n---@field range number The number of items in the command range: 0, 1, or 2 \n---@field count number Any count supplied \n---@field reg string The optional register, if specified \n---@field mods string Command modifiers, if any \n---@field smods table Command modifiers in a structured format. Has the same structure as the \"mods\" key of\n---@field raw_print boolean HACK: for debug command and info\n\n---@class obsidian.InsertTemplateContext\n---The table passed to user substitution functions when inserting templates into a buffer.\n---\n---@field type \"insert_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field location [number, number, number, number] `{ buf, win, row, col }` location from which the request was made.\n---@field partial_note? obsidian.Note An optional note with fields to copy from.\n\n---@class obsidian.CloneTemplateContext\n---The table passed to user substitution functions when cloning template files to create new notes.\n---\n---@field type \"clone_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field destination_path obsidian.Path The path the cloned template will be written to.\n---@field partial_note obsidian.Note The note being written.\n\n---@alias obsidian.TemplateContext obsidian.InsertTemplateContext | obsidian.CloneTemplateContext\n---The table passed to user substitution functions. Use `ctx.type` to distinguish between the different kinds.\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.blink.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.incomplete_response = blink_util.incomplete_response\nRefsSource.complete_response = blink_util.complete_response\n\nfunction RefsSource.new()\n return RefsSource.init(RefsSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction RefsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.incomplete_response = blink_util.incomplete_response\nTagsSource.complete_response = blink_util.complete_response\n\nfunction TagsSource.new()\n return TagsSource.init(TagsSourceBase)\nend\n\n---Implements the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction TagsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/yaml/yq.lua", "local m = {}\n\n---@param str string\n---@return any\nm.loads = function(str)\n local as_json = vim.fn.system(\"yq -o=json\", str)\n local data = vim.json.decode(as_json, { luanil = { object = true, array = true } })\n return data\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/commands/tomorrow.lua", "return function()\n local note = require(\"obsidian.daily\").tomorrow()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/yesterday.lua", "return function()\n local note = require(\"obsidian.daily\").yesterday()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/init.lua", "local M = {\n refs = require \"obsidian.completion.refs\",\n tags = require \"obsidian.completion.tags\",\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/util.lua", "local M = {}\n\nM.incomplete_response = { isIncomplete = true }\n\nM.complete_response = {\n isIncomplete = true,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/version.lua", "return \"3.12.0\"\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/types.lua", "---@class obsidian.completion.sources.base.Request.Context.Position\n---@field public col integer\n---@field public row integer\n\n---A request context class that partially matches cmp.Context to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request.Context\n---@field public bufnr integer\n---@field public cursor obsidian.completion.sources.base.Request.Context.Position|lsp.Position\n---@field public cursor_after_line string\n---@field public cursor_before_line string\n\n---A request class that partially matches cmp.Request to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request\n---@field public context obsidian.completion.sources.base.Request.Context\n"]], "task_instance_info": {"created_time": "2025-08-21 00:50:03", "created_task_model": "DeepSeek-R1", "function_skeleton": "function (entries) end", "code_description": "This code segment functions to: Process a collection of items by extracting specific attributes, present them in an interactive selection interface, and trigger navigation actions based on user choices."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nfunction(entries)\n picker:find(entries)\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-50-19"}, "editdistance_info": {"edit_distance": 12.7273, "calculate_time": "2025-08-21 00:50:19", "true_code_clean": "function(entries)\n entries = vim.tbl_map(function(match)\n return match.link\n end, entries)\n picker:pick(entries, {\n prompt_title = \"Links\",\n callback = function(link)\n api.follow_link(link)\n end,\n })\n end", "predict_code_clean": "function(entries)\n picker:find(entries)\nend"}} {"repo_name": "obsidian.nvim", "file_name": "/obsidian.nvim/lua/obsidian/img_paste.lua", "inference_info": {"prefix_code": "local Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal run_job = require(\"obsidian.async\").run_job\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\n\nlocal M = {}\n\n-- Image pasting adapted from https://github.com/ekickx/clipboard-image.nvim\n\n---@return string\nlocal function get_clip_check_command()\n local check_cmd\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n check_cmd = \"xclip -selection clipboard -o -t TARGETS\"\n elseif display_server == \"wayland\" then\n check_cmd = \"wl-paste --list-types\"\n end\n elseif this_os == api.OSType.Darwin then\n check_cmd = \"pngpaste -b 2>&1\"\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n check_cmd = 'powershell.exe \"Get-Clipboard -Format Image\"'\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return check_cmd\nend\n\n--- Check if clipboard contains image data.\n---\n---@return boolean\n", "suffix_code": "\n\n--- TODO: refactor with run_job?\n\n--- Save image from clipboard to `path`.\n---@param path string\n---\n---@return boolean|integer|? result\nlocal function save_clipboard_image(path)\n local this_os = api.get_os()\n\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local cmd\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n cmd = string.format(\"xclip -selection clipboard -t image/png -o > '%s'\", path)\n elseif display_server == \"wayland\" then\n cmd = string.format(\"wl-paste --no-newline --type image/png > %s\", vim.fn.shellescape(path))\n return run_job { \"bash\", \"-c\", cmd }\n end\n\n local result = os.execute(cmd)\n if type(result) == \"number\" and result > 0 then\n return false\n else\n return result\n end\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n local cmd = 'powershell.exe -c \"'\n .. string.format(\"(get-clipboard -format image).save('%s', 'png')\", string.gsub(path, \"/\", \"\\\\\"))\n .. '\"'\n return os.execute(cmd)\n elseif this_os == api.OSType.Darwin then\n return run_job { \"pngpaste\", path }\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\nend\n\n--- @param path string image_path The absolute path to the image file.\nM.paste = function(path)\n if util.contains_invalid_characters(path) then\n log.warn \"Links will not work with file names containing any of these characters in Obsidian: # ^ [ ] |\"\n end\n\n ---@diagnostic disable-next-line: cast-local-type\n path = Path.new(path)\n\n -- Make sure fname ends with \".png\"\n if not path.suffix then\n ---@diagnostic disable-next-line: cast-local-type\n path = path:with_suffix \".png\"\n elseif path.suffix ~= \".png\" then\n return log.err(\"invalid suffix for image name '%s', must be '.png'\", path.suffix)\n end\n\n if Obsidian.opts.attachments.confirm_img_paste then\n -- Get confirmation from user.\n if not api.confirm(\"Saving image to '\" .. tostring(path) .. \"'. Do you want to continue?\") then\n return log.warn \"Paste aborted\"\n end\n end\n\n -- Ensure parent directory exists.\n assert(path:parent()):mkdir { exist_ok = true, parents = true }\n\n -- Paste image.\n local result = save_clipboard_image(tostring(path))\n if result == false then\n log.err \"Failed to save image\"\n return\n end\n\n local img_text = Obsidian.opts.attachments.img_text_func(path)\n vim.api.nvim_put({ img_text }, \"c\", true, false)\nend\n\nreturn M\n", "middle_code": "function M.clipboard_is_img()\n local check_cmd = get_clip_check_command()\n local result_string = vim.fn.system(check_cmd)\n local content = vim.split(result_string, \"\\n\")\n local is_img = false\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n if vim.tbl_contains(content, \"image/png\") then\n is_img = true\n elseif vim.tbl_contains(content, \"text/uri-list\") then\n local success =\n os.execute \"wl-paste \n is_img = success == 0\n end\n elseif this_os == api.OSType.Darwin then\n is_img = string.sub(content[1], 1, 9) == \"iVBORw0KG\" \n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n is_img = content ~= nil\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return is_img\nend", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/obsidian.nvim/lua/obsidian/api.lua", "local M = {}\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal iter, string, table = vim.iter, string, table\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\n\n---@param dir string | obsidian.Path\n---@return Iter\nM.dir = function(dir)\n dir = tostring(dir)\n local dir_opts = {\n depth = 10,\n skip = function(p)\n return not vim.startswith(p, \".\") and p ~= vim.fs.basename(tostring(M.templates_dir()))\n end,\n follow = true,\n }\n\n return vim\n .iter(vim.fs.dir(dir, dir_opts))\n :filter(function(path)\n return vim.endswith(path, \".md\")\n end)\n :map(function(path)\n return vim.fs.joinpath(dir, path)\n end)\nend\n\n--- Get the templates folder.\n---\n---@return obsidian.Path|?\nM.templates_dir = function(workspace)\n local opts = Obsidian.opts\n\n local Workspace = require \"obsidian.workspace\"\n\n if workspace and workspace ~= Obsidian.workspace then\n opts = Workspace.normalize_opts(workspace)\n end\n\n if opts.templates == nil or opts.templates.folder == nil then\n return nil\n end\n\n local paths_to_check = { Obsidian.workspace.root / opts.templates.folder, Path.new(opts.templates.folder) }\n for _, path in ipairs(paths_to_check) do\n if path:is_dir() then\n return path\n end\n end\n\n log.err_once(\"'%s' is not a valid templates directory\", opts.templates.folder)\n return nil\nend\n\n--- Check if a path represents a note in the workspace.\n---\n---@param path string|obsidian.Path\n---@param workspace obsidian.Workspace|?\n---\n---@return boolean\nM.path_is_note = function(path, workspace)\n path = Path.new(path):resolve()\n workspace = workspace or Obsidian.workspace\n\n local in_vault = path.filename:find(vim.pesc(tostring(workspace.root))) ~= nil\n if not in_vault then\n return false\n end\n\n -- Notes have to be markdown file.\n if path.suffix ~= \".md\" then\n return false\n end\n\n -- Ignore markdown files in the templates directory.\n local templates_dir = M.templates_dir(workspace)\n if templates_dir ~= nil then\n if templates_dir:is_parent_of(path) then\n return false\n end\n end\n\n return true\nend\n\n--- Get the current note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note|?\n---@diagnostic disable-next-line: unused-local\nM.current_note = function(bufnr, opts)\n bufnr = bufnr or 0\n local Note = require \"obsidian.note\"\n if not M.path_is_note(vim.api.nvim_buf_get_name(bufnr)) then\n return nil\n end\n\n opts = opts or {}\n if not opts.max_lines then\n opts.max_lines = Obsidian.opts.search_max_lines\n end\n return Note.from_buffer(bufnr, opts)\nend\n\n---builtin functions that are impure, interacts with editor state, like vim.api\n\n---Toggle the checkbox on the current line.\n---\n---@param states table|nil Optional table containing checkbox states (e.g., {\" \", \"x\"}).\n---@param line_num number|nil Optional line number to toggle the checkbox on. Defaults to the current line.\nM.toggle_checkbox = function(states, line_num)\n if not util.in_node { \"list\", \"paragraph\" } or util.in_node \"block_quote\" then\n return\n end\n line_num = line_num or unpack(vim.api.nvim_win_get_cursor(0))\n local line = vim.api.nvim_buf_get_lines(0, line_num - 1, line_num, false)[1]\n\n local checkboxes = states or { \" \", \"x\" }\n\n if util.is_checkbox(line) then\n for i, check_char in ipairs(checkboxes) do\n if string.match(line, \"^.* %[\" .. vim.pesc(check_char) .. \"%].*\") then\n i = i % #checkboxes\n line = string.gsub(line, vim.pesc(\"[\" .. check_char .. \"]\"), \"[\" .. checkboxes[i + 1] .. \"]\", 1)\n break\n end\n end\n elseif Obsidian.opts.checkbox.create_new then\n local unordered_list_pattern = \"^(%s*)[-*+] (.*)\"\n if string.match(line, unordered_list_pattern) then\n line = string.gsub(line, unordered_list_pattern, \"%1- [ ] %2\")\n else\n line = string.gsub(line, \"^(%s*)\", \"%1- [ ] \")\n end\n else\n goto out\n end\n\n vim.api.nvim_buf_set_lines(0, line_num - 1, line_num, true, { line })\n ::out::\nend\n\n---@return [number, number, number, number] tuple containing { buf, win, row, col }\nM.get_active_window_cursor_location = function()\n local buf = vim.api.nvim_win_get_buf(0)\n local win = vim.api.nvim_get_current_win()\n local row, col = unpack(vim.api.nvim_win_get_cursor(win))\n local location = { buf, win, row, col }\n return location\nend\n\n--- Create a formatted markdown / wiki link for a note.\n---\n---@param note obsidian.Note|obsidian.Path|string The note/path to link to.\n---@param opts { label: string|?, link_style: obsidian.config.LinkStyle|?, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|? Options.\n---\n---@return string\nM.format_link = function(note, opts)\n local config = require \"obsidian.config\"\n opts = opts or {}\n\n ---@type string, string, string|integer|?\n local rel_path, label, note_id\n if type(note) == \"string\" or Path.is_path_obj(note) then\n ---@cast note string|obsidian.Path\n -- rel_path = tostring(self:vault_relative_path(note, { strict = true }))\n rel_path = assert(Path.new(note):vault_relative_path { strict = true })\n label = opts.label or tostring(note)\n note_id = opts.id\n else\n ---@cast note obsidian.Note\n -- rel_path = tostring(self:vault_relative_path(note.path, { strict = true }))\n rel_path = assert(note.path:vault_relative_path { strict = true })\n label = opts.label or note:display_name()\n note_id = opts.id or note.id\n end\n\n local link_style = opts.link_style\n if link_style == nil then\n link_style = Obsidian.opts.preferred_link_style\n end\n\n local new_opts = { path = rel_path, label = label, id = note_id, anchor = opts.anchor, block = opts.block }\n\n if link_style == config.LinkStyle.markdown then\n return Obsidian.opts.markdown_link_func(new_opts)\n elseif link_style == config.LinkStyle.wiki or link_style == nil then\n return Obsidian.opts.wiki_link_func(new_opts)\n else\n error(string.format(\"Invalid link style '%s'\", link_style))\n end\nend\n\n---Return the full link under cursror\n---\n---@return string? link\n---@return obsidian.search.RefTypes? link_type\nM.cursor_link = function()\n local line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- 0-indexed column to 1-indexed lua string position\n\n local refs = search.find_refs(line, { include_naked_urls = true, include_file_urls = true, include_block_ids = true })\n\n local match = iter(refs):find(function(match)\n local open, close = unpack(match)\n return cur_col >= open and cur_col <= close\n end)\n if match then\n return line:sub(match[1], match[2]), match[3]\n end\nend\n\n---Get the tag under the cursor, if there is one.\n---@return string?\nM.cursor_tag = function()\n local current_line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- nvim_win_get_cursor returns 0-indexed column\n\n for match in iter(search.find_tags(current_line)) do\n local open, close, _ = unpack(match)\n if open <= cur_col and cur_col <= close then\n return string.sub(current_line, open + 1, close)\n end\n end\n\n return nil\nend\n\n--- Get the heading under the cursor, if there is one.\n---@return { header: string, level: integer, anchor: string }|?\nM.cursor_heading = function()\n return util.parse_header(vim.api.nvim_get_current_line())\nend\n\n------------------\n--- buffer api ---\n------------------\n\n--- Check if a buffer is empty.\n---\n---@param bufnr integer|?\n---\n---@return boolean\nM.buffer_is_empty = function(bufnr)\n bufnr = bufnr or 0\n if vim.api.nvim_buf_line_count(bufnr) > 1 then\n return false\n else\n local first_text = vim.api.nvim_buf_get_text(bufnr, 0, 0, 0, 0, {})\n if vim.tbl_isempty(first_text) or first_text[1] == \"\" then\n return true\n else\n return false\n end\n end\nend\n\n--- Open a buffer for the corresponding path.\n---\n---@param path string|obsidian.Path\n---@param opts { line: integer|?, col: integer|?, cmd: string|? }|?\n---@return integer bufnr\nM.open_buffer = function(path, opts)\n path = Path.new(path):resolve()\n opts = opts and opts or {}\n local cmd = vim.trim(opts.cmd and opts.cmd or \"e\")\n\n ---@type integer|?\n local result_bufnr\n\n -- Check for buffer in windows and use 'drop' command if one is found.\n for _, winnr in ipairs(vim.api.nvim_list_wins()) do\n local bufnr = vim.api.nvim_win_get_buf(winnr)\n local bufname = vim.api.nvim_buf_get_name(bufnr)\n if bufname == tostring(path) then\n cmd = \"drop\"\n result_bufnr = bufnr\n break\n end\n end\n\n vim.cmd(string.format(\"%s %s\", cmd, vim.fn.fnameescape(tostring(path))))\n if opts.line then\n vim.api.nvim_win_set_cursor(0, { tonumber(opts.line), opts.col and opts.col or 0 })\n end\n\n if not result_bufnr then\n result_bufnr = vim.api.nvim_get_current_buf()\n end\n\n return result_bufnr\nend\n\n---Get an iterator of (bufnr, bufname) over all named buffers. The buffer names will be absolute paths.\n---\n---@return function () -> (integer, string)|?\nM.get_named_buffers = function()\n local idx = 0\n local buffers = vim.api.nvim_list_bufs()\n\n ---@return integer|?\n ---@return string|?\n return function()\n while idx < #buffers do\n idx = idx + 1\n local bufnr = buffers[idx]\n if vim.api.nvim_buf_is_loaded(bufnr) then\n return bufnr, vim.api.nvim_buf_get_name(bufnr)\n end\n end\n end\nend\n\n----------------\n--- text api ---\n----------------\n\n--- Get the current visual selection of text and exit visual mode.\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return { lines: string[], selection: string, csrow: integer, cscol: integer, cerow: integer, cecol: integer }|?\nM.get_visual_selection = function(opts)\n opts = opts or {}\n -- Adapted from fzf-lua:\n -- https://github.com/ibhagwan/fzf-lua/blob/6ee73fdf2a79bbd74ec56d980262e29993b46f2b/lua/fzf-lua/utils.lua#L434-L466\n -- this will exit visual mode\n -- use 'gv' to reselect the text\n local _, csrow, cscol, cerow, cecol\n local mode = vim.fn.mode()\n if opts.strict and not vim.endswith(string.lower(mode), \"v\") then\n return\n end\n\n if mode == \"v\" or mode == \"V\" or mode == \"\u0016\" then\n -- if we are in visual mode use the live position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \".\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"v\")\n if mode == \"V\" then\n -- visual line doesn't provide columns\n cscol, cecol = 0, 999\n end\n -- exit visual mode\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", true)\n else\n -- otherwise, use the last known visual position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \"'<\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"'>\")\n end\n\n -- Swap vars if needed\n if cerow < csrow then\n csrow, cerow = cerow, csrow\n cscol, cecol = cecol, cscol\n elseif cerow == csrow and cecol < cscol then\n cscol, cecol = cecol, cscol\n end\n\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n if vim.tbl_isempty(lines) then\n return\n end\n\n -- When the whole line is selected via visual line mode (\"V\"), cscol / cecol will be equal to \"v:maxcol\"\n -- for some odd reason. So change that to what they should be here. See ':h getpos' for more info.\n local maxcol = vim.api.nvim_get_vvar \"maxcol\"\n if cscol == maxcol then\n cscol = string.len(lines[1])\n end\n if cecol == maxcol then\n cecol = string.len(lines[#lines])\n end\n\n ---@type string\n local selection\n local n = #lines\n if n <= 0 then\n selection = \"\"\n elseif n == 1 then\n selection = string.sub(lines[1], cscol, cecol)\n elseif n == 2 then\n selection = string.sub(lines[1], cscol) .. \"\\n\" .. string.sub(lines[n], 1, cecol)\n else\n selection = string.sub(lines[1], cscol)\n .. \"\\n\"\n .. table.concat(lines, \"\\n\", 2, n - 1)\n .. \"\\n\"\n .. string.sub(lines[n], 1, cecol)\n end\n\n return {\n lines = lines,\n selection = selection,\n csrow = csrow,\n cscol = cscol,\n cerow = cerow,\n cecol = cecol,\n }\nend\n\n------------------\n--- UI helpers ---\n------------------\n\n---Get the strategy for opening notes\n---\n---@param opt obsidian.config.OpenStrategy\n---@return string\nM.get_open_strategy = function(opt)\n local OpenStrategy = require(\"obsidian.config\").OpenStrategy\n\n -- either 'leaf', 'row' for vertically split windows, or 'col' for horizontally split windows\n local cur_layout = vim.fn.winlayout()[1]\n\n if vim.startswith(OpenStrategy.hsplit, opt) then\n if cur_layout ~= \"col\" then\n return \"split \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit, opt) then\n if cur_layout ~= \"row\" then\n return \"vsplit \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit_force, opt) then\n return \"vsplit \"\n elseif vim.startswith(OpenStrategy.hsplit_force, opt) then\n return \"hsplit \"\n elseif vim.startswith(OpenStrategy.current, opt) then\n return \"e \"\n else\n log.err(\"undefined open strategy '%s'\", opt)\n return \"e \"\n end\nend\n\n----------------------------\n--- Integration helpers ----\n----------------------------\n\n--- Get the path to where a plugin is installed.\n---\n---@param name string\n---@return string|?\nlocal get_src_root = function(name)\n return vim.iter(vim.api.nvim_list_runtime_paths()):find(function(path)\n return vim.endswith(path, name)\n end)\nend\n\n--- Get info about a plugin.\n---\n---@param name string\n---\n---@return { commit: string|?, path: string }|?\nM.get_plugin_info = function(name)\n local src_root = get_src_root(name)\n if not src_root then\n return\n end\n local out = { path = src_root }\n local obj = vim.system({ \"git\", \"rev-parse\", \"HEAD\" }, { cwd = src_root }):wait(1000)\n if obj.code == 0 then\n out.commit = vim.trim(obj.stdout)\n else\n out.commit = \"unknown\"\n end\n return out\nend\n\n--- Get info about a external dependency.\n---\n---@param cmd string\n---@return string|?\nM.get_external_dependency_info = function(cmd)\n local obj = vim.system({ cmd, \"--version\" }, {}):wait(1000)\n if obj.code ~= 0 then\n return\n end\n local version = vim.version.parse(obj.stdout)\n if version then\n return (\"%d.%d.%d\"):format(version.major, version.minor, version.patch)\n end\nend\n\n------------------\n--- UI helpers ---\n------------------\n\nlocal INPUT_CANCELLED = \"~~~INPUT-CANCELLED~~~\"\n\n--- Prompt user for an input. Returns nil if canceled, otherwise a string (possibly empty).\n---\n---@param prompt string\n---@param opts { completion: string|?, default: string|? }|?\n---\n---@return string|?\nM.input = function(prompt, opts)\n opts = opts or {}\n\n if not vim.endswith(prompt, \" \") then\n prompt = prompt .. \" \"\n end\n\n local input = vim.trim(\n vim.fn.input { prompt = prompt, completion = opts.completion, default = opts.default, cancelreturn = INPUT_CANCELLED }\n )\n\n if input ~= INPUT_CANCELLED then\n return input\n else\n return nil\n end\nend\n\n--- Prompt user for a confirmation.\n---\n---@param prompt string\n---\n---@return boolean\nM.confirm = function(prompt)\n if not vim.endswith(util.rstrip_whitespace(prompt), \"[Y/n]\") then\n prompt = util.rstrip_whitespace(prompt) .. \" [Y/n] \"\n end\n\n local confirmation = M.input(prompt)\n if confirmation == nil then\n return false\n end\n\n confirmation = string.lower(confirmation)\n\n if confirmation == \"\" or confirmation == \"y\" or confirmation == \"yes\" then\n return true\n else\n return false\n end\nend\n\n---@enum OSType\nM.OSType = {\n Linux = \"Linux\",\n Wsl = \"Wsl\",\n Windows = \"Windows\",\n Darwin = \"Darwin\",\n FreeBSD = \"FreeBSD\",\n}\n\nM._current_os = nil\n\n---Get the running operating system.\n---Reference https://vi.stackexchange.com/a/2577/33116\n---@return OSType\nM.get_os = function()\n if M._current_os ~= nil then\n return M._current_os\n end\n\n local this_os\n if vim.fn.has \"win32\" == 1 then\n this_os = M.OSType.Windows\n else\n local sysname = vim.uv.os_uname().sysname\n local release = vim.uv.os_uname().release:lower()\n if sysname:lower() == \"linux\" and string.find(release, \"microsoft\") then\n this_os = M.OSType.Wsl\n else\n this_os = sysname\n end\n end\n\n assert(this_os)\n M._current_os = this_os\n return this_os\nend\n\n--- Get a nice icon for a file or URL, if possible.\n---\n---@param path string\n---\n---@return string|?, string|? (icon, hl_group) The icon and highlight group.\nM.get_icon = function(path)\n if util.is_url(path) then\n local icon = \"\"\n local _, hl_group = M.get_icon \"blah.html\"\n return icon, hl_group\n else\n local ok, res = pcall(function()\n local icon, hl_group = require(\"nvim-web-devicons\").get_icon(path, nil, { default = true })\n return { icon, hl_group }\n end)\n if ok and type(res) == \"table\" then\n local icon, hlgroup = unpack(res)\n return icon, hlgroup\n elseif vim.endswith(path, \".md\") then\n return \"\"\n end\n end\n return nil\nend\n\n--- Resolve a basename to full path inside the vault.\n---\n---@param src string\n---@return string\nM.resolve_image_path = function(src)\n local img_folder = Obsidian.opts.attachments.img_folder\n\n ---@cast img_folder -nil\n if vim.startswith(img_folder, \".\") then\n local dirname = Path.new(vim.fs.dirname(vim.api.nvim_buf_get_name(0)))\n return tostring(dirname / img_folder / src)\n else\n return tostring(Obsidian.dir / img_folder / src)\n end\nend\n\n--- Follow a link. If the link argument is `nil` we attempt to follow a link under the cursor.\n---\n---@param link string\n---@param opts { open_strategy: obsidian.config.OpenStrategy|? }|?\nM.follow_link = function(link, opts)\n opts = opts and opts or {}\n local Note = require \"obsidian.note\"\n\n search.resolve_link_async(link, function(results)\n if #results == 0 then\n return\n end\n\n ---@param res obsidian.ResolveLinkResult\n local function follow_link(res)\n if res.url ~= nil then\n Obsidian.opts.follow_url_func(res.url)\n return\n end\n\n if util.is_img(res.location) then\n local path = Obsidian.dir / res.location\n Obsidian.opts.follow_img_func(tostring(path))\n return\n end\n\n if res.note ~= nil then\n -- Go to resolved note.\n return res.note:open { line = res.line, col = res.col, open_strategy = opts.open_strategy }\n end\n\n if res.link_type == search.RefTypes.Wiki or res.link_type == search.RefTypes.WikiWithAlias then\n -- Prompt to create a new note.\n if M.confirm(\"Create new note '\" .. res.location .. \"'?\") then\n -- Create a new note.\n ---@type string|?, string[]\n local id, aliases\n if res.name == res.location then\n aliases = {}\n else\n aliases = { res.name }\n id = res.location\n end\n\n local note = Note.create { title = res.name, id = id, aliases = aliases }\n return note:open {\n open_strategy = opts.open_strategy,\n callback = function(bufnr)\n note:write_to_buffer { bufnr = bufnr }\n end,\n }\n else\n log.warn \"Aborted\"\n return\n end\n end\n\n return log.err(\"Failed to resolve file '\" .. res.location .. \"'\")\n end\n\n if #results == 1 then\n return vim.schedule(function()\n follow_link(results[1])\n end)\n else\n return vim.schedule(function()\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple matches to '%s', but no picker is configured\", link)\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, res in ipairs(results) do\n local icon, icon_hl\n if res.url ~= nil then\n icon, icon_hl = M.get_icon(res.url)\n end\n table.insert(entries, {\n value = res,\n display = res.name,\n filename = res.path and tostring(res.path) or nil,\n icon = icon,\n icon_hl = icon_hl,\n })\n end\n\n picker:pick(entries, {\n prompt_title = \"Follow link\",\n callback = function(res)\n follow_link(res)\n end,\n })\n end)\n end\n end)\nend\n--------------------------\n---- Mapping functions ---\n--------------------------\n\n---@param direction \"next\" | \"prev\"\nM.nav_link = function(direction)\n vim.validate(\"direction\", direction, \"string\", false, \"nav_link must be called with a direction\")\n local cursor_line, cursor_col = unpack(vim.api.nvim_win_get_cursor(0))\n local Note = require \"obsidian.note\"\n\n search.find_links(Note.from_buffer(0), {}, function(matches)\n if direction == \"next\" then\n for i = 1, #matches do\n local match = matches[i]\n if (match.line > cursor_line) or (cursor_line == match.line and cursor_col < match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n\n if direction == \"prev\" then\n for i = #matches, 1, -1 do\n local match = matches[i]\n if (match.line < cursor_line) or (cursor_line == match.line and cursor_col > match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n end)\nend\n\nM.smart_action = function()\n local legacy = Obsidian.opts.legacy_commands\n -- follow link if possible\n if M.cursor_link() then\n return legacy and \"ObsidianFollowLink\" or \"Obsidian follow_link\"\n end\n\n -- show notes with tag if possible\n if M.cursor_tag() then\n return legacy and \"ObsidianTags\" or \"Obsidian tags\"\n end\n\n if M.cursor_heading() then\n return \"za\"\n end\n\n -- toggle task if possible\n -- cycles through your custom UI checkboxes, default: [ ] [~] [>] [x]\n return legacy and \"ObsidianToggleCheckbox\" or \"Obsidian toggle_checkbox\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/health.lua", "local M = {}\nlocal VERSION = require \"obsidian.version\"\nlocal api = require \"obsidian.api\"\n\nlocal error = vim.health.error\nlocal warn = vim.health.warn\nlocal ok = vim.health.ok\n\nlocal function info(...)\n local t = { ... }\n local format = table.remove(t, 1)\n local str = #t == 0 and format or string.format(format, unpack(t))\n return ok(str)\nend\n\n---@private\n---@param name string\nlocal function start(name)\n vim.health.start(string.format(\"obsidian.nvim [%s]\", name))\nend\n\n---@param plugin string\n---@param optional boolean\n---@return boolean\nlocal function has_plugin(plugin, optional)\n local plugin_info = api.get_plugin_info(plugin)\n if plugin_info then\n info(\"%s: %s\", plugin, plugin_info.commit or \"unknown\")\n return true\n else\n if not optional then\n vim.health.error(\" \" .. plugin .. \" not installed\")\n end\n return false\n end\nend\n\nlocal function has_executable(name, optional)\n if vim.fn.executable(name) == 1 then\n local version = api.get_external_dependency_info(name)\n if version then\n info(\"%s: %s\", name, version)\n else\n info(\"%s: found\", name)\n end\n return true\n else\n if not optional then\n error(string.format(\"%s not found\", name))\n end\n return false\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_plugin(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of_executable(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_executable(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param minimum string\n---@param recommended string\nlocal function neovim(minimum, recommended)\n if vim.fn.has(\"nvim-\" .. minimum) == 0 then\n error(\"neovim < \" .. minimum)\n elseif vim.fn.has(\"nvim-\" .. recommended) == 0 then\n warn(\"neovim < \" .. recommended .. \" some features will not work\")\n else\n ok(\"neovim >= \" .. recommended)\n end\nend\n\nfunction M.check()\n local os = api.get_os()\n neovim(\"0.10\", \"0.11\")\n start \"Version\"\n info(\"obsidian.nvim v%s (%s)\", VERSION, api.get_plugin_info(\"obsidian.nvim\").commit)\n\n start \"Environment\"\n info(\"operating system: %s\", os)\n\n start \"Config\"\n info(\" • dir: %s\", Obsidian.dir)\n\n start \"Pickers\"\n\n has_one_of {\n \"telescope.nvim\",\n \"fzf-lua\",\n \"mini.nvim\",\n \"mini.pick\",\n \"snacks.nvim\",\n }\n\n start \"Completion\"\n\n has_one_of {\n \"nvim-cmp\",\n \"blink.cmp\",\n }\n\n start \"Dependencies\"\n has_executable(\"rg\", false)\n has_plugin(\"plenary.nvim\", false)\n\n if os == api.OSType.Wsl then\n has_executable(\"wsl-open\", true)\n elseif os == api.OSType.Linux then\n has_one_of_executable {\n \"xclip\",\n \"wl-paste\",\n }\n elseif os == api.OSType.Darwin then\n has_executable(\"pngpaste\", true)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/path.lua", "local abc = require \"obsidian.abc\"\n\nlocal function coerce(v)\n if v == vim.NIL then\n return nil\n else\n return v\n end\nend\n\n---@param path table\n---@param k string\n---@param factory fun(obsidian.Path): any\nlocal function cached_get(path, k, factory)\n local cache_key = \"__\" .. k\n local v = rawget(path, cache_key)\n if v == nil then\n v = factory(path)\n if v == nil then\n v = vim.NIL\n end\n path[cache_key] = v\n end\n return coerce(v)\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_name(path)\n local name = vim.fs.basename(path.filename)\n if not name or string.len(name) == 0 then\n return\n else\n return name\n end\nend\n\n---@param path obsidian.Path\n---@return string[]\n---@private\nlocal function get_suffixes(path)\n ---@type string[]\n local suffixes = {}\n local name = path.name\n while name and string.len(name) > 0 do\n local s, e, suffix = string.find(name, \"(%.[^%.]+)$\")\n if s and e and suffix then\n name = string.sub(name, 1, s - 1)\n table.insert(suffixes, suffix)\n else\n break\n end\n end\n\n -- reverse the list.\n ---@type string[]\n local out = {}\n for i = #suffixes, 1, -1 do\n table.insert(out, suffixes[i])\n end\n return out\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_suffix(path)\n local suffixes = path.suffixes\n if #suffixes > 0 then\n return suffixes[#suffixes]\n else\n return nil\n end\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_stem(path)\n local name, suffix = path.name, path.suffix\n if not name then\n return\n elseif not suffix then\n return name\n else\n return string.sub(name, 1, string.len(name) - string.len(suffix))\n end\nend\n\n--- A `Path` class that provides a subset of the functionality of the Python `pathlib` library while\n--- staying true to its API. It improves on a number of bugs in `plenary.path`.\n---\n---@toc_entry obsidian.Path\n---\n---@class obsidian.Path : obsidian.ABC\n---\n---@field filename string The underlying filename as a string.\n---@field name string|? The final path component, if any.\n---@field suffix string|? The final extension of the path, if any.\n---@field suffixes string[] A list of all of the path's extensions.\n---@field stem string|? The final path component, without its suffix.\nlocal Path = abc.new_class()\n\nPath.mt = {\n __tostring = function(self)\n return self.filename\n end,\n __eq = function(a, b)\n return a.filename == b.filename\n end,\n __div = function(self, other)\n return self:joinpath(other)\n end,\n __index = function(self, k)\n local raw = rawget(Path, k)\n if raw then\n return raw\n end\n\n local factory\n if k == \"name\" then\n factory = get_name\n elseif k == \"suffix\" then\n factory = get_suffix\n elseif k == \"suffixes\" then\n factory = get_suffixes\n elseif k == \"stem\" then\n factory = get_stem\n end\n\n if factory then\n return cached_get(self, k, factory)\n end\n end,\n}\n\n--- Check if an object is an `obsidian.Path` object.\n---\n---@param path any\n---\n---@return boolean\nPath.is_path_obj = function(path)\n if getmetatable(path) == Path.mt then\n return true\n else\n return false\n end\nend\n\n-------------------------------------------------------------------------------\n--- Constructors.\n-------------------------------------------------------------------------------\n\n--- Create a new path from a string.\n---\n---@param ... string|obsidian.Path\n---\n---@return obsidian.Path\nPath.new = function(...)\n local self = Path.init()\n\n local args = { ... }\n local arg\n if #args == 1 then\n arg = tostring(args[1])\n elseif #args == 2 and args[1] == Path then\n arg = tostring(args[2])\n else\n error \"expected one argument\"\n end\n\n if Path.is_path_obj(arg) then\n ---@cast arg obsidian.Path\n return arg\n end\n\n self.filename = vim.fs.normalize(tostring(arg))\n\n return self\nend\n\n--- Get a temporary path with a unique name.\n---\n---@param opts { suffix: string|? }|?\n---\n---@return obsidian.Path\nPath.temp = function(opts)\n opts = opts or {}\n local tmpname = vim.fn.tempname()\n if opts.suffix then\n tmpname = tmpname .. opts.suffix\n end\n return Path.new(tmpname)\nend\n\n--- Get a path corresponding to the current working directory as given by `vim.uv.cwd()`.\n---\n---@return obsidian.Path\nPath.cwd = function()\n return assert(Path.new(vim.uv.cwd()))\nend\n\n--- Get a path corresponding to a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buffer = function(bufnr)\n return Path.new(vim.api.nvim_buf_get_name(bufnr or 0))\nend\n\n--- Get a path corresponding to the parent of a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buf_dir = function(bufnr)\n return assert(Path.buffer(bufnr):parent())\nend\n\n-------------------------------------------------------------------------------\n--- Pure path methods.\n-------------------------------------------------------------------------------\n\n--- Return a new path with the suffix changed.\n---\n---@param suffix string\n---@param should_append boolean|? should the suffix append a suffix instead of replacing one which may be there?\n---\n---@return obsidian.Path\nPath.with_suffix = function(self, suffix, should_append)\n if not vim.startswith(suffix, \".\") and string.len(suffix) > 1 then\n error(string.format(\"invalid suffix '%s'\", suffix))\n elseif self.stem == nil then\n error(string.format(\"path '%s' has no stem\", self.filename))\n end\n\n local new_name = ((should_append == true) and self.name or self.stem) .. suffix\n\n ---@type obsidian.Path|?\n local parent = nil\n if self.name ~= self.filename then\n parent = self:parent()\n end\n\n if parent then\n return parent / new_name\n else\n return Path.new(new_name)\n end\nend\n\n--- Returns true if the path is already in absolute form.\n---\n---@return boolean\nPath.is_absolute = function(self)\n local api = require \"obsidian.api\"\n if\n vim.startswith(self.filename, \"/\")\n or (\n (api.get_os() == api.OSType.Windows or api.get_os() == api.OSType.Wsl)\n and string.match(self.filename, \"^[%a]:/.*$\")\n )\n then\n return true\n else\n return false\n end\nend\n\n---@param ... obsidian.Path|string\n---@return obsidian.Path\nPath.joinpath = function(self, ...)\n local args = vim.iter({ ... }):map(tostring):totable()\n return Path.new(vim.fs.joinpath(self.filename, unpack(args)))\nend\n\n--- Try to resolve a version of the path relative to the other.\n--- An error is raised when it's not possible.\n---\n---@param other obsidian.Path|string\n---\n---@return obsidian.Path\nPath.relative_to = function(self, other)\n other = Path.new(other)\n\n local other_fname = other.filename\n if not vim.endswith(other_fname, \"/\") then\n other_fname = other_fname .. \"/\"\n end\n\n if vim.startswith(self.filename, other_fname) then\n return Path.new(string.sub(self.filename, string.len(other_fname) + 1))\n end\n\n -- Edge cases when the paths are relative or under-specified, see tests.\n if not self:is_absolute() and not vim.startswith(self.filename, \"./\") and vim.startswith(other_fname, \"./\") then\n if other_fname == \"./\" then\n return self\n end\n\n local self_rel_to_cwd = Path.new \"./\" / self\n if vim.startswith(self_rel_to_cwd.filename, other_fname) then\n return Path.new(string.sub(self_rel_to_cwd.filename, string.len(other_fname) + 1))\n end\n end\n\n error(string.format(\"'%s' is not in the subpath of '%s'\", self.filename, other.filename))\nend\n\n--- The logical parent of the path.\n---\n---@return obsidian.Path|?\nPath.parent = function(self)\n local parent = vim.fs.dirname(self.filename)\n if parent ~= nil then\n return Path.new(parent)\n else\n return nil\n end\nend\n\n--- Get a list of the parent directories.\n---\n---@return obsidian.Path[]\nPath.parents = function(self)\n return vim.iter(vim.fs.parents(self.filename)):map(Path.new):totable()\nend\n\n--- Check if the path is a parent of other. This is a pure path method, so it only checks by\n--- comparing strings. Therefore in practice you probably want to `:resolve()` each path before\n--- using this.\n---\n---@param other obsidian.Path|string\n---\n---@return boolean\nPath.is_parent_of = function(self, other)\n other = Path.new(other)\n for _, parent in ipairs(other:parents()) do\n if parent == self then\n return true\n end\n end\n return false\nend\n\n---@return string?\n---@private\nPath.abspath = function(self)\n local path = vim.loop.fs_realpath(vim.fn.resolve(self.filename))\n return path\nend\n\n-------------------------------------------------------------------------------\n--- Concrete path methods.\n-------------------------------------------------------------------------------\n\n--- Make the path absolute, resolving any symlinks.\n--- If `strict` is true and the path doesn't exist, an error is raised.\n---\n---@param opts { strict: boolean }|?\n---\n---@return obsidian.Path\nPath.resolve = function(self, opts)\n opts = opts or {}\n\n local realpath = self:abspath()\n if realpath then\n return Path.new(realpath)\n elseif opts.strict then\n error(\"FileNotFoundError: \" .. self.filename)\n end\n\n -- File doesn't exist, but some parents might. Traverse up until we find a parent that\n -- does exist, and then put the path back together from there.\n local parents = self:parents()\n for _, parent in ipairs(parents) do\n local parent_realpath = parent:abspath()\n if parent_realpath then\n return Path.new(parent_realpath) / self:relative_to(parent)\n end\n end\n\n return self\nend\n\n--- Get OS stat results.\n---\n---@return table|?\nPath.stat = function(self)\n local realpath = self:abspath()\n if realpath then\n local stat, _ = vim.uv.fs_stat(realpath)\n return stat\n end\nend\n\n--- Check if the path points to an existing file or directory.\n---\n---@return boolean\nPath.exists = function(self)\n local stat = self:stat()\n return stat ~= nil\nend\n\n--- Check if the path points to an existing file.\n---\n---@return boolean\nPath.is_file = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"file\"\n end\nend\n\n--- Check if the path points to an existing directory.\n---\n---@return boolean\nPath.is_dir = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"directory\"\n end\nend\n\n--- Create a new directory at the given path.\n---\n---@param opts { mode: integer|?, parents: boolean|?, exist_ok: boolean|? }|?\nPath.mkdir = function(self, opts)\n opts = opts or {}\n\n local mode = opts.mode or 448 -- 0700 -> decimal\n ---@diagnostic disable-next-line: undefined-field\n if opts.exists_ok then -- for compat with the plenary.path API.\n opts.exist_ok = true\n end\n\n if self:is_dir() then\n if not opts.exist_ok then\n error(\"FileExistsError: \" .. self.filename)\n else\n return\n end\n end\n\n if vim.uv.fs_mkdir(self.filename, mode) then\n return\n end\n\n if not opts.parents then\n error(\"FileNotFoundError: \" .. tostring(self:parent()))\n end\n\n local parents = self:parents()\n for i = #parents, 1, -1 do\n if not parents[i]:is_dir() then\n parents[i]:mkdir { exist_ok = true, mode = mode }\n end\n end\n\n self:mkdir { mode = mode }\nend\n\n--- Remove the corresponding directory. This directory must be empty.\nPath.rmdir = function(self)\n local resolved = self:resolve { strict = false }\n\n if not resolved:is_dir() then\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_rmdir(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n-- TODO: not implemented and not used, after we get to 0.11 we can simply use vim.fs.rm\n--- Recursively remove an entire directory and its contents.\nPath.rmtree = function(self) end\n\n--- Create a file at this given path.\n---\n---@param opts { mode: integer|?, exist_ok: boolean|? }|?\nPath.touch = function(self, opts)\n opts = opts or {}\n local mode = opts.mode or 420\n\n local resolved = self:resolve { strict = false }\n if resolved:exists() then\n local new_time = os.time()\n vim.uv.fs_utime(resolved.filename, new_time, new_time)\n return\n end\n\n local parent = resolved:parent()\n if parent and not parent:exists() then\n error(\"FileNotFoundError: \" .. parent.filename)\n end\n\n local fd, err_name, err_msg = vim.uv.fs_open(resolved.filename, \"w\", mode)\n if not fd then\n error(err_name .. \": \" .. err_msg)\n end\n vim.uv.fs_close(fd)\nend\n\n--- Rename this file or directory to the given target.\n---\n---@param target obsidian.Path|string\n---\n---@return obsidian.Path\nPath.rename = function(self, target)\n local resolved = self:resolve { strict = false }\n target = Path.new(target)\n\n local ok, err_name, err_msg = vim.uv.fs_rename(resolved.filename, target.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\n\n return target\nend\n\n--- Remove the file.\n---\n---@param opts { missing_ok: boolean|? }|?\nPath.unlink = function(self, opts)\n opts = opts or {}\n\n local resolved = self:resolve { strict = false }\n\n if not resolved:exists() then\n if not opts.missing_ok then\n error(\"FileNotFoundError: \" .. resolved.filename)\n end\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_unlink(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n--- Make a path relative to the vault root, if possible, return a string\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return string?\nPath.vault_relative_path = function(self, opts)\n opts = opts or {}\n\n -- NOTE: we don't try to resolve the `path` here because that would make the path absolute,\n -- which may result in the wrong relative path if the current working directory is not within\n -- the vault.\n\n local ok, relative_path = pcall(function()\n return self:relative_to(Obsidian.workspace.root)\n end)\n\n if ok and relative_path then\n return tostring(relative_path)\n elseif not self:is_absolute() then\n return tostring(self)\n elseif opts.strict then\n error(string.format(\"failed to resolve '%s' relative to vault root '%s'\", self, Obsidian.workspace.root))\n end\nend\n\nreturn Path\n"], ["/obsidian.nvim/lua/obsidian/commands/open.lua", "local api = require \"obsidian.api\"\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\nlocal log = require \"obsidian.log\"\n\n---@param path? string|obsidian.Path\nlocal function open_in_app(path)\n local vault_name = vim.fs.basename(tostring(Obsidian.workspace.root))\n if not path then\n return Obsidian.opts.open.func(\"obsidian://open?vault=\" .. vim.uri_encode(vault_name))\n end\n path = tostring(path)\n local this_os = api.get_os()\n\n -- Normalize path for windows.\n if this_os == api.OSType.Windows then\n path = string.gsub(path, \"/\", \"\\\\\")\n end\n\n local encoded_vault = vim.uri_encode(vault_name)\n local encoded_path = vim.uri_encode(path)\n\n local uri\n if Obsidian.opts.open.use_advanced_uri then\n local line = vim.api.nvim_win_get_cursor(0)[1] or 1\n uri = (\"obsidian://advanced-uri?vault=%s&filepath=%s&line=%i\"):format(encoded_vault, encoded_path, line)\n else\n uri = (\"obsidian://open?vault=%s&file=%s\"):format(encoded_vault, encoded_path)\n end\n print(uri)\n\n Obsidian.opts.open.func(uri)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type string|?\n local search_term\n\n if data.args and data.args:len() > 0 then\n search_term = data.args\n else\n -- Check for a note reference under the cursor.\n local link_string, _ = api.cursor_link()\n search_term = link_string\n end\n\n if search_term then\n search.resolve_link_async(search_term, function(results)\n if vim.tbl_isempty(results) then\n return log.err \"Note under cusros is not resolved\"\n end\n vim.schedule(function()\n open_in_app(results[1].path)\n end)\n end)\n else\n -- Otherwise use the path of the current buffer.\n local bufname = vim.api.nvim_buf_get_name(0)\n local path = Path.new(bufname):vault_relative_path()\n open_in_app(path)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/note.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal yaml = require \"obsidian.yaml\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\nlocal enumerate = util.enumerate\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal config = require \"obsidian.config\"\n\nlocal SKIP_UPDATING_FRONTMATTER = { \"README.md\", \"CONTRIBUTING.md\", \"CHANGELOG.md\" }\n\nlocal DEFAULT_MAX_LINES = 500\n\nlocal CODE_BLOCK_PATTERN = \"^%s*```[%w_-]*$\"\n\n--- @class obsidian.note.NoteCreationOpts\n--- @field notes_subdir string\n--- @field note_id_func fun()\n--- @field new_notes_location string\n\n--- @class obsidian.note.NoteOpts\n--- @field title string|? The note's title\n--- @field id string|? An ID to assign the note. If not specified one will be generated.\n--- @field dir string|obsidian.Path|? An optional directory to place the note in. Relative paths will be interpreted\n--- relative to the workspace / vault root. If the directory doesn't exist it will\n--- be created, regardless of the value of the `should_write` option.\n--- @field aliases string[]|? Aliases for the note\n--- @field tags string[]|? Tags for this note\n--- @field should_write boolean|? Don't write the note to disk\n--- @field template string|? The name of the template\n\n---@class obsidian.note.NoteSaveOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- Whether to insert/update frontmatter. Defaults to `true`.\n---@field insert_frontmatter? boolean\n--- Override the frontmatter. Defaults to the result of `self:frontmatter()`.\n---@field frontmatter? table\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload the updated file.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.NoteWriteOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- The name of a template to use if the note file doesn't already exist.\n---@field template? string\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload each buffer's content.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.HeaderAnchor\n---\n---@field anchor string\n---@field header string\n---@field level integer\n---@field line integer\n---@field parent obsidian.note.HeaderAnchor|?\n\n---@class obsidian.note.Block\n---\n---@field id string\n---@field line integer\n---@field block string\n\n--- A class that represents a note within a vault.\n---\n---@toc_entry obsidian.Note\n---\n---@class obsidian.Note : obsidian.ABC\n---\n---@field id string\n---@field aliases string[]\n---@field title string|?\n---@field tags string[]\n---@field path obsidian.Path|?\n---@field metadata table|?\n---@field has_frontmatter boolean|?\n---@field frontmatter_end_line integer|?\n---@field contents string[]|?\n---@field anchor_links table|?\n---@field blocks table?\n---@field alt_alias string|?\n---@field bufnr integer|?\nlocal Note = abc.new_class {\n __tostring = function(self)\n return string.format(\"Note('%s')\", self.id)\n end,\n}\n\nNote.is_note_obj = function(note)\n if getmetatable(note) == Note.mt then\n return true\n else\n return false\n end\nend\n\n--- Generate a unique ID for a new note. This respects the user's `note_id_func` if configured,\n--- otherwise falls back to generated a Zettelkasten style ID.\n---\n--- @param title? string\n--- @param path? obsidian.Path\n--- @param alt_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n---@return string\nlocal function generate_id(title, path, alt_id_func)\n if alt_id_func ~= nil then\n local new_id = alt_id_func(title, path)\n if new_id == nil or string.len(new_id) == 0 then\n error(string.format(\"Your 'note_id_func' must return a non-empty string, got '%s'!\", tostring(new_id)))\n end\n -- Remote '.md' suffix if it's there (we add that later).\n new_id = new_id:gsub(\"%.md$\", \"\", 1)\n return new_id\n else\n return require(\"obsidian.builtin\").zettel_id()\n end\nend\n\n--- Generate the file path for a new note given its ID, parent directory, and title.\n--- This respects the user's `note_path_func` if configured, otherwise essentially falls back to\n--- `note_opts.dir / (note_opts.id .. \".md\")`.\n---\n--- @param title string|? The title for the note\n--- @param id string The note ID\n--- @param dir obsidian.Path The note path\n---@return obsidian.Path\n---@private\nNote._generate_path = function(title, id, dir)\n ---@type obsidian.Path\n local path\n\n if Obsidian.opts.note_path_func ~= nil then\n path = Path.new(Obsidian.opts.note_path_func { id = id, dir = dir, title = title })\n -- Ensure path is either absolute or inside `opts.dir`.\n -- NOTE: `opts.dir` should always be absolute, but for extra safety we handle the case where\n -- it's not.\n if not path:is_absolute() and (dir:is_absolute() or not dir:is_parent_of(path)) then\n path = dir / path\n end\n else\n path = dir / tostring(id)\n end\n\n -- Ensure there is only one \".md\" suffix. This might arise if `note_path_func`\n -- supplies an unusual implementation returning something like /bad/note/id.md.md.md\n while path.filename:match \"%.md$\" do\n path.filename = path.filename:gsub(\"%.md$\", \"\")\n end\n\n return path:with_suffix(\".md\", true)\nend\n\n--- Selects the strategy to use when resolving the note title, id, and path\n--- @param opts obsidian.note.NoteOpts The note creation options\n--- @return obsidian.note.NoteCreationOpts The strategy to use for creating the note\n--- @private\nNote._get_creation_opts = function(opts)\n --- @type obsidian.note.NoteCreationOpts\n local default = {\n notes_subdir = Obsidian.opts.notes_subdir,\n note_id_func = Obsidian.opts.note_id_func,\n new_notes_location = Obsidian.opts.new_notes_location,\n }\n\n local resolve_template = require(\"obsidian.templates\").resolve_template\n local success, template_path = pcall(resolve_template, opts.template, api.templates_dir())\n\n if not success then\n return default\n end\n\n local stem = template_path.stem:lower()\n\n -- Check if the configuration has a custom key for this template\n for key, cfg in pairs(Obsidian.opts.templates.customizations) do\n if key:lower() == stem then\n return {\n notes_subdir = cfg.notes_subdir,\n note_id_func = cfg.note_id_func,\n new_notes_location = config.NewNotesLocation.notes_subdir,\n }\n end\n end\n return default\nend\n\n--- Resolves the title, ID, and path for a new note.\n---\n---@param title string|?\n---@param id string|?\n---@param dir string|obsidian.Path|? The directory for the note\n---@param strategy obsidian.note.NoteCreationOpts Strategy for resolving note path and title\n---@return string|?,string,obsidian.Path\n---@private\nNote._resolve_title_id_path = function(title, id, dir, strategy)\n if title then\n title = vim.trim(title)\n if title == \"\" then\n title = nil\n end\n end\n\n if id then\n id = vim.trim(id)\n if id == \"\" then\n id = nil\n end\n end\n\n ---@param s string\n ---@param strict_paths_only boolean\n ---@return string|?, boolean, string|?\n local parse_as_path = function(s, strict_paths_only)\n local is_path = false\n ---@type string|?\n local parent\n\n if s:match \"%.md\" then\n -- Remove suffix.\n s = s:sub(1, s:len() - 3)\n is_path = true\n end\n\n -- Pull out any parent dirs from title.\n local parts = vim.split(s, \"/\")\n if #parts > 1 then\n s = parts[#parts]\n if not strict_paths_only then\n is_path = true\n end\n parent = table.concat(parts, \"/\", 1, #parts - 1)\n end\n\n if s == \"\" then\n return nil, is_path, parent\n else\n return s, is_path, parent\n end\n end\n\n local parent, _, title_is_path\n if id then\n id, _, parent = parse_as_path(id, false)\n elseif title then\n title, title_is_path, parent = parse_as_path(title, true)\n if title_is_path then\n id = title\n end\n end\n\n -- Resolve base directory.\n ---@type obsidian.Path\n local base_dir\n if parent then\n base_dir = Obsidian.dir / parent\n elseif dir ~= nil then\n base_dir = Path.new(dir)\n if not base_dir:is_absolute() then\n base_dir = Obsidian.dir / base_dir\n else\n base_dir = base_dir:resolve()\n end\n else\n local bufpath = Path.buffer(0):resolve()\n if\n strategy.new_notes_location == config.NewNotesLocation.current_dir\n -- note is actually in the workspace.\n and Obsidian.dir:is_parent_of(bufpath)\n -- note is not in dailies folder\n and (\n Obsidian.opts.daily_notes.folder == nil\n or not (Obsidian.dir / Obsidian.opts.daily_notes.folder):is_parent_of(bufpath)\n )\n then\n base_dir = Obsidian.buf_dir or assert(bufpath:parent())\n else\n base_dir = Obsidian.dir\n if strategy.notes_subdir then\n base_dir = base_dir / strategy.notes_subdir\n end\n end\n end\n\n -- Make sure `base_dir` is absolute at this point.\n assert(base_dir:is_absolute(), (\"failed to resolve note directory '%s'\"):format(base_dir))\n\n -- Generate new ID if needed.\n if not id then\n id = generate_id(title, base_dir, strategy.note_id_func)\n end\n\n dir = base_dir\n\n -- Generate path.\n local path = Note._generate_path(title, id, dir)\n\n return title, id, path\nend\n\n--- Creates a new note\n---\n--- @param opts obsidian.note.NoteOpts Options\n--- @return obsidian.Note\nNote.create = function(opts)\n local new_title, new_id, path =\n Note._resolve_title_id_path(opts.title, opts.id, opts.dir, Note._get_creation_opts(opts))\n opts = vim.tbl_extend(\"keep\", opts, { aliases = {}, tags = {} })\n\n -- Add the title as an alias.\n --- @type string[]\n local aliases = opts.aliases\n if new_title ~= nil and new_title:len() > 0 and not vim.list_contains(aliases, new_title) then\n aliases[#aliases + 1] = new_title\n end\n\n local note = Note.new(new_id, aliases, opts.tags, path)\n\n if new_title then\n note.title = new_title\n end\n\n -- Ensure the parent directory exists.\n local parent = path:parent()\n assert(parent)\n parent:mkdir { parents = true, exist_ok = true }\n\n -- Write to disk.\n if opts.should_write then\n note:write { template = opts.template }\n end\n\n return note\nend\n\n--- Instantiates a new Note object\n---\n--- Keep in mind that you have to call `note:save(...)` to create/update the note on disk.\n---\n--- @param id string|number\n--- @param aliases string[]\n--- @param tags string[]\n--- @param path string|obsidian.Path|?\n--- @return obsidian.Note\nNote.new = function(id, aliases, tags, path)\n local self = Note.init()\n self.id = id\n self.aliases = aliases and aliases or {}\n self.tags = tags and tags or {}\n self.path = path and Path.new(path) or nil\n self.metadata = nil\n self.has_frontmatter = nil\n self.frontmatter_end_line = nil\n return self\nend\n\n--- Get markdown display info about the note.\n---\n---@param opts { label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|?\n---\n---@return string\nNote.display_info = function(self, opts)\n opts = opts and opts or {}\n\n ---@type string[]\n local info = {}\n\n if opts.label ~= nil and string.len(opts.label) > 0 then\n info[#info + 1] = (\"%s\"):format(opts.label)\n info[#info + 1] = \"--------\"\n end\n\n if self.path ~= nil then\n info[#info + 1] = (\"**path:** `%s`\"):format(self.path)\n end\n\n info[#info + 1] = (\"**id:** `%s`\"):format(self.id)\n\n if #self.aliases > 0 then\n info[#info + 1] = (\"**aliases:** '%s'\"):format(table.concat(self.aliases, \"', '\"))\n end\n\n if #self.tags > 0 then\n info[#info + 1] = (\"**tags:** `#%s`\"):format(table.concat(self.tags, \"`, `#\"))\n end\n\n if opts.anchor or opts.block then\n info[#info + 1] = \"--------\"\n\n if opts.anchor then\n info[#info + 1] = (\"...\\n%s %s\\n...\"):format(string.rep(\"#\", opts.anchor.level), opts.anchor.header)\n elseif opts.block then\n info[#info + 1] = (\"...\\n%s\\n...\"):format(opts.block.block)\n end\n end\n\n return table.concat(info, \"\\n\")\nend\n\n--- Check if the note exists on the file system.\n---\n---@return boolean\nNote.exists = function(self)\n ---@diagnostic disable-next-line: return-type-mismatch\n return self.path ~= nil and self.path:is_file()\nend\n\n--- Get the filename associated with the note.\n---\n---@return string|?\nNote.fname = function(self)\n if self.path == nil then\n return nil\n else\n return vim.fs.basename(tostring(self.path))\n end\nend\n\n--- Get a list of all of the different string that can identify this note via references,\n--- including the ID, aliases, and filename.\n---@param opts { lowercase: boolean|? }|?\n---@return string[]\nNote.reference_ids = function(self, opts)\n opts = opts or {}\n ---@type string[]\n local ref_ids = { tostring(self.id), self:display_name() }\n if self.path then\n table.insert(ref_ids, self.path.name)\n table.insert(ref_ids, self.path.stem)\n end\n\n vim.list_extend(ref_ids, self.aliases)\n\n if opts.lowercase then\n ref_ids = vim.tbl_map(string.lower, ref_ids)\n end\n\n return util.tbl_unique(ref_ids)\nend\n\n--- Check if a note has a given alias.\n---\n---@param alias string\n---\n---@return boolean\nNote.has_alias = function(self, alias)\n return vim.list_contains(self.aliases, alias)\nend\n\n--- Check if a note has a given tag.\n---\n---@param tag string\n---\n---@return boolean\nNote.has_tag = function(self, tag)\n return vim.list_contains(self.tags, tag)\nend\n\n--- Add an alias to the note.\n---\n---@param alias string\n---\n---@return boolean added True if the alias was added, false if it was already present.\nNote.add_alias = function(self, alias)\n if not self:has_alias(alias) then\n table.insert(self.aliases, alias)\n return true\n else\n return false\n end\nend\n\n--- Add a tag to the note.\n---\n---@param tag string\n---\n---@return boolean added True if the tag was added, false if it was already present.\nNote.add_tag = function(self, tag)\n if not self:has_tag(tag) then\n table.insert(self.tags, tag)\n return true\n else\n return false\n end\nend\n\n--- Add or update a field in the frontmatter.\n---\n---@param key string\n---@param value any\nNote.add_field = function(self, key, value)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Updating field '%s' this way is not allowed. Please update the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n self.metadata = {}\n end\n\n self.metadata[key] = value\nend\n\n--- Get a field in the frontmatter.\n---\n---@param key string\n---\n---@return any result\nNote.get_field = function(self, key)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Getting field '%s' this way is not allowed. Please use the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n return nil\n end\n\n return self.metadata[key]\nend\n\n---@class obsidian.note.LoadOpts\n---@field max_lines integer|?\n---@field load_contents boolean|?\n---@field collect_anchor_links boolean|?\n---@field collect_blocks boolean|?\n\n--- Initialize a note from a file.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file = function(path, opts)\n if path == nil then\n error \"note path cannot be nil\"\n end\n path = tostring(Path.new(path):resolve { strict = true })\n return Note.from_lines(io.lines(path), path, opts)\nend\n\n--- An async version of `.from_file()`, i.e. it needs to be called in an async context.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file_async = function(path, opts)\n path = Path.new(path):resolve { strict = true }\n local f = io.open(tostring(path), \"r\")\n assert(f)\n local ok, res = pcall(Note.from_lines, f:lines \"*l\", path, opts)\n f:close()\n if ok then\n return res\n else\n error(res)\n end\nend\n\n--- Like `.from_file_async()` but also returns the contents of the file as a list of lines.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note,string[]\nNote.from_file_with_contents_async = function(path, opts)\n opts = vim.tbl_extend(\"force\", opts or {}, { load_contents = true })\n local note = Note.from_file_async(path, opts)\n assert(note.contents ~= nil)\n return note, note.contents\nend\n\n--- Initialize a note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_buffer = function(bufnr, opts)\n bufnr = bufnr or vim.api.nvim_get_current_buf()\n local path = vim.api.nvim_buf_get_name(bufnr)\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)\n local note = Note.from_lines(iter(lines), path, opts)\n note.bufnr = bufnr\n return note\nend\n\n--- Get the display name for note.\n---\n---@return string\nNote.display_name = function(self)\n if self.title then\n return self.title\n elseif #self.aliases > 0 then\n return self.aliases[#self.aliases]\n end\n return tostring(self.id)\nend\n\n--- Initialize a note from an iterator of lines.\n---\n---@param lines fun(): string|? | Iter\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_lines = function(lines, path, opts)\n opts = opts or {}\n path = Path.new(path):resolve()\n\n local max_lines = opts.max_lines or DEFAULT_MAX_LINES\n\n local id = nil\n local title = nil\n local aliases = {}\n local tags = {}\n\n ---@type string[]|?\n local contents\n if opts.load_contents then\n contents = {}\n end\n\n ---@type table|?\n local anchor_links\n ---@type obsidian.note.HeaderAnchor[]|?\n local anchor_stack\n if opts.collect_anchor_links then\n anchor_links = {}\n anchor_stack = {}\n end\n\n ---@type table|?\n local blocks\n if opts.collect_blocks then\n blocks = {}\n end\n\n ---@param anchor_data obsidian.note.HeaderAnchor\n ---@return obsidian.note.HeaderAnchor|?\n local function get_parent_anchor(anchor_data)\n assert(anchor_links)\n assert(anchor_stack)\n for i = #anchor_stack, 1, -1 do\n local parent = anchor_stack[i]\n if parent.level < anchor_data.level then\n return parent\n end\n end\n end\n\n ---@param anchor string\n ---@param data obsidian.note.HeaderAnchor|?\n local function format_nested_anchor(anchor, data)\n local out = anchor\n if not data then\n return out\n end\n\n local parent = data.parent\n while parent ~= nil do\n out = parent.anchor .. out\n data = get_parent_anchor(parent)\n if data then\n parent = data.parent\n else\n parent = nil\n end\n end\n\n return out\n end\n\n -- Iterate over lines in the file, collecting frontmatter and parsing the title.\n local frontmatter_lines = {}\n local has_frontmatter, in_frontmatter, at_boundary = false, false, false -- luacheck: ignore (false positive)\n local frontmatter_end_line = nil\n local in_code_block = false\n for line_idx, line in enumerate(lines) do\n line = util.rstrip_whitespace(line)\n\n if line_idx == 1 and Note._is_frontmatter_boundary(line) then\n has_frontmatter = true\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n frontmatter_end_line = line_idx\n else\n at_boundary = false\n end\n\n if string.match(line, CODE_BLOCK_PATTERN) then\n in_code_block = not in_code_block\n end\n\n if in_frontmatter and not at_boundary then\n table.insert(frontmatter_lines, line)\n elseif not in_frontmatter and not at_boundary and not in_code_block then\n -- Check for title/header and collect anchor link.\n local header_match = util.parse_header(line)\n if header_match then\n if not title and header_match.level == 1 then\n title = header_match.header\n end\n\n -- Collect anchor link.\n if opts.collect_anchor_links then\n assert(anchor_links)\n assert(anchor_stack)\n -- We collect up to two anchor for each header. One standalone, e.g. '#header1', and\n -- one with the parents, e.g. '#header1#header2'.\n -- This is our standalone one:\n ---@type obsidian.note.HeaderAnchor\n local data = {\n anchor = header_match.anchor,\n line = line_idx,\n header = header_match.header,\n level = header_match.level,\n }\n data.parent = get_parent_anchor(data)\n\n anchor_links[header_match.anchor] = data\n table.insert(anchor_stack, data)\n\n -- Now if there's a parent we collect the nested version. All of the data will be the same\n -- except the anchor key.\n if data.parent ~= nil then\n local nested_anchor = format_nested_anchor(header_match.anchor, data)\n anchor_links[nested_anchor] = vim.tbl_extend(\"force\", data, { anchor = nested_anchor })\n end\n end\n end\n\n -- Check for block.\n if opts.collect_blocks then\n local block = util.parse_block(line)\n if block then\n blocks[block] = { id = block, line = line_idx, block = line }\n end\n end\n end\n\n -- Collect contents.\n if contents ~= nil then\n table.insert(contents, line)\n end\n\n -- Check if we can stop reading lines now.\n if\n line_idx > max_lines\n or (title and not opts.load_contents and not opts.collect_anchor_links and not opts.collect_blocks)\n then\n break\n end\n end\n\n if title ~= nil then\n -- Remove references and links from title\n title = search.replace_refs(title)\n end\n\n -- Parse the frontmatter YAML.\n local metadata = nil\n if #frontmatter_lines > 0 then\n local frontmatter = table.concat(frontmatter_lines, \"\\n\")\n local ok, data = pcall(yaml.loads, frontmatter)\n if type(data) ~= \"table\" then\n data = {}\n end\n if ok then\n ---@diagnostic disable-next-line: param-type-mismatch\n for k, v in pairs(data) do\n if k == \"id\" then\n if type(v) == \"string\" or type(v) == \"number\" then\n id = v\n else\n log.warn(\"Invalid 'id' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"aliases\" then\n if type(v) == \"table\" then\n for alias in iter(v) do\n if type(alias) == \"string\" then\n table.insert(aliases, alias)\n else\n log.warn(\n \"Invalid alias value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(alias)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n table.insert(aliases, v)\n else\n log.warn(\"Invalid 'aliases' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"tags\" then\n if type(v) == \"table\" then\n for tag in iter(v) do\n if type(tag) == \"string\" then\n table.insert(tags, tag)\n else\n log.warn(\n \"Invalid tag value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(tag)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n tags = vim.split(v, \" \")\n else\n log.warn(\"Invalid 'tags' in frontmatter for '%s'\", path)\n end\n else\n if metadata == nil then\n metadata = {}\n end\n metadata[k] = v\n end\n end\n end\n end\n\n -- ID should default to the filename without the extension.\n if id == nil or id == path.name then\n id = path.stem\n end\n assert(id)\n\n local n = Note.new(id, aliases, tags, path)\n n.title = title\n n.metadata = metadata\n n.has_frontmatter = has_frontmatter\n n.frontmatter_end_line = frontmatter_end_line\n n.contents = contents\n n.anchor_links = anchor_links\n n.blocks = blocks\n return n\nend\n\n--- Check if a line matches a frontmatter boundary.\n---\n---@param line string\n---\n---@return boolean\n---\n---@private\nNote._is_frontmatter_boundary = function(line)\n return line:match \"^---+$\" ~= nil\nend\n\n--- Get the frontmatter table to save.\n---\n---@return table\nNote.frontmatter = function(self)\n local out = { id = self.id, aliases = self.aliases, tags = self.tags }\n if self.metadata ~= nil and not vim.tbl_isempty(self.metadata) then\n for k, v in pairs(self.metadata) do\n out[k] = v\n end\n end\n return out\nend\n\n--- Get frontmatter lines that can be written to a buffer.\n---\n---@param eol boolean|?\n---@param frontmatter table|?\n---\n---@return string[]\nNote.frontmatter_lines = function(self, eol, frontmatter)\n local new_lines = { \"---\" }\n\n local frontmatter_ = frontmatter and frontmatter or self:frontmatter()\n if vim.tbl_isempty(frontmatter_) then\n return {}\n end\n\n for line in\n iter(yaml.dumps_lines(frontmatter_, function(a, b)\n local a_idx = nil\n local b_idx = nil\n for i, k in ipairs { \"id\", \"aliases\", \"tags\" } do\n if a == k then\n a_idx = i\n end\n if b == k then\n b_idx = i\n end\n end\n if a_idx ~= nil and b_idx ~= nil then\n return a_idx < b_idx\n elseif a_idx ~= nil then\n return true\n elseif b_idx ~= nil then\n return false\n else\n return a < b\n end\n end))\n do\n table.insert(new_lines, line)\n end\n\n table.insert(new_lines, \"---\")\n if not self.has_frontmatter then\n -- Make sure there's an empty line between end of the frontmatter and the contents.\n table.insert(new_lines, \"\")\n end\n\n if eol then\n return vim.tbl_map(function(l)\n return l .. \"\\n\"\n end, new_lines)\n else\n return new_lines\n end\nend\n\n--- Update the frontmatter in a buffer for the note.\n---\n---@param bufnr integer|?\n---\n---@return boolean updated If the the frontmatter was updated.\nNote.update_frontmatter = function(self, bufnr)\n if not self:should_save_frontmatter() then\n return false\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n return self:save_to_buffer { bufnr = bufnr, frontmatter = frontmatter }\nend\n\n--- Checks if the parameter note is in the blacklist of files which shouldn't have\n--- frontmatter applied\n---\n--- @param note obsidian.Note The note\n--- @return boolean true if so\nlocal is_in_frontmatter_blacklist = function(note)\n local fname = note:fname()\n return (fname ~= nil and vim.list_contains(SKIP_UPDATING_FRONTMATTER, fname))\nend\n\n--- Determines whether a note's frontmatter is managed by obsidian.nvim.\n---\n---@return boolean\nNote.should_save_frontmatter = function(self)\n -- Check if the note is a template.\n local templates_dir = api.templates_dir()\n if templates_dir ~= nil then\n templates_dir = templates_dir:resolve()\n for _, parent in ipairs(self.path:parents()) do\n if parent == templates_dir then\n return false\n end\n end\n end\n\n if is_in_frontmatter_blacklist(self) then\n return false\n elseif type(Obsidian.opts.disable_frontmatter) == \"boolean\" then\n return not Obsidian.opts.disable_frontmatter\n elseif type(Obsidian.opts.disable_frontmatter) == \"function\" then\n return not Obsidian.opts.disable_frontmatter(self.path:vault_relative_path { strict = true })\n else\n return true\n end\nend\n\n--- Write the note to disk.\n---\n---@param opts? obsidian.note.NoteWriteOpts\n---@return obsidian.Note\nNote.write = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n local path = assert(self.path, \"A path must be provided\")\n path = Path.new(path)\n\n ---@type string\n local verb\n if path:is_file() then\n verb = \"Updated\"\n else\n verb = \"Created\"\n if opts.template ~= nil then\n self = Template.clone_template {\n type = \"clone_template\",\n template_name = opts.template,\n destination_path = path,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n partial_note = self,\n }\n end\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n self:save {\n path = path,\n insert_frontmatter = self:should_save_frontmatter(),\n frontmatter = frontmatter,\n update_content = opts.update_content,\n check_buffers = opts.check_buffers,\n }\n\n log.info(\"%s note '%s' at '%s'\", verb, self.id, self.path:vault_relative_path(self.path) or self.path)\n\n return self\nend\n\n--- Save the note to a file.\n--- In general this only updates the frontmatter and header, leaving the rest of the contents unchanged\n--- unless you use the `update_content()` callback.\n---\n---@param opts? obsidian.note.NoteSaveOpts\nNote.save = function(self, opts)\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n if self.path == nil then\n error \"a path is required\"\n end\n\n local save_path = Path.new(assert(opts.path or self.path)):resolve()\n assert(save_path:parent()):mkdir { parents = true, exist_ok = true }\n\n -- Read contents from existing file or buffer, if there is one.\n -- TODO: check for open buffer?\n ---@type string[]\n local content = {}\n ---@type string[]\n local existing_frontmatter = {}\n if self.path ~= nil and self.path:is_file() then\n -- with(open(tostring(self.path)), function(reader)\n local in_frontmatter, at_boundary = false, false -- luacheck: ignore (false positive)\n for idx, line in enumerate(io.lines(tostring(self.path))) do\n if idx == 1 and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n else\n at_boundary = false\n end\n\n if not in_frontmatter and not at_boundary then\n table.insert(content, line)\n else\n table.insert(existing_frontmatter, line)\n end\n end\n -- end)\n elseif self.title ~= nil then\n -- Add a header.\n table.insert(content, \"# \" .. self.title)\n end\n\n -- Pass content through callback.\n if opts.update_content then\n content = opts.update_content(content)\n end\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n -- Replace frontmatter.\n new_lines = compat.flatten { self:frontmatter_lines(false, opts.frontmatter), content }\n else\n -- Use existing frontmatter.\n new_lines = compat.flatten { existing_frontmatter, content }\n end\n\n util.write_file(tostring(save_path), table.concat(new_lines, \"\\n\"))\n\n if opts.check_buffers then\n -- `vim.fn.bufnr` returns the **max** bufnr loaded from the same path.\n if vim.fn.bufnr(save_path.filename) ~= -1 then\n -- But we want to call |checktime| on **all** buffers loaded from the path.\n vim.cmd.checktime(save_path.filename)\n end\n end\nend\n\n--- Write the note to a buffer.\n---\n---@param opts { bufnr: integer|?, template: string|? }|? Options.\n---\n--- Options:\n--- - `bufnr`: Override the buffer to write to. Defaults to current buffer.\n--- - `template`: The name of a template to use if the buffer is empty.\n---\n---@return boolean updated If the buffer was updated.\nNote.write_to_buffer = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = opts or {}\n\n if opts.template and api.buffer_is_empty(opts.bufnr) then\n self = Template.insert_template {\n type = \"insert_template\",\n template_name = opts.template,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n location = api.get_active_window_cursor_location(),\n partial_note = self,\n }\n end\n\n local frontmatter = nil\n local should_save_frontmatter = self:should_save_frontmatter()\n if should_save_frontmatter and Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n return self:save_to_buffer {\n bufnr = opts.bufnr,\n insert_frontmatter = should_save_frontmatter,\n frontmatter = frontmatter,\n }\nend\n\n--- Save the note to the buffer\n---\n---@param opts { bufnr: integer|?, insert_frontmatter: boolean|?, frontmatter: table|? }|? Options.\n---\n---@return boolean updated True if the buffer lines were updated, false otherwise.\nNote.save_to_buffer = function(self, opts)\n opts = opts or {}\n\n local bufnr = opts.bufnr\n if not bufnr then\n bufnr = self.bufnr or 0\n end\n\n local cur_buf_note = Note.from_buffer(bufnr)\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n new_lines = self:frontmatter_lines(nil, opts.frontmatter)\n else\n new_lines = {}\n end\n\n if api.buffer_is_empty(bufnr) and self.title ~= nil then\n table.insert(new_lines, \"# \" .. self.title)\n end\n\n ---@type string[]\n local cur_lines = {}\n if cur_buf_note.frontmatter_end_line ~= nil then\n cur_lines = vim.api.nvim_buf_get_lines(bufnr, 0, cur_buf_note.frontmatter_end_line, false)\n end\n\n if not vim.deep_equal(cur_lines, new_lines) then\n vim.api.nvim_buf_set_lines(\n bufnr,\n 0,\n cur_buf_note.frontmatter_end_line and cur_buf_note.frontmatter_end_line or 0,\n false,\n new_lines\n )\n return true\n else\n return false\n end\nend\n\n--- Try to resolve an anchor link to a line number in the note's file.\n---\n---@param anchor_link string\n---@return obsidian.note.HeaderAnchor|?\nNote.resolve_anchor_link = function(self, anchor_link)\n anchor_link = util.standardize_anchor(anchor_link)\n\n if self.anchor_links ~= nil then\n return self.anchor_links[anchor_link]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_anchor_links = true })\n self.anchor_links = n.anchor_links\n return n:resolve_anchor_link(anchor_link)\nend\n\n--- Try to resolve a block identifier.\n---\n---@param block_id string\n---\n---@return obsidian.note.Block|?\nNote.resolve_block = function(self, block_id)\n block_id = util.standardize_block(block_id)\n\n if self.blocks ~= nil then\n return self.blocks[block_id]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_blocks = true })\n self.blocks = n.blocks\n return self.blocks[block_id]\nend\n\n--- Open a note in a buffer.\n---@param opts { line: integer|?, col: integer|?, open_strategy: obsidian.config.OpenStrategy|?, sync: boolean|?, callback: fun(bufnr: integer)|? }|?\nNote.open = function(self, opts)\n opts = opts or {}\n\n local path = self.path\n\n local function open_it()\n local open_cmd = api.get_open_strategy(opts.open_strategy and opts.open_strategy or Obsidian.opts.open_notes_in)\n ---@cast path obsidian.Path\n local bufnr = api.open_buffer(path, { line = opts.line, col = opts.col, cmd = open_cmd })\n if opts.callback then\n opts.callback(bufnr)\n end\n end\n\n if opts.sync then\n open_it()\n else\n vim.schedule(open_it)\n end\nend\n\nreturn Note\n"], ["/obsidian.nvim/lua/obsidian/commands/rename.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal util = require \"obsidian.util\"\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal enumerate, zip = util.enumerate, util.zip\n\nlocal resolve_note = function(query, opts)\n opts = opts or {}\n return require(\"obsidian.async\").block_on(function(cb)\n print(query)\n return search.resolve_note_async(query, cb, { notes = opts.notes })\n end, 5000)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n -- Resolve the note to rename.\n ---@type boolean\n local is_current_buf\n ---@type integer|?\n local cur_note_bufnr\n ---@type obsidian.Path\n local cur_note_path\n ---@type obsidian.Note\n local cur_note, cur_note_id\n\n local cur_link = api.cursor_link()\n if not cur_link then\n -- rename current note\n is_current_buf = true\n cur_note_bufnr = assert(vim.fn.bufnr())\n cur_note_path = Path.buffer(cur_note_bufnr)\n cur_note = Note.from_file(cur_note_path)\n cur_note_id = tostring(cur_note.id)\n else\n -- rename note under the cursor\n local link_id = util.parse_link(cur_link)\n local notes = { resolve_note(link_id) }\n if #notes == 0 then\n log.err(\"Failed to resolve '%s' to a note\", cur_link)\n return\n elseif #notes > 1 then\n log.err(\"Failed to resolve '%s' to a single note, found %d matches\", cur_link, #notes)\n return\n else\n cur_note = notes[1]\n end\n\n is_current_buf = false\n cur_note_id = tostring(cur_note.id)\n cur_note_path = cur_note.path\n for bufnr, bufpath in api.get_named_buffers() do\n if bufpath == cur_note_path then\n cur_note_bufnr = bufnr\n break\n end\n end\n end\n\n -- Validate args.\n local dry_run = false\n ---@type string|?\n local arg\n\n if data.args == \"--dry-run\" then\n dry_run = true\n data.args = nil\n end\n\n if data.args ~= nil and string.len(data.args) > 0 then\n arg = vim.trim(data.args)\n else\n arg = api.input(\"Enter new note ID/name/path: \", { completion = \"file\", default = cur_note_id })\n if not arg or string.len(arg) == 0 then\n log.warn \"Rename aborted\"\n return\n end\n end\n\n if vim.endswith(arg, \" --dry-run\") then\n dry_run = true\n arg = vim.trim(string.sub(arg, 1, -string.len \" --dry-run\" - 1))\n end\n\n assert(cur_note_path)\n local dirname = assert(cur_note_path:parent(), string.format(\"failed to resolve parent of '%s'\", cur_note_path))\n\n -- Parse new note ID / path from args.\n local parts = vim.split(arg, \"/\", { plain = true })\n local new_note_id = parts[#parts]\n if new_note_id == \"\" then\n log.err \"Invalid new note ID\"\n return\n elseif vim.endswith(new_note_id, \".md\") then\n new_note_id = string.sub(new_note_id, 1, -4)\n end\n\n ---@type obsidian.Path\n local new_note_path\n if #parts > 1 then\n parts[#parts] = nil\n new_note_path = Obsidian.dir:joinpath(unpack(compat.flatten { parts, new_note_id })):with_suffix \".md\"\n else\n new_note_path = (dirname / new_note_id):with_suffix \".md\"\n end\n\n if new_note_id == cur_note_id then\n log.warn \"New note ID is the same, doing nothing\"\n return\n end\n\n -- Get confirmation before continuing.\n local confirmation\n if not dry_run then\n confirmation = api.confirm(\n \"Renaming '\"\n .. cur_note_id\n .. \"' to '\"\n .. new_note_id\n .. \"'...\\n\"\n .. \"This will write all buffers and potentially modify a lot of files. If you're using version control \"\n .. \"with your vault it would be a good idea to commit the current state of your vault before running this.\\n\"\n .. \"You can also do a dry run of this by running ':Obsidian rename \"\n .. arg\n .. \" --dry-run'.\\n\"\n .. \"Do you want to continue?\"\n )\n else\n confirmation = api.confirm(\n \"Dry run: renaming '\" .. cur_note_id .. \"' to '\" .. new_note_id .. \"'...\\n\" .. \"Do you want to continue?\"\n )\n end\n\n if not confirmation then\n log.warn \"Rename aborted\"\n return\n end\n\n ---@param fn function\n local function quietly(fn, ...)\n local ok, res = pcall(fn, ...)\n if not ok then\n error(res)\n end\n end\n\n -- Write all buffers.\n quietly(vim.cmd.wall)\n\n -- Rename the note file and remove or rename the corresponding buffer, if there is one.\n if cur_note_bufnr ~= nil then\n if is_current_buf then\n -- If we're renaming the note of a current buffer, save as the new path.\n if not dry_run then\n quietly(vim.cmd.saveas, tostring(new_note_path))\n local new_bufnr_current_note = vim.fn.bufnr(tostring(cur_note_path))\n quietly(vim.cmd.bdelete, new_bufnr_current_note)\n vim.fn.delete(tostring(cur_note_path))\n else\n log.info(\"Dry run: saving current buffer as '\" .. tostring(new_note_path) .. \"' and removing old file\")\n end\n else\n -- For the non-current buffer the best we can do is delete the buffer (we've already saved it above)\n -- and then make a file-system call to rename the file.\n if not dry_run then\n quietly(vim.cmd.bdelete, cur_note_bufnr)\n cur_note_path:rename(new_note_path)\n else\n log.info(\n \"Dry run: removing buffer '\"\n .. tostring(cur_note_path)\n .. \"' and renaming file to '\"\n .. tostring(new_note_path)\n .. \"'\"\n )\n end\n end\n else\n -- When the note is not loaded into a buffer we just need to rename the file.\n if not dry_run then\n cur_note_path:rename(new_note_path)\n else\n log.info(\"Dry run: renaming file '\" .. tostring(cur_note_path) .. \"' to '\" .. tostring(new_note_path) .. \"'\")\n end\n end\n\n -- We need to update its frontmatter note_id\n -- to account for the rename.\n cur_note.id = new_note_id\n cur_note.path = Path.new(new_note_path)\n if not dry_run then\n cur_note:save()\n else\n log.info(\"Dry run: updating frontmatter of '\" .. tostring(new_note_path) .. \"'\")\n end\n\n local cur_note_rel_path = assert(cur_note_path:vault_relative_path { strict = true })\n local new_note_rel_path = assert(new_note_path:vault_relative_path { strict = true })\n\n -- Search notes on disk for any references to `cur_note_id`.\n -- We look for the following forms of references:\n -- * '[[cur_note_id]]'\n -- * '[[cur_note_id|ALIAS]]'\n -- * '[[cur_note_id\\|ALIAS]]' (a wiki link within a table)\n -- * '[ALIAS](cur_note_id)'\n -- And all of the above with relative paths (from the vault root) to the note instead of just the note ID,\n -- with and without the \".md\" suffix.\n -- Another possible form is [[ALIAS]], but we don't change the note's aliases when renaming\n -- so those links will still be valid.\n ---@param ref_link string\n ---@return string[]\n local function get_ref_forms(ref_link)\n return {\n \"[[\" .. ref_link .. \"]]\",\n \"[[\" .. ref_link .. \"|\",\n \"[[\" .. ref_link .. \"\\\\|\",\n \"[[\" .. ref_link .. \"#\",\n \"](\" .. ref_link .. \")\",\n \"](\" .. ref_link .. \"#\",\n }\n end\n\n local reference_forms = compat.flatten {\n get_ref_forms(cur_note_id),\n get_ref_forms(cur_note_rel_path),\n get_ref_forms(string.sub(cur_note_rel_path, 1, -4)),\n }\n local replace_with = compat.flatten {\n get_ref_forms(new_note_id),\n get_ref_forms(new_note_rel_path),\n get_ref_forms(string.sub(new_note_rel_path, 1, -4)),\n }\n\n local executor = AsyncExecutor.new()\n\n local file_count = 0\n local replacement_count = 0\n local all_tasks_submitted = false\n\n ---@param path string\n ---@return integer\n local function replace_refs(path)\n --- Read lines, replacing refs as we go.\n local count = 0\n local lines = {}\n local f = io.open(path, \"r\")\n assert(f)\n for line_num, line in enumerate(f:lines \"*L\") do\n for ref, replacement in zip(reference_forms, replace_with) do\n local n\n line, n = string.gsub(line, vim.pesc(ref), replacement)\n if dry_run and n > 0 then\n log.info(\n \"Dry run: '\"\n .. tostring(path)\n .. \"':\"\n .. line_num\n .. \" Replacing \"\n .. n\n .. \" occurrence(s) of '\"\n .. ref\n .. \"' with '\"\n .. replacement\n .. \"'\"\n )\n end\n count = count + n\n end\n lines[#lines + 1] = line\n end\n f:close()\n\n --- Write the new lines back.\n if not dry_run and count > 0 then\n f = io.open(path, \"w\")\n assert(f)\n f:write(unpack(lines))\n f:close()\n end\n\n return count\n end\n\n local function on_search_match(match)\n local path = tostring(Path.new(match.path.text):resolve { strict = true })\n file_count = file_count + 1\n executor:submit(replace_refs, function(count)\n replacement_count = replacement_count + count\n end, path)\n end\n\n search.search_async(\n Obsidian.dir,\n reference_forms,\n { fixed_strings = true, max_count_per_file = 1 },\n on_search_match,\n function(_)\n all_tasks_submitted = true\n end\n )\n\n -- Wait for all tasks to get submitted.\n vim.wait(2000, function()\n return all_tasks_submitted\n end, 50, false)\n\n -- Then block until all tasks are finished.\n executor:join(2000)\n\n local prefix = dry_run and \"Dry run: replaced \" or \"Replaced \"\n log.info(prefix .. replacement_count .. \" reference(s) across \" .. file_count .. \" file(s)\")\n\n -- In case the files of any current buffers were changed.\n vim.cmd.checktime()\nend\n"], ["/obsidian.nvim/lua/obsidian/search.lua", "local Path = require \"obsidian.path\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\nlocal run_job_async = require(\"obsidian.async\").run_job_async\nlocal compat = require \"obsidian.compat\"\nlocal log = require \"obsidian.log\"\nlocal block_on = require(\"obsidian.async\").block_on\n\nlocal M = {}\n\nM._BASE_CMD = { \"rg\", \"--no-config\", \"--type=md\" }\nM._SEARCH_CMD = compat.flatten { M._BASE_CMD, \"--json\" }\nM._FIND_CMD = compat.flatten { M._BASE_CMD, \"--files\" }\n\n---@enum obsidian.search.RefTypes\nM.RefTypes = {\n WikiWithAlias = \"WikiWithAlias\",\n Wiki = \"Wiki\",\n Markdown = \"Markdown\",\n NakedUrl = \"NakedUrl\",\n FileUrl = \"FileUrl\",\n MailtoUrl = \"MailtoUrl\",\n Tag = \"Tag\",\n BlockID = \"BlockID\",\n Highlight = \"Highlight\",\n}\n\n---@enum obsidian.search.Patterns\nM.Patterns = {\n -- Tags\n TagCharsOptional = \"[A-Za-z0-9_/-]*\",\n TagCharsRequired = \"[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\", -- assumes tag is at least 2 chars\n Tag = \"#[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\",\n\n -- Miscellaneous\n Highlight = \"==[^=]+==\", -- ==text==\n\n -- References\n WikiWithAlias = \"%[%[[^][%|]+%|[^%]]+%]%]\", -- [[xxx|yyy]]\n Wiki = \"%[%[[^][%|]+%]%]\", -- [[xxx]]\n Markdown = \"%[[^][]+%]%([^%)]+%)\", -- [yyy](xxx)\n NakedUrl = \"https?://[a-zA-Z0-9._-@]+[a-zA-Z0-9._#/=&?:+%%-@]+[a-zA-Z0-9/]\", -- https://xyz.com\n FileUrl = \"file:/[/{2}]?.*\", -- file:///\n MailtoUrl = \"mailto:.*\", -- mailto:emailaddress\n BlockID = util.BLOCK_PATTERN .. \"$\", -- ^hello-world\n}\n\n---@type table\nM.PatternConfig = {\n [M.RefTypes.Tag] = { ignore_if_escape_prefix = true },\n}\n\n--- Find all matches of a pattern\n---\n---@param s string\n---@param pattern_names obsidian.search.RefTypes[]\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_matches = function(s, pattern_names)\n -- First find all inline code blocks so we can skip reference matches inside of those.\n local inline_code_blocks = {}\n for m_start, m_end in util.gfind(s, \"`[^`]*`\") do\n inline_code_blocks[#inline_code_blocks + 1] = { m_start, m_end }\n end\n\n local matches = {}\n for pattern_name in iter(pattern_names) do\n local pattern = M.Patterns[pattern_name]\n local pattern_cfg = M.PatternConfig[pattern_name]\n local search_start = 1\n while search_start < #s do\n local m_start, m_end = string.find(s, pattern, search_start)\n if m_start ~= nil and m_end ~= nil then\n -- Check if we're inside a code block.\n local inside_code_block = false\n for code_block_boundary in iter(inline_code_blocks) do\n if code_block_boundary[1] < m_start and m_end < code_block_boundary[2] then\n inside_code_block = true\n break\n end\n end\n\n if not inside_code_block then\n -- Check if this match overlaps with any others (e.g. a naked URL match would be contained in\n -- a markdown URL).\n local overlap = false\n for match in iter(matches) do\n if (match[1] <= m_start and m_start <= match[2]) or (match[1] <= m_end and m_end <= match[2]) then\n overlap = true\n break\n end\n end\n\n -- Check if we should skip to an escape sequence before the pattern.\n local skip_due_to_escape = false\n if\n pattern_cfg ~= nil\n and pattern_cfg.ignore_if_escape_prefix\n and string.sub(s, m_start - 1, m_start - 1) == [[\\]]\n then\n skip_due_to_escape = true\n end\n\n if not overlap and not skip_due_to_escape then\n matches[#matches + 1] = { m_start, m_end, pattern_name }\n end\n end\n\n search_start = m_end\n else\n break\n end\n end\n end\n\n -- Sort results by position.\n table.sort(matches, function(a, b)\n return a[1] < b[1]\n end)\n\n return matches\nend\n\n--- Find inline highlights\n---\n---@param s string\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_highlight = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Highlight })) do\n -- Remove highlights that begin/end with whitespace\n local match_start, match_end, _ = unpack(match)\n local text = string.sub(s, match_start + 2, match_end - 2)\n if vim.trim(text) == text then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n---@class obsidian.search.FindRefsOpts\n---\n---@field include_naked_urls boolean|?\n---@field include_tags boolean|?\n---@field include_file_urls boolean|?\n---@field include_block_ids boolean|?\n\n--- Find refs and URLs.\n---@param s string the string to search\n---@param opts obsidian.search.FindRefsOpts|?\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_refs = function(s, opts)\n opts = opts and opts or {}\n\n local pattern_names = { M.RefTypes.WikiWithAlias, M.RefTypes.Wiki, M.RefTypes.Markdown }\n if opts.include_naked_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.NakedUrl\n end\n if opts.include_tags then\n pattern_names[#pattern_names + 1] = M.RefTypes.Tag\n end\n if opts.include_file_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.FileUrl\n end\n if opts.include_block_ids then\n pattern_names[#pattern_names + 1] = M.RefTypes.BlockID\n end\n\n return M.find_matches(s, pattern_names)\nend\n\n--- Find all tags in a string.\n---@param s string the string to search\n---\n---@return {[1]: integer, [2]: integer, [3]: obsidian.search.RefTypes}[]\nM.find_tags = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Tag })) do\n local st, ed, m_type = unpack(match)\n local match_string = s:sub(st, ed)\n if m_type == M.RefTypes.Tag and not util.is_hex_color(match_string) then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n--- Replace references of the form '[[xxx|xxx]]', '[[xxx]]', or '[xxx](xxx)' with their title.\n---\n---@param s string\n---\n---@return string\nM.replace_refs = function(s)\n local out, _ = string.gsub(s, \"%[%[[^%|%]]+%|([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[%[([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[([^%]]+)%]%([^%)]+%)\", \"%1\")\n return out\nend\n\n--- Find all refs in a string and replace with their titles.\n---\n---@param s string\n--\n---@return string\n---@return table\n---@return string[]\nM.find_and_replace_refs = function(s)\n local pieces = {}\n local refs = {}\n local is_ref = {}\n local matches = M.find_refs(s)\n local last_end = 1\n for _, match in pairs(matches) do\n local m_start, m_end, _ = unpack(match)\n assert(type(m_start) == \"number\")\n if last_end < m_start then\n table.insert(pieces, string.sub(s, last_end, m_start - 1))\n table.insert(is_ref, false)\n end\n local ref_str = string.sub(s, m_start, m_end)\n table.insert(pieces, M.replace_refs(ref_str))\n table.insert(refs, ref_str)\n table.insert(is_ref, true)\n last_end = m_end + 1\n end\n\n local indices = {}\n local length = 0\n for i, piece in ipairs(pieces) do\n local i_end = length + string.len(piece)\n if is_ref[i] then\n table.insert(indices, { length + 1, i_end })\n end\n length = i_end\n end\n\n return table.concat(pieces, \"\"), indices, refs\nend\n\n--- Find all code block boundaries in a list of lines.\n---\n---@param lines string[]\n---\n---@return { [1]: integer, [2]: integer }[]\nM.find_code_blocks = function(lines)\n ---@type { [1]: integer, [2]: integer }[]\n local blocks = {}\n ---@type integer|?\n local start_idx\n for i, line in ipairs(lines) do\n if string.match(line, \"^%s*```.*```%s*$\") then\n table.insert(blocks, { i, i })\n start_idx = nil\n elseif string.match(line, \"^%s*```\") then\n if start_idx ~= nil then\n table.insert(blocks, { start_idx, i })\n start_idx = nil\n else\n start_idx = i\n end\n end\n end\n return blocks\nend\n\n---@class obsidian.search.SearchOpts\n---\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field fixed_strings boolean|?\n---@field ignore_case boolean|?\n---@field smart_case boolean|?\n---@field exclude string[]|? paths to exclude\n---@field max_count_per_file integer|?\n---@field escape_path boolean|?\n---@field include_non_markdown boolean|?\n\nlocal SearchOpts = {}\nM.SearchOpts = SearchOpts\n\nSearchOpts.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\nend\n\n---@param one obsidian.search.SearchOpts|table\n---@param other obsidian.search.SearchOpts|table\n---@return obsidian.search.SearchOpts\nSearchOpts.merge = function(one, other)\n return vim.tbl_extend(\"force\", SearchOpts.as_tbl(one), SearchOpts.as_tbl(other))\nend\n\n---@param opts obsidian.search.SearchOpts\n---@param path string\nSearchOpts.add_exclude = function(opts, path)\n if opts.exclude == nil then\n opts.exclude = {}\n end\n opts.exclude[#opts.exclude + 1] = path\nend\n\n---@param opts obsidian.search.SearchOpts\n---@return string[]\nSearchOpts.to_ripgrep_opts = function(opts)\n local ret = {}\n\n if opts.sort_by ~= nil then\n local sort = \"sortr\" -- default sort is reverse\n if opts.sort_reversed == false then\n sort = \"sort\"\n end\n ret[#ret + 1] = \"--\" .. sort .. \"=\" .. opts.sort_by\n end\n\n if opts.fixed_strings then\n ret[#ret + 1] = \"--fixed-strings\"\n end\n\n if opts.ignore_case then\n ret[#ret + 1] = \"--ignore-case\"\n end\n\n if opts.smart_case then\n ret[#ret + 1] = \"--smart-case\"\n end\n\n if opts.exclude ~= nil then\n assert(type(opts.exclude) == \"table\")\n for path in iter(opts.exclude) do\n ret[#ret + 1] = \"-g!\" .. path\n end\n end\n\n if opts.max_count_per_file ~= nil then\n ret[#ret + 1] = \"-m=\" .. opts.max_count_per_file\n end\n\n return ret\nend\n\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_search_cmd = function(dir, term, opts)\n opts = opts and opts or {}\n\n local search_terms\n if type(term) == \"string\" then\n search_terms = { \"-e\", term }\n else\n search_terms = {}\n for t in iter(term) do\n search_terms[#search_terms + 1] = \"-e\"\n search_terms[#search_terms + 1] = t\n end\n end\n\n local path = tostring(Path.new(dir):resolve { strict = true })\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(path))\n end\n\n return compat.flatten {\n M._SEARCH_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n search_terms,\n path,\n }\nend\n\n--- Build the 'rg' command for finding files.\n---\n---@param path string|?\n---@param term string|?\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_find_cmd = function(path, term, opts)\n opts = opts and opts or {}\n\n local additional_opts = {}\n\n if term ~= nil then\n if opts.include_non_markdown then\n term = \"*\" .. term .. \"*\"\n elseif not vim.endswith(term, \".md\") then\n term = \"*\" .. term .. \"*.md\"\n else\n term = \"*\" .. term\n end\n additional_opts[#additional_opts + 1] = \"-g\"\n additional_opts[#additional_opts + 1] = term\n end\n\n if opts.ignore_case then\n additional_opts[#additional_opts + 1] = \"--glob-case-insensitive\"\n end\n\n if path ~= nil and path ~= \".\" then\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(tostring(path)))\n end\n additional_opts[#additional_opts + 1] = path\n end\n\n return compat.flatten { M._FIND_CMD, SearchOpts.to_ripgrep_opts(opts), additional_opts }\nend\n\n--- Build the 'rg' grep command for pickers.\n---\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_grep_cmd = function(opts)\n opts = opts and opts or {}\n\n return compat.flatten {\n M._BASE_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n \"--column\",\n \"--line-number\",\n \"--no-heading\",\n \"--with-filename\",\n \"--color=never\",\n }\nend\n\n---@class MatchPath\n---\n---@field text string\n\n---@class MatchText\n---\n---@field text string\n\n---@class SubMatch\n---\n---@field match MatchText\n---@field start integer\n---@field end integer\n\n---@class MatchData\n---\n---@field path MatchPath\n---@field lines MatchText\n---@field line_number integer 0-indexed\n---@field absolute_offset integer\n---@field submatches SubMatch[]\n\n--- Search markdown files in a directory for a given term. Each match is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(match: MatchData)\n---@param on_exit fun(exit_code: integer)|?\nM.search_async = function(dir, term, opts, on_match, on_exit)\n local cmd = M.build_search_cmd(dir, term, opts)\n run_job_async(cmd, function(line)\n local data = vim.json.decode(line)\n if data[\"type\"] == \"match\" then\n local match_data = data.data\n on_match(match_data)\n end\n end, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\n--- Find markdown files in a directory matching a given term. Each matching path is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(path: string)\n---@param on_exit fun(exit_code: integer)|?\nM.find_async = function(dir, term, opts, on_match, on_exit)\n local norm_dir = Path.new(dir):resolve { strict = true }\n local cmd = M.build_find_cmd(tostring(norm_dir), term, opts)\n run_job_async(cmd, on_match, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\nlocal search_defualts = {\n sort = false,\n include_templates = false,\n ignore_case = false,\n}\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nlocal _prepare_search_opts = function(opts, additional_opts)\n opts = opts or search_defualts\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n M.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = M.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---@param callback fun(path: obsidian.Path)\n---@param exit_callback fun(paths: obsidian.Path[])\nlocal _search_async = function(term, search_opts, find_opts, callback, exit_callback)\n local found = {}\n local result = {}\n local cmds_done = 0\n\n local function dedup_send(path)\n local key = tostring(path:resolve { strict = true })\n if not found[key] then\n found[key] = true\n result[#result + 1] = path\n callback(path)\n end\n end\n\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text)\n dedup_send(path)\n end\n\n local function on_find_match(path_match)\n local path = Path.new(path_match)\n dedup_send(path)\n end\n\n local function on_exit()\n cmds_done = cmds_done + 1\n if cmds_done == 2 then\n exit_callback(result)\n end\n end\n\n M.search_async(\n Obsidian.dir,\n term,\n _prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n M.find_async(Obsidian.dir, term, _prepare_search_opts(find_opts, { ignore_case = true }), on_find_match, on_exit)\nend\n\n--- An async version of `find_notes()` that runs the callback with an array of all matching notes.\n---\n---@param term string The term to search for\n---@param callback fun(notes: obsidian.Note[])\n---@param opts { search: obsidian.SearchOpts|?, notes: obsidian.note.LoadOpts|? }|?\nM.find_notes_async = function(term, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n\n ---@type table\n local paths = {}\n local num_results = 0\n local err_count = 0\n local first_err\n local first_err_path\n local notes = {}\n local Note = require \"obsidian.note\"\n\n ---@param path obsidian.Path\n local function on_path(path)\n local ok, res = pcall(Note.from_file, path, opts.notes)\n\n if ok then\n num_results = num_results + 1\n paths[tostring(path)] = num_results\n notes[#notes + 1] = res\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n end\n end\n\n local on_exit = function()\n -- Then sort by original order.\n table.sort(notes, function(a, b)\n return paths[tostring(a.path)] < paths[tostring(b.path)]\n end)\n\n -- Check for errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n callback(notes)\n end\n\n _search_async(term, opts.search, nil, on_path, on_exit)\nend\n\nM.find_notes = function(term, opts)\n opts = opts or {}\n opts.timeout = opts.timeout or 1000\n return block_on(function(cb)\n return M.find_notes_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n---@param query string\n---@param callback fun(results: obsidian.Note[])\n---@param opts { notes: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note|?\nlocal _resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n local Note = require \"obsidian.note\"\n\n -- Autocompletion for command args will have this format.\n local note_path, count = string.gsub(query, \"^.*  \", \"\")\n if count > 0 then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n local full_path = Obsidian.dir / note_path\n callback { Note.from_file(full_path, opts.notes) }\n end\n\n -- Query might be a path.\n local fname = query\n if not vim.endswith(fname, \".md\") then\n fname = fname .. \".md\"\n end\n\n local paths_to_check = { Path.new(fname), Obsidian.dir / fname }\n\n if Obsidian.opts.notes_subdir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.notes_subdir / fname\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.daily_notes.folder / fname\n end\n\n if Obsidian.buf_dir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.buf_dir / fname\n end\n\n for _, path in pairs(paths_to_check) do\n if path:is_file() then\n return callback { Note.from_file(path, opts.notes) }\n end\n end\n\n M.find_notes_async(query, function(results)\n local query_lwr = string.lower(query)\n\n -- We'll gather both exact matches (of ID, filename, and aliases) and fuzzy matches.\n -- If we end up with any exact matches, we'll return those. Otherwise we fall back to fuzzy\n -- matches.\n ---@type obsidian.Note[]\n local exact_matches = {}\n ---@type obsidian.Note[]\n local fuzzy_matches = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local reference_ids = note:reference_ids { lowercase = true }\n\n -- Check for exact match.\n if vim.list_contains(reference_ids, query_lwr) then\n table.insert(exact_matches, note)\n else\n -- Fall back to fuzzy match.\n for ref_id in iter(reference_ids) do\n if util.string_contains(ref_id, query_lwr) then\n table.insert(fuzzy_matches, note)\n break\n end\n end\n end\n end\n\n if #exact_matches > 0 then\n return callback(exact_matches)\n else\n return callback(fuzzy_matches)\n end\n end, { search = { sort = true, ignore_case = true }, notes = opts.notes })\nend\n\n--- Resolve a note, opens a picker to choose a single note when there are multiple matches.\n---\n---@param query string\n---@param callback fun(obsidian.Note)\n---@param opts { notes: obsidian.note.LoadOpts|?, prompt_title: string|?, pick: boolean }|?\n---\n---@return obsidian.Note|?\nM.resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.pick = vim.F.if_nil(opts.pick, true)\n\n _resolve_note_async(query, function(notes)\n if opts.pick then\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", query)\n return\n elseif #notes == 1 then\n return callback(notes[1])\n end\n\n -- Fall back to picker.\n vim.schedule(function()\n -- Otherwise run the preferred picker to search for notes.\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple notes matching '%s', but no picker is configured\", query)\n return\n end\n\n picker:pick_note(notes, {\n prompt_title = opts.prompt_title,\n callback = callback,\n })\n end)\n else\n callback(notes)\n end\n end, { notes = opts.notes })\nend\n\n---@class obsidian.ResolveLinkResult\n---\n---@field location string\n---@field name string\n---@field link_type obsidian.search.RefTypes\n---@field path obsidian.Path|?\n---@field note obsidian.Note|?\n---@field url string|?\n---@field line integer|?\n---@field col integer|?\n---@field anchor obsidian.note.HeaderAnchor|?\n---@field block obsidian.note.Block|?\n\n--- Resolve a link.\n---\n---@param link string\n---@param callback fun(results: obsidian.ResolveLinkResult[])\nM.resolve_link_async = function(link, callback)\n local Note = require \"obsidian.note\"\n\n local location, name, link_type\n location, name, link_type = util.parse_link(link, { include_naked_urls = true, include_file_urls = true })\n\n if location == nil or name == nil or link_type == nil then\n return callback {}\n end\n\n ---@type obsidian.ResolveLinkResult\n local res = { location = location, name = name, link_type = link_type }\n\n if util.is_url(location) then\n res.url = location\n return callback { res }\n end\n\n -- The Obsidian app will follow URL-encoded links, so we should to.\n location = vim.uri_decode(location)\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n --- Finalize the `obsidian.ResolveLinkResult` for a note while resolving block or anchor link to line.\n ---\n ---@param note obsidian.Note\n ---@return obsidian.ResolveLinkResult\n local function finalize_result(note)\n ---@type integer|?, obsidian.note.Block|?, obsidian.note.HeaderAnchor|?\n local line, block_match, anchor_match\n if block_link ~= nil then\n block_match = note:resolve_block(block_link)\n if block_match then\n line = block_match.line\n end\n elseif anchor_link ~= nil then\n anchor_match = note:resolve_anchor_link(anchor_link)\n if anchor_match then\n line = anchor_match.line\n end\n end\n\n return vim.tbl_extend(\n \"force\",\n res,\n { path = note.path, note = note, line = line, block = block_match, anchor = anchor_match }\n )\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = anchor_link and true or false,\n collect_blocks = block_link and true or false,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n res.location = vim.api.nvim_buf_get_name(0)\n local note = Note.from_buffer(0, load_opts)\n return callback { finalize_result(note) }\n end\n\n res.location = location\n\n M.resolve_note_async(location, function(notes)\n if #notes == 0 then\n local path = Path.new(location)\n if path:exists() then\n res.path = path\n return callback { res }\n else\n return callback { res }\n end\n end\n\n local matches = {}\n for _, note in ipairs(notes) do\n table.insert(matches, finalize_result(note))\n end\n\n return callback(matches)\n end, { notes = load_opts, pick = false })\nend\n\n---@class obsidian.LinkMatch\n---@field link string\n---@field line integer\n---@field start integer 0-indexed\n---@field end integer 0-indexed\n\n-- Gather all unique links from the a note.\n--\n---@param note obsidian.Note\n---@param opts { on_match: fun(link: obsidian.LinkMatch) }\n---@param callback fun(links: obsidian.LinkMatch[])\nM.find_links = function(note, opts, callback)\n ---@type obsidian.LinkMatch[]\n local matches = {}\n ---@type table\n local found = {}\n local lines = io.lines(tostring(note.path))\n\n for lnum, line in util.enumerate(lines) do\n for ref_match in vim.iter(M.find_refs(line, { include_naked_urls = true, include_file_urls = true })) do\n local m_start, m_end = unpack(ref_match)\n local link = string.sub(line, m_start, m_end)\n if not found[link] then\n local match = {\n link = link,\n line = lnum,\n start = m_start - 1,\n [\"end\"] = m_end - 1,\n }\n matches[#matches + 1] = match\n found[link] = true\n if opts.on_match then\n opts.on_match(match)\n end\n end\n end\n end\n\n callback(matches)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/util.lua", "local compat = require \"obsidian.compat\"\nlocal ts, string, table = vim.treesitter, string, table\nlocal util = {}\n\nsetmetatable(util, {\n __index = function(_, k)\n return require(\"obsidian.api\")[k] or require(\"obsidian.builtin\")[k]\n end,\n})\n\n-------------------\n--- File tools ----\n-------------------\n\n---@param file string\n---@param contents string\nutil.write_file = function(file, contents)\n local fd = assert(io.open(file, \"w+\"))\n fd:write(contents)\n fd:close()\nend\n\n-------------------\n--- Iter tools ----\n-------------------\n\n---Create an enumeration iterator over an iterable.\n---@param iterable table|string|function\n---@return function\nutil.enumerate = function(iterable)\n local iterator = vim.iter(iterable)\n local i = 0\n\n return function()\n local next = iterator()\n if next == nil then\n return nil, nil\n else\n i = i + 1\n return i, next\n end\n end\nend\n\n---Zip two iterables together.\n---@param iterable1 table|string|function\n---@param iterable2 table|string|function\n---@return function\nutil.zip = function(iterable1, iterable2)\n local iterator1 = vim.iter(iterable1)\n local iterator2 = vim.iter(iterable2)\n\n return function()\n local next1 = iterator1()\n local next2 = iterator2()\n if next1 == nil or next2 == nil then\n return nil\n else\n return next1, next2\n end\n end\nend\n\n-------------------\n--- Table tools ---\n-------------------\n\n---Check if an object is an array-like table.\n--- TODO: after 0.12 replace with vim.islist\n---\n---@param t any\n---@return boolean\nutil.islist = function(t)\n return compat.is_list(t)\nend\n\n---Return a new list table with only the unique values of the original table.\n---\n---@param t table\n---@return any[]\nutil.tbl_unique = function(t)\n local found = {}\n for _, val in pairs(t) do\n found[val] = true\n end\n return vim.tbl_keys(found)\nend\n\n--------------------\n--- String Tools ---\n--------------------\n\n---Iterate over all matches of 'pattern' in 's'. 'gfind' is to 'find' as 'gsub' is to 'sub'.\n---@param s string\n---@param pattern string\n---@param init integer|?\n---@param plain boolean|?\nutil.gfind = function(s, pattern, init, plain)\n init = init and init or 1\n\n return function()\n if init < #s then\n local m_start, m_end = string.find(s, pattern, init, plain)\n if m_start ~= nil and m_end ~= nil then\n init = m_end + 1\n return m_start, m_end\n end\n end\n return nil\n end\nend\n\nlocal char_to_hex = function(c)\n return string.format(\"%%%02X\", string.byte(c))\nend\n\n--- Encode a string into URL-safe version.\n---\n---@param str string\n---@param opts { keep_path_sep: boolean|? }|?\n---\n---@return string\nutil.urlencode = function(str, opts)\n opts = opts or {}\n local url = str\n url = url:gsub(\"\\n\", \"\\r\\n\")\n url = url:gsub(\"([%(%)%*%?%[%]%$\\\"':<>|\\\\'{}])\", char_to_hex)\n if not opts.keep_path_sep then\n url = url:gsub(\"/\", char_to_hex)\n end\n\n -- Spaces in URLs are always safely encoded with `%20`, but not always safe\n -- with `+`. For example, `+` in a query param's value will be interpreted\n -- as a literal plus-sign if the decoder is using JavaScript's `decodeURI`\n -- function.\n url = url:gsub(\" \", \"%%20\")\n return url\nend\n\nutil.is_hex_color = function(s)\n return (s:match \"^#%x%x%x$\" or s:match \"^#%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x%x%x$\")\n ~= nil\nend\n\n---Match the case of 'key' to the given 'prefix' of the key.\n---\n---@param prefix string\n---@param key string\n---@return string|?\nutil.match_case = function(prefix, key)\n local out_chars = {}\n for i = 1, string.len(key) do\n local c_key = string.sub(key, i, i)\n local c_pre = string.sub(prefix, i, i)\n if c_pre:lower() == c_key:lower() then\n table.insert(out_chars, c_pre)\n elseif c_pre:len() > 0 then\n return nil\n else\n table.insert(out_chars, c_key)\n end\n end\n return table.concat(out_chars, \"\")\nend\n\n---Check if a string is a checkbox list item\n---\n---Supported checboox lists:\n--- - [ ] foo\n--- - [x] foo\n--- + [x] foo\n--- * [ ] foo\n--- 1. [ ] foo\n--- 1) [ ] foo\n---\n---@param s string\n---@return boolean\nutil.is_checkbox = function(s)\n -- - [ ] and * [ ] and + [ ]\n if string.match(s, \"^%s*[-+*]%s+%[.%]\") ~= nil then\n return true\n end\n -- 1. [ ] and 1) [ ]\n if string.match(s, \"^%s*%d+[%.%)]%s+%[.%]\") ~= nil then\n return true\n end\n return false\nend\n\n---Check if a string is a valid URL.\n---@param s string\n---@return boolean\nutil.is_url = function(s)\n local search = require \"obsidian.search\"\n\n if\n string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.NakedUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.FileUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.MailtoUrl] .. \"$\")\n then\n return true\n else\n return false\n end\nend\n\n---Checks if a given string represents an image file based on its suffix.\n---\n---@param s string: The input string to check.\n---@return boolean: Returns true if the string ends with a supported image suffix, false otherwise.\nutil.is_img = function(s)\n for _, suffix in ipairs { \".png\", \".jpg\", \".jpeg\", \".heic\", \".gif\", \".svg\", \".ico\" } do\n if vim.endswith(s, suffix) then\n return true\n end\n end\n return false\nend\n\n-- This function removes a single backslash within double square brackets\nutil.unescape_single_backslash = function(text)\n return text:gsub(\"(%[%[[^\\\\]+)\\\\(%|[^\\\\]+]])\", \"%1%2\")\nend\n\nutil.string_enclosing_chars = { [[\"]], [[']] }\n\n---Count the indentation of a line.\n---@param str string\n---@return integer\nutil.count_indent = function(str)\n local indent = 0\n for i = 1, #str do\n local c = string.sub(str, i, i)\n -- space or tab both count as 1 indent\n if c == \" \" or c == \"\t\" then\n indent = indent + 1\n else\n break\n end\n end\n return indent\nend\n\n---Check if a string is only whitespace.\n---@param str string\n---@return boolean\nutil.is_whitespace = function(str)\n return string.match(str, \"^%s+$\") ~= nil\nend\n\n---Get the substring of `str` starting from the first character and up to the stop character,\n---ignoring any enclosing characters (like double quotes) and stop characters that are within the\n---enclosing characters. For example, if `str = [=[\"foo\", \"bar\"]=]` and `stop_char = \",\"`, this\n---would return the string `[=[foo]=]`.\n---\n---@param str string\n---@param stop_chars string[]\n---@param keep_stop_char boolean|?\n---@return string|?, string\nutil.next_item = function(str, stop_chars, keep_stop_char)\n local og_str = str\n\n -- Check for enclosing characters.\n local enclosing_char = nil\n local first_char = string.sub(str, 1, 1)\n for _, c in ipairs(util.string_enclosing_chars) do\n if first_char == c then\n enclosing_char = c\n str = string.sub(str, 2)\n break\n end\n end\n\n local result\n local hits\n\n for _, stop_char in ipairs(stop_chars) do\n -- First check for next item when `stop_char` is present.\n if enclosing_char ~= nil then\n result, hits = string.gsub(\n str,\n \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*\" .. stop_char .. \".*\",\n \"%1%2\"\n )\n result = enclosing_char .. result .. enclosing_char\n else\n result, hits = string.gsub(str, \"([^\" .. stop_char .. \"]+)\" .. stop_char .. \".*\", \"%1\")\n end\n if hits ~= 0 then\n local i = string.find(str, stop_char, string.len(result), true)\n if keep_stop_char then\n return result .. stop_char, string.sub(str, i + 1)\n else\n return result, string.sub(str, i + 1)\n end\n end\n\n -- Now check for next item without the `stop_char` after.\n if not keep_stop_char and enclosing_char ~= nil then\n result, hits = string.gsub(str, \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*$\", \"%1%2\")\n result = enclosing_char .. result .. enclosing_char\n elseif not keep_stop_char then\n result = str\n hits = 1\n else\n result = nil\n hits = 0\n end\n if hits ~= 0 then\n if keep_stop_char then\n result = result .. stop_char\n end\n return result, \"\"\n end\n end\n\n return nil, og_str\nend\n\n---Strip whitespace from the right end of a string.\n---@param str string\n---@return string\nutil.rstrip_whitespace = function(str)\n str = string.gsub(str, \"%s+$\", \"\")\n return str\nend\n\n---Strip whitespace from the left end of a string.\n---@param str string\n---@param limit integer|?\n---@return string\nutil.lstrip_whitespace = function(str, limit)\n if limit ~= nil then\n local num_found = 0\n while num_found < limit do\n str = string.gsub(str, \"^%s\", \"\")\n num_found = num_found + 1\n end\n else\n str = string.gsub(str, \"^%s+\", \"\")\n end\n return str\nend\n\n---Strip enclosing characters like quotes from a string.\n---@param str string\n---@return string\nutil.strip_enclosing_chars = function(str)\n local c_start = string.sub(str, 1, 1)\n local c_end = string.sub(str, #str, #str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if c_start == enclosing_char and c_end == enclosing_char then\n str = string.sub(str, 2, #str - 1)\n break\n end\n end\n return str\nend\n\n---Check if a string has enclosing characters like quotes.\n---@param str string\n---@return boolean\nutil.has_enclosing_chars = function(str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if vim.startswith(str, enclosing_char) and vim.endswith(str, enclosing_char) then\n return true\n end\n end\n return false\nend\n\n---Strip YAML comments from a string.\n---@param str string\n---@return string\nutil.strip_comments = function(str)\n if vim.startswith(str, \"# \") then\n return \"\"\n elseif not util.has_enclosing_chars(str) then\n return select(1, string.gsub(str, [[%s+#%s.*$]], \"\"))\n else\n return str\n end\nend\n\n---Check if a string contains a substring.\n---@param str string\n---@param substr string\n---@return boolean\nutil.string_contains = function(str, substr)\n local i = string.find(str, substr, 1, true)\n return i ~= nil\nend\n\n--------------------\n--- Date helpers ---\n--------------------\n\n---Determines if the given date is a working day (not weekend)\n---\n---@param time integer\n---\n---@return boolean\nutil.is_working_day = function(time)\n local is_saturday = (os.date(\"%w\", time) == \"6\")\n local is_sunday = (os.date(\"%w\", time) == \"0\")\n return not (is_saturday or is_sunday)\nend\n\n--- Returns the previous day from given time\n---\n--- @param time integer\n--- @return integer\nutil.previous_day = function(time)\n return time - (24 * 60 * 60)\nend\n---\n--- Returns the next day from given time\n---\n--- @param time integer\n--- @return integer\nutil.next_day = function(time)\n return time + (24 * 60 * 60)\nend\n\n---Determines the last working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_before = function(time)\n local previous_day = util.previous_day(time)\n if util.is_working_day(previous_day) then\n return previous_day\n else\n return util.working_day_before(previous_day)\n end\nend\n\n---Determines the next working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_after = function(time)\n local next_day = util.next_day(time)\n if util.is_working_day(next_day) then\n return next_day\n else\n return util.working_day_after(next_day)\n end\nend\n\n---@param link string\n---@param opts { include_naked_urls: boolean|?, include_file_urls: boolean|?, include_block_ids: boolean|?, link_type: obsidian.search.RefTypes|? }|?\n---\n---@return string|?, string|?, obsidian.search.RefTypes|?\nutil.parse_link = function(link, opts)\n local search = require \"obsidian.search\"\n\n opts = opts and opts or {}\n\n local link_type = opts.link_type\n if link_type == nil then\n for match in\n vim.iter(search.find_refs(link, {\n include_naked_urls = opts.include_naked_urls,\n include_file_urls = opts.include_file_urls,\n include_block_ids = opts.include_block_ids,\n }))\n do\n local _, _, m_type = unpack(match)\n if m_type then\n link_type = m_type\n break\n end\n end\n end\n\n if link_type == nil then\n return nil\n end\n\n local link_location, link_name\n if link_type == search.RefTypes.Markdown then\n link_location = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%2\")\n link_name = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%1\")\n elseif link_type == search.RefTypes.NakedUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.FileUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.WikiWithAlias then\n link = util.unescape_single_backslash(link)\n -- remove boundary brackets, e.g. '[[XXX|YYY]]' -> 'XXX|YYY'\n link = link:sub(3, #link - 2)\n -- split on the \"|\"\n local split_idx = link:find \"|\"\n link_location = link:sub(1, split_idx - 1)\n link_name = link:sub(split_idx + 1)\n elseif link_type == search.RefTypes.Wiki then\n -- remove boundary brackets, e.g. '[[YYY]]' -> 'YYY'\n link = link:sub(3, #link - 2)\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.BlockID then\n link_location = util.standardize_block(link)\n link_name = link\n else\n error(\"not implemented for \" .. link_type)\n end\n\n return link_location, link_name, link_type\nend\n\n------------------------------------\n-- Miscellaneous helper functions --\n------------------------------------\n---@param anchor obsidian.note.HeaderAnchor\n---@return string\nutil.format_anchor_label = function(anchor)\n return string.format(\" ❯ %s\", anchor.header)\nend\n\n-- We are very loose here because obsidian allows pretty much anything\nutil.ANCHOR_LINK_PATTERN = \"#[%w%d\\128-\\255][^#]*\"\n\nutil.BLOCK_PATTERN = \"%^[%w%d][%w%d-]*\"\n\nutil.BLOCK_LINK_PATTERN = \"#\" .. util.BLOCK_PATTERN\n\n--- Strip anchor links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_anchor_links = function(line)\n ---@type string|?\n local anchor\n\n while true do\n local anchor_match = string.match(line, util.ANCHOR_LINK_PATTERN .. \"$\")\n if anchor_match then\n anchor = anchor or \"\"\n anchor = anchor_match .. anchor\n line = string.sub(line, 1, -anchor_match:len() - 1)\n else\n break\n end\n end\n\n return line, anchor and util.standardize_anchor(anchor)\nend\n\n--- Parse a block line from a line.\n---\n---@param line string\n---\n---@return string|?\nutil.parse_block = function(line)\n local block_match = string.match(line, util.BLOCK_PATTERN .. \"$\")\n return block_match\nend\n\n--- Strip block links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_block_links = function(line)\n local block_match = string.match(line, util.BLOCK_LINK_PATTERN .. \"$\")\n if block_match then\n line = string.sub(line, 1, -block_match:len() - 1)\n end\n return line, block_match\nend\n\n--- Standardize a block identifier.\n---@param block_id string\n---@return string\nutil.standardize_block = function(block_id)\n if vim.startswith(block_id, \"#\") then\n block_id = string.sub(block_id, 2)\n end\n\n if not vim.startswith(block_id, \"^\") then\n block_id = \"^\" .. block_id\n end\n\n return block_id\nend\n\n--- Check if a line is a markdown header.\n---@param line string\n---@return boolean\nutil.is_header = function(line)\n if string.match(line, \"^#+%s+[%w]+\") then\n return true\n else\n return false\n end\nend\n\n--- Get the header level of a line.\n---@param line string\n---@return integer\nutil.header_level = function(line)\n local headers, match_count = string.gsub(line, \"^(#+)%s+[%w]+.*\", \"%1\")\n if match_count > 0 then\n return string.len(headers)\n else\n return 0\n end\nend\n\n---@param line string\n---@return { header: string, level: integer, anchor: string }|?\nutil.parse_header = function(line)\n local header_start, header = string.match(line, \"^(#+)%s+([^%s]+.*)$\")\n if header_start and header then\n header = vim.trim(header)\n return {\n header = vim.trim(header),\n level = string.len(header_start),\n anchor = util.header_to_anchor(header),\n }\n else\n return nil\n end\nend\n\n--- Standardize a header anchor link.\n---\n---@param anchor string\n---\n---@return string\nutil.standardize_anchor = function(anchor)\n -- Lowercase everything.\n anchor = string.lower(anchor)\n -- Replace whitespace with \"-\".\n anchor = string.gsub(anchor, \"%s\", \"-\")\n -- Remove every non-alphanumeric character.\n anchor = string.gsub(anchor, \"[^#%w\\128-\\255_-]\", \"\")\n return anchor\nend\n\n--- Transform a markdown header into an link, e.g. \"# Hello World\" -> \"#hello-world\".\n---\n---@param header string\n---\n---@return string\nutil.header_to_anchor = function(header)\n -- Remove leading '#' and strip whitespace.\n local anchor = vim.trim(string.gsub(header, [[^#+%s+]], \"\"))\n return util.standardize_anchor(\"#\" .. anchor)\nend\n\n---@alias datetime_cadence \"daily\"\n\n--- Parse possible relative date macros like '@tomorrow'.\n---\n---@param macro string\n---\n---@return { macro: string, offset: integer, cadence: datetime_cadence }[]\nutil.resolve_date_macro = function(macro)\n ---@type { macro: string, offset: integer, cadence: datetime_cadence }[]\n local out = {}\n for m, offset_days in pairs { today = 0, tomorrow = 1, yesterday = -1 } do\n m = \"@\" .. m\n if vim.startswith(m, macro) then\n out[#out + 1] = { macro = m, offset = offset_days, cadence = \"daily\" }\n end\n end\n return out\nend\n\n--- Check if a string contains invalid characters.\n---\n--- @param fname string\n---\n--- @return boolean\nutil.contains_invalid_characters = function(fname)\n local invalid_chars = \"#^%[%]|\"\n return string.find(fname, \"[\" .. invalid_chars .. \"]\") ~= nil\nend\n\n---Check if a string is NaN\n---\n---@param v any\n---@return boolean\nutil.isNan = function(v)\n return tostring(v) == tostring(0 / 0)\nend\n\n---Higher order function, make sure a function is called with complete lines\n---@param fn fun(string)?\n---@return fun(string)\nutil.buffer_fn = function(fn)\n if not fn then\n return function() end\n end\n local buffer = \"\"\n return function(data)\n buffer = buffer .. data\n local lines = vim.split(buffer, \"\\n\")\n if #lines > 1 then\n for i = 1, #lines - 1 do\n fn(lines[i])\n end\n buffer = lines[#lines] -- Store remaining partial line\n end\n end\nend\n\n---@param event string\n---@param callback fun(...)\n---@param ... any\n---@return boolean success\nutil.fire_callback = function(event, callback, ...)\n local log = require \"obsidian.log\"\n if not callback then\n return false\n end\n local ok, err = pcall(callback, ...)\n if ok then\n return true\n else\n log.error(\"Error running %s callback: %s\", event, err)\n return false\n end\nend\n\n---@param node_type string | string[]\n---@return boolean\nutil.in_node = function(node_type)\n local function in_node(t)\n local node = ts.get_node()\n while node do\n if node:type() == t then\n return true\n end\n node = node:parent()\n end\n return false\n end\n if type(node_type) == \"string\" then\n return in_node(node_type)\n elseif type(node_type) == \"table\" then\n for _, t in ipairs(node_type) do\n local is_in_node = in_node(t)\n if is_in_node then\n return true\n end\n end\n end\n return false\nend\n\nreturn util\n"], ["/obsidian.nvim/lua/obsidian/config.lua", "local log = require \"obsidian.log\"\n\nlocal config = {}\n\n---@class obsidian.config\n---@field workspaces obsidian.workspace.WorkspaceSpec[]\n---@field log_level? integer\n---@field notes_subdir? string\n---@field templates? obsidian.config.TemplateOpts\n---@field new_notes_location? obsidian.config.NewNotesLocation\n---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func? fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path\n---@field wiki_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field markdown_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field preferred_link_style? obsidian.config.LinkStyle\n---@field follow_url_func? fun(url: string)\n---@field follow_img_func? fun(img: string)\n---@field note_frontmatter_func? (fun(note: obsidian.Note): table)\n---@field disable_frontmatter? (fun(fname: string?): boolean)|boolean\n---@field backlinks? obsidian.config.BacklinkOpts\n---@field completion? obsidian.config.CompletionOpts\n---@field picker? obsidian.config.PickerOpts\n---@field daily_notes? obsidian.config.DailyNotesOpts\n---@field sort_by? obsidian.config.SortBy\n---@field sort_reversed? boolean\n---@field search_max_lines? integer\n---@field open_notes_in? obsidian.config.OpenStrategy\n---@field ui? obsidian.config.UIOpts | table\n---@field attachments? obsidian.config.AttachmentsOpts\n---@field callbacks? obsidian.config.CallbackConfig\n---@field legacy_commands? boolean\n---@field statusline? obsidian.config.StatuslineOpts\n---@field footer? obsidian.config.FooterOpts\n---@field open? obsidian.config.OpenOpts\n---@field checkbox? obsidian.config.CheckboxOpts\n---@field comment? obsidian.config.CommentOpts\n\n---@class obsidian.config.ClientOpts\n---@field dir string|?\n---@field workspaces obsidian.workspace.WorkspaceSpec[]|?\n---@field log_level integer\n---@field notes_subdir string|?\n---@field templates obsidian.config.TemplateOpts\n---@field new_notes_location obsidian.config.NewNotesLocation\n---@field note_id_func (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func (fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path)|?\n---@field wiki_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field markdown_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field preferred_link_style obsidian.config.LinkStyle\n---@field follow_url_func fun(url: string)|?\n---@field follow_img_func fun(img: string)|?\n---@field note_frontmatter_func (fun(note: obsidian.Note): table)|?\n---@field disable_frontmatter (fun(fname: string?): boolean)|boolean|?\n---@field backlinks obsidian.config.BacklinkOpts\n---@field completion obsidian.config.CompletionOpts\n---@field picker obsidian.config.PickerOpts\n---@field daily_notes obsidian.config.DailyNotesOpts\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field search_max_lines integer\n---@field open_notes_in obsidian.config.OpenStrategy\n---@field ui obsidian.config.UIOpts | table\n---@field attachments obsidian.config.AttachmentsOpts\n---@field callbacks obsidian.config.CallbackConfig\n---@field legacy_commands boolean\n---@field statusline obsidian.config.StatuslineOpts\n---@field footer obsidian.config.FooterOpts\n---@field open obsidian.config.OpenOpts\n---@field checkbox obsidian.config.CheckboxOpts\n---@field comment obsidian.config.CommentOpts\n\n---@enum obsidian.config.OpenStrategy\nconfig.OpenStrategy = {\n current = \"current\",\n vsplit = \"vsplit\",\n hsplit = \"hsplit\",\n vsplit_force = \"vsplit_force\",\n hsplit_force = \"hsplit_force\",\n}\n\n---@enum obsidian.config.SortBy\nconfig.SortBy = {\n path = \"path\",\n modified = \"modified\",\n accessed = \"accessed\",\n created = \"created\",\n}\n\n---@enum obsidian.config.NewNotesLocation\nconfig.NewNotesLocation = {\n current_dir = \"current_dir\",\n notes_subdir = \"notes_subdir\",\n}\n\n---@enum obsidian.config.LinkStyle\nconfig.LinkStyle = {\n wiki = \"wiki\",\n markdown = \"markdown\",\n}\n\n---@enum obsidian.config.Picker\nconfig.Picker = {\n telescope = \"telescope.nvim\",\n fzf_lua = \"fzf-lua\",\n mini = \"mini.pick\",\n snacks = \"snacks.pick\",\n}\n\n--- Get defaults.\n---\n---@return obsidian.config.ClientOpts\nconfig.default = {\n legacy_commands = true,\n workspaces = {},\n log_level = vim.log.levels.INFO,\n notes_subdir = nil,\n new_notes_location = config.NewNotesLocation.current_dir,\n note_id_func = nil,\n wiki_link_func = require(\"obsidian.builtin\").wiki_link_id_prefix,\n markdown_link_func = require(\"obsidian.builtin\").markdown_link,\n preferred_link_style = config.LinkStyle.wiki,\n follow_url_func = vim.ui.open,\n follow_img_func = vim.ui.open,\n note_frontmatter_func = nil,\n disable_frontmatter = false,\n sort_by = \"modified\",\n sort_reversed = true,\n search_max_lines = 1000,\n open_notes_in = \"current\",\n\n ---@class obsidian.config.TemplateOpts\n ---\n ---@field folder string|obsidian.Path|?\n ---@field date_format string|?\n ---@field time_format string|?\n --- A map for custom variables, the key should be the variable and the value a function.\n --- Functions are called with obsidian.TemplateContext objects as their sole parameter.\n --- See: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Template#substitutions\n ---@field substitutions table|?\n ---@field customizations table|?\n templates = {\n folder = nil,\n date_format = nil,\n time_format = nil,\n substitutions = {},\n\n ---@class obsidian.config.CustomTemplateOpts\n ---\n ---@field notes_subdir? string\n ---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n customizations = {},\n },\n\n ---@class obsidian.config.BacklinkOpts\n ---\n ---@field parse_headers boolean\n backlinks = {\n parse_headers = true,\n },\n\n ---@class obsidian.config.CompletionOpts\n ---\n ---@field nvim_cmp? boolean\n ---@field blink? boolean\n ---@field min_chars? integer\n ---@field match_case? boolean\n ---@field create_new? boolean\n completion = (function()\n local has_nvim_cmp, _ = pcall(require, \"cmp\")\n return {\n nvim_cmp = has_nvim_cmp,\n min_chars = 2,\n match_case = true,\n create_new = true,\n }\n end)(),\n\n ---@class obsidian.config.PickerNoteMappingOpts\n ---\n ---@field new? string\n ---@field insert_link? string\n\n ---@class obsidian.config.PickerTagMappingOpts\n ---\n ---@field tag_note? string\n ---@field insert_tag? string\n\n ---@class obsidian.config.PickerOpts\n ---\n ---@field name obsidian.config.Picker|?\n ---@field note_mappings? obsidian.config.PickerNoteMappingOpts\n ---@field tag_mappings? obsidian.config.PickerTagMappingOpts\n picker = {\n name = nil,\n note_mappings = {\n new = \"\",\n insert_link = \"\",\n },\n tag_mappings = {\n tag_note = \"\",\n insert_tag = \"\",\n },\n },\n\n ---@class obsidian.config.DailyNotesOpts\n ---\n ---@field folder? string\n ---@field date_format? string\n ---@field alias_format? string\n ---@field template? string\n ---@field default_tags? string[]\n ---@field workdays_only? boolean\n daily_notes = {\n folder = nil,\n date_format = nil,\n alias_format = nil,\n default_tags = { \"daily-notes\" },\n workdays_only = true,\n },\n\n ---@class obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.CheckboxSpec : obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.UIStyleSpec\n ---@field hl_group string\n\n ---@class obsidian.config.UIOpts\n ---\n ---@field enable boolean\n ---@field ignore_conceal_warn boolean\n ---@field update_debounce integer\n ---@field max_file_length integer|?\n ---@field checkboxes table\n ---@field bullets obsidian.config.UICharSpec|?\n ---@field external_link_icon obsidian.config.UICharSpec\n ---@field reference_text obsidian.config.UIStyleSpec\n ---@field highlight_text obsidian.config.UIStyleSpec\n ---@field tags obsidian.config.UIStyleSpec\n ---@field block_ids obsidian.config.UIStyleSpec\n ---@field hl_groups table\n ui = {\n enable = true,\n ignore_conceal_warn = false,\n update_debounce = 200,\n max_file_length = 5000,\n checkboxes = {\n [\" \"] = { char = \"󰄱\", hl_group = \"obsidiantodo\" },\n [\"~\"] = { char = \"󰰱\", hl_group = \"obsidiantilde\" },\n [\"!\"] = { char = \"\", hl_group = \"obsidianimportant\" },\n [\">\"] = { char = \"\", hl_group = \"obsidianrightarrow\" },\n [\"x\"] = { char = \"\", hl_group = \"obsidiandone\" },\n },\n bullets = { char = \"•\", hl_group = \"ObsidianBullet\" },\n external_link_icon = { char = \"\", hl_group = \"ObsidianExtLinkIcon\" },\n reference_text = { hl_group = \"ObsidianRefText\" },\n highlight_text = { hl_group = \"ObsidianHighlightText\" },\n tags = { hl_group = \"ObsidianTag\" },\n block_ids = { hl_group = \"ObsidianBlockID\" },\n hl_groups = {\n ObsidianTodo = { bold = true, fg = \"#f78c6c\" },\n ObsidianDone = { bold = true, fg = \"#89ddff\" },\n ObsidianRightArrow = { bold = true, fg = \"#f78c6c\" },\n ObsidianTilde = { bold = true, fg = \"#ff5370\" },\n ObsidianImportant = { bold = true, fg = \"#d73128\" },\n ObsidianBullet = { bold = true, fg = \"#89ddff\" },\n ObsidianRefText = { underline = true, fg = \"#c792ea\" },\n ObsidianExtLinkIcon = { fg = \"#c792ea\" },\n ObsidianTag = { italic = true, fg = \"#89ddff\" },\n ObsidianBlockID = { italic = true, fg = \"#89ddff\" },\n ObsidianHighlightText = { bg = \"#75662e\" },\n },\n },\n\n ---@class obsidian.config.AttachmentsOpts\n ---\n ---Default folder to save images to, relative to the vault root (/) or current dir (.), see https://github.com/obsidian-nvim/obsidian.nvim/wiki/Images#change-image-save-location\n ---@field img_folder? string\n ---\n ---Default name for pasted images\n ---@field img_name_func? fun(): string\n ---\n ---Default text to insert for pasted images\n ---@field img_text_func? fun(path: obsidian.Path): string\n ---\n ---Whether to confirm the paste or not. Defaults to true.\n ---@field confirm_img_paste? boolean\n attachments = {\n img_folder = \"assets/imgs\",\n img_text_func = require(\"obsidian.builtin\").img_text_func,\n img_name_func = function()\n return string.format(\"Pasted image %s\", os.date \"%Y%m%d%H%M%S\")\n end,\n confirm_img_paste = true,\n },\n\n ---@class obsidian.config.CallbackConfig\n ---\n ---Runs right after the `obsidian.Client` is initialized.\n ---@field post_setup? fun(client: obsidian.Client)\n ---\n ---Runs when entering a note buffer.\n ---@field enter_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs when leaving a note buffer.\n ---@field leave_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs right before writing a note buffer.\n ---@field pre_write_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs anytime the workspace is set/changed.\n ---@field post_set_workspace? fun(client: obsidian.Client, workspace: obsidian.Workspace)\n callbacks = {},\n\n ---@class obsidian.config.StatuslineOpts\n ---\n ---@field format? string\n ---@field enabled? boolean\n statusline = {\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n enabled = true,\n },\n\n ---@class obsidian.config.FooterOpts\n ---\n ---@field enabled? boolean\n ---@field format? string\n ---@field hl_group? string\n ---@field separator? string|false Set false to disable separator; set an empty string to insert a blank line separator.\n footer = {\n enabled = true,\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n hl_group = \"Comment\",\n separator = string.rep(\"-\", 80),\n },\n\n ---@class obsidian.config.OpenOpts\n ---\n ---Opens the file with current line number\n ---@field use_advanced_uri? boolean\n ---\n ---Function to do the opening, default to vim.ui.open\n ---@field func? fun(uri: string)\n open = {\n use_advanced_uri = false,\n func = vim.ui.open,\n },\n\n ---@class obsidian.config.CheckboxOpts\n ---\n ---@field enabled? boolean\n ---\n ---Order of checkbox state chars, e.g. { \" \", \"x\" }\n ---@field order? string[]\n ---\n ---Whether to create new checkbox on paragraphs\n ---@field create_new? boolean\n checkbox = {\n enabled = true,\n create_new = true,\n order = { \" \", \"~\", \"!\", \">\", \"x\" },\n },\n\n ---@class obsidian.config.CommentOpts\n ---@field enabled boolean\n comment = {\n enabled = false,\n },\n}\n\nlocal tbl_override = function(defaults, overrides)\n local out = vim.tbl_extend(\"force\", defaults, overrides)\n for k, v in pairs(out) do\n if v == vim.NIL then\n out[k] = nil\n end\n end\n return out\nend\n\nlocal function deprecate(name, alternative, version)\n vim.deprecate(name, alternative, version, \"obsidian.nvim\", false)\nend\n\n--- Normalize options.\n---\n---@param opts table\n---@param defaults obsidian.config.ClientOpts|?\n---\n---@return obsidian.config.ClientOpts\nconfig.normalize = function(opts, defaults)\n local builtin = require \"obsidian.builtin\"\n local util = require \"obsidian.util\"\n\n if not defaults then\n defaults = config.default\n end\n\n -------------------------------------------------------------------------------------\n -- Rename old fields for backwards compatibility and warn about deprecated fields. --\n -------------------------------------------------------------------------------------\n\n if opts.ui and opts.ui.tick then\n opts.ui.update_debounce = opts.ui.tick\n opts.ui.tick = nil\n end\n\n if not opts.picker then\n opts.picker = {}\n if opts.finder then\n opts.picker.name = opts.finder\n opts.finder = nil\n end\n if opts.finder_mappings then\n opts.picker.note_mappings = opts.finder_mappings\n opts.finder_mappings = nil\n end\n if opts.picker.mappings and not opts.picker.note_mappings then\n opts.picker.note_mappings = opts.picker.mappings\n opts.picker.mappings = nil\n end\n end\n\n if opts.wiki_link_func == nil and opts.completion ~= nil then\n local warn = false\n\n if opts.completion.prepend_note_id then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n opts.completion.prepend_note_id = nil\n warn = true\n elseif opts.completion.prepend_note_path then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n opts.completion.prepend_note_path = nil\n warn = true\n elseif opts.completion.use_path_only then\n opts.wiki_link_func = builtin.wiki_link_path_only\n opts.completion.use_path_only = nil\n warn = true\n end\n\n if warn then\n log.warn_once(\n \"The config options 'completion.prepend_note_id', 'completion.prepend_note_path', and 'completion.use_path_only' \"\n .. \"are deprecated. Please use 'wiki_link_func' instead.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/406\"\n )\n end\n end\n\n if opts.wiki_link_func == \"prepend_note_id\" then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n elseif opts.wiki_link_func == \"prepend_note_path\" then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n elseif opts.wiki_link_func == \"use_path_only\" then\n opts.wiki_link_func = builtin.wiki_link_path_only\n elseif opts.wiki_link_func == \"use_alias_only\" then\n opts.wiki_link_func = builtin.wiki_link_alias_only\n elseif type(opts.wiki_link_func) == \"string\" then\n error(string.format(\"invalid option '%s' for 'wiki_link_func'\", opts.wiki_link_func))\n end\n\n if opts.completion ~= nil and opts.completion.preferred_link_style ~= nil then\n opts.preferred_link_style = opts.completion.preferred_link_style\n opts.completion.preferred_link_style = nil\n log.warn_once(\n \"The config option 'completion.preferred_link_style' is deprecated, please use the top-level \"\n .. \"'preferred_link_style' instead.\"\n )\n end\n\n if opts.completion ~= nil and opts.completion.new_notes_location ~= nil then\n opts.new_notes_location = opts.completion.new_notes_location\n opts.completion.new_notes_location = nil\n log.warn_once(\n \"The config option 'completion.new_notes_location' is deprecated, please use the top-level \"\n .. \"'new_notes_location' instead.\"\n )\n end\n\n if opts.detect_cwd ~= nil then\n opts.detect_cwd = nil\n log.warn_once(\n \"The 'detect_cwd' field is deprecated and no longer has any affect.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/366 for more details.\"\n )\n end\n\n if opts.open_app_foreground ~= nil then\n opts.open_app_foreground = nil\n log.warn_once [[The config option 'open_app_foreground' is deprecated, please use the `func` field in `open` module:\n\n```lua\n{\n open = {\n func = function(uri)\n vim.ui.open(uri, { cmd = { \"open\", \"-a\", \"/Applications/Obsidian.app\" } })\n end\n }\n}\n```]]\n end\n\n if opts.use_advanced_uri ~= nil then\n opts.use_advanced_uri = nil\n log.warn_once [[The config option 'use_advanced_uri' is deprecated, please use in `open` module instead]]\n end\n\n if opts.overwrite_mappings ~= nil then\n log.warn_once \"The 'overwrite_mappings' config option is deprecated and no longer has any affect.\"\n opts.overwrite_mappings = nil\n end\n\n if opts.mappings ~= nil then\n log.warn_once [[The 'mappings' config option is deprecated and no longer has any affect.\nSee: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Keymaps]]\n opts.overwrite_mappings = nil\n end\n\n if opts.tags ~= nil then\n log.warn_once \"The 'tags' config option is deprecated and no longer has any affect.\"\n opts.tags = nil\n end\n\n if opts.templates and opts.templates.subdir then\n opts.templates.folder = opts.templates.subdir\n opts.templates.subdir = nil\n end\n\n if opts.image_name_func then\n if opts.attachments == nil then\n opts.attachments = {}\n end\n opts.attachments.img_name_func = opts.image_name_func\n opts.image_name_func = nil\n end\n\n if opts.statusline and opts.statusline.enabled then\n deprecate(\"statusline.{enabled,format} and vim.g.obsidian\", \"footer.{enabled,format}\", \"4.0\")\n end\n\n --------------------------\n -- Merge with defaults. --\n --------------------------\n\n ---@type obsidian.config.ClientOpts\n opts = tbl_override(defaults, opts)\n\n opts.backlinks = tbl_override(defaults.backlinks, opts.backlinks)\n opts.completion = tbl_override(defaults.completion, opts.completion)\n opts.picker = tbl_override(defaults.picker, opts.picker)\n opts.daily_notes = tbl_override(defaults.daily_notes, opts.daily_notes)\n opts.templates = tbl_override(defaults.templates, opts.templates)\n opts.ui = tbl_override(defaults.ui, opts.ui)\n opts.attachments = tbl_override(defaults.attachments, opts.attachments)\n opts.statusline = tbl_override(defaults.statusline, opts.statusline)\n opts.footer = tbl_override(defaults.footer, opts.footer)\n opts.open = tbl_override(defaults.open, opts.open)\n opts.checkbox = tbl_override(defaults.checkbox, opts.checkbox)\n opts.comment = tbl_override(defaults.comment, opts.comment)\n\n ---------------\n -- Validate. --\n ---------------\n\n if opts.legacy_commands then\n deprecate(\n \"legacy_commands\",\n [[move from commands like `ObsidianBacklinks` to `Obsidian backlinks`\nand set `opts.legacy_commands` to false to get rid of this warning.\nsee https://github.com/obsidian-nvim/obsidian.nvim/wiki/Commands for details.\n ]],\n \"4.0\"\n )\n end\n\n if opts.sort_by ~= nil and not vim.tbl_contains(vim.tbl_values(config.SortBy), opts.sort_by) then\n error(\"Invalid 'sort_by' option '\" .. opts.sort_by .. \"' in obsidian.nvim config.\")\n end\n\n if not util.islist(opts.workspaces) then\n error \"Invalid obsidian.nvim config, the 'config.workspaces' should be an array/list.\"\n elseif vim.tbl_isempty(opts.workspaces) then\n error \"At least one workspace is required!\\nPlease specify a workspace \"\n end\n\n for i, workspace in ipairs(opts.workspaces) do\n local path = type(workspace.path) == \"function\" and workspace.path() or workspace.path\n ---@cast path -function\n opts.workspaces[i].path = vim.fn.resolve(vim.fs.normalize(path))\n end\n\n -- Convert dir to workspace format.\n if opts.dir ~= nil then\n table.insert(opts.workspaces, 1, { path = opts.dir })\n end\n\n return opts\nend\n\nreturn config\n"], ["/obsidian.nvim/lua/obsidian/pickers/picker.lua", "local abc = require \"obsidian.abc\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal strings = require \"plenary.strings\"\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---@class obsidian.Picker : obsidian.ABC\n---\n---@field calling_bufnr integer\nlocal Picker = abc.new_class()\n\nPicker.new = function()\n local self = Picker.init()\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n return self\nend\n\n-------------------------------------------------------------------\n--- Abstract methods that need to be implemented by subclasses. ---\n-------------------------------------------------------------------\n\n---@class obsidian.PickerMappingOpts\n---\n---@field desc string\n---@field callback fun(...)\n---@field fallback_to_query boolean|?\n---@field keep_open boolean|?\n---@field allow_multiple boolean|?\n\n---@alias obsidian.PickerMappingTable table\n\n---@class obsidian.PickerFindOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Find files in a directory.\n---\n---@param opts obsidian.PickerFindOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `callback`: Callback to run with the selected entry.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.find_files = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerGrepOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field query string|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable\n---@field selection_mappings obsidian.PickerMappingTable\n\n--- Grep for a string.\n---\n---@param opts obsidian.PickerGrepOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.grep = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerEntry\n---\n---@field value any\n---@field ordinal string|?\n---@field display string|?\n---@field filename string|?\n---@field valid boolean|?\n---@field lnum integer|?\n---@field col integer|?\n---@field icon string|?\n---@field icon_hl string|?\n\n---@class obsidian.PickerPickOpts\n---\n---@field prompt_title string|?\n---@field callback fun(value: any, ...: any)|?\n---@field allow_multiple boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Pick from a list of items.\n---\n---@param values string[]|obsidian.PickerEntry[] Items to pick from.\n---@param opts obsidian.PickerPickOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected item(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.pick = function(self, values, opts)\n error \"not implemented\"\nend\n\n------------------------------------------------------------------\n--- Concrete methods with a default implementation subclasses. ---\n------------------------------------------------------------------\n\n--- Find notes by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.find_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Notes\",\n dir = Obsidian.dir,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Find templates by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string) }|? Options.\n---\n--- Options:\n--- `callback`: Callback to run with the selected template path.\nPicker.find_templates = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local templates_dir = api.templates_dir()\n\n if templates_dir == nil then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Templates\",\n callback = opts.callback,\n dir = templates_dir,\n no_default_mappings = true,\n }\nend\n\n--- Grep search in notes.\n---\n---@param opts { prompt_title: string|?, query: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.grep_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n self:grep {\n prompt_title = opts.prompt_title or \"Grep notes\",\n dir = Obsidian.dir,\n query = opts.query,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Open picker with a list of notes.\n---\n---@param notes obsidian.Note[]\n---@param opts { prompt_title: string|?, callback: fun(note: obsidian.Note, ...: obsidian.Note), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_note = function(self, notes, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n -- Launch picker with results.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, note in ipairs(notes) do\n assert(note.path)\n local rel_path = assert(note.path:vault_relative_path { strict = true })\n local display_name = note:display_name()\n entries[#entries + 1] = {\n value = note,\n display = display_name,\n ordinal = rel_path .. \" \" .. display_name,\n filename = tostring(note.path),\n }\n end\n\n self:pick(entries, {\n prompt_title = opts.prompt_title or \"Notes\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--- Open picker with a list of tags.\n---\n---@param tags string[]\n---@param opts { prompt_title: string|?, callback: fun(tag: string, ...: string), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected tag(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_tag = function(self, tags, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local selection_mappings\n if not opts.no_default_mappings then\n selection_mappings = self:_tag_selection_mappings()\n end\n\n self:pick(tags, {\n prompt_title = opts.prompt_title or \"Tags\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--------------------------------\n--- Concrete helper methods. ---\n--------------------------------\n\n---@param key string|?\n---@return boolean\nlocal function key_is_set(key)\n if key ~= nil and string.len(key) > 0 then\n return true\n else\n return false\n end\nend\n\n--- Get query mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_query_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.new) then\n mappings[Obsidian.opts.picker.note_mappings.new] = {\n desc = \"new\",\n callback = function(query)\n ---@diagnostic disable-next-line: missing-fields\n require \"obsidian.commands.new\"(require(\"obsidian\").get_client(), { args = query })\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.insert_link) then\n mappings[Obsidian.opts.picker.note_mappings.insert_link] = {\n desc = \"insert link\",\n callback = function(note_or_path)\n ---@type obsidian.Note\n local note\n if Note.is_note_obj(note_or_path) then\n note = note_or_path\n else\n note = Note.from_file(note_or_path)\n end\n local link = api.format_link(note, {})\n vim.api.nvim_put({ link }, \"\", false, true)\n require(\"obsidian.ui\").update(0)\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `pick_tag()`.\n---@return obsidian.PickerMappingTable\nPicker._tag_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.tag_mappings then\n if key_is_set(Obsidian.opts.picker.tag_mappings.tag_note) then\n mappings[Obsidian.opts.picker.tag_mappings.tag_note] = {\n desc = \"tag note\",\n callback = function(...)\n local tags = { ... }\n\n local note = api.current_note(self.calling_bufnr)\n if not note then\n log.warn(\"'%s' is not a note in your workspace\", vim.api.nvim_buf_get_name(self.calling_bufnr))\n return\n end\n\n -- Add the tag and save the new frontmatter to the buffer.\n local tags_added = {}\n local tags_not_added = {}\n for _, tag in ipairs(tags) do\n if note:add_tag(tag) then\n table.insert(tags_added, tag)\n else\n table.insert(tags_not_added, tag)\n end\n end\n\n if #tags_added > 0 then\n if note:update_frontmatter(self.calling_bufnr) then\n log.info(\"Added tags %s to frontmatter\", tags_added)\n else\n log.warn \"Frontmatter unchanged\"\n end\n end\n\n if #tags_not_added > 0 then\n log.warn(\"Note already has tags %s\", tags_not_added)\n end\n end,\n fallback_to_query = true,\n keep_open = true,\n allow_multiple = true,\n }\n end\n\n if key_is_set(Obsidian.opts.picker.tag_mappings.insert_tag) then\n mappings[Obsidian.opts.picker.tag_mappings.insert_tag] = {\n desc = \"insert tag\",\n callback = function(tag)\n vim.api.nvim_put({ \"#\" .. tag }, \"\", false, true)\n end,\n fallback_to_query = true,\n }\n end\n end\n\n return mappings\nend\n\n---@param opts { prompt_title: string, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|? }|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nPicker._build_prompt = function(self, opts)\n opts = opts or {}\n\n ---@type string\n local prompt = opts.prompt_title or \"Find\"\n if string.len(prompt) > 50 then\n prompt = string.sub(prompt, 1, 50) .. \"…\"\n end\n\n prompt = prompt .. \" | confirm\"\n\n if opts.query_mappings then\n local keys = vim.tbl_keys(opts.query_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.query_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n if opts.selection_mappings then\n local keys = vim.tbl_keys(opts.selection_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.selection_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n return prompt\nend\n\n---@param entry obsidian.PickerEntry\n---\n---@return string, { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n---@diagnostic disable-next-line: unused-local\nPicker._make_display = function(self, entry)\n ---@type string\n local display = \"\"\n ---@type { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n local highlights = {}\n\n if entry.filename ~= nil then\n local icon, icon_hl\n if entry.icon then\n icon = entry.icon\n icon_hl = entry.icon_hl\n else\n icon, icon_hl = api.get_icon(entry.filename)\n end\n\n if icon ~= nil then\n display = display .. icon .. \" \"\n if icon_hl ~= nil then\n highlights[#highlights + 1] = { { 0, strings.strdisplaywidth(icon) }, icon_hl }\n end\n end\n\n display = display .. Path.new(entry.filename):vault_relative_path { strict = true }\n\n if entry.lnum ~= nil then\n display = display .. \":\" .. entry.lnum\n\n if entry.col ~= nil then\n display = display .. \":\" .. entry.col\n end\n end\n\n if entry.display ~= nil then\n display = display .. \":\" .. entry.display\n end\n elseif entry.display ~= nil then\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. entry.display\n else\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. tostring(entry.value)\n end\n\n return assert(display), highlights\nend\n\n---@return string[]\nPicker._build_find_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = { sort_by = Obsidian.opts.sort_by, sort_reversed = Obsidian.opts.sort_reversed }\n return search.build_find_cmd(\".\", nil, search_opts)\nend\n\nPicker._build_grep_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = {\n sort_by = Obsidian.opts.sort_by,\n sort_reversed = Obsidian.opts.sort_reversed,\n smart_case = true,\n fixed_strings = true,\n }\n return search.build_grep_cmd(search_opts)\nend\n\nreturn Picker\n"], ["/obsidian.nvim/lua/obsidian/commands/paste_img.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal img = require \"obsidian.img_paste\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not img.clipboard_is_img() then\n return log.err \"There is no image data in the clipboard\"\n end\n\n ---@type string|?\n local default_name = Obsidian.opts.attachments.img_name_func()\n\n local should_confirm = Obsidian.opts.attachments.confirm_img_paste\n\n ---@type string\n local fname = vim.trim(data.args)\n\n -- Get filename to save to.\n if fname == nil or fname == \"\" then\n if default_name and not should_confirm then\n fname = default_name\n else\n local input = api.input(\"Enter file name: \", { default = default_name, completion = \"file\" })\n if not input then\n return log.warn \"Paste aborted\"\n end\n fname = input\n end\n end\n\n local path = api.resolve_image_path(fname)\n\n img.paste(path)\nend\n"], ["/obsidian.nvim/lua/obsidian/workspace.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\nlocal config = require \"obsidian.config\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.workspace.WorkspaceSpec\n---\n---@field path string|(fun(): string)\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts?\n\n---@class obsidian.workspace.WorkspaceOpts\n---\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts|?\n\n--- Each workspace represents a working directory (usually an Obsidian vault) along with\n--- a set of configuration options specific to the workspace.\n---\n--- Workspaces are a little more general than Obsidian vaults as you can have a workspace\n--- outside of a vault or as a subdirectory of a vault.\n---\n---@toc_entry obsidian.Workspace\n---\n---@class obsidian.Workspace : obsidian.ABC\n---\n---@field name string An arbitrary name for the workspace.\n---@field path obsidian.Path The normalized path to the workspace.\n---@field root obsidian.Path The normalized path to the vault root of the workspace. This usually matches 'path'.\n---@field overrides table|obsidian.config.ClientOpts|?\n---@field locked boolean|?\nlocal Workspace = abc.new_class {\n __tostring = function(self)\n return string.format(\"Workspace(name='%s', path='%s', root='%s')\", self.name, self.path, self.root)\n end,\n __eq = function(a, b)\n local a_fields = a:as_tbl()\n a_fields.locked = nil\n local b_fields = b:as_tbl()\n b_fields.locked = nil\n return vim.deep_equal(a_fields, b_fields)\n end,\n}\n\n--- Find the vault root from a given directory.\n---\n--- This will traverse the directory tree upwards until a '.obsidian/' folder is found to\n--- indicate the root of a vault, otherwise the given directory is used as-is.\n---\n---@param base_dir string|obsidian.Path\n---\n---@return obsidian.Path|?\nlocal function find_vault_root(base_dir)\n local vault_indicator_folder = \".obsidian\"\n base_dir = Path.new(base_dir)\n local dirs = Path.new(base_dir):parents()\n table.insert(dirs, 1, base_dir)\n\n for _, dir in ipairs(dirs) do\n local maybe_vault = dir / vault_indicator_folder\n if maybe_vault:is_dir() then\n return dir\n end\n end\n\n return nil\nend\n\n--- Create a new 'Workspace' object. This assumes the workspace already exists on the filesystem.\n---\n---@param path string|obsidian.Path Workspace path.\n---@param opts obsidian.workspace.WorkspaceOpts|?\n---\n---@return obsidian.Workspace\nWorkspace.new = function(path, opts)\n opts = opts and opts or {}\n\n local self = Workspace.init()\n self.path = Path.new(path):resolve { strict = true }\n self.name = assert(opts.name or self.path.name)\n self.overrides = opts.overrides\n\n if opts.strict then\n self.root = self.path\n else\n local vault_root = find_vault_root(self.path)\n if vault_root then\n self.root = vault_root\n else\n self.root = self.path\n end\n end\n\n return self\nend\n\n--- Initialize a new 'Workspace' object from a workspace spec.\n---\n---@param spec obsidian.workspace.WorkspaceSpec\n---\n---@return obsidian.Workspace\nWorkspace.new_from_spec = function(spec)\n ---@type string|obsidian.Path\n local path\n if type(spec.path) == \"function\" then\n path = spec.path()\n else\n ---@diagnostic disable-next-line: cast-local-type\n path = spec.path\n end\n\n ---@diagnostic disable-next-line: param-type-mismatch\n return Workspace.new(path, {\n name = spec.name,\n strict = spec.strict,\n overrides = spec.overrides,\n })\nend\n\n--- Lock the workspace.\nWorkspace.lock = function(self)\n self.locked = true\nend\n\n--- Unlock the workspace.\nWorkspace._unlock = function(self)\n self.locked = false\nend\n\n--- Get the workspace corresponding to the directory (or a parent of), if there\n--- is one.\n---\n---@param cur_dir string|obsidian.Path\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_dir = function(cur_dir, workspaces)\n local ok\n ok, cur_dir = pcall(function()\n return Path.new(cur_dir):resolve { strict = true }\n end)\n\n if not ok then\n return\n end\n\n for _, spec in ipairs(workspaces) do\n local w = Workspace.new_from_spec(spec)\n if w.path == cur_dir or w.path:is_parent_of(cur_dir) then\n return w\n end\n end\nend\n\n--- Get the workspace corresponding to the current working directory (or a parent of), if there\n--- is one.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_cwd = function(workspaces)\n local cwd = assert(vim.fn.getcwd())\n return Workspace.get_workspace_for_dir(cwd, workspaces)\nend\n\n--- Returns the default workspace.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|nil\nWorkspace.get_default_workspace = function(workspaces)\n if not vim.tbl_isempty(workspaces) then\n return Workspace.new_from_spec(workspaces[1])\n else\n return nil\n end\nend\n\n--- Resolves current workspace from the client config.\n---\n---@param opts obsidian.config.ClientOpts\n---\n---@return obsidian.Workspace|?\nWorkspace.get_from_opts = function(opts)\n local current_workspace = Workspace.get_workspace_for_cwd(opts.workspaces)\n\n if not current_workspace then\n current_workspace = Workspace.get_default_workspace(opts.workspaces)\n end\n\n return current_workspace\nend\n\n--- Get the normalize opts for a given workspace.\n---\n---@param workspace obsidian.Workspace|?\n---\n---@return obsidian.config.ClientOpts\nWorkspace.normalize_opts = function(workspace)\n if workspace then\n return config.normalize(workspace.overrides and workspace.overrides or {}, Obsidian._opts)\n else\n return Obsidian.opts\n end\nend\n\n---@param workspace obsidian.Workspace\n---@param opts { lock: boolean|? }|?\nWorkspace.set = function(workspace, opts)\n opts = opts and opts or {}\n\n local dir = workspace.root\n local options = Workspace.normalize_opts(workspace) -- TODO: test\n\n Obsidian.workspace = workspace\n Obsidian.dir = dir\n Obsidian.opts = options\n\n -- Ensure directories exist.\n dir:mkdir { parents = true, exists_ok = true }\n\n if options.notes_subdir ~= nil then\n local notes_subdir = dir / Obsidian.opts.notes_subdir\n notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n local daily_notes_subdir = Obsidian.dir / Obsidian.opts.daily_notes.folder\n daily_notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n -- Setup UI add-ons.\n local has_no_renderer = not (api.get_plugin_info \"render-markdown.nvim\" or api.get_plugin_info \"markview.nvim\")\n if has_no_renderer and Obsidian.opts.ui.enable then\n require(\"obsidian.ui\").setup(Obsidian.workspace, Obsidian.opts.ui)\n end\n\n if opts.lock then\n Obsidian.workspace:lock()\n end\n\n Obsidian.picker = require(\"obsidian.pickers\").get(Obsidian.opts.picker.name)\n\n util.fire_callback(\"post_set_workspace\", Obsidian.opts.callbacks.post_set_workspace, workspace)\n\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = \"ObsidianWorkpspaceSet\",\n data = { workspace = workspace },\n })\nend\n\n---@param workspace obsidian.Workspace|string The workspace object or the name of an existing workspace.\n---@param opts { lock: boolean|? }|?\nWorkspace.switch = function(workspace, opts)\n opts = opts and opts or {}\n\n if workspace == Obsidian.workspace.name then\n log.info(\"Already in workspace '%s' @ '%s'\", workspace, Obsidian.workspace.path)\n return\n end\n\n for _, ws in ipairs(Obsidian.opts.workspaces) do\n if ws.name == workspace then\n return Workspace.set(Workspace.new_from_spec(ws), opts)\n end\n end\n\n error(string.format(\"Workspace '%s' not found\", workspace))\nend\n\nreturn Workspace\n"], ["/obsidian.nvim/lua/obsidian/templates.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nlocal M = {}\n\n--- Resolve a template name to a path.\n---\n---@param template_name string|obsidian.Path\n---@param templates_dir obsidian.Path\n---\n---@return obsidian.Path\nM.resolve_template = function(template_name, templates_dir)\n ---@type obsidian.Path|?\n local template_path\n local paths_to_check = { templates_dir / tostring(template_name), Path:new(template_name) }\n for _, path in ipairs(paths_to_check) do\n if path:is_file() then\n template_path = path\n break\n elseif not vim.endswith(tostring(path), \".md\") then\n local path_with_suffix = Path:new(tostring(path) .. \".md\")\n if path_with_suffix:is_file() then\n template_path = path_with_suffix\n break\n end\n end\n end\n\n if template_path == nil then\n error(string.format(\"Template '%s' not found\", template_name))\n end\n\n return template_path\nend\n\n--- Substitute variables inside the given text.\n---\n---@param text string\n---@param ctx obsidian.TemplateContext\n---\n---@return string\nM.substitute_template_variables = function(text, ctx)\n local methods = vim.deepcopy(ctx.template_opts.substitutions or {})\n\n if not methods[\"date\"] then\n methods[\"date\"] = function()\n local date_format = ctx.template_opts.date_format or \"%Y-%m-%d\"\n return tostring(os.date(date_format))\n end\n end\n\n if not methods[\"time\"] then\n methods[\"time\"] = function()\n local time_format = ctx.template_opts.time_format or \"%H:%M\"\n return tostring(os.date(time_format))\n end\n end\n\n if not methods[\"title\"] and ctx.partial_note then\n methods[\"title\"] = ctx.partial_note.title or ctx.partial_note:display_name()\n end\n\n if not methods[\"id\"] and ctx.partial_note then\n methods[\"id\"] = tostring(ctx.partial_note.id)\n end\n\n if not methods[\"path\"] and ctx.partial_note and ctx.partial_note.path then\n methods[\"path\"] = tostring(ctx.partial_note.path)\n end\n\n -- Replace known variables.\n for key, subst in pairs(methods) do\n while true do\n local m_start, m_end = string.find(text, \"{{\" .. key .. \"}}\", nil, true)\n if not m_start or not m_end then\n break\n end\n ---@type string\n local value\n if type(subst) == \"string\" then\n value = subst\n else\n value = subst(ctx)\n -- cache the result\n methods[key] = value\n end\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n -- Find unknown variables and prompt for them.\n for m_start, m_end in util.gfind(text, \"{{[^}]+}}\") do\n local key = vim.trim(string.sub(text, m_start + 2, m_end - 2))\n local value = api.input(string.format(\"Enter value for '%s' ( to skip): \", key))\n if value and string.len(value) > 0 then\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n return text\nend\n\n--- Clone template to a new note.\n---\n---@param ctx obsidian.CloneTemplateContext\n---\n---@return obsidian.Note\nM.clone_template = function(ctx)\n local note_path = Path.new(ctx.destination_path)\n assert(note_path:parent()):mkdir { parents = true, exist_ok = true }\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local template_file, read_err = io.open(tostring(template_path), \"r\")\n if not template_file then\n error(string.format(\"Unable to read template at '%s': %s\", template_path, tostring(read_err)))\n end\n\n local note_file, write_err = io.open(tostring(note_path), \"w\")\n if not note_file then\n error(string.format(\"Unable to write note at '%s': %s\", note_path, tostring(write_err)))\n end\n\n for line in template_file:lines \"L\" do\n line = M.substitute_template_variables(line, ctx)\n note_file:write(line)\n end\n\n assert(template_file:close())\n assert(note_file:close())\n\n local new_note = Note.from_file(note_path)\n\n if ctx.partial_note then\n -- Transfer fields from `ctx.partial_note`.\n new_note.id = ctx.partial_note.id\n if new_note.title == nil then\n new_note.title = ctx.partial_note.title\n end\n for _, alias in ipairs(ctx.partial_note.aliases) do\n new_note:add_alias(alias)\n end\n for _, tag in ipairs(ctx.partial_note.tags) do\n new_note:add_tag(tag)\n end\n end\n\n return new_note\nend\n\n---Insert a template at the given location.\n---\n---@param ctx obsidian.InsertTemplateContext\n---\n---@return obsidian.Note\nM.insert_template = function(ctx)\n local buf, win, row, _ = unpack(ctx.location)\n if ctx.partial_note == nil then\n ctx.partial_note = Note.from_buffer(buf)\n end\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local insert_lines = {}\n local template_file = io.open(tostring(template_path), \"r\")\n if template_file then\n local lines = template_file:lines()\n for line in lines do\n local new_lines = M.substitute_template_variables(line, ctx)\n if string.find(new_lines, \"[\\r\\n]\") then\n local line_start = 1\n for line_end in util.gfind(new_lines, \"[\\r\\n]\") do\n local new_line = string.sub(new_lines, line_start, line_end - 1)\n table.insert(insert_lines, new_line)\n line_start = line_end + 1\n end\n local last_line = string.sub(new_lines, line_start)\n if string.len(last_line) > 0 then\n table.insert(insert_lines, last_line)\n end\n else\n table.insert(insert_lines, new_lines)\n end\n end\n template_file:close()\n else\n error(string.format(\"Template file '%s' not found\", template_path))\n end\n\n vim.api.nvim_buf_set_lines(buf, row - 1, row - 1, false, insert_lines)\n local new_cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(win))\n vim.api.nvim_win_set_cursor(0, { new_cursor_row, 0 })\n\n require(\"obsidian.ui\").update(0)\n\n return Note.from_buffer(buf)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/client.lua", "--- *obsidian-api*\n---\n--- The Obsidian.nvim Lua API.\n---\n--- ==============================================================================\n---\n--- Table of contents\n---\n---@toc\n\nlocal Path = require \"obsidian.path\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal Note = require \"obsidian.note\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal block_on = require(\"obsidian.async\").block_on\nlocal iter = vim.iter\n\n---@class obsidian.SearchOpts\n---\n---@field sort boolean|?\n---@field include_templates boolean|?\n---@field ignore_case boolean|?\n---@field default function?\n\n--- The Obsidian client is the main API for programmatically interacting with obsidian.nvim's features\n--- in Lua. To get the client instance, run:\n---\n--- `local client = require(\"obsidian\").get_client()`\n---\n---@toc_entry obsidian.Client\n---\n---@class obsidian.Client : obsidian.ABC\nlocal Client = {}\n\nlocal depreacted_lookup = {\n dir = \"dir\",\n buf_dir = \"buf_dir\",\n current_workspace = \"workspace\",\n opts = \"opts\",\n}\n\nClient.__index = function(_, k)\n if depreacted_lookup[k] then\n local msg = string.format(\n [[client.%s is depreacted, use Obsidian.%s instead.\nclient is going to be removed in the future as well.]],\n k,\n depreacted_lookup[k]\n )\n log.warn(msg)\n return Obsidian[depreacted_lookup[k]]\n elseif rawget(Client, k) then\n return rawget(Client, k)\n end\nend\n\n--- Create a new Obsidian client without additional setup.\n--- This is mostly used for testing. In practice you usually want to obtain the existing\n--- client through:\n---\n--- `require(\"obsidian\").get_client()`\n---\n---@return obsidian.Client\nClient.new = function()\n return setmetatable({}, Client)\nend\n\n--- Get the default search options.\n---\n---@return obsidian.SearchOpts\nClient.search_defaults = function()\n return {\n sort = false,\n include_templates = false,\n ignore_case = false,\n }\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---\n---@return obsidian.SearchOpts\n---\n---@private\nClient._search_opts_from_arg = function(self, opts)\n if opts == nil then\n opts = self:search_defaults()\n elseif type(opts) == \"boolean\" then\n local sort = opts\n opts = self:search_defaults()\n opts.sort = sort\n end\n return opts\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nClient._prepare_search_opts = function(self, opts, additional_opts)\n opts = self:_search_opts_from_arg(opts)\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n search.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = search.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---\n---@return function\n---\n---@private\nClient._search_iter_async = function(self, term, search_opts, find_opts)\n local tx, rx = channel.mpsc()\n local found = {}\n\n local function on_exit(_)\n tx.send(nil)\n end\n\n ---@param content_match MatchData\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n ---@param path_match string\n local function on_find_match(path_match)\n local path = Path.new(path_match):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n local cmds_done = 0 -- out of the two, one for 'search' and one for 'find'\n\n search.search_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n search.find_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(find_opts, { ignore_case = true }),\n on_find_match,\n on_exit\n )\n\n return function()\n while cmds_done < 2 do\n local value = rx.recv()\n if value == nil then\n cmds_done = cmds_done + 1\n else\n return value\n end\n end\n return nil\n end\nend\n\n---@class obsidian.TagLocation\n---\n---@field tag string The tag found.\n---@field note obsidian.Note The note instance where the tag was found.\n---@field path string|obsidian.Path The path to the note where the tag was found.\n---@field line integer The line number (1-indexed) where the tag was found.\n---@field text string The text (with whitespace stripped) of the line where the tag was found.\n---@field tag_start integer|? The index within 'text' where the tag starts.\n---@field tag_end integer|? The index within 'text' where the tag ends.\n\n--- Find all tags starting with the given search term(s).\n---\n---@param term string|string[] The search term.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|? }|?\n---\n---@return obsidian.TagLocation[]\nClient.find_tags = function(self, term, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_tags_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n--- An async version of 'find_tags()'.\n---\n---@param term string|string[] The search term.\n---@param callback fun(tags: obsidian.TagLocation[])\n---@param opts { search: obsidian.SearchOpts }|?\nClient.find_tags_async = function(self, term, callback, opts)\n opts = opts or {}\n\n ---@type string[]\n local terms\n if type(term) == \"string\" then\n terms = { term }\n else\n terms = term\n end\n\n for i, t in ipairs(terms) do\n if vim.startswith(t, \"#\") then\n terms[i] = string.sub(t, 2)\n end\n end\n\n terms = util.tbl_unique(terms)\n\n -- Maps paths to tag locations.\n ---@type table\n local path_to_tag_loc = {}\n -- Caches note objects.\n ---@type table\n local path_to_note = {}\n -- Caches code block locations.\n ---@type table\n local path_to_code_blocks = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n ---@param tag string\n ---@param path string|obsidian.Path\n ---@param note obsidian.Note\n ---@param lnum integer\n ---@param text string\n ---@param col_start integer|?\n ---@param col_end integer|?\n local add_match = function(tag, path, note, lnum, text, col_start, col_end)\n if vim.startswith(tag, \"#\") then\n tag = string.sub(tag, 2)\n end\n if not path_to_tag_loc[path] then\n path_to_tag_loc[path] = {}\n end\n path_to_tag_loc[path][#path_to_tag_loc[path] + 1] = {\n tag = tag,\n path = path,\n note = note,\n line = lnum,\n text = text,\n tag_start = col_start,\n tag_end = col_end,\n }\n end\n\n -- Wraps `Note.from_file_with_contents_async()` to return a table instead of a tuple and\n -- find the code blocks.\n ---@param path obsidian.Path\n ---@return { [1]: obsidian.Note, [2]: {[1]: integer, [2]: integer}[] }\n local load_note = function(path)\n local note, contents = Note.from_file_with_contents_async(path, { max_lines = Obsidian.opts.search_max_lines })\n return { note, search.find_code_blocks(contents) }\n end\n\n ---@param match_data MatchData\n local on_match = function(match_data)\n local path = Path.new(match_data.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local note = path_to_note[path]\n local code_blocks = path_to_code_blocks[path]\n if not note or not code_blocks then\n local ok, res = pcall(load_note, path)\n if ok then\n note, code_blocks = unpack(res)\n path_to_note[path] = note\n path_to_code_blocks[path] = code_blocks\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n local line_number = match_data.line_number + 1 -- match_data.line_number is 0-indexed\n\n -- check if the match was inside a code block.\n for block in iter(code_blocks) do\n if block[1] <= line_number and line_number <= block[2] then\n return\n end\n end\n\n local line = vim.trim(match_data.lines.text)\n local n_matches = 0\n\n -- check for tag in the wild of the form '#{tag}'\n for match in iter(search.find_tags(line)) do\n local m_start, m_end, _ = unpack(match)\n local tag = string.sub(line, m_start + 1, m_end)\n if string.match(tag, \"^\" .. search.Patterns.TagCharsRequired .. \"$\") then\n add_match(tag, path, note, match_data.line_number, line, m_start, m_end)\n end\n end\n\n -- check for tags in frontmatter\n if n_matches == 0 and note.tags ~= nil and (vim.startswith(line, \"tags:\") or string.match(line, \"%s*- \")) then\n for tag in iter(note.tags) do\n tag = tostring(tag)\n for _, t in ipairs(terms) do\n if string.len(t) == 0 or util.string_contains(tag:lower(), t:lower()) then\n add_match(tag, path, note, match_data.line_number, line)\n end\n end\n end\n end\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n local search_terms = {}\n for t in iter(terms) do\n if string.len(t) > 0 then\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsOptional .. t .. search.Patterns.TagCharsOptional\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n else\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsRequired\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \" .. search.Patterns.TagCharsRequired .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\" .. search.Patterns.TagCharsRequired\n end\n end\n\n search.search_async(\n Obsidian.dir,\n search_terms,\n self:_prepare_search_opts(opts.search, { ignore_case = true }),\n on_match,\n function(_)\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.TagLocation[]\n local tags_list = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results in path order.\n for _, path in ipairs(paths) do\n local tag_locs = path_to_tag_loc[path]\n if tag_locs ~= nil then\n table.sort(tag_locs, function(a, b)\n return a.line < b.line\n end)\n for _, tag_loc in ipairs(tag_locs) do\n tags_list[#tags_list + 1] = tag_loc\n end\n end\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return tags_list\n end, callback)\nend\n\n---@class obsidian.BacklinkMatches\n---\n---@field note obsidian.Note The note instance where the backlinks were found.\n---@field path string|obsidian.Path The path to the note where the backlinks were found.\n---@field matches obsidian.BacklinkMatch[] The backlinks within the note.\n\n---@class obsidian.BacklinkMatch\n---\n---@field line integer The line number (1-indexed) where the backlink was found.\n---@field text string The text of the line where the backlink was found.\n\n--- Find all backlinks to a note.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|?, anchor: string|?, block: string|? }|?\n---\n---@return obsidian.BacklinkMatches[]\nClient.find_backlinks = function(self, note, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_backlinks_async(note, cb, { search = opts.search, anchor = opts.anchor, block = opts.block })\n end, opts.timeout)\nend\n\n--- An async version of 'find_backlinks()'.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param callback fun(backlinks: obsidian.BacklinkMatches[])\n---@param opts { search: obsidian.SearchOpts, anchor: string|?, block: string|? }|?\nClient.find_backlinks_async = function(self, note, callback, opts)\n opts = opts or {}\n\n ---@type string|?\n local block = opts.block and util.standardize_block(opts.block) or nil\n local anchor = opts.anchor and util.standardize_anchor(opts.anchor) or nil\n ---@type obsidian.note.HeaderAnchor|?\n local anchor_obj\n if anchor then\n anchor_obj = note:resolve_anchor_link(anchor)\n end\n\n -- Maps paths (string) to note object and a list of matches.\n ---@type table\n local backlink_matches = {}\n ---@type table\n local path_to_note = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n -- Prepare search terms.\n local search_terms = {}\n local note_path = Path.new(note.path)\n for raw_ref in iter { tostring(note.id), note_path.name, note_path.stem, note.path:vault_relative_path() } do\n for ref in\n iter(util.tbl_unique {\n raw_ref,\n util.urlencode(tostring(raw_ref)),\n util.urlencode(tostring(raw_ref), { keep_path_sep = true }),\n })\n do\n if ref ~= nil then\n if anchor == nil and block == nil then\n -- Wiki links without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", ref)\n search_terms[#search_terms + 1] = string.format(\"[[%s|\", ref)\n -- Markdown link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s)\", ref)\n -- Markdown link without anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s)\", ref)\n -- Wiki links with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif anchor then\n -- Note: Obsidian allow a lot of different forms of anchor links, so we can't assume\n -- it's the standardized form here.\n -- Wiki links with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif block then\n -- Wiki links with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", ref, block)\n -- Markdown link with block.\n search_terms[#search_terms + 1] = string.format(\"(%s#%s\", ref, block)\n -- Markdown link with block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#%s\", ref, block)\n end\n end\n end\n end\n for alias in iter(note.aliases) do\n if anchor == nil and block == nil then\n -- Wiki link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", alias)\n -- Wiki link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif anchor then\n -- Wiki link with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif block then\n -- Wiki link with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", alias, block)\n end\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = opts.anchor ~= nil,\n collect_blocks = opts.block ~= nil,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n ---@param match MatchData\n local function on_match(match)\n local path = Path.new(match.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local n = path_to_note[path]\n if not n then\n local ok, res = pcall(Note.from_file_async, path, load_opts)\n if ok then\n n = res\n path_to_note[path] = n\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n if anchor then\n -- Check for a match with the anchor.\n -- NOTE: no need to do this with blocks, since blocks are standardized.\n local match_text = string.sub(match.lines.text, match.submatches[1].start)\n local link_location = util.parse_link(match_text)\n if not link_location then\n log.error(\"Failed to parse reference from '%s' ('%s')\", match_text, match)\n return\n end\n\n local anchor_link = select(2, util.strip_anchor_links(link_location))\n if not anchor_link then\n return\n end\n\n if anchor_link ~= anchor and anchor_obj ~= nil then\n local resolved_anchor = note:resolve_anchor_link(anchor_link)\n if resolved_anchor == nil or resolved_anchor.header ~= anchor_obj.header then\n return\n end\n end\n end\n\n ---@type obsidian.BacklinkMatch[]\n local line_matches = backlink_matches[path]\n if line_matches == nil then\n line_matches = {}\n backlink_matches[path] = line_matches\n end\n\n line_matches[#line_matches + 1] = {\n line = match.line_number,\n text = util.rstrip_whitespace(match.lines.text),\n }\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n -- Execute search.\n search.search_async(\n Obsidian.dir,\n util.tbl_unique(search_terms),\n self:_prepare_search_opts(opts.search, { fixed_strings = true, ignore_case = true }),\n on_match,\n function()\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.BacklinkMatches[]\n local results = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results.\n for i, path in ipairs(paths) do\n results[i] = { note = path_to_note[path], path = path, matches = backlink_matches[path] }\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return vim.tbl_filter(function(bl)\n return bl.matches ~= nil\n end, results)\n end, callback)\nend\n\n--- Gather a list of all tags in the vault. If 'term' is provided, only tags that partially match the search\n--- term will be included.\n---\n---@param term string|? An optional search term to match tags\n---@param timeout integer|? Timeout in milliseconds\n---\n---@return string[]\nClient.list_tags = function(self, term, timeout)\n local tags = {}\n for _, tag_loc in ipairs(self:find_tags(term and term or \"\", { timeout = timeout })) do\n tags[tag_loc.tag] = true\n end\n return vim.tbl_keys(tags)\nend\n\n--- An async version of 'list_tags()'.\n---\n---@param term string|?\n---@param callback fun(tags: string[])\nClient.list_tags_async = function(self, term, callback)\n self:find_tags_async(term and term or \"\", function(tag_locations)\n local tags = {}\n for _, tag_loc in ipairs(tag_locations) do\n local tag = tag_loc.tag:lower()\n if not tags[tag] then\n tags[tag] = true\n end\n end\n callback(vim.tbl_keys(tags))\n end)\nend\n\nreturn Client\n"], ["/obsidian.nvim/lua/obsidian/async.lua", "local abc = require \"obsidian.abc\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal uv = vim.uv\n\nlocal M = {}\n\n---An abstract class that mimics Python's `concurrent.futures.Executor` class.\n---@class obsidian.Executor : obsidian.ABC\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal Executor = abc.new_class()\n\n---@return obsidian.Executor\nExecutor.new = function()\n local self = Executor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback for the executor to run.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local,unused-vararg\nExecutor.submit = function(self, fn, callback, ...)\n error \"not implemented\"\nend\n\n---Map a function over a generator or array of task args, or the keys and values in a regular table.\n---The callback is called with an array of the results once all tasks have finished.\n---The order of the results passed to the callback will be the same as the order of the corresponding task args.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param task_args table[]|table|function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nExecutor.map = function(self, fn, task_args, callback)\n local results = {}\n local num_tasks = 0\n local tasks_completed = 0\n local all_submitted = false\n local tx, rx = channel.oneshot()\n\n local function collect_results()\n rx()\n return results\n end\n\n local function get_task_done_fn(i)\n return function(...)\n tasks_completed = tasks_completed + 1\n results[i] = { ... }\n if all_submitted and tasks_completed == num_tasks then\n tx()\n end\n end\n end\n\n if type(task_args) == \"table\" and util.islist(task_args) then\n num_tasks = #task_args\n for i, args in ipairs(task_args) do\n if i == #task_args then\n all_submitted = true\n end\n if type(args) ~= \"table\" then\n args = { args }\n end\n self:submit(fn, get_task_done_fn(i), unpack(args))\n end\n elseif type(task_args) == \"table\" then\n num_tasks = vim.tbl_count(task_args)\n local i = 0\n for k, v in pairs(task_args) do\n i = i + 1\n if i == #task_args then\n all_submitted = true\n end\n self:submit(fn, get_task_done_fn(i), k, v)\n end\n elseif type(task_args) == \"function\" then\n local i = 0\n local args = { task_args() }\n local next_args = { task_args() }\n while args[1] ~= nil do\n if next_args[1] == nil then\n all_submitted = true\n end\n i = i + 1\n num_tasks = num_tasks + 1\n self:submit(fn, get_task_done_fn(i), unpack(args))\n args = next_args\n next_args = { task_args() }\n end\n else\n error(string.format(\"unexpected type '%s' for 'task_args'\", type(task_args)))\n end\n\n if num_tasks == 0 then\n if callback ~= nil then\n callback {}\n end\n else\n async.run(collect_results, callback and callback or function(_) end)\n end\nend\n\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param pause_fn function(integer)\nExecutor._join = function(self, timeout, pause_fn)\n local start_time = uv.hrtime() / 1000000 -- ns -> ms\n local pause_for = 100\n if timeout ~= nil then\n pause_for = math.min(timeout / 2, pause_for)\n end\n while self.tasks_pending > 0 or self.tasks_running > 0 do\n pause_fn(pause_for)\n if timeout ~= nil and (uv.hrtime() / 1000000) - start_time > timeout then\n error \"Timeout error from Executor.join()\"\n end\n end\nend\n\n---Block Neovim until all currently running tasks have completed, waiting at most `timeout` milliseconds\n---before raising a timeout error.\n---\n---This is useful in testing, but in general you want to avoid blocking Neovim.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join = function(self, timeout)\n self:_join(timeout, vim.wait)\nend\n\n---An async version of `.join()`.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join_async = function(self, timeout)\n self:_join(timeout, async.util.sleep)\nend\n\n---Run the callback when the executor finishes all tasks.\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param callback function\nExecutor.join_and_then = function(self, timeout, callback)\n async.run(function()\n self:join_async(timeout)\n end, callback)\nend\n\n---An Executor that uses coroutines to run user functions concurrently.\n---@class obsidian.AsyncExecutor : obsidian.Executor\n---@field max_workers integer|?\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal AsyncExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"AsyncExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.AsyncExecutor = AsyncExecutor\n\n---@param max_workers integer|?\n---@return obsidian.AsyncExecutor\nAsyncExecutor.new = function(max_workers)\n local self = AsyncExecutor.init()\n if max_workers == nil then\n max_workers = 10\n elseif max_workers < 0 then\n max_workers = nil\n elseif max_workers == 0 then\n max_workers = 1\n end\n self.max_workers = max_workers\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.AsyncExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nAsyncExecutor.submit = function(self, fn, callback, ...)\n self.tasks_pending = self.tasks_pending + 1\n local args = { ... }\n async.run(function()\n if self.max_workers ~= nil then\n while self.tasks_running >= self.max_workers do\n async.util.sleep(20)\n end\n end\n self.tasks_pending = self.tasks_pending - 1\n self.tasks_running = self.tasks_running + 1\n return fn(unpack(args))\n end, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\nend\n\n---A multi-threaded Executor which uses the Libuv threadpool.\n---@class obsidian.ThreadPoolExecutor : obsidian.Executor\n---@field tasks_running integer\nlocal ThreadPoolExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"ThreadPoolExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.ThreadPoolExecutor = ThreadPoolExecutor\n\n---@return obsidian.ThreadPoolExecutor\nThreadPoolExecutor.new = function()\n local self = ThreadPoolExecutor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.ThreadPoolExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nThreadPoolExecutor.submit = function(self, fn, callback, ...)\n self.tasks_running = self.tasks_running + 1\n local ctx = uv.new_work(fn, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\n ctx:queue(...)\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@param sync boolean\nlocal init_job = function(cmds, on_stdout, on_exit, sync)\n local stderr_lines = false\n\n local on_obj = function(obj)\n --- NOTE: commands like `rg` return a non-zero exit code when there are no matches, which is okay.\n --- So we only log no-zero exit codes as errors when there's also stderr lines.\n if obj.code > 0 and stderr_lines then\n log.err(\"Command '%s' exited with non-zero code %s. See logs for stderr.\", cmds, obj.code)\n elseif stderr_lines then\n log.warn(\"Captured stderr output while running command '%s'. See logs for details.\", cmds)\n end\n if on_exit ~= nil then\n on_exit(obj.code)\n end\n end\n\n on_stdout = util.buffer_fn(on_stdout)\n\n local function stdout(err, data)\n if err ~= nil then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n end\n if data ~= nil then\n on_stdout(data)\n end\n end\n\n local function stderr(err, data)\n if err then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n elseif data ~= nil then\n if not stderr_lines then\n log.err(\"Captured stderr output while running command '%s'\", cmds)\n stderr_lines = true\n end\n log.err(\"[stderr] %s\", data)\n end\n end\n\n return function()\n log.debug(\"Initializing job '%s'\", cmds)\n\n if sync then\n local obj = vim.system(cmds, { stdout = stdout, stderr = stderr }):wait()\n on_obj(obj)\n return obj\n else\n vim.system(cmds, { stdout = stdout, stderr = stderr }, on_obj)\n end\n end\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@return integer exit_code\nM.run_job = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, true)\n return job().code\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\nM.run_job_async = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, false)\n job()\nend\n\n---@param fn function\n---@param timeout integer (milliseconds)\nM.throttle = function(fn, timeout)\n ---@type integer\n local last_call = 0\n ---@type uv.uv_timer_t?\n local timer = nil\n\n return function(...)\n if timer ~= nil then\n timer:stop()\n end\n\n local ms_remaining = timeout - (vim.uv.now() - last_call)\n\n if ms_remaining > 0 then\n if timer == nil then\n timer = assert(vim.uv.new_timer())\n end\n\n local args = { ... }\n\n timer:start(\n ms_remaining,\n 0,\n vim.schedule_wrap(function()\n if timer ~= nil then\n timer:stop()\n timer:close()\n timer = nil\n end\n\n last_call = vim.uv.now()\n fn(unpack(args))\n end)\n )\n else\n last_call = vim.uv.now()\n fn(...)\n end\n end\nend\n\n---Run an async function in a non-async context. The async function is expected to take a single\n---callback parameters with the results. This function returns those results.\n---@param async_fn_with_callback function (function,) -> any\n---@param timeout integer|?\n---@return ...any results\nM.block_on = function(async_fn_with_callback, timeout)\n local done = false\n local result\n timeout = timeout and timeout or 2000\n\n local function collect_result(...)\n result = { ... }\n done = true\n end\n\n async_fn_with_callback(collect_result)\n\n vim.wait(timeout, function()\n return done\n end, 20, false)\n\n return unpack(result)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/init.lua", "local iter = vim.iter\nlocal log = require \"obsidian.log\"\nlocal legacycommands = require \"obsidian.commands.init-legacy\"\nlocal search = require \"obsidian.search\"\n\nlocal M = { commands = {} }\n\nlocal function in_note()\n return vim.bo.filetype == \"markdown\"\nend\n\n---@param commands obsidian.CommandConfig[]\n---@param is_visual boolean\n---@param is_note boolean\n---@return string[]\nlocal function get_commands_by_context(commands, is_visual, is_note)\n local choices = vim.tbl_values(commands)\n return vim\n .iter(choices)\n :filter(function(config)\n if is_visual then\n return config.range ~= nil\n else\n return config.range == nil\n end\n end)\n :filter(function(config)\n if is_note then\n return true\n else\n return not config.note_action\n end\n end)\n :map(function(config)\n return config.name\n end)\n :totable()\nend\n\nlocal function show_menu(data)\n local is_visual, is_note = data.range ~= 0, in_note()\n local choices = get_commands_by_context(M.commands, is_visual, is_note)\n\n vim.ui.select(choices, { prompt = \"Obsidian Commands\" }, function(item)\n if item then\n return vim.cmd.Obsidian(item)\n else\n vim.notify(\"Aborted\", 3)\n end\n end)\nend\n\n---@class obsidian.CommandConfig\n---@field complete function|string|?\n---@field nargs string|integer|?\n---@field range boolean|?\n---@field func function|? (obsidian.Client, table) -> nil\n---@field name string?\n---@field note_action boolean?\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfig\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n local mod = require(\"obsidian.commands.\" .. name)\n return mod(client, data)\n end\n end\n config.name = name\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n vim.api.nvim_create_user_command(\"Obsidian\", function(data)\n if #data.fargs == 0 then\n show_menu(data)\n return\n end\n M.handle_command(client, data)\n end, {\n nargs = \"*\",\n complete = function(_, cmdline, _)\n return M.get_completions(client, cmdline)\n end,\n range = 2,\n })\nend\n\nM.install_legacy = legacycommands.install\n\n---@param client obsidian.Client\nM.handle_command = function(client, data)\n local cmd = data.fargs[1]\n table.remove(data.fargs, 1)\n data.args = table.concat(data.fargs, \" \")\n local nargs = #data.fargs\n\n local cmdconfig = M.commands[cmd]\n if cmdconfig == nil then\n log.err(\"Command '\" .. cmd .. \"' not found\")\n return\n end\n\n local exp_nargs = cmdconfig.nargs\n local range_allowed = cmdconfig.range\n\n if exp_nargs == \"?\" then\n if nargs > 1 then\n log.err(\"Command '\" .. cmd .. \"' expects 0 or 1 arguments, but \" .. nargs .. \" were provided\")\n return\n end\n elseif exp_nargs == \"+\" then\n if nargs == 0 then\n log.err(\"Command '\" .. cmd .. \"' expects at least one argument, but none were provided\")\n return\n end\n elseif exp_nargs ~= \"*\" and exp_nargs ~= nargs then\n log.err(\"Command '\" .. cmd .. \"' expects \" .. exp_nargs .. \" arguments, but \" .. nargs .. \" were provided\")\n return\n end\n\n if not range_allowed and data.range > 0 then\n log.error(\"Command '\" .. cmd .. \"' does not accept a range\")\n return\n end\n\n cmdconfig.func(client, data)\nend\n\n---@param client obsidian.Client\n---@param cmdline string\nM.get_completions = function(client, cmdline)\n local obspat = \"^['<,'>]*Obsidian[!]?\"\n local splitcmd = vim.split(cmdline, \" \", { plain = true, trimempty = true })\n local obsidiancmd = splitcmd[2]\n if cmdline:match(obspat .. \"%s$\") then\n local is_visual = vim.startswith(cmdline, \"'<,'>\")\n return get_commands_by_context(M.commands, is_visual, in_note())\n end\n if cmdline:match(obspat .. \"%s%S+$\") then\n return vim.tbl_filter(function(s)\n return s:sub(1, #obsidiancmd) == obsidiancmd\n end, vim.tbl_keys(M.commands))\n end\n local cmdconfig = M.commands[obsidiancmd]\n if cmdconfig == nil then\n return\n end\n if cmdline:match(obspat .. \"%s%S*%s%S*$\") then\n local cmd_arg = table.concat(vim.list_slice(splitcmd, 3), \" \")\n local complete_type = type(cmdconfig.complete)\n if complete_type == \"function\" then\n return cmdconfig.complete(cmd_arg)\n end\n if complete_type == \"string\" then\n return vim.fn.getcompletion(cmd_arg, cmdconfig.complete)\n end\n end\nend\n\n--TODO: Note completion is currently broken (see: https://github.com/epwalsh/obsidian.nvim/issues/753)\n---@return string[]\nM.note_complete = function(cmd_arg)\n local query\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\n------------------------\n---- general action ----\n------------------------\n\nM.register(\"check\", { nargs = 0 })\n\nM.register(\"today\", { nargs = \"?\" })\n\nM.register(\"yesterday\", { nargs = 0 })\n\nM.register(\"tomorrow\", { nargs = 0 })\n\nM.register(\"dailies\", { nargs = \"*\" })\n\nM.register(\"new\", { nargs = \"?\" })\n\nM.register(\"open\", { nargs = \"?\", complete = M.note_complete })\n\nM.register(\"tags\", { nargs = \"*\" })\n\nM.register(\"search\", { nargs = \"?\" })\n\nM.register(\"new_from_template\", { nargs = \"*\" })\n\nM.register(\"quick_switch\", { nargs = \"?\" })\n\nM.register(\"workspace\", { nargs = \"?\" })\n\n---------------------\n---- note action ----\n---------------------\n\nM.register(\"backlinks\", { nargs = 0, note_action = true })\n\nM.register(\"template\", { nargs = \"?\", note_action = true })\n\nM.register(\"link_new\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"link\", { nargs = \"?\", range = true, complete = M.note_complete, note_action = true })\n\nM.register(\"links\", { nargs = 0, note_action = true })\n\nM.register(\"follow_link\", { nargs = \"?\", note_action = true })\n\nM.register(\"toggle_checkbox\", { nargs = 0, range = true, note_action = true })\n\nM.register(\"rename\", { nargs = \"?\", note_action = true })\n\nM.register(\"paste_img\", { nargs = \"?\", note_action = true })\n\nM.register(\"extract_note\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"toc\", { nargs = 0, note_action = true })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/yaml/parser.lua", "local Line = require \"obsidian.yaml.line\"\nlocal abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\n\nlocal m = {}\n\n---@class obsidian.yaml.ParserOpts\n---@field luanil boolean\nlocal ParserOpts = {}\n\nm.ParserOpts = ParserOpts\n\n---@return obsidian.yaml.ParserOpts\nParserOpts.default = function()\n return {\n luanil = true,\n }\nend\n\n---@param opts table\n---@return obsidian.yaml.ParserOpts\nParserOpts.normalize = function(opts)\n ---@type obsidian.yaml.ParserOpts\n opts = vim.tbl_extend(\"force\", ParserOpts.default(), opts)\n return opts\nend\n\n---@class obsidian.yaml.Parser : obsidian.ABC\n---@field opts obsidian.yaml.ParserOpts\nlocal Parser = abc.new_class()\n\nm.Parser = Parser\n\n---@enum YamlType\nlocal YamlType = {\n Scalar = \"Scalar\", -- a boolean, string, number, or NULL\n Mapping = \"Mapping\",\n Array = \"Array\",\n ArrayItem = \"ArrayItem\",\n EmptyLine = \"EmptyLine\",\n}\n\nm.YamlType = YamlType\n\n---@class vim.NIL\n\n---Create a new Parser.\n---@param opts obsidian.yaml.ParserOpts|?\n---@return obsidian.yaml.Parser\nm.new = function(opts)\n local self = Parser.init()\n self.opts = ParserOpts.normalize(opts and opts or {})\n return self\nend\n\n---Parse a YAML string.\n---@param str string\n---@return any\nParser.parse = function(self, str)\n -- Collect and pre-process lines.\n local lines = {}\n local base_indent = 0\n for raw_line in str:gmatch \"[^\\r\\n]+\" do\n local ok, result = pcall(Line.new, raw_line, base_indent)\n if ok then\n local line = result\n if #lines == 0 then\n base_indent = line.indent\n line.indent = 0\n end\n table.insert(lines, line)\n else\n local err = result\n error(self:_error_msg(tostring(err), #lines + 1))\n end\n end\n\n -- Now iterate over the root elements, differing to `self:_parse_next()` to recurse into child elements.\n ---@type any\n local root_value = nil\n ---@type table|?\n local parent = nil\n local current_indent = 0\n local i = 1\n while i <= #lines do\n local line = lines[i]\n\n if line:is_empty() then\n -- Empty line, skip it.\n i = i + 1\n elseif line.indent == current_indent then\n local value\n local value_type\n i, value, value_type = self:_parse_next(lines, i)\n assert(value_type ~= YamlType.EmptyLine)\n if root_value == nil and line.indent == 0 then\n -- Set the root value.\n if value_type == YamlType.ArrayItem then\n root_value = { value }\n else\n root_value = value\n end\n\n -- The parent must always be a table (array or mapping), so set that to the root value now\n -- if we have a table.\n if type(root_value) == \"table\" then\n parent = root_value\n end\n elseif util.islist(parent) and value_type == YamlType.ArrayItem then\n -- Add value to parent array.\n parent[#parent + 1] = value\n elseif type(parent) == \"table\" and value_type == YamlType.Mapping then\n assert(parent ~= nil) -- for type checking\n -- Add value to parent mapping.\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if parent[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i, line.content))\n else\n parent[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value\", i, line.content))\n end\n else\n error(self:_error_msg(\"invalid indentation\", i))\n end\n current_indent = line.indent\n end\n\n return root_value\nend\n\n---Parse the next single item, recursing to child blocks if necessary.\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@param text string|?\n---@return integer, any, string\nParser._parse_next = function(self, lines, i, text)\n local line = lines[i]\n if text == nil then\n -- Skip empty lines.\n while line:is_empty() and i <= #lines do\n i = i + 1\n line = lines[i]\n end\n if line:is_empty() then\n return i, nil, YamlType.EmptyLine\n end\n text = util.strip_comments(line.content)\n end\n\n local _, ok, value\n\n -- First just check for a string enclosed in quotes.\n if util.has_enclosing_chars(text) then\n _, _, value = self:_parse_string(i, text)\n return i + 1, value, YamlType.Scalar\n end\n\n -- Check for array item, like `- foo`.\n ok, i, value = self:_try_parse_array_item(lines, i, text)\n if ok then\n return i, value, YamlType.ArrayItem\n end\n\n -- Check for a block string field, like `foo: |`.\n ok, i, value = self:_try_parse_block_string(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Check for any other `key: value` fields.\n ok, i, value = self:_try_parse_field(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Otherwise we have an inline value.\n local value_type\n value, value_type = self:_parse_inline_value(i, text)\n return i + 1, value, value_type\nend\n\n---@return vim.NIL|nil\nParser._new_null = function(self)\n if self.opts.luanil then\n return nil\n else\n return vim.NIL\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param msg string\n---@param line_num integer\n---@param line_text string|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nParser._error_msg = function(self, msg, line_num, line_text)\n local full_msg = \"[line=\" .. tostring(line_num) .. \"] \" .. msg\n if line_text ~= nil then\n full_msg = full_msg .. \" (text='\" .. line_text .. \"')\"\n end\n return full_msg\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_field = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n\n local _, key, value\n\n -- First look for start of mapping, array, block, etc, e.g. 'foo:'\n _, _, key = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*):$\")\n if not key then\n -- Then try inline field, e.g. 'foo: bar'\n _, _, key, value = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*): (.*)\")\n end\n\n value = value and vim.trim(value) or nil\n if value == \"\" then\n value = nil\n end\n\n if key ~= nil and value ~= nil then\n -- This is a mapping, e.g. `foo: 1`.\n local out = {}\n value = self:_parse_inline_value(i, value)\n local j = i + 1\n -- Check for multi-line string here.\n local next_line = lines[j]\n if type(value) == \"string\" and next_line ~= nil and next_line.indent > line.indent then\n local next_indent = next_line.indent\n while next_line ~= nil and next_line.indent == next_indent do\n local next_value_str = util.strip_comments(next_line.content)\n if string.len(next_value_str) > 0 then\n local next_value = self:_parse_inline_value(j, next_line.content)\n if type(next_value) ~= \"string\" then\n error(self:_error_msg(\"expected a string, found \" .. type(next_value), j, next_line.content))\n end\n value = value .. \" \" .. next_value\n end\n j = j + 1\n next_line = lines[j]\n end\n end\n out[key] = value\n return true, j, out\n elseif key ~= nil then\n local out = {}\n local next_line = lines[i + 1]\n local j = i + 1\n if next_line ~= nil and next_line.indent >= line.indent and vim.startswith(next_line.content, \"- \") then\n -- This is the start of an array.\n local array\n j, array = self:_parse_array(lines, j)\n out[key] = array\n elseif next_line ~= nil and next_line.indent > line.indent then\n -- This is the start of a mapping.\n local mapping\n j, mapping = self:_parse_mapping(j, lines)\n out[key] = mapping\n else\n -- This is an implicit null field.\n out[key] = self:_new_null()\n end\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_block_string = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n local _, _, block_key = string.find(text, \"([a-zA-Z0-9_-]+):%s?|\")\n if block_key ~= nil then\n local block_lines = {}\n local j = i + 1\n local next_line = lines[j]\n if next_line == nil then\n error(self:_error_msg(\"expected another line\", i, text))\n end\n local item_indent = next_line.indent\n while j <= #lines do\n next_line = lines[j]\n if next_line ~= nil and next_line.indent >= item_indent then\n j = j + 1\n table.insert(block_lines, util.lstrip_whitespace(next_line.raw_content, item_indent))\n else\n break\n end\n end\n local out = {}\n out[block_key] = table.concat(block_lines, \"\\n\")\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_array_item = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n if vim.startswith(text, \"- \") then\n local _, _, array_item_str = string.find(text, \"- (.*)\")\n local value\n -- Check for null entry.\n if array_item_str == \"\" then\n value = self:_new_null()\n i = i + 1\n else\n i, value = self:_parse_next(lines, i, array_item_str)\n end\n return true, i, value\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@return integer, any[]\nParser._parse_array = function(self, lines, i)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent and vim.startswith(line.content, \"- \") then\n local is_array_item, value\n is_array_item, i, value = self:_try_parse_array_item(lines, i)\n assert(is_array_item)\n out[#out + 1] = value\n elseif line:is_empty() then\n i = i + 1\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse an array but didn't find any entries\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@return integer, table\nParser._parse_mapping = function(self, i, lines)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent then\n local value, value_type\n i, value, value_type = self:_parse_next(lines, i)\n if value_type == YamlType.Mapping then\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if out[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i))\n else\n out[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value found found in table\", i))\n end\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse a mapping but didn't find any entries to parse\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return any, string\nParser._parse_inline_value = function(self, i, text)\n for parse_func_and_type in iter {\n { self._parse_number, YamlType.Scalar },\n { self._parse_null, YamlType.Scalar },\n { self._parse_boolean, YamlType.Scalar },\n { self._parse_inline_array, YamlType.Array },\n { self._parse_inline_mapping, YamlType.Mapping },\n { self._parse_string, YamlType.Scalar },\n } do\n local parse_func, parse_type = unpack(parse_func_and_type)\n local ok, errmsg, res = parse_func(self, i, text)\n if ok then\n return res, parse_type\n elseif errmsg ~= nil then\n error(errmsg)\n end\n end\n -- Should never get here because we always fall back to parsing as a string.\n error(self:_error_msg(\"unable to parse\", i))\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, any[]|?\nParser._parse_inline_array = function(self, i, text)\n local str\n if vim.startswith(text, \"[\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"]\") then\n str = string.sub(str, 1, -2)\n else\n return false, nil, nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n local item_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n item_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n item_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n item_str, str = util.next_item(str, { \",\" }, false)\n end\n if item_str == nil then\n return false, self:_error_msg(\"invalid inline array\", i, text), nil\n end\n out[#out + 1] = self:_parse_inline_value(i, item_str)\n\n if vim.startswith(str, \",\") then\n str = string.sub(str, 2)\n end\n str = util.lstrip_whitespace(str)\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, table|?\nParser._parse_inline_mapping = function(self, i, text)\n local str\n if vim.startswith(text, \"{\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"}\") then\n str = string.sub(str, 1, -2)\n else\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n -- Parse the key.\n local key_str\n key_str, str = util.next_item(str, { \":\" }, false)\n if key_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local _, _, key = self:_parse_string(i, key_str)\n\n -- Parse the value.\n str = util.lstrip_whitespace(str)\n local value_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n value_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n value_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n value_str, str = util.next_item(str, { \",\" }, false)\n end\n if value_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local value = self:_parse_inline_value(i, value_str)\n if out[key] == nil then\n out[key] = value\n else\n return false, self:_error_msg(\"duplicate key '\" .. key .. \"' found in inline mapping\", i, text), nil\n end\n\n if vim.startswith(str, \",\") then\n str = util.lstrip_whitespace(string.sub(str, 2))\n end\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, string\n---@diagnostic disable-next-line: unused-local\nParser._parse_string = function(self, i, text)\n if vim.startswith(text, [[\"]]) and vim.endswith(text, [[\"]]) then\n -- when the text is enclosed with double-quotes we need to un-escape certain characters.\n text = string.gsub(text, vim.pesc [[\\\"]], [[\"]])\n end\n return true, nil, util.strip_enclosing_chars(vim.trim(text))\nend\n\n---Parse a string value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return string\nParser.parse_string = function(self, text)\n local _, _, str = self:_parse_string(1, util.strip_comments(text))\n return str\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, number|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_number = function(self, i, text)\n local out = tonumber(text)\n if out == nil or util.isNan(out) then\n return false, nil, nil\n else\n return true, nil, out\n end\nend\n\n---Parse a number value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return number\nParser.parse_number = function(self, text)\n local ok, errmsg, res = self:_parse_number(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a number\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, boolean|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_boolean = function(self, i, text)\n if text == \"true\" then\n return true, nil, true\n elseif text == \"false\" then\n return true, nil, false\n else\n return false, nil, nil\n end\nend\n\n---Parse a boolean value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean\nParser.parse_boolean = function(self, text)\n local ok, errmsg, res = self:_parse_boolean(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a boolean\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean, string|?, vim.NIL|nil\n---@diagnostic disable-next-line: unused-local\nParser._parse_null = function(self, i, text)\n if text == \"null\" or text == \"\" then\n return true, nil, self:_new_null()\n else\n return false, nil, nil\n end\nend\n\n---Parse a NULL value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return vim.NIL|nil\nParser.parse_null = function(self, text)\n local ok, errmsg, res = self:_parse_null(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a null value\", 1, text)\n error(errmsg)\n else\n return res\n end\nend\n\n---Deserialize a YAML string.\nm.loads = function(str)\n local parser = m.new()\n return parser:parse(str)\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/refs.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.RefsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field in_buffer_only boolean\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\n---@field block_link string|?\n---@field anchor_link string|?\n---@field new_text_to_option table\nlocal RefsSourceCompletionContext = abc.new_class()\n\nRefsSourceCompletionContext.new = function()\n return RefsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.RefsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal RefsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.RefsSourceBase\nRefsSourceBase.new = function()\n return RefsSourceBase.init()\nend\n\nRefsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = RefsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n completion_context.in_buffer_only = false\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n self:strip_links(cc)\n self:determine_buffer_only_search_scope(cc)\n\n if cc.in_buffer_only then\n local note = api.current_note(0, { collect_anchor_links = true, collect_blocks = true })\n if note then\n self:process_search_results(cc, { note })\n else\n cc.completion_resolve_callback(self.incomplete_response)\n end\n else\n local search_ops = cc.client.search_defaults()\n search_ops.ignore_case = true\n\n search.find_notes_async(cc.search, function(results)\n self:process_search_results(cc, results)\n end, {\n search = search_ops,\n notes = { collect_anchor_links = cc.anchor_link ~= nil, collect_blocks = cc.block_link ~= nil },\n })\n end\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction RefsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\n---Collect matching block links.\n---@param note obsidian.Note\n---@param block_link string?\n---@return obsidian.note.Block[]|?\nfunction RefsSourceBase:collect_matching_blocks(note, block_link)\n ---@type obsidian.note.Block[]|?\n local matching_blocks\n if block_link then\n assert(note.blocks)\n matching_blocks = {}\n for block_id, block_data in pairs(note.blocks) do\n if vim.startswith(\"#\" .. block_id, block_link) then\n table.insert(matching_blocks, block_data)\n end\n end\n\n if #matching_blocks == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_blocks, { id = util.standardize_block(block_link), line = 1 })\n end\n end\n\n return matching_blocks\nend\n\n---Collect matching anchor links.\n---@param note obsidian.Note\n---@param anchor_link string?\n---@return obsidian.note.HeaderAnchor[]?\nfunction RefsSourceBase:collect_matching_anchors(note, anchor_link)\n ---@type obsidian.note.HeaderAnchor[]|?\n local matching_anchors\n if anchor_link then\n assert(note.anchor_links)\n matching_anchors = {}\n for anchor, anchor_data in pairs(note.anchor_links) do\n if vim.startswith(anchor, anchor_link) then\n table.insert(matching_anchors, anchor_data)\n end\n end\n\n if #matching_anchors == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_anchors, { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 })\n end\n end\n\n return matching_anchors\nend\n\n--- Strips block and anchor links from the current search string\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:strip_links(cc)\n cc.search, cc.block_link = util.strip_block_links(cc.search)\n cc.search, cc.anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, we'll match against all block links.\n if not cc.block_link and vim.endswith(cc.search, \"#^\") then\n cc.block_link = \"#^\"\n cc.search = string.sub(cc.search, 1, -3)\n end\n\n -- If anchor link is incomplete, we'll match against all anchor links.\n if not cc.anchor_link and vim.endswith(cc.search, \"#\") then\n cc.anchor_link = \"#\"\n cc.search = string.sub(cc.search, 1, -2)\n end\nend\n\n--- Determines whatever the in_buffer_only should be enabled\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:determine_buffer_only_search_scope(cc)\n if (cc.anchor_link or cc.block_link) and string.len(cc.search) == 0 then\n -- Search over headers/blocks in current buffer only.\n cc.in_buffer_only = true\n end\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param results obsidian.Note[]\nfunction RefsSourceBase:process_search_results(cc, results)\n assert(cc)\n assert(results)\n\n local completion_items = {}\n\n cc.new_text_to_option = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local matching_blocks = self:collect_matching_blocks(note, cc.block_link)\n local matching_anchors = self:collect_matching_anchors(note, cc.anchor_link)\n\n if cc.in_buffer_only then\n self:update_completion_options(cc, nil, nil, matching_anchors, matching_blocks, note)\n else\n -- Collect all valid aliases for the note, including ID, title, and filename.\n ---@type string[]\n local aliases\n if not cc.in_buffer_only then\n aliases = util.tbl_unique { tostring(note.id), note:display_name(), unpack(note.aliases) }\n if note.title ~= nil then\n table.insert(aliases, note.title)\n end\n end\n\n for alias in iter(aliases) do\n self:update_completion_options(cc, alias, nil, matching_anchors, matching_blocks, note)\n local alias_case_matched = util.match_case(cc.search, alias)\n\n if\n alias_case_matched ~= nil\n and alias_case_matched ~= alias\n and not vim.list_contains(note.aliases, alias_case_matched)\n and Obsidian.opts.completion.match_case\n then\n self:update_completion_options(cc, alias_case_matched, nil, matching_anchors, matching_blocks, note)\n end\n end\n\n if note.alt_alias ~= nil then\n self:update_completion_options(cc, note:display_name(), note.alt_alias, matching_anchors, matching_blocks, note)\n end\n end\n end\n\n for _, option in pairs(cc.new_text_to_option) do\n -- TODO: need a better label, maybe just the note's display name?\n ---@type string\n local label\n if cc.ref_type == completion.RefType.Wiki then\n label = string.format(\"[[%s]]\", option.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n label = string.format(\"[%s](…)\", option.label)\n else\n error \"not implemented\"\n end\n\n table.insert(completion_items, {\n documentation = option.documentation,\n sortText = option.sort_text,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = option.new_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n })\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = completion_items }))\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param label string|?\n---@param alt_label string|?\n---@param note obsidian.Note\nfunction RefsSourceBase:update_completion_options(cc, label, alt_label, matching_anchors, matching_blocks, note)\n ---@type { label: string|?, alt_label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }[]\n local new_options = {}\n if matching_anchors ~= nil then\n for anchor in iter(matching_anchors) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor })\n end\n elseif matching_blocks ~= nil then\n for block in iter(matching_blocks) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block })\n end\n else\n if label then\n table.insert(new_options, { label = label, alt_label = alt_label })\n end\n\n -- Add all blocks and anchors, let cmp sort it out.\n for _, anchor_data in pairs(note.anchor_links or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor_data })\n end\n for _, block_data in pairs(note.blocks or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block_data })\n end\n end\n\n -- De-duplicate options relative to their `new_text`.\n for _, option in ipairs(new_options) do\n ---@type obsidian.config.LinkStyle\n local link_style\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n else\n error \"not implemented\"\n end\n\n ---@type string, string, string, table|?\n local final_label, sort_text, new_text, documentation\n if option.label then\n new_text = api.format_link(\n note,\n { label = option.label, link_style = link_style, anchor = option.anchor, block = option.block }\n )\n\n final_label = assert(option.alt_label or option.label)\n if option.anchor then\n final_label = final_label .. option.anchor.anchor\n elseif option.block then\n final_label = final_label .. \"#\" .. option.block.id\n end\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = note:display_info {\n label = new_text,\n anchor = option.anchor,\n block = option.block,\n },\n }\n elseif option.anchor then\n -- In buffer anchor link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.anchor.header .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.anchor.header .. \"](\" .. option.anchor.anchor .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = option.anchor.anchor\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n elseif option.block then\n -- In buffer block link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.block.id .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.block.id .. \"](#\" .. option.block.id .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = \"#\" .. option.block.id\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n else\n error \"should not happen\"\n end\n\n if cc.new_text_to_option[new_text] then\n cc.new_text_to_option[new_text].sort_text = cc.new_text_to_option[new_text].sort_text .. \" \" .. sort_text\n else\n cc.new_text_to_option[new_text] =\n { label = final_label, new_text = new_text, sort_text = sort_text, documentation = documentation }\n end\n end\nend\n\nreturn RefsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/pickers/_fzf.lua", "local fzf = require \"fzf-lua\"\nlocal fzf_actions = require \"fzf-lua.actions\"\nlocal entry_to_file = require(\"fzf-lua.path\").entry_to_file\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@param prompt_title string|?\n---@return string|?\nlocal function format_prompt(prompt_title)\n if not prompt_title then\n return\n else\n return prompt_title .. \" ❯ \"\n end\nend\n\n---@param keymap string\n---@return string\nlocal function format_keymap(keymap)\n keymap = string.lower(keymap)\n keymap = string.gsub(keymap, vim.pesc \"\", \"\")\n return keymap\nend\n\n---@class obsidian.pickers.FzfPicker : obsidian.Picker\nlocal FzfPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"FzfPicker()\"\n end,\n}, Picker)\n\n---@param opts { callback: fun(path: string)|?, no_default_mappings: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_path_actions(opts)\n local actions = {\n default = function(selected, fzf_opts)\n if not opts.no_default_mappings then\n fzf_actions.file_edit_or_qf(selected, fzf_opts)\n end\n\n if opts.callback then\n local path = entry_to_file(selected[1], fzf_opts).path\n opts.callback(path)\n end\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected, fzf_opts)\n local path = entry_to_file(selected[1], fzf_opts).path\n mapping.callback(path)\n end\n end\n end\n\n return actions\nend\n\n---@param display_to_value_map table\n---@param opts { callback: fun(path: string)|?, allow_multiple: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_value_actions(display_to_value_map, opts)\n ---@param allow_multiple boolean|?\n ---@return any[]|?\n local function get_values(selected, allow_multiple)\n if not selected then\n return\n end\n\n local values = vim.tbl_map(function(k)\n return display_to_value_map[k]\n end, selected)\n\n values = vim.tbl_filter(function(v)\n return v ~= nil\n end, values)\n\n if #values > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if #values > 0 then\n return values\n else\n return nil\n end\n end\n\n local actions = {\n default = function(selected)\n if not opts.callback then\n return\n end\n\n local values = get_values(selected, opts.allow_multiple)\n if not values then\n return\n end\n\n opts.callback(unpack(values))\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected)\n local values = get_values(selected, mapping.allow_multiple)\n if not values then\n return\n end\n\n mapping.callback(unpack(values))\n end\n end\n end\n\n return actions\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nFzfPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path.new(opts.dir) or Obsidian.dir\n\n fzf.files {\n cwd = tostring(dir),\n cmd = table.concat(self:_build_find_cmd(), \" \"),\n actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n },\n prompt = format_prompt(opts.prompt_title),\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nFzfPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n local cmd = table.concat(self:_build_grep_cmd(), \" \")\n local actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n if opts.query and string.len(opts.query) > 0 then\n fzf.grep {\n cwd = tostring(dir),\n search = opts.query,\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n else\n fzf.live_grep {\n cwd = tostring(dir),\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nFzfPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n ---@type table\n local display_to_value_map = {}\n\n ---@type string[]\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n display_to_value_map[value] = value\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n local display = self:_make_display(value)\n display_to_value_map[display] = value.value\n entries[#entries + 1] = display\n end\n end\n\n fzf.fzf_exec(entries, {\n prompt = format_prompt(\n self:_build_prompt { prompt_title = opts.prompt_title, selection_mappings = opts.selection_mappings }\n ),\n actions = get_value_actions(display_to_value_map, {\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n selection_mappings = opts.selection_mappings,\n }),\n })\nend\n\nreturn FzfPicker\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/blink.lua", "local util = require \"obsidian.util\"\nlocal obsidian = require \"obsidian\"\n\nlocal M = {}\n\nM.injected_once = false\n\nM.providers = {\n { name = \"obsidian\", module = \"obsidian.completion.sources.blink.refs\" },\n { name = \"obsidian_tags\", module = \"obsidian.completion.sources.blink.tags\" },\n}\n\nlocal function add_provider(blink, provider_name, proivder_module)\n local add_source_provider = blink.add_source_provider or blink.add_provider\n add_source_provider(provider_name, {\n name = provider_name,\n module = proivder_module,\n async = true,\n opts = {},\n enabled = function()\n -- Enable only in markdown buffers.\n return vim.tbl_contains({ \"markdown\" }, vim.bo.filetype)\n and vim.bo.buftype ~= \"prompt\"\n and vim.b.completion ~= false\n end,\n })\nend\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_providers(opts)\n local blink = require \"blink.cmp\"\n\n if opts.completion.create_new then\n table.insert(M.providers, { name = \"obsidian_new\", module = \"obsidian.completion.sources.blink.new\" })\n end\n\n for _, provider in pairs(M.providers) do\n add_provider(blink, provider.name, provider.module)\n end\nend\n\nlocal function add_element_to_list_if_not_exists(list, element)\n if not vim.tbl_contains(list, element) then\n table.insert(list, 1, element)\n end\nend\n\nlocal function should_return_if_not_in_workspace()\n local current_file_path = vim.api.nvim_buf_get_name(0)\n local buf_dir = vim.fs.dirname(current_file_path)\n\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return true\n else\n return false\n end\nend\n\nlocal function log_unexpected_type(config_path, unexpected_type, expected_type)\n vim.notify(\n \"blink.cmp's `\"\n .. config_path\n .. \"` configuration appears to be an '\"\n .. unexpected_type\n .. \"' type, but it \"\n .. \"should be '\"\n .. expected_type\n .. \"'. Obsidian won't update this configuration, and \"\n .. \"completion won't work with blink.cmp\",\n vim.log.levels.ERROR\n )\nend\n\n---Attempts to inject the Obsidian sources into per_filetype if that's what the user seems to use for markdown\n---@param blink_sources_per_filetype table\n---@return boolean true if it obsidian sources were injected into the sources.per_filetype\nlocal function try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype)\n -- If the per_filetype is an empty object, then it's probably not utilized by the user\n if vim.deep_equal(blink_sources_per_filetype, {}) then\n return false\n end\n\n local markdown_config = blink_sources_per_filetype[\"markdown\"]\n\n -- If the markdown key is not used, then per_filetype it's probably not utilized by the user\n if markdown_config == nil then\n return false\n end\n\n local markdown_config_type = type(markdown_config)\n if markdown_config_type == \"table\" and util.islist(markdown_config) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(markdown_config, provider.name)\n end\n return true\n elseif markdown_config_type == \"function\" then\n local original_func = markdown_config\n markdown_config = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.per_filetype[\"markdown\"] = markdown_config\n return true\n else\n log_unexpected_type(\n \".sources.per_filetype['markdown']\",\n markdown_config_type,\n \"a list or a function that returns a list of sources\"\n )\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n---Attempts to inject the Obsidian sources into default if that's what the user seems to use for markdown\n---@param blink_sources_default (fun():string[])|(string[])\n---@return boolean true if it obsidian sources were injected into the sources.default\nlocal function try_inject_blink_sources_into_default(blink_sources_default)\n local blink_default_type = type(blink_sources_default)\n if blink_default_type == \"function\" then\n local original_func = blink_sources_default\n blink_sources_default = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.default = blink_sources_default\n return true\n elseif blink_default_type == \"table\" and util.islist(blink_sources_default) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(blink_sources_default, provider.name)\n end\n\n return true\n elseif blink_default_type == \"table\" then\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n else\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list or a function that returns a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace. nvm_cmp had the capability to configure the sources\n-- per buffer, but blink.cmp doesn't have that capability. Instead, we have to inject the sources into the global\n-- configuration and set a boolean on the module to return early the next time this function is called.\n--\n-- In-case the user used functions to configure their sources, the completion will properly work just for the markdown\n-- files that are in a workspace. Otherwise, the completion will work for all markdown files.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n if M.injected_once then\n return\n end\n\n M.injected_once = true\n\n local blink_config = require \"blink.cmp.config\"\n -- 'per_filetype' sources has priority over 'default' sources.\n -- 'per_filetype' can be a table or a function which returns a table ([\"filetype\"] = { \"a\", \"b\" })\n -- 'per_filetype' has the default value of {} (even if it's not configured by the user)\n local blink_sources_per_filetype = blink_config.sources.per_filetype\n if try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype) then\n return\n end\n\n -- 'default' can be a list/array or a function which returns a list/array ({ \"a\", \"b\"})\n local blink_sources_default = blink_config.sources[\"default\"]\n if try_inject_blink_sources_into_default(blink_sources_default) then\n return\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/ui.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal M = {}\n\nlocal NAMESPACE = \"ObsidianUI\"\n\n---@param ui_opts obsidian.config.UIOpts\nlocal function install_hl_groups(ui_opts)\n for group_name, opts in pairs(ui_opts.hl_groups) do\n vim.api.nvim_set_hl(0, group_name, opts)\n end\nend\n\n-- We cache marks locally to help avoid redrawing marks when its not necessary. The main reason\n-- we need to do this is because the conceal char we get back from `nvim_buf_get_extmarks()` gets mangled.\n-- For example, \"󰄱\" is turned into \"1\\1\\15\".\n-- TODO: if we knew how to un-mangle the conceal char we wouldn't need the cache.\n\nM._buf_mark_cache = vim.defaulttable()\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\n---@return ExtMark|?\nlocal function cache_get(bufnr, ns_id, mark_id)\n local buf_ns_cache = M._buf_mark_cache[bufnr][ns_id]\n return buf_ns_cache[mark_id]\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark ExtMark\n---@return ExtMark|?\nlocal function cache_set(bufnr, ns_id, mark)\n assert(mark.id ~= nil)\n M._buf_mark_cache[bufnr][ns_id][mark.id] = mark\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\nlocal function cache_evict(bufnr, ns_id, mark_id)\n M._buf_mark_cache[bufnr][ns_id][mark_id] = nil\nend\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function cache_clear(bufnr, ns_id)\n M._buf_mark_cache[bufnr][ns_id] = {}\nend\n\n---@class ExtMark : obsidian.ABC\n---@field id integer|? ID of the mark, only set for marks that are actually materialized in the buffer.\n---@field row integer 0-based row index to place the mark.\n---@field col integer 0-based col index to place the mark.\n---@field opts ExtMarkOpts Optional parameters passed directly to `nvim_buf_set_extmark()`.\nlocal ExtMark = abc.new_class {\n __eq = function(a, b)\n return a.row == b.row and a.col == b.col and a.opts == b.opts\n end,\n}\n\nM.ExtMark = ExtMark\n\n---@class ExtMarkOpts : obsidian.ABC\n---@field end_row integer\n---@field end_col integer\n---@field conceal string|?\n---@field hl_group string|?\n---@field spell boolean|?\nlocal ExtMarkOpts = abc.new_class()\n\nM.ExtMarkOpts = ExtMarkOpts\n\n---@param data table\n---@return ExtMarkOpts\nExtMarkOpts.from_tbl = function(data)\n local self = ExtMarkOpts.init()\n self.end_row = data.end_row\n self.end_col = data.end_col\n self.conceal = data.conceal\n self.hl_group = data.hl_group\n self.spell = data.spell\n return self\nend\n\n---@param self ExtMarkOpts\n---@return table\nExtMarkOpts.to_tbl = function(self)\n return {\n end_row = self.end_row,\n end_col = self.end_col,\n conceal = self.conceal,\n hl_group = self.hl_group,\n spell = self.spell,\n }\nend\n\n---@param id integer|?\n---@param row integer\n---@param col integer\n---@param opts ExtMarkOpts\n---@return ExtMark\nExtMark.new = function(id, row, col, opts)\n local self = ExtMark.init()\n self.id = id\n self.row = row\n self.col = col\n self.opts = opts\n return self\nend\n\n---Materialize the ExtMark if needed. After calling this the 'id' will be set if it wasn't already.\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return ExtMark\nExtMark.materialize = function(self, bufnr, ns_id)\n if self.id == nil then\n self.id = vim.api.nvim_buf_set_extmark(bufnr, ns_id, self.row, self.col, self.opts:to_tbl())\n end\n cache_set(bufnr, ns_id, self)\n return self\nend\n\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return boolean\nExtMark.clear = function(self, bufnr, ns_id)\n if self.id ~= nil then\n cache_evict(bufnr, ns_id, self.id)\n return vim.api.nvim_buf_del_extmark(bufnr, ns_id, self.id)\n else\n return false\n end\nend\n\n---Collect all existing (materialized) marks within a region.\n---@param bufnr integer\n---@param ns_id integer\n---@param region_start integer|integer[]|?\n---@param region_end integer|integer[]|?\n---@return ExtMark[]\nExtMark.collect = function(bufnr, ns_id, region_start, region_end)\n region_start = region_start and region_start or 0\n region_end = region_end and region_end or -1\n local marks = {}\n for data in iter(vim.api.nvim_buf_get_extmarks(bufnr, ns_id, region_start, region_end, { details = true })) do\n local mark = ExtMark.new(data[1], data[2], data[3], ExtMarkOpts.from_tbl(data[4]))\n -- NOTE: since the conceal char we get back from `nvim_buf_get_extmarks()` is mangled, e.g.\n -- \"󰄱\" is turned into \"1\\1\\15\", we used the cached version.\n local cached_mark = cache_get(bufnr, ns_id, mark.id)\n if cached_mark ~= nil then\n mark.opts.conceal = cached_mark.opts.conceal\n end\n cache_set(bufnr, ns_id, mark)\n marks[#marks + 1] = mark\n end\n return marks\nend\n\n---Clear all existing (materialized) marks with a line region.\n---@param bufnr integer\n---@param ns_id integer\n---@param line_start integer\n---@param line_end integer\nExtMark.clear_range = function(bufnr, ns_id, line_start, line_end)\n return vim.api.nvim_buf_clear_namespace(bufnr, ns_id, line_start, line_end)\nend\n\n---Clear all existing (materialized) marks on a line.\n---@param bufnr integer\n---@param ns_id integer\n---@param line integer\nExtMark.clear_line = function(bufnr, ns_id, line)\n return ExtMark.clear_range(bufnr, ns_id, line, line + 1)\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_check_extmarks(marks, line, lnum, ui_opts)\n for char, opts in pairs(ui_opts.checkboxes) do\n if string.match(line, \"^%s*- %[\" .. vim.pesc(char) .. \"%]\") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 5,\n conceal = opts.char,\n hl_group = opts.hl_group,\n }\n )\n return marks\n end\n end\n\n if ui_opts.bullets ~= nil and string.match(line, \"^%s*[-%*%+] \") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 1,\n conceal = ui_opts.bullets.char,\n hl_group = ui_opts.bullets.hl_group,\n }\n )\n end\n\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_ref_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_refs(line, { include_naked_urls = true, include_tags = true, include_block_ids = true })\n for match in iter(matches) do\n local m_start, m_end, m_type = unpack(match)\n if m_type == search.RefTypes.WikiWithAlias then\n -- Reference of the form [[xxx|yyy]]\n local pipe_loc = string.find(line, \"|\", m_start, true)\n assert(pipe_loc)\n -- Conceal everything from '[[' up to '|'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = pipe_loc,\n conceal = \"\",\n }\n )\n -- Highlight the alias 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n pipe_loc,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Wiki then\n -- Reference of the form [[xxx]]\n -- Conceal the opening '[['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'xxx'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Markdown then\n -- Reference of the form [yyy](xxx)\n local closing_bracket_loc = string.find(line, \"]\", m_start, true)\n assert(closing_bracket_loc)\n local is_url = util.is_url(string.sub(line, closing_bracket_loc + 2, m_end - 1))\n -- Conceal the opening '['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc - 1,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the ']('\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc + 1,\n conceal = is_url and \" \" or \"\",\n }\n )\n -- Conceal the URL part 'xxx' with the external URL character\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 1,\n conceal = is_url and ui_opts.external_link_icon.char or \"\",\n hl_group = ui_opts.external_link_icon.hl_group,\n }\n )\n -- Conceal the closing ')'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = is_url and \" \" or \"\",\n }\n )\n elseif m_type == search.RefTypes.NakedUrl then\n -- A \"naked\" URL is just a URL by itself, like 'https://github.com/'\n local domain_start_loc = string.find(line, \"://\", m_start, true)\n assert(domain_start_loc)\n domain_start_loc = domain_start_loc + 3\n -- Conceal the \"https?://\" part\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = domain_start_loc - 1,\n conceal = \"\",\n }\n )\n -- Highlight the whole thing.\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.Tag then\n -- A tag is like '#tag'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.tags.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.BlockID then\n -- A block ID, like '^hello-world'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.block_ids.hl_group,\n spell = false,\n }\n )\n end\n end\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_highlight(line)\n for match in iter(matches) do\n local m_start, m_end, _ = unpack(match)\n -- Conceal opening '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight text in the middle\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.highlight_text.hl_group,\n spell = false,\n }\n )\n -- Conceal closing '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n end\n return marks\nend\n\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal get_line_marks = function(line, lnum, ui_opts)\n local marks = {}\n get_line_check_extmarks(marks, line, lnum, ui_opts)\n get_line_ref_extmarks(marks, line, lnum, ui_opts)\n get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n return marks\nend\n\n---@param bufnr integer\n---@param ui_opts obsidian.config.UIOpts\nlocal function update_extmarks(bufnr, ns_id, ui_opts)\n local start_time = vim.uv.hrtime()\n local n_marks_added = 0\n local n_marks_cleared = 0\n\n -- Collect all current marks, grouped by line.\n local cur_marks_by_line = vim.defaulttable()\n for mark in iter(ExtMark.collect(bufnr, ns_id)) do\n local cur_line_marks = cur_marks_by_line[mark.row]\n cur_line_marks[#cur_line_marks + 1] = mark\n end\n\n -- Iterate over lines (skipping code blocks) and update marks.\n local inside_code_block = false\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, true)\n for i, line in ipairs(lines) do\n local lnum = i - 1\n local cur_line_marks = cur_marks_by_line[lnum]\n\n local function clear_line()\n ExtMark.clear_line(bufnr, ns_id, lnum)\n n_marks_cleared = n_marks_cleared + #cur_line_marks\n for mark in iter(cur_line_marks) do\n cache_evict(bufnr, ns_id, mark.id)\n end\n end\n\n -- Check if inside a code block or at code block boundary. If not, update marks.\n if string.match(line, \"^%s*```[^`]*$\") then\n inside_code_block = not inside_code_block\n -- Remove any existing marks here on the boundary of a code block.\n clear_line()\n elseif not inside_code_block then\n -- Get all marks that should be materialized.\n -- Some of these might already be materialized, which we'll check below and avoid re-drawing\n -- if that's the case.\n local new_line_marks = get_line_marks(line, lnum, ui_opts)\n if #new_line_marks > 0 then\n -- Materialize new marks.\n for mark in iter(new_line_marks) do\n if not vim.list_contains(cur_line_marks, mark) then\n mark:materialize(bufnr, ns_id)\n n_marks_added = n_marks_added + 1\n end\n end\n\n -- Clear old marks.\n for mark in iter(cur_line_marks) do\n if not vim.list_contains(new_line_marks, mark) then\n mark:clear(bufnr, ns_id)\n n_marks_cleared = n_marks_cleared + 1\n end\n end\n else\n -- Remove any existing marks here since there are no new marks.\n clear_line()\n end\n else\n -- Remove any existing marks here since we're inside a code block.\n clear_line()\n end\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n log.debug(\"Added %d new marks, cleared %d old marks in %dms\", n_marks_added, n_marks_cleared, runtime)\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param bufnr integer|?\n---@return boolean\nlocal function should_update(ui_opts, bufnr)\n if ui_opts.enable == false then\n return false\n end\n\n bufnr = bufnr or 0\n\n if not vim.endswith(vim.api.nvim_buf_get_name(bufnr), \".md\") then\n return false\n end\n\n if ui_opts.max_file_length ~= nil and vim.fn.line \"$\" > ui_opts.max_file_length then\n return false\n end\n\n return true\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param throttle boolean\n---@return function\nlocal function get_extmarks_autocmd_callback(ui_opts, throttle)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n\n local callback = function(ev)\n if not should_update(ui_opts, ev.bufnr) then\n return\n end\n update_extmarks(ev.buf, ns_id, ui_opts)\n end\n\n if throttle then\n return require(\"obsidian.async\").throttle(callback, ui_opts.update_debounce)\n else\n return callback\n end\nend\n\n---Manually update extmarks.\n---\n---@param bufnr integer|?\nM.update = function(bufnr)\n bufnr = bufnr or 0\n local ui_opts = Obsidian.opts.ui\n if not should_update(ui_opts, bufnr) then\n return\n end\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n update_extmarks(bufnr, ns_id, ui_opts)\nend\n\n---@param workspace obsidian.Workspace\n---@param ui_opts obsidian.config.UIOpts\nM.setup = function(workspace, ui_opts)\n if ui_opts.enable == false then\n return\n end\n\n local group = vim.api.nvim_create_augroup(\"ObsidianUI\" .. workspace.name, { clear = true })\n\n install_hl_groups(ui_opts)\n\n local pattern = tostring(workspace.root) .. \"/**.md\"\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = function()\n local conceallevel = vim.opt_local.conceallevel:get()\n\n if (conceallevel < 1 or conceallevel > 2) and not ui_opts.ignore_conceal_warn then\n log.warn_once(\n \"Obsidian additional syntax features require 'conceallevel' to be set to 1 or 2, \"\n .. \"but you have 'conceallevel' set to '%s'.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/issues/286 for more details.\\n\"\n .. \"If you don't want Obsidian's additional UI features, you can disable them and suppress \"\n .. \"this warning by setting 'ui.enable = false' in your Obsidian nvim config.\",\n conceallevel\n )\n end\n\n -- delete the autocommand\n return true\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, false),\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\", \"TextChanged\", \"TextChangedI\", \"TextChangedP\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, true),\n })\n\n vim.api.nvim_create_autocmd({ \"BufUnload\" }, {\n group = group,\n pattern = pattern,\n callback = function(ev)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n cache_clear(ev.buf, ns_id)\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/init-legacy.lua", "local util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal command_lookups = {\n ObsidianCheck = \"obsidian.commands.check\",\n ObsidianToggleCheckbox = \"obsidian.commands.toggle_checkbox\",\n ObsidianToday = \"obsidian.commands.today\",\n ObsidianYesterday = \"obsidian.commands.yesterday\",\n ObsidianTomorrow = \"obsidian.commands.tomorrow\",\n ObsidianDailies = \"obsidian.commands.dailies\",\n ObsidianNew = \"obsidian.commands.new\",\n ObsidianOpen = \"obsidian.commands.open\",\n ObsidianBacklinks = \"obsidian.commands.backlinks\",\n ObsidianSearch = \"obsidian.commands.search\",\n ObsidianTags = \"obsidian.commands.tags\",\n ObsidianTemplate = \"obsidian.commands.template\",\n ObsidianNewFromTemplate = \"obsidian.commands.new_from_template\",\n ObsidianQuickSwitch = \"obsidian.commands.quick_switch\",\n ObsidianLinkNew = \"obsidian.commands.link_new\",\n ObsidianLink = \"obsidian.commands.link\",\n ObsidianLinks = \"obsidian.commands.links\",\n ObsidianFollowLink = \"obsidian.commands.follow_link\",\n ObsidianWorkspace = \"obsidian.commands.workspace\",\n ObsidianRename = \"obsidian.commands.rename\",\n ObsidianPasteImg = \"obsidian.commands.paste_img\",\n ObsidianExtractNote = \"obsidian.commands.extract_note\",\n ObsidianTOC = \"obsidian.commands.toc\",\n}\n\nlocal M = setmetatable({\n commands = {},\n}, {\n __index = function(t, k)\n local require_path = command_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@class obsidian.CommandConfigLegacy\n---@field opts table\n---@field complete function|?\n---@field func function|? (obsidian.Client, table) -> nil\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfigLegacy\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n return M[name](client, data)\n end\n end\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n for command_name, command_config in pairs(M.commands) do\n local func = function(data)\n command_config.func(client, data)\n end\n\n if command_config.complete ~= nil then\n command_config.opts.complete = function(arg_lead, cmd_line, cursor_pos)\n return command_config.complete(client, arg_lead, cmd_line, cursor_pos)\n end\n end\n\n vim.api.nvim_create_user_command(command_name, func, command_config.opts)\n end\nend\n\n---@param client obsidian.Client\n---@return string[]\nM.complete_args_search = function(client, _, cmd_line, _)\n local query\n local cmd_arg, _ = util.lstrip_whitespace(string.gsub(cmd_line, \"^.*Obsidian[A-Za-z0-9]+\", \"\"))\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\nM.register(\"ObsidianCheck\", { opts = { nargs = 0, desc = \"Check for issues in your vault\" } })\n\nM.register(\"ObsidianToday\", { opts = { nargs = \"?\", desc = \"Open today's daily note\" } })\n\nM.register(\"ObsidianYesterday\", { opts = { nargs = 0, desc = \"Open the daily note for the previous working day\" } })\n\nM.register(\"ObsidianTomorrow\", { opts = { nargs = 0, desc = \"Open the daily note for the next working day\" } })\n\nM.register(\"ObsidianDailies\", { opts = { nargs = \"*\", desc = \"Open a picker with daily notes\" } })\n\nM.register(\"ObsidianNew\", { opts = { nargs = \"?\", desc = \"Create a new note\" } })\n\nM.register(\n \"ObsidianOpen\",\n { opts = { nargs = \"?\", desc = \"Open in the Obsidian app\" }, complete = M.complete_args_search }\n)\n\nM.register(\"ObsidianBacklinks\", { opts = { nargs = 0, desc = \"Collect backlinks\" } })\n\nM.register(\"ObsidianTags\", { opts = { nargs = \"*\", range = true, desc = \"Find tags\" } })\n\nM.register(\"ObsidianSearch\", { opts = { nargs = \"?\", desc = \"Search vault\" } })\n\nM.register(\"ObsidianTemplate\", { opts = { nargs = \"?\", desc = \"Insert a template\" } })\n\nM.register(\"ObsidianNewFromTemplate\", { opts = { nargs = \"*\", desc = \"Create a new note from a template\" } })\n\nM.register(\"ObsidianQuickSwitch\", { opts = { nargs = \"?\", desc = \"Switch notes\" } })\n\nM.register(\"ObsidianLinkNew\", { opts = { nargs = \"?\", range = true, desc = \"Link selected text to a new note\" } })\n\nM.register(\"ObsidianLink\", {\n opts = { nargs = \"?\", range = true, desc = \"Link selected text to an existing note\" },\n complete = M.complete_args_search,\n})\n\nM.register(\"ObsidianLinks\", { opts = { nargs = 0, desc = \"Collect all links within the current buffer\" } })\n\nM.register(\"ObsidianFollowLink\", { opts = { nargs = \"?\", desc = \"Follow reference or link under cursor\" } })\n\nM.register(\"ObsidianToggleCheckbox\", { opts = { nargs = 0, desc = \"Toggle checkbox\", range = true } })\n\nM.register(\"ObsidianWorkspace\", { opts = { nargs = \"?\", desc = \"Check or switch workspace\" } })\n\nM.register(\"ObsidianRename\", { opts = { nargs = \"?\", desc = \"Rename note and update all references to it\" } })\n\nM.register(\"ObsidianPasteImg\", { opts = { nargs = \"?\", desc = \"Paste an image from the clipboard\" } })\n\nM.register(\n \"ObsidianExtractNote\",\n { opts = { nargs = \"?\", range = true, desc = \"Extract selected text to a new note and link to it\" } }\n)\n\nM.register(\"ObsidianTOC\", { opts = { nargs = 0, desc = \"Load the table of contents into a picker\" } })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/_mini.lua", "local mini_pick = require \"mini.pick\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\n---@param entry string\n---@return string\nlocal function clean_path(entry)\n local path_end = assert(string.find(entry, \":\", 1, true))\n return string.sub(entry, 1, path_end - 1)\nend\n\n---@class obsidian.pickers.MiniPicker : obsidian.Picker\nlocal MiniPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"MiniPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nMiniPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local path = mini_pick.builtin.cli({\n command = self:_build_find_cmd(),\n }, {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n })\n\n if path and opts.callback then\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nMiniPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local pick_opts = {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n }\n\n ---@type string|?\n local result\n if opts.query and string.len(opts.query) > 0 then\n result = mini_pick.builtin.grep({ pattern = opts.query }, pick_opts)\n else\n result = mini_pick.builtin.grep_live({}, pick_opts)\n end\n\n if result and opts.callback then\n local path = clean_path(result)\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nMiniPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n entries[#entries + 1] = {\n value = value.value,\n text = self:_make_display(value),\n path = value.filename,\n lnum = value.lnum,\n col = value.col,\n }\n end\n end\n\n local entry = mini_pick.start {\n source = {\n name = opts.prompt_title,\n items = entries,\n choose = function() end,\n },\n }\n\n if entry and opts.callback then\n if type(entry) == \"string\" then\n opts.callback(entry)\n else\n opts.callback(entry.value)\n end\n end\nend\n\nreturn MiniPicker\n"], ["/obsidian.nvim/lua/obsidian/pickers/_telescope.lua", "local telescope = require \"telescope.builtin\"\nlocal telescope_actions = require \"telescope.actions\"\nlocal actions_state = require \"telescope.actions.state\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.pickers.TelescopePicker : obsidian.Picker\nlocal TelescopePicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"TelescopePicker()\"\n end,\n}, Picker)\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@return table|?\nlocal function get_entry(prompt_bufnr, keep_open)\n local entry = actions_state.get_selected_entry()\n if entry and not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return entry\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param allow_multiple boolean|?\n---@return table[]|?\nlocal function get_selected(prompt_bufnr, keep_open, allow_multiple)\n local picker = actions_state.get_current_picker(prompt_bufnr)\n local entries = picker:get_multi_selection()\n if entries and #entries > 0 then\n if #entries > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n\n return entries\n else\n local entry = get_entry(prompt_bufnr, keep_open)\n\n if entry then\n return { entry }\n end\n end\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param initial_query string|?\n---@return string|?\nlocal function get_query(prompt_bufnr, keep_open, initial_query)\n local query = actions_state.get_current_line()\n if not query or string.len(query) == 0 then\n query = initial_query\n end\n if query and string.len(query) > 0 then\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return query\n else\n return nil\n end\nend\n\n---@param opts { entry_key: string|?, callback: fun(path: string)|?, allow_multiple: boolean|?, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|?, initial_query: string|? }\nlocal function attach_picker_mappings(map, opts)\n -- Docs for telescope actions:\n -- https://github.com/nvim-telescope/telescope.nvim/blob/master/lua/telescope/actions/init.lua\n\n local function entry_to_value(entry)\n if opts.entry_key then\n return entry[opts.entry_key]\n else\n return entry\n end\n end\n\n if opts.query_mappings then\n for key, mapping in pairs(opts.query_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local query = get_query(prompt_bufnr, false, opts.initial_query)\n if query then\n mapping.callback(query)\n end\n end)\n end\n end\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, mapping.keep_open, mapping.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n mapping.callback(unpack(values))\n elseif mapping.fallback_to_query then\n local query = get_query(prompt_bufnr, mapping.keep_open)\n if query then\n mapping.callback(query)\n end\n end\n end)\n end\n end\n\n if opts.callback then\n map({ \"i\", \"n\" }, \"\", function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, false, opts.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n opts.callback(unpack(values))\n end\n end)\n end\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nTelescopePicker.find_files = function(self, opts)\n opts = opts or {}\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n telescope.find_files {\n prompt_title = prompt_title,\n cwd = opts.dir and tostring(opts.dir) or tostring(Obsidian.dir),\n find_command = self:_build_find_cmd(),\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nTelescopePicker.grep = function(self, opts)\n opts = opts or {}\n\n local cwd = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n initial_query = opts.query,\n })\n return true\n end\n\n if opts.query and string.len(opts.query) > 0 then\n telescope.grep_string {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n search = opts.query,\n attach_mappings = attach_mappings,\n }\n else\n telescope.live_grep {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n attach_mappings = attach_mappings,\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\nTelescopePicker.pick = function(self, values, opts)\n local pickers = require \"telescope.pickers\"\n local finders = require \"telescope.finders\"\n local conf = require \"telescope.config\"\n local make_entry = require \"telescope.make_entry\"\n\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local picker_opts = {\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"value\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\n\n local displayer = function(entry)\n return self:_make_display(entry.raw)\n end\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local previewer\n if type(values[1]) == \"table\" then\n previewer = conf.values.grep_previewer(picker_opts)\n -- Get theme to use.\n if conf.pickers then\n for _, picker_name in ipairs { \"grep_string\", \"live_grep\", \"find_files\" } do\n local picker_conf = conf.pickers[picker_name]\n if picker_conf and picker_conf.theme then\n picker_opts =\n vim.tbl_extend(\"force\", picker_opts, require(\"telescope.themes\")[\"get_\" .. picker_conf.theme] {})\n break\n end\n end\n end\n end\n\n local make_entry_from_string = make_entry.gen_from_string(picker_opts)\n\n pickers\n .new(picker_opts, {\n prompt_title = prompt_title,\n finder = finders.new_table {\n results = values,\n entry_maker = function(v)\n if type(v) == \"string\" then\n return make_entry_from_string(v)\n else\n local ordinal = v.ordinal\n if ordinal == nil then\n ordinal = \"\"\n if type(v.display) == \"string\" then\n ordinal = ordinal .. v.display\n end\n if v.filename ~= nil then\n ordinal = ordinal .. \" \" .. v.filename\n end\n end\n\n return {\n value = v.value,\n display = displayer,\n ordinal = ordinal,\n filename = v.filename,\n valid = v.valid,\n lnum = v.lnum,\n col = v.col,\n raw = v,\n }\n end\n end,\n },\n sorter = conf.values.generic_sorter(picker_opts),\n previewer = previewer,\n })\n :find()\nend\n\nreturn TelescopePicker\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/new.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.NewNoteSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\nlocal NewNoteSourceCompletionContext = abc.new_class()\n\nNewNoteSourceCompletionContext.new = function()\n return NewNoteSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.NewNoteSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal NewNoteSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.NewNoteSourceBase\nNewNoteSourceBase.new = function()\n return NewNoteSourceBase.init()\nend\n\nNewNoteSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = NewNoteSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n ---@type string|?\n local block_link\n cc.search, block_link = util.strip_block_links(cc.search)\n\n ---@type string|?\n local anchor_link\n cc.search, anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, do nothing.\n if not block_link and vim.endswith(cc.search, \"#^\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- If anchor link is incomplete, do nothing.\n if not anchor_link and vim.endswith(cc.search, \"#\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Probably just a block/anchor link within current note.\n if string.len(cc.search) == 0 then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Create a mock block.\n ---@type obsidian.note.Block|?\n local block\n if block_link then\n block = { block = \"\", id = util.standardize_block(block_link), line = 1 }\n end\n\n -- Create a mock anchor.\n ---@type obsidian.note.HeaderAnchor|?\n local anchor\n if anchor_link then\n anchor = { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 }\n end\n\n ---@type { label: string, note: obsidian.Note, template: string|? }[]\n local new_notes_opts = {}\n\n local note = Note.create { title = cc.search }\n if note.title and string.len(note.title) > 0 then\n new_notes_opts[#new_notes_opts + 1] = { label = cc.search, note = note }\n end\n\n -- Check for datetime macros.\n for _, dt_offset in ipairs(util.resolve_date_macro(cc.search)) do\n if dt_offset.cadence == \"daily\" then\n note = require(\"obsidian.daily\").daily(dt_offset.offset, { no_write = true })\n if not note:exists() then\n new_notes_opts[#new_notes_opts + 1] =\n { label = dt_offset.macro, note = note, template = Obsidian.opts.daily_notes.template }\n end\n end\n end\n\n -- Completion items.\n local items = {}\n\n for _, new_note_opts in ipairs(new_notes_opts) do\n local new_note = new_note_opts.note\n\n assert(new_note.path)\n\n ---@type obsidian.config.LinkStyle, string\n local link_style, label\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n label = string.format(\"[[%s]] (create)\", new_note_opts.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n label = string.format(\"[%s](…) (create)\", new_note_opts.label)\n else\n error \"not implemented\"\n end\n\n local new_text = api.format_link(new_note, { link_style = link_style, anchor = anchor, block = block })\n local documentation = {\n kind = \"markdown\",\n value = new_note:display_info {\n label = \"Create: \" .. new_text,\n },\n }\n\n items[#items + 1] = {\n documentation = documentation,\n sortText = new_note_opts.label,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = new_text,\n range = {\n start = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n data = {\n note = new_note,\n template = new_note_opts.template,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction NewNoteSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if cc.search ~= nil then\n cc.search = util.lstrip_whitespace(cc.search)\n end\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n return true\nend\n\n--- Runs a generalized version of the execute method\n---@param item any\n---@return table|? callback_return_value\nfunction NewNoteSourceBase:process_execute(item)\n local data = item.data\n\n if data == nil then\n return nil\n end\n\n -- Make sure `data.note` is actually an `obsidian.Note` object. If it gets serialized at some\n -- point (seems to happen on Linux), it will lose its metatable.\n if not Note.is_note_obj(data.note) then\n data.note = setmetatable(data.note, Note.mt)\n data.note.path = setmetatable(data.note.path, Path.mt)\n end\n\n data.note:write { template = data.template }\n return {}\nend\n\nreturn NewNoteSourceBase\n"], ["/obsidian.nvim/lua/obsidian/init.lua", "local log = require \"obsidian.log\"\n\nlocal module_lookups = {\n abc = \"obsidian.abc\",\n api = \"obsidian.api\",\n async = \"obsidian.async\",\n Client = \"obsidian.client\",\n commands = \"obsidian.commands\",\n completion = \"obsidian.completion\",\n config = \"obsidian.config\",\n log = \"obsidian.log\",\n img_paste = \"obsidian.img_paste\",\n Note = \"obsidian.note\",\n Path = \"obsidian.path\",\n pickers = \"obsidian.pickers\",\n search = \"obsidian.search\",\n templates = \"obsidian.templates\",\n ui = \"obsidian.ui\",\n util = \"obsidian.util\",\n VERSION = \"obsidian.version\",\n Workspace = \"obsidian.workspace\",\n yaml = \"obsidian.yaml\",\n}\n\nlocal obsidian = setmetatable({}, {\n __index = function(t, k)\n local require_path = module_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@type obsidian.Client|?\nobsidian._client = nil\n\n---Get the current obsidian client.\n---@return obsidian.Client\nobsidian.get_client = function()\n if obsidian._client == nil then\n error \"Obsidian client has not been set! Did you forget to call 'setup()'?\"\n else\n return obsidian._client\n end\nend\n\nobsidian.register_command = require(\"obsidian.commands\").register\n\n--- Setup a new Obsidian client. This should only be called once from an Nvim session.\n---\n---@param opts obsidian.config.ClientOpts | table\n---\n---@return obsidian.Client\nobsidian.setup = function(opts)\n opts = obsidian.config.normalize(opts)\n\n ---@class obsidian.state\n ---@field picker obsidian.Picker The picker instance to use.\n ---@field workspace obsidian.Workspace The current workspace.\n ---@field dir obsidian.Path The root of the vault for the current workspace.\n ---@field buf_dir obsidian.Path|? The parent directory of the current buffer.\n ---@field opts obsidian.config.ClientOpts current options\n ---@field _opts obsidian.config.ClientOpts default options\n _G.Obsidian = {} -- init a state table\n\n local client = obsidian.Client.new(opts)\n\n Obsidian._opts = opts\n\n obsidian.Workspace.set(assert(obsidian.Workspace.get_from_opts(opts)), {})\n\n log.set_level(Obsidian.opts.log_level)\n\n -- Install commands.\n -- These will be available across all buffers, not just note buffers in the vault.\n obsidian.commands.install(client)\n\n if opts.legacy_commands then\n obsidian.commands.install_legacy(client)\n end\n\n if opts.statusline.enabled then\n require(\"obsidian.statusline\").start(client)\n end\n\n if opts.footer.enabled then\n require(\"obsidian.footer\").start(client)\n end\n\n -- Register completion sources, providers\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").register_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").register_providers(opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_setup\", { clear = true })\n\n -- wrapper for creating autocmd events\n ---@param pattern string\n ---@param buf integer\n local function exec_autocmds(pattern, buf)\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = pattern,\n data = {\n note = require(\"obsidian.note\").from_buffer(buf),\n },\n })\n end\n\n -- Complete setup and update workspace (if needed) when entering a markdown buffer.\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Set the current directory of the buffer.\n local buf_dir = vim.fs.dirname(ev.match)\n if buf_dir then\n Obsidian.buf_dir = obsidian.Path.new(buf_dir)\n end\n\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n if opts.comment.enabled then\n vim.o.commentstring = \"%%%s%%\"\n end\n\n -- Switch to the workspace and complete the workspace setup.\n if not Obsidian.workspace.locked and workspace ~= Obsidian.workspace then\n log.debug(\"Switching to workspace '%s' @ '%s'\", workspace.name, workspace.path)\n obsidian.Workspace.set(workspace)\n require(\"obsidian.ui\").update(ev.buf)\n end\n\n -- Register keymap.\n vim.keymap.set(\n \"n\",\n \"\",\n obsidian.api.smart_action,\n { expr = true, buffer = true, desc = \"Obsidian Smart Action\" }\n )\n\n vim.keymap.set(\"n\", \"]o\", function()\n obsidian.api.nav_link \"next\"\n end, { buffer = true, desc = \"Obsidian Next Link\" })\n\n vim.keymap.set(\"n\", \"[o\", function()\n obsidian.api.nav_link \"prev\"\n end, { buffer = true, desc = \"Obsidian Previous Link\" })\n\n -- Inject completion sources, providers to their plugin configurations\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").inject_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").inject_sources(opts)\n end\n\n -- Run enter-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"enter_note\", Obsidian.opts.callbacks.enter_note, client, note)\n\n exec_autocmds(\"ObsidianNoteEnter\", ev.buf)\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufLeave\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(vim.fs.dirname(ev.match), Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Run leave-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"leave_note\", Obsidian.opts.callbacks.leave_note, client, note)\n\n exec_autocmds(\"ObsidianNoteLeave\", ev.buf)\n end,\n })\n\n -- Add/update frontmatter for notes before writing.\n vim.api.nvim_create_autocmd({ \"BufWritePre\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Initialize note.\n local bufnr = ev.buf\n local note = obsidian.Note.from_buffer(bufnr)\n\n -- Run pre-write-note callback.\n obsidian.util.fire_callback(\"pre_write_note\", Obsidian.opts.callbacks.pre_write_note, client, note)\n\n exec_autocmds(\"ObsidianNoteWritePre\", ev.buf)\n\n -- Update buffer with new frontmatter.\n if note:update_frontmatter(bufnr) then\n log.info \"Updated frontmatter\"\n end\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufWritePost\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n exec_autocmds(\"ObsidianNoteWritePost\", ev.buf)\n end,\n })\n\n -- Set global client.\n obsidian._client = client\n\n obsidian.util.fire_callback(\"post_setup\", Obsidian.opts.callbacks.post_setup, client)\n\n return client\nend\n\nreturn obsidian\n"], ["/obsidian.nvim/lua/obsidian/yaml/init.lua", "local util = require \"obsidian.util\"\nlocal parser = require \"obsidian.yaml.parser\"\n\nlocal yaml = {}\n\n---Deserialize a YAML string.\n---@param str string\n---@return any\nyaml.loads = function(str)\n return parser.loads(str)\nend\n\n---@param s string\n---@return boolean\nlocal should_quote = function(s)\n -- TODO: this probably doesn't cover all edge cases.\n -- See https://www.yaml.info/learn/quote.html\n -- Check if it starts with a special character.\n if string.match(s, [[^[\"'\\\\[{&!-].*]]) then\n return true\n -- Check if it has a colon followed by whitespace.\n elseif string.find(s, \": \", 1, true) then\n return true\n -- Check if it's an empty string.\n elseif s == \"\" or string.match(s, \"^[%s]+$\") then\n return true\n else\n return false\n end\nend\n\n---@return string[]\nlocal dumps\ndumps = function(x, indent, order)\n local indent_str = string.rep(\" \", indent)\n\n if type(x) == \"string\" then\n if should_quote(x) then\n x = string.gsub(x, '\"', '\\\\\"')\n return { indent_str .. [[\"]] .. x .. [[\"]] }\n else\n return { indent_str .. x }\n end\n end\n\n if type(x) == \"boolean\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"number\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"table\" then\n local out = {}\n\n if util.islist(x) then\n for _, v in ipairs(x) do\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. \"- \" .. util.lstrip_whitespace(item_lines[1]))\n for i = 2, #item_lines do\n table.insert(out, item_lines[i])\n end\n end\n else\n -- Gather and sort keys so we can keep the order deterministic.\n local keys = {}\n for k, _ in pairs(x) do\n table.insert(keys, k)\n end\n table.sort(keys, order)\n for _, k in ipairs(keys) do\n local v = x[k]\n if type(v) == \"string\" or type(v) == \"boolean\" or type(v) == \"number\" then\n table.insert(out, indent_str .. tostring(k) .. \": \" .. dumps(v, 0)[1])\n elseif type(v) == \"table\" and vim.tbl_isempty(v) then\n table.insert(out, indent_str .. tostring(k) .. \": []\")\n else\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. tostring(k) .. \":\")\n for _, line in ipairs(item_lines) do\n table.insert(out, line)\n end\n end\n end\n end\n\n return out\n end\n\n error(\"Can't convert object with type \" .. type(x) .. \" to YAML\")\nend\n\n---Dump an object to YAML lines.\n---@param x any\n---@param order function\n---@return string[]\nyaml.dumps_lines = function(x, order)\n return dumps(x, 0, order)\nend\n\n---Dump an object to a YAML string.\n---@param x any\n---@param order function|?\n---@return string\nyaml.dumps = function(x, order)\n return table.concat(dumps(x, 0, order), \"\\n\")\nend\n\nreturn yaml\n"], ["/obsidian.nvim/lua/obsidian/commands/backlinks.lua", "local util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal RefTypes = require(\"obsidian.search\").RefTypes\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param note obsidian.Note\n---@param opts { anchor: string|?, block: string|? }|?\nlocal function collect_backlinks(client, picker, note, opts)\n opts = opts or {}\n\n client:find_backlinks_async(note, function(backlinks)\n if vim.tbl_isempty(backlinks) then\n if opts.anchor then\n log.info(\"No backlinks found for anchor '%s' in note '%s'\", opts.anchor, note.id)\n elseif opts.block then\n log.info(\"No backlinks found for block '%s' in note '%s'\", opts.block, note.id)\n else\n log.info(\"No backlinks found for note '%s'\", note.id)\n end\n return\n end\n\n local entries = {}\n for _, matches in ipairs(backlinks) do\n for _, match in ipairs(matches.matches) do\n entries[#entries + 1] = {\n value = { path = matches.path, line = match.line },\n filename = tostring(matches.path),\n lnum = match.line,\n }\n end\n end\n\n ---@type string\n local prompt_title\n if opts.anchor then\n prompt_title = string.format(\"Backlinks to '%s%s'\", note.id, opts.anchor)\n elseif opts.block then\n prompt_title = string.format(\"Backlinks to '%s#%s'\", note.id, util.standardize_block(opts.block))\n else\n prompt_title = string.format(\"Backlinks to '%s'\", note.id)\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = prompt_title,\n callback = function(value)\n api.open_buffer(value.path, { line = value.line })\n end,\n })\n end)\n end, { search = { sort = true }, anchor = opts.anchor, block = opts.block })\nend\n\n---@param client obsidian.Client\nreturn function(client)\n local picker = assert(Obsidian.picker)\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local cur_link, link_type = api.cursor_link()\n\n if\n cur_link ~= nil\n and link_type ~= RefTypes.NakedUrl\n and link_type ~= RefTypes.FileUrl\n and link_type ~= RefTypes.BlockID\n then\n local location = util.parse_link(cur_link, { include_block_ids = true })\n assert(location, \"cursor on a link but failed to parse, please report to repo\")\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n location = vim.api.nvim_buf_get_name(0)\n end\n\n local opts = { anchor = anchor_link, block = block_link }\n\n search.resolve_note_async(location, function(...)\n ---@type obsidian.Note[]\n local notes = { ... }\n\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", location)\n return\n elseif #notes == 1 then\n return collect_backlinks(client, picker, notes[1], opts)\n else\n return vim.schedule(function()\n picker:pick_note(notes, {\n prompt_title = \"Select note\",\n callback = function(note)\n collect_backlinks(client, picker, note, opts)\n end,\n })\n end)\n end\n end)\n else\n ---@type { anchor: string|?, block: string|? }\n local opts = {}\n ---@type obsidian.note.LoadOpts\n local load_opts = {}\n\n if cur_link and link_type == RefTypes.BlockID then\n opts.block = util.parse_link(cur_link, { include_block_ids = true })\n else\n load_opts.collect_anchor_links = true\n end\n\n local note = api.current_note(0, load_opts)\n\n -- Check if cursor is on a header, if so and header parsing is enabled, use that anchor.\n if Obsidian.opts.backlinks.parse_headers then\n local header_match = util.parse_header(vim.api.nvim_get_current_line())\n if header_match then\n opts.anchor = header_match.anchor\n end\n end\n\n if note == nil then\n log.err \"Current buffer does not appear to be a note inside the vault\"\n else\n collect_backlinks(client, picker, note, opts)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/refs.lua", "local util = require \"obsidian.util\"\n\nlocal M = {}\n\n---@enum obsidian.completion.RefType\nM.RefType = {\n Wiki = 1,\n Markdown = 2,\n}\n\n---Backtrack through a string to find the first occurrence of '[['.\n---\n---@param input string\n---@return string|?, string|?, obsidian.completion.RefType|?\nlocal find_search_start = function(input)\n for i = string.len(input), 1, -1 do\n local substr = string.sub(input, i)\n if vim.startswith(substr, \"]\") or vim.endswith(substr, \"]\") then\n return nil\n elseif vim.startswith(substr, \"[[\") then\n return substr, string.sub(substr, 3)\n elseif vim.startswith(substr, \"[\") and string.sub(input, i - 1, i - 1) ~= \"[\" then\n return substr, string.sub(substr, 2)\n end\n end\n return nil\nend\n\n---Check if a completion request can/should be carried out. Returns a boolean\n---and, if true, the search string and the column indices of where the completion\n---items should be inserted.\n---\n---@return boolean, string|?, integer|?, integer|?, obsidian.completion.RefType|?\nM.can_complete = function(request)\n local input, search = find_search_start(request.context.cursor_before_line)\n if input == nil or search == nil then\n return false\n elseif string.len(search) == 0 or util.is_whitespace(search) then\n return false\n end\n\n if vim.startswith(input, \"[[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 2)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]]\" and 1 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Wiki\n elseif vim.startswith(input, \"[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 1)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]\" and 0 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Markdown\n else\n return false\n end\nend\n\nM.get_trigger_characters = function()\n return { \"[\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n return [=[\\%(^\\|[^\\[]\\)\\zs\\[\\{1,2}[^\\]]\\+\\]\\{,2}]=]\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/check.lua", "local Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal iter = vim.iter\n\nreturn function()\n local start_time = vim.uv.hrtime()\n local count = 0\n local errors = {}\n local warnings = {}\n\n for path in api.dir(Obsidian.dir) do\n local relative_path = Path.new(path):vault_relative_path { strict = true }\n local ok, res = pcall(Note.from_file, path)\n\n if not ok then\n errors[#errors + 1] = string.format(\"Failed to parse note '%s': \", relative_path, res)\n elseif res.has_frontmatter == false then\n warnings[#warnings + 1] = string.format(\"'%s' missing frontmatter\", relative_path)\n end\n count = count + 1\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n local messages = { \"Checked \" .. tostring(count) .. \" notes in \" .. runtime .. \"ms\" }\n local log_level = vim.log.levels.INFO\n\n if #warnings > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#warnings) .. \" warning(s):\"\n log_level = vim.log.levels.WARN\n for warning in iter(warnings) do\n messages[#messages + 1] = \"  \" .. warning\n end\n end\n\n if #errors > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#errors) .. \" error(s):\"\n for err in iter(errors) do\n messages[#messages + 1] = \"  \" .. err\n end\n log_level = vim.log.levels.ERROR\n end\n\n log.log(table.concat(messages, \"\\n\"), log_level)\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/extract_note.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---Extract the selected text into a new note\n---and replace the selection with a link to the new note.\n---\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"Obsidian extract_note must be called with visual selection\"\n return\n end\n\n local content = vim.split(viz.selection, \"\\n\", { plain = true })\n\n ---@type string|?\n local title\n if data.args ~= nil and string.len(data.args) > 0 then\n title = vim.trim(data.args)\n else\n title = api.input \"Enter title (optional): \"\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n end\n\n -- create the new note.\n local note = Note.create { title = title }\n\n -- replace selection with link to new note\n local link = api.format_link(note)\n vim.api.nvim_buf_set_text(0, viz.csrow - 1, viz.cscol - 1, viz.cerow - 1, viz.cecol, { link })\n\n require(\"obsidian.ui\").update(0)\n\n -- add the selected text to the end of the new note\n note:open { sync = true }\n vim.api.nvim_buf_set_lines(0, -1, -1, false, content)\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/tags.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param tags string[]\nlocal function gather_tag_picker_list(client, picker, tags)\n client:find_tags_async(tags, function(tag_locations)\n -- Format results into picker entries, filtering out results that aren't exact matches or sub-tags.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, tag_loc in ipairs(tag_locations) do\n for _, tag in ipairs(tags) do\n if tag_loc.tag:lower() == tag:lower() or vim.startswith(tag_loc.tag:lower(), tag:lower() .. \"/\") then\n local display = string.format(\"%s [%s] %s\", tag_loc.note:display_name(), tag_loc.line, tag_loc.text)\n entries[#entries + 1] = {\n value = { path = tag_loc.path, line = tag_loc.line, col = tag_loc.tag_start },\n display = display,\n ordinal = display,\n filename = tostring(tag_loc.path),\n lnum = tag_loc.line,\n col = tag_loc.tag_start,\n }\n break\n end\n end\n end\n\n if vim.tbl_isempty(entries) then\n if #tags == 1 then\n log.warn \"Tag not found\"\n else\n log.warn \"Tags not found\"\n end\n return\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = \"#\" .. table.concat(tags, \", #\"),\n callback = function(value)\n api.open_buffer(value.path, { line = value.line, col = value.col })\n end,\n })\n end)\n end, { search = { sort = true } })\nend\n\n---@param client obsidian.Client\n---@param data CommandArgs\nreturn function(client, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local tags = data.fargs or {}\n\n if vim.tbl_isempty(tags) then\n local tag = api.cursor_tag()\n if tag then\n tags = { tag }\n end\n end\n\n if not vim.tbl_isempty(tags) then\n return gather_tag_picker_list(client, picker, util.tbl_unique(tags))\n else\n client:list_tags_async(nil, function(all_tags)\n vim.schedule(function()\n -- Open picker with tags.\n picker:pick_tag(all_tags, {\n callback = function(...)\n gather_tag_picker_list(client, picker, { ... })\n end,\n allow_multiple = true,\n })\n end)\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/dailies.lua", "local log = require \"obsidian.log\"\nlocal daily = require \"obsidian.daily\"\n\n---@param arg string\n---@return number\nlocal function parse_offset(arg)\n if vim.startswith(arg, \"+\") then\n return assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%'\", arg))\n elseif vim.startswith(arg, \"-\") then\n return -assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%s'\", arg))\n else\n return assert(tonumber(arg), string.format(\"invalid offset '%s'\", arg))\n end\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_start = -5\n local offset_end = 0\n\n if data.fargs and #data.fargs > 0 then\n if #data.fargs == 1 then\n local offset = parse_offset(data.fargs[1])\n if offset >= 0 then\n offset_end = offset\n else\n offset_start = offset\n end\n elseif #data.fargs == 2 then\n local offsets = vim.tbl_map(parse_offset, data.fargs)\n table.sort(offsets)\n offset_start = offsets[1]\n offset_end = offsets[2]\n else\n error \":Obsidian dailies expected at most 2 arguments\"\n end\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local dailies = {}\n for offset = offset_end, offset_start, -1 do\n local datetime = os.time() + (offset * 3600 * 24)\n local daily_note_path = daily.daily_note_path(datetime)\n local daily_note_alias = tostring(os.date(Obsidian.opts.daily_notes.alias_format or \"%A %B %-d, %Y\", datetime))\n if offset == 0 then\n daily_note_alias = daily_note_alias .. \" @today\"\n elseif offset == -1 then\n daily_note_alias = daily_note_alias .. \" @yesterday\"\n elseif offset == 1 then\n daily_note_alias = daily_note_alias .. \" @tomorrow\"\n end\n if not daily_note_path:is_file() then\n daily_note_alias = daily_note_alias .. \" ➡️ create\"\n end\n dailies[#dailies + 1] = {\n value = offset,\n display = daily_note_alias,\n ordinal = daily_note_alias,\n filename = tostring(daily_note_path),\n }\n end\n\n picker:pick(dailies, {\n prompt_title = \"Dailies\",\n callback = function(offset)\n local note = daily.daily(offset, {})\n note:open()\n end,\n })\nend\n"], ["/obsidian.nvim/lua/obsidian/daily/init.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\n\n--- Get the path to a daily note.\n---\n---@param datetime integer|?\n---\n---@return obsidian.Path, string (Path, ID) The path and ID of the note.\nlocal daily_note_path = function(datetime)\n datetime = datetime and datetime or os.time()\n\n ---@type obsidian.Path\n local path = Path:new(Obsidian.dir)\n\n local options = Obsidian.opts\n\n if options.daily_notes.folder ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.daily_notes.folder\n elseif options.notes_subdir ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.notes_subdir\n end\n\n local id\n if options.daily_notes.date_format ~= nil then\n id = tostring(os.date(options.daily_notes.date_format, datetime))\n else\n id = tostring(os.date(\"%Y-%m-%d\", datetime))\n end\n\n path = path / (id .. \".md\")\n\n -- ID may contain additional path components, so make sure we use the stem.\n id = path.stem\n\n return path, id\nend\n\n--- Open (or create) the daily note.\n---\n---@param datetime integer\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\n---\nlocal _daily = function(datetime, opts)\n opts = opts or {}\n\n local path, id = daily_note_path(datetime)\n\n local options = Obsidian.opts\n\n ---@type string|?\n local alias\n if options.daily_notes.alias_format ~= nil then\n alias = tostring(os.date(options.daily_notes.alias_format, datetime))\n end\n\n ---@type obsidian.Note\n local note\n if path:exists() then\n note = Note.from_file(path, opts.load)\n else\n note = Note.create {\n id = id,\n aliases = {},\n tags = options.daily_notes.default_tags or {},\n dir = path:parent(),\n }\n\n if alias then\n note:add_alias(alias)\n note.title = alias\n end\n\n if not opts.no_write then\n note:write { template = options.daily_notes.template }\n end\n end\n\n return note\nend\n\n--- Open (or create) the daily note for today.\n---\n---@return obsidian.Note\nlocal today = function()\n return _daily(os.time(), {})\nend\n\n--- Open (or create) the daily note from the last day.\n---\n---@return obsidian.Note\nlocal yesterday = function()\n local now = os.time()\n local yesterday\n\n if Obsidian.opts.daily_notes.workdays_only then\n yesterday = util.working_day_before(now)\n else\n yesterday = util.previous_day(now)\n end\n\n return _daily(yesterday, {})\nend\n\n--- Open (or create) the daily note for the next day.\n---\n---@return obsidian.Note\nlocal tomorrow = function()\n local now = os.time()\n local tomorrow\n\n if Obsidian.opts.daily_notes.workdays_only then\n tomorrow = util.working_day_after(now)\n else\n tomorrow = util.next_day(now)\n end\n\n return _daily(tomorrow, {})\nend\n\n--- Open (or create) the daily note for today + `offset_days`.\n---\n---@param offset_days integer|?\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\nlocal daily = function(offset_days, opts)\n return _daily(os.time() + (offset_days * 3600 * 24), opts)\nend\n\nreturn {\n daily_note_path = daily_note_path,\n daily = daily,\n tomorrow = tomorrow,\n yesterday = yesterday,\n today = today,\n}\n"], ["/obsidian.nvim/lua/obsidian/completion/tags.lua", "local Note = require \"obsidian.note\"\nlocal Patterns = require(\"obsidian.search\").Patterns\n\nlocal M = {}\n\n---@type { pattern: string, offset: integer }[]\nlocal TAG_PATTERNS = {\n { pattern = \"[%s%(]#\" .. Patterns.TagCharsOptional .. \"$\", offset = 2 },\n { pattern = \"^#\" .. Patterns.TagCharsOptional .. \"$\", offset = 1 },\n}\n\nM.find_tags_start = function(input)\n for _, pattern in ipairs(TAG_PATTERNS) do\n local match = string.match(input, pattern.pattern)\n if match then\n return string.sub(match, pattern.offset + 1)\n end\n end\nend\n\n--- Find the boundaries of the YAML frontmatter within the buffer.\n---@param bufnr integer\n---@return integer|?, integer|?\nlocal get_frontmatter_boundaries = function(bufnr)\n local note = Note.from_buffer(bufnr)\n if note.frontmatter_end_line ~= nil then\n return 1, note.frontmatter_end_line\n end\nend\n\n---@return boolean, string|?, boolean|?\nM.can_complete = function(request)\n local search = M.find_tags_start(request.context.cursor_before_line)\n if not search or string.len(search) == 0 then\n return false\n end\n\n -- Check if we're inside frontmatter.\n local in_frontmatter = false\n local line = request.context.cursor.line\n local frontmatter_start, frontmatter_end = get_frontmatter_boundaries(request.context.bufnr)\n if\n frontmatter_start ~= nil\n and frontmatter_start <= (line + 1)\n and frontmatter_end ~= nil\n and line <= frontmatter_end\n then\n in_frontmatter = true\n end\n\n return true, search, in_frontmatter\nend\n\nM.get_trigger_characters = function()\n return { \"#\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n -- return [=[\\%(^\\|[^#]\\)\\zs#[a-zA-Z0-9_/-]\\+]=]\n return \"#[a-zA-Z0-9_/-]\\\\+\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/abc.lua", "local M = {}\n\n---@class obsidian.ABC\n---@field init function an init function which essentially calls 'setmetatable({}, mt)'.\n---@field as_tbl function get a raw table with only the instance's fields\n---@field mt table the metatable\n\n---Create a new class.\n---\n---This handles the boilerplate of setting up metatables correctly and consistently when defining new classes,\n---and comes with some better default metamethods, like '.__eq' which will recursively compare all fields\n---that don't start with a double underscore.\n---\n---When you use this you should call `.init()` within your constructors instead of `setmetatable()`.\n---For example:\n---\n---```lua\n--- local Foo = new_class()\n---\n--- Foo.new = function(x)\n--- local self = Foo.init()\n--- self.x = x\n--- return self\n--- end\n---```\n---\n---The metatable for classes created this way is accessed with the field `.mt`. This way you can easily\n---add/override metamethods to your classes. Continuing the example above:\n---\n---```lua\n--- Foo.mt.__tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end\n---\n--- local foo = Foo.new(1)\n--- print(foo)\n---```\n---\n---Alternatively you can pass metamethods directly to 'new_class()'. For example:\n---\n---```lua\n--- local Foo = new_class {\n--- __tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end,\n--- }\n---```\n---\n---@param metamethods table|? {string, function} - Metamethods\n---@param base_class table|? A base class to start from\n---@return obsidian.ABC\nM.new_class = function(metamethods, base_class)\n local class = base_class and base_class or {}\n\n -- Metatable for the class so that all instances have the same metatable.\n class.mt = vim.tbl_extend(\"force\", {\n __index = class,\n __eq = function(a, b)\n -- In order to use 'vim.deep_equal' we need to pull out the raw fields first.\n -- If we passed 'a' and 'b' directly to 'vim.deep_equal' we'd get a stack overflow due\n -- to infinite recursion, since 'vim.deep_equal' calls the '.__eq' metamethod.\n local a_fields = a:as_tbl()\n local b_fields = b:as_tbl()\n return vim.deep_equal(a_fields, b_fields)\n end,\n }, metamethods and metamethods or {})\n\n class.init = function(t)\n local self = setmetatable(t and t or {}, class.mt)\n return self\n end\n\n class.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\n end\n\n return class\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/builtin.lua", "---builtin functions that are default values for config options\nlocal M = {}\nlocal util = require \"obsidian.util\"\n\n---Create a new unique Zettel ID.\n---\n---@return string\nM.zettel_id = function()\n local suffix = \"\"\n for _ = 1, 4 do\n suffix = suffix .. string.char(math.random(65, 90))\n end\n return tostring(os.time()) .. \"-\" .. suffix\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_alias_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = string.format(\"#%s\", opts.anchor.header)\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.label, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = opts.anchor.anchor\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.path, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.label ~= opts.path then\n return string.format(\"[[%s%s|%s%s]]\", opts.path, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.path, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_id_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.id == nil then\n return string.format(\"[[%s%s]]\", opts.label, anchor)\n elseif opts.label ~= opts.id then\n return string.format(\"[[%s%s|%s%s]]\", opts.id, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.id, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.markdown_link = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n local path = util.urlencode(opts.path, { keep_path_sep = true })\n return string.format(\"[%s%s](%s%s)\", opts.label, header, path, anchor)\nend\n\n---@param path string\n---@return string\nM.img_text_func = function(path)\n local format_string = {\n markdown = \"![](%s)\",\n wiki = \"![[%s]]\",\n }\n local style = Obsidian.opts.preferred_link_style\n local name = vim.fs.basename(tostring(path))\n\n if style == \"markdown\" then\n name = require(\"obsidian.util\").urlencode(name)\n end\n\n return string.format(format_string[style], name)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/_snacks.lua", "local snacks_picker = require \"snacks.picker\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\nlocal function debug_once(msg, ...)\n -- vim.notify(msg .. vim.inspect(...))\nend\n\n---@param mapping table\n---@return table\nlocal function notes_mappings(mapping)\n if type(mapping) == \"table\" then\n local opts = { win = { input = { keys = {} } }, actions = {} }\n for k, v in pairs(mapping) do\n local name = string.gsub(v.desc, \" \", \"_\")\n opts.win.input.keys = {\n [k] = { name, mode = { \"n\", \"i\" }, desc = v.desc },\n }\n opts.actions[name] = function(picker, item)\n debug_once(\"mappings :\", item)\n picker:close()\n vim.schedule(function()\n v.callback(item.value or item._path)\n end)\n end\n end\n return opts\n end\n return {}\nend\n\n---@class obsidian.pickers.SnacksPicker : obsidian.Picker\nlocal SnacksPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"SnacksPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nSnacksPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"files\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"find files callback: \", item)\n opts.callback(item._path)\n else\n debug_once(\"find files jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nSnacksPicker.grep = function(self, opts)\n opts = opts or {}\n\n debug_once(\"grep opts : \", opts)\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"grep\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"grep callback: \", item)\n opts.callback(item._path or item.filename)\n else\n debug_once(\"grep jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nSnacksPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n debug_once(\"pick opts: \", opts)\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n table.insert(entries, {\n text = value,\n value = value,\n })\n elseif value.valid ~= false then\n local name = self:_make_display(value)\n table.insert(entries, {\n text = name,\n buf = self.calling_bufnr,\n filename = value.filename,\n value = value.value,\n pos = { value.lnum, value.col or 0 },\n })\n end\n end\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n tilte = opts.prompt_title,\n items = entries,\n layout = {\n preview = false,\n },\n format = \"text\",\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"pick callback: \", item)\n opts.callback(item.value)\n else\n debug_once(\"pick jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n\n snacks_picker.pick(pick_opts)\nend\n\nreturn SnacksPicker\n"], ["/obsidian.nvim/lua/obsidian/commands/template.lua", "local templates = require \"obsidian.templates\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local templates_dir = api.templates_dir()\n if not templates_dir then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n -- We need to get this upfront before the picker hijacks the current window.\n local insert_location = api.get_active_window_cursor_location()\n\n local function insert_template(name)\n templates.insert_template {\n type = \"insert_template\",\n template_name = name,\n template_opts = Obsidian.opts.templates,\n templates_dir = templates_dir,\n location = insert_location,\n }\n end\n\n if string.len(data.args) > 0 then\n local template_name = vim.trim(data.args)\n insert_template(template_name)\n return\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_templates {\n callback = function(path)\n insert_template(path)\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/link.lua", "local search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n ---@type string\n local search_term\n if data.args ~= nil and string.len(data.args) > 0 then\n search_term = data.args\n else\n search_term = viz.selection\n end\n\n ---@param note obsidian.Note\n local function insert_ref(note)\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = viz.selection })\n .. string.sub(line, viz.cecol + 1)\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\n require(\"obsidian.ui\").update(0)\n end\n\n search.resolve_note_async(search_term, function(note)\n vim.schedule(function()\n insert_ref(note)\n end)\n end, { prompt_title = \"Select note to link\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/log.lua", "---@class obsidian.Logger\nlocal log = {}\n\nlog._log_level = vim.log.levels.INFO\n\n---@param t table\n---@return boolean\nlocal function has_tostring(t)\n local mt = getmetatable(t)\n return mt ~= nil and mt.__tostring ~= nil\nend\n\n---@param msg string\n---@return any[]\nlocal function message_args(msg, ...)\n local args = { ... }\n local num_directives = select(2, string.gsub(msg, \"%%\", \"\")) - 2 * select(2, string.gsub(msg, \"%%%%\", \"\"))\n\n -- Some elements might be nil, so we can't use 'ipairs'.\n local out = {}\n for i = 1, #args do\n local v = args[i]\n if v == nil then\n out[i] = tostring(v)\n elseif type(v) == \"table\" and not has_tostring(v) then\n out[i] = vim.inspect(v)\n else\n out[i] = v\n end\n end\n\n -- If were short formatting args relative to the number of directives, add \"nil\" strings on.\n if #out < num_directives then\n for i = #out + 1, num_directives do\n out[i] = \"nil\"\n end\n end\n\n return out\nend\n\n---@param level integer\nlog.set_level = function(level)\n log._log_level = level\nend\n\n--- Log a message.\n---\n---@param msg any\n---@param level integer|?\nlog.log = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---Log a message only once.\n---\n---@param msg any\n---@param level integer|?\nlog.log_once = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---@param msg string\nlog.debug = function(msg, ...)\n log.log(msg, vim.log.levels.DEBUG, ...)\nend\n\n---@param msg string\nlog.info = function(msg, ...)\n log.log(msg, vim.log.levels.INFO, ...)\nend\n\n---@param msg string\nlog.warn = function(msg, ...)\n log.log(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.warn_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.err = function(msg, ...)\n log.log(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error = log.err\n\n---@param msg string\nlog.err_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error_once = log.err\n\nreturn log\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/tags.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal iter = vim.iter\nlocal obsidian = require \"obsidian\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.TagsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field in_frontmatter boolean|?\nlocal TagsSourceCompletionContext = abc.new_class()\n\nTagsSourceCompletionContext.new = function()\n return TagsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.TagsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal TagsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.TagsSourceBase\nTagsSourceBase.new = function()\n return TagsSourceBase.init()\nend\n\nTagsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = TagsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n local search_opts = cc.client.search_defaults()\n search_opts.sort = false\n\n cc.client:find_tags_async(cc.search, function(tag_locs)\n local tags = {}\n for tag_loc in iter(tag_locs) do\n tags[tag_loc.tag] = true\n end\n\n local items = {}\n for tag, _ in pairs(tags) do\n -- Generate context-appropriate text\n local insert_text, label_text\n if cc.in_frontmatter then\n -- Frontmatter: insert tag without # (YAML format)\n insert_text = tag\n label_text = \"Tag: \" .. tag\n else\n -- Document body: insert tag with # (Obsidian format)\n insert_text = \"#\" .. tag\n label_text = \"Tag: #\" .. tag\n end\n\n -- Calculate the range to replace (the entire #tag pattern)\n local cursor_before = cc.request.context.cursor_before_line\n local hash_start = string.find(cursor_before, \"#[^%s]*$\")\n local insert_start = hash_start and (hash_start - 1) or #cursor_before\n local insert_end = #cursor_before\n\n items[#items + 1] = {\n sortText = \"#\" .. tag,\n label = label_text,\n kind = vim.lsp.protocol.CompletionItemKind.Text,\n textEdit = {\n newText = insert_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_end,\n },\n },\n },\n data = {\n bufnr = cc.request.context.bufnr,\n in_frontmatter = cc.in_frontmatter,\n line = cc.request.context.cursor.line,\n tag = tag,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\n end, { search = search_opts })\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction TagsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.in_frontmatter = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\nreturn TagsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/footer/init.lua", "local M = {}\nlocal api = require \"obsidian.api\"\n\nlocal ns_id = vim.api.nvim_create_namespace \"ObsidianFooter\"\n\n--- Register buffer-specific variables\nM.start = function(client)\n local refresh_info = function(buf)\n local note = api.current_note(buf)\n if not note then\n return\n end\n local info = {}\n local wc = vim.fn.wordcount()\n info.words = wc.words\n info.chars = wc.chars\n info.properties = vim.tbl_count(note:frontmatter())\n info.backlinks = #client:find_backlinks(note)\n return info\n end\n\n local function update_obsidian_footer(buf)\n local info = refresh_info(buf)\n if info == nil then\n return\n end\n local footer_text = assert(Obsidian.opts.footer.format)\n for k, v in pairs(info) do\n footer_text = footer_text:gsub(\"{{\" .. k .. \"}}\", v)\n end\n local row0 = #vim.api.nvim_buf_get_lines(buf, 0, -2, false)\n local col0 = 0\n local separator = Obsidian.opts.footer.separator\n local hl_group = Obsidian.opts.footer.hl_group\n local footer_contents = { { footer_text, hl_group } }\n local footer_chunks\n if separator then\n local footer_separator = { { separator, hl_group } }\n footer_chunks = { footer_separator, footer_contents }\n else\n footer_chunks = { footer_contents }\n end\n local opts = { virt_lines = footer_chunks }\n vim.api.nvim_buf_clear_namespace(buf, ns_id, 0, -1)\n vim.api.nvim_buf_set_extmark(buf, ns_id, row0, col0, opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_footer\", {})\n local attached_bufs = {}\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n desc = \"Initialize obsidian footer\",\n pattern = \"ObsidianNoteEnter\",\n callback = function(ev)\n if attached_bufs[ev.buf] then\n return\n end\n vim.schedule(function()\n update_obsidian_footer(ev.buf)\n end)\n local id = vim.api.nvim_create_autocmd({\n \"FileChangedShellPost\",\n \"TextChanged\",\n \"TextChangedI\",\n \"TextChangedP\",\n }, {\n group = group,\n desc = \"Update obsidian footer\",\n buffer = ev.buf,\n callback = vim.schedule_wrap(function()\n update_obsidian_footer(ev.buf)\n end),\n })\n attached_bufs[ev.buf] = id\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/new_from_template.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type string?\n local title = table.concat(data.fargs, \" \", 1, #data.fargs - 1)\n local template = data.fargs[#data.fargs]\n\n if title ~= nil and template ~= nil then\n local note = Note.create { title = title, template = template, should_write = true }\n note:open { sync = true }\n return\n end\n\n picker:find_templates {\n callback = function(template_name)\n if title == nil or title == \"\" then\n -- Must use pcall in case of KeyboardInterrupt\n -- We cannot place `title` where `safe_title` is because it would be redeclaring it\n local success, safe_title = pcall(util.input, \"Enter title or path (optional): \", { completion = \"file\" })\n title = safe_title\n if not success or not safe_title then\n log.warn \"Aborted\"\n return\n elseif safe_title == \"\" then\n title = nil\n end\n end\n\n if template_name == nil or template_name == \"\" then\n log.warn \"Aborted\"\n return\n end\n\n ---@type obsidian.Note\n local note = Note.create { title = title, template = template_name, should_write = true }\n note:open { sync = false }\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/statusline/init.lua", "local M = {}\nlocal uv = vim.uv\nlocal api = require \"obsidian.api\"\n\n--- Register the global variable that updates itself\nM.start = function(client)\n local current_note\n\n local refresh = function()\n local note = api.current_note()\n if not note then -- no note\n return \"\"\n elseif current_note == note then -- no refresh\n return\n else -- refresh\n current_note = note\n end\n\n client:find_backlinks_async(\n note,\n vim.schedule_wrap(function(backlinks)\n local format = assert(Obsidian.opts.statusline.format)\n local wc = vim.fn.wordcount()\n local info = {\n words = wc.words,\n chars = wc.chars,\n backlinks = #backlinks,\n properties = vim.tbl_count(note:frontmatter()),\n }\n for k, v in pairs(info) do\n format = format:gsub(\"{{\" .. k .. \"}}\", v)\n end\n vim.g.obsidian = format\n end)\n )\n end\n\n local timer = uv:new_timer()\n assert(timer, \"Failed to create timer\")\n timer:start(0, 1000, vim.schedule_wrap(refresh))\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/link_new.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n local title\n if string.len(data.args) > 0 then\n title = data.args\n else\n title = viz.selection\n end\n\n local note = Note.create { title = title }\n\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = title })\n .. string.sub(line, viz.cecol + 1)\n\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/new.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type obsidian.Note\n local note\n if data.args:len() > 0 then\n note = Note.create { title = data.args }\n else\n local title = api.input(\"Enter title or path (optional): \", { completion = \"file\" })\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n note = Note.create { title = title }\n end\n\n -- Open the note in a new buffer.\n note:open { sync = true }\n note:write_to_buffer()\nend\n"], ["/obsidian.nvim/lua/obsidian/yaml/line.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\n\n---@class obsidian.yaml.Line : obsidian.ABC\n---@field content string\n---@field raw_content string\n---@field indent integer\nlocal Line = abc.new_class {\n __tostring = function(self)\n return string.format(\"Line('%s')\", self.raw_content)\n end,\n}\n\n---Create a new Line instance from a raw line string.\n---@param raw_line string\n---@param base_indent integer|?\n---@return obsidian.yaml.Line\nLine.new = function(raw_line, base_indent)\n local self = Line.init()\n self.indent = util.count_indent(raw_line)\n if base_indent ~= nil then\n if base_indent > self.indent then\n error \"relative indentation for line is less than base indentation\"\n end\n self.indent = self.indent - base_indent\n end\n self.raw_content = util.lstrip_whitespace(raw_line, base_indent)\n self.content = vim.trim(self.raw_content)\n return self\nend\n\n---Check if a line is empty.\n---@param self obsidian.yaml.Line\n---@return boolean\nLine.is_empty = function(self)\n if util.strip_comments(self.content) == \"\" then\n return true\n else\n return false\n end\nend\n\nreturn Line\n"], ["/obsidian.nvim/lua/obsidian/pickers/init.lua", "local PickerName = require(\"obsidian.config\").Picker\n\nlocal M = {}\n\n--- Get the default Picker.\n---\n---@param picker_name obsidian.config.Picker|?\n---\n---@return obsidian.Picker|?\nM.get = function(picker_name)\n picker_name = picker_name and picker_name or Obsidian.opts.picker.name\n if picker_name then\n picker_name = string.lower(picker_name)\n else\n for _, name in ipairs { PickerName.telescope, PickerName.fzf_lua, PickerName.mini, PickerName.snacks } do\n local ok, res = pcall(M.get, name)\n if ok then\n return res\n end\n end\n return nil\n end\n\n if picker_name == string.lower(PickerName.telescope) then\n return require(\"obsidian.pickers._telescope\").new()\n elseif picker_name == string.lower(PickerName.mini) then\n return require(\"obsidian.pickers._mini\").new()\n elseif picker_name == string.lower(PickerName.fzf_lua) then\n return require(\"obsidian.pickers._fzf\").new()\n elseif picker_name == string.lower(PickerName.snacks) then\n return require(\"obsidian.pickers._snacks\").new()\n elseif picker_name then\n error(\"not implemented for \" .. picker_name)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/workspace.lua", "local log = require \"obsidian.log\"\nlocal Workspace = require \"obsidian.workspace\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.info(\"Current workspace: '%s' @ '%s'\", Obsidian.workspace.name, Obsidian.workspace.path)\n return\n end\n\n local options = {}\n for i, spec in ipairs(Obsidian.opts.workspaces) do\n local workspace = Workspace.new_from_spec(spec)\n if workspace == Obsidian.workspace then\n options[#options + 1] = string.format(\"*[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n else\n options[#options + 1] = string.format(\"[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n end\n end\n\n picker:pick(options, {\n prompt_title = \"Workspaces\",\n callback = function(workspace_str)\n local idx = tonumber(string.match(workspace_str, \"%*?%[(%d+)]\"))\n Workspace.switch(Obsidian.opts.workspaces[idx].name, { lock = true })\n end,\n })\n else\n Workspace.switch(data.args, { lock = true })\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/toc.lua", "local util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local note = assert(api.current_note(0, { collect_anchor_links = true }))\n\n ---@type obsidian.PickerEntry[]\n local picker_entries = {}\n for _, anchor in pairs(note.anchor_links) do\n local display = string.rep(\"#\", anchor.level) .. \" \" .. anchor.header\n table.insert(\n picker_entries,\n { value = display, display = display, filename = tostring(note.path), lnum = anchor.line }\n )\n end\n\n -- De-duplicate and sort.\n picker_entries = util.tbl_unique(picker_entries)\n table.sort(picker_entries, function(a, b)\n return a.lnum < b.lnum\n end)\n\n local picker = assert(Obsidian.picker)\n picker:pick(picker_entries, { prompt_title = \"Table of Contents\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/types.lua", "-- Useful type definitions go here.\n\n---@class CommandArgs\n---The table passed to user commands.\n---For details see `:help nvim_create_user_command()` and the command attribute docs\n---\n---@field name string Command name\n---@field args string The args passed to the command, if any \n---@field fargs table The args split by unescaped whitespace (when more than one argument is allowed), if any \n---@field nargs string Number of arguments |:command-nargs|\n---@field bang boolean \"true\" if the command was executed with a ! modifier \n---@field line1 number The starting line of the command range \n---@field line2 number The final line of the command range \n---@field range number The number of items in the command range: 0, 1, or 2 \n---@field count number Any count supplied \n---@field reg string The optional register, if specified \n---@field mods string Command modifiers, if any \n---@field smods table Command modifiers in a structured format. Has the same structure as the \"mods\" key of\n---@field raw_print boolean HACK: for debug command and info\n\n---@class obsidian.InsertTemplateContext\n---The table passed to user substitution functions when inserting templates into a buffer.\n---\n---@field type \"insert_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field location [number, number, number, number] `{ buf, win, row, col }` location from which the request was made.\n---@field partial_note? obsidian.Note An optional note with fields to copy from.\n\n---@class obsidian.CloneTemplateContext\n---The table passed to user substitution functions when cloning template files to create new notes.\n---\n---@field type \"clone_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field destination_path obsidian.Path The path the cloned template will be written to.\n---@field partial_note obsidian.Note The note being written.\n\n---@alias obsidian.TemplateContext obsidian.InsertTemplateContext | obsidian.CloneTemplateContext\n---The table passed to user substitution functions. Use `ctx.type` to distinguish between the different kinds.\n"], ["/obsidian.nvim/minimal.lua", "vim.env.LAZY_STDPATH = \".repro\"\nload(vim.fn.system \"curl -s https://raw.githubusercontent.com/folke/lazy.nvim/main/bootstrap.lua\")()\n\nvim.fn.mkdir(\".repro/vault\", \"p\")\n\nvim.o.conceallevel = 2\n\nlocal plugins = {\n {\n \"obsidian-nvim/obsidian.nvim\",\n dependencies = { \"nvim-lua/plenary.nvim\" },\n opts = {\n completion = {\n blink = true,\n nvim_cmp = false,\n },\n workspaces = {\n {\n name = \"test\",\n path = vim.fs.joinpath(vim.uv.cwd(), \".repro\", \"vault\"),\n },\n },\n },\n },\n\n -- **Choose your renderer**\n -- { \"MeanderingProgrammer/render-markdown.nvim\", dependencies = { \"echasnovski/mini.icons\" }, opts = {} },\n -- { \"OXY2DEV/markview.nvim\", lazy = false },\n\n -- **Choose your picker**\n -- \"nvim-telescope/telescope.nvim\",\n -- \"folke/snacks.nvim\",\n -- \"ibhagwan/fzf-lua\",\n -- \"echasnovski/mini.pick\",\n\n -- **Choose your completion engine**\n -- {\n -- \"hrsh7th/nvim-cmp\",\n -- config = function()\n -- local cmp = require \"cmp\"\n -- cmp.setup {\n -- mapping = cmp.mapping.preset.insert {\n -- [\"\"] = cmp.mapping.abort(),\n -- [\"\"] = cmp.mapping.confirm { select = true },\n -- },\n -- }\n -- end,\n -- },\n -- {\n -- \"saghen/blink.cmp\",\n -- opts = {\n -- fuzzy = { implementation = \"lua\" }, -- no need to build binary\n -- keymap = {\n -- preset = \"default\",\n -- },\n -- },\n -- },\n}\n\nrequire(\"lazy.minit\").repro { spec = plugins }\n\nvim.cmd \"checkhealth obsidian\"\n"], ["/obsidian.nvim/lua/obsidian/compat.lua", "local compat = {}\n\nlocal has_nvim_0_11 = false\nif vim.fn.has \"nvim-0.11\" == 1 then\n has_nvim_0_11 = true\nend\n\ncompat.is_list = function(t)\n if has_nvim_0_11 then\n return vim.islist(t)\n else\n return vim.tbl_islist(t)\n end\nend\n\ncompat.flatten = function(t)\n if has_nvim_0_11 then\n ---@diagnostic disable-next-line: undefined-field\n return vim.iter(t):flatten():totable()\n else\n return vim.tbl_flatten(t)\n end\nend\n\nreturn compat\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/nvim_cmp.lua", "local M = {}\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_sources(opts)\n local cmp = require \"cmp\"\n\n cmp.register_source(\"obsidian\", require(\"obsidian.completion.sources.nvim_cmp.refs\").new())\n cmp.register_source(\"obsidian_tags\", require(\"obsidian.completion.sources.nvim_cmp.tags\").new())\n if opts.completion.create_new then\n cmp.register_source(\"obsidian_new\", require(\"obsidian.completion.sources.nvim_cmp.new\").new())\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace and configures nvim_cmp sources for the current buffer.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n local cmp = require \"cmp\"\n\n local sources = {\n { name = \"obsidian\" },\n { name = \"obsidian_tags\" },\n }\n if opts.completion.create_new then\n table.insert(sources, { name = \"obsidian_new\" })\n end\n for _, source in pairs(cmp.get_config().sources) do\n if source.name ~= \"obsidian\" and source.name ~= \"obsidian_new\" and source.name ~= \"obsidian_tags\" then\n table.insert(sources, source)\n end\n end\n ---@diagnostic disable-next-line: missing-fields\n cmp.setup.buffer { sources = sources }\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/links.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local picker = Obsidian.picker\n if not picker then\n return log.err \"No picker configured\"\n end\n\n local note = api.current_note(0)\n assert(note, \"not in a note\")\n\n search.find_links(note, {}, function(entries)\n entries = vim.tbl_map(function(match)\n return match.link\n end, entries)\n\n -- Launch picker.\n picker:pick(entries, {\n prompt_title = \"Links\",\n callback = function(link)\n api.follow_link(link)\n end,\n })\n end)\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/quick_switch.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_notes()\n else\n search.resolve_note_async(data.args, function(note)\n note:open()\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/today.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_days = 0\n local arg = string.gsub(data.args, \" \", \"\")\n if string.len(arg) > 0 then\n local offset = tonumber(arg)\n if offset == nil then\n log.err \"Invalid argument, expected an integer offset\"\n return\n else\n offset_days = offset\n end\n end\n local note = require(\"obsidian.daily\").daily(offset_days, {})\n note:open()\nend\n"], ["/obsidian.nvim/after/ftplugin/markdown.lua", "local obsidian = require \"obsidian\"\nlocal buf = vim.api.nvim_get_current_buf()\nlocal buf_dir = vim.fs.dirname(vim.api.nvim_buf_get_name(buf))\n\nlocal workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\nif not workspace then\n return -- if not in any workspace.\nend\n\nlocal win = vim.api.nvim_get_current_win()\n\nvim.treesitter.start(buf, \"markdown\") -- for when user don't use nvim-treesitter\nvim.wo[win].foldmethod = \"expr\"\nvim.wo[win].foldexpr = \"v:lua.vim.treesitter.foldexpr()\"\nvim.wo[win].foldlevel = 99\n"], ["/obsidian.nvim/lua/obsidian/commands/toggle_checkbox.lua", "local toggle_checkbox = require(\"obsidian.api\").toggle_checkbox\n\n---@param data CommandArgs\nreturn function(_, data)\n local start_line, end_line\n local checkboxes = Obsidian.opts.checkbox.order\n start_line = data.line1\n end_line = data.line2\n\n local buf = vim.api.nvim_get_current_buf()\n\n for line_nb = start_line, end_line do\n local current_line = vim.api.nvim_buf_get_lines(buf, line_nb - 1, line_nb, false)[1]\n if current_line and current_line:match \"%S\" then\n toggle_checkbox(checkboxes, line_nb)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/follow_link.lua", "local api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local opts = {}\n if data.args and string.len(data.args) > 0 then\n opts.open_strategy = data.args\n end\n\n local link = api.cursor_link()\n\n if link then\n api.follow_link(link, opts)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/util.lua", "local M = {}\n\n---Generates the completion request from a blink context\n---@param context blink.cmp.Context\n---@return obsidian.completion.sources.base.Request\nM.generate_completion_request_from_editor_state = function(context)\n local row = context.cursor[1]\n local col = context.cursor[2] + 1\n local cursor_before_line = context.line:sub(1, col - 1)\n local cursor_after_line = context.line:sub(col)\n\n return {\n context = {\n bufnr = context.bufnr,\n cursor_before_line = cursor_before_line,\n cursor_after_line = cursor_after_line,\n cursor = {\n row = row,\n col = col,\n line = row + 1,\n },\n },\n }\nend\n\nM.incomplete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = true,\n items = {},\n}\n\nM.complete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = false,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.nvim_cmp.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.new = function()\n return RefsSource.init(RefsSourceBase)\nend\n\nRefsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nRefsSource.incomplete_response = nvim_cmp_util.incomplete_response\nRefsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction RefsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.blink.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.incomplete_response = blink_util.incomplete_response\nRefsSource.complete_response = blink_util.complete_response\n\nfunction RefsSource.new()\n return RefsSource.init(RefsSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction RefsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.incomplete_response = blink_util.incomplete_response\nNewNoteSource.complete_response = blink_util.complete_response\n\nfunction NewNoteSource.new()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction NewNoteSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\n---Implements the execute method of the completion provider\n---@param _ blink.cmp.Context\n---@param item blink.cmp.CompletionItem\n---@param callback fun(),\n---@param default_implementation fun(context?: blink.cmp.Context, item?: blink.cmp.CompletionItem)): ((fun(): nil) | nil)\nfunction NewNoteSource:execute(_, item, callback, default_implementation)\n self:process_execute(item)\n default_implementation() -- Ensure completion is still executed\n callback() -- Required (as per blink documentation)\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/commands/search.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n picker:grep_notes { query = data.args }\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.new = function()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\nNewNoteSource.get_keyword_pattern = completion.get_keyword_pattern\n\nNewNoteSource.incomplete_response = nvim_cmp_util.incomplete_response\nNewNoteSource.complete_response = nvim_cmp_util.complete_response\n\n---Invoke completion (required).\n---@param request cmp.SourceCompletionApiParams\n---@param callback fun(response: lsp.CompletionResponse|nil)\nfunction NewNoteSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\n---Creates a new note using the default template for the completion item.\n---Executed after the item was selected.\n---@param completion_item lsp.CompletionItem\n---@param callback fun(completion_item: lsp.CompletionItem|nil)\nfunction NewNoteSource:execute(completion_item, callback)\n return callback(self:process_execute(completion_item))\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/yaml/yq.lua", "local m = {}\n\n---@param str string\n---@return any\nm.loads = function(str)\n local as_json = vim.fn.system(\"yq -o=json\", str)\n local data = vim.json.decode(as_json, { luanil = { object = true, array = true } })\n return data\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.incomplete_response = blink_util.incomplete_response\nTagsSource.complete_response = blink_util.complete_response\n\nfunction TagsSource.new()\n return TagsSource.init(TagsSourceBase)\nend\n\n---Implements the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction TagsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.new = function()\n return TagsSource.init(TagsSourceBase)\nend\n\nTagsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nTagsSource.incomplete_response = nvim_cmp_util.incomplete_response\nTagsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction TagsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/version.lua", "return \"3.12.0\"\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/types.lua", "---@class obsidian.completion.sources.base.Request.Context.Position\n---@field public col integer\n---@field public row integer\n\n---A request context class that partially matches cmp.Context to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request.Context\n---@field public bufnr integer\n---@field public cursor obsidian.completion.sources.base.Request.Context.Position|lsp.Position\n---@field public cursor_after_line string\n---@field public cursor_before_line string\n\n---A request class that partially matches cmp.Request to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request\n---@field public context obsidian.completion.sources.base.Request.Context\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/util.lua", "local M = {}\n\nM.incomplete_response = { isIncomplete = true }\n\nM.complete_response = {\n isIncomplete = true,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/init.lua", "local M = {\n refs = require \"obsidian.completion.refs\",\n tags = require \"obsidian.completion.tags\",\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/tomorrow.lua", "return function()\n local note = require(\"obsidian.daily\").tomorrow()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/yesterday.lua", "return function()\n local note = require(\"obsidian.daily\").yesterday()\n note:open()\nend\n"]], "task_instance_info": {"created_time": "2025-08-21 00:50:03", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Detect the presence of image data in system clipboard content by verifying platform-specific data formats and signatures through OS-dependent validation checks."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nM.check_clipboard = function()\n local check_cmd = get_clip_check_command()\n local this_os = api.get_os()\n \n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n local success, exit_code, output = run_job({\"bash\", \"-c\", check_cmd})\n if success and exit_code == 0 then\n return string.find(output, \"image/png\") ~= nil\n end\n return false\n elseif this_os == api.OSType.Darwin then\n local success, exit_code = run_job{\"bash\", \"-c\", check_cmd}\n return success and exit_code == 0\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n local success, exit_code = run_job{\"powershell.exe\", \"-Command\", \"Get-Clipboard -Format Image -ErrorAction SilentlyContinue\"}\n return success and exit_code == 0\n else\n log.err(\"Clipboard check not implemented for OS '%s'\", this_os)\n return false\n end\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-50-20"}, "editdistance_info": {"edit_distance": 29.3878, "calculate_time": "2025-08-21 00:50:20", "true_code_clean": "function M.clipboard_is_img()\n local check_cmd = get_clip_check_command()\n local result_string = vim.fn.system(check_cmd)\n local content = vim.split(result_string, \"\\n\")\n local is_img = false\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n if vim.tbl_contains(content, \"image/png\") then\n is_img = true\n elseif vim.tbl_contains(content, \"text/uri-list\") then\n local success =\n os.execute \"wl-paste \n is_img = success == 0\n end\n elseif this_os == api.OSType.Darwin then\n is_img = string.sub(content[1], 1, 9) == \"iVBORw0KG\" \n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n is_img = content ~= nil\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return is_img\nend", "predict_code_clean": "M.check_clipboard = function()\n local check_cmd = get_clip_check_command()\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n local success, exit_code, output = run_job({\"bash\", \"-c\", check_cmd})\n if success and exit_code == 0 then\n return string.find(output, \"image/png\") ~= nil\n end\n return false\n elseif this_os == api.OSType.Darwin then\n local success, exit_code = run_job{\"bash\", \"-c\", check_cmd}\n return success and exit_code == 0\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n local success, exit_code = run_job{\"powershell.exe\", \"-Command\", \"Get-Clipboard -Format Image -ErrorAction SilentlyContinue\"}\n return success and exit_code == 0\n else\n log.err(\"Clipboard check not implemented for OS '%s'\", this_os)\n return false\n end\nend"}} {"repo_name": "obsidian.nvim", "file_name": "/obsidian.nvim/lua/obsidian/pickers/init.lua", "inference_info": {"prefix_code": "local PickerName = require(\"obsidian.config\").Picker\n\nlocal M = {}\n\n--- Get the default Picker.\n---\n---@param picker_name obsidian.config.Picker|?\n---\n---@return obsidian.Picker|?\nM.get = ", "suffix_code": "\n\nreturn M\n", "middle_code": "function(picker_name)\n picker_name = picker_name and picker_name or Obsidian.opts.picker.name\n if picker_name then\n picker_name = string.lower(picker_name)\n else\n for _, name in ipairs { PickerName.telescope, PickerName.fzf_lua, PickerName.mini, PickerName.snacks } do\n local ok, res = pcall(M.get, name)\n if ok then\n return res\n end\n end\n return nil\n end\n if picker_name == string.lower(PickerName.telescope) then\n return require(\"obsidian.pickers._telescope\").new()\n elseif picker_name == string.lower(PickerName.mini) then\n return require(\"obsidian.pickers._mini\").new()\n elseif picker_name == string.lower(PickerName.fzf_lua) then\n return require(\"obsidian.pickers._fzf\").new()\n elseif picker_name == string.lower(PickerName.snacks) then\n return require(\"obsidian.pickers._snacks\").new()\n elseif picker_name then\n error(\"not implemented for \" .. picker_name)\n end\nend", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/obsidian.nvim/lua/obsidian/pickers/_telescope.lua", "local telescope = require \"telescope.builtin\"\nlocal telescope_actions = require \"telescope.actions\"\nlocal actions_state = require \"telescope.actions.state\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.pickers.TelescopePicker : obsidian.Picker\nlocal TelescopePicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"TelescopePicker()\"\n end,\n}, Picker)\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@return table|?\nlocal function get_entry(prompt_bufnr, keep_open)\n local entry = actions_state.get_selected_entry()\n if entry and not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return entry\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param allow_multiple boolean|?\n---@return table[]|?\nlocal function get_selected(prompt_bufnr, keep_open, allow_multiple)\n local picker = actions_state.get_current_picker(prompt_bufnr)\n local entries = picker:get_multi_selection()\n if entries and #entries > 0 then\n if #entries > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n\n return entries\n else\n local entry = get_entry(prompt_bufnr, keep_open)\n\n if entry then\n return { entry }\n end\n end\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param initial_query string|?\n---@return string|?\nlocal function get_query(prompt_bufnr, keep_open, initial_query)\n local query = actions_state.get_current_line()\n if not query or string.len(query) == 0 then\n query = initial_query\n end\n if query and string.len(query) > 0 then\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return query\n else\n return nil\n end\nend\n\n---@param opts { entry_key: string|?, callback: fun(path: string)|?, allow_multiple: boolean|?, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|?, initial_query: string|? }\nlocal function attach_picker_mappings(map, opts)\n -- Docs for telescope actions:\n -- https://github.com/nvim-telescope/telescope.nvim/blob/master/lua/telescope/actions/init.lua\n\n local function entry_to_value(entry)\n if opts.entry_key then\n return entry[opts.entry_key]\n else\n return entry\n end\n end\n\n if opts.query_mappings then\n for key, mapping in pairs(opts.query_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local query = get_query(prompt_bufnr, false, opts.initial_query)\n if query then\n mapping.callback(query)\n end\n end)\n end\n end\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, mapping.keep_open, mapping.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n mapping.callback(unpack(values))\n elseif mapping.fallback_to_query then\n local query = get_query(prompt_bufnr, mapping.keep_open)\n if query then\n mapping.callback(query)\n end\n end\n end)\n end\n end\n\n if opts.callback then\n map({ \"i\", \"n\" }, \"\", function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, false, opts.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n opts.callback(unpack(values))\n end\n end)\n end\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nTelescopePicker.find_files = function(self, opts)\n opts = opts or {}\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n telescope.find_files {\n prompt_title = prompt_title,\n cwd = opts.dir and tostring(opts.dir) or tostring(Obsidian.dir),\n find_command = self:_build_find_cmd(),\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nTelescopePicker.grep = function(self, opts)\n opts = opts or {}\n\n local cwd = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n initial_query = opts.query,\n })\n return true\n end\n\n if opts.query and string.len(opts.query) > 0 then\n telescope.grep_string {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n search = opts.query,\n attach_mappings = attach_mappings,\n }\n else\n telescope.live_grep {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n attach_mappings = attach_mappings,\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\nTelescopePicker.pick = function(self, values, opts)\n local pickers = require \"telescope.pickers\"\n local finders = require \"telescope.finders\"\n local conf = require \"telescope.config\"\n local make_entry = require \"telescope.make_entry\"\n\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local picker_opts = {\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"value\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\n\n local displayer = function(entry)\n return self:_make_display(entry.raw)\n end\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local previewer\n if type(values[1]) == \"table\" then\n previewer = conf.values.grep_previewer(picker_opts)\n -- Get theme to use.\n if conf.pickers then\n for _, picker_name in ipairs { \"grep_string\", \"live_grep\", \"find_files\" } do\n local picker_conf = conf.pickers[picker_name]\n if picker_conf and picker_conf.theme then\n picker_opts =\n vim.tbl_extend(\"force\", picker_opts, require(\"telescope.themes\")[\"get_\" .. picker_conf.theme] {})\n break\n end\n end\n end\n end\n\n local make_entry_from_string = make_entry.gen_from_string(picker_opts)\n\n pickers\n .new(picker_opts, {\n prompt_title = prompt_title,\n finder = finders.new_table {\n results = values,\n entry_maker = function(v)\n if type(v) == \"string\" then\n return make_entry_from_string(v)\n else\n local ordinal = v.ordinal\n if ordinal == nil then\n ordinal = \"\"\n if type(v.display) == \"string\" then\n ordinal = ordinal .. v.display\n end\n if v.filename ~= nil then\n ordinal = ordinal .. \" \" .. v.filename\n end\n end\n\n return {\n value = v.value,\n display = displayer,\n ordinal = ordinal,\n filename = v.filename,\n valid = v.valid,\n lnum = v.lnum,\n col = v.col,\n raw = v,\n }\n end\n end,\n },\n sorter = conf.values.generic_sorter(picker_opts),\n previewer = previewer,\n })\n :find()\nend\n\nreturn TelescopePicker\n"], ["/obsidian.nvim/lua/obsidian/pickers/_snacks.lua", "local snacks_picker = require \"snacks.picker\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\nlocal function debug_once(msg, ...)\n -- vim.notify(msg .. vim.inspect(...))\nend\n\n---@param mapping table\n---@return table\nlocal function notes_mappings(mapping)\n if type(mapping) == \"table\" then\n local opts = { win = { input = { keys = {} } }, actions = {} }\n for k, v in pairs(mapping) do\n local name = string.gsub(v.desc, \" \", \"_\")\n opts.win.input.keys = {\n [k] = { name, mode = { \"n\", \"i\" }, desc = v.desc },\n }\n opts.actions[name] = function(picker, item)\n debug_once(\"mappings :\", item)\n picker:close()\n vim.schedule(function()\n v.callback(item.value or item._path)\n end)\n end\n end\n return opts\n end\n return {}\nend\n\n---@class obsidian.pickers.SnacksPicker : obsidian.Picker\nlocal SnacksPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"SnacksPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nSnacksPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"files\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"find files callback: \", item)\n opts.callback(item._path)\n else\n debug_once(\"find files jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nSnacksPicker.grep = function(self, opts)\n opts = opts or {}\n\n debug_once(\"grep opts : \", opts)\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"grep\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"grep callback: \", item)\n opts.callback(item._path or item.filename)\n else\n debug_once(\"grep jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nSnacksPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n debug_once(\"pick opts: \", opts)\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n table.insert(entries, {\n text = value,\n value = value,\n })\n elseif value.valid ~= false then\n local name = self:_make_display(value)\n table.insert(entries, {\n text = name,\n buf = self.calling_bufnr,\n filename = value.filename,\n value = value.value,\n pos = { value.lnum, value.col or 0 },\n })\n end\n end\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n tilte = opts.prompt_title,\n items = entries,\n layout = {\n preview = false,\n },\n format = \"text\",\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"pick callback: \", item)\n opts.callback(item.value)\n else\n debug_once(\"pick jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n\n snacks_picker.pick(pick_opts)\nend\n\nreturn SnacksPicker\n"], ["/obsidian.nvim/lua/obsidian/pickers/picker.lua", "local abc = require \"obsidian.abc\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal strings = require \"plenary.strings\"\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---@class obsidian.Picker : obsidian.ABC\n---\n---@field calling_bufnr integer\nlocal Picker = abc.new_class()\n\nPicker.new = function()\n local self = Picker.init()\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n return self\nend\n\n-------------------------------------------------------------------\n--- Abstract methods that need to be implemented by subclasses. ---\n-------------------------------------------------------------------\n\n---@class obsidian.PickerMappingOpts\n---\n---@field desc string\n---@field callback fun(...)\n---@field fallback_to_query boolean|?\n---@field keep_open boolean|?\n---@field allow_multiple boolean|?\n\n---@alias obsidian.PickerMappingTable table\n\n---@class obsidian.PickerFindOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Find files in a directory.\n---\n---@param opts obsidian.PickerFindOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `callback`: Callback to run with the selected entry.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.find_files = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerGrepOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field query string|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable\n---@field selection_mappings obsidian.PickerMappingTable\n\n--- Grep for a string.\n---\n---@param opts obsidian.PickerGrepOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.grep = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerEntry\n---\n---@field value any\n---@field ordinal string|?\n---@field display string|?\n---@field filename string|?\n---@field valid boolean|?\n---@field lnum integer|?\n---@field col integer|?\n---@field icon string|?\n---@field icon_hl string|?\n\n---@class obsidian.PickerPickOpts\n---\n---@field prompt_title string|?\n---@field callback fun(value: any, ...: any)|?\n---@field allow_multiple boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Pick from a list of items.\n---\n---@param values string[]|obsidian.PickerEntry[] Items to pick from.\n---@param opts obsidian.PickerPickOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected item(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.pick = function(self, values, opts)\n error \"not implemented\"\nend\n\n------------------------------------------------------------------\n--- Concrete methods with a default implementation subclasses. ---\n------------------------------------------------------------------\n\n--- Find notes by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.find_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Notes\",\n dir = Obsidian.dir,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Find templates by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string) }|? Options.\n---\n--- Options:\n--- `callback`: Callback to run with the selected template path.\nPicker.find_templates = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local templates_dir = api.templates_dir()\n\n if templates_dir == nil then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Templates\",\n callback = opts.callback,\n dir = templates_dir,\n no_default_mappings = true,\n }\nend\n\n--- Grep search in notes.\n---\n---@param opts { prompt_title: string|?, query: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.grep_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n self:grep {\n prompt_title = opts.prompt_title or \"Grep notes\",\n dir = Obsidian.dir,\n query = opts.query,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Open picker with a list of notes.\n---\n---@param notes obsidian.Note[]\n---@param opts { prompt_title: string|?, callback: fun(note: obsidian.Note, ...: obsidian.Note), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_note = function(self, notes, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n -- Launch picker with results.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, note in ipairs(notes) do\n assert(note.path)\n local rel_path = assert(note.path:vault_relative_path { strict = true })\n local display_name = note:display_name()\n entries[#entries + 1] = {\n value = note,\n display = display_name,\n ordinal = rel_path .. \" \" .. display_name,\n filename = tostring(note.path),\n }\n end\n\n self:pick(entries, {\n prompt_title = opts.prompt_title or \"Notes\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--- Open picker with a list of tags.\n---\n---@param tags string[]\n---@param opts { prompt_title: string|?, callback: fun(tag: string, ...: string), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected tag(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_tag = function(self, tags, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local selection_mappings\n if not opts.no_default_mappings then\n selection_mappings = self:_tag_selection_mappings()\n end\n\n self:pick(tags, {\n prompt_title = opts.prompt_title or \"Tags\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--------------------------------\n--- Concrete helper methods. ---\n--------------------------------\n\n---@param key string|?\n---@return boolean\nlocal function key_is_set(key)\n if key ~= nil and string.len(key) > 0 then\n return true\n else\n return false\n end\nend\n\n--- Get query mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_query_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.new) then\n mappings[Obsidian.opts.picker.note_mappings.new] = {\n desc = \"new\",\n callback = function(query)\n ---@diagnostic disable-next-line: missing-fields\n require \"obsidian.commands.new\"(require(\"obsidian\").get_client(), { args = query })\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.insert_link) then\n mappings[Obsidian.opts.picker.note_mappings.insert_link] = {\n desc = \"insert link\",\n callback = function(note_or_path)\n ---@type obsidian.Note\n local note\n if Note.is_note_obj(note_or_path) then\n note = note_or_path\n else\n note = Note.from_file(note_or_path)\n end\n local link = api.format_link(note, {})\n vim.api.nvim_put({ link }, \"\", false, true)\n require(\"obsidian.ui\").update(0)\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `pick_tag()`.\n---@return obsidian.PickerMappingTable\nPicker._tag_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.tag_mappings then\n if key_is_set(Obsidian.opts.picker.tag_mappings.tag_note) then\n mappings[Obsidian.opts.picker.tag_mappings.tag_note] = {\n desc = \"tag note\",\n callback = function(...)\n local tags = { ... }\n\n local note = api.current_note(self.calling_bufnr)\n if not note then\n log.warn(\"'%s' is not a note in your workspace\", vim.api.nvim_buf_get_name(self.calling_bufnr))\n return\n end\n\n -- Add the tag and save the new frontmatter to the buffer.\n local tags_added = {}\n local tags_not_added = {}\n for _, tag in ipairs(tags) do\n if note:add_tag(tag) then\n table.insert(tags_added, tag)\n else\n table.insert(tags_not_added, tag)\n end\n end\n\n if #tags_added > 0 then\n if note:update_frontmatter(self.calling_bufnr) then\n log.info(\"Added tags %s to frontmatter\", tags_added)\n else\n log.warn \"Frontmatter unchanged\"\n end\n end\n\n if #tags_not_added > 0 then\n log.warn(\"Note already has tags %s\", tags_not_added)\n end\n end,\n fallback_to_query = true,\n keep_open = true,\n allow_multiple = true,\n }\n end\n\n if key_is_set(Obsidian.opts.picker.tag_mappings.insert_tag) then\n mappings[Obsidian.opts.picker.tag_mappings.insert_tag] = {\n desc = \"insert tag\",\n callback = function(tag)\n vim.api.nvim_put({ \"#\" .. tag }, \"\", false, true)\n end,\n fallback_to_query = true,\n }\n end\n end\n\n return mappings\nend\n\n---@param opts { prompt_title: string, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|? }|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nPicker._build_prompt = function(self, opts)\n opts = opts or {}\n\n ---@type string\n local prompt = opts.prompt_title or \"Find\"\n if string.len(prompt) > 50 then\n prompt = string.sub(prompt, 1, 50) .. \"…\"\n end\n\n prompt = prompt .. \" | confirm\"\n\n if opts.query_mappings then\n local keys = vim.tbl_keys(opts.query_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.query_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n if opts.selection_mappings then\n local keys = vim.tbl_keys(opts.selection_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.selection_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n return prompt\nend\n\n---@param entry obsidian.PickerEntry\n---\n---@return string, { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n---@diagnostic disable-next-line: unused-local\nPicker._make_display = function(self, entry)\n ---@type string\n local display = \"\"\n ---@type { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n local highlights = {}\n\n if entry.filename ~= nil then\n local icon, icon_hl\n if entry.icon then\n icon = entry.icon\n icon_hl = entry.icon_hl\n else\n icon, icon_hl = api.get_icon(entry.filename)\n end\n\n if icon ~= nil then\n display = display .. icon .. \" \"\n if icon_hl ~= nil then\n highlights[#highlights + 1] = { { 0, strings.strdisplaywidth(icon) }, icon_hl }\n end\n end\n\n display = display .. Path.new(entry.filename):vault_relative_path { strict = true }\n\n if entry.lnum ~= nil then\n display = display .. \":\" .. entry.lnum\n\n if entry.col ~= nil then\n display = display .. \":\" .. entry.col\n end\n end\n\n if entry.display ~= nil then\n display = display .. \":\" .. entry.display\n end\n elseif entry.display ~= nil then\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. entry.display\n else\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. tostring(entry.value)\n end\n\n return assert(display), highlights\nend\n\n---@return string[]\nPicker._build_find_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = { sort_by = Obsidian.opts.sort_by, sort_reversed = Obsidian.opts.sort_reversed }\n return search.build_find_cmd(\".\", nil, search_opts)\nend\n\nPicker._build_grep_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = {\n sort_by = Obsidian.opts.sort_by,\n sort_reversed = Obsidian.opts.sort_reversed,\n smart_case = true,\n fixed_strings = true,\n }\n return search.build_grep_cmd(search_opts)\nend\n\nreturn Picker\n"], ["/obsidian.nvim/lua/obsidian/api.lua", "local M = {}\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal iter, string, table = vim.iter, string, table\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\n\n---@param dir string | obsidian.Path\n---@return Iter\nM.dir = function(dir)\n dir = tostring(dir)\n local dir_opts = {\n depth = 10,\n skip = function(p)\n return not vim.startswith(p, \".\") and p ~= vim.fs.basename(tostring(M.templates_dir()))\n end,\n follow = true,\n }\n\n return vim\n .iter(vim.fs.dir(dir, dir_opts))\n :filter(function(path)\n return vim.endswith(path, \".md\")\n end)\n :map(function(path)\n return vim.fs.joinpath(dir, path)\n end)\nend\n\n--- Get the templates folder.\n---\n---@return obsidian.Path|?\nM.templates_dir = function(workspace)\n local opts = Obsidian.opts\n\n local Workspace = require \"obsidian.workspace\"\n\n if workspace and workspace ~= Obsidian.workspace then\n opts = Workspace.normalize_opts(workspace)\n end\n\n if opts.templates == nil or opts.templates.folder == nil then\n return nil\n end\n\n local paths_to_check = { Obsidian.workspace.root / opts.templates.folder, Path.new(opts.templates.folder) }\n for _, path in ipairs(paths_to_check) do\n if path:is_dir() then\n return path\n end\n end\n\n log.err_once(\"'%s' is not a valid templates directory\", opts.templates.folder)\n return nil\nend\n\n--- Check if a path represents a note in the workspace.\n---\n---@param path string|obsidian.Path\n---@param workspace obsidian.Workspace|?\n---\n---@return boolean\nM.path_is_note = function(path, workspace)\n path = Path.new(path):resolve()\n workspace = workspace or Obsidian.workspace\n\n local in_vault = path.filename:find(vim.pesc(tostring(workspace.root))) ~= nil\n if not in_vault then\n return false\n end\n\n -- Notes have to be markdown file.\n if path.suffix ~= \".md\" then\n return false\n end\n\n -- Ignore markdown files in the templates directory.\n local templates_dir = M.templates_dir(workspace)\n if templates_dir ~= nil then\n if templates_dir:is_parent_of(path) then\n return false\n end\n end\n\n return true\nend\n\n--- Get the current note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note|?\n---@diagnostic disable-next-line: unused-local\nM.current_note = function(bufnr, opts)\n bufnr = bufnr or 0\n local Note = require \"obsidian.note\"\n if not M.path_is_note(vim.api.nvim_buf_get_name(bufnr)) then\n return nil\n end\n\n opts = opts or {}\n if not opts.max_lines then\n opts.max_lines = Obsidian.opts.search_max_lines\n end\n return Note.from_buffer(bufnr, opts)\nend\n\n---builtin functions that are impure, interacts with editor state, like vim.api\n\n---Toggle the checkbox on the current line.\n---\n---@param states table|nil Optional table containing checkbox states (e.g., {\" \", \"x\"}).\n---@param line_num number|nil Optional line number to toggle the checkbox on. Defaults to the current line.\nM.toggle_checkbox = function(states, line_num)\n if not util.in_node { \"list\", \"paragraph\" } or util.in_node \"block_quote\" then\n return\n end\n line_num = line_num or unpack(vim.api.nvim_win_get_cursor(0))\n local line = vim.api.nvim_buf_get_lines(0, line_num - 1, line_num, false)[1]\n\n local checkboxes = states or { \" \", \"x\" }\n\n if util.is_checkbox(line) then\n for i, check_char in ipairs(checkboxes) do\n if string.match(line, \"^.* %[\" .. vim.pesc(check_char) .. \"%].*\") then\n i = i % #checkboxes\n line = string.gsub(line, vim.pesc(\"[\" .. check_char .. \"]\"), \"[\" .. checkboxes[i + 1] .. \"]\", 1)\n break\n end\n end\n elseif Obsidian.opts.checkbox.create_new then\n local unordered_list_pattern = \"^(%s*)[-*+] (.*)\"\n if string.match(line, unordered_list_pattern) then\n line = string.gsub(line, unordered_list_pattern, \"%1- [ ] %2\")\n else\n line = string.gsub(line, \"^(%s*)\", \"%1- [ ] \")\n end\n else\n goto out\n end\n\n vim.api.nvim_buf_set_lines(0, line_num - 1, line_num, true, { line })\n ::out::\nend\n\n---@return [number, number, number, number] tuple containing { buf, win, row, col }\nM.get_active_window_cursor_location = function()\n local buf = vim.api.nvim_win_get_buf(0)\n local win = vim.api.nvim_get_current_win()\n local row, col = unpack(vim.api.nvim_win_get_cursor(win))\n local location = { buf, win, row, col }\n return location\nend\n\n--- Create a formatted markdown / wiki link for a note.\n---\n---@param note obsidian.Note|obsidian.Path|string The note/path to link to.\n---@param opts { label: string|?, link_style: obsidian.config.LinkStyle|?, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|? Options.\n---\n---@return string\nM.format_link = function(note, opts)\n local config = require \"obsidian.config\"\n opts = opts or {}\n\n ---@type string, string, string|integer|?\n local rel_path, label, note_id\n if type(note) == \"string\" or Path.is_path_obj(note) then\n ---@cast note string|obsidian.Path\n -- rel_path = tostring(self:vault_relative_path(note, { strict = true }))\n rel_path = assert(Path.new(note):vault_relative_path { strict = true })\n label = opts.label or tostring(note)\n note_id = opts.id\n else\n ---@cast note obsidian.Note\n -- rel_path = tostring(self:vault_relative_path(note.path, { strict = true }))\n rel_path = assert(note.path:vault_relative_path { strict = true })\n label = opts.label or note:display_name()\n note_id = opts.id or note.id\n end\n\n local link_style = opts.link_style\n if link_style == nil then\n link_style = Obsidian.opts.preferred_link_style\n end\n\n local new_opts = { path = rel_path, label = label, id = note_id, anchor = opts.anchor, block = opts.block }\n\n if link_style == config.LinkStyle.markdown then\n return Obsidian.opts.markdown_link_func(new_opts)\n elseif link_style == config.LinkStyle.wiki or link_style == nil then\n return Obsidian.opts.wiki_link_func(new_opts)\n else\n error(string.format(\"Invalid link style '%s'\", link_style))\n end\nend\n\n---Return the full link under cursror\n---\n---@return string? link\n---@return obsidian.search.RefTypes? link_type\nM.cursor_link = function()\n local line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- 0-indexed column to 1-indexed lua string position\n\n local refs = search.find_refs(line, { include_naked_urls = true, include_file_urls = true, include_block_ids = true })\n\n local match = iter(refs):find(function(match)\n local open, close = unpack(match)\n return cur_col >= open and cur_col <= close\n end)\n if match then\n return line:sub(match[1], match[2]), match[3]\n end\nend\n\n---Get the tag under the cursor, if there is one.\n---@return string?\nM.cursor_tag = function()\n local current_line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- nvim_win_get_cursor returns 0-indexed column\n\n for match in iter(search.find_tags(current_line)) do\n local open, close, _ = unpack(match)\n if open <= cur_col and cur_col <= close then\n return string.sub(current_line, open + 1, close)\n end\n end\n\n return nil\nend\n\n--- Get the heading under the cursor, if there is one.\n---@return { header: string, level: integer, anchor: string }|?\nM.cursor_heading = function()\n return util.parse_header(vim.api.nvim_get_current_line())\nend\n\n------------------\n--- buffer api ---\n------------------\n\n--- Check if a buffer is empty.\n---\n---@param bufnr integer|?\n---\n---@return boolean\nM.buffer_is_empty = function(bufnr)\n bufnr = bufnr or 0\n if vim.api.nvim_buf_line_count(bufnr) > 1 then\n return false\n else\n local first_text = vim.api.nvim_buf_get_text(bufnr, 0, 0, 0, 0, {})\n if vim.tbl_isempty(first_text) or first_text[1] == \"\" then\n return true\n else\n return false\n end\n end\nend\n\n--- Open a buffer for the corresponding path.\n---\n---@param path string|obsidian.Path\n---@param opts { line: integer|?, col: integer|?, cmd: string|? }|?\n---@return integer bufnr\nM.open_buffer = function(path, opts)\n path = Path.new(path):resolve()\n opts = opts and opts or {}\n local cmd = vim.trim(opts.cmd and opts.cmd or \"e\")\n\n ---@type integer|?\n local result_bufnr\n\n -- Check for buffer in windows and use 'drop' command if one is found.\n for _, winnr in ipairs(vim.api.nvim_list_wins()) do\n local bufnr = vim.api.nvim_win_get_buf(winnr)\n local bufname = vim.api.nvim_buf_get_name(bufnr)\n if bufname == tostring(path) then\n cmd = \"drop\"\n result_bufnr = bufnr\n break\n end\n end\n\n vim.cmd(string.format(\"%s %s\", cmd, vim.fn.fnameescape(tostring(path))))\n if opts.line then\n vim.api.nvim_win_set_cursor(0, { tonumber(opts.line), opts.col and opts.col or 0 })\n end\n\n if not result_bufnr then\n result_bufnr = vim.api.nvim_get_current_buf()\n end\n\n return result_bufnr\nend\n\n---Get an iterator of (bufnr, bufname) over all named buffers. The buffer names will be absolute paths.\n---\n---@return function () -> (integer, string)|?\nM.get_named_buffers = function()\n local idx = 0\n local buffers = vim.api.nvim_list_bufs()\n\n ---@return integer|?\n ---@return string|?\n return function()\n while idx < #buffers do\n idx = idx + 1\n local bufnr = buffers[idx]\n if vim.api.nvim_buf_is_loaded(bufnr) then\n return bufnr, vim.api.nvim_buf_get_name(bufnr)\n end\n end\n end\nend\n\n----------------\n--- text api ---\n----------------\n\n--- Get the current visual selection of text and exit visual mode.\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return { lines: string[], selection: string, csrow: integer, cscol: integer, cerow: integer, cecol: integer }|?\nM.get_visual_selection = function(opts)\n opts = opts or {}\n -- Adapted from fzf-lua:\n -- https://github.com/ibhagwan/fzf-lua/blob/6ee73fdf2a79bbd74ec56d980262e29993b46f2b/lua/fzf-lua/utils.lua#L434-L466\n -- this will exit visual mode\n -- use 'gv' to reselect the text\n local _, csrow, cscol, cerow, cecol\n local mode = vim.fn.mode()\n if opts.strict and not vim.endswith(string.lower(mode), \"v\") then\n return\n end\n\n if mode == \"v\" or mode == \"V\" or mode == \"\u0016\" then\n -- if we are in visual mode use the live position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \".\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"v\")\n if mode == \"V\" then\n -- visual line doesn't provide columns\n cscol, cecol = 0, 999\n end\n -- exit visual mode\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", true)\n else\n -- otherwise, use the last known visual position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \"'<\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"'>\")\n end\n\n -- Swap vars if needed\n if cerow < csrow then\n csrow, cerow = cerow, csrow\n cscol, cecol = cecol, cscol\n elseif cerow == csrow and cecol < cscol then\n cscol, cecol = cecol, cscol\n end\n\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n if vim.tbl_isempty(lines) then\n return\n end\n\n -- When the whole line is selected via visual line mode (\"V\"), cscol / cecol will be equal to \"v:maxcol\"\n -- for some odd reason. So change that to what they should be here. See ':h getpos' for more info.\n local maxcol = vim.api.nvim_get_vvar \"maxcol\"\n if cscol == maxcol then\n cscol = string.len(lines[1])\n end\n if cecol == maxcol then\n cecol = string.len(lines[#lines])\n end\n\n ---@type string\n local selection\n local n = #lines\n if n <= 0 then\n selection = \"\"\n elseif n == 1 then\n selection = string.sub(lines[1], cscol, cecol)\n elseif n == 2 then\n selection = string.sub(lines[1], cscol) .. \"\\n\" .. string.sub(lines[n], 1, cecol)\n else\n selection = string.sub(lines[1], cscol)\n .. \"\\n\"\n .. table.concat(lines, \"\\n\", 2, n - 1)\n .. \"\\n\"\n .. string.sub(lines[n], 1, cecol)\n end\n\n return {\n lines = lines,\n selection = selection,\n csrow = csrow,\n cscol = cscol,\n cerow = cerow,\n cecol = cecol,\n }\nend\n\n------------------\n--- UI helpers ---\n------------------\n\n---Get the strategy for opening notes\n---\n---@param opt obsidian.config.OpenStrategy\n---@return string\nM.get_open_strategy = function(opt)\n local OpenStrategy = require(\"obsidian.config\").OpenStrategy\n\n -- either 'leaf', 'row' for vertically split windows, or 'col' for horizontally split windows\n local cur_layout = vim.fn.winlayout()[1]\n\n if vim.startswith(OpenStrategy.hsplit, opt) then\n if cur_layout ~= \"col\" then\n return \"split \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit, opt) then\n if cur_layout ~= \"row\" then\n return \"vsplit \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit_force, opt) then\n return \"vsplit \"\n elseif vim.startswith(OpenStrategy.hsplit_force, opt) then\n return \"hsplit \"\n elseif vim.startswith(OpenStrategy.current, opt) then\n return \"e \"\n else\n log.err(\"undefined open strategy '%s'\", opt)\n return \"e \"\n end\nend\n\n----------------------------\n--- Integration helpers ----\n----------------------------\n\n--- Get the path to where a plugin is installed.\n---\n---@param name string\n---@return string|?\nlocal get_src_root = function(name)\n return vim.iter(vim.api.nvim_list_runtime_paths()):find(function(path)\n return vim.endswith(path, name)\n end)\nend\n\n--- Get info about a plugin.\n---\n---@param name string\n---\n---@return { commit: string|?, path: string }|?\nM.get_plugin_info = function(name)\n local src_root = get_src_root(name)\n if not src_root then\n return\n end\n local out = { path = src_root }\n local obj = vim.system({ \"git\", \"rev-parse\", \"HEAD\" }, { cwd = src_root }):wait(1000)\n if obj.code == 0 then\n out.commit = vim.trim(obj.stdout)\n else\n out.commit = \"unknown\"\n end\n return out\nend\n\n--- Get info about a external dependency.\n---\n---@param cmd string\n---@return string|?\nM.get_external_dependency_info = function(cmd)\n local obj = vim.system({ cmd, \"--version\" }, {}):wait(1000)\n if obj.code ~= 0 then\n return\n end\n local version = vim.version.parse(obj.stdout)\n if version then\n return (\"%d.%d.%d\"):format(version.major, version.minor, version.patch)\n end\nend\n\n------------------\n--- UI helpers ---\n------------------\n\nlocal INPUT_CANCELLED = \"~~~INPUT-CANCELLED~~~\"\n\n--- Prompt user for an input. Returns nil if canceled, otherwise a string (possibly empty).\n---\n---@param prompt string\n---@param opts { completion: string|?, default: string|? }|?\n---\n---@return string|?\nM.input = function(prompt, opts)\n opts = opts or {}\n\n if not vim.endswith(prompt, \" \") then\n prompt = prompt .. \" \"\n end\n\n local input = vim.trim(\n vim.fn.input { prompt = prompt, completion = opts.completion, default = opts.default, cancelreturn = INPUT_CANCELLED }\n )\n\n if input ~= INPUT_CANCELLED then\n return input\n else\n return nil\n end\nend\n\n--- Prompt user for a confirmation.\n---\n---@param prompt string\n---\n---@return boolean\nM.confirm = function(prompt)\n if not vim.endswith(util.rstrip_whitespace(prompt), \"[Y/n]\") then\n prompt = util.rstrip_whitespace(prompt) .. \" [Y/n] \"\n end\n\n local confirmation = M.input(prompt)\n if confirmation == nil then\n return false\n end\n\n confirmation = string.lower(confirmation)\n\n if confirmation == \"\" or confirmation == \"y\" or confirmation == \"yes\" then\n return true\n else\n return false\n end\nend\n\n---@enum OSType\nM.OSType = {\n Linux = \"Linux\",\n Wsl = \"Wsl\",\n Windows = \"Windows\",\n Darwin = \"Darwin\",\n FreeBSD = \"FreeBSD\",\n}\n\nM._current_os = nil\n\n---Get the running operating system.\n---Reference https://vi.stackexchange.com/a/2577/33116\n---@return OSType\nM.get_os = function()\n if M._current_os ~= nil then\n return M._current_os\n end\n\n local this_os\n if vim.fn.has \"win32\" == 1 then\n this_os = M.OSType.Windows\n else\n local sysname = vim.uv.os_uname().sysname\n local release = vim.uv.os_uname().release:lower()\n if sysname:lower() == \"linux\" and string.find(release, \"microsoft\") then\n this_os = M.OSType.Wsl\n else\n this_os = sysname\n end\n end\n\n assert(this_os)\n M._current_os = this_os\n return this_os\nend\n\n--- Get a nice icon for a file or URL, if possible.\n---\n---@param path string\n---\n---@return string|?, string|? (icon, hl_group) The icon and highlight group.\nM.get_icon = function(path)\n if util.is_url(path) then\n local icon = \"\"\n local _, hl_group = M.get_icon \"blah.html\"\n return icon, hl_group\n else\n local ok, res = pcall(function()\n local icon, hl_group = require(\"nvim-web-devicons\").get_icon(path, nil, { default = true })\n return { icon, hl_group }\n end)\n if ok and type(res) == \"table\" then\n local icon, hlgroup = unpack(res)\n return icon, hlgroup\n elseif vim.endswith(path, \".md\") then\n return \"\"\n end\n end\n return nil\nend\n\n--- Resolve a basename to full path inside the vault.\n---\n---@param src string\n---@return string\nM.resolve_image_path = function(src)\n local img_folder = Obsidian.opts.attachments.img_folder\n\n ---@cast img_folder -nil\n if vim.startswith(img_folder, \".\") then\n local dirname = Path.new(vim.fs.dirname(vim.api.nvim_buf_get_name(0)))\n return tostring(dirname / img_folder / src)\n else\n return tostring(Obsidian.dir / img_folder / src)\n end\nend\n\n--- Follow a link. If the link argument is `nil` we attempt to follow a link under the cursor.\n---\n---@param link string\n---@param opts { open_strategy: obsidian.config.OpenStrategy|? }|?\nM.follow_link = function(link, opts)\n opts = opts and opts or {}\n local Note = require \"obsidian.note\"\n\n search.resolve_link_async(link, function(results)\n if #results == 0 then\n return\n end\n\n ---@param res obsidian.ResolveLinkResult\n local function follow_link(res)\n if res.url ~= nil then\n Obsidian.opts.follow_url_func(res.url)\n return\n end\n\n if util.is_img(res.location) then\n local path = Obsidian.dir / res.location\n Obsidian.opts.follow_img_func(tostring(path))\n return\n end\n\n if res.note ~= nil then\n -- Go to resolved note.\n return res.note:open { line = res.line, col = res.col, open_strategy = opts.open_strategy }\n end\n\n if res.link_type == search.RefTypes.Wiki or res.link_type == search.RefTypes.WikiWithAlias then\n -- Prompt to create a new note.\n if M.confirm(\"Create new note '\" .. res.location .. \"'?\") then\n -- Create a new note.\n ---@type string|?, string[]\n local id, aliases\n if res.name == res.location then\n aliases = {}\n else\n aliases = { res.name }\n id = res.location\n end\n\n local note = Note.create { title = res.name, id = id, aliases = aliases }\n return note:open {\n open_strategy = opts.open_strategy,\n callback = function(bufnr)\n note:write_to_buffer { bufnr = bufnr }\n end,\n }\n else\n log.warn \"Aborted\"\n return\n end\n end\n\n return log.err(\"Failed to resolve file '\" .. res.location .. \"'\")\n end\n\n if #results == 1 then\n return vim.schedule(function()\n follow_link(results[1])\n end)\n else\n return vim.schedule(function()\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple matches to '%s', but no picker is configured\", link)\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, res in ipairs(results) do\n local icon, icon_hl\n if res.url ~= nil then\n icon, icon_hl = M.get_icon(res.url)\n end\n table.insert(entries, {\n value = res,\n display = res.name,\n filename = res.path and tostring(res.path) or nil,\n icon = icon,\n icon_hl = icon_hl,\n })\n end\n\n picker:pick(entries, {\n prompt_title = \"Follow link\",\n callback = function(res)\n follow_link(res)\n end,\n })\n end)\n end\n end)\nend\n--------------------------\n---- Mapping functions ---\n--------------------------\n\n---@param direction \"next\" | \"prev\"\nM.nav_link = function(direction)\n vim.validate(\"direction\", direction, \"string\", false, \"nav_link must be called with a direction\")\n local cursor_line, cursor_col = unpack(vim.api.nvim_win_get_cursor(0))\n local Note = require \"obsidian.note\"\n\n search.find_links(Note.from_buffer(0), {}, function(matches)\n if direction == \"next\" then\n for i = 1, #matches do\n local match = matches[i]\n if (match.line > cursor_line) or (cursor_line == match.line and cursor_col < match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n\n if direction == \"prev\" then\n for i = #matches, 1, -1 do\n local match = matches[i]\n if (match.line < cursor_line) or (cursor_line == match.line and cursor_col > match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n end)\nend\n\nM.smart_action = function()\n local legacy = Obsidian.opts.legacy_commands\n -- follow link if possible\n if M.cursor_link() then\n return legacy and \"ObsidianFollowLink\" or \"Obsidian follow_link\"\n end\n\n -- show notes with tag if possible\n if M.cursor_tag() then\n return legacy and \"ObsidianTags\" or \"Obsidian tags\"\n end\n\n if M.cursor_heading() then\n return \"za\"\n end\n\n -- toggle task if possible\n -- cycles through your custom UI checkboxes, default: [ ] [~] [>] [x]\n return legacy and \"ObsidianToggleCheckbox\" or \"Obsidian toggle_checkbox\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/_fzf.lua", "local fzf = require \"fzf-lua\"\nlocal fzf_actions = require \"fzf-lua.actions\"\nlocal entry_to_file = require(\"fzf-lua.path\").entry_to_file\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@param prompt_title string|?\n---@return string|?\nlocal function format_prompt(prompt_title)\n if not prompt_title then\n return\n else\n return prompt_title .. \" ❯ \"\n end\nend\n\n---@param keymap string\n---@return string\nlocal function format_keymap(keymap)\n keymap = string.lower(keymap)\n keymap = string.gsub(keymap, vim.pesc \"\", \"\")\n return keymap\nend\n\n---@class obsidian.pickers.FzfPicker : obsidian.Picker\nlocal FzfPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"FzfPicker()\"\n end,\n}, Picker)\n\n---@param opts { callback: fun(path: string)|?, no_default_mappings: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_path_actions(opts)\n local actions = {\n default = function(selected, fzf_opts)\n if not opts.no_default_mappings then\n fzf_actions.file_edit_or_qf(selected, fzf_opts)\n end\n\n if opts.callback then\n local path = entry_to_file(selected[1], fzf_opts).path\n opts.callback(path)\n end\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected, fzf_opts)\n local path = entry_to_file(selected[1], fzf_opts).path\n mapping.callback(path)\n end\n end\n end\n\n return actions\nend\n\n---@param display_to_value_map table\n---@param opts { callback: fun(path: string)|?, allow_multiple: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_value_actions(display_to_value_map, opts)\n ---@param allow_multiple boolean|?\n ---@return any[]|?\n local function get_values(selected, allow_multiple)\n if not selected then\n return\n end\n\n local values = vim.tbl_map(function(k)\n return display_to_value_map[k]\n end, selected)\n\n values = vim.tbl_filter(function(v)\n return v ~= nil\n end, values)\n\n if #values > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if #values > 0 then\n return values\n else\n return nil\n end\n end\n\n local actions = {\n default = function(selected)\n if not opts.callback then\n return\n end\n\n local values = get_values(selected, opts.allow_multiple)\n if not values then\n return\n end\n\n opts.callback(unpack(values))\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected)\n local values = get_values(selected, mapping.allow_multiple)\n if not values then\n return\n end\n\n mapping.callback(unpack(values))\n end\n end\n end\n\n return actions\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nFzfPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path.new(opts.dir) or Obsidian.dir\n\n fzf.files {\n cwd = tostring(dir),\n cmd = table.concat(self:_build_find_cmd(), \" \"),\n actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n },\n prompt = format_prompt(opts.prompt_title),\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nFzfPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n local cmd = table.concat(self:_build_grep_cmd(), \" \")\n local actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n if opts.query and string.len(opts.query) > 0 then\n fzf.grep {\n cwd = tostring(dir),\n search = opts.query,\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n else\n fzf.live_grep {\n cwd = tostring(dir),\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nFzfPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n ---@type table\n local display_to_value_map = {}\n\n ---@type string[]\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n display_to_value_map[value] = value\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n local display = self:_make_display(value)\n display_to_value_map[display] = value.value\n entries[#entries + 1] = display\n end\n end\n\n fzf.fzf_exec(entries, {\n prompt = format_prompt(\n self:_build_prompt { prompt_title = opts.prompt_title, selection_mappings = opts.selection_mappings }\n ),\n actions = get_value_actions(display_to_value_map, {\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n selection_mappings = opts.selection_mappings,\n }),\n })\nend\n\nreturn FzfPicker\n"], ["/obsidian.nvim/lua/obsidian/config.lua", "local log = require \"obsidian.log\"\n\nlocal config = {}\n\n---@class obsidian.config\n---@field workspaces obsidian.workspace.WorkspaceSpec[]\n---@field log_level? integer\n---@field notes_subdir? string\n---@field templates? obsidian.config.TemplateOpts\n---@field new_notes_location? obsidian.config.NewNotesLocation\n---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func? fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path\n---@field wiki_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field markdown_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field preferred_link_style? obsidian.config.LinkStyle\n---@field follow_url_func? fun(url: string)\n---@field follow_img_func? fun(img: string)\n---@field note_frontmatter_func? (fun(note: obsidian.Note): table)\n---@field disable_frontmatter? (fun(fname: string?): boolean)|boolean\n---@field backlinks? obsidian.config.BacklinkOpts\n---@field completion? obsidian.config.CompletionOpts\n---@field picker? obsidian.config.PickerOpts\n---@field daily_notes? obsidian.config.DailyNotesOpts\n---@field sort_by? obsidian.config.SortBy\n---@field sort_reversed? boolean\n---@field search_max_lines? integer\n---@field open_notes_in? obsidian.config.OpenStrategy\n---@field ui? obsidian.config.UIOpts | table\n---@field attachments? obsidian.config.AttachmentsOpts\n---@field callbacks? obsidian.config.CallbackConfig\n---@field legacy_commands? boolean\n---@field statusline? obsidian.config.StatuslineOpts\n---@field footer? obsidian.config.FooterOpts\n---@field open? obsidian.config.OpenOpts\n---@field checkbox? obsidian.config.CheckboxOpts\n---@field comment? obsidian.config.CommentOpts\n\n---@class obsidian.config.ClientOpts\n---@field dir string|?\n---@field workspaces obsidian.workspace.WorkspaceSpec[]|?\n---@field log_level integer\n---@field notes_subdir string|?\n---@field templates obsidian.config.TemplateOpts\n---@field new_notes_location obsidian.config.NewNotesLocation\n---@field note_id_func (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func (fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path)|?\n---@field wiki_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field markdown_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field preferred_link_style obsidian.config.LinkStyle\n---@field follow_url_func fun(url: string)|?\n---@field follow_img_func fun(img: string)|?\n---@field note_frontmatter_func (fun(note: obsidian.Note): table)|?\n---@field disable_frontmatter (fun(fname: string?): boolean)|boolean|?\n---@field backlinks obsidian.config.BacklinkOpts\n---@field completion obsidian.config.CompletionOpts\n---@field picker obsidian.config.PickerOpts\n---@field daily_notes obsidian.config.DailyNotesOpts\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field search_max_lines integer\n---@field open_notes_in obsidian.config.OpenStrategy\n---@field ui obsidian.config.UIOpts | table\n---@field attachments obsidian.config.AttachmentsOpts\n---@field callbacks obsidian.config.CallbackConfig\n---@field legacy_commands boolean\n---@field statusline obsidian.config.StatuslineOpts\n---@field footer obsidian.config.FooterOpts\n---@field open obsidian.config.OpenOpts\n---@field checkbox obsidian.config.CheckboxOpts\n---@field comment obsidian.config.CommentOpts\n\n---@enum obsidian.config.OpenStrategy\nconfig.OpenStrategy = {\n current = \"current\",\n vsplit = \"vsplit\",\n hsplit = \"hsplit\",\n vsplit_force = \"vsplit_force\",\n hsplit_force = \"hsplit_force\",\n}\n\n---@enum obsidian.config.SortBy\nconfig.SortBy = {\n path = \"path\",\n modified = \"modified\",\n accessed = \"accessed\",\n created = \"created\",\n}\n\n---@enum obsidian.config.NewNotesLocation\nconfig.NewNotesLocation = {\n current_dir = \"current_dir\",\n notes_subdir = \"notes_subdir\",\n}\n\n---@enum obsidian.config.LinkStyle\nconfig.LinkStyle = {\n wiki = \"wiki\",\n markdown = \"markdown\",\n}\n\n---@enum obsidian.config.Picker\nconfig.Picker = {\n telescope = \"telescope.nvim\",\n fzf_lua = \"fzf-lua\",\n mini = \"mini.pick\",\n snacks = \"snacks.pick\",\n}\n\n--- Get defaults.\n---\n---@return obsidian.config.ClientOpts\nconfig.default = {\n legacy_commands = true,\n workspaces = {},\n log_level = vim.log.levels.INFO,\n notes_subdir = nil,\n new_notes_location = config.NewNotesLocation.current_dir,\n note_id_func = nil,\n wiki_link_func = require(\"obsidian.builtin\").wiki_link_id_prefix,\n markdown_link_func = require(\"obsidian.builtin\").markdown_link,\n preferred_link_style = config.LinkStyle.wiki,\n follow_url_func = vim.ui.open,\n follow_img_func = vim.ui.open,\n note_frontmatter_func = nil,\n disable_frontmatter = false,\n sort_by = \"modified\",\n sort_reversed = true,\n search_max_lines = 1000,\n open_notes_in = \"current\",\n\n ---@class obsidian.config.TemplateOpts\n ---\n ---@field folder string|obsidian.Path|?\n ---@field date_format string|?\n ---@field time_format string|?\n --- A map for custom variables, the key should be the variable and the value a function.\n --- Functions are called with obsidian.TemplateContext objects as their sole parameter.\n --- See: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Template#substitutions\n ---@field substitutions table|?\n ---@field customizations table|?\n templates = {\n folder = nil,\n date_format = nil,\n time_format = nil,\n substitutions = {},\n\n ---@class obsidian.config.CustomTemplateOpts\n ---\n ---@field notes_subdir? string\n ---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n customizations = {},\n },\n\n ---@class obsidian.config.BacklinkOpts\n ---\n ---@field parse_headers boolean\n backlinks = {\n parse_headers = true,\n },\n\n ---@class obsidian.config.CompletionOpts\n ---\n ---@field nvim_cmp? boolean\n ---@field blink? boolean\n ---@field min_chars? integer\n ---@field match_case? boolean\n ---@field create_new? boolean\n completion = (function()\n local has_nvim_cmp, _ = pcall(require, \"cmp\")\n return {\n nvim_cmp = has_nvim_cmp,\n min_chars = 2,\n match_case = true,\n create_new = true,\n }\n end)(),\n\n ---@class obsidian.config.PickerNoteMappingOpts\n ---\n ---@field new? string\n ---@field insert_link? string\n\n ---@class obsidian.config.PickerTagMappingOpts\n ---\n ---@field tag_note? string\n ---@field insert_tag? string\n\n ---@class obsidian.config.PickerOpts\n ---\n ---@field name obsidian.config.Picker|?\n ---@field note_mappings? obsidian.config.PickerNoteMappingOpts\n ---@field tag_mappings? obsidian.config.PickerTagMappingOpts\n picker = {\n name = nil,\n note_mappings = {\n new = \"\",\n insert_link = \"\",\n },\n tag_mappings = {\n tag_note = \"\",\n insert_tag = \"\",\n },\n },\n\n ---@class obsidian.config.DailyNotesOpts\n ---\n ---@field folder? string\n ---@field date_format? string\n ---@field alias_format? string\n ---@field template? string\n ---@field default_tags? string[]\n ---@field workdays_only? boolean\n daily_notes = {\n folder = nil,\n date_format = nil,\n alias_format = nil,\n default_tags = { \"daily-notes\" },\n workdays_only = true,\n },\n\n ---@class obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.CheckboxSpec : obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.UIStyleSpec\n ---@field hl_group string\n\n ---@class obsidian.config.UIOpts\n ---\n ---@field enable boolean\n ---@field ignore_conceal_warn boolean\n ---@field update_debounce integer\n ---@field max_file_length integer|?\n ---@field checkboxes table\n ---@field bullets obsidian.config.UICharSpec|?\n ---@field external_link_icon obsidian.config.UICharSpec\n ---@field reference_text obsidian.config.UIStyleSpec\n ---@field highlight_text obsidian.config.UIStyleSpec\n ---@field tags obsidian.config.UIStyleSpec\n ---@field block_ids obsidian.config.UIStyleSpec\n ---@field hl_groups table\n ui = {\n enable = true,\n ignore_conceal_warn = false,\n update_debounce = 200,\n max_file_length = 5000,\n checkboxes = {\n [\" \"] = { char = \"󰄱\", hl_group = \"obsidiantodo\" },\n [\"~\"] = { char = \"󰰱\", hl_group = \"obsidiantilde\" },\n [\"!\"] = { char = \"\", hl_group = \"obsidianimportant\" },\n [\">\"] = { char = \"\", hl_group = \"obsidianrightarrow\" },\n [\"x\"] = { char = \"\", hl_group = \"obsidiandone\" },\n },\n bullets = { char = \"•\", hl_group = \"ObsidianBullet\" },\n external_link_icon = { char = \"\", hl_group = \"ObsidianExtLinkIcon\" },\n reference_text = { hl_group = \"ObsidianRefText\" },\n highlight_text = { hl_group = \"ObsidianHighlightText\" },\n tags = { hl_group = \"ObsidianTag\" },\n block_ids = { hl_group = \"ObsidianBlockID\" },\n hl_groups = {\n ObsidianTodo = { bold = true, fg = \"#f78c6c\" },\n ObsidianDone = { bold = true, fg = \"#89ddff\" },\n ObsidianRightArrow = { bold = true, fg = \"#f78c6c\" },\n ObsidianTilde = { bold = true, fg = \"#ff5370\" },\n ObsidianImportant = { bold = true, fg = \"#d73128\" },\n ObsidianBullet = { bold = true, fg = \"#89ddff\" },\n ObsidianRefText = { underline = true, fg = \"#c792ea\" },\n ObsidianExtLinkIcon = { fg = \"#c792ea\" },\n ObsidianTag = { italic = true, fg = \"#89ddff\" },\n ObsidianBlockID = { italic = true, fg = \"#89ddff\" },\n ObsidianHighlightText = { bg = \"#75662e\" },\n },\n },\n\n ---@class obsidian.config.AttachmentsOpts\n ---\n ---Default folder to save images to, relative to the vault root (/) or current dir (.), see https://github.com/obsidian-nvim/obsidian.nvim/wiki/Images#change-image-save-location\n ---@field img_folder? string\n ---\n ---Default name for pasted images\n ---@field img_name_func? fun(): string\n ---\n ---Default text to insert for pasted images\n ---@field img_text_func? fun(path: obsidian.Path): string\n ---\n ---Whether to confirm the paste or not. Defaults to true.\n ---@field confirm_img_paste? boolean\n attachments = {\n img_folder = \"assets/imgs\",\n img_text_func = require(\"obsidian.builtin\").img_text_func,\n img_name_func = function()\n return string.format(\"Pasted image %s\", os.date \"%Y%m%d%H%M%S\")\n end,\n confirm_img_paste = true,\n },\n\n ---@class obsidian.config.CallbackConfig\n ---\n ---Runs right after the `obsidian.Client` is initialized.\n ---@field post_setup? fun(client: obsidian.Client)\n ---\n ---Runs when entering a note buffer.\n ---@field enter_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs when leaving a note buffer.\n ---@field leave_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs right before writing a note buffer.\n ---@field pre_write_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs anytime the workspace is set/changed.\n ---@field post_set_workspace? fun(client: obsidian.Client, workspace: obsidian.Workspace)\n callbacks = {},\n\n ---@class obsidian.config.StatuslineOpts\n ---\n ---@field format? string\n ---@field enabled? boolean\n statusline = {\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n enabled = true,\n },\n\n ---@class obsidian.config.FooterOpts\n ---\n ---@field enabled? boolean\n ---@field format? string\n ---@field hl_group? string\n ---@field separator? string|false Set false to disable separator; set an empty string to insert a blank line separator.\n footer = {\n enabled = true,\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n hl_group = \"Comment\",\n separator = string.rep(\"-\", 80),\n },\n\n ---@class obsidian.config.OpenOpts\n ---\n ---Opens the file with current line number\n ---@field use_advanced_uri? boolean\n ---\n ---Function to do the opening, default to vim.ui.open\n ---@field func? fun(uri: string)\n open = {\n use_advanced_uri = false,\n func = vim.ui.open,\n },\n\n ---@class obsidian.config.CheckboxOpts\n ---\n ---@field enabled? boolean\n ---\n ---Order of checkbox state chars, e.g. { \" \", \"x\" }\n ---@field order? string[]\n ---\n ---Whether to create new checkbox on paragraphs\n ---@field create_new? boolean\n checkbox = {\n enabled = true,\n create_new = true,\n order = { \" \", \"~\", \"!\", \">\", \"x\" },\n },\n\n ---@class obsidian.config.CommentOpts\n ---@field enabled boolean\n comment = {\n enabled = false,\n },\n}\n\nlocal tbl_override = function(defaults, overrides)\n local out = vim.tbl_extend(\"force\", defaults, overrides)\n for k, v in pairs(out) do\n if v == vim.NIL then\n out[k] = nil\n end\n end\n return out\nend\n\nlocal function deprecate(name, alternative, version)\n vim.deprecate(name, alternative, version, \"obsidian.nvim\", false)\nend\n\n--- Normalize options.\n---\n---@param opts table\n---@param defaults obsidian.config.ClientOpts|?\n---\n---@return obsidian.config.ClientOpts\nconfig.normalize = function(opts, defaults)\n local builtin = require \"obsidian.builtin\"\n local util = require \"obsidian.util\"\n\n if not defaults then\n defaults = config.default\n end\n\n -------------------------------------------------------------------------------------\n -- Rename old fields for backwards compatibility and warn about deprecated fields. --\n -------------------------------------------------------------------------------------\n\n if opts.ui and opts.ui.tick then\n opts.ui.update_debounce = opts.ui.tick\n opts.ui.tick = nil\n end\n\n if not opts.picker then\n opts.picker = {}\n if opts.finder then\n opts.picker.name = opts.finder\n opts.finder = nil\n end\n if opts.finder_mappings then\n opts.picker.note_mappings = opts.finder_mappings\n opts.finder_mappings = nil\n end\n if opts.picker.mappings and not opts.picker.note_mappings then\n opts.picker.note_mappings = opts.picker.mappings\n opts.picker.mappings = nil\n end\n end\n\n if opts.wiki_link_func == nil and opts.completion ~= nil then\n local warn = false\n\n if opts.completion.prepend_note_id then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n opts.completion.prepend_note_id = nil\n warn = true\n elseif opts.completion.prepend_note_path then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n opts.completion.prepend_note_path = nil\n warn = true\n elseif opts.completion.use_path_only then\n opts.wiki_link_func = builtin.wiki_link_path_only\n opts.completion.use_path_only = nil\n warn = true\n end\n\n if warn then\n log.warn_once(\n \"The config options 'completion.prepend_note_id', 'completion.prepend_note_path', and 'completion.use_path_only' \"\n .. \"are deprecated. Please use 'wiki_link_func' instead.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/406\"\n )\n end\n end\n\n if opts.wiki_link_func == \"prepend_note_id\" then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n elseif opts.wiki_link_func == \"prepend_note_path\" then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n elseif opts.wiki_link_func == \"use_path_only\" then\n opts.wiki_link_func = builtin.wiki_link_path_only\n elseif opts.wiki_link_func == \"use_alias_only\" then\n opts.wiki_link_func = builtin.wiki_link_alias_only\n elseif type(opts.wiki_link_func) == \"string\" then\n error(string.format(\"invalid option '%s' for 'wiki_link_func'\", opts.wiki_link_func))\n end\n\n if opts.completion ~= nil and opts.completion.preferred_link_style ~= nil then\n opts.preferred_link_style = opts.completion.preferred_link_style\n opts.completion.preferred_link_style = nil\n log.warn_once(\n \"The config option 'completion.preferred_link_style' is deprecated, please use the top-level \"\n .. \"'preferred_link_style' instead.\"\n )\n end\n\n if opts.completion ~= nil and opts.completion.new_notes_location ~= nil then\n opts.new_notes_location = opts.completion.new_notes_location\n opts.completion.new_notes_location = nil\n log.warn_once(\n \"The config option 'completion.new_notes_location' is deprecated, please use the top-level \"\n .. \"'new_notes_location' instead.\"\n )\n end\n\n if opts.detect_cwd ~= nil then\n opts.detect_cwd = nil\n log.warn_once(\n \"The 'detect_cwd' field is deprecated and no longer has any affect.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/366 for more details.\"\n )\n end\n\n if opts.open_app_foreground ~= nil then\n opts.open_app_foreground = nil\n log.warn_once [[The config option 'open_app_foreground' is deprecated, please use the `func` field in `open` module:\n\n```lua\n{\n open = {\n func = function(uri)\n vim.ui.open(uri, { cmd = { \"open\", \"-a\", \"/Applications/Obsidian.app\" } })\n end\n }\n}\n```]]\n end\n\n if opts.use_advanced_uri ~= nil then\n opts.use_advanced_uri = nil\n log.warn_once [[The config option 'use_advanced_uri' is deprecated, please use in `open` module instead]]\n end\n\n if opts.overwrite_mappings ~= nil then\n log.warn_once \"The 'overwrite_mappings' config option is deprecated and no longer has any affect.\"\n opts.overwrite_mappings = nil\n end\n\n if opts.mappings ~= nil then\n log.warn_once [[The 'mappings' config option is deprecated and no longer has any affect.\nSee: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Keymaps]]\n opts.overwrite_mappings = nil\n end\n\n if opts.tags ~= nil then\n log.warn_once \"The 'tags' config option is deprecated and no longer has any affect.\"\n opts.tags = nil\n end\n\n if opts.templates and opts.templates.subdir then\n opts.templates.folder = opts.templates.subdir\n opts.templates.subdir = nil\n end\n\n if opts.image_name_func then\n if opts.attachments == nil then\n opts.attachments = {}\n end\n opts.attachments.img_name_func = opts.image_name_func\n opts.image_name_func = nil\n end\n\n if opts.statusline and opts.statusline.enabled then\n deprecate(\"statusline.{enabled,format} and vim.g.obsidian\", \"footer.{enabled,format}\", \"4.0\")\n end\n\n --------------------------\n -- Merge with defaults. --\n --------------------------\n\n ---@type obsidian.config.ClientOpts\n opts = tbl_override(defaults, opts)\n\n opts.backlinks = tbl_override(defaults.backlinks, opts.backlinks)\n opts.completion = tbl_override(defaults.completion, opts.completion)\n opts.picker = tbl_override(defaults.picker, opts.picker)\n opts.daily_notes = tbl_override(defaults.daily_notes, opts.daily_notes)\n opts.templates = tbl_override(defaults.templates, opts.templates)\n opts.ui = tbl_override(defaults.ui, opts.ui)\n opts.attachments = tbl_override(defaults.attachments, opts.attachments)\n opts.statusline = tbl_override(defaults.statusline, opts.statusline)\n opts.footer = tbl_override(defaults.footer, opts.footer)\n opts.open = tbl_override(defaults.open, opts.open)\n opts.checkbox = tbl_override(defaults.checkbox, opts.checkbox)\n opts.comment = tbl_override(defaults.comment, opts.comment)\n\n ---------------\n -- Validate. --\n ---------------\n\n if opts.legacy_commands then\n deprecate(\n \"legacy_commands\",\n [[move from commands like `ObsidianBacklinks` to `Obsidian backlinks`\nand set `opts.legacy_commands` to false to get rid of this warning.\nsee https://github.com/obsidian-nvim/obsidian.nvim/wiki/Commands for details.\n ]],\n \"4.0\"\n )\n end\n\n if opts.sort_by ~= nil and not vim.tbl_contains(vim.tbl_values(config.SortBy), opts.sort_by) then\n error(\"Invalid 'sort_by' option '\" .. opts.sort_by .. \"' in obsidian.nvim config.\")\n end\n\n if not util.islist(opts.workspaces) then\n error \"Invalid obsidian.nvim config, the 'config.workspaces' should be an array/list.\"\n elseif vim.tbl_isempty(opts.workspaces) then\n error \"At least one workspace is required!\\nPlease specify a workspace \"\n end\n\n for i, workspace in ipairs(opts.workspaces) do\n local path = type(workspace.path) == \"function\" and workspace.path() or workspace.path\n ---@cast path -function\n opts.workspaces[i].path = vim.fn.resolve(vim.fs.normalize(path))\n end\n\n -- Convert dir to workspace format.\n if opts.dir ~= nil then\n table.insert(opts.workspaces, 1, { path = opts.dir })\n end\n\n return opts\nend\n\nreturn config\n"], ["/obsidian.nvim/lua/obsidian/search.lua", "local Path = require \"obsidian.path\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\nlocal run_job_async = require(\"obsidian.async\").run_job_async\nlocal compat = require \"obsidian.compat\"\nlocal log = require \"obsidian.log\"\nlocal block_on = require(\"obsidian.async\").block_on\n\nlocal M = {}\n\nM._BASE_CMD = { \"rg\", \"--no-config\", \"--type=md\" }\nM._SEARCH_CMD = compat.flatten { M._BASE_CMD, \"--json\" }\nM._FIND_CMD = compat.flatten { M._BASE_CMD, \"--files\" }\n\n---@enum obsidian.search.RefTypes\nM.RefTypes = {\n WikiWithAlias = \"WikiWithAlias\",\n Wiki = \"Wiki\",\n Markdown = \"Markdown\",\n NakedUrl = \"NakedUrl\",\n FileUrl = \"FileUrl\",\n MailtoUrl = \"MailtoUrl\",\n Tag = \"Tag\",\n BlockID = \"BlockID\",\n Highlight = \"Highlight\",\n}\n\n---@enum obsidian.search.Patterns\nM.Patterns = {\n -- Tags\n TagCharsOptional = \"[A-Za-z0-9_/-]*\",\n TagCharsRequired = \"[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\", -- assumes tag is at least 2 chars\n Tag = \"#[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\",\n\n -- Miscellaneous\n Highlight = \"==[^=]+==\", -- ==text==\n\n -- References\n WikiWithAlias = \"%[%[[^][%|]+%|[^%]]+%]%]\", -- [[xxx|yyy]]\n Wiki = \"%[%[[^][%|]+%]%]\", -- [[xxx]]\n Markdown = \"%[[^][]+%]%([^%)]+%)\", -- [yyy](xxx)\n NakedUrl = \"https?://[a-zA-Z0-9._-@]+[a-zA-Z0-9._#/=&?:+%%-@]+[a-zA-Z0-9/]\", -- https://xyz.com\n FileUrl = \"file:/[/{2}]?.*\", -- file:///\n MailtoUrl = \"mailto:.*\", -- mailto:emailaddress\n BlockID = util.BLOCK_PATTERN .. \"$\", -- ^hello-world\n}\n\n---@type table\nM.PatternConfig = {\n [M.RefTypes.Tag] = { ignore_if_escape_prefix = true },\n}\n\n--- Find all matches of a pattern\n---\n---@param s string\n---@param pattern_names obsidian.search.RefTypes[]\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_matches = function(s, pattern_names)\n -- First find all inline code blocks so we can skip reference matches inside of those.\n local inline_code_blocks = {}\n for m_start, m_end in util.gfind(s, \"`[^`]*`\") do\n inline_code_blocks[#inline_code_blocks + 1] = { m_start, m_end }\n end\n\n local matches = {}\n for pattern_name in iter(pattern_names) do\n local pattern = M.Patterns[pattern_name]\n local pattern_cfg = M.PatternConfig[pattern_name]\n local search_start = 1\n while search_start < #s do\n local m_start, m_end = string.find(s, pattern, search_start)\n if m_start ~= nil and m_end ~= nil then\n -- Check if we're inside a code block.\n local inside_code_block = false\n for code_block_boundary in iter(inline_code_blocks) do\n if code_block_boundary[1] < m_start and m_end < code_block_boundary[2] then\n inside_code_block = true\n break\n end\n end\n\n if not inside_code_block then\n -- Check if this match overlaps with any others (e.g. a naked URL match would be contained in\n -- a markdown URL).\n local overlap = false\n for match in iter(matches) do\n if (match[1] <= m_start and m_start <= match[2]) or (match[1] <= m_end and m_end <= match[2]) then\n overlap = true\n break\n end\n end\n\n -- Check if we should skip to an escape sequence before the pattern.\n local skip_due_to_escape = false\n if\n pattern_cfg ~= nil\n and pattern_cfg.ignore_if_escape_prefix\n and string.sub(s, m_start - 1, m_start - 1) == [[\\]]\n then\n skip_due_to_escape = true\n end\n\n if not overlap and not skip_due_to_escape then\n matches[#matches + 1] = { m_start, m_end, pattern_name }\n end\n end\n\n search_start = m_end\n else\n break\n end\n end\n end\n\n -- Sort results by position.\n table.sort(matches, function(a, b)\n return a[1] < b[1]\n end)\n\n return matches\nend\n\n--- Find inline highlights\n---\n---@param s string\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_highlight = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Highlight })) do\n -- Remove highlights that begin/end with whitespace\n local match_start, match_end, _ = unpack(match)\n local text = string.sub(s, match_start + 2, match_end - 2)\n if vim.trim(text) == text then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n---@class obsidian.search.FindRefsOpts\n---\n---@field include_naked_urls boolean|?\n---@field include_tags boolean|?\n---@field include_file_urls boolean|?\n---@field include_block_ids boolean|?\n\n--- Find refs and URLs.\n---@param s string the string to search\n---@param opts obsidian.search.FindRefsOpts|?\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_refs = function(s, opts)\n opts = opts and opts or {}\n\n local pattern_names = { M.RefTypes.WikiWithAlias, M.RefTypes.Wiki, M.RefTypes.Markdown }\n if opts.include_naked_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.NakedUrl\n end\n if opts.include_tags then\n pattern_names[#pattern_names + 1] = M.RefTypes.Tag\n end\n if opts.include_file_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.FileUrl\n end\n if opts.include_block_ids then\n pattern_names[#pattern_names + 1] = M.RefTypes.BlockID\n end\n\n return M.find_matches(s, pattern_names)\nend\n\n--- Find all tags in a string.\n---@param s string the string to search\n---\n---@return {[1]: integer, [2]: integer, [3]: obsidian.search.RefTypes}[]\nM.find_tags = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Tag })) do\n local st, ed, m_type = unpack(match)\n local match_string = s:sub(st, ed)\n if m_type == M.RefTypes.Tag and not util.is_hex_color(match_string) then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n--- Replace references of the form '[[xxx|xxx]]', '[[xxx]]', or '[xxx](xxx)' with their title.\n---\n---@param s string\n---\n---@return string\nM.replace_refs = function(s)\n local out, _ = string.gsub(s, \"%[%[[^%|%]]+%|([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[%[([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[([^%]]+)%]%([^%)]+%)\", \"%1\")\n return out\nend\n\n--- Find all refs in a string and replace with their titles.\n---\n---@param s string\n--\n---@return string\n---@return table\n---@return string[]\nM.find_and_replace_refs = function(s)\n local pieces = {}\n local refs = {}\n local is_ref = {}\n local matches = M.find_refs(s)\n local last_end = 1\n for _, match in pairs(matches) do\n local m_start, m_end, _ = unpack(match)\n assert(type(m_start) == \"number\")\n if last_end < m_start then\n table.insert(pieces, string.sub(s, last_end, m_start - 1))\n table.insert(is_ref, false)\n end\n local ref_str = string.sub(s, m_start, m_end)\n table.insert(pieces, M.replace_refs(ref_str))\n table.insert(refs, ref_str)\n table.insert(is_ref, true)\n last_end = m_end + 1\n end\n\n local indices = {}\n local length = 0\n for i, piece in ipairs(pieces) do\n local i_end = length + string.len(piece)\n if is_ref[i] then\n table.insert(indices, { length + 1, i_end })\n end\n length = i_end\n end\n\n return table.concat(pieces, \"\"), indices, refs\nend\n\n--- Find all code block boundaries in a list of lines.\n---\n---@param lines string[]\n---\n---@return { [1]: integer, [2]: integer }[]\nM.find_code_blocks = function(lines)\n ---@type { [1]: integer, [2]: integer }[]\n local blocks = {}\n ---@type integer|?\n local start_idx\n for i, line in ipairs(lines) do\n if string.match(line, \"^%s*```.*```%s*$\") then\n table.insert(blocks, { i, i })\n start_idx = nil\n elseif string.match(line, \"^%s*```\") then\n if start_idx ~= nil then\n table.insert(blocks, { start_idx, i })\n start_idx = nil\n else\n start_idx = i\n end\n end\n end\n return blocks\nend\n\n---@class obsidian.search.SearchOpts\n---\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field fixed_strings boolean|?\n---@field ignore_case boolean|?\n---@field smart_case boolean|?\n---@field exclude string[]|? paths to exclude\n---@field max_count_per_file integer|?\n---@field escape_path boolean|?\n---@field include_non_markdown boolean|?\n\nlocal SearchOpts = {}\nM.SearchOpts = SearchOpts\n\nSearchOpts.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\nend\n\n---@param one obsidian.search.SearchOpts|table\n---@param other obsidian.search.SearchOpts|table\n---@return obsidian.search.SearchOpts\nSearchOpts.merge = function(one, other)\n return vim.tbl_extend(\"force\", SearchOpts.as_tbl(one), SearchOpts.as_tbl(other))\nend\n\n---@param opts obsidian.search.SearchOpts\n---@param path string\nSearchOpts.add_exclude = function(opts, path)\n if opts.exclude == nil then\n opts.exclude = {}\n end\n opts.exclude[#opts.exclude + 1] = path\nend\n\n---@param opts obsidian.search.SearchOpts\n---@return string[]\nSearchOpts.to_ripgrep_opts = function(opts)\n local ret = {}\n\n if opts.sort_by ~= nil then\n local sort = \"sortr\" -- default sort is reverse\n if opts.sort_reversed == false then\n sort = \"sort\"\n end\n ret[#ret + 1] = \"--\" .. sort .. \"=\" .. opts.sort_by\n end\n\n if opts.fixed_strings then\n ret[#ret + 1] = \"--fixed-strings\"\n end\n\n if opts.ignore_case then\n ret[#ret + 1] = \"--ignore-case\"\n end\n\n if opts.smart_case then\n ret[#ret + 1] = \"--smart-case\"\n end\n\n if opts.exclude ~= nil then\n assert(type(opts.exclude) == \"table\")\n for path in iter(opts.exclude) do\n ret[#ret + 1] = \"-g!\" .. path\n end\n end\n\n if opts.max_count_per_file ~= nil then\n ret[#ret + 1] = \"-m=\" .. opts.max_count_per_file\n end\n\n return ret\nend\n\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_search_cmd = function(dir, term, opts)\n opts = opts and opts or {}\n\n local search_terms\n if type(term) == \"string\" then\n search_terms = { \"-e\", term }\n else\n search_terms = {}\n for t in iter(term) do\n search_terms[#search_terms + 1] = \"-e\"\n search_terms[#search_terms + 1] = t\n end\n end\n\n local path = tostring(Path.new(dir):resolve { strict = true })\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(path))\n end\n\n return compat.flatten {\n M._SEARCH_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n search_terms,\n path,\n }\nend\n\n--- Build the 'rg' command for finding files.\n---\n---@param path string|?\n---@param term string|?\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_find_cmd = function(path, term, opts)\n opts = opts and opts or {}\n\n local additional_opts = {}\n\n if term ~= nil then\n if opts.include_non_markdown then\n term = \"*\" .. term .. \"*\"\n elseif not vim.endswith(term, \".md\") then\n term = \"*\" .. term .. \"*.md\"\n else\n term = \"*\" .. term\n end\n additional_opts[#additional_opts + 1] = \"-g\"\n additional_opts[#additional_opts + 1] = term\n end\n\n if opts.ignore_case then\n additional_opts[#additional_opts + 1] = \"--glob-case-insensitive\"\n end\n\n if path ~= nil and path ~= \".\" then\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(tostring(path)))\n end\n additional_opts[#additional_opts + 1] = path\n end\n\n return compat.flatten { M._FIND_CMD, SearchOpts.to_ripgrep_opts(opts), additional_opts }\nend\n\n--- Build the 'rg' grep command for pickers.\n---\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_grep_cmd = function(opts)\n opts = opts and opts or {}\n\n return compat.flatten {\n M._BASE_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n \"--column\",\n \"--line-number\",\n \"--no-heading\",\n \"--with-filename\",\n \"--color=never\",\n }\nend\n\n---@class MatchPath\n---\n---@field text string\n\n---@class MatchText\n---\n---@field text string\n\n---@class SubMatch\n---\n---@field match MatchText\n---@field start integer\n---@field end integer\n\n---@class MatchData\n---\n---@field path MatchPath\n---@field lines MatchText\n---@field line_number integer 0-indexed\n---@field absolute_offset integer\n---@field submatches SubMatch[]\n\n--- Search markdown files in a directory for a given term. Each match is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(match: MatchData)\n---@param on_exit fun(exit_code: integer)|?\nM.search_async = function(dir, term, opts, on_match, on_exit)\n local cmd = M.build_search_cmd(dir, term, opts)\n run_job_async(cmd, function(line)\n local data = vim.json.decode(line)\n if data[\"type\"] == \"match\" then\n local match_data = data.data\n on_match(match_data)\n end\n end, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\n--- Find markdown files in a directory matching a given term. Each matching path is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(path: string)\n---@param on_exit fun(exit_code: integer)|?\nM.find_async = function(dir, term, opts, on_match, on_exit)\n local norm_dir = Path.new(dir):resolve { strict = true }\n local cmd = M.build_find_cmd(tostring(norm_dir), term, opts)\n run_job_async(cmd, on_match, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\nlocal search_defualts = {\n sort = false,\n include_templates = false,\n ignore_case = false,\n}\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nlocal _prepare_search_opts = function(opts, additional_opts)\n opts = opts or search_defualts\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n M.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = M.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---@param callback fun(path: obsidian.Path)\n---@param exit_callback fun(paths: obsidian.Path[])\nlocal _search_async = function(term, search_opts, find_opts, callback, exit_callback)\n local found = {}\n local result = {}\n local cmds_done = 0\n\n local function dedup_send(path)\n local key = tostring(path:resolve { strict = true })\n if not found[key] then\n found[key] = true\n result[#result + 1] = path\n callback(path)\n end\n end\n\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text)\n dedup_send(path)\n end\n\n local function on_find_match(path_match)\n local path = Path.new(path_match)\n dedup_send(path)\n end\n\n local function on_exit()\n cmds_done = cmds_done + 1\n if cmds_done == 2 then\n exit_callback(result)\n end\n end\n\n M.search_async(\n Obsidian.dir,\n term,\n _prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n M.find_async(Obsidian.dir, term, _prepare_search_opts(find_opts, { ignore_case = true }), on_find_match, on_exit)\nend\n\n--- An async version of `find_notes()` that runs the callback with an array of all matching notes.\n---\n---@param term string The term to search for\n---@param callback fun(notes: obsidian.Note[])\n---@param opts { search: obsidian.SearchOpts|?, notes: obsidian.note.LoadOpts|? }|?\nM.find_notes_async = function(term, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n\n ---@type table\n local paths = {}\n local num_results = 0\n local err_count = 0\n local first_err\n local first_err_path\n local notes = {}\n local Note = require \"obsidian.note\"\n\n ---@param path obsidian.Path\n local function on_path(path)\n local ok, res = pcall(Note.from_file, path, opts.notes)\n\n if ok then\n num_results = num_results + 1\n paths[tostring(path)] = num_results\n notes[#notes + 1] = res\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n end\n end\n\n local on_exit = function()\n -- Then sort by original order.\n table.sort(notes, function(a, b)\n return paths[tostring(a.path)] < paths[tostring(b.path)]\n end)\n\n -- Check for errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n callback(notes)\n end\n\n _search_async(term, opts.search, nil, on_path, on_exit)\nend\n\nM.find_notes = function(term, opts)\n opts = opts or {}\n opts.timeout = opts.timeout or 1000\n return block_on(function(cb)\n return M.find_notes_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n---@param query string\n---@param callback fun(results: obsidian.Note[])\n---@param opts { notes: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note|?\nlocal _resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n local Note = require \"obsidian.note\"\n\n -- Autocompletion for command args will have this format.\n local note_path, count = string.gsub(query, \"^.*  \", \"\")\n if count > 0 then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n local full_path = Obsidian.dir / note_path\n callback { Note.from_file(full_path, opts.notes) }\n end\n\n -- Query might be a path.\n local fname = query\n if not vim.endswith(fname, \".md\") then\n fname = fname .. \".md\"\n end\n\n local paths_to_check = { Path.new(fname), Obsidian.dir / fname }\n\n if Obsidian.opts.notes_subdir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.notes_subdir / fname\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.daily_notes.folder / fname\n end\n\n if Obsidian.buf_dir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.buf_dir / fname\n end\n\n for _, path in pairs(paths_to_check) do\n if path:is_file() then\n return callback { Note.from_file(path, opts.notes) }\n end\n end\n\n M.find_notes_async(query, function(results)\n local query_lwr = string.lower(query)\n\n -- We'll gather both exact matches (of ID, filename, and aliases) and fuzzy matches.\n -- If we end up with any exact matches, we'll return those. Otherwise we fall back to fuzzy\n -- matches.\n ---@type obsidian.Note[]\n local exact_matches = {}\n ---@type obsidian.Note[]\n local fuzzy_matches = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local reference_ids = note:reference_ids { lowercase = true }\n\n -- Check for exact match.\n if vim.list_contains(reference_ids, query_lwr) then\n table.insert(exact_matches, note)\n else\n -- Fall back to fuzzy match.\n for ref_id in iter(reference_ids) do\n if util.string_contains(ref_id, query_lwr) then\n table.insert(fuzzy_matches, note)\n break\n end\n end\n end\n end\n\n if #exact_matches > 0 then\n return callback(exact_matches)\n else\n return callback(fuzzy_matches)\n end\n end, { search = { sort = true, ignore_case = true }, notes = opts.notes })\nend\n\n--- Resolve a note, opens a picker to choose a single note when there are multiple matches.\n---\n---@param query string\n---@param callback fun(obsidian.Note)\n---@param opts { notes: obsidian.note.LoadOpts|?, prompt_title: string|?, pick: boolean }|?\n---\n---@return obsidian.Note|?\nM.resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.pick = vim.F.if_nil(opts.pick, true)\n\n _resolve_note_async(query, function(notes)\n if opts.pick then\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", query)\n return\n elseif #notes == 1 then\n return callback(notes[1])\n end\n\n -- Fall back to picker.\n vim.schedule(function()\n -- Otherwise run the preferred picker to search for notes.\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple notes matching '%s', but no picker is configured\", query)\n return\n end\n\n picker:pick_note(notes, {\n prompt_title = opts.prompt_title,\n callback = callback,\n })\n end)\n else\n callback(notes)\n end\n end, { notes = opts.notes })\nend\n\n---@class obsidian.ResolveLinkResult\n---\n---@field location string\n---@field name string\n---@field link_type obsidian.search.RefTypes\n---@field path obsidian.Path|?\n---@field note obsidian.Note|?\n---@field url string|?\n---@field line integer|?\n---@field col integer|?\n---@field anchor obsidian.note.HeaderAnchor|?\n---@field block obsidian.note.Block|?\n\n--- Resolve a link.\n---\n---@param link string\n---@param callback fun(results: obsidian.ResolveLinkResult[])\nM.resolve_link_async = function(link, callback)\n local Note = require \"obsidian.note\"\n\n local location, name, link_type\n location, name, link_type = util.parse_link(link, { include_naked_urls = true, include_file_urls = true })\n\n if location == nil or name == nil or link_type == nil then\n return callback {}\n end\n\n ---@type obsidian.ResolveLinkResult\n local res = { location = location, name = name, link_type = link_type }\n\n if util.is_url(location) then\n res.url = location\n return callback { res }\n end\n\n -- The Obsidian app will follow URL-encoded links, so we should to.\n location = vim.uri_decode(location)\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n --- Finalize the `obsidian.ResolveLinkResult` for a note while resolving block or anchor link to line.\n ---\n ---@param note obsidian.Note\n ---@return obsidian.ResolveLinkResult\n local function finalize_result(note)\n ---@type integer|?, obsidian.note.Block|?, obsidian.note.HeaderAnchor|?\n local line, block_match, anchor_match\n if block_link ~= nil then\n block_match = note:resolve_block(block_link)\n if block_match then\n line = block_match.line\n end\n elseif anchor_link ~= nil then\n anchor_match = note:resolve_anchor_link(anchor_link)\n if anchor_match then\n line = anchor_match.line\n end\n end\n\n return vim.tbl_extend(\n \"force\",\n res,\n { path = note.path, note = note, line = line, block = block_match, anchor = anchor_match }\n )\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = anchor_link and true or false,\n collect_blocks = block_link and true or false,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n res.location = vim.api.nvim_buf_get_name(0)\n local note = Note.from_buffer(0, load_opts)\n return callback { finalize_result(note) }\n end\n\n res.location = location\n\n M.resolve_note_async(location, function(notes)\n if #notes == 0 then\n local path = Path.new(location)\n if path:exists() then\n res.path = path\n return callback { res }\n else\n return callback { res }\n end\n end\n\n local matches = {}\n for _, note in ipairs(notes) do\n table.insert(matches, finalize_result(note))\n end\n\n return callback(matches)\n end, { notes = load_opts, pick = false })\nend\n\n---@class obsidian.LinkMatch\n---@field link string\n---@field line integer\n---@field start integer 0-indexed\n---@field end integer 0-indexed\n\n-- Gather all unique links from the a note.\n--\n---@param note obsidian.Note\n---@param opts { on_match: fun(link: obsidian.LinkMatch) }\n---@param callback fun(links: obsidian.LinkMatch[])\nM.find_links = function(note, opts, callback)\n ---@type obsidian.LinkMatch[]\n local matches = {}\n ---@type table\n local found = {}\n local lines = io.lines(tostring(note.path))\n\n for lnum, line in util.enumerate(lines) do\n for ref_match in vim.iter(M.find_refs(line, { include_naked_urls = true, include_file_urls = true })) do\n local m_start, m_end = unpack(ref_match)\n local link = string.sub(line, m_start, m_end)\n if not found[link] then\n local match = {\n link = link,\n line = lnum,\n start = m_start - 1,\n [\"end\"] = m_end - 1,\n }\n matches[#matches + 1] = match\n found[link] = true\n if opts.on_match then\n opts.on_match(match)\n end\n end\n end\n end\n\n callback(matches)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/backlinks.lua", "local util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal RefTypes = require(\"obsidian.search\").RefTypes\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param note obsidian.Note\n---@param opts { anchor: string|?, block: string|? }|?\nlocal function collect_backlinks(client, picker, note, opts)\n opts = opts or {}\n\n client:find_backlinks_async(note, function(backlinks)\n if vim.tbl_isempty(backlinks) then\n if opts.anchor then\n log.info(\"No backlinks found for anchor '%s' in note '%s'\", opts.anchor, note.id)\n elseif opts.block then\n log.info(\"No backlinks found for block '%s' in note '%s'\", opts.block, note.id)\n else\n log.info(\"No backlinks found for note '%s'\", note.id)\n end\n return\n end\n\n local entries = {}\n for _, matches in ipairs(backlinks) do\n for _, match in ipairs(matches.matches) do\n entries[#entries + 1] = {\n value = { path = matches.path, line = match.line },\n filename = tostring(matches.path),\n lnum = match.line,\n }\n end\n end\n\n ---@type string\n local prompt_title\n if opts.anchor then\n prompt_title = string.format(\"Backlinks to '%s%s'\", note.id, opts.anchor)\n elseif opts.block then\n prompt_title = string.format(\"Backlinks to '%s#%s'\", note.id, util.standardize_block(opts.block))\n else\n prompt_title = string.format(\"Backlinks to '%s'\", note.id)\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = prompt_title,\n callback = function(value)\n api.open_buffer(value.path, { line = value.line })\n end,\n })\n end)\n end, { search = { sort = true }, anchor = opts.anchor, block = opts.block })\nend\n\n---@param client obsidian.Client\nreturn function(client)\n local picker = assert(Obsidian.picker)\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local cur_link, link_type = api.cursor_link()\n\n if\n cur_link ~= nil\n and link_type ~= RefTypes.NakedUrl\n and link_type ~= RefTypes.FileUrl\n and link_type ~= RefTypes.BlockID\n then\n local location = util.parse_link(cur_link, { include_block_ids = true })\n assert(location, \"cursor on a link but failed to parse, please report to repo\")\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n location = vim.api.nvim_buf_get_name(0)\n end\n\n local opts = { anchor = anchor_link, block = block_link }\n\n search.resolve_note_async(location, function(...)\n ---@type obsidian.Note[]\n local notes = { ... }\n\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", location)\n return\n elseif #notes == 1 then\n return collect_backlinks(client, picker, notes[1], opts)\n else\n return vim.schedule(function()\n picker:pick_note(notes, {\n prompt_title = \"Select note\",\n callback = function(note)\n collect_backlinks(client, picker, note, opts)\n end,\n })\n end)\n end\n end)\n else\n ---@type { anchor: string|?, block: string|? }\n local opts = {}\n ---@type obsidian.note.LoadOpts\n local load_opts = {}\n\n if cur_link and link_type == RefTypes.BlockID then\n opts.block = util.parse_link(cur_link, { include_block_ids = true })\n else\n load_opts.collect_anchor_links = true\n end\n\n local note = api.current_note(0, load_opts)\n\n -- Check if cursor is on a header, if so and header parsing is enabled, use that anchor.\n if Obsidian.opts.backlinks.parse_headers then\n local header_match = util.parse_header(vim.api.nvim_get_current_line())\n if header_match then\n opts.anchor = header_match.anchor\n end\n end\n\n if note == nil then\n log.err \"Current buffer does not appear to be a note inside the vault\"\n else\n collect_backlinks(client, picker, note, opts)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/new_from_template.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type string?\n local title = table.concat(data.fargs, \" \", 1, #data.fargs - 1)\n local template = data.fargs[#data.fargs]\n\n if title ~= nil and template ~= nil then\n local note = Note.create { title = title, template = template, should_write = true }\n note:open { sync = true }\n return\n end\n\n picker:find_templates {\n callback = function(template_name)\n if title == nil or title == \"\" then\n -- Must use pcall in case of KeyboardInterrupt\n -- We cannot place `title` where `safe_title` is because it would be redeclaring it\n local success, safe_title = pcall(util.input, \"Enter title or path (optional): \", { completion = \"file\" })\n title = safe_title\n if not success or not safe_title then\n log.warn \"Aborted\"\n return\n elseif safe_title == \"\" then\n title = nil\n end\n end\n\n if template_name == nil or template_name == \"\" then\n log.warn \"Aborted\"\n return\n end\n\n ---@type obsidian.Note\n local note = Note.create { title = title, template = template_name, should_write = true }\n note:open { sync = false }\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/tags.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param tags string[]\nlocal function gather_tag_picker_list(client, picker, tags)\n client:find_tags_async(tags, function(tag_locations)\n -- Format results into picker entries, filtering out results that aren't exact matches or sub-tags.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, tag_loc in ipairs(tag_locations) do\n for _, tag in ipairs(tags) do\n if tag_loc.tag:lower() == tag:lower() or vim.startswith(tag_loc.tag:lower(), tag:lower() .. \"/\") then\n local display = string.format(\"%s [%s] %s\", tag_loc.note:display_name(), tag_loc.line, tag_loc.text)\n entries[#entries + 1] = {\n value = { path = tag_loc.path, line = tag_loc.line, col = tag_loc.tag_start },\n display = display,\n ordinal = display,\n filename = tostring(tag_loc.path),\n lnum = tag_loc.line,\n col = tag_loc.tag_start,\n }\n break\n end\n end\n end\n\n if vim.tbl_isempty(entries) then\n if #tags == 1 then\n log.warn \"Tag not found\"\n else\n log.warn \"Tags not found\"\n end\n return\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = \"#\" .. table.concat(tags, \", #\"),\n callback = function(value)\n api.open_buffer(value.path, { line = value.line, col = value.col })\n end,\n })\n end)\n end, { search = { sort = true } })\nend\n\n---@param client obsidian.Client\n---@param data CommandArgs\nreturn function(client, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local tags = data.fargs or {}\n\n if vim.tbl_isempty(tags) then\n local tag = api.cursor_tag()\n if tag then\n tags = { tag }\n end\n end\n\n if not vim.tbl_isempty(tags) then\n return gather_tag_picker_list(client, picker, util.tbl_unique(tags))\n else\n client:list_tags_async(nil, function(all_tags)\n vim.schedule(function()\n -- Open picker with tags.\n picker:pick_tag(all_tags, {\n callback = function(...)\n gather_tag_picker_list(client, picker, { ... })\n end,\n allow_multiple = true,\n })\n end)\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/init-legacy.lua", "local util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal command_lookups = {\n ObsidianCheck = \"obsidian.commands.check\",\n ObsidianToggleCheckbox = \"obsidian.commands.toggle_checkbox\",\n ObsidianToday = \"obsidian.commands.today\",\n ObsidianYesterday = \"obsidian.commands.yesterday\",\n ObsidianTomorrow = \"obsidian.commands.tomorrow\",\n ObsidianDailies = \"obsidian.commands.dailies\",\n ObsidianNew = \"obsidian.commands.new\",\n ObsidianOpen = \"obsidian.commands.open\",\n ObsidianBacklinks = \"obsidian.commands.backlinks\",\n ObsidianSearch = \"obsidian.commands.search\",\n ObsidianTags = \"obsidian.commands.tags\",\n ObsidianTemplate = \"obsidian.commands.template\",\n ObsidianNewFromTemplate = \"obsidian.commands.new_from_template\",\n ObsidianQuickSwitch = \"obsidian.commands.quick_switch\",\n ObsidianLinkNew = \"obsidian.commands.link_new\",\n ObsidianLink = \"obsidian.commands.link\",\n ObsidianLinks = \"obsidian.commands.links\",\n ObsidianFollowLink = \"obsidian.commands.follow_link\",\n ObsidianWorkspace = \"obsidian.commands.workspace\",\n ObsidianRename = \"obsidian.commands.rename\",\n ObsidianPasteImg = \"obsidian.commands.paste_img\",\n ObsidianExtractNote = \"obsidian.commands.extract_note\",\n ObsidianTOC = \"obsidian.commands.toc\",\n}\n\nlocal M = setmetatable({\n commands = {},\n}, {\n __index = function(t, k)\n local require_path = command_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@class obsidian.CommandConfigLegacy\n---@field opts table\n---@field complete function|?\n---@field func function|? (obsidian.Client, table) -> nil\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfigLegacy\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n return M[name](client, data)\n end\n end\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n for command_name, command_config in pairs(M.commands) do\n local func = function(data)\n command_config.func(client, data)\n end\n\n if command_config.complete ~= nil then\n command_config.opts.complete = function(arg_lead, cmd_line, cursor_pos)\n return command_config.complete(client, arg_lead, cmd_line, cursor_pos)\n end\n end\n\n vim.api.nvim_create_user_command(command_name, func, command_config.opts)\n end\nend\n\n---@param client obsidian.Client\n---@return string[]\nM.complete_args_search = function(client, _, cmd_line, _)\n local query\n local cmd_arg, _ = util.lstrip_whitespace(string.gsub(cmd_line, \"^.*Obsidian[A-Za-z0-9]+\", \"\"))\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\nM.register(\"ObsidianCheck\", { opts = { nargs = 0, desc = \"Check for issues in your vault\" } })\n\nM.register(\"ObsidianToday\", { opts = { nargs = \"?\", desc = \"Open today's daily note\" } })\n\nM.register(\"ObsidianYesterday\", { opts = { nargs = 0, desc = \"Open the daily note for the previous working day\" } })\n\nM.register(\"ObsidianTomorrow\", { opts = { nargs = 0, desc = \"Open the daily note for the next working day\" } })\n\nM.register(\"ObsidianDailies\", { opts = { nargs = \"*\", desc = \"Open a picker with daily notes\" } })\n\nM.register(\"ObsidianNew\", { opts = { nargs = \"?\", desc = \"Create a new note\" } })\n\nM.register(\n \"ObsidianOpen\",\n { opts = { nargs = \"?\", desc = \"Open in the Obsidian app\" }, complete = M.complete_args_search }\n)\n\nM.register(\"ObsidianBacklinks\", { opts = { nargs = 0, desc = \"Collect backlinks\" } })\n\nM.register(\"ObsidianTags\", { opts = { nargs = \"*\", range = true, desc = \"Find tags\" } })\n\nM.register(\"ObsidianSearch\", { opts = { nargs = \"?\", desc = \"Search vault\" } })\n\nM.register(\"ObsidianTemplate\", { opts = { nargs = \"?\", desc = \"Insert a template\" } })\n\nM.register(\"ObsidianNewFromTemplate\", { opts = { nargs = \"*\", desc = \"Create a new note from a template\" } })\n\nM.register(\"ObsidianQuickSwitch\", { opts = { nargs = \"?\", desc = \"Switch notes\" } })\n\nM.register(\"ObsidianLinkNew\", { opts = { nargs = \"?\", range = true, desc = \"Link selected text to a new note\" } })\n\nM.register(\"ObsidianLink\", {\n opts = { nargs = \"?\", range = true, desc = \"Link selected text to an existing note\" },\n complete = M.complete_args_search,\n})\n\nM.register(\"ObsidianLinks\", { opts = { nargs = 0, desc = \"Collect all links within the current buffer\" } })\n\nM.register(\"ObsidianFollowLink\", { opts = { nargs = \"?\", desc = \"Follow reference or link under cursor\" } })\n\nM.register(\"ObsidianToggleCheckbox\", { opts = { nargs = 0, desc = \"Toggle checkbox\", range = true } })\n\nM.register(\"ObsidianWorkspace\", { opts = { nargs = \"?\", desc = \"Check or switch workspace\" } })\n\nM.register(\"ObsidianRename\", { opts = { nargs = \"?\", desc = \"Rename note and update all references to it\" } })\n\nM.register(\"ObsidianPasteImg\", { opts = { nargs = \"?\", desc = \"Paste an image from the clipboard\" } })\n\nM.register(\n \"ObsidianExtractNote\",\n { opts = { nargs = \"?\", range = true, desc = \"Extract selected text to a new note and link to it\" } }\n)\n\nM.register(\"ObsidianTOC\", { opts = { nargs = 0, desc = \"Load the table of contents into a picker\" } })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/_mini.lua", "local mini_pick = require \"mini.pick\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\n---@param entry string\n---@return string\nlocal function clean_path(entry)\n local path_end = assert(string.find(entry, \":\", 1, true))\n return string.sub(entry, 1, path_end - 1)\nend\n\n---@class obsidian.pickers.MiniPicker : obsidian.Picker\nlocal MiniPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"MiniPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nMiniPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local path = mini_pick.builtin.cli({\n command = self:_build_find_cmd(),\n }, {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n })\n\n if path and opts.callback then\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nMiniPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local pick_opts = {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n }\n\n ---@type string|?\n local result\n if opts.query and string.len(opts.query) > 0 then\n result = mini_pick.builtin.grep({ pattern = opts.query }, pick_opts)\n else\n result = mini_pick.builtin.grep_live({}, pick_opts)\n end\n\n if result and opts.callback then\n local path = clean_path(result)\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nMiniPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n entries[#entries + 1] = {\n value = value.value,\n text = self:_make_display(value),\n path = value.filename,\n lnum = value.lnum,\n col = value.col,\n }\n end\n end\n\n local entry = mini_pick.start {\n source = {\n name = opts.prompt_title,\n items = entries,\n choose = function() end,\n },\n }\n\n if entry and opts.callback then\n if type(entry) == \"string\" then\n opts.callback(entry)\n else\n opts.callback(entry.value)\n end\n end\nend\n\nreturn MiniPicker\n"], ["/obsidian.nvim/lua/obsidian/workspace.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\nlocal config = require \"obsidian.config\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.workspace.WorkspaceSpec\n---\n---@field path string|(fun(): string)\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts?\n\n---@class obsidian.workspace.WorkspaceOpts\n---\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts|?\n\n--- Each workspace represents a working directory (usually an Obsidian vault) along with\n--- a set of configuration options specific to the workspace.\n---\n--- Workspaces are a little more general than Obsidian vaults as you can have a workspace\n--- outside of a vault or as a subdirectory of a vault.\n---\n---@toc_entry obsidian.Workspace\n---\n---@class obsidian.Workspace : obsidian.ABC\n---\n---@field name string An arbitrary name for the workspace.\n---@field path obsidian.Path The normalized path to the workspace.\n---@field root obsidian.Path The normalized path to the vault root of the workspace. This usually matches 'path'.\n---@field overrides table|obsidian.config.ClientOpts|?\n---@field locked boolean|?\nlocal Workspace = abc.new_class {\n __tostring = function(self)\n return string.format(\"Workspace(name='%s', path='%s', root='%s')\", self.name, self.path, self.root)\n end,\n __eq = function(a, b)\n local a_fields = a:as_tbl()\n a_fields.locked = nil\n local b_fields = b:as_tbl()\n b_fields.locked = nil\n return vim.deep_equal(a_fields, b_fields)\n end,\n}\n\n--- Find the vault root from a given directory.\n---\n--- This will traverse the directory tree upwards until a '.obsidian/' folder is found to\n--- indicate the root of a vault, otherwise the given directory is used as-is.\n---\n---@param base_dir string|obsidian.Path\n---\n---@return obsidian.Path|?\nlocal function find_vault_root(base_dir)\n local vault_indicator_folder = \".obsidian\"\n base_dir = Path.new(base_dir)\n local dirs = Path.new(base_dir):parents()\n table.insert(dirs, 1, base_dir)\n\n for _, dir in ipairs(dirs) do\n local maybe_vault = dir / vault_indicator_folder\n if maybe_vault:is_dir() then\n return dir\n end\n end\n\n return nil\nend\n\n--- Create a new 'Workspace' object. This assumes the workspace already exists on the filesystem.\n---\n---@param path string|obsidian.Path Workspace path.\n---@param opts obsidian.workspace.WorkspaceOpts|?\n---\n---@return obsidian.Workspace\nWorkspace.new = function(path, opts)\n opts = opts and opts or {}\n\n local self = Workspace.init()\n self.path = Path.new(path):resolve { strict = true }\n self.name = assert(opts.name or self.path.name)\n self.overrides = opts.overrides\n\n if opts.strict then\n self.root = self.path\n else\n local vault_root = find_vault_root(self.path)\n if vault_root then\n self.root = vault_root\n else\n self.root = self.path\n end\n end\n\n return self\nend\n\n--- Initialize a new 'Workspace' object from a workspace spec.\n---\n---@param spec obsidian.workspace.WorkspaceSpec\n---\n---@return obsidian.Workspace\nWorkspace.new_from_spec = function(spec)\n ---@type string|obsidian.Path\n local path\n if type(spec.path) == \"function\" then\n path = spec.path()\n else\n ---@diagnostic disable-next-line: cast-local-type\n path = spec.path\n end\n\n ---@diagnostic disable-next-line: param-type-mismatch\n return Workspace.new(path, {\n name = spec.name,\n strict = spec.strict,\n overrides = spec.overrides,\n })\nend\n\n--- Lock the workspace.\nWorkspace.lock = function(self)\n self.locked = true\nend\n\n--- Unlock the workspace.\nWorkspace._unlock = function(self)\n self.locked = false\nend\n\n--- Get the workspace corresponding to the directory (or a parent of), if there\n--- is one.\n---\n---@param cur_dir string|obsidian.Path\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_dir = function(cur_dir, workspaces)\n local ok\n ok, cur_dir = pcall(function()\n return Path.new(cur_dir):resolve { strict = true }\n end)\n\n if not ok then\n return\n end\n\n for _, spec in ipairs(workspaces) do\n local w = Workspace.new_from_spec(spec)\n if w.path == cur_dir or w.path:is_parent_of(cur_dir) then\n return w\n end\n end\nend\n\n--- Get the workspace corresponding to the current working directory (or a parent of), if there\n--- is one.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_cwd = function(workspaces)\n local cwd = assert(vim.fn.getcwd())\n return Workspace.get_workspace_for_dir(cwd, workspaces)\nend\n\n--- Returns the default workspace.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|nil\nWorkspace.get_default_workspace = function(workspaces)\n if not vim.tbl_isempty(workspaces) then\n return Workspace.new_from_spec(workspaces[1])\n else\n return nil\n end\nend\n\n--- Resolves current workspace from the client config.\n---\n---@param opts obsidian.config.ClientOpts\n---\n---@return obsidian.Workspace|?\nWorkspace.get_from_opts = function(opts)\n local current_workspace = Workspace.get_workspace_for_cwd(opts.workspaces)\n\n if not current_workspace then\n current_workspace = Workspace.get_default_workspace(opts.workspaces)\n end\n\n return current_workspace\nend\n\n--- Get the normalize opts for a given workspace.\n---\n---@param workspace obsidian.Workspace|?\n---\n---@return obsidian.config.ClientOpts\nWorkspace.normalize_opts = function(workspace)\n if workspace then\n return config.normalize(workspace.overrides and workspace.overrides or {}, Obsidian._opts)\n else\n return Obsidian.opts\n end\nend\n\n---@param workspace obsidian.Workspace\n---@param opts { lock: boolean|? }|?\nWorkspace.set = function(workspace, opts)\n opts = opts and opts or {}\n\n local dir = workspace.root\n local options = Workspace.normalize_opts(workspace) -- TODO: test\n\n Obsidian.workspace = workspace\n Obsidian.dir = dir\n Obsidian.opts = options\n\n -- Ensure directories exist.\n dir:mkdir { parents = true, exists_ok = true }\n\n if options.notes_subdir ~= nil then\n local notes_subdir = dir / Obsidian.opts.notes_subdir\n notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n local daily_notes_subdir = Obsidian.dir / Obsidian.opts.daily_notes.folder\n daily_notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n -- Setup UI add-ons.\n local has_no_renderer = not (api.get_plugin_info \"render-markdown.nvim\" or api.get_plugin_info \"markview.nvim\")\n if has_no_renderer and Obsidian.opts.ui.enable then\n require(\"obsidian.ui\").setup(Obsidian.workspace, Obsidian.opts.ui)\n end\n\n if opts.lock then\n Obsidian.workspace:lock()\n end\n\n Obsidian.picker = require(\"obsidian.pickers\").get(Obsidian.opts.picker.name)\n\n util.fire_callback(\"post_set_workspace\", Obsidian.opts.callbacks.post_set_workspace, workspace)\n\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = \"ObsidianWorkpspaceSet\",\n data = { workspace = workspace },\n })\nend\n\n---@param workspace obsidian.Workspace|string The workspace object or the name of an existing workspace.\n---@param opts { lock: boolean|? }|?\nWorkspace.switch = function(workspace, opts)\n opts = opts and opts or {}\n\n if workspace == Obsidian.workspace.name then\n log.info(\"Already in workspace '%s' @ '%s'\", workspace, Obsidian.workspace.path)\n return\n end\n\n for _, ws in ipairs(Obsidian.opts.workspaces) do\n if ws.name == workspace then\n return Workspace.set(Workspace.new_from_spec(ws), opts)\n end\n end\n\n error(string.format(\"Workspace '%s' not found\", workspace))\nend\n\nreturn Workspace\n"], ["/obsidian.nvim/lua/obsidian/commands/template.lua", "local templates = require \"obsidian.templates\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local templates_dir = api.templates_dir()\n if not templates_dir then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n -- We need to get this upfront before the picker hijacks the current window.\n local insert_location = api.get_active_window_cursor_location()\n\n local function insert_template(name)\n templates.insert_template {\n type = \"insert_template\",\n template_name = name,\n template_opts = Obsidian.opts.templates,\n templates_dir = templates_dir,\n location = insert_location,\n }\n end\n\n if string.len(data.args) > 0 then\n local template_name = vim.trim(data.args)\n insert_template(template_name)\n return\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_templates {\n callback = function(path)\n insert_template(path)\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/init.lua", "local iter = vim.iter\nlocal log = require \"obsidian.log\"\nlocal legacycommands = require \"obsidian.commands.init-legacy\"\nlocal search = require \"obsidian.search\"\n\nlocal M = { commands = {} }\n\nlocal function in_note()\n return vim.bo.filetype == \"markdown\"\nend\n\n---@param commands obsidian.CommandConfig[]\n---@param is_visual boolean\n---@param is_note boolean\n---@return string[]\nlocal function get_commands_by_context(commands, is_visual, is_note)\n local choices = vim.tbl_values(commands)\n return vim\n .iter(choices)\n :filter(function(config)\n if is_visual then\n return config.range ~= nil\n else\n return config.range == nil\n end\n end)\n :filter(function(config)\n if is_note then\n return true\n else\n return not config.note_action\n end\n end)\n :map(function(config)\n return config.name\n end)\n :totable()\nend\n\nlocal function show_menu(data)\n local is_visual, is_note = data.range ~= 0, in_note()\n local choices = get_commands_by_context(M.commands, is_visual, is_note)\n\n vim.ui.select(choices, { prompt = \"Obsidian Commands\" }, function(item)\n if item then\n return vim.cmd.Obsidian(item)\n else\n vim.notify(\"Aborted\", 3)\n end\n end)\nend\n\n---@class obsidian.CommandConfig\n---@field complete function|string|?\n---@field nargs string|integer|?\n---@field range boolean|?\n---@field func function|? (obsidian.Client, table) -> nil\n---@field name string?\n---@field note_action boolean?\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfig\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n local mod = require(\"obsidian.commands.\" .. name)\n return mod(client, data)\n end\n end\n config.name = name\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n vim.api.nvim_create_user_command(\"Obsidian\", function(data)\n if #data.fargs == 0 then\n show_menu(data)\n return\n end\n M.handle_command(client, data)\n end, {\n nargs = \"*\",\n complete = function(_, cmdline, _)\n return M.get_completions(client, cmdline)\n end,\n range = 2,\n })\nend\n\nM.install_legacy = legacycommands.install\n\n---@param client obsidian.Client\nM.handle_command = function(client, data)\n local cmd = data.fargs[1]\n table.remove(data.fargs, 1)\n data.args = table.concat(data.fargs, \" \")\n local nargs = #data.fargs\n\n local cmdconfig = M.commands[cmd]\n if cmdconfig == nil then\n log.err(\"Command '\" .. cmd .. \"' not found\")\n return\n end\n\n local exp_nargs = cmdconfig.nargs\n local range_allowed = cmdconfig.range\n\n if exp_nargs == \"?\" then\n if nargs > 1 then\n log.err(\"Command '\" .. cmd .. \"' expects 0 or 1 arguments, but \" .. nargs .. \" were provided\")\n return\n end\n elseif exp_nargs == \"+\" then\n if nargs == 0 then\n log.err(\"Command '\" .. cmd .. \"' expects at least one argument, but none were provided\")\n return\n end\n elseif exp_nargs ~= \"*\" and exp_nargs ~= nargs then\n log.err(\"Command '\" .. cmd .. \"' expects \" .. exp_nargs .. \" arguments, but \" .. nargs .. \" were provided\")\n return\n end\n\n if not range_allowed and data.range > 0 then\n log.error(\"Command '\" .. cmd .. \"' does not accept a range\")\n return\n end\n\n cmdconfig.func(client, data)\nend\n\n---@param client obsidian.Client\n---@param cmdline string\nM.get_completions = function(client, cmdline)\n local obspat = \"^['<,'>]*Obsidian[!]?\"\n local splitcmd = vim.split(cmdline, \" \", { plain = true, trimempty = true })\n local obsidiancmd = splitcmd[2]\n if cmdline:match(obspat .. \"%s$\") then\n local is_visual = vim.startswith(cmdline, \"'<,'>\")\n return get_commands_by_context(M.commands, is_visual, in_note())\n end\n if cmdline:match(obspat .. \"%s%S+$\") then\n return vim.tbl_filter(function(s)\n return s:sub(1, #obsidiancmd) == obsidiancmd\n end, vim.tbl_keys(M.commands))\n end\n local cmdconfig = M.commands[obsidiancmd]\n if cmdconfig == nil then\n return\n end\n if cmdline:match(obspat .. \"%s%S*%s%S*$\") then\n local cmd_arg = table.concat(vim.list_slice(splitcmd, 3), \" \")\n local complete_type = type(cmdconfig.complete)\n if complete_type == \"function\" then\n return cmdconfig.complete(cmd_arg)\n end\n if complete_type == \"string\" then\n return vim.fn.getcompletion(cmd_arg, cmdconfig.complete)\n end\n end\nend\n\n--TODO: Note completion is currently broken (see: https://github.com/epwalsh/obsidian.nvim/issues/753)\n---@return string[]\nM.note_complete = function(cmd_arg)\n local query\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\n------------------------\n---- general action ----\n------------------------\n\nM.register(\"check\", { nargs = 0 })\n\nM.register(\"today\", { nargs = \"?\" })\n\nM.register(\"yesterday\", { nargs = 0 })\n\nM.register(\"tomorrow\", { nargs = 0 })\n\nM.register(\"dailies\", { nargs = \"*\" })\n\nM.register(\"new\", { nargs = \"?\" })\n\nM.register(\"open\", { nargs = \"?\", complete = M.note_complete })\n\nM.register(\"tags\", { nargs = \"*\" })\n\nM.register(\"search\", { nargs = \"?\" })\n\nM.register(\"new_from_template\", { nargs = \"*\" })\n\nM.register(\"quick_switch\", { nargs = \"?\" })\n\nM.register(\"workspace\", { nargs = \"?\" })\n\n---------------------\n---- note action ----\n---------------------\n\nM.register(\"backlinks\", { nargs = 0, note_action = true })\n\nM.register(\"template\", { nargs = \"?\", note_action = true })\n\nM.register(\"link_new\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"link\", { nargs = \"?\", range = true, complete = M.note_complete, note_action = true })\n\nM.register(\"links\", { nargs = 0, note_action = true })\n\nM.register(\"follow_link\", { nargs = \"?\", note_action = true })\n\nM.register(\"toggle_checkbox\", { nargs = 0, range = true, note_action = true })\n\nM.register(\"rename\", { nargs = \"?\", note_action = true })\n\nM.register(\"paste_img\", { nargs = \"?\", note_action = true })\n\nM.register(\"extract_note\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"toc\", { nargs = 0, note_action = true })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/init.lua", "local log = require \"obsidian.log\"\n\nlocal module_lookups = {\n abc = \"obsidian.abc\",\n api = \"obsidian.api\",\n async = \"obsidian.async\",\n Client = \"obsidian.client\",\n commands = \"obsidian.commands\",\n completion = \"obsidian.completion\",\n config = \"obsidian.config\",\n log = \"obsidian.log\",\n img_paste = \"obsidian.img_paste\",\n Note = \"obsidian.note\",\n Path = \"obsidian.path\",\n pickers = \"obsidian.pickers\",\n search = \"obsidian.search\",\n templates = \"obsidian.templates\",\n ui = \"obsidian.ui\",\n util = \"obsidian.util\",\n VERSION = \"obsidian.version\",\n Workspace = \"obsidian.workspace\",\n yaml = \"obsidian.yaml\",\n}\n\nlocal obsidian = setmetatable({}, {\n __index = function(t, k)\n local require_path = module_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@type obsidian.Client|?\nobsidian._client = nil\n\n---Get the current obsidian client.\n---@return obsidian.Client\nobsidian.get_client = function()\n if obsidian._client == nil then\n error \"Obsidian client has not been set! Did you forget to call 'setup()'?\"\n else\n return obsidian._client\n end\nend\n\nobsidian.register_command = require(\"obsidian.commands\").register\n\n--- Setup a new Obsidian client. This should only be called once from an Nvim session.\n---\n---@param opts obsidian.config.ClientOpts | table\n---\n---@return obsidian.Client\nobsidian.setup = function(opts)\n opts = obsidian.config.normalize(opts)\n\n ---@class obsidian.state\n ---@field picker obsidian.Picker The picker instance to use.\n ---@field workspace obsidian.Workspace The current workspace.\n ---@field dir obsidian.Path The root of the vault for the current workspace.\n ---@field buf_dir obsidian.Path|? The parent directory of the current buffer.\n ---@field opts obsidian.config.ClientOpts current options\n ---@field _opts obsidian.config.ClientOpts default options\n _G.Obsidian = {} -- init a state table\n\n local client = obsidian.Client.new(opts)\n\n Obsidian._opts = opts\n\n obsidian.Workspace.set(assert(obsidian.Workspace.get_from_opts(opts)), {})\n\n log.set_level(Obsidian.opts.log_level)\n\n -- Install commands.\n -- These will be available across all buffers, not just note buffers in the vault.\n obsidian.commands.install(client)\n\n if opts.legacy_commands then\n obsidian.commands.install_legacy(client)\n end\n\n if opts.statusline.enabled then\n require(\"obsidian.statusline\").start(client)\n end\n\n if opts.footer.enabled then\n require(\"obsidian.footer\").start(client)\n end\n\n -- Register completion sources, providers\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").register_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").register_providers(opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_setup\", { clear = true })\n\n -- wrapper for creating autocmd events\n ---@param pattern string\n ---@param buf integer\n local function exec_autocmds(pattern, buf)\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = pattern,\n data = {\n note = require(\"obsidian.note\").from_buffer(buf),\n },\n })\n end\n\n -- Complete setup and update workspace (if needed) when entering a markdown buffer.\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Set the current directory of the buffer.\n local buf_dir = vim.fs.dirname(ev.match)\n if buf_dir then\n Obsidian.buf_dir = obsidian.Path.new(buf_dir)\n end\n\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n if opts.comment.enabled then\n vim.o.commentstring = \"%%%s%%\"\n end\n\n -- Switch to the workspace and complete the workspace setup.\n if not Obsidian.workspace.locked and workspace ~= Obsidian.workspace then\n log.debug(\"Switching to workspace '%s' @ '%s'\", workspace.name, workspace.path)\n obsidian.Workspace.set(workspace)\n require(\"obsidian.ui\").update(ev.buf)\n end\n\n -- Register keymap.\n vim.keymap.set(\n \"n\",\n \"\",\n obsidian.api.smart_action,\n { expr = true, buffer = true, desc = \"Obsidian Smart Action\" }\n )\n\n vim.keymap.set(\"n\", \"]o\", function()\n obsidian.api.nav_link \"next\"\n end, { buffer = true, desc = \"Obsidian Next Link\" })\n\n vim.keymap.set(\"n\", \"[o\", function()\n obsidian.api.nav_link \"prev\"\n end, { buffer = true, desc = \"Obsidian Previous Link\" })\n\n -- Inject completion sources, providers to their plugin configurations\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").inject_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").inject_sources(opts)\n end\n\n -- Run enter-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"enter_note\", Obsidian.opts.callbacks.enter_note, client, note)\n\n exec_autocmds(\"ObsidianNoteEnter\", ev.buf)\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufLeave\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(vim.fs.dirname(ev.match), Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Run leave-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"leave_note\", Obsidian.opts.callbacks.leave_note, client, note)\n\n exec_autocmds(\"ObsidianNoteLeave\", ev.buf)\n end,\n })\n\n -- Add/update frontmatter for notes before writing.\n vim.api.nvim_create_autocmd({ \"BufWritePre\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Initialize note.\n local bufnr = ev.buf\n local note = obsidian.Note.from_buffer(bufnr)\n\n -- Run pre-write-note callback.\n obsidian.util.fire_callback(\"pre_write_note\", Obsidian.opts.callbacks.pre_write_note, client, note)\n\n exec_autocmds(\"ObsidianNoteWritePre\", ev.buf)\n\n -- Update buffer with new frontmatter.\n if note:update_frontmatter(bufnr) then\n log.info \"Updated frontmatter\"\n end\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufWritePost\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n exec_autocmds(\"ObsidianNoteWritePost\", ev.buf)\n end,\n })\n\n -- Set global client.\n obsidian._client = client\n\n obsidian.util.fire_callback(\"post_setup\", Obsidian.opts.callbacks.post_setup, client)\n\n return client\nend\n\nreturn obsidian\n"], ["/obsidian.nvim/lua/obsidian/path.lua", "local abc = require \"obsidian.abc\"\n\nlocal function coerce(v)\n if v == vim.NIL then\n return nil\n else\n return v\n end\nend\n\n---@param path table\n---@param k string\n---@param factory fun(obsidian.Path): any\nlocal function cached_get(path, k, factory)\n local cache_key = \"__\" .. k\n local v = rawget(path, cache_key)\n if v == nil then\n v = factory(path)\n if v == nil then\n v = vim.NIL\n end\n path[cache_key] = v\n end\n return coerce(v)\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_name(path)\n local name = vim.fs.basename(path.filename)\n if not name or string.len(name) == 0 then\n return\n else\n return name\n end\nend\n\n---@param path obsidian.Path\n---@return string[]\n---@private\nlocal function get_suffixes(path)\n ---@type string[]\n local suffixes = {}\n local name = path.name\n while name and string.len(name) > 0 do\n local s, e, suffix = string.find(name, \"(%.[^%.]+)$\")\n if s and e and suffix then\n name = string.sub(name, 1, s - 1)\n table.insert(suffixes, suffix)\n else\n break\n end\n end\n\n -- reverse the list.\n ---@type string[]\n local out = {}\n for i = #suffixes, 1, -1 do\n table.insert(out, suffixes[i])\n end\n return out\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_suffix(path)\n local suffixes = path.suffixes\n if #suffixes > 0 then\n return suffixes[#suffixes]\n else\n return nil\n end\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_stem(path)\n local name, suffix = path.name, path.suffix\n if not name then\n return\n elseif not suffix then\n return name\n else\n return string.sub(name, 1, string.len(name) - string.len(suffix))\n end\nend\n\n--- A `Path` class that provides a subset of the functionality of the Python `pathlib` library while\n--- staying true to its API. It improves on a number of bugs in `plenary.path`.\n---\n---@toc_entry obsidian.Path\n---\n---@class obsidian.Path : obsidian.ABC\n---\n---@field filename string The underlying filename as a string.\n---@field name string|? The final path component, if any.\n---@field suffix string|? The final extension of the path, if any.\n---@field suffixes string[] A list of all of the path's extensions.\n---@field stem string|? The final path component, without its suffix.\nlocal Path = abc.new_class()\n\nPath.mt = {\n __tostring = function(self)\n return self.filename\n end,\n __eq = function(a, b)\n return a.filename == b.filename\n end,\n __div = function(self, other)\n return self:joinpath(other)\n end,\n __index = function(self, k)\n local raw = rawget(Path, k)\n if raw then\n return raw\n end\n\n local factory\n if k == \"name\" then\n factory = get_name\n elseif k == \"suffix\" then\n factory = get_suffix\n elseif k == \"suffixes\" then\n factory = get_suffixes\n elseif k == \"stem\" then\n factory = get_stem\n end\n\n if factory then\n return cached_get(self, k, factory)\n end\n end,\n}\n\n--- Check if an object is an `obsidian.Path` object.\n---\n---@param path any\n---\n---@return boolean\nPath.is_path_obj = function(path)\n if getmetatable(path) == Path.mt then\n return true\n else\n return false\n end\nend\n\n-------------------------------------------------------------------------------\n--- Constructors.\n-------------------------------------------------------------------------------\n\n--- Create a new path from a string.\n---\n---@param ... string|obsidian.Path\n---\n---@return obsidian.Path\nPath.new = function(...)\n local self = Path.init()\n\n local args = { ... }\n local arg\n if #args == 1 then\n arg = tostring(args[1])\n elseif #args == 2 and args[1] == Path then\n arg = tostring(args[2])\n else\n error \"expected one argument\"\n end\n\n if Path.is_path_obj(arg) then\n ---@cast arg obsidian.Path\n return arg\n end\n\n self.filename = vim.fs.normalize(tostring(arg))\n\n return self\nend\n\n--- Get a temporary path with a unique name.\n---\n---@param opts { suffix: string|? }|?\n---\n---@return obsidian.Path\nPath.temp = function(opts)\n opts = opts or {}\n local tmpname = vim.fn.tempname()\n if opts.suffix then\n tmpname = tmpname .. opts.suffix\n end\n return Path.new(tmpname)\nend\n\n--- Get a path corresponding to the current working directory as given by `vim.uv.cwd()`.\n---\n---@return obsidian.Path\nPath.cwd = function()\n return assert(Path.new(vim.uv.cwd()))\nend\n\n--- Get a path corresponding to a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buffer = function(bufnr)\n return Path.new(vim.api.nvim_buf_get_name(bufnr or 0))\nend\n\n--- Get a path corresponding to the parent of a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buf_dir = function(bufnr)\n return assert(Path.buffer(bufnr):parent())\nend\n\n-------------------------------------------------------------------------------\n--- Pure path methods.\n-------------------------------------------------------------------------------\n\n--- Return a new path with the suffix changed.\n---\n---@param suffix string\n---@param should_append boolean|? should the suffix append a suffix instead of replacing one which may be there?\n---\n---@return obsidian.Path\nPath.with_suffix = function(self, suffix, should_append)\n if not vim.startswith(suffix, \".\") and string.len(suffix) > 1 then\n error(string.format(\"invalid suffix '%s'\", suffix))\n elseif self.stem == nil then\n error(string.format(\"path '%s' has no stem\", self.filename))\n end\n\n local new_name = ((should_append == true) and self.name or self.stem) .. suffix\n\n ---@type obsidian.Path|?\n local parent = nil\n if self.name ~= self.filename then\n parent = self:parent()\n end\n\n if parent then\n return parent / new_name\n else\n return Path.new(new_name)\n end\nend\n\n--- Returns true if the path is already in absolute form.\n---\n---@return boolean\nPath.is_absolute = function(self)\n local api = require \"obsidian.api\"\n if\n vim.startswith(self.filename, \"/\")\n or (\n (api.get_os() == api.OSType.Windows or api.get_os() == api.OSType.Wsl)\n and string.match(self.filename, \"^[%a]:/.*$\")\n )\n then\n return true\n else\n return false\n end\nend\n\n---@param ... obsidian.Path|string\n---@return obsidian.Path\nPath.joinpath = function(self, ...)\n local args = vim.iter({ ... }):map(tostring):totable()\n return Path.new(vim.fs.joinpath(self.filename, unpack(args)))\nend\n\n--- Try to resolve a version of the path relative to the other.\n--- An error is raised when it's not possible.\n---\n---@param other obsidian.Path|string\n---\n---@return obsidian.Path\nPath.relative_to = function(self, other)\n other = Path.new(other)\n\n local other_fname = other.filename\n if not vim.endswith(other_fname, \"/\") then\n other_fname = other_fname .. \"/\"\n end\n\n if vim.startswith(self.filename, other_fname) then\n return Path.new(string.sub(self.filename, string.len(other_fname) + 1))\n end\n\n -- Edge cases when the paths are relative or under-specified, see tests.\n if not self:is_absolute() and not vim.startswith(self.filename, \"./\") and vim.startswith(other_fname, \"./\") then\n if other_fname == \"./\" then\n return self\n end\n\n local self_rel_to_cwd = Path.new \"./\" / self\n if vim.startswith(self_rel_to_cwd.filename, other_fname) then\n return Path.new(string.sub(self_rel_to_cwd.filename, string.len(other_fname) + 1))\n end\n end\n\n error(string.format(\"'%s' is not in the subpath of '%s'\", self.filename, other.filename))\nend\n\n--- The logical parent of the path.\n---\n---@return obsidian.Path|?\nPath.parent = function(self)\n local parent = vim.fs.dirname(self.filename)\n if parent ~= nil then\n return Path.new(parent)\n else\n return nil\n end\nend\n\n--- Get a list of the parent directories.\n---\n---@return obsidian.Path[]\nPath.parents = function(self)\n return vim.iter(vim.fs.parents(self.filename)):map(Path.new):totable()\nend\n\n--- Check if the path is a parent of other. This is a pure path method, so it only checks by\n--- comparing strings. Therefore in practice you probably want to `:resolve()` each path before\n--- using this.\n---\n---@param other obsidian.Path|string\n---\n---@return boolean\nPath.is_parent_of = function(self, other)\n other = Path.new(other)\n for _, parent in ipairs(other:parents()) do\n if parent == self then\n return true\n end\n end\n return false\nend\n\n---@return string?\n---@private\nPath.abspath = function(self)\n local path = vim.loop.fs_realpath(vim.fn.resolve(self.filename))\n return path\nend\n\n-------------------------------------------------------------------------------\n--- Concrete path methods.\n-------------------------------------------------------------------------------\n\n--- Make the path absolute, resolving any symlinks.\n--- If `strict` is true and the path doesn't exist, an error is raised.\n---\n---@param opts { strict: boolean }|?\n---\n---@return obsidian.Path\nPath.resolve = function(self, opts)\n opts = opts or {}\n\n local realpath = self:abspath()\n if realpath then\n return Path.new(realpath)\n elseif opts.strict then\n error(\"FileNotFoundError: \" .. self.filename)\n end\n\n -- File doesn't exist, but some parents might. Traverse up until we find a parent that\n -- does exist, and then put the path back together from there.\n local parents = self:parents()\n for _, parent in ipairs(parents) do\n local parent_realpath = parent:abspath()\n if parent_realpath then\n return Path.new(parent_realpath) / self:relative_to(parent)\n end\n end\n\n return self\nend\n\n--- Get OS stat results.\n---\n---@return table|?\nPath.stat = function(self)\n local realpath = self:abspath()\n if realpath then\n local stat, _ = vim.uv.fs_stat(realpath)\n return stat\n end\nend\n\n--- Check if the path points to an existing file or directory.\n---\n---@return boolean\nPath.exists = function(self)\n local stat = self:stat()\n return stat ~= nil\nend\n\n--- Check if the path points to an existing file.\n---\n---@return boolean\nPath.is_file = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"file\"\n end\nend\n\n--- Check if the path points to an existing directory.\n---\n---@return boolean\nPath.is_dir = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"directory\"\n end\nend\n\n--- Create a new directory at the given path.\n---\n---@param opts { mode: integer|?, parents: boolean|?, exist_ok: boolean|? }|?\nPath.mkdir = function(self, opts)\n opts = opts or {}\n\n local mode = opts.mode or 448 -- 0700 -> decimal\n ---@diagnostic disable-next-line: undefined-field\n if opts.exists_ok then -- for compat with the plenary.path API.\n opts.exist_ok = true\n end\n\n if self:is_dir() then\n if not opts.exist_ok then\n error(\"FileExistsError: \" .. self.filename)\n else\n return\n end\n end\n\n if vim.uv.fs_mkdir(self.filename, mode) then\n return\n end\n\n if not opts.parents then\n error(\"FileNotFoundError: \" .. tostring(self:parent()))\n end\n\n local parents = self:parents()\n for i = #parents, 1, -1 do\n if not parents[i]:is_dir() then\n parents[i]:mkdir { exist_ok = true, mode = mode }\n end\n end\n\n self:mkdir { mode = mode }\nend\n\n--- Remove the corresponding directory. This directory must be empty.\nPath.rmdir = function(self)\n local resolved = self:resolve { strict = false }\n\n if not resolved:is_dir() then\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_rmdir(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n-- TODO: not implemented and not used, after we get to 0.11 we can simply use vim.fs.rm\n--- Recursively remove an entire directory and its contents.\nPath.rmtree = function(self) end\n\n--- Create a file at this given path.\n---\n---@param opts { mode: integer|?, exist_ok: boolean|? }|?\nPath.touch = function(self, opts)\n opts = opts or {}\n local mode = opts.mode or 420\n\n local resolved = self:resolve { strict = false }\n if resolved:exists() then\n local new_time = os.time()\n vim.uv.fs_utime(resolved.filename, new_time, new_time)\n return\n end\n\n local parent = resolved:parent()\n if parent and not parent:exists() then\n error(\"FileNotFoundError: \" .. parent.filename)\n end\n\n local fd, err_name, err_msg = vim.uv.fs_open(resolved.filename, \"w\", mode)\n if not fd then\n error(err_name .. \": \" .. err_msg)\n end\n vim.uv.fs_close(fd)\nend\n\n--- Rename this file or directory to the given target.\n---\n---@param target obsidian.Path|string\n---\n---@return obsidian.Path\nPath.rename = function(self, target)\n local resolved = self:resolve { strict = false }\n target = Path.new(target)\n\n local ok, err_name, err_msg = vim.uv.fs_rename(resolved.filename, target.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\n\n return target\nend\n\n--- Remove the file.\n---\n---@param opts { missing_ok: boolean|? }|?\nPath.unlink = function(self, opts)\n opts = opts or {}\n\n local resolved = self:resolve { strict = false }\n\n if not resolved:exists() then\n if not opts.missing_ok then\n error(\"FileNotFoundError: \" .. resolved.filename)\n end\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_unlink(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n--- Make a path relative to the vault root, if possible, return a string\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return string?\nPath.vault_relative_path = function(self, opts)\n opts = opts or {}\n\n -- NOTE: we don't try to resolve the `path` here because that would make the path absolute,\n -- which may result in the wrong relative path if the current working directory is not within\n -- the vault.\n\n local ok, relative_path = pcall(function()\n return self:relative_to(Obsidian.workspace.root)\n end)\n\n if ok and relative_path then\n return tostring(relative_path)\n elseif not self:is_absolute() then\n return tostring(self)\n elseif opts.strict then\n error(string.format(\"failed to resolve '%s' relative to vault root '%s'\", self, Obsidian.workspace.root))\n end\nend\n\nreturn Path\n"], ["/obsidian.nvim/lua/obsidian/note.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal yaml = require \"obsidian.yaml\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\nlocal enumerate = util.enumerate\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal config = require \"obsidian.config\"\n\nlocal SKIP_UPDATING_FRONTMATTER = { \"README.md\", \"CONTRIBUTING.md\", \"CHANGELOG.md\" }\n\nlocal DEFAULT_MAX_LINES = 500\n\nlocal CODE_BLOCK_PATTERN = \"^%s*```[%w_-]*$\"\n\n--- @class obsidian.note.NoteCreationOpts\n--- @field notes_subdir string\n--- @field note_id_func fun()\n--- @field new_notes_location string\n\n--- @class obsidian.note.NoteOpts\n--- @field title string|? The note's title\n--- @field id string|? An ID to assign the note. If not specified one will be generated.\n--- @field dir string|obsidian.Path|? An optional directory to place the note in. Relative paths will be interpreted\n--- relative to the workspace / vault root. If the directory doesn't exist it will\n--- be created, regardless of the value of the `should_write` option.\n--- @field aliases string[]|? Aliases for the note\n--- @field tags string[]|? Tags for this note\n--- @field should_write boolean|? Don't write the note to disk\n--- @field template string|? The name of the template\n\n---@class obsidian.note.NoteSaveOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- Whether to insert/update frontmatter. Defaults to `true`.\n---@field insert_frontmatter? boolean\n--- Override the frontmatter. Defaults to the result of `self:frontmatter()`.\n---@field frontmatter? table\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload the updated file.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.NoteWriteOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- The name of a template to use if the note file doesn't already exist.\n---@field template? string\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload each buffer's content.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.HeaderAnchor\n---\n---@field anchor string\n---@field header string\n---@field level integer\n---@field line integer\n---@field parent obsidian.note.HeaderAnchor|?\n\n---@class obsidian.note.Block\n---\n---@field id string\n---@field line integer\n---@field block string\n\n--- A class that represents a note within a vault.\n---\n---@toc_entry obsidian.Note\n---\n---@class obsidian.Note : obsidian.ABC\n---\n---@field id string\n---@field aliases string[]\n---@field title string|?\n---@field tags string[]\n---@field path obsidian.Path|?\n---@field metadata table|?\n---@field has_frontmatter boolean|?\n---@field frontmatter_end_line integer|?\n---@field contents string[]|?\n---@field anchor_links table|?\n---@field blocks table?\n---@field alt_alias string|?\n---@field bufnr integer|?\nlocal Note = abc.new_class {\n __tostring = function(self)\n return string.format(\"Note('%s')\", self.id)\n end,\n}\n\nNote.is_note_obj = function(note)\n if getmetatable(note) == Note.mt then\n return true\n else\n return false\n end\nend\n\n--- Generate a unique ID for a new note. This respects the user's `note_id_func` if configured,\n--- otherwise falls back to generated a Zettelkasten style ID.\n---\n--- @param title? string\n--- @param path? obsidian.Path\n--- @param alt_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n---@return string\nlocal function generate_id(title, path, alt_id_func)\n if alt_id_func ~= nil then\n local new_id = alt_id_func(title, path)\n if new_id == nil or string.len(new_id) == 0 then\n error(string.format(\"Your 'note_id_func' must return a non-empty string, got '%s'!\", tostring(new_id)))\n end\n -- Remote '.md' suffix if it's there (we add that later).\n new_id = new_id:gsub(\"%.md$\", \"\", 1)\n return new_id\n else\n return require(\"obsidian.builtin\").zettel_id()\n end\nend\n\n--- Generate the file path for a new note given its ID, parent directory, and title.\n--- This respects the user's `note_path_func` if configured, otherwise essentially falls back to\n--- `note_opts.dir / (note_opts.id .. \".md\")`.\n---\n--- @param title string|? The title for the note\n--- @param id string The note ID\n--- @param dir obsidian.Path The note path\n---@return obsidian.Path\n---@private\nNote._generate_path = function(title, id, dir)\n ---@type obsidian.Path\n local path\n\n if Obsidian.opts.note_path_func ~= nil then\n path = Path.new(Obsidian.opts.note_path_func { id = id, dir = dir, title = title })\n -- Ensure path is either absolute or inside `opts.dir`.\n -- NOTE: `opts.dir` should always be absolute, but for extra safety we handle the case where\n -- it's not.\n if not path:is_absolute() and (dir:is_absolute() or not dir:is_parent_of(path)) then\n path = dir / path\n end\n else\n path = dir / tostring(id)\n end\n\n -- Ensure there is only one \".md\" suffix. This might arise if `note_path_func`\n -- supplies an unusual implementation returning something like /bad/note/id.md.md.md\n while path.filename:match \"%.md$\" do\n path.filename = path.filename:gsub(\"%.md$\", \"\")\n end\n\n return path:with_suffix(\".md\", true)\nend\n\n--- Selects the strategy to use when resolving the note title, id, and path\n--- @param opts obsidian.note.NoteOpts The note creation options\n--- @return obsidian.note.NoteCreationOpts The strategy to use for creating the note\n--- @private\nNote._get_creation_opts = function(opts)\n --- @type obsidian.note.NoteCreationOpts\n local default = {\n notes_subdir = Obsidian.opts.notes_subdir,\n note_id_func = Obsidian.opts.note_id_func,\n new_notes_location = Obsidian.opts.new_notes_location,\n }\n\n local resolve_template = require(\"obsidian.templates\").resolve_template\n local success, template_path = pcall(resolve_template, opts.template, api.templates_dir())\n\n if not success then\n return default\n end\n\n local stem = template_path.stem:lower()\n\n -- Check if the configuration has a custom key for this template\n for key, cfg in pairs(Obsidian.opts.templates.customizations) do\n if key:lower() == stem then\n return {\n notes_subdir = cfg.notes_subdir,\n note_id_func = cfg.note_id_func,\n new_notes_location = config.NewNotesLocation.notes_subdir,\n }\n end\n end\n return default\nend\n\n--- Resolves the title, ID, and path for a new note.\n---\n---@param title string|?\n---@param id string|?\n---@param dir string|obsidian.Path|? The directory for the note\n---@param strategy obsidian.note.NoteCreationOpts Strategy for resolving note path and title\n---@return string|?,string,obsidian.Path\n---@private\nNote._resolve_title_id_path = function(title, id, dir, strategy)\n if title then\n title = vim.trim(title)\n if title == \"\" then\n title = nil\n end\n end\n\n if id then\n id = vim.trim(id)\n if id == \"\" then\n id = nil\n end\n end\n\n ---@param s string\n ---@param strict_paths_only boolean\n ---@return string|?, boolean, string|?\n local parse_as_path = function(s, strict_paths_only)\n local is_path = false\n ---@type string|?\n local parent\n\n if s:match \"%.md\" then\n -- Remove suffix.\n s = s:sub(1, s:len() - 3)\n is_path = true\n end\n\n -- Pull out any parent dirs from title.\n local parts = vim.split(s, \"/\")\n if #parts > 1 then\n s = parts[#parts]\n if not strict_paths_only then\n is_path = true\n end\n parent = table.concat(parts, \"/\", 1, #parts - 1)\n end\n\n if s == \"\" then\n return nil, is_path, parent\n else\n return s, is_path, parent\n end\n end\n\n local parent, _, title_is_path\n if id then\n id, _, parent = parse_as_path(id, false)\n elseif title then\n title, title_is_path, parent = parse_as_path(title, true)\n if title_is_path then\n id = title\n end\n end\n\n -- Resolve base directory.\n ---@type obsidian.Path\n local base_dir\n if parent then\n base_dir = Obsidian.dir / parent\n elseif dir ~= nil then\n base_dir = Path.new(dir)\n if not base_dir:is_absolute() then\n base_dir = Obsidian.dir / base_dir\n else\n base_dir = base_dir:resolve()\n end\n else\n local bufpath = Path.buffer(0):resolve()\n if\n strategy.new_notes_location == config.NewNotesLocation.current_dir\n -- note is actually in the workspace.\n and Obsidian.dir:is_parent_of(bufpath)\n -- note is not in dailies folder\n and (\n Obsidian.opts.daily_notes.folder == nil\n or not (Obsidian.dir / Obsidian.opts.daily_notes.folder):is_parent_of(bufpath)\n )\n then\n base_dir = Obsidian.buf_dir or assert(bufpath:parent())\n else\n base_dir = Obsidian.dir\n if strategy.notes_subdir then\n base_dir = base_dir / strategy.notes_subdir\n end\n end\n end\n\n -- Make sure `base_dir` is absolute at this point.\n assert(base_dir:is_absolute(), (\"failed to resolve note directory '%s'\"):format(base_dir))\n\n -- Generate new ID if needed.\n if not id then\n id = generate_id(title, base_dir, strategy.note_id_func)\n end\n\n dir = base_dir\n\n -- Generate path.\n local path = Note._generate_path(title, id, dir)\n\n return title, id, path\nend\n\n--- Creates a new note\n---\n--- @param opts obsidian.note.NoteOpts Options\n--- @return obsidian.Note\nNote.create = function(opts)\n local new_title, new_id, path =\n Note._resolve_title_id_path(opts.title, opts.id, opts.dir, Note._get_creation_opts(opts))\n opts = vim.tbl_extend(\"keep\", opts, { aliases = {}, tags = {} })\n\n -- Add the title as an alias.\n --- @type string[]\n local aliases = opts.aliases\n if new_title ~= nil and new_title:len() > 0 and not vim.list_contains(aliases, new_title) then\n aliases[#aliases + 1] = new_title\n end\n\n local note = Note.new(new_id, aliases, opts.tags, path)\n\n if new_title then\n note.title = new_title\n end\n\n -- Ensure the parent directory exists.\n local parent = path:parent()\n assert(parent)\n parent:mkdir { parents = true, exist_ok = true }\n\n -- Write to disk.\n if opts.should_write then\n note:write { template = opts.template }\n end\n\n return note\nend\n\n--- Instantiates a new Note object\n---\n--- Keep in mind that you have to call `note:save(...)` to create/update the note on disk.\n---\n--- @param id string|number\n--- @param aliases string[]\n--- @param tags string[]\n--- @param path string|obsidian.Path|?\n--- @return obsidian.Note\nNote.new = function(id, aliases, tags, path)\n local self = Note.init()\n self.id = id\n self.aliases = aliases and aliases or {}\n self.tags = tags and tags or {}\n self.path = path and Path.new(path) or nil\n self.metadata = nil\n self.has_frontmatter = nil\n self.frontmatter_end_line = nil\n return self\nend\n\n--- Get markdown display info about the note.\n---\n---@param opts { label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|?\n---\n---@return string\nNote.display_info = function(self, opts)\n opts = opts and opts or {}\n\n ---@type string[]\n local info = {}\n\n if opts.label ~= nil and string.len(opts.label) > 0 then\n info[#info + 1] = (\"%s\"):format(opts.label)\n info[#info + 1] = \"--------\"\n end\n\n if self.path ~= nil then\n info[#info + 1] = (\"**path:** `%s`\"):format(self.path)\n end\n\n info[#info + 1] = (\"**id:** `%s`\"):format(self.id)\n\n if #self.aliases > 0 then\n info[#info + 1] = (\"**aliases:** '%s'\"):format(table.concat(self.aliases, \"', '\"))\n end\n\n if #self.tags > 0 then\n info[#info + 1] = (\"**tags:** `#%s`\"):format(table.concat(self.tags, \"`, `#\"))\n end\n\n if opts.anchor or opts.block then\n info[#info + 1] = \"--------\"\n\n if opts.anchor then\n info[#info + 1] = (\"...\\n%s %s\\n...\"):format(string.rep(\"#\", opts.anchor.level), opts.anchor.header)\n elseif opts.block then\n info[#info + 1] = (\"...\\n%s\\n...\"):format(opts.block.block)\n end\n end\n\n return table.concat(info, \"\\n\")\nend\n\n--- Check if the note exists on the file system.\n---\n---@return boolean\nNote.exists = function(self)\n ---@diagnostic disable-next-line: return-type-mismatch\n return self.path ~= nil and self.path:is_file()\nend\n\n--- Get the filename associated with the note.\n---\n---@return string|?\nNote.fname = function(self)\n if self.path == nil then\n return nil\n else\n return vim.fs.basename(tostring(self.path))\n end\nend\n\n--- Get a list of all of the different string that can identify this note via references,\n--- including the ID, aliases, and filename.\n---@param opts { lowercase: boolean|? }|?\n---@return string[]\nNote.reference_ids = function(self, opts)\n opts = opts or {}\n ---@type string[]\n local ref_ids = { tostring(self.id), self:display_name() }\n if self.path then\n table.insert(ref_ids, self.path.name)\n table.insert(ref_ids, self.path.stem)\n end\n\n vim.list_extend(ref_ids, self.aliases)\n\n if opts.lowercase then\n ref_ids = vim.tbl_map(string.lower, ref_ids)\n end\n\n return util.tbl_unique(ref_ids)\nend\n\n--- Check if a note has a given alias.\n---\n---@param alias string\n---\n---@return boolean\nNote.has_alias = function(self, alias)\n return vim.list_contains(self.aliases, alias)\nend\n\n--- Check if a note has a given tag.\n---\n---@param tag string\n---\n---@return boolean\nNote.has_tag = function(self, tag)\n return vim.list_contains(self.tags, tag)\nend\n\n--- Add an alias to the note.\n---\n---@param alias string\n---\n---@return boolean added True if the alias was added, false if it was already present.\nNote.add_alias = function(self, alias)\n if not self:has_alias(alias) then\n table.insert(self.aliases, alias)\n return true\n else\n return false\n end\nend\n\n--- Add a tag to the note.\n---\n---@param tag string\n---\n---@return boolean added True if the tag was added, false if it was already present.\nNote.add_tag = function(self, tag)\n if not self:has_tag(tag) then\n table.insert(self.tags, tag)\n return true\n else\n return false\n end\nend\n\n--- Add or update a field in the frontmatter.\n---\n---@param key string\n---@param value any\nNote.add_field = function(self, key, value)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Updating field '%s' this way is not allowed. Please update the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n self.metadata = {}\n end\n\n self.metadata[key] = value\nend\n\n--- Get a field in the frontmatter.\n---\n---@param key string\n---\n---@return any result\nNote.get_field = function(self, key)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Getting field '%s' this way is not allowed. Please use the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n return nil\n end\n\n return self.metadata[key]\nend\n\n---@class obsidian.note.LoadOpts\n---@field max_lines integer|?\n---@field load_contents boolean|?\n---@field collect_anchor_links boolean|?\n---@field collect_blocks boolean|?\n\n--- Initialize a note from a file.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file = function(path, opts)\n if path == nil then\n error \"note path cannot be nil\"\n end\n path = tostring(Path.new(path):resolve { strict = true })\n return Note.from_lines(io.lines(path), path, opts)\nend\n\n--- An async version of `.from_file()`, i.e. it needs to be called in an async context.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file_async = function(path, opts)\n path = Path.new(path):resolve { strict = true }\n local f = io.open(tostring(path), \"r\")\n assert(f)\n local ok, res = pcall(Note.from_lines, f:lines \"*l\", path, opts)\n f:close()\n if ok then\n return res\n else\n error(res)\n end\nend\n\n--- Like `.from_file_async()` but also returns the contents of the file as a list of lines.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note,string[]\nNote.from_file_with_contents_async = function(path, opts)\n opts = vim.tbl_extend(\"force\", opts or {}, { load_contents = true })\n local note = Note.from_file_async(path, opts)\n assert(note.contents ~= nil)\n return note, note.contents\nend\n\n--- Initialize a note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_buffer = function(bufnr, opts)\n bufnr = bufnr or vim.api.nvim_get_current_buf()\n local path = vim.api.nvim_buf_get_name(bufnr)\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)\n local note = Note.from_lines(iter(lines), path, opts)\n note.bufnr = bufnr\n return note\nend\n\n--- Get the display name for note.\n---\n---@return string\nNote.display_name = function(self)\n if self.title then\n return self.title\n elseif #self.aliases > 0 then\n return self.aliases[#self.aliases]\n end\n return tostring(self.id)\nend\n\n--- Initialize a note from an iterator of lines.\n---\n---@param lines fun(): string|? | Iter\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_lines = function(lines, path, opts)\n opts = opts or {}\n path = Path.new(path):resolve()\n\n local max_lines = opts.max_lines or DEFAULT_MAX_LINES\n\n local id = nil\n local title = nil\n local aliases = {}\n local tags = {}\n\n ---@type string[]|?\n local contents\n if opts.load_contents then\n contents = {}\n end\n\n ---@type table|?\n local anchor_links\n ---@type obsidian.note.HeaderAnchor[]|?\n local anchor_stack\n if opts.collect_anchor_links then\n anchor_links = {}\n anchor_stack = {}\n end\n\n ---@type table|?\n local blocks\n if opts.collect_blocks then\n blocks = {}\n end\n\n ---@param anchor_data obsidian.note.HeaderAnchor\n ---@return obsidian.note.HeaderAnchor|?\n local function get_parent_anchor(anchor_data)\n assert(anchor_links)\n assert(anchor_stack)\n for i = #anchor_stack, 1, -1 do\n local parent = anchor_stack[i]\n if parent.level < anchor_data.level then\n return parent\n end\n end\n end\n\n ---@param anchor string\n ---@param data obsidian.note.HeaderAnchor|?\n local function format_nested_anchor(anchor, data)\n local out = anchor\n if not data then\n return out\n end\n\n local parent = data.parent\n while parent ~= nil do\n out = parent.anchor .. out\n data = get_parent_anchor(parent)\n if data then\n parent = data.parent\n else\n parent = nil\n end\n end\n\n return out\n end\n\n -- Iterate over lines in the file, collecting frontmatter and parsing the title.\n local frontmatter_lines = {}\n local has_frontmatter, in_frontmatter, at_boundary = false, false, false -- luacheck: ignore (false positive)\n local frontmatter_end_line = nil\n local in_code_block = false\n for line_idx, line in enumerate(lines) do\n line = util.rstrip_whitespace(line)\n\n if line_idx == 1 and Note._is_frontmatter_boundary(line) then\n has_frontmatter = true\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n frontmatter_end_line = line_idx\n else\n at_boundary = false\n end\n\n if string.match(line, CODE_BLOCK_PATTERN) then\n in_code_block = not in_code_block\n end\n\n if in_frontmatter and not at_boundary then\n table.insert(frontmatter_lines, line)\n elseif not in_frontmatter and not at_boundary and not in_code_block then\n -- Check for title/header and collect anchor link.\n local header_match = util.parse_header(line)\n if header_match then\n if not title and header_match.level == 1 then\n title = header_match.header\n end\n\n -- Collect anchor link.\n if opts.collect_anchor_links then\n assert(anchor_links)\n assert(anchor_stack)\n -- We collect up to two anchor for each header. One standalone, e.g. '#header1', and\n -- one with the parents, e.g. '#header1#header2'.\n -- This is our standalone one:\n ---@type obsidian.note.HeaderAnchor\n local data = {\n anchor = header_match.anchor,\n line = line_idx,\n header = header_match.header,\n level = header_match.level,\n }\n data.parent = get_parent_anchor(data)\n\n anchor_links[header_match.anchor] = data\n table.insert(anchor_stack, data)\n\n -- Now if there's a parent we collect the nested version. All of the data will be the same\n -- except the anchor key.\n if data.parent ~= nil then\n local nested_anchor = format_nested_anchor(header_match.anchor, data)\n anchor_links[nested_anchor] = vim.tbl_extend(\"force\", data, { anchor = nested_anchor })\n end\n end\n end\n\n -- Check for block.\n if opts.collect_blocks then\n local block = util.parse_block(line)\n if block then\n blocks[block] = { id = block, line = line_idx, block = line }\n end\n end\n end\n\n -- Collect contents.\n if contents ~= nil then\n table.insert(contents, line)\n end\n\n -- Check if we can stop reading lines now.\n if\n line_idx > max_lines\n or (title and not opts.load_contents and not opts.collect_anchor_links and not opts.collect_blocks)\n then\n break\n end\n end\n\n if title ~= nil then\n -- Remove references and links from title\n title = search.replace_refs(title)\n end\n\n -- Parse the frontmatter YAML.\n local metadata = nil\n if #frontmatter_lines > 0 then\n local frontmatter = table.concat(frontmatter_lines, \"\\n\")\n local ok, data = pcall(yaml.loads, frontmatter)\n if type(data) ~= \"table\" then\n data = {}\n end\n if ok then\n ---@diagnostic disable-next-line: param-type-mismatch\n for k, v in pairs(data) do\n if k == \"id\" then\n if type(v) == \"string\" or type(v) == \"number\" then\n id = v\n else\n log.warn(\"Invalid 'id' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"aliases\" then\n if type(v) == \"table\" then\n for alias in iter(v) do\n if type(alias) == \"string\" then\n table.insert(aliases, alias)\n else\n log.warn(\n \"Invalid alias value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(alias)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n table.insert(aliases, v)\n else\n log.warn(\"Invalid 'aliases' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"tags\" then\n if type(v) == \"table\" then\n for tag in iter(v) do\n if type(tag) == \"string\" then\n table.insert(tags, tag)\n else\n log.warn(\n \"Invalid tag value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(tag)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n tags = vim.split(v, \" \")\n else\n log.warn(\"Invalid 'tags' in frontmatter for '%s'\", path)\n end\n else\n if metadata == nil then\n metadata = {}\n end\n metadata[k] = v\n end\n end\n end\n end\n\n -- ID should default to the filename without the extension.\n if id == nil or id == path.name then\n id = path.stem\n end\n assert(id)\n\n local n = Note.new(id, aliases, tags, path)\n n.title = title\n n.metadata = metadata\n n.has_frontmatter = has_frontmatter\n n.frontmatter_end_line = frontmatter_end_line\n n.contents = contents\n n.anchor_links = anchor_links\n n.blocks = blocks\n return n\nend\n\n--- Check if a line matches a frontmatter boundary.\n---\n---@param line string\n---\n---@return boolean\n---\n---@private\nNote._is_frontmatter_boundary = function(line)\n return line:match \"^---+$\" ~= nil\nend\n\n--- Get the frontmatter table to save.\n---\n---@return table\nNote.frontmatter = function(self)\n local out = { id = self.id, aliases = self.aliases, tags = self.tags }\n if self.metadata ~= nil and not vim.tbl_isempty(self.metadata) then\n for k, v in pairs(self.metadata) do\n out[k] = v\n end\n end\n return out\nend\n\n--- Get frontmatter lines that can be written to a buffer.\n---\n---@param eol boolean|?\n---@param frontmatter table|?\n---\n---@return string[]\nNote.frontmatter_lines = function(self, eol, frontmatter)\n local new_lines = { \"---\" }\n\n local frontmatter_ = frontmatter and frontmatter or self:frontmatter()\n if vim.tbl_isempty(frontmatter_) then\n return {}\n end\n\n for line in\n iter(yaml.dumps_lines(frontmatter_, function(a, b)\n local a_idx = nil\n local b_idx = nil\n for i, k in ipairs { \"id\", \"aliases\", \"tags\" } do\n if a == k then\n a_idx = i\n end\n if b == k then\n b_idx = i\n end\n end\n if a_idx ~= nil and b_idx ~= nil then\n return a_idx < b_idx\n elseif a_idx ~= nil then\n return true\n elseif b_idx ~= nil then\n return false\n else\n return a < b\n end\n end))\n do\n table.insert(new_lines, line)\n end\n\n table.insert(new_lines, \"---\")\n if not self.has_frontmatter then\n -- Make sure there's an empty line between end of the frontmatter and the contents.\n table.insert(new_lines, \"\")\n end\n\n if eol then\n return vim.tbl_map(function(l)\n return l .. \"\\n\"\n end, new_lines)\n else\n return new_lines\n end\nend\n\n--- Update the frontmatter in a buffer for the note.\n---\n---@param bufnr integer|?\n---\n---@return boolean updated If the the frontmatter was updated.\nNote.update_frontmatter = function(self, bufnr)\n if not self:should_save_frontmatter() then\n return false\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n return self:save_to_buffer { bufnr = bufnr, frontmatter = frontmatter }\nend\n\n--- Checks if the parameter note is in the blacklist of files which shouldn't have\n--- frontmatter applied\n---\n--- @param note obsidian.Note The note\n--- @return boolean true if so\nlocal is_in_frontmatter_blacklist = function(note)\n local fname = note:fname()\n return (fname ~= nil and vim.list_contains(SKIP_UPDATING_FRONTMATTER, fname))\nend\n\n--- Determines whether a note's frontmatter is managed by obsidian.nvim.\n---\n---@return boolean\nNote.should_save_frontmatter = function(self)\n -- Check if the note is a template.\n local templates_dir = api.templates_dir()\n if templates_dir ~= nil then\n templates_dir = templates_dir:resolve()\n for _, parent in ipairs(self.path:parents()) do\n if parent == templates_dir then\n return false\n end\n end\n end\n\n if is_in_frontmatter_blacklist(self) then\n return false\n elseif type(Obsidian.opts.disable_frontmatter) == \"boolean\" then\n return not Obsidian.opts.disable_frontmatter\n elseif type(Obsidian.opts.disable_frontmatter) == \"function\" then\n return not Obsidian.opts.disable_frontmatter(self.path:vault_relative_path { strict = true })\n else\n return true\n end\nend\n\n--- Write the note to disk.\n---\n---@param opts? obsidian.note.NoteWriteOpts\n---@return obsidian.Note\nNote.write = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n local path = assert(self.path, \"A path must be provided\")\n path = Path.new(path)\n\n ---@type string\n local verb\n if path:is_file() then\n verb = \"Updated\"\n else\n verb = \"Created\"\n if opts.template ~= nil then\n self = Template.clone_template {\n type = \"clone_template\",\n template_name = opts.template,\n destination_path = path,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n partial_note = self,\n }\n end\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n self:save {\n path = path,\n insert_frontmatter = self:should_save_frontmatter(),\n frontmatter = frontmatter,\n update_content = opts.update_content,\n check_buffers = opts.check_buffers,\n }\n\n log.info(\"%s note '%s' at '%s'\", verb, self.id, self.path:vault_relative_path(self.path) or self.path)\n\n return self\nend\n\n--- Save the note to a file.\n--- In general this only updates the frontmatter and header, leaving the rest of the contents unchanged\n--- unless you use the `update_content()` callback.\n---\n---@param opts? obsidian.note.NoteSaveOpts\nNote.save = function(self, opts)\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n if self.path == nil then\n error \"a path is required\"\n end\n\n local save_path = Path.new(assert(opts.path or self.path)):resolve()\n assert(save_path:parent()):mkdir { parents = true, exist_ok = true }\n\n -- Read contents from existing file or buffer, if there is one.\n -- TODO: check for open buffer?\n ---@type string[]\n local content = {}\n ---@type string[]\n local existing_frontmatter = {}\n if self.path ~= nil and self.path:is_file() then\n -- with(open(tostring(self.path)), function(reader)\n local in_frontmatter, at_boundary = false, false -- luacheck: ignore (false positive)\n for idx, line in enumerate(io.lines(tostring(self.path))) do\n if idx == 1 and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n else\n at_boundary = false\n end\n\n if not in_frontmatter and not at_boundary then\n table.insert(content, line)\n else\n table.insert(existing_frontmatter, line)\n end\n end\n -- end)\n elseif self.title ~= nil then\n -- Add a header.\n table.insert(content, \"# \" .. self.title)\n end\n\n -- Pass content through callback.\n if opts.update_content then\n content = opts.update_content(content)\n end\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n -- Replace frontmatter.\n new_lines = compat.flatten { self:frontmatter_lines(false, opts.frontmatter), content }\n else\n -- Use existing frontmatter.\n new_lines = compat.flatten { existing_frontmatter, content }\n end\n\n util.write_file(tostring(save_path), table.concat(new_lines, \"\\n\"))\n\n if opts.check_buffers then\n -- `vim.fn.bufnr` returns the **max** bufnr loaded from the same path.\n if vim.fn.bufnr(save_path.filename) ~= -1 then\n -- But we want to call |checktime| on **all** buffers loaded from the path.\n vim.cmd.checktime(save_path.filename)\n end\n end\nend\n\n--- Write the note to a buffer.\n---\n---@param opts { bufnr: integer|?, template: string|? }|? Options.\n---\n--- Options:\n--- - `bufnr`: Override the buffer to write to. Defaults to current buffer.\n--- - `template`: The name of a template to use if the buffer is empty.\n---\n---@return boolean updated If the buffer was updated.\nNote.write_to_buffer = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = opts or {}\n\n if opts.template and api.buffer_is_empty(opts.bufnr) then\n self = Template.insert_template {\n type = \"insert_template\",\n template_name = opts.template,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n location = api.get_active_window_cursor_location(),\n partial_note = self,\n }\n end\n\n local frontmatter = nil\n local should_save_frontmatter = self:should_save_frontmatter()\n if should_save_frontmatter and Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n return self:save_to_buffer {\n bufnr = opts.bufnr,\n insert_frontmatter = should_save_frontmatter,\n frontmatter = frontmatter,\n }\nend\n\n--- Save the note to the buffer\n---\n---@param opts { bufnr: integer|?, insert_frontmatter: boolean|?, frontmatter: table|? }|? Options.\n---\n---@return boolean updated True if the buffer lines were updated, false otherwise.\nNote.save_to_buffer = function(self, opts)\n opts = opts or {}\n\n local bufnr = opts.bufnr\n if not bufnr then\n bufnr = self.bufnr or 0\n end\n\n local cur_buf_note = Note.from_buffer(bufnr)\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n new_lines = self:frontmatter_lines(nil, opts.frontmatter)\n else\n new_lines = {}\n end\n\n if api.buffer_is_empty(bufnr) and self.title ~= nil then\n table.insert(new_lines, \"# \" .. self.title)\n end\n\n ---@type string[]\n local cur_lines = {}\n if cur_buf_note.frontmatter_end_line ~= nil then\n cur_lines = vim.api.nvim_buf_get_lines(bufnr, 0, cur_buf_note.frontmatter_end_line, false)\n end\n\n if not vim.deep_equal(cur_lines, new_lines) then\n vim.api.nvim_buf_set_lines(\n bufnr,\n 0,\n cur_buf_note.frontmatter_end_line and cur_buf_note.frontmatter_end_line or 0,\n false,\n new_lines\n )\n return true\n else\n return false\n end\nend\n\n--- Try to resolve an anchor link to a line number in the note's file.\n---\n---@param anchor_link string\n---@return obsidian.note.HeaderAnchor|?\nNote.resolve_anchor_link = function(self, anchor_link)\n anchor_link = util.standardize_anchor(anchor_link)\n\n if self.anchor_links ~= nil then\n return self.anchor_links[anchor_link]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_anchor_links = true })\n self.anchor_links = n.anchor_links\n return n:resolve_anchor_link(anchor_link)\nend\n\n--- Try to resolve a block identifier.\n---\n---@param block_id string\n---\n---@return obsidian.note.Block|?\nNote.resolve_block = function(self, block_id)\n block_id = util.standardize_block(block_id)\n\n if self.blocks ~= nil then\n return self.blocks[block_id]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_blocks = true })\n self.blocks = n.blocks\n return self.blocks[block_id]\nend\n\n--- Open a note in a buffer.\n---@param opts { line: integer|?, col: integer|?, open_strategy: obsidian.config.OpenStrategy|?, sync: boolean|?, callback: fun(bufnr: integer)|? }|?\nNote.open = function(self, opts)\n opts = opts or {}\n\n local path = self.path\n\n local function open_it()\n local open_cmd = api.get_open_strategy(opts.open_strategy and opts.open_strategy or Obsidian.opts.open_notes_in)\n ---@cast path obsidian.Path\n local bufnr = api.open_buffer(path, { line = opts.line, col = opts.col, cmd = open_cmd })\n if opts.callback then\n opts.callback(bufnr)\n end\n end\n\n if opts.sync then\n open_it()\n else\n vim.schedule(open_it)\n end\nend\n\nreturn Note\n"], ["/obsidian.nvim/lua/obsidian/commands/dailies.lua", "local log = require \"obsidian.log\"\nlocal daily = require \"obsidian.daily\"\n\n---@param arg string\n---@return number\nlocal function parse_offset(arg)\n if vim.startswith(arg, \"+\") then\n return assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%'\", arg))\n elseif vim.startswith(arg, \"-\") then\n return -assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%s'\", arg))\n else\n return assert(tonumber(arg), string.format(\"invalid offset '%s'\", arg))\n end\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_start = -5\n local offset_end = 0\n\n if data.fargs and #data.fargs > 0 then\n if #data.fargs == 1 then\n local offset = parse_offset(data.fargs[1])\n if offset >= 0 then\n offset_end = offset\n else\n offset_start = offset\n end\n elseif #data.fargs == 2 then\n local offsets = vim.tbl_map(parse_offset, data.fargs)\n table.sort(offsets)\n offset_start = offsets[1]\n offset_end = offsets[2]\n else\n error \":Obsidian dailies expected at most 2 arguments\"\n end\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local dailies = {}\n for offset = offset_end, offset_start, -1 do\n local datetime = os.time() + (offset * 3600 * 24)\n local daily_note_path = daily.daily_note_path(datetime)\n local daily_note_alias = tostring(os.date(Obsidian.opts.daily_notes.alias_format or \"%A %B %-d, %Y\", datetime))\n if offset == 0 then\n daily_note_alias = daily_note_alias .. \" @today\"\n elseif offset == -1 then\n daily_note_alias = daily_note_alias .. \" @yesterday\"\n elseif offset == 1 then\n daily_note_alias = daily_note_alias .. \" @tomorrow\"\n end\n if not daily_note_path:is_file() then\n daily_note_alias = daily_note_alias .. \" ➡️ create\"\n end\n dailies[#dailies + 1] = {\n value = offset,\n display = daily_note_alias,\n ordinal = daily_note_alias,\n filename = tostring(daily_note_path),\n }\n end\n\n picker:pick(dailies, {\n prompt_title = \"Dailies\",\n callback = function(offset)\n local note = daily.daily(offset, {})\n note:open()\n end,\n })\nend\n"], ["/obsidian.nvim/lua/obsidian/health.lua", "local M = {}\nlocal VERSION = require \"obsidian.version\"\nlocal api = require \"obsidian.api\"\n\nlocal error = vim.health.error\nlocal warn = vim.health.warn\nlocal ok = vim.health.ok\n\nlocal function info(...)\n local t = { ... }\n local format = table.remove(t, 1)\n local str = #t == 0 and format or string.format(format, unpack(t))\n return ok(str)\nend\n\n---@private\n---@param name string\nlocal function start(name)\n vim.health.start(string.format(\"obsidian.nvim [%s]\", name))\nend\n\n---@param plugin string\n---@param optional boolean\n---@return boolean\nlocal function has_plugin(plugin, optional)\n local plugin_info = api.get_plugin_info(plugin)\n if plugin_info then\n info(\"%s: %s\", plugin, plugin_info.commit or \"unknown\")\n return true\n else\n if not optional then\n vim.health.error(\" \" .. plugin .. \" not installed\")\n end\n return false\n end\nend\n\nlocal function has_executable(name, optional)\n if vim.fn.executable(name) == 1 then\n local version = api.get_external_dependency_info(name)\n if version then\n info(\"%s: %s\", name, version)\n else\n info(\"%s: found\", name)\n end\n return true\n else\n if not optional then\n error(string.format(\"%s not found\", name))\n end\n return false\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_plugin(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of_executable(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_executable(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param minimum string\n---@param recommended string\nlocal function neovim(minimum, recommended)\n if vim.fn.has(\"nvim-\" .. minimum) == 0 then\n error(\"neovim < \" .. minimum)\n elseif vim.fn.has(\"nvim-\" .. recommended) == 0 then\n warn(\"neovim < \" .. recommended .. \" some features will not work\")\n else\n ok(\"neovim >= \" .. recommended)\n end\nend\n\nfunction M.check()\n local os = api.get_os()\n neovim(\"0.10\", \"0.11\")\n start \"Version\"\n info(\"obsidian.nvim v%s (%s)\", VERSION, api.get_plugin_info(\"obsidian.nvim\").commit)\n\n start \"Environment\"\n info(\"operating system: %s\", os)\n\n start \"Config\"\n info(\" • dir: %s\", Obsidian.dir)\n\n start \"Pickers\"\n\n has_one_of {\n \"telescope.nvim\",\n \"fzf-lua\",\n \"mini.nvim\",\n \"mini.pick\",\n \"snacks.nvim\",\n }\n\n start \"Completion\"\n\n has_one_of {\n \"nvim-cmp\",\n \"blink.cmp\",\n }\n\n start \"Dependencies\"\n has_executable(\"rg\", false)\n has_plugin(\"plenary.nvim\", false)\n\n if os == api.OSType.Wsl then\n has_executable(\"wsl-open\", true)\n elseif os == api.OSType.Linux then\n has_one_of_executable {\n \"xclip\",\n \"wl-paste\",\n }\n elseif os == api.OSType.Darwin then\n has_executable(\"pngpaste\", true)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/blink.lua", "local util = require \"obsidian.util\"\nlocal obsidian = require \"obsidian\"\n\nlocal M = {}\n\nM.injected_once = false\n\nM.providers = {\n { name = \"obsidian\", module = \"obsidian.completion.sources.blink.refs\" },\n { name = \"obsidian_tags\", module = \"obsidian.completion.sources.blink.tags\" },\n}\n\nlocal function add_provider(blink, provider_name, proivder_module)\n local add_source_provider = blink.add_source_provider or blink.add_provider\n add_source_provider(provider_name, {\n name = provider_name,\n module = proivder_module,\n async = true,\n opts = {},\n enabled = function()\n -- Enable only in markdown buffers.\n return vim.tbl_contains({ \"markdown\" }, vim.bo.filetype)\n and vim.bo.buftype ~= \"prompt\"\n and vim.b.completion ~= false\n end,\n })\nend\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_providers(opts)\n local blink = require \"blink.cmp\"\n\n if opts.completion.create_new then\n table.insert(M.providers, { name = \"obsidian_new\", module = \"obsidian.completion.sources.blink.new\" })\n end\n\n for _, provider in pairs(M.providers) do\n add_provider(blink, provider.name, provider.module)\n end\nend\n\nlocal function add_element_to_list_if_not_exists(list, element)\n if not vim.tbl_contains(list, element) then\n table.insert(list, 1, element)\n end\nend\n\nlocal function should_return_if_not_in_workspace()\n local current_file_path = vim.api.nvim_buf_get_name(0)\n local buf_dir = vim.fs.dirname(current_file_path)\n\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return true\n else\n return false\n end\nend\n\nlocal function log_unexpected_type(config_path, unexpected_type, expected_type)\n vim.notify(\n \"blink.cmp's `\"\n .. config_path\n .. \"` configuration appears to be an '\"\n .. unexpected_type\n .. \"' type, but it \"\n .. \"should be '\"\n .. expected_type\n .. \"'. Obsidian won't update this configuration, and \"\n .. \"completion won't work with blink.cmp\",\n vim.log.levels.ERROR\n )\nend\n\n---Attempts to inject the Obsidian sources into per_filetype if that's what the user seems to use for markdown\n---@param blink_sources_per_filetype table\n---@return boolean true if it obsidian sources were injected into the sources.per_filetype\nlocal function try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype)\n -- If the per_filetype is an empty object, then it's probably not utilized by the user\n if vim.deep_equal(blink_sources_per_filetype, {}) then\n return false\n end\n\n local markdown_config = blink_sources_per_filetype[\"markdown\"]\n\n -- If the markdown key is not used, then per_filetype it's probably not utilized by the user\n if markdown_config == nil then\n return false\n end\n\n local markdown_config_type = type(markdown_config)\n if markdown_config_type == \"table\" and util.islist(markdown_config) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(markdown_config, provider.name)\n end\n return true\n elseif markdown_config_type == \"function\" then\n local original_func = markdown_config\n markdown_config = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.per_filetype[\"markdown\"] = markdown_config\n return true\n else\n log_unexpected_type(\n \".sources.per_filetype['markdown']\",\n markdown_config_type,\n \"a list or a function that returns a list of sources\"\n )\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n---Attempts to inject the Obsidian sources into default if that's what the user seems to use for markdown\n---@param blink_sources_default (fun():string[])|(string[])\n---@return boolean true if it obsidian sources were injected into the sources.default\nlocal function try_inject_blink_sources_into_default(blink_sources_default)\n local blink_default_type = type(blink_sources_default)\n if blink_default_type == \"function\" then\n local original_func = blink_sources_default\n blink_sources_default = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.default = blink_sources_default\n return true\n elseif blink_default_type == \"table\" and util.islist(blink_sources_default) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(blink_sources_default, provider.name)\n end\n\n return true\n elseif blink_default_type == \"table\" then\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n else\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list or a function that returns a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace. nvm_cmp had the capability to configure the sources\n-- per buffer, but blink.cmp doesn't have that capability. Instead, we have to inject the sources into the global\n-- configuration and set a boolean on the module to return early the next time this function is called.\n--\n-- In-case the user used functions to configure their sources, the completion will properly work just for the markdown\n-- files that are in a workspace. Otherwise, the completion will work for all markdown files.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n if M.injected_once then\n return\n end\n\n M.injected_once = true\n\n local blink_config = require \"blink.cmp.config\"\n -- 'per_filetype' sources has priority over 'default' sources.\n -- 'per_filetype' can be a table or a function which returns a table ([\"filetype\"] = { \"a\", \"b\" })\n -- 'per_filetype' has the default value of {} (even if it's not configured by the user)\n local blink_sources_per_filetype = blink_config.sources.per_filetype\n if try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype) then\n return\n end\n\n -- 'default' can be a list/array or a function which returns a list/array ({ \"a\", \"b\"})\n local blink_sources_default = blink_config.sources[\"default\"]\n if try_inject_blink_sources_into_default(blink_sources_default) then\n return\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/templates.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nlocal M = {}\n\n--- Resolve a template name to a path.\n---\n---@param template_name string|obsidian.Path\n---@param templates_dir obsidian.Path\n---\n---@return obsidian.Path\nM.resolve_template = function(template_name, templates_dir)\n ---@type obsidian.Path|?\n local template_path\n local paths_to_check = { templates_dir / tostring(template_name), Path:new(template_name) }\n for _, path in ipairs(paths_to_check) do\n if path:is_file() then\n template_path = path\n break\n elseif not vim.endswith(tostring(path), \".md\") then\n local path_with_suffix = Path:new(tostring(path) .. \".md\")\n if path_with_suffix:is_file() then\n template_path = path_with_suffix\n break\n end\n end\n end\n\n if template_path == nil then\n error(string.format(\"Template '%s' not found\", template_name))\n end\n\n return template_path\nend\n\n--- Substitute variables inside the given text.\n---\n---@param text string\n---@param ctx obsidian.TemplateContext\n---\n---@return string\nM.substitute_template_variables = function(text, ctx)\n local methods = vim.deepcopy(ctx.template_opts.substitutions or {})\n\n if not methods[\"date\"] then\n methods[\"date\"] = function()\n local date_format = ctx.template_opts.date_format or \"%Y-%m-%d\"\n return tostring(os.date(date_format))\n end\n end\n\n if not methods[\"time\"] then\n methods[\"time\"] = function()\n local time_format = ctx.template_opts.time_format or \"%H:%M\"\n return tostring(os.date(time_format))\n end\n end\n\n if not methods[\"title\"] and ctx.partial_note then\n methods[\"title\"] = ctx.partial_note.title or ctx.partial_note:display_name()\n end\n\n if not methods[\"id\"] and ctx.partial_note then\n methods[\"id\"] = tostring(ctx.partial_note.id)\n end\n\n if not methods[\"path\"] and ctx.partial_note and ctx.partial_note.path then\n methods[\"path\"] = tostring(ctx.partial_note.path)\n end\n\n -- Replace known variables.\n for key, subst in pairs(methods) do\n while true do\n local m_start, m_end = string.find(text, \"{{\" .. key .. \"}}\", nil, true)\n if not m_start or not m_end then\n break\n end\n ---@type string\n local value\n if type(subst) == \"string\" then\n value = subst\n else\n value = subst(ctx)\n -- cache the result\n methods[key] = value\n end\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n -- Find unknown variables and prompt for them.\n for m_start, m_end in util.gfind(text, \"{{[^}]+}}\") do\n local key = vim.trim(string.sub(text, m_start + 2, m_end - 2))\n local value = api.input(string.format(\"Enter value for '%s' ( to skip): \", key))\n if value and string.len(value) > 0 then\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n return text\nend\n\n--- Clone template to a new note.\n---\n---@param ctx obsidian.CloneTemplateContext\n---\n---@return obsidian.Note\nM.clone_template = function(ctx)\n local note_path = Path.new(ctx.destination_path)\n assert(note_path:parent()):mkdir { parents = true, exist_ok = true }\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local template_file, read_err = io.open(tostring(template_path), \"r\")\n if not template_file then\n error(string.format(\"Unable to read template at '%s': %s\", template_path, tostring(read_err)))\n end\n\n local note_file, write_err = io.open(tostring(note_path), \"w\")\n if not note_file then\n error(string.format(\"Unable to write note at '%s': %s\", note_path, tostring(write_err)))\n end\n\n for line in template_file:lines \"L\" do\n line = M.substitute_template_variables(line, ctx)\n note_file:write(line)\n end\n\n assert(template_file:close())\n assert(note_file:close())\n\n local new_note = Note.from_file(note_path)\n\n if ctx.partial_note then\n -- Transfer fields from `ctx.partial_note`.\n new_note.id = ctx.partial_note.id\n if new_note.title == nil then\n new_note.title = ctx.partial_note.title\n end\n for _, alias in ipairs(ctx.partial_note.aliases) do\n new_note:add_alias(alias)\n end\n for _, tag in ipairs(ctx.partial_note.tags) do\n new_note:add_tag(tag)\n end\n end\n\n return new_note\nend\n\n---Insert a template at the given location.\n---\n---@param ctx obsidian.InsertTemplateContext\n---\n---@return obsidian.Note\nM.insert_template = function(ctx)\n local buf, win, row, _ = unpack(ctx.location)\n if ctx.partial_note == nil then\n ctx.partial_note = Note.from_buffer(buf)\n end\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local insert_lines = {}\n local template_file = io.open(tostring(template_path), \"r\")\n if template_file then\n local lines = template_file:lines()\n for line in lines do\n local new_lines = M.substitute_template_variables(line, ctx)\n if string.find(new_lines, \"[\\r\\n]\") then\n local line_start = 1\n for line_end in util.gfind(new_lines, \"[\\r\\n]\") do\n local new_line = string.sub(new_lines, line_start, line_end - 1)\n table.insert(insert_lines, new_line)\n line_start = line_end + 1\n end\n local last_line = string.sub(new_lines, line_start)\n if string.len(last_line) > 0 then\n table.insert(insert_lines, last_line)\n end\n else\n table.insert(insert_lines, new_lines)\n end\n end\n template_file:close()\n else\n error(string.format(\"Template file '%s' not found\", template_path))\n end\n\n vim.api.nvim_buf_set_lines(buf, row - 1, row - 1, false, insert_lines)\n local new_cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(win))\n vim.api.nvim_win_set_cursor(0, { new_cursor_row, 0 })\n\n require(\"obsidian.ui\").update(0)\n\n return Note.from_buffer(buf)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/toc.lua", "local util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local note = assert(api.current_note(0, { collect_anchor_links = true }))\n\n ---@type obsidian.PickerEntry[]\n local picker_entries = {}\n for _, anchor in pairs(note.anchor_links) do\n local display = string.rep(\"#\", anchor.level) .. \" \" .. anchor.header\n table.insert(\n picker_entries,\n { value = display, display = display, filename = tostring(note.path), lnum = anchor.line }\n )\n end\n\n -- De-duplicate and sort.\n picker_entries = util.tbl_unique(picker_entries)\n table.sort(picker_entries, function(a, b)\n return a.lnum < b.lnum\n end)\n\n local picker = assert(Obsidian.picker)\n picker:pick(picker_entries, { prompt_title = \"Table of Contents\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/util.lua", "local compat = require \"obsidian.compat\"\nlocal ts, string, table = vim.treesitter, string, table\nlocal util = {}\n\nsetmetatable(util, {\n __index = function(_, k)\n return require(\"obsidian.api\")[k] or require(\"obsidian.builtin\")[k]\n end,\n})\n\n-------------------\n--- File tools ----\n-------------------\n\n---@param file string\n---@param contents string\nutil.write_file = function(file, contents)\n local fd = assert(io.open(file, \"w+\"))\n fd:write(contents)\n fd:close()\nend\n\n-------------------\n--- Iter tools ----\n-------------------\n\n---Create an enumeration iterator over an iterable.\n---@param iterable table|string|function\n---@return function\nutil.enumerate = function(iterable)\n local iterator = vim.iter(iterable)\n local i = 0\n\n return function()\n local next = iterator()\n if next == nil then\n return nil, nil\n else\n i = i + 1\n return i, next\n end\n end\nend\n\n---Zip two iterables together.\n---@param iterable1 table|string|function\n---@param iterable2 table|string|function\n---@return function\nutil.zip = function(iterable1, iterable2)\n local iterator1 = vim.iter(iterable1)\n local iterator2 = vim.iter(iterable2)\n\n return function()\n local next1 = iterator1()\n local next2 = iterator2()\n if next1 == nil or next2 == nil then\n return nil\n else\n return next1, next2\n end\n end\nend\n\n-------------------\n--- Table tools ---\n-------------------\n\n---Check if an object is an array-like table.\n--- TODO: after 0.12 replace with vim.islist\n---\n---@param t any\n---@return boolean\nutil.islist = function(t)\n return compat.is_list(t)\nend\n\n---Return a new list table with only the unique values of the original table.\n---\n---@param t table\n---@return any[]\nutil.tbl_unique = function(t)\n local found = {}\n for _, val in pairs(t) do\n found[val] = true\n end\n return vim.tbl_keys(found)\nend\n\n--------------------\n--- String Tools ---\n--------------------\n\n---Iterate over all matches of 'pattern' in 's'. 'gfind' is to 'find' as 'gsub' is to 'sub'.\n---@param s string\n---@param pattern string\n---@param init integer|?\n---@param plain boolean|?\nutil.gfind = function(s, pattern, init, plain)\n init = init and init or 1\n\n return function()\n if init < #s then\n local m_start, m_end = string.find(s, pattern, init, plain)\n if m_start ~= nil and m_end ~= nil then\n init = m_end + 1\n return m_start, m_end\n end\n end\n return nil\n end\nend\n\nlocal char_to_hex = function(c)\n return string.format(\"%%%02X\", string.byte(c))\nend\n\n--- Encode a string into URL-safe version.\n---\n---@param str string\n---@param opts { keep_path_sep: boolean|? }|?\n---\n---@return string\nutil.urlencode = function(str, opts)\n opts = opts or {}\n local url = str\n url = url:gsub(\"\\n\", \"\\r\\n\")\n url = url:gsub(\"([%(%)%*%?%[%]%$\\\"':<>|\\\\'{}])\", char_to_hex)\n if not opts.keep_path_sep then\n url = url:gsub(\"/\", char_to_hex)\n end\n\n -- Spaces in URLs are always safely encoded with `%20`, but not always safe\n -- with `+`. For example, `+` in a query param's value will be interpreted\n -- as a literal plus-sign if the decoder is using JavaScript's `decodeURI`\n -- function.\n url = url:gsub(\" \", \"%%20\")\n return url\nend\n\nutil.is_hex_color = function(s)\n return (s:match \"^#%x%x%x$\" or s:match \"^#%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x%x%x$\")\n ~= nil\nend\n\n---Match the case of 'key' to the given 'prefix' of the key.\n---\n---@param prefix string\n---@param key string\n---@return string|?\nutil.match_case = function(prefix, key)\n local out_chars = {}\n for i = 1, string.len(key) do\n local c_key = string.sub(key, i, i)\n local c_pre = string.sub(prefix, i, i)\n if c_pre:lower() == c_key:lower() then\n table.insert(out_chars, c_pre)\n elseif c_pre:len() > 0 then\n return nil\n else\n table.insert(out_chars, c_key)\n end\n end\n return table.concat(out_chars, \"\")\nend\n\n---Check if a string is a checkbox list item\n---\n---Supported checboox lists:\n--- - [ ] foo\n--- - [x] foo\n--- + [x] foo\n--- * [ ] foo\n--- 1. [ ] foo\n--- 1) [ ] foo\n---\n---@param s string\n---@return boolean\nutil.is_checkbox = function(s)\n -- - [ ] and * [ ] and + [ ]\n if string.match(s, \"^%s*[-+*]%s+%[.%]\") ~= nil then\n return true\n end\n -- 1. [ ] and 1) [ ]\n if string.match(s, \"^%s*%d+[%.%)]%s+%[.%]\") ~= nil then\n return true\n end\n return false\nend\n\n---Check if a string is a valid URL.\n---@param s string\n---@return boolean\nutil.is_url = function(s)\n local search = require \"obsidian.search\"\n\n if\n string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.NakedUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.FileUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.MailtoUrl] .. \"$\")\n then\n return true\n else\n return false\n end\nend\n\n---Checks if a given string represents an image file based on its suffix.\n---\n---@param s string: The input string to check.\n---@return boolean: Returns true if the string ends with a supported image suffix, false otherwise.\nutil.is_img = function(s)\n for _, suffix in ipairs { \".png\", \".jpg\", \".jpeg\", \".heic\", \".gif\", \".svg\", \".ico\" } do\n if vim.endswith(s, suffix) then\n return true\n end\n end\n return false\nend\n\n-- This function removes a single backslash within double square brackets\nutil.unescape_single_backslash = function(text)\n return text:gsub(\"(%[%[[^\\\\]+)\\\\(%|[^\\\\]+]])\", \"%1%2\")\nend\n\nutil.string_enclosing_chars = { [[\"]], [[']] }\n\n---Count the indentation of a line.\n---@param str string\n---@return integer\nutil.count_indent = function(str)\n local indent = 0\n for i = 1, #str do\n local c = string.sub(str, i, i)\n -- space or tab both count as 1 indent\n if c == \" \" or c == \"\t\" then\n indent = indent + 1\n else\n break\n end\n end\n return indent\nend\n\n---Check if a string is only whitespace.\n---@param str string\n---@return boolean\nutil.is_whitespace = function(str)\n return string.match(str, \"^%s+$\") ~= nil\nend\n\n---Get the substring of `str` starting from the first character and up to the stop character,\n---ignoring any enclosing characters (like double quotes) and stop characters that are within the\n---enclosing characters. For example, if `str = [=[\"foo\", \"bar\"]=]` and `stop_char = \",\"`, this\n---would return the string `[=[foo]=]`.\n---\n---@param str string\n---@param stop_chars string[]\n---@param keep_stop_char boolean|?\n---@return string|?, string\nutil.next_item = function(str, stop_chars, keep_stop_char)\n local og_str = str\n\n -- Check for enclosing characters.\n local enclosing_char = nil\n local first_char = string.sub(str, 1, 1)\n for _, c in ipairs(util.string_enclosing_chars) do\n if first_char == c then\n enclosing_char = c\n str = string.sub(str, 2)\n break\n end\n end\n\n local result\n local hits\n\n for _, stop_char in ipairs(stop_chars) do\n -- First check for next item when `stop_char` is present.\n if enclosing_char ~= nil then\n result, hits = string.gsub(\n str,\n \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*\" .. stop_char .. \".*\",\n \"%1%2\"\n )\n result = enclosing_char .. result .. enclosing_char\n else\n result, hits = string.gsub(str, \"([^\" .. stop_char .. \"]+)\" .. stop_char .. \".*\", \"%1\")\n end\n if hits ~= 0 then\n local i = string.find(str, stop_char, string.len(result), true)\n if keep_stop_char then\n return result .. stop_char, string.sub(str, i + 1)\n else\n return result, string.sub(str, i + 1)\n end\n end\n\n -- Now check for next item without the `stop_char` after.\n if not keep_stop_char and enclosing_char ~= nil then\n result, hits = string.gsub(str, \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*$\", \"%1%2\")\n result = enclosing_char .. result .. enclosing_char\n elseif not keep_stop_char then\n result = str\n hits = 1\n else\n result = nil\n hits = 0\n end\n if hits ~= 0 then\n if keep_stop_char then\n result = result .. stop_char\n end\n return result, \"\"\n end\n end\n\n return nil, og_str\nend\n\n---Strip whitespace from the right end of a string.\n---@param str string\n---@return string\nutil.rstrip_whitespace = function(str)\n str = string.gsub(str, \"%s+$\", \"\")\n return str\nend\n\n---Strip whitespace from the left end of a string.\n---@param str string\n---@param limit integer|?\n---@return string\nutil.lstrip_whitespace = function(str, limit)\n if limit ~= nil then\n local num_found = 0\n while num_found < limit do\n str = string.gsub(str, \"^%s\", \"\")\n num_found = num_found + 1\n end\n else\n str = string.gsub(str, \"^%s+\", \"\")\n end\n return str\nend\n\n---Strip enclosing characters like quotes from a string.\n---@param str string\n---@return string\nutil.strip_enclosing_chars = function(str)\n local c_start = string.sub(str, 1, 1)\n local c_end = string.sub(str, #str, #str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if c_start == enclosing_char and c_end == enclosing_char then\n str = string.sub(str, 2, #str - 1)\n break\n end\n end\n return str\nend\n\n---Check if a string has enclosing characters like quotes.\n---@param str string\n---@return boolean\nutil.has_enclosing_chars = function(str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if vim.startswith(str, enclosing_char) and vim.endswith(str, enclosing_char) then\n return true\n end\n end\n return false\nend\n\n---Strip YAML comments from a string.\n---@param str string\n---@return string\nutil.strip_comments = function(str)\n if vim.startswith(str, \"# \") then\n return \"\"\n elseif not util.has_enclosing_chars(str) then\n return select(1, string.gsub(str, [[%s+#%s.*$]], \"\"))\n else\n return str\n end\nend\n\n---Check if a string contains a substring.\n---@param str string\n---@param substr string\n---@return boolean\nutil.string_contains = function(str, substr)\n local i = string.find(str, substr, 1, true)\n return i ~= nil\nend\n\n--------------------\n--- Date helpers ---\n--------------------\n\n---Determines if the given date is a working day (not weekend)\n---\n---@param time integer\n---\n---@return boolean\nutil.is_working_day = function(time)\n local is_saturday = (os.date(\"%w\", time) == \"6\")\n local is_sunday = (os.date(\"%w\", time) == \"0\")\n return not (is_saturday or is_sunday)\nend\n\n--- Returns the previous day from given time\n---\n--- @param time integer\n--- @return integer\nutil.previous_day = function(time)\n return time - (24 * 60 * 60)\nend\n---\n--- Returns the next day from given time\n---\n--- @param time integer\n--- @return integer\nutil.next_day = function(time)\n return time + (24 * 60 * 60)\nend\n\n---Determines the last working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_before = function(time)\n local previous_day = util.previous_day(time)\n if util.is_working_day(previous_day) then\n return previous_day\n else\n return util.working_day_before(previous_day)\n end\nend\n\n---Determines the next working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_after = function(time)\n local next_day = util.next_day(time)\n if util.is_working_day(next_day) then\n return next_day\n else\n return util.working_day_after(next_day)\n end\nend\n\n---@param link string\n---@param opts { include_naked_urls: boolean|?, include_file_urls: boolean|?, include_block_ids: boolean|?, link_type: obsidian.search.RefTypes|? }|?\n---\n---@return string|?, string|?, obsidian.search.RefTypes|?\nutil.parse_link = function(link, opts)\n local search = require \"obsidian.search\"\n\n opts = opts and opts or {}\n\n local link_type = opts.link_type\n if link_type == nil then\n for match in\n vim.iter(search.find_refs(link, {\n include_naked_urls = opts.include_naked_urls,\n include_file_urls = opts.include_file_urls,\n include_block_ids = opts.include_block_ids,\n }))\n do\n local _, _, m_type = unpack(match)\n if m_type then\n link_type = m_type\n break\n end\n end\n end\n\n if link_type == nil then\n return nil\n end\n\n local link_location, link_name\n if link_type == search.RefTypes.Markdown then\n link_location = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%2\")\n link_name = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%1\")\n elseif link_type == search.RefTypes.NakedUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.FileUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.WikiWithAlias then\n link = util.unescape_single_backslash(link)\n -- remove boundary brackets, e.g. '[[XXX|YYY]]' -> 'XXX|YYY'\n link = link:sub(3, #link - 2)\n -- split on the \"|\"\n local split_idx = link:find \"|\"\n link_location = link:sub(1, split_idx - 1)\n link_name = link:sub(split_idx + 1)\n elseif link_type == search.RefTypes.Wiki then\n -- remove boundary brackets, e.g. '[[YYY]]' -> 'YYY'\n link = link:sub(3, #link - 2)\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.BlockID then\n link_location = util.standardize_block(link)\n link_name = link\n else\n error(\"not implemented for \" .. link_type)\n end\n\n return link_location, link_name, link_type\nend\n\n------------------------------------\n-- Miscellaneous helper functions --\n------------------------------------\n---@param anchor obsidian.note.HeaderAnchor\n---@return string\nutil.format_anchor_label = function(anchor)\n return string.format(\" ❯ %s\", anchor.header)\nend\n\n-- We are very loose here because obsidian allows pretty much anything\nutil.ANCHOR_LINK_PATTERN = \"#[%w%d\\128-\\255][^#]*\"\n\nutil.BLOCK_PATTERN = \"%^[%w%d][%w%d-]*\"\n\nutil.BLOCK_LINK_PATTERN = \"#\" .. util.BLOCK_PATTERN\n\n--- Strip anchor links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_anchor_links = function(line)\n ---@type string|?\n local anchor\n\n while true do\n local anchor_match = string.match(line, util.ANCHOR_LINK_PATTERN .. \"$\")\n if anchor_match then\n anchor = anchor or \"\"\n anchor = anchor_match .. anchor\n line = string.sub(line, 1, -anchor_match:len() - 1)\n else\n break\n end\n end\n\n return line, anchor and util.standardize_anchor(anchor)\nend\n\n--- Parse a block line from a line.\n---\n---@param line string\n---\n---@return string|?\nutil.parse_block = function(line)\n local block_match = string.match(line, util.BLOCK_PATTERN .. \"$\")\n return block_match\nend\n\n--- Strip block links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_block_links = function(line)\n local block_match = string.match(line, util.BLOCK_LINK_PATTERN .. \"$\")\n if block_match then\n line = string.sub(line, 1, -block_match:len() - 1)\n end\n return line, block_match\nend\n\n--- Standardize a block identifier.\n---@param block_id string\n---@return string\nutil.standardize_block = function(block_id)\n if vim.startswith(block_id, \"#\") then\n block_id = string.sub(block_id, 2)\n end\n\n if not vim.startswith(block_id, \"^\") then\n block_id = \"^\" .. block_id\n end\n\n return block_id\nend\n\n--- Check if a line is a markdown header.\n---@param line string\n---@return boolean\nutil.is_header = function(line)\n if string.match(line, \"^#+%s+[%w]+\") then\n return true\n else\n return false\n end\nend\n\n--- Get the header level of a line.\n---@param line string\n---@return integer\nutil.header_level = function(line)\n local headers, match_count = string.gsub(line, \"^(#+)%s+[%w]+.*\", \"%1\")\n if match_count > 0 then\n return string.len(headers)\n else\n return 0\n end\nend\n\n---@param line string\n---@return { header: string, level: integer, anchor: string }|?\nutil.parse_header = function(line)\n local header_start, header = string.match(line, \"^(#+)%s+([^%s]+.*)$\")\n if header_start and header then\n header = vim.trim(header)\n return {\n header = vim.trim(header),\n level = string.len(header_start),\n anchor = util.header_to_anchor(header),\n }\n else\n return nil\n end\nend\n\n--- Standardize a header anchor link.\n---\n---@param anchor string\n---\n---@return string\nutil.standardize_anchor = function(anchor)\n -- Lowercase everything.\n anchor = string.lower(anchor)\n -- Replace whitespace with \"-\".\n anchor = string.gsub(anchor, \"%s\", \"-\")\n -- Remove every non-alphanumeric character.\n anchor = string.gsub(anchor, \"[^#%w\\128-\\255_-]\", \"\")\n return anchor\nend\n\n--- Transform a markdown header into an link, e.g. \"# Hello World\" -> \"#hello-world\".\n---\n---@param header string\n---\n---@return string\nutil.header_to_anchor = function(header)\n -- Remove leading '#' and strip whitespace.\n local anchor = vim.trim(string.gsub(header, [[^#+%s+]], \"\"))\n return util.standardize_anchor(\"#\" .. anchor)\nend\n\n---@alias datetime_cadence \"daily\"\n\n--- Parse possible relative date macros like '@tomorrow'.\n---\n---@param macro string\n---\n---@return { macro: string, offset: integer, cadence: datetime_cadence }[]\nutil.resolve_date_macro = function(macro)\n ---@type { macro: string, offset: integer, cadence: datetime_cadence }[]\n local out = {}\n for m, offset_days in pairs { today = 0, tomorrow = 1, yesterday = -1 } do\n m = \"@\" .. m\n if vim.startswith(m, macro) then\n out[#out + 1] = { macro = m, offset = offset_days, cadence = \"daily\" }\n end\n end\n return out\nend\n\n--- Check if a string contains invalid characters.\n---\n--- @param fname string\n---\n--- @return boolean\nutil.contains_invalid_characters = function(fname)\n local invalid_chars = \"#^%[%]|\"\n return string.find(fname, \"[\" .. invalid_chars .. \"]\") ~= nil\nend\n\n---Check if a string is NaN\n---\n---@param v any\n---@return boolean\nutil.isNan = function(v)\n return tostring(v) == tostring(0 / 0)\nend\n\n---Higher order function, make sure a function is called with complete lines\n---@param fn fun(string)?\n---@return fun(string)\nutil.buffer_fn = function(fn)\n if not fn then\n return function() end\n end\n local buffer = \"\"\n return function(data)\n buffer = buffer .. data\n local lines = vim.split(buffer, \"\\n\")\n if #lines > 1 then\n for i = 1, #lines - 1 do\n fn(lines[i])\n end\n buffer = lines[#lines] -- Store remaining partial line\n end\n end\nend\n\n---@param event string\n---@param callback fun(...)\n---@param ... any\n---@return boolean success\nutil.fire_callback = function(event, callback, ...)\n local log = require \"obsidian.log\"\n if not callback then\n return false\n end\n local ok, err = pcall(callback, ...)\n if ok then\n return true\n else\n log.error(\"Error running %s callback: %s\", event, err)\n return false\n end\nend\n\n---@param node_type string | string[]\n---@return boolean\nutil.in_node = function(node_type)\n local function in_node(t)\n local node = ts.get_node()\n while node do\n if node:type() == t then\n return true\n end\n node = node:parent()\n end\n return false\n end\n if type(node_type) == \"string\" then\n return in_node(node_type)\n elseif type(node_type) == \"table\" then\n for _, t in ipairs(node_type) do\n local is_in_node = in_node(t)\n if is_in_node then\n return true\n end\n end\n end\n return false\nend\n\nreturn util\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/refs.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.RefsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field in_buffer_only boolean\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\n---@field block_link string|?\n---@field anchor_link string|?\n---@field new_text_to_option table\nlocal RefsSourceCompletionContext = abc.new_class()\n\nRefsSourceCompletionContext.new = function()\n return RefsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.RefsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal RefsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.RefsSourceBase\nRefsSourceBase.new = function()\n return RefsSourceBase.init()\nend\n\nRefsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = RefsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n completion_context.in_buffer_only = false\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n self:strip_links(cc)\n self:determine_buffer_only_search_scope(cc)\n\n if cc.in_buffer_only then\n local note = api.current_note(0, { collect_anchor_links = true, collect_blocks = true })\n if note then\n self:process_search_results(cc, { note })\n else\n cc.completion_resolve_callback(self.incomplete_response)\n end\n else\n local search_ops = cc.client.search_defaults()\n search_ops.ignore_case = true\n\n search.find_notes_async(cc.search, function(results)\n self:process_search_results(cc, results)\n end, {\n search = search_ops,\n notes = { collect_anchor_links = cc.anchor_link ~= nil, collect_blocks = cc.block_link ~= nil },\n })\n end\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction RefsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\n---Collect matching block links.\n---@param note obsidian.Note\n---@param block_link string?\n---@return obsidian.note.Block[]|?\nfunction RefsSourceBase:collect_matching_blocks(note, block_link)\n ---@type obsidian.note.Block[]|?\n local matching_blocks\n if block_link then\n assert(note.blocks)\n matching_blocks = {}\n for block_id, block_data in pairs(note.blocks) do\n if vim.startswith(\"#\" .. block_id, block_link) then\n table.insert(matching_blocks, block_data)\n end\n end\n\n if #matching_blocks == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_blocks, { id = util.standardize_block(block_link), line = 1 })\n end\n end\n\n return matching_blocks\nend\n\n---Collect matching anchor links.\n---@param note obsidian.Note\n---@param anchor_link string?\n---@return obsidian.note.HeaderAnchor[]?\nfunction RefsSourceBase:collect_matching_anchors(note, anchor_link)\n ---@type obsidian.note.HeaderAnchor[]|?\n local matching_anchors\n if anchor_link then\n assert(note.anchor_links)\n matching_anchors = {}\n for anchor, anchor_data in pairs(note.anchor_links) do\n if vim.startswith(anchor, anchor_link) then\n table.insert(matching_anchors, anchor_data)\n end\n end\n\n if #matching_anchors == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_anchors, { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 })\n end\n end\n\n return matching_anchors\nend\n\n--- Strips block and anchor links from the current search string\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:strip_links(cc)\n cc.search, cc.block_link = util.strip_block_links(cc.search)\n cc.search, cc.anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, we'll match against all block links.\n if not cc.block_link and vim.endswith(cc.search, \"#^\") then\n cc.block_link = \"#^\"\n cc.search = string.sub(cc.search, 1, -3)\n end\n\n -- If anchor link is incomplete, we'll match against all anchor links.\n if not cc.anchor_link and vim.endswith(cc.search, \"#\") then\n cc.anchor_link = \"#\"\n cc.search = string.sub(cc.search, 1, -2)\n end\nend\n\n--- Determines whatever the in_buffer_only should be enabled\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:determine_buffer_only_search_scope(cc)\n if (cc.anchor_link or cc.block_link) and string.len(cc.search) == 0 then\n -- Search over headers/blocks in current buffer only.\n cc.in_buffer_only = true\n end\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param results obsidian.Note[]\nfunction RefsSourceBase:process_search_results(cc, results)\n assert(cc)\n assert(results)\n\n local completion_items = {}\n\n cc.new_text_to_option = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local matching_blocks = self:collect_matching_blocks(note, cc.block_link)\n local matching_anchors = self:collect_matching_anchors(note, cc.anchor_link)\n\n if cc.in_buffer_only then\n self:update_completion_options(cc, nil, nil, matching_anchors, matching_blocks, note)\n else\n -- Collect all valid aliases for the note, including ID, title, and filename.\n ---@type string[]\n local aliases\n if not cc.in_buffer_only then\n aliases = util.tbl_unique { tostring(note.id), note:display_name(), unpack(note.aliases) }\n if note.title ~= nil then\n table.insert(aliases, note.title)\n end\n end\n\n for alias in iter(aliases) do\n self:update_completion_options(cc, alias, nil, matching_anchors, matching_blocks, note)\n local alias_case_matched = util.match_case(cc.search, alias)\n\n if\n alias_case_matched ~= nil\n and alias_case_matched ~= alias\n and not vim.list_contains(note.aliases, alias_case_matched)\n and Obsidian.opts.completion.match_case\n then\n self:update_completion_options(cc, alias_case_matched, nil, matching_anchors, matching_blocks, note)\n end\n end\n\n if note.alt_alias ~= nil then\n self:update_completion_options(cc, note:display_name(), note.alt_alias, matching_anchors, matching_blocks, note)\n end\n end\n end\n\n for _, option in pairs(cc.new_text_to_option) do\n -- TODO: need a better label, maybe just the note's display name?\n ---@type string\n local label\n if cc.ref_type == completion.RefType.Wiki then\n label = string.format(\"[[%s]]\", option.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n label = string.format(\"[%s](…)\", option.label)\n else\n error \"not implemented\"\n end\n\n table.insert(completion_items, {\n documentation = option.documentation,\n sortText = option.sort_text,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = option.new_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n })\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = completion_items }))\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param label string|?\n---@param alt_label string|?\n---@param note obsidian.Note\nfunction RefsSourceBase:update_completion_options(cc, label, alt_label, matching_anchors, matching_blocks, note)\n ---@type { label: string|?, alt_label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }[]\n local new_options = {}\n if matching_anchors ~= nil then\n for anchor in iter(matching_anchors) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor })\n end\n elseif matching_blocks ~= nil then\n for block in iter(matching_blocks) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block })\n end\n else\n if label then\n table.insert(new_options, { label = label, alt_label = alt_label })\n end\n\n -- Add all blocks and anchors, let cmp sort it out.\n for _, anchor_data in pairs(note.anchor_links or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor_data })\n end\n for _, block_data in pairs(note.blocks or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block_data })\n end\n end\n\n -- De-duplicate options relative to their `new_text`.\n for _, option in ipairs(new_options) do\n ---@type obsidian.config.LinkStyle\n local link_style\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n else\n error \"not implemented\"\n end\n\n ---@type string, string, string, table|?\n local final_label, sort_text, new_text, documentation\n if option.label then\n new_text = api.format_link(\n note,\n { label = option.label, link_style = link_style, anchor = option.anchor, block = option.block }\n )\n\n final_label = assert(option.alt_label or option.label)\n if option.anchor then\n final_label = final_label .. option.anchor.anchor\n elseif option.block then\n final_label = final_label .. \"#\" .. option.block.id\n end\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = note:display_info {\n label = new_text,\n anchor = option.anchor,\n block = option.block,\n },\n }\n elseif option.anchor then\n -- In buffer anchor link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.anchor.header .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.anchor.header .. \"](\" .. option.anchor.anchor .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = option.anchor.anchor\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n elseif option.block then\n -- In buffer block link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.block.id .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.block.id .. \"](#\" .. option.block.id .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = \"#\" .. option.block.id\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n else\n error \"should not happen\"\n end\n\n if cc.new_text_to_option[new_text] then\n cc.new_text_to_option[new_text].sort_text = cc.new_text_to_option[new_text].sort_text .. \" \" .. sort_text\n else\n cc.new_text_to_option[new_text] =\n { label = final_label, new_text = new_text, sort_text = sort_text, documentation = documentation }\n end\n end\nend\n\nreturn RefsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/yaml/parser.lua", "local Line = require \"obsidian.yaml.line\"\nlocal abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\n\nlocal m = {}\n\n---@class obsidian.yaml.ParserOpts\n---@field luanil boolean\nlocal ParserOpts = {}\n\nm.ParserOpts = ParserOpts\n\n---@return obsidian.yaml.ParserOpts\nParserOpts.default = function()\n return {\n luanil = true,\n }\nend\n\n---@param opts table\n---@return obsidian.yaml.ParserOpts\nParserOpts.normalize = function(opts)\n ---@type obsidian.yaml.ParserOpts\n opts = vim.tbl_extend(\"force\", ParserOpts.default(), opts)\n return opts\nend\n\n---@class obsidian.yaml.Parser : obsidian.ABC\n---@field opts obsidian.yaml.ParserOpts\nlocal Parser = abc.new_class()\n\nm.Parser = Parser\n\n---@enum YamlType\nlocal YamlType = {\n Scalar = \"Scalar\", -- a boolean, string, number, or NULL\n Mapping = \"Mapping\",\n Array = \"Array\",\n ArrayItem = \"ArrayItem\",\n EmptyLine = \"EmptyLine\",\n}\n\nm.YamlType = YamlType\n\n---@class vim.NIL\n\n---Create a new Parser.\n---@param opts obsidian.yaml.ParserOpts|?\n---@return obsidian.yaml.Parser\nm.new = function(opts)\n local self = Parser.init()\n self.opts = ParserOpts.normalize(opts and opts or {})\n return self\nend\n\n---Parse a YAML string.\n---@param str string\n---@return any\nParser.parse = function(self, str)\n -- Collect and pre-process lines.\n local lines = {}\n local base_indent = 0\n for raw_line in str:gmatch \"[^\\r\\n]+\" do\n local ok, result = pcall(Line.new, raw_line, base_indent)\n if ok then\n local line = result\n if #lines == 0 then\n base_indent = line.indent\n line.indent = 0\n end\n table.insert(lines, line)\n else\n local err = result\n error(self:_error_msg(tostring(err), #lines + 1))\n end\n end\n\n -- Now iterate over the root elements, differing to `self:_parse_next()` to recurse into child elements.\n ---@type any\n local root_value = nil\n ---@type table|?\n local parent = nil\n local current_indent = 0\n local i = 1\n while i <= #lines do\n local line = lines[i]\n\n if line:is_empty() then\n -- Empty line, skip it.\n i = i + 1\n elseif line.indent == current_indent then\n local value\n local value_type\n i, value, value_type = self:_parse_next(lines, i)\n assert(value_type ~= YamlType.EmptyLine)\n if root_value == nil and line.indent == 0 then\n -- Set the root value.\n if value_type == YamlType.ArrayItem then\n root_value = { value }\n else\n root_value = value\n end\n\n -- The parent must always be a table (array or mapping), so set that to the root value now\n -- if we have a table.\n if type(root_value) == \"table\" then\n parent = root_value\n end\n elseif util.islist(parent) and value_type == YamlType.ArrayItem then\n -- Add value to parent array.\n parent[#parent + 1] = value\n elseif type(parent) == \"table\" and value_type == YamlType.Mapping then\n assert(parent ~= nil) -- for type checking\n -- Add value to parent mapping.\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if parent[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i, line.content))\n else\n parent[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value\", i, line.content))\n end\n else\n error(self:_error_msg(\"invalid indentation\", i))\n end\n current_indent = line.indent\n end\n\n return root_value\nend\n\n---Parse the next single item, recursing to child blocks if necessary.\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@param text string|?\n---@return integer, any, string\nParser._parse_next = function(self, lines, i, text)\n local line = lines[i]\n if text == nil then\n -- Skip empty lines.\n while line:is_empty() and i <= #lines do\n i = i + 1\n line = lines[i]\n end\n if line:is_empty() then\n return i, nil, YamlType.EmptyLine\n end\n text = util.strip_comments(line.content)\n end\n\n local _, ok, value\n\n -- First just check for a string enclosed in quotes.\n if util.has_enclosing_chars(text) then\n _, _, value = self:_parse_string(i, text)\n return i + 1, value, YamlType.Scalar\n end\n\n -- Check for array item, like `- foo`.\n ok, i, value = self:_try_parse_array_item(lines, i, text)\n if ok then\n return i, value, YamlType.ArrayItem\n end\n\n -- Check for a block string field, like `foo: |`.\n ok, i, value = self:_try_parse_block_string(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Check for any other `key: value` fields.\n ok, i, value = self:_try_parse_field(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Otherwise we have an inline value.\n local value_type\n value, value_type = self:_parse_inline_value(i, text)\n return i + 1, value, value_type\nend\n\n---@return vim.NIL|nil\nParser._new_null = function(self)\n if self.opts.luanil then\n return nil\n else\n return vim.NIL\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param msg string\n---@param line_num integer\n---@param line_text string|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nParser._error_msg = function(self, msg, line_num, line_text)\n local full_msg = \"[line=\" .. tostring(line_num) .. \"] \" .. msg\n if line_text ~= nil then\n full_msg = full_msg .. \" (text='\" .. line_text .. \"')\"\n end\n return full_msg\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_field = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n\n local _, key, value\n\n -- First look for start of mapping, array, block, etc, e.g. 'foo:'\n _, _, key = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*):$\")\n if not key then\n -- Then try inline field, e.g. 'foo: bar'\n _, _, key, value = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*): (.*)\")\n end\n\n value = value and vim.trim(value) or nil\n if value == \"\" then\n value = nil\n end\n\n if key ~= nil and value ~= nil then\n -- This is a mapping, e.g. `foo: 1`.\n local out = {}\n value = self:_parse_inline_value(i, value)\n local j = i + 1\n -- Check for multi-line string here.\n local next_line = lines[j]\n if type(value) == \"string\" and next_line ~= nil and next_line.indent > line.indent then\n local next_indent = next_line.indent\n while next_line ~= nil and next_line.indent == next_indent do\n local next_value_str = util.strip_comments(next_line.content)\n if string.len(next_value_str) > 0 then\n local next_value = self:_parse_inline_value(j, next_line.content)\n if type(next_value) ~= \"string\" then\n error(self:_error_msg(\"expected a string, found \" .. type(next_value), j, next_line.content))\n end\n value = value .. \" \" .. next_value\n end\n j = j + 1\n next_line = lines[j]\n end\n end\n out[key] = value\n return true, j, out\n elseif key ~= nil then\n local out = {}\n local next_line = lines[i + 1]\n local j = i + 1\n if next_line ~= nil and next_line.indent >= line.indent and vim.startswith(next_line.content, \"- \") then\n -- This is the start of an array.\n local array\n j, array = self:_parse_array(lines, j)\n out[key] = array\n elseif next_line ~= nil and next_line.indent > line.indent then\n -- This is the start of a mapping.\n local mapping\n j, mapping = self:_parse_mapping(j, lines)\n out[key] = mapping\n else\n -- This is an implicit null field.\n out[key] = self:_new_null()\n end\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_block_string = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n local _, _, block_key = string.find(text, \"([a-zA-Z0-9_-]+):%s?|\")\n if block_key ~= nil then\n local block_lines = {}\n local j = i + 1\n local next_line = lines[j]\n if next_line == nil then\n error(self:_error_msg(\"expected another line\", i, text))\n end\n local item_indent = next_line.indent\n while j <= #lines do\n next_line = lines[j]\n if next_line ~= nil and next_line.indent >= item_indent then\n j = j + 1\n table.insert(block_lines, util.lstrip_whitespace(next_line.raw_content, item_indent))\n else\n break\n end\n end\n local out = {}\n out[block_key] = table.concat(block_lines, \"\\n\")\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_array_item = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n if vim.startswith(text, \"- \") then\n local _, _, array_item_str = string.find(text, \"- (.*)\")\n local value\n -- Check for null entry.\n if array_item_str == \"\" then\n value = self:_new_null()\n i = i + 1\n else\n i, value = self:_parse_next(lines, i, array_item_str)\n end\n return true, i, value\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@return integer, any[]\nParser._parse_array = function(self, lines, i)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent and vim.startswith(line.content, \"- \") then\n local is_array_item, value\n is_array_item, i, value = self:_try_parse_array_item(lines, i)\n assert(is_array_item)\n out[#out + 1] = value\n elseif line:is_empty() then\n i = i + 1\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse an array but didn't find any entries\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@return integer, table\nParser._parse_mapping = function(self, i, lines)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent then\n local value, value_type\n i, value, value_type = self:_parse_next(lines, i)\n if value_type == YamlType.Mapping then\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if out[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i))\n else\n out[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value found found in table\", i))\n end\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse a mapping but didn't find any entries to parse\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return any, string\nParser._parse_inline_value = function(self, i, text)\n for parse_func_and_type in iter {\n { self._parse_number, YamlType.Scalar },\n { self._parse_null, YamlType.Scalar },\n { self._parse_boolean, YamlType.Scalar },\n { self._parse_inline_array, YamlType.Array },\n { self._parse_inline_mapping, YamlType.Mapping },\n { self._parse_string, YamlType.Scalar },\n } do\n local parse_func, parse_type = unpack(parse_func_and_type)\n local ok, errmsg, res = parse_func(self, i, text)\n if ok then\n return res, parse_type\n elseif errmsg ~= nil then\n error(errmsg)\n end\n end\n -- Should never get here because we always fall back to parsing as a string.\n error(self:_error_msg(\"unable to parse\", i))\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, any[]|?\nParser._parse_inline_array = function(self, i, text)\n local str\n if vim.startswith(text, \"[\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"]\") then\n str = string.sub(str, 1, -2)\n else\n return false, nil, nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n local item_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n item_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n item_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n item_str, str = util.next_item(str, { \",\" }, false)\n end\n if item_str == nil then\n return false, self:_error_msg(\"invalid inline array\", i, text), nil\n end\n out[#out + 1] = self:_parse_inline_value(i, item_str)\n\n if vim.startswith(str, \",\") then\n str = string.sub(str, 2)\n end\n str = util.lstrip_whitespace(str)\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, table|?\nParser._parse_inline_mapping = function(self, i, text)\n local str\n if vim.startswith(text, \"{\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"}\") then\n str = string.sub(str, 1, -2)\n else\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n -- Parse the key.\n local key_str\n key_str, str = util.next_item(str, { \":\" }, false)\n if key_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local _, _, key = self:_parse_string(i, key_str)\n\n -- Parse the value.\n str = util.lstrip_whitespace(str)\n local value_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n value_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n value_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n value_str, str = util.next_item(str, { \",\" }, false)\n end\n if value_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local value = self:_parse_inline_value(i, value_str)\n if out[key] == nil then\n out[key] = value\n else\n return false, self:_error_msg(\"duplicate key '\" .. key .. \"' found in inline mapping\", i, text), nil\n end\n\n if vim.startswith(str, \",\") then\n str = util.lstrip_whitespace(string.sub(str, 2))\n end\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, string\n---@diagnostic disable-next-line: unused-local\nParser._parse_string = function(self, i, text)\n if vim.startswith(text, [[\"]]) and vim.endswith(text, [[\"]]) then\n -- when the text is enclosed with double-quotes we need to un-escape certain characters.\n text = string.gsub(text, vim.pesc [[\\\"]], [[\"]])\n end\n return true, nil, util.strip_enclosing_chars(vim.trim(text))\nend\n\n---Parse a string value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return string\nParser.parse_string = function(self, text)\n local _, _, str = self:_parse_string(1, util.strip_comments(text))\n return str\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, number|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_number = function(self, i, text)\n local out = tonumber(text)\n if out == nil or util.isNan(out) then\n return false, nil, nil\n else\n return true, nil, out\n end\nend\n\n---Parse a number value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return number\nParser.parse_number = function(self, text)\n local ok, errmsg, res = self:_parse_number(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a number\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, boolean|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_boolean = function(self, i, text)\n if text == \"true\" then\n return true, nil, true\n elseif text == \"false\" then\n return true, nil, false\n else\n return false, nil, nil\n end\nend\n\n---Parse a boolean value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean\nParser.parse_boolean = function(self, text)\n local ok, errmsg, res = self:_parse_boolean(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a boolean\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean, string|?, vim.NIL|nil\n---@diagnostic disable-next-line: unused-local\nParser._parse_null = function(self, i, text)\n if text == \"null\" or text == \"\" then\n return true, nil, self:_new_null()\n else\n return false, nil, nil\n end\nend\n\n---Parse a NULL value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return vim.NIL|nil\nParser.parse_null = function(self, text)\n local ok, errmsg, res = self:_parse_null(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a null value\", 1, text)\n error(errmsg)\n else\n return res\n end\nend\n\n---Deserialize a YAML string.\nm.loads = function(str)\n local parser = m.new()\n return parser:parse(str)\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/commands/workspace.lua", "local log = require \"obsidian.log\"\nlocal Workspace = require \"obsidian.workspace\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.info(\"Current workspace: '%s' @ '%s'\", Obsidian.workspace.name, Obsidian.workspace.path)\n return\n end\n\n local options = {}\n for i, spec in ipairs(Obsidian.opts.workspaces) do\n local workspace = Workspace.new_from_spec(spec)\n if workspace == Obsidian.workspace then\n options[#options + 1] = string.format(\"*[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n else\n options[#options + 1] = string.format(\"[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n end\n end\n\n picker:pick(options, {\n prompt_title = \"Workspaces\",\n callback = function(workspace_str)\n local idx = tonumber(string.match(workspace_str, \"%*?%[(%d+)]\"))\n Workspace.switch(Obsidian.opts.workspaces[idx].name, { lock = true })\n end,\n })\n else\n Workspace.switch(data.args, { lock = true })\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/client.lua", "--- *obsidian-api*\n---\n--- The Obsidian.nvim Lua API.\n---\n--- ==============================================================================\n---\n--- Table of contents\n---\n---@toc\n\nlocal Path = require \"obsidian.path\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal Note = require \"obsidian.note\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal block_on = require(\"obsidian.async\").block_on\nlocal iter = vim.iter\n\n---@class obsidian.SearchOpts\n---\n---@field sort boolean|?\n---@field include_templates boolean|?\n---@field ignore_case boolean|?\n---@field default function?\n\n--- The Obsidian client is the main API for programmatically interacting with obsidian.nvim's features\n--- in Lua. To get the client instance, run:\n---\n--- `local client = require(\"obsidian\").get_client()`\n---\n---@toc_entry obsidian.Client\n---\n---@class obsidian.Client : obsidian.ABC\nlocal Client = {}\n\nlocal depreacted_lookup = {\n dir = \"dir\",\n buf_dir = \"buf_dir\",\n current_workspace = \"workspace\",\n opts = \"opts\",\n}\n\nClient.__index = function(_, k)\n if depreacted_lookup[k] then\n local msg = string.format(\n [[client.%s is depreacted, use Obsidian.%s instead.\nclient is going to be removed in the future as well.]],\n k,\n depreacted_lookup[k]\n )\n log.warn(msg)\n return Obsidian[depreacted_lookup[k]]\n elseif rawget(Client, k) then\n return rawget(Client, k)\n end\nend\n\n--- Create a new Obsidian client without additional setup.\n--- This is mostly used for testing. In practice you usually want to obtain the existing\n--- client through:\n---\n--- `require(\"obsidian\").get_client()`\n---\n---@return obsidian.Client\nClient.new = function()\n return setmetatable({}, Client)\nend\n\n--- Get the default search options.\n---\n---@return obsidian.SearchOpts\nClient.search_defaults = function()\n return {\n sort = false,\n include_templates = false,\n ignore_case = false,\n }\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---\n---@return obsidian.SearchOpts\n---\n---@private\nClient._search_opts_from_arg = function(self, opts)\n if opts == nil then\n opts = self:search_defaults()\n elseif type(opts) == \"boolean\" then\n local sort = opts\n opts = self:search_defaults()\n opts.sort = sort\n end\n return opts\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nClient._prepare_search_opts = function(self, opts, additional_opts)\n opts = self:_search_opts_from_arg(opts)\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n search.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = search.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---\n---@return function\n---\n---@private\nClient._search_iter_async = function(self, term, search_opts, find_opts)\n local tx, rx = channel.mpsc()\n local found = {}\n\n local function on_exit(_)\n tx.send(nil)\n end\n\n ---@param content_match MatchData\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n ---@param path_match string\n local function on_find_match(path_match)\n local path = Path.new(path_match):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n local cmds_done = 0 -- out of the two, one for 'search' and one for 'find'\n\n search.search_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n search.find_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(find_opts, { ignore_case = true }),\n on_find_match,\n on_exit\n )\n\n return function()\n while cmds_done < 2 do\n local value = rx.recv()\n if value == nil then\n cmds_done = cmds_done + 1\n else\n return value\n end\n end\n return nil\n end\nend\n\n---@class obsidian.TagLocation\n---\n---@field tag string The tag found.\n---@field note obsidian.Note The note instance where the tag was found.\n---@field path string|obsidian.Path The path to the note where the tag was found.\n---@field line integer The line number (1-indexed) where the tag was found.\n---@field text string The text (with whitespace stripped) of the line where the tag was found.\n---@field tag_start integer|? The index within 'text' where the tag starts.\n---@field tag_end integer|? The index within 'text' where the tag ends.\n\n--- Find all tags starting with the given search term(s).\n---\n---@param term string|string[] The search term.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|? }|?\n---\n---@return obsidian.TagLocation[]\nClient.find_tags = function(self, term, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_tags_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n--- An async version of 'find_tags()'.\n---\n---@param term string|string[] The search term.\n---@param callback fun(tags: obsidian.TagLocation[])\n---@param opts { search: obsidian.SearchOpts }|?\nClient.find_tags_async = function(self, term, callback, opts)\n opts = opts or {}\n\n ---@type string[]\n local terms\n if type(term) == \"string\" then\n terms = { term }\n else\n terms = term\n end\n\n for i, t in ipairs(terms) do\n if vim.startswith(t, \"#\") then\n terms[i] = string.sub(t, 2)\n end\n end\n\n terms = util.tbl_unique(terms)\n\n -- Maps paths to tag locations.\n ---@type table\n local path_to_tag_loc = {}\n -- Caches note objects.\n ---@type table\n local path_to_note = {}\n -- Caches code block locations.\n ---@type table\n local path_to_code_blocks = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n ---@param tag string\n ---@param path string|obsidian.Path\n ---@param note obsidian.Note\n ---@param lnum integer\n ---@param text string\n ---@param col_start integer|?\n ---@param col_end integer|?\n local add_match = function(tag, path, note, lnum, text, col_start, col_end)\n if vim.startswith(tag, \"#\") then\n tag = string.sub(tag, 2)\n end\n if not path_to_tag_loc[path] then\n path_to_tag_loc[path] = {}\n end\n path_to_tag_loc[path][#path_to_tag_loc[path] + 1] = {\n tag = tag,\n path = path,\n note = note,\n line = lnum,\n text = text,\n tag_start = col_start,\n tag_end = col_end,\n }\n end\n\n -- Wraps `Note.from_file_with_contents_async()` to return a table instead of a tuple and\n -- find the code blocks.\n ---@param path obsidian.Path\n ---@return { [1]: obsidian.Note, [2]: {[1]: integer, [2]: integer}[] }\n local load_note = function(path)\n local note, contents = Note.from_file_with_contents_async(path, { max_lines = Obsidian.opts.search_max_lines })\n return { note, search.find_code_blocks(contents) }\n end\n\n ---@param match_data MatchData\n local on_match = function(match_data)\n local path = Path.new(match_data.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local note = path_to_note[path]\n local code_blocks = path_to_code_blocks[path]\n if not note or not code_blocks then\n local ok, res = pcall(load_note, path)\n if ok then\n note, code_blocks = unpack(res)\n path_to_note[path] = note\n path_to_code_blocks[path] = code_blocks\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n local line_number = match_data.line_number + 1 -- match_data.line_number is 0-indexed\n\n -- check if the match was inside a code block.\n for block in iter(code_blocks) do\n if block[1] <= line_number and line_number <= block[2] then\n return\n end\n end\n\n local line = vim.trim(match_data.lines.text)\n local n_matches = 0\n\n -- check for tag in the wild of the form '#{tag}'\n for match in iter(search.find_tags(line)) do\n local m_start, m_end, _ = unpack(match)\n local tag = string.sub(line, m_start + 1, m_end)\n if string.match(tag, \"^\" .. search.Patterns.TagCharsRequired .. \"$\") then\n add_match(tag, path, note, match_data.line_number, line, m_start, m_end)\n end\n end\n\n -- check for tags in frontmatter\n if n_matches == 0 and note.tags ~= nil and (vim.startswith(line, \"tags:\") or string.match(line, \"%s*- \")) then\n for tag in iter(note.tags) do\n tag = tostring(tag)\n for _, t in ipairs(terms) do\n if string.len(t) == 0 or util.string_contains(tag:lower(), t:lower()) then\n add_match(tag, path, note, match_data.line_number, line)\n end\n end\n end\n end\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n local search_terms = {}\n for t in iter(terms) do\n if string.len(t) > 0 then\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsOptional .. t .. search.Patterns.TagCharsOptional\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n else\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsRequired\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \" .. search.Patterns.TagCharsRequired .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\" .. search.Patterns.TagCharsRequired\n end\n end\n\n search.search_async(\n Obsidian.dir,\n search_terms,\n self:_prepare_search_opts(opts.search, { ignore_case = true }),\n on_match,\n function(_)\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.TagLocation[]\n local tags_list = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results in path order.\n for _, path in ipairs(paths) do\n local tag_locs = path_to_tag_loc[path]\n if tag_locs ~= nil then\n table.sort(tag_locs, function(a, b)\n return a.line < b.line\n end)\n for _, tag_loc in ipairs(tag_locs) do\n tags_list[#tags_list + 1] = tag_loc\n end\n end\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return tags_list\n end, callback)\nend\n\n---@class obsidian.BacklinkMatches\n---\n---@field note obsidian.Note The note instance where the backlinks were found.\n---@field path string|obsidian.Path The path to the note where the backlinks were found.\n---@field matches obsidian.BacklinkMatch[] The backlinks within the note.\n\n---@class obsidian.BacklinkMatch\n---\n---@field line integer The line number (1-indexed) where the backlink was found.\n---@field text string The text of the line where the backlink was found.\n\n--- Find all backlinks to a note.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|?, anchor: string|?, block: string|? }|?\n---\n---@return obsidian.BacklinkMatches[]\nClient.find_backlinks = function(self, note, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_backlinks_async(note, cb, { search = opts.search, anchor = opts.anchor, block = opts.block })\n end, opts.timeout)\nend\n\n--- An async version of 'find_backlinks()'.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param callback fun(backlinks: obsidian.BacklinkMatches[])\n---@param opts { search: obsidian.SearchOpts, anchor: string|?, block: string|? }|?\nClient.find_backlinks_async = function(self, note, callback, opts)\n opts = opts or {}\n\n ---@type string|?\n local block = opts.block and util.standardize_block(opts.block) or nil\n local anchor = opts.anchor and util.standardize_anchor(opts.anchor) or nil\n ---@type obsidian.note.HeaderAnchor|?\n local anchor_obj\n if anchor then\n anchor_obj = note:resolve_anchor_link(anchor)\n end\n\n -- Maps paths (string) to note object and a list of matches.\n ---@type table\n local backlink_matches = {}\n ---@type table\n local path_to_note = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n -- Prepare search terms.\n local search_terms = {}\n local note_path = Path.new(note.path)\n for raw_ref in iter { tostring(note.id), note_path.name, note_path.stem, note.path:vault_relative_path() } do\n for ref in\n iter(util.tbl_unique {\n raw_ref,\n util.urlencode(tostring(raw_ref)),\n util.urlencode(tostring(raw_ref), { keep_path_sep = true }),\n })\n do\n if ref ~= nil then\n if anchor == nil and block == nil then\n -- Wiki links without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", ref)\n search_terms[#search_terms + 1] = string.format(\"[[%s|\", ref)\n -- Markdown link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s)\", ref)\n -- Markdown link without anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s)\", ref)\n -- Wiki links with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif anchor then\n -- Note: Obsidian allow a lot of different forms of anchor links, so we can't assume\n -- it's the standardized form here.\n -- Wiki links with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif block then\n -- Wiki links with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", ref, block)\n -- Markdown link with block.\n search_terms[#search_terms + 1] = string.format(\"(%s#%s\", ref, block)\n -- Markdown link with block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#%s\", ref, block)\n end\n end\n end\n end\n for alias in iter(note.aliases) do\n if anchor == nil and block == nil then\n -- Wiki link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", alias)\n -- Wiki link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif anchor then\n -- Wiki link with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif block then\n -- Wiki link with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", alias, block)\n end\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = opts.anchor ~= nil,\n collect_blocks = opts.block ~= nil,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n ---@param match MatchData\n local function on_match(match)\n local path = Path.new(match.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local n = path_to_note[path]\n if not n then\n local ok, res = pcall(Note.from_file_async, path, load_opts)\n if ok then\n n = res\n path_to_note[path] = n\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n if anchor then\n -- Check for a match with the anchor.\n -- NOTE: no need to do this with blocks, since blocks are standardized.\n local match_text = string.sub(match.lines.text, match.submatches[1].start)\n local link_location = util.parse_link(match_text)\n if not link_location then\n log.error(\"Failed to parse reference from '%s' ('%s')\", match_text, match)\n return\n end\n\n local anchor_link = select(2, util.strip_anchor_links(link_location))\n if not anchor_link then\n return\n end\n\n if anchor_link ~= anchor and anchor_obj ~= nil then\n local resolved_anchor = note:resolve_anchor_link(anchor_link)\n if resolved_anchor == nil or resolved_anchor.header ~= anchor_obj.header then\n return\n end\n end\n end\n\n ---@type obsidian.BacklinkMatch[]\n local line_matches = backlink_matches[path]\n if line_matches == nil then\n line_matches = {}\n backlink_matches[path] = line_matches\n end\n\n line_matches[#line_matches + 1] = {\n line = match.line_number,\n text = util.rstrip_whitespace(match.lines.text),\n }\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n -- Execute search.\n search.search_async(\n Obsidian.dir,\n util.tbl_unique(search_terms),\n self:_prepare_search_opts(opts.search, { fixed_strings = true, ignore_case = true }),\n on_match,\n function()\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.BacklinkMatches[]\n local results = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results.\n for i, path in ipairs(paths) do\n results[i] = { note = path_to_note[path], path = path, matches = backlink_matches[path] }\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return vim.tbl_filter(function(bl)\n return bl.matches ~= nil\n end, results)\n end, callback)\nend\n\n--- Gather a list of all tags in the vault. If 'term' is provided, only tags that partially match the search\n--- term will be included.\n---\n---@param term string|? An optional search term to match tags\n---@param timeout integer|? Timeout in milliseconds\n---\n---@return string[]\nClient.list_tags = function(self, term, timeout)\n local tags = {}\n for _, tag_loc in ipairs(self:find_tags(term and term or \"\", { timeout = timeout })) do\n tags[tag_loc.tag] = true\n end\n return vim.tbl_keys(tags)\nend\n\n--- An async version of 'list_tags()'.\n---\n---@param term string|?\n---@param callback fun(tags: string[])\nClient.list_tags_async = function(self, term, callback)\n self:find_tags_async(term and term or \"\", function(tag_locations)\n local tags = {}\n for _, tag_loc in ipairs(tag_locations) do\n local tag = tag_loc.tag:lower()\n if not tags[tag] then\n tags[tag] = true\n end\n end\n callback(vim.tbl_keys(tags))\n end)\nend\n\nreturn Client\n"], ["/obsidian.nvim/lua/obsidian/ui.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal M = {}\n\nlocal NAMESPACE = \"ObsidianUI\"\n\n---@param ui_opts obsidian.config.UIOpts\nlocal function install_hl_groups(ui_opts)\n for group_name, opts in pairs(ui_opts.hl_groups) do\n vim.api.nvim_set_hl(0, group_name, opts)\n end\nend\n\n-- We cache marks locally to help avoid redrawing marks when its not necessary. The main reason\n-- we need to do this is because the conceal char we get back from `nvim_buf_get_extmarks()` gets mangled.\n-- For example, \"󰄱\" is turned into \"1\\1\\15\".\n-- TODO: if we knew how to un-mangle the conceal char we wouldn't need the cache.\n\nM._buf_mark_cache = vim.defaulttable()\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\n---@return ExtMark|?\nlocal function cache_get(bufnr, ns_id, mark_id)\n local buf_ns_cache = M._buf_mark_cache[bufnr][ns_id]\n return buf_ns_cache[mark_id]\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark ExtMark\n---@return ExtMark|?\nlocal function cache_set(bufnr, ns_id, mark)\n assert(mark.id ~= nil)\n M._buf_mark_cache[bufnr][ns_id][mark.id] = mark\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\nlocal function cache_evict(bufnr, ns_id, mark_id)\n M._buf_mark_cache[bufnr][ns_id][mark_id] = nil\nend\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function cache_clear(bufnr, ns_id)\n M._buf_mark_cache[bufnr][ns_id] = {}\nend\n\n---@class ExtMark : obsidian.ABC\n---@field id integer|? ID of the mark, only set for marks that are actually materialized in the buffer.\n---@field row integer 0-based row index to place the mark.\n---@field col integer 0-based col index to place the mark.\n---@field opts ExtMarkOpts Optional parameters passed directly to `nvim_buf_set_extmark()`.\nlocal ExtMark = abc.new_class {\n __eq = function(a, b)\n return a.row == b.row and a.col == b.col and a.opts == b.opts\n end,\n}\n\nM.ExtMark = ExtMark\n\n---@class ExtMarkOpts : obsidian.ABC\n---@field end_row integer\n---@field end_col integer\n---@field conceal string|?\n---@field hl_group string|?\n---@field spell boolean|?\nlocal ExtMarkOpts = abc.new_class()\n\nM.ExtMarkOpts = ExtMarkOpts\n\n---@param data table\n---@return ExtMarkOpts\nExtMarkOpts.from_tbl = function(data)\n local self = ExtMarkOpts.init()\n self.end_row = data.end_row\n self.end_col = data.end_col\n self.conceal = data.conceal\n self.hl_group = data.hl_group\n self.spell = data.spell\n return self\nend\n\n---@param self ExtMarkOpts\n---@return table\nExtMarkOpts.to_tbl = function(self)\n return {\n end_row = self.end_row,\n end_col = self.end_col,\n conceal = self.conceal,\n hl_group = self.hl_group,\n spell = self.spell,\n }\nend\n\n---@param id integer|?\n---@param row integer\n---@param col integer\n---@param opts ExtMarkOpts\n---@return ExtMark\nExtMark.new = function(id, row, col, opts)\n local self = ExtMark.init()\n self.id = id\n self.row = row\n self.col = col\n self.opts = opts\n return self\nend\n\n---Materialize the ExtMark if needed. After calling this the 'id' will be set if it wasn't already.\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return ExtMark\nExtMark.materialize = function(self, bufnr, ns_id)\n if self.id == nil then\n self.id = vim.api.nvim_buf_set_extmark(bufnr, ns_id, self.row, self.col, self.opts:to_tbl())\n end\n cache_set(bufnr, ns_id, self)\n return self\nend\n\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return boolean\nExtMark.clear = function(self, bufnr, ns_id)\n if self.id ~= nil then\n cache_evict(bufnr, ns_id, self.id)\n return vim.api.nvim_buf_del_extmark(bufnr, ns_id, self.id)\n else\n return false\n end\nend\n\n---Collect all existing (materialized) marks within a region.\n---@param bufnr integer\n---@param ns_id integer\n---@param region_start integer|integer[]|?\n---@param region_end integer|integer[]|?\n---@return ExtMark[]\nExtMark.collect = function(bufnr, ns_id, region_start, region_end)\n region_start = region_start and region_start or 0\n region_end = region_end and region_end or -1\n local marks = {}\n for data in iter(vim.api.nvim_buf_get_extmarks(bufnr, ns_id, region_start, region_end, { details = true })) do\n local mark = ExtMark.new(data[1], data[2], data[3], ExtMarkOpts.from_tbl(data[4]))\n -- NOTE: since the conceal char we get back from `nvim_buf_get_extmarks()` is mangled, e.g.\n -- \"󰄱\" is turned into \"1\\1\\15\", we used the cached version.\n local cached_mark = cache_get(bufnr, ns_id, mark.id)\n if cached_mark ~= nil then\n mark.opts.conceal = cached_mark.opts.conceal\n end\n cache_set(bufnr, ns_id, mark)\n marks[#marks + 1] = mark\n end\n return marks\nend\n\n---Clear all existing (materialized) marks with a line region.\n---@param bufnr integer\n---@param ns_id integer\n---@param line_start integer\n---@param line_end integer\nExtMark.clear_range = function(bufnr, ns_id, line_start, line_end)\n return vim.api.nvim_buf_clear_namespace(bufnr, ns_id, line_start, line_end)\nend\n\n---Clear all existing (materialized) marks on a line.\n---@param bufnr integer\n---@param ns_id integer\n---@param line integer\nExtMark.clear_line = function(bufnr, ns_id, line)\n return ExtMark.clear_range(bufnr, ns_id, line, line + 1)\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_check_extmarks(marks, line, lnum, ui_opts)\n for char, opts in pairs(ui_opts.checkboxes) do\n if string.match(line, \"^%s*- %[\" .. vim.pesc(char) .. \"%]\") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 5,\n conceal = opts.char,\n hl_group = opts.hl_group,\n }\n )\n return marks\n end\n end\n\n if ui_opts.bullets ~= nil and string.match(line, \"^%s*[-%*%+] \") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 1,\n conceal = ui_opts.bullets.char,\n hl_group = ui_opts.bullets.hl_group,\n }\n )\n end\n\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_ref_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_refs(line, { include_naked_urls = true, include_tags = true, include_block_ids = true })\n for match in iter(matches) do\n local m_start, m_end, m_type = unpack(match)\n if m_type == search.RefTypes.WikiWithAlias then\n -- Reference of the form [[xxx|yyy]]\n local pipe_loc = string.find(line, \"|\", m_start, true)\n assert(pipe_loc)\n -- Conceal everything from '[[' up to '|'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = pipe_loc,\n conceal = \"\",\n }\n )\n -- Highlight the alias 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n pipe_loc,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Wiki then\n -- Reference of the form [[xxx]]\n -- Conceal the opening '[['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'xxx'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Markdown then\n -- Reference of the form [yyy](xxx)\n local closing_bracket_loc = string.find(line, \"]\", m_start, true)\n assert(closing_bracket_loc)\n local is_url = util.is_url(string.sub(line, closing_bracket_loc + 2, m_end - 1))\n -- Conceal the opening '['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc - 1,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the ']('\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc + 1,\n conceal = is_url and \" \" or \"\",\n }\n )\n -- Conceal the URL part 'xxx' with the external URL character\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 1,\n conceal = is_url and ui_opts.external_link_icon.char or \"\",\n hl_group = ui_opts.external_link_icon.hl_group,\n }\n )\n -- Conceal the closing ')'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = is_url and \" \" or \"\",\n }\n )\n elseif m_type == search.RefTypes.NakedUrl then\n -- A \"naked\" URL is just a URL by itself, like 'https://github.com/'\n local domain_start_loc = string.find(line, \"://\", m_start, true)\n assert(domain_start_loc)\n domain_start_loc = domain_start_loc + 3\n -- Conceal the \"https?://\" part\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = domain_start_loc - 1,\n conceal = \"\",\n }\n )\n -- Highlight the whole thing.\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.Tag then\n -- A tag is like '#tag'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.tags.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.BlockID then\n -- A block ID, like '^hello-world'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.block_ids.hl_group,\n spell = false,\n }\n )\n end\n end\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_highlight(line)\n for match in iter(matches) do\n local m_start, m_end, _ = unpack(match)\n -- Conceal opening '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight text in the middle\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.highlight_text.hl_group,\n spell = false,\n }\n )\n -- Conceal closing '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n end\n return marks\nend\n\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal get_line_marks = function(line, lnum, ui_opts)\n local marks = {}\n get_line_check_extmarks(marks, line, lnum, ui_opts)\n get_line_ref_extmarks(marks, line, lnum, ui_opts)\n get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n return marks\nend\n\n---@param bufnr integer\n---@param ui_opts obsidian.config.UIOpts\nlocal function update_extmarks(bufnr, ns_id, ui_opts)\n local start_time = vim.uv.hrtime()\n local n_marks_added = 0\n local n_marks_cleared = 0\n\n -- Collect all current marks, grouped by line.\n local cur_marks_by_line = vim.defaulttable()\n for mark in iter(ExtMark.collect(bufnr, ns_id)) do\n local cur_line_marks = cur_marks_by_line[mark.row]\n cur_line_marks[#cur_line_marks + 1] = mark\n end\n\n -- Iterate over lines (skipping code blocks) and update marks.\n local inside_code_block = false\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, true)\n for i, line in ipairs(lines) do\n local lnum = i - 1\n local cur_line_marks = cur_marks_by_line[lnum]\n\n local function clear_line()\n ExtMark.clear_line(bufnr, ns_id, lnum)\n n_marks_cleared = n_marks_cleared + #cur_line_marks\n for mark in iter(cur_line_marks) do\n cache_evict(bufnr, ns_id, mark.id)\n end\n end\n\n -- Check if inside a code block or at code block boundary. If not, update marks.\n if string.match(line, \"^%s*```[^`]*$\") then\n inside_code_block = not inside_code_block\n -- Remove any existing marks here on the boundary of a code block.\n clear_line()\n elseif not inside_code_block then\n -- Get all marks that should be materialized.\n -- Some of these might already be materialized, which we'll check below and avoid re-drawing\n -- if that's the case.\n local new_line_marks = get_line_marks(line, lnum, ui_opts)\n if #new_line_marks > 0 then\n -- Materialize new marks.\n for mark in iter(new_line_marks) do\n if not vim.list_contains(cur_line_marks, mark) then\n mark:materialize(bufnr, ns_id)\n n_marks_added = n_marks_added + 1\n end\n end\n\n -- Clear old marks.\n for mark in iter(cur_line_marks) do\n if not vim.list_contains(new_line_marks, mark) then\n mark:clear(bufnr, ns_id)\n n_marks_cleared = n_marks_cleared + 1\n end\n end\n else\n -- Remove any existing marks here since there are no new marks.\n clear_line()\n end\n else\n -- Remove any existing marks here since we're inside a code block.\n clear_line()\n end\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n log.debug(\"Added %d new marks, cleared %d old marks in %dms\", n_marks_added, n_marks_cleared, runtime)\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param bufnr integer|?\n---@return boolean\nlocal function should_update(ui_opts, bufnr)\n if ui_opts.enable == false then\n return false\n end\n\n bufnr = bufnr or 0\n\n if not vim.endswith(vim.api.nvim_buf_get_name(bufnr), \".md\") then\n return false\n end\n\n if ui_opts.max_file_length ~= nil and vim.fn.line \"$\" > ui_opts.max_file_length then\n return false\n end\n\n return true\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param throttle boolean\n---@return function\nlocal function get_extmarks_autocmd_callback(ui_opts, throttle)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n\n local callback = function(ev)\n if not should_update(ui_opts, ev.bufnr) then\n return\n end\n update_extmarks(ev.buf, ns_id, ui_opts)\n end\n\n if throttle then\n return require(\"obsidian.async\").throttle(callback, ui_opts.update_debounce)\n else\n return callback\n end\nend\n\n---Manually update extmarks.\n---\n---@param bufnr integer|?\nM.update = function(bufnr)\n bufnr = bufnr or 0\n local ui_opts = Obsidian.opts.ui\n if not should_update(ui_opts, bufnr) then\n return\n end\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n update_extmarks(bufnr, ns_id, ui_opts)\nend\n\n---@param workspace obsidian.Workspace\n---@param ui_opts obsidian.config.UIOpts\nM.setup = function(workspace, ui_opts)\n if ui_opts.enable == false then\n return\n end\n\n local group = vim.api.nvim_create_augroup(\"ObsidianUI\" .. workspace.name, { clear = true })\n\n install_hl_groups(ui_opts)\n\n local pattern = tostring(workspace.root) .. \"/**.md\"\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = function()\n local conceallevel = vim.opt_local.conceallevel:get()\n\n if (conceallevel < 1 or conceallevel > 2) and not ui_opts.ignore_conceal_warn then\n log.warn_once(\n \"Obsidian additional syntax features require 'conceallevel' to be set to 1 or 2, \"\n .. \"but you have 'conceallevel' set to '%s'.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/issues/286 for more details.\\n\"\n .. \"If you don't want Obsidian's additional UI features, you can disable them and suppress \"\n .. \"this warning by setting 'ui.enable = false' in your Obsidian nvim config.\",\n conceallevel\n )\n end\n\n -- delete the autocommand\n return true\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, false),\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\", \"TextChanged\", \"TextChangedI\", \"TextChangedP\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, true),\n })\n\n vim.api.nvim_create_autocmd({ \"BufUnload\" }, {\n group = group,\n pattern = pattern,\n callback = function(ev)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n cache_clear(ev.buf, ns_id)\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/paste_img.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal img = require \"obsidian.img_paste\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not img.clipboard_is_img() then\n return log.err \"There is no image data in the clipboard\"\n end\n\n ---@type string|?\n local default_name = Obsidian.opts.attachments.img_name_func()\n\n local should_confirm = Obsidian.opts.attachments.confirm_img_paste\n\n ---@type string\n local fname = vim.trim(data.args)\n\n -- Get filename to save to.\n if fname == nil or fname == \"\" then\n if default_name and not should_confirm then\n fname = default_name\n else\n local input = api.input(\"Enter file name: \", { default = default_name, completion = \"file\" })\n if not input then\n return log.warn \"Paste aborted\"\n end\n fname = input\n end\n end\n\n local path = api.resolve_image_path(fname)\n\n img.paste(path)\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/new.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.NewNoteSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\nlocal NewNoteSourceCompletionContext = abc.new_class()\n\nNewNoteSourceCompletionContext.new = function()\n return NewNoteSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.NewNoteSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal NewNoteSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.NewNoteSourceBase\nNewNoteSourceBase.new = function()\n return NewNoteSourceBase.init()\nend\n\nNewNoteSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = NewNoteSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n ---@type string|?\n local block_link\n cc.search, block_link = util.strip_block_links(cc.search)\n\n ---@type string|?\n local anchor_link\n cc.search, anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, do nothing.\n if not block_link and vim.endswith(cc.search, \"#^\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- If anchor link is incomplete, do nothing.\n if not anchor_link and vim.endswith(cc.search, \"#\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Probably just a block/anchor link within current note.\n if string.len(cc.search) == 0 then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Create a mock block.\n ---@type obsidian.note.Block|?\n local block\n if block_link then\n block = { block = \"\", id = util.standardize_block(block_link), line = 1 }\n end\n\n -- Create a mock anchor.\n ---@type obsidian.note.HeaderAnchor|?\n local anchor\n if anchor_link then\n anchor = { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 }\n end\n\n ---@type { label: string, note: obsidian.Note, template: string|? }[]\n local new_notes_opts = {}\n\n local note = Note.create { title = cc.search }\n if note.title and string.len(note.title) > 0 then\n new_notes_opts[#new_notes_opts + 1] = { label = cc.search, note = note }\n end\n\n -- Check for datetime macros.\n for _, dt_offset in ipairs(util.resolve_date_macro(cc.search)) do\n if dt_offset.cadence == \"daily\" then\n note = require(\"obsidian.daily\").daily(dt_offset.offset, { no_write = true })\n if not note:exists() then\n new_notes_opts[#new_notes_opts + 1] =\n { label = dt_offset.macro, note = note, template = Obsidian.opts.daily_notes.template }\n end\n end\n end\n\n -- Completion items.\n local items = {}\n\n for _, new_note_opts in ipairs(new_notes_opts) do\n local new_note = new_note_opts.note\n\n assert(new_note.path)\n\n ---@type obsidian.config.LinkStyle, string\n local link_style, label\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n label = string.format(\"[[%s]] (create)\", new_note_opts.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n label = string.format(\"[%s](…) (create)\", new_note_opts.label)\n else\n error \"not implemented\"\n end\n\n local new_text = api.format_link(new_note, { link_style = link_style, anchor = anchor, block = block })\n local documentation = {\n kind = \"markdown\",\n value = new_note:display_info {\n label = \"Create: \" .. new_text,\n },\n }\n\n items[#items + 1] = {\n documentation = documentation,\n sortText = new_note_opts.label,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = new_text,\n range = {\n start = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n data = {\n note = new_note,\n template = new_note_opts.template,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction NewNoteSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if cc.search ~= nil then\n cc.search = util.lstrip_whitespace(cc.search)\n end\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n return true\nend\n\n--- Runs a generalized version of the execute method\n---@param item any\n---@return table|? callback_return_value\nfunction NewNoteSourceBase:process_execute(item)\n local data = item.data\n\n if data == nil then\n return nil\n end\n\n -- Make sure `data.note` is actually an `obsidian.Note` object. If it gets serialized at some\n -- point (seems to happen on Linux), it will lose its metatable.\n if not Note.is_note_obj(data.note) then\n data.note = setmetatable(data.note, Note.mt)\n data.note.path = setmetatable(data.note.path, Path.mt)\n end\n\n data.note:write { template = data.template }\n return {}\nend\n\nreturn NewNoteSourceBase\n"], ["/obsidian.nvim/minimal.lua", "vim.env.LAZY_STDPATH = \".repro\"\nload(vim.fn.system \"curl -s https://raw.githubusercontent.com/folke/lazy.nvim/main/bootstrap.lua\")()\n\nvim.fn.mkdir(\".repro/vault\", \"p\")\n\nvim.o.conceallevel = 2\n\nlocal plugins = {\n {\n \"obsidian-nvim/obsidian.nvim\",\n dependencies = { \"nvim-lua/plenary.nvim\" },\n opts = {\n completion = {\n blink = true,\n nvim_cmp = false,\n },\n workspaces = {\n {\n name = \"test\",\n path = vim.fs.joinpath(vim.uv.cwd(), \".repro\", \"vault\"),\n },\n },\n },\n },\n\n -- **Choose your renderer**\n -- { \"MeanderingProgrammer/render-markdown.nvim\", dependencies = { \"echasnovski/mini.icons\" }, opts = {} },\n -- { \"OXY2DEV/markview.nvim\", lazy = false },\n\n -- **Choose your picker**\n -- \"nvim-telescope/telescope.nvim\",\n -- \"folke/snacks.nvim\",\n -- \"ibhagwan/fzf-lua\",\n -- \"echasnovski/mini.pick\",\n\n -- **Choose your completion engine**\n -- {\n -- \"hrsh7th/nvim-cmp\",\n -- config = function()\n -- local cmp = require \"cmp\"\n -- cmp.setup {\n -- mapping = cmp.mapping.preset.insert {\n -- [\"\"] = cmp.mapping.abort(),\n -- [\"\"] = cmp.mapping.confirm { select = true },\n -- },\n -- }\n -- end,\n -- },\n -- {\n -- \"saghen/blink.cmp\",\n -- opts = {\n -- fuzzy = { implementation = \"lua\" }, -- no need to build binary\n -- keymap = {\n -- preset = \"default\",\n -- },\n -- },\n -- },\n}\n\nrequire(\"lazy.minit\").repro { spec = plugins }\n\nvim.cmd \"checkhealth obsidian\"\n"], ["/obsidian.nvim/lua/obsidian/img_paste.lua", "local Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal run_job = require(\"obsidian.async\").run_job\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\n\nlocal M = {}\n\n-- Image pasting adapted from https://github.com/ekickx/clipboard-image.nvim\n\n---@return string\nlocal function get_clip_check_command()\n local check_cmd\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n check_cmd = \"xclip -selection clipboard -o -t TARGETS\"\n elseif display_server == \"wayland\" then\n check_cmd = \"wl-paste --list-types\"\n end\n elseif this_os == api.OSType.Darwin then\n check_cmd = \"pngpaste -b 2>&1\"\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n check_cmd = 'powershell.exe \"Get-Clipboard -Format Image\"'\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return check_cmd\nend\n\n--- Check if clipboard contains image data.\n---\n---@return boolean\nfunction M.clipboard_is_img()\n local check_cmd = get_clip_check_command()\n local result_string = vim.fn.system(check_cmd)\n local content = vim.split(result_string, \"\\n\")\n\n local is_img = false\n -- See: [Data URI scheme](https://en.wikipedia.org/wiki/Data_URI_scheme)\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n if vim.tbl_contains(content, \"image/png\") then\n is_img = true\n elseif vim.tbl_contains(content, \"text/uri-list\") then\n local success =\n os.execute \"wl-paste --type text/uri-list | sed 's|file://||' | head -n1 | tr -d '[:space:]' | xargs -I{} sh -c 'wl-copy < \\\"$1\\\"' _ {}\"\n is_img = success == 0\n end\n elseif this_os == api.OSType.Darwin then\n is_img = string.sub(content[1], 1, 9) == \"iVBORw0KG\" -- Magic png number in base64\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n is_img = content ~= nil\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return is_img\nend\n\n--- TODO: refactor with run_job?\n\n--- Save image from clipboard to `path`.\n---@param path string\n---\n---@return boolean|integer|? result\nlocal function save_clipboard_image(path)\n local this_os = api.get_os()\n\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local cmd\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n cmd = string.format(\"xclip -selection clipboard -t image/png -o > '%s'\", path)\n elseif display_server == \"wayland\" then\n cmd = string.format(\"wl-paste --no-newline --type image/png > %s\", vim.fn.shellescape(path))\n return run_job { \"bash\", \"-c\", cmd }\n end\n\n local result = os.execute(cmd)\n if type(result) == \"number\" and result > 0 then\n return false\n else\n return result\n end\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n local cmd = 'powershell.exe -c \"'\n .. string.format(\"(get-clipboard -format image).save('%s', 'png')\", string.gsub(path, \"/\", \"\\\\\"))\n .. '\"'\n return os.execute(cmd)\n elseif this_os == api.OSType.Darwin then\n return run_job { \"pngpaste\", path }\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\nend\n\n--- @param path string image_path The absolute path to the image file.\nM.paste = function(path)\n if util.contains_invalid_characters(path) then\n log.warn \"Links will not work with file names containing any of these characters in Obsidian: # ^ [ ] |\"\n end\n\n ---@diagnostic disable-next-line: cast-local-type\n path = Path.new(path)\n\n -- Make sure fname ends with \".png\"\n if not path.suffix then\n ---@diagnostic disable-next-line: cast-local-type\n path = path:with_suffix \".png\"\n elseif path.suffix ~= \".png\" then\n return log.err(\"invalid suffix for image name '%s', must be '.png'\", path.suffix)\n end\n\n if Obsidian.opts.attachments.confirm_img_paste then\n -- Get confirmation from user.\n if not api.confirm(\"Saving image to '\" .. tostring(path) .. \"'. Do you want to continue?\") then\n return log.warn \"Paste aborted\"\n end\n end\n\n -- Ensure parent directory exists.\n assert(path:parent()):mkdir { exist_ok = true, parents = true }\n\n -- Paste image.\n local result = save_clipboard_image(tostring(path))\n if result == false then\n log.err \"Failed to save image\"\n return\n end\n\n local img_text = Obsidian.opts.attachments.img_text_func(path)\n vim.api.nvim_put({ img_text }, \"c\", true, false)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/quick_switch.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_notes()\n else\n search.resolve_note_async(data.args, function(note)\n note:open()\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/async.lua", "local abc = require \"obsidian.abc\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal uv = vim.uv\n\nlocal M = {}\n\n---An abstract class that mimics Python's `concurrent.futures.Executor` class.\n---@class obsidian.Executor : obsidian.ABC\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal Executor = abc.new_class()\n\n---@return obsidian.Executor\nExecutor.new = function()\n local self = Executor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback for the executor to run.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local,unused-vararg\nExecutor.submit = function(self, fn, callback, ...)\n error \"not implemented\"\nend\n\n---Map a function over a generator or array of task args, or the keys and values in a regular table.\n---The callback is called with an array of the results once all tasks have finished.\n---The order of the results passed to the callback will be the same as the order of the corresponding task args.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param task_args table[]|table|function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nExecutor.map = function(self, fn, task_args, callback)\n local results = {}\n local num_tasks = 0\n local tasks_completed = 0\n local all_submitted = false\n local tx, rx = channel.oneshot()\n\n local function collect_results()\n rx()\n return results\n end\n\n local function get_task_done_fn(i)\n return function(...)\n tasks_completed = tasks_completed + 1\n results[i] = { ... }\n if all_submitted and tasks_completed == num_tasks then\n tx()\n end\n end\n end\n\n if type(task_args) == \"table\" and util.islist(task_args) then\n num_tasks = #task_args\n for i, args in ipairs(task_args) do\n if i == #task_args then\n all_submitted = true\n end\n if type(args) ~= \"table\" then\n args = { args }\n end\n self:submit(fn, get_task_done_fn(i), unpack(args))\n end\n elseif type(task_args) == \"table\" then\n num_tasks = vim.tbl_count(task_args)\n local i = 0\n for k, v in pairs(task_args) do\n i = i + 1\n if i == #task_args then\n all_submitted = true\n end\n self:submit(fn, get_task_done_fn(i), k, v)\n end\n elseif type(task_args) == \"function\" then\n local i = 0\n local args = { task_args() }\n local next_args = { task_args() }\n while args[1] ~= nil do\n if next_args[1] == nil then\n all_submitted = true\n end\n i = i + 1\n num_tasks = num_tasks + 1\n self:submit(fn, get_task_done_fn(i), unpack(args))\n args = next_args\n next_args = { task_args() }\n end\n else\n error(string.format(\"unexpected type '%s' for 'task_args'\", type(task_args)))\n end\n\n if num_tasks == 0 then\n if callback ~= nil then\n callback {}\n end\n else\n async.run(collect_results, callback and callback or function(_) end)\n end\nend\n\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param pause_fn function(integer)\nExecutor._join = function(self, timeout, pause_fn)\n local start_time = uv.hrtime() / 1000000 -- ns -> ms\n local pause_for = 100\n if timeout ~= nil then\n pause_for = math.min(timeout / 2, pause_for)\n end\n while self.tasks_pending > 0 or self.tasks_running > 0 do\n pause_fn(pause_for)\n if timeout ~= nil and (uv.hrtime() / 1000000) - start_time > timeout then\n error \"Timeout error from Executor.join()\"\n end\n end\nend\n\n---Block Neovim until all currently running tasks have completed, waiting at most `timeout` milliseconds\n---before raising a timeout error.\n---\n---This is useful in testing, but in general you want to avoid blocking Neovim.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join = function(self, timeout)\n self:_join(timeout, vim.wait)\nend\n\n---An async version of `.join()`.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join_async = function(self, timeout)\n self:_join(timeout, async.util.sleep)\nend\n\n---Run the callback when the executor finishes all tasks.\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param callback function\nExecutor.join_and_then = function(self, timeout, callback)\n async.run(function()\n self:join_async(timeout)\n end, callback)\nend\n\n---An Executor that uses coroutines to run user functions concurrently.\n---@class obsidian.AsyncExecutor : obsidian.Executor\n---@field max_workers integer|?\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal AsyncExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"AsyncExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.AsyncExecutor = AsyncExecutor\n\n---@param max_workers integer|?\n---@return obsidian.AsyncExecutor\nAsyncExecutor.new = function(max_workers)\n local self = AsyncExecutor.init()\n if max_workers == nil then\n max_workers = 10\n elseif max_workers < 0 then\n max_workers = nil\n elseif max_workers == 0 then\n max_workers = 1\n end\n self.max_workers = max_workers\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.AsyncExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nAsyncExecutor.submit = function(self, fn, callback, ...)\n self.tasks_pending = self.tasks_pending + 1\n local args = { ... }\n async.run(function()\n if self.max_workers ~= nil then\n while self.tasks_running >= self.max_workers do\n async.util.sleep(20)\n end\n end\n self.tasks_pending = self.tasks_pending - 1\n self.tasks_running = self.tasks_running + 1\n return fn(unpack(args))\n end, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\nend\n\n---A multi-threaded Executor which uses the Libuv threadpool.\n---@class obsidian.ThreadPoolExecutor : obsidian.Executor\n---@field tasks_running integer\nlocal ThreadPoolExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"ThreadPoolExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.ThreadPoolExecutor = ThreadPoolExecutor\n\n---@return obsidian.ThreadPoolExecutor\nThreadPoolExecutor.new = function()\n local self = ThreadPoolExecutor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.ThreadPoolExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nThreadPoolExecutor.submit = function(self, fn, callback, ...)\n self.tasks_running = self.tasks_running + 1\n local ctx = uv.new_work(fn, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\n ctx:queue(...)\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@param sync boolean\nlocal init_job = function(cmds, on_stdout, on_exit, sync)\n local stderr_lines = false\n\n local on_obj = function(obj)\n --- NOTE: commands like `rg` return a non-zero exit code when there are no matches, which is okay.\n --- So we only log no-zero exit codes as errors when there's also stderr lines.\n if obj.code > 0 and stderr_lines then\n log.err(\"Command '%s' exited with non-zero code %s. See logs for stderr.\", cmds, obj.code)\n elseif stderr_lines then\n log.warn(\"Captured stderr output while running command '%s'. See logs for details.\", cmds)\n end\n if on_exit ~= nil then\n on_exit(obj.code)\n end\n end\n\n on_stdout = util.buffer_fn(on_stdout)\n\n local function stdout(err, data)\n if err ~= nil then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n end\n if data ~= nil then\n on_stdout(data)\n end\n end\n\n local function stderr(err, data)\n if err then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n elseif data ~= nil then\n if not stderr_lines then\n log.err(\"Captured stderr output while running command '%s'\", cmds)\n stderr_lines = true\n end\n log.err(\"[stderr] %s\", data)\n end\n end\n\n return function()\n log.debug(\"Initializing job '%s'\", cmds)\n\n if sync then\n local obj = vim.system(cmds, { stdout = stdout, stderr = stderr }):wait()\n on_obj(obj)\n return obj\n else\n vim.system(cmds, { stdout = stdout, stderr = stderr }, on_obj)\n end\n end\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@return integer exit_code\nM.run_job = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, true)\n return job().code\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\nM.run_job_async = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, false)\n job()\nend\n\n---@param fn function\n---@param timeout integer (milliseconds)\nM.throttle = function(fn, timeout)\n ---@type integer\n local last_call = 0\n ---@type uv.uv_timer_t?\n local timer = nil\n\n return function(...)\n if timer ~= nil then\n timer:stop()\n end\n\n local ms_remaining = timeout - (vim.uv.now() - last_call)\n\n if ms_remaining > 0 then\n if timer == nil then\n timer = assert(vim.uv.new_timer())\n end\n\n local args = { ... }\n\n timer:start(\n ms_remaining,\n 0,\n vim.schedule_wrap(function()\n if timer ~= nil then\n timer:stop()\n timer:close()\n timer = nil\n end\n\n last_call = vim.uv.now()\n fn(unpack(args))\n end)\n )\n else\n last_call = vim.uv.now()\n fn(...)\n end\n end\nend\n\n---Run an async function in a non-async context. The async function is expected to take a single\n---callback parameters with the results. This function returns those results.\n---@param async_fn_with_callback function (function,) -> any\n---@param timeout integer|?\n---@return ...any results\nM.block_on = function(async_fn_with_callback, timeout)\n local done = false\n local result\n timeout = timeout and timeout or 2000\n\n local function collect_result(...)\n result = { ... }\n done = true\n end\n\n async_fn_with_callback(collect_result)\n\n vim.wait(timeout, function()\n return done\n end, 20, false)\n\n return unpack(result)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/open.lua", "local api = require \"obsidian.api\"\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\nlocal log = require \"obsidian.log\"\n\n---@param path? string|obsidian.Path\nlocal function open_in_app(path)\n local vault_name = vim.fs.basename(tostring(Obsidian.workspace.root))\n if not path then\n return Obsidian.opts.open.func(\"obsidian://open?vault=\" .. vim.uri_encode(vault_name))\n end\n path = tostring(path)\n local this_os = api.get_os()\n\n -- Normalize path for windows.\n if this_os == api.OSType.Windows then\n path = string.gsub(path, \"/\", \"\\\\\")\n end\n\n local encoded_vault = vim.uri_encode(vault_name)\n local encoded_path = vim.uri_encode(path)\n\n local uri\n if Obsidian.opts.open.use_advanced_uri then\n local line = vim.api.nvim_win_get_cursor(0)[1] or 1\n uri = (\"obsidian://advanced-uri?vault=%s&filepath=%s&line=%i\"):format(encoded_vault, encoded_path, line)\n else\n uri = (\"obsidian://open?vault=%s&file=%s\"):format(encoded_vault, encoded_path)\n end\n print(uri)\n\n Obsidian.opts.open.func(uri)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type string|?\n local search_term\n\n if data.args and data.args:len() > 0 then\n search_term = data.args\n else\n -- Check for a note reference under the cursor.\n local link_string, _ = api.cursor_link()\n search_term = link_string\n end\n\n if search_term then\n search.resolve_link_async(search_term, function(results)\n if vim.tbl_isempty(results) then\n return log.err \"Note under cusros is not resolved\"\n end\n vim.schedule(function()\n open_in_app(results[1].path)\n end)\n end)\n else\n -- Otherwise use the path of the current buffer.\n local bufname = vim.api.nvim_buf_get_name(0)\n local path = Path.new(bufname):vault_relative_path()\n open_in_app(path)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/links.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local picker = Obsidian.picker\n if not picker then\n return log.err \"No picker configured\"\n end\n\n local note = api.current_note(0)\n assert(note, \"not in a note\")\n\n search.find_links(note, {}, function(entries)\n entries = vim.tbl_map(function(match)\n return match.link\n end, entries)\n\n -- Launch picker.\n picker:pick(entries, {\n prompt_title = \"Links\",\n callback = function(link)\n api.follow_link(link)\n end,\n })\n end)\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/nvim_cmp.lua", "local M = {}\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_sources(opts)\n local cmp = require \"cmp\"\n\n cmp.register_source(\"obsidian\", require(\"obsidian.completion.sources.nvim_cmp.refs\").new())\n cmp.register_source(\"obsidian_tags\", require(\"obsidian.completion.sources.nvim_cmp.tags\").new())\n if opts.completion.create_new then\n cmp.register_source(\"obsidian_new\", require(\"obsidian.completion.sources.nvim_cmp.new\").new())\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace and configures nvim_cmp sources for the current buffer.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n local cmp = require \"cmp\"\n\n local sources = {\n { name = \"obsidian\" },\n { name = \"obsidian_tags\" },\n }\n if opts.completion.create_new then\n table.insert(sources, { name = \"obsidian_new\" })\n end\n for _, source in pairs(cmp.get_config().sources) do\n if source.name ~= \"obsidian\" and source.name ~= \"obsidian_new\" and source.name ~= \"obsidian_tags\" then\n table.insert(sources, source)\n end\n end\n ---@diagnostic disable-next-line: missing-fields\n cmp.setup.buffer { sources = sources }\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/rename.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal util = require \"obsidian.util\"\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal enumerate, zip = util.enumerate, util.zip\n\nlocal resolve_note = function(query, opts)\n opts = opts or {}\n return require(\"obsidian.async\").block_on(function(cb)\n print(query)\n return search.resolve_note_async(query, cb, { notes = opts.notes })\n end, 5000)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n -- Resolve the note to rename.\n ---@type boolean\n local is_current_buf\n ---@type integer|?\n local cur_note_bufnr\n ---@type obsidian.Path\n local cur_note_path\n ---@type obsidian.Note\n local cur_note, cur_note_id\n\n local cur_link = api.cursor_link()\n if not cur_link then\n -- rename current note\n is_current_buf = true\n cur_note_bufnr = assert(vim.fn.bufnr())\n cur_note_path = Path.buffer(cur_note_bufnr)\n cur_note = Note.from_file(cur_note_path)\n cur_note_id = tostring(cur_note.id)\n else\n -- rename note under the cursor\n local link_id = util.parse_link(cur_link)\n local notes = { resolve_note(link_id) }\n if #notes == 0 then\n log.err(\"Failed to resolve '%s' to a note\", cur_link)\n return\n elseif #notes > 1 then\n log.err(\"Failed to resolve '%s' to a single note, found %d matches\", cur_link, #notes)\n return\n else\n cur_note = notes[1]\n end\n\n is_current_buf = false\n cur_note_id = tostring(cur_note.id)\n cur_note_path = cur_note.path\n for bufnr, bufpath in api.get_named_buffers() do\n if bufpath == cur_note_path then\n cur_note_bufnr = bufnr\n break\n end\n end\n end\n\n -- Validate args.\n local dry_run = false\n ---@type string|?\n local arg\n\n if data.args == \"--dry-run\" then\n dry_run = true\n data.args = nil\n end\n\n if data.args ~= nil and string.len(data.args) > 0 then\n arg = vim.trim(data.args)\n else\n arg = api.input(\"Enter new note ID/name/path: \", { completion = \"file\", default = cur_note_id })\n if not arg or string.len(arg) == 0 then\n log.warn \"Rename aborted\"\n return\n end\n end\n\n if vim.endswith(arg, \" --dry-run\") then\n dry_run = true\n arg = vim.trim(string.sub(arg, 1, -string.len \" --dry-run\" - 1))\n end\n\n assert(cur_note_path)\n local dirname = assert(cur_note_path:parent(), string.format(\"failed to resolve parent of '%s'\", cur_note_path))\n\n -- Parse new note ID / path from args.\n local parts = vim.split(arg, \"/\", { plain = true })\n local new_note_id = parts[#parts]\n if new_note_id == \"\" then\n log.err \"Invalid new note ID\"\n return\n elseif vim.endswith(new_note_id, \".md\") then\n new_note_id = string.sub(new_note_id, 1, -4)\n end\n\n ---@type obsidian.Path\n local new_note_path\n if #parts > 1 then\n parts[#parts] = nil\n new_note_path = Obsidian.dir:joinpath(unpack(compat.flatten { parts, new_note_id })):with_suffix \".md\"\n else\n new_note_path = (dirname / new_note_id):with_suffix \".md\"\n end\n\n if new_note_id == cur_note_id then\n log.warn \"New note ID is the same, doing nothing\"\n return\n end\n\n -- Get confirmation before continuing.\n local confirmation\n if not dry_run then\n confirmation = api.confirm(\n \"Renaming '\"\n .. cur_note_id\n .. \"' to '\"\n .. new_note_id\n .. \"'...\\n\"\n .. \"This will write all buffers and potentially modify a lot of files. If you're using version control \"\n .. \"with your vault it would be a good idea to commit the current state of your vault before running this.\\n\"\n .. \"You can also do a dry run of this by running ':Obsidian rename \"\n .. arg\n .. \" --dry-run'.\\n\"\n .. \"Do you want to continue?\"\n )\n else\n confirmation = api.confirm(\n \"Dry run: renaming '\" .. cur_note_id .. \"' to '\" .. new_note_id .. \"'...\\n\" .. \"Do you want to continue?\"\n )\n end\n\n if not confirmation then\n log.warn \"Rename aborted\"\n return\n end\n\n ---@param fn function\n local function quietly(fn, ...)\n local ok, res = pcall(fn, ...)\n if not ok then\n error(res)\n end\n end\n\n -- Write all buffers.\n quietly(vim.cmd.wall)\n\n -- Rename the note file and remove or rename the corresponding buffer, if there is one.\n if cur_note_bufnr ~= nil then\n if is_current_buf then\n -- If we're renaming the note of a current buffer, save as the new path.\n if not dry_run then\n quietly(vim.cmd.saveas, tostring(new_note_path))\n local new_bufnr_current_note = vim.fn.bufnr(tostring(cur_note_path))\n quietly(vim.cmd.bdelete, new_bufnr_current_note)\n vim.fn.delete(tostring(cur_note_path))\n else\n log.info(\"Dry run: saving current buffer as '\" .. tostring(new_note_path) .. \"' and removing old file\")\n end\n else\n -- For the non-current buffer the best we can do is delete the buffer (we've already saved it above)\n -- and then make a file-system call to rename the file.\n if not dry_run then\n quietly(vim.cmd.bdelete, cur_note_bufnr)\n cur_note_path:rename(new_note_path)\n else\n log.info(\n \"Dry run: removing buffer '\"\n .. tostring(cur_note_path)\n .. \"' and renaming file to '\"\n .. tostring(new_note_path)\n .. \"'\"\n )\n end\n end\n else\n -- When the note is not loaded into a buffer we just need to rename the file.\n if not dry_run then\n cur_note_path:rename(new_note_path)\n else\n log.info(\"Dry run: renaming file '\" .. tostring(cur_note_path) .. \"' to '\" .. tostring(new_note_path) .. \"'\")\n end\n end\n\n -- We need to update its frontmatter note_id\n -- to account for the rename.\n cur_note.id = new_note_id\n cur_note.path = Path.new(new_note_path)\n if not dry_run then\n cur_note:save()\n else\n log.info(\"Dry run: updating frontmatter of '\" .. tostring(new_note_path) .. \"'\")\n end\n\n local cur_note_rel_path = assert(cur_note_path:vault_relative_path { strict = true })\n local new_note_rel_path = assert(new_note_path:vault_relative_path { strict = true })\n\n -- Search notes on disk for any references to `cur_note_id`.\n -- We look for the following forms of references:\n -- * '[[cur_note_id]]'\n -- * '[[cur_note_id|ALIAS]]'\n -- * '[[cur_note_id\\|ALIAS]]' (a wiki link within a table)\n -- * '[ALIAS](cur_note_id)'\n -- And all of the above with relative paths (from the vault root) to the note instead of just the note ID,\n -- with and without the \".md\" suffix.\n -- Another possible form is [[ALIAS]], but we don't change the note's aliases when renaming\n -- so those links will still be valid.\n ---@param ref_link string\n ---@return string[]\n local function get_ref_forms(ref_link)\n return {\n \"[[\" .. ref_link .. \"]]\",\n \"[[\" .. ref_link .. \"|\",\n \"[[\" .. ref_link .. \"\\\\|\",\n \"[[\" .. ref_link .. \"#\",\n \"](\" .. ref_link .. \")\",\n \"](\" .. ref_link .. \"#\",\n }\n end\n\n local reference_forms = compat.flatten {\n get_ref_forms(cur_note_id),\n get_ref_forms(cur_note_rel_path),\n get_ref_forms(string.sub(cur_note_rel_path, 1, -4)),\n }\n local replace_with = compat.flatten {\n get_ref_forms(new_note_id),\n get_ref_forms(new_note_rel_path),\n get_ref_forms(string.sub(new_note_rel_path, 1, -4)),\n }\n\n local executor = AsyncExecutor.new()\n\n local file_count = 0\n local replacement_count = 0\n local all_tasks_submitted = false\n\n ---@param path string\n ---@return integer\n local function replace_refs(path)\n --- Read lines, replacing refs as we go.\n local count = 0\n local lines = {}\n local f = io.open(path, \"r\")\n assert(f)\n for line_num, line in enumerate(f:lines \"*L\") do\n for ref, replacement in zip(reference_forms, replace_with) do\n local n\n line, n = string.gsub(line, vim.pesc(ref), replacement)\n if dry_run and n > 0 then\n log.info(\n \"Dry run: '\"\n .. tostring(path)\n .. \"':\"\n .. line_num\n .. \" Replacing \"\n .. n\n .. \" occurrence(s) of '\"\n .. ref\n .. \"' with '\"\n .. replacement\n .. \"'\"\n )\n end\n count = count + n\n end\n lines[#lines + 1] = line\n end\n f:close()\n\n --- Write the new lines back.\n if not dry_run and count > 0 then\n f = io.open(path, \"w\")\n assert(f)\n f:write(unpack(lines))\n f:close()\n end\n\n return count\n end\n\n local function on_search_match(match)\n local path = tostring(Path.new(match.path.text):resolve { strict = true })\n file_count = file_count + 1\n executor:submit(replace_refs, function(count)\n replacement_count = replacement_count + count\n end, path)\n end\n\n search.search_async(\n Obsidian.dir,\n reference_forms,\n { fixed_strings = true, max_count_per_file = 1 },\n on_search_match,\n function(_)\n all_tasks_submitted = true\n end\n )\n\n -- Wait for all tasks to get submitted.\n vim.wait(2000, function()\n return all_tasks_submitted\n end, 50, false)\n\n -- Then block until all tasks are finished.\n executor:join(2000)\n\n local prefix = dry_run and \"Dry run: replaced \" or \"Replaced \"\n log.info(prefix .. replacement_count .. \" reference(s) across \" .. file_count .. \" file(s)\")\n\n -- In case the files of any current buffers were changed.\n vim.cmd.checktime()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/search.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n picker:grep_notes { query = data.args }\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/tags.lua", "local Note = require \"obsidian.note\"\nlocal Patterns = require(\"obsidian.search\").Patterns\n\nlocal M = {}\n\n---@type { pattern: string, offset: integer }[]\nlocal TAG_PATTERNS = {\n { pattern = \"[%s%(]#\" .. Patterns.TagCharsOptional .. \"$\", offset = 2 },\n { pattern = \"^#\" .. Patterns.TagCharsOptional .. \"$\", offset = 1 },\n}\n\nM.find_tags_start = function(input)\n for _, pattern in ipairs(TAG_PATTERNS) do\n local match = string.match(input, pattern.pattern)\n if match then\n return string.sub(match, pattern.offset + 1)\n end\n end\nend\n\n--- Find the boundaries of the YAML frontmatter within the buffer.\n---@param bufnr integer\n---@return integer|?, integer|?\nlocal get_frontmatter_boundaries = function(bufnr)\n local note = Note.from_buffer(bufnr)\n if note.frontmatter_end_line ~= nil then\n return 1, note.frontmatter_end_line\n end\nend\n\n---@return boolean, string|?, boolean|?\nM.can_complete = function(request)\n local search = M.find_tags_start(request.context.cursor_before_line)\n if not search or string.len(search) == 0 then\n return false\n end\n\n -- Check if we're inside frontmatter.\n local in_frontmatter = false\n local line = request.context.cursor.line\n local frontmatter_start, frontmatter_end = get_frontmatter_boundaries(request.context.bufnr)\n if\n frontmatter_start ~= nil\n and frontmatter_start <= (line + 1)\n and frontmatter_end ~= nil\n and line <= frontmatter_end\n then\n in_frontmatter = true\n end\n\n return true, search, in_frontmatter\nend\n\nM.get_trigger_characters = function()\n return { \"#\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n -- return [=[\\%(^\\|[^#]\\)\\zs#[a-zA-Z0-9_/-]\\+]=]\n return \"#[a-zA-Z0-9_/-]\\\\+\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/refs.lua", "local util = require \"obsidian.util\"\n\nlocal M = {}\n\n---@enum obsidian.completion.RefType\nM.RefType = {\n Wiki = 1,\n Markdown = 2,\n}\n\n---Backtrack through a string to find the first occurrence of '[['.\n---\n---@param input string\n---@return string|?, string|?, obsidian.completion.RefType|?\nlocal find_search_start = function(input)\n for i = string.len(input), 1, -1 do\n local substr = string.sub(input, i)\n if vim.startswith(substr, \"]\") or vim.endswith(substr, \"]\") then\n return nil\n elseif vim.startswith(substr, \"[[\") then\n return substr, string.sub(substr, 3)\n elseif vim.startswith(substr, \"[\") and string.sub(input, i - 1, i - 1) ~= \"[\" then\n return substr, string.sub(substr, 2)\n end\n end\n return nil\nend\n\n---Check if a completion request can/should be carried out. Returns a boolean\n---and, if true, the search string and the column indices of where the completion\n---items should be inserted.\n---\n---@return boolean, string|?, integer|?, integer|?, obsidian.completion.RefType|?\nM.can_complete = function(request)\n local input, search = find_search_start(request.context.cursor_before_line)\n if input == nil or search == nil then\n return false\n elseif string.len(search) == 0 or util.is_whitespace(search) then\n return false\n end\n\n if vim.startswith(input, \"[[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 2)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]]\" and 1 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Wiki\n elseif vim.startswith(input, \"[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 1)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]\" and 0 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Markdown\n else\n return false\n end\nend\n\nM.get_trigger_characters = function()\n return { \"[\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n return [=[\\%(^\\|[^\\[]\\)\\zs\\[\\{1,2}[^\\]]\\+\\]\\{,2}]=]\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/log.lua", "---@class obsidian.Logger\nlocal log = {}\n\nlog._log_level = vim.log.levels.INFO\n\n---@param t table\n---@return boolean\nlocal function has_tostring(t)\n local mt = getmetatable(t)\n return mt ~= nil and mt.__tostring ~= nil\nend\n\n---@param msg string\n---@return any[]\nlocal function message_args(msg, ...)\n local args = { ... }\n local num_directives = select(2, string.gsub(msg, \"%%\", \"\")) - 2 * select(2, string.gsub(msg, \"%%%%\", \"\"))\n\n -- Some elements might be nil, so we can't use 'ipairs'.\n local out = {}\n for i = 1, #args do\n local v = args[i]\n if v == nil then\n out[i] = tostring(v)\n elseif type(v) == \"table\" and not has_tostring(v) then\n out[i] = vim.inspect(v)\n else\n out[i] = v\n end\n end\n\n -- If were short formatting args relative to the number of directives, add \"nil\" strings on.\n if #out < num_directives then\n for i = #out + 1, num_directives do\n out[i] = \"nil\"\n end\n end\n\n return out\nend\n\n---@param level integer\nlog.set_level = function(level)\n log._log_level = level\nend\n\n--- Log a message.\n---\n---@param msg any\n---@param level integer|?\nlog.log = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---Log a message only once.\n---\n---@param msg any\n---@param level integer|?\nlog.log_once = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---@param msg string\nlog.debug = function(msg, ...)\n log.log(msg, vim.log.levels.DEBUG, ...)\nend\n\n---@param msg string\nlog.info = function(msg, ...)\n log.log(msg, vim.log.levels.INFO, ...)\nend\n\n---@param msg string\nlog.warn = function(msg, ...)\n log.log(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.warn_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.err = function(msg, ...)\n log.log(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error = log.err\n\n---@param msg string\nlog.err_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error_once = log.err\n\nreturn log\n"], ["/obsidian.nvim/lua/obsidian/builtin.lua", "---builtin functions that are default values for config options\nlocal M = {}\nlocal util = require \"obsidian.util\"\n\n---Create a new unique Zettel ID.\n---\n---@return string\nM.zettel_id = function()\n local suffix = \"\"\n for _ = 1, 4 do\n suffix = suffix .. string.char(math.random(65, 90))\n end\n return tostring(os.time()) .. \"-\" .. suffix\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_alias_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = string.format(\"#%s\", opts.anchor.header)\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.label, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = opts.anchor.anchor\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.path, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.label ~= opts.path then\n return string.format(\"[[%s%s|%s%s]]\", opts.path, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.path, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_id_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.id == nil then\n return string.format(\"[[%s%s]]\", opts.label, anchor)\n elseif opts.label ~= opts.id then\n return string.format(\"[[%s%s|%s%s]]\", opts.id, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.id, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.markdown_link = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n local path = util.urlencode(opts.path, { keep_path_sep = true })\n return string.format(\"[%s%s](%s%s)\", opts.label, header, path, anchor)\nend\n\n---@param path string\n---@return string\nM.img_text_func = function(path)\n local format_string = {\n markdown = \"![](%s)\",\n wiki = \"![[%s]]\",\n }\n local style = Obsidian.opts.preferred_link_style\n local name = vim.fs.basename(tostring(path))\n\n if style == \"markdown\" then\n name = require(\"obsidian.util\").urlencode(name)\n end\n\n return string.format(format_string[style], name)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/types.lua", "-- Useful type definitions go here.\n\n---@class CommandArgs\n---The table passed to user commands.\n---For details see `:help nvim_create_user_command()` and the command attribute docs\n---\n---@field name string Command name\n---@field args string The args passed to the command, if any \n---@field fargs table The args split by unescaped whitespace (when more than one argument is allowed), if any \n---@field nargs string Number of arguments |:command-nargs|\n---@field bang boolean \"true\" if the command was executed with a ! modifier \n---@field line1 number The starting line of the command range \n---@field line2 number The final line of the command range \n---@field range number The number of items in the command range: 0, 1, or 2 \n---@field count number Any count supplied \n---@field reg string The optional register, if specified \n---@field mods string Command modifiers, if any \n---@field smods table Command modifiers in a structured format. Has the same structure as the \"mods\" key of\n---@field raw_print boolean HACK: for debug command and info\n\n---@class obsidian.InsertTemplateContext\n---The table passed to user substitution functions when inserting templates into a buffer.\n---\n---@field type \"insert_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field location [number, number, number, number] `{ buf, win, row, col }` location from which the request was made.\n---@field partial_note? obsidian.Note An optional note with fields to copy from.\n\n---@class obsidian.CloneTemplateContext\n---The table passed to user substitution functions when cloning template files to create new notes.\n---\n---@field type \"clone_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field destination_path obsidian.Path The path the cloned template will be written to.\n---@field partial_note obsidian.Note The note being written.\n\n---@alias obsidian.TemplateContext obsidian.InsertTemplateContext | obsidian.CloneTemplateContext\n---The table passed to user substitution functions. Use `ctx.type` to distinguish between the different kinds.\n"], ["/obsidian.nvim/lua/obsidian/commands/check.lua", "local Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal iter = vim.iter\n\nreturn function()\n local start_time = vim.uv.hrtime()\n local count = 0\n local errors = {}\n local warnings = {}\n\n for path in api.dir(Obsidian.dir) do\n local relative_path = Path.new(path):vault_relative_path { strict = true }\n local ok, res = pcall(Note.from_file, path)\n\n if not ok then\n errors[#errors + 1] = string.format(\"Failed to parse note '%s': \", relative_path, res)\n elseif res.has_frontmatter == false then\n warnings[#warnings + 1] = string.format(\"'%s' missing frontmatter\", relative_path)\n end\n count = count + 1\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n local messages = { \"Checked \" .. tostring(count) .. \" notes in \" .. runtime .. \"ms\" }\n local log_level = vim.log.levels.INFO\n\n if #warnings > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#warnings) .. \" warning(s):\"\n log_level = vim.log.levels.WARN\n for warning in iter(warnings) do\n messages[#messages + 1] = \"  \" .. warning\n end\n end\n\n if #errors > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#errors) .. \" error(s):\"\n for err in iter(errors) do\n messages[#messages + 1] = \"  \" .. err\n end\n log_level = vim.log.levels.ERROR\n end\n\n log.log(table.concat(messages, \"\\n\"), log_level)\nend\n"], ["/obsidian.nvim/lua/obsidian/abc.lua", "local M = {}\n\n---@class obsidian.ABC\n---@field init function an init function which essentially calls 'setmetatable({}, mt)'.\n---@field as_tbl function get a raw table with only the instance's fields\n---@field mt table the metatable\n\n---Create a new class.\n---\n---This handles the boilerplate of setting up metatables correctly and consistently when defining new classes,\n---and comes with some better default metamethods, like '.__eq' which will recursively compare all fields\n---that don't start with a double underscore.\n---\n---When you use this you should call `.init()` within your constructors instead of `setmetatable()`.\n---For example:\n---\n---```lua\n--- local Foo = new_class()\n---\n--- Foo.new = function(x)\n--- local self = Foo.init()\n--- self.x = x\n--- return self\n--- end\n---```\n---\n---The metatable for classes created this way is accessed with the field `.mt`. This way you can easily\n---add/override metamethods to your classes. Continuing the example above:\n---\n---```lua\n--- Foo.mt.__tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end\n---\n--- local foo = Foo.new(1)\n--- print(foo)\n---```\n---\n---Alternatively you can pass metamethods directly to 'new_class()'. For example:\n---\n---```lua\n--- local Foo = new_class {\n--- __tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end,\n--- }\n---```\n---\n---@param metamethods table|? {string, function} - Metamethods\n---@param base_class table|? A base class to start from\n---@return obsidian.ABC\nM.new_class = function(metamethods, base_class)\n local class = base_class and base_class or {}\n\n -- Metatable for the class so that all instances have the same metatable.\n class.mt = vim.tbl_extend(\"force\", {\n __index = class,\n __eq = function(a, b)\n -- In order to use 'vim.deep_equal' we need to pull out the raw fields first.\n -- If we passed 'a' and 'b' directly to 'vim.deep_equal' we'd get a stack overflow due\n -- to infinite recursion, since 'vim.deep_equal' calls the '.__eq' metamethod.\n local a_fields = a:as_tbl()\n local b_fields = b:as_tbl()\n return vim.deep_equal(a_fields, b_fields)\n end,\n }, metamethods and metamethods or {})\n\n class.init = function(t)\n local self = setmetatable(t and t or {}, class.mt)\n return self\n end\n\n class.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\n end\n\n return class\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/yaml/init.lua", "local util = require \"obsidian.util\"\nlocal parser = require \"obsidian.yaml.parser\"\n\nlocal yaml = {}\n\n---Deserialize a YAML string.\n---@param str string\n---@return any\nyaml.loads = function(str)\n return parser.loads(str)\nend\n\n---@param s string\n---@return boolean\nlocal should_quote = function(s)\n -- TODO: this probably doesn't cover all edge cases.\n -- See https://www.yaml.info/learn/quote.html\n -- Check if it starts with a special character.\n if string.match(s, [[^[\"'\\\\[{&!-].*]]) then\n return true\n -- Check if it has a colon followed by whitespace.\n elseif string.find(s, \": \", 1, true) then\n return true\n -- Check if it's an empty string.\n elseif s == \"\" or string.match(s, \"^[%s]+$\") then\n return true\n else\n return false\n end\nend\n\n---@return string[]\nlocal dumps\ndumps = function(x, indent, order)\n local indent_str = string.rep(\" \", indent)\n\n if type(x) == \"string\" then\n if should_quote(x) then\n x = string.gsub(x, '\"', '\\\\\"')\n return { indent_str .. [[\"]] .. x .. [[\"]] }\n else\n return { indent_str .. x }\n end\n end\n\n if type(x) == \"boolean\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"number\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"table\" then\n local out = {}\n\n if util.islist(x) then\n for _, v in ipairs(x) do\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. \"- \" .. util.lstrip_whitespace(item_lines[1]))\n for i = 2, #item_lines do\n table.insert(out, item_lines[i])\n end\n end\n else\n -- Gather and sort keys so we can keep the order deterministic.\n local keys = {}\n for k, _ in pairs(x) do\n table.insert(keys, k)\n end\n table.sort(keys, order)\n for _, k in ipairs(keys) do\n local v = x[k]\n if type(v) == \"string\" or type(v) == \"boolean\" or type(v) == \"number\" then\n table.insert(out, indent_str .. tostring(k) .. \": \" .. dumps(v, 0)[1])\n elseif type(v) == \"table\" and vim.tbl_isempty(v) then\n table.insert(out, indent_str .. tostring(k) .. \": []\")\n else\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. tostring(k) .. \":\")\n for _, line in ipairs(item_lines) do\n table.insert(out, line)\n end\n end\n end\n end\n\n return out\n end\n\n error(\"Can't convert object with type \" .. type(x) .. \" to YAML\")\nend\n\n---Dump an object to YAML lines.\n---@param x any\n---@param order function\n---@return string[]\nyaml.dumps_lines = function(x, order)\n return dumps(x, 0, order)\nend\n\n---Dump an object to a YAML string.\n---@param x any\n---@param order function|?\n---@return string\nyaml.dumps = function(x, order)\n return table.concat(dumps(x, 0, order), \"\\n\")\nend\n\nreturn yaml\n"], ["/obsidian.nvim/lua/obsidian/daily/init.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\n\n--- Get the path to a daily note.\n---\n---@param datetime integer|?\n---\n---@return obsidian.Path, string (Path, ID) The path and ID of the note.\nlocal daily_note_path = function(datetime)\n datetime = datetime and datetime or os.time()\n\n ---@type obsidian.Path\n local path = Path:new(Obsidian.dir)\n\n local options = Obsidian.opts\n\n if options.daily_notes.folder ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.daily_notes.folder\n elseif options.notes_subdir ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.notes_subdir\n end\n\n local id\n if options.daily_notes.date_format ~= nil then\n id = tostring(os.date(options.daily_notes.date_format, datetime))\n else\n id = tostring(os.date(\"%Y-%m-%d\", datetime))\n end\n\n path = path / (id .. \".md\")\n\n -- ID may contain additional path components, so make sure we use the stem.\n id = path.stem\n\n return path, id\nend\n\n--- Open (or create) the daily note.\n---\n---@param datetime integer\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\n---\nlocal _daily = function(datetime, opts)\n opts = opts or {}\n\n local path, id = daily_note_path(datetime)\n\n local options = Obsidian.opts\n\n ---@type string|?\n local alias\n if options.daily_notes.alias_format ~= nil then\n alias = tostring(os.date(options.daily_notes.alias_format, datetime))\n end\n\n ---@type obsidian.Note\n local note\n if path:exists() then\n note = Note.from_file(path, opts.load)\n else\n note = Note.create {\n id = id,\n aliases = {},\n tags = options.daily_notes.default_tags or {},\n dir = path:parent(),\n }\n\n if alias then\n note:add_alias(alias)\n note.title = alias\n end\n\n if not opts.no_write then\n note:write { template = options.daily_notes.template }\n end\n end\n\n return note\nend\n\n--- Open (or create) the daily note for today.\n---\n---@return obsidian.Note\nlocal today = function()\n return _daily(os.time(), {})\nend\n\n--- Open (or create) the daily note from the last day.\n---\n---@return obsidian.Note\nlocal yesterday = function()\n local now = os.time()\n local yesterday\n\n if Obsidian.opts.daily_notes.workdays_only then\n yesterday = util.working_day_before(now)\n else\n yesterday = util.previous_day(now)\n end\n\n return _daily(yesterday, {})\nend\n\n--- Open (or create) the daily note for the next day.\n---\n---@return obsidian.Note\nlocal tomorrow = function()\n local now = os.time()\n local tomorrow\n\n if Obsidian.opts.daily_notes.workdays_only then\n tomorrow = util.working_day_after(now)\n else\n tomorrow = util.next_day(now)\n end\n\n return _daily(tomorrow, {})\nend\n\n--- Open (or create) the daily note for today + `offset_days`.\n---\n---@param offset_days integer|?\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\nlocal daily = function(offset_days, opts)\n return _daily(os.time() + (offset_days * 3600 * 24), opts)\nend\n\nreturn {\n daily_note_path = daily_note_path,\n daily = daily,\n tomorrow = tomorrow,\n yesterday = yesterday,\n today = today,\n}\n"], ["/obsidian.nvim/lua/obsidian/commands/extract_note.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---Extract the selected text into a new note\n---and replace the selection with a link to the new note.\n---\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"Obsidian extract_note must be called with visual selection\"\n return\n end\n\n local content = vim.split(viz.selection, \"\\n\", { plain = true })\n\n ---@type string|?\n local title\n if data.args ~= nil and string.len(data.args) > 0 then\n title = vim.trim(data.args)\n else\n title = api.input \"Enter title (optional): \"\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n end\n\n -- create the new note.\n local note = Note.create { title = title }\n\n -- replace selection with link to new note\n local link = api.format_link(note)\n vim.api.nvim_buf_set_text(0, viz.csrow - 1, viz.cscol - 1, viz.cerow - 1, viz.cecol, { link })\n\n require(\"obsidian.ui\").update(0)\n\n -- add the selected text to the end of the new note\n note:open { sync = true }\n vim.api.nvim_buf_set_lines(0, -1, -1, false, content)\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/tags.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal iter = vim.iter\nlocal obsidian = require \"obsidian\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.TagsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field in_frontmatter boolean|?\nlocal TagsSourceCompletionContext = abc.new_class()\n\nTagsSourceCompletionContext.new = function()\n return TagsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.TagsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal TagsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.TagsSourceBase\nTagsSourceBase.new = function()\n return TagsSourceBase.init()\nend\n\nTagsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = TagsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n local search_opts = cc.client.search_defaults()\n search_opts.sort = false\n\n cc.client:find_tags_async(cc.search, function(tag_locs)\n local tags = {}\n for tag_loc in iter(tag_locs) do\n tags[tag_loc.tag] = true\n end\n\n local items = {}\n for tag, _ in pairs(tags) do\n -- Generate context-appropriate text\n local insert_text, label_text\n if cc.in_frontmatter then\n -- Frontmatter: insert tag without # (YAML format)\n insert_text = tag\n label_text = \"Tag: \" .. tag\n else\n -- Document body: insert tag with # (Obsidian format)\n insert_text = \"#\" .. tag\n label_text = \"Tag: #\" .. tag\n end\n\n -- Calculate the range to replace (the entire #tag pattern)\n local cursor_before = cc.request.context.cursor_before_line\n local hash_start = string.find(cursor_before, \"#[^%s]*$\")\n local insert_start = hash_start and (hash_start - 1) or #cursor_before\n local insert_end = #cursor_before\n\n items[#items + 1] = {\n sortText = \"#\" .. tag,\n label = label_text,\n kind = vim.lsp.protocol.CompletionItemKind.Text,\n textEdit = {\n newText = insert_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_end,\n },\n },\n },\n data = {\n bufnr = cc.request.context.bufnr,\n in_frontmatter = cc.in_frontmatter,\n line = cc.request.context.cursor.line,\n tag = tag,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\n end, { search = search_opts })\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction TagsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.in_frontmatter = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\nreturn TagsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/commands/link.lua", "local search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n ---@type string\n local search_term\n if data.args ~= nil and string.len(data.args) > 0 then\n search_term = data.args\n else\n search_term = viz.selection\n end\n\n ---@param note obsidian.Note\n local function insert_ref(note)\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = viz.selection })\n .. string.sub(line, viz.cecol + 1)\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\n require(\"obsidian.ui\").update(0)\n end\n\n search.resolve_note_async(search_term, function(note)\n vim.schedule(function()\n insert_ref(note)\n end)\n end, { prompt_title = \"Select note to link\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/footer/init.lua", "local M = {}\nlocal api = require \"obsidian.api\"\n\nlocal ns_id = vim.api.nvim_create_namespace \"ObsidianFooter\"\n\n--- Register buffer-specific variables\nM.start = function(client)\n local refresh_info = function(buf)\n local note = api.current_note(buf)\n if not note then\n return\n end\n local info = {}\n local wc = vim.fn.wordcount()\n info.words = wc.words\n info.chars = wc.chars\n info.properties = vim.tbl_count(note:frontmatter())\n info.backlinks = #client:find_backlinks(note)\n return info\n end\n\n local function update_obsidian_footer(buf)\n local info = refresh_info(buf)\n if info == nil then\n return\n end\n local footer_text = assert(Obsidian.opts.footer.format)\n for k, v in pairs(info) do\n footer_text = footer_text:gsub(\"{{\" .. k .. \"}}\", v)\n end\n local row0 = #vim.api.nvim_buf_get_lines(buf, 0, -2, false)\n local col0 = 0\n local separator = Obsidian.opts.footer.separator\n local hl_group = Obsidian.opts.footer.hl_group\n local footer_contents = { { footer_text, hl_group } }\n local footer_chunks\n if separator then\n local footer_separator = { { separator, hl_group } }\n footer_chunks = { footer_separator, footer_contents }\n else\n footer_chunks = { footer_contents }\n end\n local opts = { virt_lines = footer_chunks }\n vim.api.nvim_buf_clear_namespace(buf, ns_id, 0, -1)\n vim.api.nvim_buf_set_extmark(buf, ns_id, row0, col0, opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_footer\", {})\n local attached_bufs = {}\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n desc = \"Initialize obsidian footer\",\n pattern = \"ObsidianNoteEnter\",\n callback = function(ev)\n if attached_bufs[ev.buf] then\n return\n end\n vim.schedule(function()\n update_obsidian_footer(ev.buf)\n end)\n local id = vim.api.nvim_create_autocmd({\n \"FileChangedShellPost\",\n \"TextChanged\",\n \"TextChangedI\",\n \"TextChangedP\",\n }, {\n group = group,\n desc = \"Update obsidian footer\",\n buffer = ev.buf,\n callback = vim.schedule_wrap(function()\n update_obsidian_footer(ev.buf)\n end),\n })\n attached_bufs[ev.buf] = id\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/statusline/init.lua", "local M = {}\nlocal uv = vim.uv\nlocal api = require \"obsidian.api\"\n\n--- Register the global variable that updates itself\nM.start = function(client)\n local current_note\n\n local refresh = function()\n local note = api.current_note()\n if not note then -- no note\n return \"\"\n elseif current_note == note then -- no refresh\n return\n else -- refresh\n current_note = note\n end\n\n client:find_backlinks_async(\n note,\n vim.schedule_wrap(function(backlinks)\n local format = assert(Obsidian.opts.statusline.format)\n local wc = vim.fn.wordcount()\n local info = {\n words = wc.words,\n chars = wc.chars,\n backlinks = #backlinks,\n properties = vim.tbl_count(note:frontmatter()),\n }\n for k, v in pairs(info) do\n format = format:gsub(\"{{\" .. k .. \"}}\", v)\n end\n vim.g.obsidian = format\n end)\n )\n end\n\n local timer = uv:new_timer()\n assert(timer, \"Failed to create timer\")\n timer:start(0, 1000, vim.schedule_wrap(refresh))\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/yaml/line.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\n\n---@class obsidian.yaml.Line : obsidian.ABC\n---@field content string\n---@field raw_content string\n---@field indent integer\nlocal Line = abc.new_class {\n __tostring = function(self)\n return string.format(\"Line('%s')\", self.raw_content)\n end,\n}\n\n---Create a new Line instance from a raw line string.\n---@param raw_line string\n---@param base_indent integer|?\n---@return obsidian.yaml.Line\nLine.new = function(raw_line, base_indent)\n local self = Line.init()\n self.indent = util.count_indent(raw_line)\n if base_indent ~= nil then\n if base_indent > self.indent then\n error \"relative indentation for line is less than base indentation\"\n end\n self.indent = self.indent - base_indent\n end\n self.raw_content = util.lstrip_whitespace(raw_line, base_indent)\n self.content = vim.trim(self.raw_content)\n return self\nend\n\n---Check if a line is empty.\n---@param self obsidian.yaml.Line\n---@return boolean\nLine.is_empty = function(self)\n if util.strip_comments(self.content) == \"\" then\n return true\n else\n return false\n end\nend\n\nreturn Line\n"], ["/obsidian.nvim/after/ftplugin/markdown.lua", "local obsidian = require \"obsidian\"\nlocal buf = vim.api.nvim_get_current_buf()\nlocal buf_dir = vim.fs.dirname(vim.api.nvim_buf_get_name(buf))\n\nlocal workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\nif not workspace then\n return -- if not in any workspace.\nend\n\nlocal win = vim.api.nvim_get_current_win()\n\nvim.treesitter.start(buf, \"markdown\") -- for when user don't use nvim-treesitter\nvim.wo[win].foldmethod = \"expr\"\nvim.wo[win].foldexpr = \"v:lua.vim.treesitter.foldexpr()\"\nvim.wo[win].foldlevel = 99\n"], ["/obsidian.nvim/lua/obsidian/commands/today.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_days = 0\n local arg = string.gsub(data.args, \" \", \"\")\n if string.len(arg) > 0 then\n local offset = tonumber(arg)\n if offset == nil then\n log.err \"Invalid argument, expected an integer offset\"\n return\n else\n offset_days = offset\n end\n end\n local note = require(\"obsidian.daily\").daily(offset_days, {})\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/new.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type obsidian.Note\n local note\n if data.args:len() > 0 then\n note = Note.create { title = data.args }\n else\n local title = api.input(\"Enter title or path (optional): \", { completion = \"file\" })\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n note = Note.create { title = title }\n end\n\n -- Open the note in a new buffer.\n note:open { sync = true }\n note:write_to_buffer()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/link_new.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n local title\n if string.len(data.args) > 0 then\n title = data.args\n else\n title = viz.selection\n end\n\n local note = Note.create { title = title }\n\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = title })\n .. string.sub(line, viz.cecol + 1)\n\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/toggle_checkbox.lua", "local toggle_checkbox = require(\"obsidian.api\").toggle_checkbox\n\n---@param data CommandArgs\nreturn function(_, data)\n local start_line, end_line\n local checkboxes = Obsidian.opts.checkbox.order\n start_line = data.line1\n end_line = data.line2\n\n local buf = vim.api.nvim_get_current_buf()\n\n for line_nb = start_line, end_line do\n local current_line = vim.api.nvim_buf_get_lines(buf, line_nb - 1, line_nb, false)[1]\n if current_line and current_line:match \"%S\" then\n toggle_checkbox(checkboxes, line_nb)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.new = function()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\nNewNoteSource.get_keyword_pattern = completion.get_keyword_pattern\n\nNewNoteSource.incomplete_response = nvim_cmp_util.incomplete_response\nNewNoteSource.complete_response = nvim_cmp_util.complete_response\n\n---Invoke completion (required).\n---@param request cmp.SourceCompletionApiParams\n---@param callback fun(response: lsp.CompletionResponse|nil)\nfunction NewNoteSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\n---Creates a new note using the default template for the completion item.\n---Executed after the item was selected.\n---@param completion_item lsp.CompletionItem\n---@param callback fun(completion_item: lsp.CompletionItem|nil)\nfunction NewNoteSource:execute(completion_item, callback)\n return callback(self:process_execute(completion_item))\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/util.lua", "local M = {}\n\n---Generates the completion request from a blink context\n---@param context blink.cmp.Context\n---@return obsidian.completion.sources.base.Request\nM.generate_completion_request_from_editor_state = function(context)\n local row = context.cursor[1]\n local col = context.cursor[2] + 1\n local cursor_before_line = context.line:sub(1, col - 1)\n local cursor_after_line = context.line:sub(col)\n\n return {\n context = {\n bufnr = context.bufnr,\n cursor_before_line = cursor_before_line,\n cursor_after_line = cursor_after_line,\n cursor = {\n row = row,\n col = col,\n line = row + 1,\n },\n },\n }\nend\n\nM.incomplete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = true,\n items = {},\n}\n\nM.complete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = false,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/follow_link.lua", "local api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local opts = {}\n if data.args and string.len(data.args) > 0 then\n opts.open_strategy = data.args\n end\n\n local link = api.cursor_link()\n\n if link then\n api.follow_link(link, opts)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/compat.lua", "local compat = {}\n\nlocal has_nvim_0_11 = false\nif vim.fn.has \"nvim-0.11\" == 1 then\n has_nvim_0_11 = true\nend\n\ncompat.is_list = function(t)\n if has_nvim_0_11 then\n return vim.islist(t)\n else\n return vim.tbl_islist(t)\n end\nend\n\ncompat.flatten = function(t)\n if has_nvim_0_11 then\n ---@diagnostic disable-next-line: undefined-field\n return vim.iter(t):flatten():totable()\n else\n return vim.tbl_flatten(t)\n end\nend\n\nreturn compat\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.incomplete_response = blink_util.incomplete_response\nNewNoteSource.complete_response = blink_util.complete_response\n\nfunction NewNoteSource.new()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction NewNoteSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\n---Implements the execute method of the completion provider\n---@param _ blink.cmp.Context\n---@param item blink.cmp.CompletionItem\n---@param callback fun(),\n---@param default_implementation fun(context?: blink.cmp.Context, item?: blink.cmp.CompletionItem)): ((fun(): nil) | nil)\nfunction NewNoteSource:execute(_, item, callback, default_implementation)\n self:process_execute(item)\n default_implementation() -- Ensure completion is still executed\n callback() -- Required (as per blink documentation)\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.nvim_cmp.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.new = function()\n return RefsSource.init(RefsSourceBase)\nend\n\nRefsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nRefsSource.incomplete_response = nvim_cmp_util.incomplete_response\nRefsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction RefsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.blink.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.incomplete_response = blink_util.incomplete_response\nRefsSource.complete_response = blink_util.complete_response\n\nfunction RefsSource.new()\n return RefsSource.init(RefsSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction RefsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/commands/yesterday.lua", "return function()\n local note = require(\"obsidian.daily\").yesterday()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/tomorrow.lua", "return function()\n local note = require(\"obsidian.daily\").tomorrow()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/yaml/yq.lua", "local m = {}\n\n---@param str string\n---@return any\nm.loads = function(str)\n local as_json = vim.fn.system(\"yq -o=json\", str)\n local data = vim.json.decode(as_json, { luanil = { object = true, array = true } })\n return data\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.new = function()\n return TagsSource.init(TagsSourceBase)\nend\n\nTagsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nTagsSource.incomplete_response = nvim_cmp_util.incomplete_response\nTagsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction TagsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.incomplete_response = blink_util.incomplete_response\nTagsSource.complete_response = blink_util.complete_response\n\nfunction TagsSource.new()\n return TagsSource.init(TagsSourceBase)\nend\n\n---Implements the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction TagsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/types.lua", "---@class obsidian.completion.sources.base.Request.Context.Position\n---@field public col integer\n---@field public row integer\n\n---A request context class that partially matches cmp.Context to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request.Context\n---@field public bufnr integer\n---@field public cursor obsidian.completion.sources.base.Request.Context.Position|lsp.Position\n---@field public cursor_after_line string\n---@field public cursor_before_line string\n\n---A request class that partially matches cmp.Request to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request\n---@field public context obsidian.completion.sources.base.Request.Context\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/util.lua", "local M = {}\n\nM.incomplete_response = { isIncomplete = true }\n\nM.complete_response = {\n isIncomplete = true,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/init.lua", "local M = {\n refs = require \"obsidian.completion.refs\",\n tags = require \"obsidian.completion.tags\",\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/version.lua", "return \"3.12.0\"\n"]], "task_instance_info": {"created_time": "2025-08-21 00:50:03", "created_task_model": "DeepSeek-R1", "function_skeleton": "function (picker_name) end", "code_description": "This code segment functions to: Dynamically initialize and return a component based on a specified name while providing fallback mechanisms through prioritized checks of available implementations, handling case normalization for configuration matching, and loading corresponding dependencies when required."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nfunction(picker_name)\n local name = picker_name or PickerName\n local ok, picker = pcall(require, \"obsidian.pickers.\" .. name:lower())\n if ok then\n return picker\n end\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-50-20"}, "editdistance_info": {"edit_distance": 14.4033, "calculate_time": "2025-08-21 00:50:20", "true_code_clean": "function(picker_name)\n picker_name = picker_name and picker_name or Obsidian.opts.picker.name\n if picker_name then\n picker_name = string.lower(picker_name)\n else\n for _, name in ipairs { PickerName.telescope, PickerName.fzf_lua, PickerName.mini, PickerName.snacks } do\n local ok, res = pcall(M.get, name)\n if ok then\n return res\n end\n end\n return nil\n end\n if picker_name == string.lower(PickerName.telescope) then\n return require(\"obsidian.pickers._telescope\").new()\n elseif picker_name == string.lower(PickerName.mini) then\n return require(\"obsidian.pickers._mini\").new()\n elseif picker_name == string.lower(PickerName.fzf_lua) then\n return require(\"obsidian.pickers._fzf\").new()\n elseif picker_name == string.lower(PickerName.snacks) then\n return require(\"obsidian.pickers._snacks\").new()\n elseif picker_name then\n error(\"not implemented for \" .. picker_name)\n end\nend", "predict_code_clean": "function(picker_name)\n local name = picker_name or PickerName\n local ok, picker = pcall(require, \"obsidian.pickers.\" .. name:lower())\n if ok then\n return picker\n end\nend"}} {"repo_name": "obsidian.nvim", "file_name": "/obsidian.nvim/lua/obsidian/commands/new.lua", "inference_info": {"prefix_code": "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn ", "suffix_code": "\n", "middle_code": "function(_, data)\n local note\n if data.args:len() > 0 then\n note = Note.create { title = data.args }\n else\n local title = api.input(\"Enter title or path (optional): \", { completion = \"file\" })\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n note = Note.create { title = title }\n end\n note:open { sync = true }\n note:write_to_buffer()\nend", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/obsidian.nvim/lua/obsidian/commands/new_from_template.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type string?\n local title = table.concat(data.fargs, \" \", 1, #data.fargs - 1)\n local template = data.fargs[#data.fargs]\n\n if title ~= nil and template ~= nil then\n local note = Note.create { title = title, template = template, should_write = true }\n note:open { sync = true }\n return\n end\n\n picker:find_templates {\n callback = function(template_name)\n if title == nil or title == \"\" then\n -- Must use pcall in case of KeyboardInterrupt\n -- We cannot place `title` where `safe_title` is because it would be redeclaring it\n local success, safe_title = pcall(util.input, \"Enter title or path (optional): \", { completion = \"file\" })\n title = safe_title\n if not success or not safe_title then\n log.warn \"Aborted\"\n return\n elseif safe_title == \"\" then\n title = nil\n end\n end\n\n if template_name == nil or template_name == \"\" then\n log.warn \"Aborted\"\n return\n end\n\n ---@type obsidian.Note\n local note = Note.create { title = title, template = template_name, should_write = true }\n note:open { sync = false }\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/extract_note.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---Extract the selected text into a new note\n---and replace the selection with a link to the new note.\n---\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"Obsidian extract_note must be called with visual selection\"\n return\n end\n\n local content = vim.split(viz.selection, \"\\n\", { plain = true })\n\n ---@type string|?\n local title\n if data.args ~= nil and string.len(data.args) > 0 then\n title = vim.trim(data.args)\n else\n title = api.input \"Enter title (optional): \"\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n end\n\n -- create the new note.\n local note = Note.create { title = title }\n\n -- replace selection with link to new note\n local link = api.format_link(note)\n vim.api.nvim_buf_set_text(0, viz.csrow - 1, viz.cscol - 1, viz.cerow - 1, viz.cecol, { link })\n\n require(\"obsidian.ui\").update(0)\n\n -- add the selected text to the end of the new note\n note:open { sync = true }\n vim.api.nvim_buf_set_lines(0, -1, -1, false, content)\nend\n"], ["/obsidian.nvim/lua/obsidian/note.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal yaml = require \"obsidian.yaml\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\nlocal enumerate = util.enumerate\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal config = require \"obsidian.config\"\n\nlocal SKIP_UPDATING_FRONTMATTER = { \"README.md\", \"CONTRIBUTING.md\", \"CHANGELOG.md\" }\n\nlocal DEFAULT_MAX_LINES = 500\n\nlocal CODE_BLOCK_PATTERN = \"^%s*```[%w_-]*$\"\n\n--- @class obsidian.note.NoteCreationOpts\n--- @field notes_subdir string\n--- @field note_id_func fun()\n--- @field new_notes_location string\n\n--- @class obsidian.note.NoteOpts\n--- @field title string|? The note's title\n--- @field id string|? An ID to assign the note. If not specified one will be generated.\n--- @field dir string|obsidian.Path|? An optional directory to place the note in. Relative paths will be interpreted\n--- relative to the workspace / vault root. If the directory doesn't exist it will\n--- be created, regardless of the value of the `should_write` option.\n--- @field aliases string[]|? Aliases for the note\n--- @field tags string[]|? Tags for this note\n--- @field should_write boolean|? Don't write the note to disk\n--- @field template string|? The name of the template\n\n---@class obsidian.note.NoteSaveOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- Whether to insert/update frontmatter. Defaults to `true`.\n---@field insert_frontmatter? boolean\n--- Override the frontmatter. Defaults to the result of `self:frontmatter()`.\n---@field frontmatter? table\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload the updated file.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.NoteWriteOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- The name of a template to use if the note file doesn't already exist.\n---@field template? string\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload each buffer's content.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.HeaderAnchor\n---\n---@field anchor string\n---@field header string\n---@field level integer\n---@field line integer\n---@field parent obsidian.note.HeaderAnchor|?\n\n---@class obsidian.note.Block\n---\n---@field id string\n---@field line integer\n---@field block string\n\n--- A class that represents a note within a vault.\n---\n---@toc_entry obsidian.Note\n---\n---@class obsidian.Note : obsidian.ABC\n---\n---@field id string\n---@field aliases string[]\n---@field title string|?\n---@field tags string[]\n---@field path obsidian.Path|?\n---@field metadata table|?\n---@field has_frontmatter boolean|?\n---@field frontmatter_end_line integer|?\n---@field contents string[]|?\n---@field anchor_links table|?\n---@field blocks table?\n---@field alt_alias string|?\n---@field bufnr integer|?\nlocal Note = abc.new_class {\n __tostring = function(self)\n return string.format(\"Note('%s')\", self.id)\n end,\n}\n\nNote.is_note_obj = function(note)\n if getmetatable(note) == Note.mt then\n return true\n else\n return false\n end\nend\n\n--- Generate a unique ID for a new note. This respects the user's `note_id_func` if configured,\n--- otherwise falls back to generated a Zettelkasten style ID.\n---\n--- @param title? string\n--- @param path? obsidian.Path\n--- @param alt_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n---@return string\nlocal function generate_id(title, path, alt_id_func)\n if alt_id_func ~= nil then\n local new_id = alt_id_func(title, path)\n if new_id == nil or string.len(new_id) == 0 then\n error(string.format(\"Your 'note_id_func' must return a non-empty string, got '%s'!\", tostring(new_id)))\n end\n -- Remote '.md' suffix if it's there (we add that later).\n new_id = new_id:gsub(\"%.md$\", \"\", 1)\n return new_id\n else\n return require(\"obsidian.builtin\").zettel_id()\n end\nend\n\n--- Generate the file path for a new note given its ID, parent directory, and title.\n--- This respects the user's `note_path_func` if configured, otherwise essentially falls back to\n--- `note_opts.dir / (note_opts.id .. \".md\")`.\n---\n--- @param title string|? The title for the note\n--- @param id string The note ID\n--- @param dir obsidian.Path The note path\n---@return obsidian.Path\n---@private\nNote._generate_path = function(title, id, dir)\n ---@type obsidian.Path\n local path\n\n if Obsidian.opts.note_path_func ~= nil then\n path = Path.new(Obsidian.opts.note_path_func { id = id, dir = dir, title = title })\n -- Ensure path is either absolute or inside `opts.dir`.\n -- NOTE: `opts.dir` should always be absolute, but for extra safety we handle the case where\n -- it's not.\n if not path:is_absolute() and (dir:is_absolute() or not dir:is_parent_of(path)) then\n path = dir / path\n end\n else\n path = dir / tostring(id)\n end\n\n -- Ensure there is only one \".md\" suffix. This might arise if `note_path_func`\n -- supplies an unusual implementation returning something like /bad/note/id.md.md.md\n while path.filename:match \"%.md$\" do\n path.filename = path.filename:gsub(\"%.md$\", \"\")\n end\n\n return path:with_suffix(\".md\", true)\nend\n\n--- Selects the strategy to use when resolving the note title, id, and path\n--- @param opts obsidian.note.NoteOpts The note creation options\n--- @return obsidian.note.NoteCreationOpts The strategy to use for creating the note\n--- @private\nNote._get_creation_opts = function(opts)\n --- @type obsidian.note.NoteCreationOpts\n local default = {\n notes_subdir = Obsidian.opts.notes_subdir,\n note_id_func = Obsidian.opts.note_id_func,\n new_notes_location = Obsidian.opts.new_notes_location,\n }\n\n local resolve_template = require(\"obsidian.templates\").resolve_template\n local success, template_path = pcall(resolve_template, opts.template, api.templates_dir())\n\n if not success then\n return default\n end\n\n local stem = template_path.stem:lower()\n\n -- Check if the configuration has a custom key for this template\n for key, cfg in pairs(Obsidian.opts.templates.customizations) do\n if key:lower() == stem then\n return {\n notes_subdir = cfg.notes_subdir,\n note_id_func = cfg.note_id_func,\n new_notes_location = config.NewNotesLocation.notes_subdir,\n }\n end\n end\n return default\nend\n\n--- Resolves the title, ID, and path for a new note.\n---\n---@param title string|?\n---@param id string|?\n---@param dir string|obsidian.Path|? The directory for the note\n---@param strategy obsidian.note.NoteCreationOpts Strategy for resolving note path and title\n---@return string|?,string,obsidian.Path\n---@private\nNote._resolve_title_id_path = function(title, id, dir, strategy)\n if title then\n title = vim.trim(title)\n if title == \"\" then\n title = nil\n end\n end\n\n if id then\n id = vim.trim(id)\n if id == \"\" then\n id = nil\n end\n end\n\n ---@param s string\n ---@param strict_paths_only boolean\n ---@return string|?, boolean, string|?\n local parse_as_path = function(s, strict_paths_only)\n local is_path = false\n ---@type string|?\n local parent\n\n if s:match \"%.md\" then\n -- Remove suffix.\n s = s:sub(1, s:len() - 3)\n is_path = true\n end\n\n -- Pull out any parent dirs from title.\n local parts = vim.split(s, \"/\")\n if #parts > 1 then\n s = parts[#parts]\n if not strict_paths_only then\n is_path = true\n end\n parent = table.concat(parts, \"/\", 1, #parts - 1)\n end\n\n if s == \"\" then\n return nil, is_path, parent\n else\n return s, is_path, parent\n end\n end\n\n local parent, _, title_is_path\n if id then\n id, _, parent = parse_as_path(id, false)\n elseif title then\n title, title_is_path, parent = parse_as_path(title, true)\n if title_is_path then\n id = title\n end\n end\n\n -- Resolve base directory.\n ---@type obsidian.Path\n local base_dir\n if parent then\n base_dir = Obsidian.dir / parent\n elseif dir ~= nil then\n base_dir = Path.new(dir)\n if not base_dir:is_absolute() then\n base_dir = Obsidian.dir / base_dir\n else\n base_dir = base_dir:resolve()\n end\n else\n local bufpath = Path.buffer(0):resolve()\n if\n strategy.new_notes_location == config.NewNotesLocation.current_dir\n -- note is actually in the workspace.\n and Obsidian.dir:is_parent_of(bufpath)\n -- note is not in dailies folder\n and (\n Obsidian.opts.daily_notes.folder == nil\n or not (Obsidian.dir / Obsidian.opts.daily_notes.folder):is_parent_of(bufpath)\n )\n then\n base_dir = Obsidian.buf_dir or assert(bufpath:parent())\n else\n base_dir = Obsidian.dir\n if strategy.notes_subdir then\n base_dir = base_dir / strategy.notes_subdir\n end\n end\n end\n\n -- Make sure `base_dir` is absolute at this point.\n assert(base_dir:is_absolute(), (\"failed to resolve note directory '%s'\"):format(base_dir))\n\n -- Generate new ID if needed.\n if not id then\n id = generate_id(title, base_dir, strategy.note_id_func)\n end\n\n dir = base_dir\n\n -- Generate path.\n local path = Note._generate_path(title, id, dir)\n\n return title, id, path\nend\n\n--- Creates a new note\n---\n--- @param opts obsidian.note.NoteOpts Options\n--- @return obsidian.Note\nNote.create = function(opts)\n local new_title, new_id, path =\n Note._resolve_title_id_path(opts.title, opts.id, opts.dir, Note._get_creation_opts(opts))\n opts = vim.tbl_extend(\"keep\", opts, { aliases = {}, tags = {} })\n\n -- Add the title as an alias.\n --- @type string[]\n local aliases = opts.aliases\n if new_title ~= nil and new_title:len() > 0 and not vim.list_contains(aliases, new_title) then\n aliases[#aliases + 1] = new_title\n end\n\n local note = Note.new(new_id, aliases, opts.tags, path)\n\n if new_title then\n note.title = new_title\n end\n\n -- Ensure the parent directory exists.\n local parent = path:parent()\n assert(parent)\n parent:mkdir { parents = true, exist_ok = true }\n\n -- Write to disk.\n if opts.should_write then\n note:write { template = opts.template }\n end\n\n return note\nend\n\n--- Instantiates a new Note object\n---\n--- Keep in mind that you have to call `note:save(...)` to create/update the note on disk.\n---\n--- @param id string|number\n--- @param aliases string[]\n--- @param tags string[]\n--- @param path string|obsidian.Path|?\n--- @return obsidian.Note\nNote.new = function(id, aliases, tags, path)\n local self = Note.init()\n self.id = id\n self.aliases = aliases and aliases or {}\n self.tags = tags and tags or {}\n self.path = path and Path.new(path) or nil\n self.metadata = nil\n self.has_frontmatter = nil\n self.frontmatter_end_line = nil\n return self\nend\n\n--- Get markdown display info about the note.\n---\n---@param opts { label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|?\n---\n---@return string\nNote.display_info = function(self, opts)\n opts = opts and opts or {}\n\n ---@type string[]\n local info = {}\n\n if opts.label ~= nil and string.len(opts.label) > 0 then\n info[#info + 1] = (\"%s\"):format(opts.label)\n info[#info + 1] = \"--------\"\n end\n\n if self.path ~= nil then\n info[#info + 1] = (\"**path:** `%s`\"):format(self.path)\n end\n\n info[#info + 1] = (\"**id:** `%s`\"):format(self.id)\n\n if #self.aliases > 0 then\n info[#info + 1] = (\"**aliases:** '%s'\"):format(table.concat(self.aliases, \"', '\"))\n end\n\n if #self.tags > 0 then\n info[#info + 1] = (\"**tags:** `#%s`\"):format(table.concat(self.tags, \"`, `#\"))\n end\n\n if opts.anchor or opts.block then\n info[#info + 1] = \"--------\"\n\n if opts.anchor then\n info[#info + 1] = (\"...\\n%s %s\\n...\"):format(string.rep(\"#\", opts.anchor.level), opts.anchor.header)\n elseif opts.block then\n info[#info + 1] = (\"...\\n%s\\n...\"):format(opts.block.block)\n end\n end\n\n return table.concat(info, \"\\n\")\nend\n\n--- Check if the note exists on the file system.\n---\n---@return boolean\nNote.exists = function(self)\n ---@diagnostic disable-next-line: return-type-mismatch\n return self.path ~= nil and self.path:is_file()\nend\n\n--- Get the filename associated with the note.\n---\n---@return string|?\nNote.fname = function(self)\n if self.path == nil then\n return nil\n else\n return vim.fs.basename(tostring(self.path))\n end\nend\n\n--- Get a list of all of the different string that can identify this note via references,\n--- including the ID, aliases, and filename.\n---@param opts { lowercase: boolean|? }|?\n---@return string[]\nNote.reference_ids = function(self, opts)\n opts = opts or {}\n ---@type string[]\n local ref_ids = { tostring(self.id), self:display_name() }\n if self.path then\n table.insert(ref_ids, self.path.name)\n table.insert(ref_ids, self.path.stem)\n end\n\n vim.list_extend(ref_ids, self.aliases)\n\n if opts.lowercase then\n ref_ids = vim.tbl_map(string.lower, ref_ids)\n end\n\n return util.tbl_unique(ref_ids)\nend\n\n--- Check if a note has a given alias.\n---\n---@param alias string\n---\n---@return boolean\nNote.has_alias = function(self, alias)\n return vim.list_contains(self.aliases, alias)\nend\n\n--- Check if a note has a given tag.\n---\n---@param tag string\n---\n---@return boolean\nNote.has_tag = function(self, tag)\n return vim.list_contains(self.tags, tag)\nend\n\n--- Add an alias to the note.\n---\n---@param alias string\n---\n---@return boolean added True if the alias was added, false if it was already present.\nNote.add_alias = function(self, alias)\n if not self:has_alias(alias) then\n table.insert(self.aliases, alias)\n return true\n else\n return false\n end\nend\n\n--- Add a tag to the note.\n---\n---@param tag string\n---\n---@return boolean added True if the tag was added, false if it was already present.\nNote.add_tag = function(self, tag)\n if not self:has_tag(tag) then\n table.insert(self.tags, tag)\n return true\n else\n return false\n end\nend\n\n--- Add or update a field in the frontmatter.\n---\n---@param key string\n---@param value any\nNote.add_field = function(self, key, value)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Updating field '%s' this way is not allowed. Please update the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n self.metadata = {}\n end\n\n self.metadata[key] = value\nend\n\n--- Get a field in the frontmatter.\n---\n---@param key string\n---\n---@return any result\nNote.get_field = function(self, key)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Getting field '%s' this way is not allowed. Please use the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n return nil\n end\n\n return self.metadata[key]\nend\n\n---@class obsidian.note.LoadOpts\n---@field max_lines integer|?\n---@field load_contents boolean|?\n---@field collect_anchor_links boolean|?\n---@field collect_blocks boolean|?\n\n--- Initialize a note from a file.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file = function(path, opts)\n if path == nil then\n error \"note path cannot be nil\"\n end\n path = tostring(Path.new(path):resolve { strict = true })\n return Note.from_lines(io.lines(path), path, opts)\nend\n\n--- An async version of `.from_file()`, i.e. it needs to be called in an async context.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file_async = function(path, opts)\n path = Path.new(path):resolve { strict = true }\n local f = io.open(tostring(path), \"r\")\n assert(f)\n local ok, res = pcall(Note.from_lines, f:lines \"*l\", path, opts)\n f:close()\n if ok then\n return res\n else\n error(res)\n end\nend\n\n--- Like `.from_file_async()` but also returns the contents of the file as a list of lines.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note,string[]\nNote.from_file_with_contents_async = function(path, opts)\n opts = vim.tbl_extend(\"force\", opts or {}, { load_contents = true })\n local note = Note.from_file_async(path, opts)\n assert(note.contents ~= nil)\n return note, note.contents\nend\n\n--- Initialize a note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_buffer = function(bufnr, opts)\n bufnr = bufnr or vim.api.nvim_get_current_buf()\n local path = vim.api.nvim_buf_get_name(bufnr)\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)\n local note = Note.from_lines(iter(lines), path, opts)\n note.bufnr = bufnr\n return note\nend\n\n--- Get the display name for note.\n---\n---@return string\nNote.display_name = function(self)\n if self.title then\n return self.title\n elseif #self.aliases > 0 then\n return self.aliases[#self.aliases]\n end\n return tostring(self.id)\nend\n\n--- Initialize a note from an iterator of lines.\n---\n---@param lines fun(): string|? | Iter\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_lines = function(lines, path, opts)\n opts = opts or {}\n path = Path.new(path):resolve()\n\n local max_lines = opts.max_lines or DEFAULT_MAX_LINES\n\n local id = nil\n local title = nil\n local aliases = {}\n local tags = {}\n\n ---@type string[]|?\n local contents\n if opts.load_contents then\n contents = {}\n end\n\n ---@type table|?\n local anchor_links\n ---@type obsidian.note.HeaderAnchor[]|?\n local anchor_stack\n if opts.collect_anchor_links then\n anchor_links = {}\n anchor_stack = {}\n end\n\n ---@type table|?\n local blocks\n if opts.collect_blocks then\n blocks = {}\n end\n\n ---@param anchor_data obsidian.note.HeaderAnchor\n ---@return obsidian.note.HeaderAnchor|?\n local function get_parent_anchor(anchor_data)\n assert(anchor_links)\n assert(anchor_stack)\n for i = #anchor_stack, 1, -1 do\n local parent = anchor_stack[i]\n if parent.level < anchor_data.level then\n return parent\n end\n end\n end\n\n ---@param anchor string\n ---@param data obsidian.note.HeaderAnchor|?\n local function format_nested_anchor(anchor, data)\n local out = anchor\n if not data then\n return out\n end\n\n local parent = data.parent\n while parent ~= nil do\n out = parent.anchor .. out\n data = get_parent_anchor(parent)\n if data then\n parent = data.parent\n else\n parent = nil\n end\n end\n\n return out\n end\n\n -- Iterate over lines in the file, collecting frontmatter and parsing the title.\n local frontmatter_lines = {}\n local has_frontmatter, in_frontmatter, at_boundary = false, false, false -- luacheck: ignore (false positive)\n local frontmatter_end_line = nil\n local in_code_block = false\n for line_idx, line in enumerate(lines) do\n line = util.rstrip_whitespace(line)\n\n if line_idx == 1 and Note._is_frontmatter_boundary(line) then\n has_frontmatter = true\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n frontmatter_end_line = line_idx\n else\n at_boundary = false\n end\n\n if string.match(line, CODE_BLOCK_PATTERN) then\n in_code_block = not in_code_block\n end\n\n if in_frontmatter and not at_boundary then\n table.insert(frontmatter_lines, line)\n elseif not in_frontmatter and not at_boundary and not in_code_block then\n -- Check for title/header and collect anchor link.\n local header_match = util.parse_header(line)\n if header_match then\n if not title and header_match.level == 1 then\n title = header_match.header\n end\n\n -- Collect anchor link.\n if opts.collect_anchor_links then\n assert(anchor_links)\n assert(anchor_stack)\n -- We collect up to two anchor for each header. One standalone, e.g. '#header1', and\n -- one with the parents, e.g. '#header1#header2'.\n -- This is our standalone one:\n ---@type obsidian.note.HeaderAnchor\n local data = {\n anchor = header_match.anchor,\n line = line_idx,\n header = header_match.header,\n level = header_match.level,\n }\n data.parent = get_parent_anchor(data)\n\n anchor_links[header_match.anchor] = data\n table.insert(anchor_stack, data)\n\n -- Now if there's a parent we collect the nested version. All of the data will be the same\n -- except the anchor key.\n if data.parent ~= nil then\n local nested_anchor = format_nested_anchor(header_match.anchor, data)\n anchor_links[nested_anchor] = vim.tbl_extend(\"force\", data, { anchor = nested_anchor })\n end\n end\n end\n\n -- Check for block.\n if opts.collect_blocks then\n local block = util.parse_block(line)\n if block then\n blocks[block] = { id = block, line = line_idx, block = line }\n end\n end\n end\n\n -- Collect contents.\n if contents ~= nil then\n table.insert(contents, line)\n end\n\n -- Check if we can stop reading lines now.\n if\n line_idx > max_lines\n or (title and not opts.load_contents and not opts.collect_anchor_links and not opts.collect_blocks)\n then\n break\n end\n end\n\n if title ~= nil then\n -- Remove references and links from title\n title = search.replace_refs(title)\n end\n\n -- Parse the frontmatter YAML.\n local metadata = nil\n if #frontmatter_lines > 0 then\n local frontmatter = table.concat(frontmatter_lines, \"\\n\")\n local ok, data = pcall(yaml.loads, frontmatter)\n if type(data) ~= \"table\" then\n data = {}\n end\n if ok then\n ---@diagnostic disable-next-line: param-type-mismatch\n for k, v in pairs(data) do\n if k == \"id\" then\n if type(v) == \"string\" or type(v) == \"number\" then\n id = v\n else\n log.warn(\"Invalid 'id' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"aliases\" then\n if type(v) == \"table\" then\n for alias in iter(v) do\n if type(alias) == \"string\" then\n table.insert(aliases, alias)\n else\n log.warn(\n \"Invalid alias value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(alias)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n table.insert(aliases, v)\n else\n log.warn(\"Invalid 'aliases' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"tags\" then\n if type(v) == \"table\" then\n for tag in iter(v) do\n if type(tag) == \"string\" then\n table.insert(tags, tag)\n else\n log.warn(\n \"Invalid tag value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(tag)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n tags = vim.split(v, \" \")\n else\n log.warn(\"Invalid 'tags' in frontmatter for '%s'\", path)\n end\n else\n if metadata == nil then\n metadata = {}\n end\n metadata[k] = v\n end\n end\n end\n end\n\n -- ID should default to the filename without the extension.\n if id == nil or id == path.name then\n id = path.stem\n end\n assert(id)\n\n local n = Note.new(id, aliases, tags, path)\n n.title = title\n n.metadata = metadata\n n.has_frontmatter = has_frontmatter\n n.frontmatter_end_line = frontmatter_end_line\n n.contents = contents\n n.anchor_links = anchor_links\n n.blocks = blocks\n return n\nend\n\n--- Check if a line matches a frontmatter boundary.\n---\n---@param line string\n---\n---@return boolean\n---\n---@private\nNote._is_frontmatter_boundary = function(line)\n return line:match \"^---+$\" ~= nil\nend\n\n--- Get the frontmatter table to save.\n---\n---@return table\nNote.frontmatter = function(self)\n local out = { id = self.id, aliases = self.aliases, tags = self.tags }\n if self.metadata ~= nil and not vim.tbl_isempty(self.metadata) then\n for k, v in pairs(self.metadata) do\n out[k] = v\n end\n end\n return out\nend\n\n--- Get frontmatter lines that can be written to a buffer.\n---\n---@param eol boolean|?\n---@param frontmatter table|?\n---\n---@return string[]\nNote.frontmatter_lines = function(self, eol, frontmatter)\n local new_lines = { \"---\" }\n\n local frontmatter_ = frontmatter and frontmatter or self:frontmatter()\n if vim.tbl_isempty(frontmatter_) then\n return {}\n end\n\n for line in\n iter(yaml.dumps_lines(frontmatter_, function(a, b)\n local a_idx = nil\n local b_idx = nil\n for i, k in ipairs { \"id\", \"aliases\", \"tags\" } do\n if a == k then\n a_idx = i\n end\n if b == k then\n b_idx = i\n end\n end\n if a_idx ~= nil and b_idx ~= nil then\n return a_idx < b_idx\n elseif a_idx ~= nil then\n return true\n elseif b_idx ~= nil then\n return false\n else\n return a < b\n end\n end))\n do\n table.insert(new_lines, line)\n end\n\n table.insert(new_lines, \"---\")\n if not self.has_frontmatter then\n -- Make sure there's an empty line between end of the frontmatter and the contents.\n table.insert(new_lines, \"\")\n end\n\n if eol then\n return vim.tbl_map(function(l)\n return l .. \"\\n\"\n end, new_lines)\n else\n return new_lines\n end\nend\n\n--- Update the frontmatter in a buffer for the note.\n---\n---@param bufnr integer|?\n---\n---@return boolean updated If the the frontmatter was updated.\nNote.update_frontmatter = function(self, bufnr)\n if not self:should_save_frontmatter() then\n return false\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n return self:save_to_buffer { bufnr = bufnr, frontmatter = frontmatter }\nend\n\n--- Checks if the parameter note is in the blacklist of files which shouldn't have\n--- frontmatter applied\n---\n--- @param note obsidian.Note The note\n--- @return boolean true if so\nlocal is_in_frontmatter_blacklist = function(note)\n local fname = note:fname()\n return (fname ~= nil and vim.list_contains(SKIP_UPDATING_FRONTMATTER, fname))\nend\n\n--- Determines whether a note's frontmatter is managed by obsidian.nvim.\n---\n---@return boolean\nNote.should_save_frontmatter = function(self)\n -- Check if the note is a template.\n local templates_dir = api.templates_dir()\n if templates_dir ~= nil then\n templates_dir = templates_dir:resolve()\n for _, parent in ipairs(self.path:parents()) do\n if parent == templates_dir then\n return false\n end\n end\n end\n\n if is_in_frontmatter_blacklist(self) then\n return false\n elseif type(Obsidian.opts.disable_frontmatter) == \"boolean\" then\n return not Obsidian.opts.disable_frontmatter\n elseif type(Obsidian.opts.disable_frontmatter) == \"function\" then\n return not Obsidian.opts.disable_frontmatter(self.path:vault_relative_path { strict = true })\n else\n return true\n end\nend\n\n--- Write the note to disk.\n---\n---@param opts? obsidian.note.NoteWriteOpts\n---@return obsidian.Note\nNote.write = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n local path = assert(self.path, \"A path must be provided\")\n path = Path.new(path)\n\n ---@type string\n local verb\n if path:is_file() then\n verb = \"Updated\"\n else\n verb = \"Created\"\n if opts.template ~= nil then\n self = Template.clone_template {\n type = \"clone_template\",\n template_name = opts.template,\n destination_path = path,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n partial_note = self,\n }\n end\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n self:save {\n path = path,\n insert_frontmatter = self:should_save_frontmatter(),\n frontmatter = frontmatter,\n update_content = opts.update_content,\n check_buffers = opts.check_buffers,\n }\n\n log.info(\"%s note '%s' at '%s'\", verb, self.id, self.path:vault_relative_path(self.path) or self.path)\n\n return self\nend\n\n--- Save the note to a file.\n--- In general this only updates the frontmatter and header, leaving the rest of the contents unchanged\n--- unless you use the `update_content()` callback.\n---\n---@param opts? obsidian.note.NoteSaveOpts\nNote.save = function(self, opts)\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n if self.path == nil then\n error \"a path is required\"\n end\n\n local save_path = Path.new(assert(opts.path or self.path)):resolve()\n assert(save_path:parent()):mkdir { parents = true, exist_ok = true }\n\n -- Read contents from existing file or buffer, if there is one.\n -- TODO: check for open buffer?\n ---@type string[]\n local content = {}\n ---@type string[]\n local existing_frontmatter = {}\n if self.path ~= nil and self.path:is_file() then\n -- with(open(tostring(self.path)), function(reader)\n local in_frontmatter, at_boundary = false, false -- luacheck: ignore (false positive)\n for idx, line in enumerate(io.lines(tostring(self.path))) do\n if idx == 1 and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n else\n at_boundary = false\n end\n\n if not in_frontmatter and not at_boundary then\n table.insert(content, line)\n else\n table.insert(existing_frontmatter, line)\n end\n end\n -- end)\n elseif self.title ~= nil then\n -- Add a header.\n table.insert(content, \"# \" .. self.title)\n end\n\n -- Pass content through callback.\n if opts.update_content then\n content = opts.update_content(content)\n end\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n -- Replace frontmatter.\n new_lines = compat.flatten { self:frontmatter_lines(false, opts.frontmatter), content }\n else\n -- Use existing frontmatter.\n new_lines = compat.flatten { existing_frontmatter, content }\n end\n\n util.write_file(tostring(save_path), table.concat(new_lines, \"\\n\"))\n\n if opts.check_buffers then\n -- `vim.fn.bufnr` returns the **max** bufnr loaded from the same path.\n if vim.fn.bufnr(save_path.filename) ~= -1 then\n -- But we want to call |checktime| on **all** buffers loaded from the path.\n vim.cmd.checktime(save_path.filename)\n end\n end\nend\n\n--- Write the note to a buffer.\n---\n---@param opts { bufnr: integer|?, template: string|? }|? Options.\n---\n--- Options:\n--- - `bufnr`: Override the buffer to write to. Defaults to current buffer.\n--- - `template`: The name of a template to use if the buffer is empty.\n---\n---@return boolean updated If the buffer was updated.\nNote.write_to_buffer = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = opts or {}\n\n if opts.template and api.buffer_is_empty(opts.bufnr) then\n self = Template.insert_template {\n type = \"insert_template\",\n template_name = opts.template,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n location = api.get_active_window_cursor_location(),\n partial_note = self,\n }\n end\n\n local frontmatter = nil\n local should_save_frontmatter = self:should_save_frontmatter()\n if should_save_frontmatter and Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n return self:save_to_buffer {\n bufnr = opts.bufnr,\n insert_frontmatter = should_save_frontmatter,\n frontmatter = frontmatter,\n }\nend\n\n--- Save the note to the buffer\n---\n---@param opts { bufnr: integer|?, insert_frontmatter: boolean|?, frontmatter: table|? }|? Options.\n---\n---@return boolean updated True if the buffer lines were updated, false otherwise.\nNote.save_to_buffer = function(self, opts)\n opts = opts or {}\n\n local bufnr = opts.bufnr\n if not bufnr then\n bufnr = self.bufnr or 0\n end\n\n local cur_buf_note = Note.from_buffer(bufnr)\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n new_lines = self:frontmatter_lines(nil, opts.frontmatter)\n else\n new_lines = {}\n end\n\n if api.buffer_is_empty(bufnr) and self.title ~= nil then\n table.insert(new_lines, \"# \" .. self.title)\n end\n\n ---@type string[]\n local cur_lines = {}\n if cur_buf_note.frontmatter_end_line ~= nil then\n cur_lines = vim.api.nvim_buf_get_lines(bufnr, 0, cur_buf_note.frontmatter_end_line, false)\n end\n\n if not vim.deep_equal(cur_lines, new_lines) then\n vim.api.nvim_buf_set_lines(\n bufnr,\n 0,\n cur_buf_note.frontmatter_end_line and cur_buf_note.frontmatter_end_line or 0,\n false,\n new_lines\n )\n return true\n else\n return false\n end\nend\n\n--- Try to resolve an anchor link to a line number in the note's file.\n---\n---@param anchor_link string\n---@return obsidian.note.HeaderAnchor|?\nNote.resolve_anchor_link = function(self, anchor_link)\n anchor_link = util.standardize_anchor(anchor_link)\n\n if self.anchor_links ~= nil then\n return self.anchor_links[anchor_link]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_anchor_links = true })\n self.anchor_links = n.anchor_links\n return n:resolve_anchor_link(anchor_link)\nend\n\n--- Try to resolve a block identifier.\n---\n---@param block_id string\n---\n---@return obsidian.note.Block|?\nNote.resolve_block = function(self, block_id)\n block_id = util.standardize_block(block_id)\n\n if self.blocks ~= nil then\n return self.blocks[block_id]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_blocks = true })\n self.blocks = n.blocks\n return self.blocks[block_id]\nend\n\n--- Open a note in a buffer.\n---@param opts { line: integer|?, col: integer|?, open_strategy: obsidian.config.OpenStrategy|?, sync: boolean|?, callback: fun(bufnr: integer)|? }|?\nNote.open = function(self, opts)\n opts = opts or {}\n\n local path = self.path\n\n local function open_it()\n local open_cmd = api.get_open_strategy(opts.open_strategy and opts.open_strategy or Obsidian.opts.open_notes_in)\n ---@cast path obsidian.Path\n local bufnr = api.open_buffer(path, { line = opts.line, col = opts.col, cmd = open_cmd })\n if opts.callback then\n opts.callback(bufnr)\n end\n end\n\n if opts.sync then\n open_it()\n else\n vim.schedule(open_it)\n end\nend\n\nreturn Note\n"], ["/obsidian.nvim/lua/obsidian/commands/link_new.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n local title\n if string.len(data.args) > 0 then\n title = data.args\n else\n title = viz.selection\n end\n\n local note = Note.create { title = title }\n\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = title })\n .. string.sub(line, viz.cecol + 1)\n\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/rename.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal util = require \"obsidian.util\"\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal enumerate, zip = util.enumerate, util.zip\n\nlocal resolve_note = function(query, opts)\n opts = opts or {}\n return require(\"obsidian.async\").block_on(function(cb)\n print(query)\n return search.resolve_note_async(query, cb, { notes = opts.notes })\n end, 5000)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n -- Resolve the note to rename.\n ---@type boolean\n local is_current_buf\n ---@type integer|?\n local cur_note_bufnr\n ---@type obsidian.Path\n local cur_note_path\n ---@type obsidian.Note\n local cur_note, cur_note_id\n\n local cur_link = api.cursor_link()\n if not cur_link then\n -- rename current note\n is_current_buf = true\n cur_note_bufnr = assert(vim.fn.bufnr())\n cur_note_path = Path.buffer(cur_note_bufnr)\n cur_note = Note.from_file(cur_note_path)\n cur_note_id = tostring(cur_note.id)\n else\n -- rename note under the cursor\n local link_id = util.parse_link(cur_link)\n local notes = { resolve_note(link_id) }\n if #notes == 0 then\n log.err(\"Failed to resolve '%s' to a note\", cur_link)\n return\n elseif #notes > 1 then\n log.err(\"Failed to resolve '%s' to a single note, found %d matches\", cur_link, #notes)\n return\n else\n cur_note = notes[1]\n end\n\n is_current_buf = false\n cur_note_id = tostring(cur_note.id)\n cur_note_path = cur_note.path\n for bufnr, bufpath in api.get_named_buffers() do\n if bufpath == cur_note_path then\n cur_note_bufnr = bufnr\n break\n end\n end\n end\n\n -- Validate args.\n local dry_run = false\n ---@type string|?\n local arg\n\n if data.args == \"--dry-run\" then\n dry_run = true\n data.args = nil\n end\n\n if data.args ~= nil and string.len(data.args) > 0 then\n arg = vim.trim(data.args)\n else\n arg = api.input(\"Enter new note ID/name/path: \", { completion = \"file\", default = cur_note_id })\n if not arg or string.len(arg) == 0 then\n log.warn \"Rename aborted\"\n return\n end\n end\n\n if vim.endswith(arg, \" --dry-run\") then\n dry_run = true\n arg = vim.trim(string.sub(arg, 1, -string.len \" --dry-run\" - 1))\n end\n\n assert(cur_note_path)\n local dirname = assert(cur_note_path:parent(), string.format(\"failed to resolve parent of '%s'\", cur_note_path))\n\n -- Parse new note ID / path from args.\n local parts = vim.split(arg, \"/\", { plain = true })\n local new_note_id = parts[#parts]\n if new_note_id == \"\" then\n log.err \"Invalid new note ID\"\n return\n elseif vim.endswith(new_note_id, \".md\") then\n new_note_id = string.sub(new_note_id, 1, -4)\n end\n\n ---@type obsidian.Path\n local new_note_path\n if #parts > 1 then\n parts[#parts] = nil\n new_note_path = Obsidian.dir:joinpath(unpack(compat.flatten { parts, new_note_id })):with_suffix \".md\"\n else\n new_note_path = (dirname / new_note_id):with_suffix \".md\"\n end\n\n if new_note_id == cur_note_id then\n log.warn \"New note ID is the same, doing nothing\"\n return\n end\n\n -- Get confirmation before continuing.\n local confirmation\n if not dry_run then\n confirmation = api.confirm(\n \"Renaming '\"\n .. cur_note_id\n .. \"' to '\"\n .. new_note_id\n .. \"'...\\n\"\n .. \"This will write all buffers and potentially modify a lot of files. If you're using version control \"\n .. \"with your vault it would be a good idea to commit the current state of your vault before running this.\\n\"\n .. \"You can also do a dry run of this by running ':Obsidian rename \"\n .. arg\n .. \" --dry-run'.\\n\"\n .. \"Do you want to continue?\"\n )\n else\n confirmation = api.confirm(\n \"Dry run: renaming '\" .. cur_note_id .. \"' to '\" .. new_note_id .. \"'...\\n\" .. \"Do you want to continue?\"\n )\n end\n\n if not confirmation then\n log.warn \"Rename aborted\"\n return\n end\n\n ---@param fn function\n local function quietly(fn, ...)\n local ok, res = pcall(fn, ...)\n if not ok then\n error(res)\n end\n end\n\n -- Write all buffers.\n quietly(vim.cmd.wall)\n\n -- Rename the note file and remove or rename the corresponding buffer, if there is one.\n if cur_note_bufnr ~= nil then\n if is_current_buf then\n -- If we're renaming the note of a current buffer, save as the new path.\n if not dry_run then\n quietly(vim.cmd.saveas, tostring(new_note_path))\n local new_bufnr_current_note = vim.fn.bufnr(tostring(cur_note_path))\n quietly(vim.cmd.bdelete, new_bufnr_current_note)\n vim.fn.delete(tostring(cur_note_path))\n else\n log.info(\"Dry run: saving current buffer as '\" .. tostring(new_note_path) .. \"' and removing old file\")\n end\n else\n -- For the non-current buffer the best we can do is delete the buffer (we've already saved it above)\n -- and then make a file-system call to rename the file.\n if not dry_run then\n quietly(vim.cmd.bdelete, cur_note_bufnr)\n cur_note_path:rename(new_note_path)\n else\n log.info(\n \"Dry run: removing buffer '\"\n .. tostring(cur_note_path)\n .. \"' and renaming file to '\"\n .. tostring(new_note_path)\n .. \"'\"\n )\n end\n end\n else\n -- When the note is not loaded into a buffer we just need to rename the file.\n if not dry_run then\n cur_note_path:rename(new_note_path)\n else\n log.info(\"Dry run: renaming file '\" .. tostring(cur_note_path) .. \"' to '\" .. tostring(new_note_path) .. \"'\")\n end\n end\n\n -- We need to update its frontmatter note_id\n -- to account for the rename.\n cur_note.id = new_note_id\n cur_note.path = Path.new(new_note_path)\n if not dry_run then\n cur_note:save()\n else\n log.info(\"Dry run: updating frontmatter of '\" .. tostring(new_note_path) .. \"'\")\n end\n\n local cur_note_rel_path = assert(cur_note_path:vault_relative_path { strict = true })\n local new_note_rel_path = assert(new_note_path:vault_relative_path { strict = true })\n\n -- Search notes on disk for any references to `cur_note_id`.\n -- We look for the following forms of references:\n -- * '[[cur_note_id]]'\n -- * '[[cur_note_id|ALIAS]]'\n -- * '[[cur_note_id\\|ALIAS]]' (a wiki link within a table)\n -- * '[ALIAS](cur_note_id)'\n -- And all of the above with relative paths (from the vault root) to the note instead of just the note ID,\n -- with and without the \".md\" suffix.\n -- Another possible form is [[ALIAS]], but we don't change the note's aliases when renaming\n -- so those links will still be valid.\n ---@param ref_link string\n ---@return string[]\n local function get_ref_forms(ref_link)\n return {\n \"[[\" .. ref_link .. \"]]\",\n \"[[\" .. ref_link .. \"|\",\n \"[[\" .. ref_link .. \"\\\\|\",\n \"[[\" .. ref_link .. \"#\",\n \"](\" .. ref_link .. \")\",\n \"](\" .. ref_link .. \"#\",\n }\n end\n\n local reference_forms = compat.flatten {\n get_ref_forms(cur_note_id),\n get_ref_forms(cur_note_rel_path),\n get_ref_forms(string.sub(cur_note_rel_path, 1, -4)),\n }\n local replace_with = compat.flatten {\n get_ref_forms(new_note_id),\n get_ref_forms(new_note_rel_path),\n get_ref_forms(string.sub(new_note_rel_path, 1, -4)),\n }\n\n local executor = AsyncExecutor.new()\n\n local file_count = 0\n local replacement_count = 0\n local all_tasks_submitted = false\n\n ---@param path string\n ---@return integer\n local function replace_refs(path)\n --- Read lines, replacing refs as we go.\n local count = 0\n local lines = {}\n local f = io.open(path, \"r\")\n assert(f)\n for line_num, line in enumerate(f:lines \"*L\") do\n for ref, replacement in zip(reference_forms, replace_with) do\n local n\n line, n = string.gsub(line, vim.pesc(ref), replacement)\n if dry_run and n > 0 then\n log.info(\n \"Dry run: '\"\n .. tostring(path)\n .. \"':\"\n .. line_num\n .. \" Replacing \"\n .. n\n .. \" occurrence(s) of '\"\n .. ref\n .. \"' with '\"\n .. replacement\n .. \"'\"\n )\n end\n count = count + n\n end\n lines[#lines + 1] = line\n end\n f:close()\n\n --- Write the new lines back.\n if not dry_run and count > 0 then\n f = io.open(path, \"w\")\n assert(f)\n f:write(unpack(lines))\n f:close()\n end\n\n return count\n end\n\n local function on_search_match(match)\n local path = tostring(Path.new(match.path.text):resolve { strict = true })\n file_count = file_count + 1\n executor:submit(replace_refs, function(count)\n replacement_count = replacement_count + count\n end, path)\n end\n\n search.search_async(\n Obsidian.dir,\n reference_forms,\n { fixed_strings = true, max_count_per_file = 1 },\n on_search_match,\n function(_)\n all_tasks_submitted = true\n end\n )\n\n -- Wait for all tasks to get submitted.\n vim.wait(2000, function()\n return all_tasks_submitted\n end, 50, false)\n\n -- Then block until all tasks are finished.\n executor:join(2000)\n\n local prefix = dry_run and \"Dry run: replaced \" or \"Replaced \"\n log.info(prefix .. replacement_count .. \" reference(s) across \" .. file_count .. \" file(s)\")\n\n -- In case the files of any current buffers were changed.\n vim.cmd.checktime()\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/new.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.NewNoteSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\nlocal NewNoteSourceCompletionContext = abc.new_class()\n\nNewNoteSourceCompletionContext.new = function()\n return NewNoteSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.NewNoteSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal NewNoteSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.NewNoteSourceBase\nNewNoteSourceBase.new = function()\n return NewNoteSourceBase.init()\nend\n\nNewNoteSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = NewNoteSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n ---@type string|?\n local block_link\n cc.search, block_link = util.strip_block_links(cc.search)\n\n ---@type string|?\n local anchor_link\n cc.search, anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, do nothing.\n if not block_link and vim.endswith(cc.search, \"#^\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- If anchor link is incomplete, do nothing.\n if not anchor_link and vim.endswith(cc.search, \"#\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Probably just a block/anchor link within current note.\n if string.len(cc.search) == 0 then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Create a mock block.\n ---@type obsidian.note.Block|?\n local block\n if block_link then\n block = { block = \"\", id = util.standardize_block(block_link), line = 1 }\n end\n\n -- Create a mock anchor.\n ---@type obsidian.note.HeaderAnchor|?\n local anchor\n if anchor_link then\n anchor = { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 }\n end\n\n ---@type { label: string, note: obsidian.Note, template: string|? }[]\n local new_notes_opts = {}\n\n local note = Note.create { title = cc.search }\n if note.title and string.len(note.title) > 0 then\n new_notes_opts[#new_notes_opts + 1] = { label = cc.search, note = note }\n end\n\n -- Check for datetime macros.\n for _, dt_offset in ipairs(util.resolve_date_macro(cc.search)) do\n if dt_offset.cadence == \"daily\" then\n note = require(\"obsidian.daily\").daily(dt_offset.offset, { no_write = true })\n if not note:exists() then\n new_notes_opts[#new_notes_opts + 1] =\n { label = dt_offset.macro, note = note, template = Obsidian.opts.daily_notes.template }\n end\n end\n end\n\n -- Completion items.\n local items = {}\n\n for _, new_note_opts in ipairs(new_notes_opts) do\n local new_note = new_note_opts.note\n\n assert(new_note.path)\n\n ---@type obsidian.config.LinkStyle, string\n local link_style, label\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n label = string.format(\"[[%s]] (create)\", new_note_opts.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n label = string.format(\"[%s](…) (create)\", new_note_opts.label)\n else\n error \"not implemented\"\n end\n\n local new_text = api.format_link(new_note, { link_style = link_style, anchor = anchor, block = block })\n local documentation = {\n kind = \"markdown\",\n value = new_note:display_info {\n label = \"Create: \" .. new_text,\n },\n }\n\n items[#items + 1] = {\n documentation = documentation,\n sortText = new_note_opts.label,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = new_text,\n range = {\n start = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n data = {\n note = new_note,\n template = new_note_opts.template,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction NewNoteSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if cc.search ~= nil then\n cc.search = util.lstrip_whitespace(cc.search)\n end\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n return true\nend\n\n--- Runs a generalized version of the execute method\n---@param item any\n---@return table|? callback_return_value\nfunction NewNoteSourceBase:process_execute(item)\n local data = item.data\n\n if data == nil then\n return nil\n end\n\n -- Make sure `data.note` is actually an `obsidian.Note` object. If it gets serialized at some\n -- point (seems to happen on Linux), it will lose its metatable.\n if not Note.is_note_obj(data.note) then\n data.note = setmetatable(data.note, Note.mt)\n data.note.path = setmetatable(data.note.path, Path.mt)\n end\n\n data.note:write { template = data.template }\n return {}\nend\n\nreturn NewNoteSourceBase\n"], ["/obsidian.nvim/lua/obsidian/api.lua", "local M = {}\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal iter, string, table = vim.iter, string, table\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\n\n---@param dir string | obsidian.Path\n---@return Iter\nM.dir = function(dir)\n dir = tostring(dir)\n local dir_opts = {\n depth = 10,\n skip = function(p)\n return not vim.startswith(p, \".\") and p ~= vim.fs.basename(tostring(M.templates_dir()))\n end,\n follow = true,\n }\n\n return vim\n .iter(vim.fs.dir(dir, dir_opts))\n :filter(function(path)\n return vim.endswith(path, \".md\")\n end)\n :map(function(path)\n return vim.fs.joinpath(dir, path)\n end)\nend\n\n--- Get the templates folder.\n---\n---@return obsidian.Path|?\nM.templates_dir = function(workspace)\n local opts = Obsidian.opts\n\n local Workspace = require \"obsidian.workspace\"\n\n if workspace and workspace ~= Obsidian.workspace then\n opts = Workspace.normalize_opts(workspace)\n end\n\n if opts.templates == nil or opts.templates.folder == nil then\n return nil\n end\n\n local paths_to_check = { Obsidian.workspace.root / opts.templates.folder, Path.new(opts.templates.folder) }\n for _, path in ipairs(paths_to_check) do\n if path:is_dir() then\n return path\n end\n end\n\n log.err_once(\"'%s' is not a valid templates directory\", opts.templates.folder)\n return nil\nend\n\n--- Check if a path represents a note in the workspace.\n---\n---@param path string|obsidian.Path\n---@param workspace obsidian.Workspace|?\n---\n---@return boolean\nM.path_is_note = function(path, workspace)\n path = Path.new(path):resolve()\n workspace = workspace or Obsidian.workspace\n\n local in_vault = path.filename:find(vim.pesc(tostring(workspace.root))) ~= nil\n if not in_vault then\n return false\n end\n\n -- Notes have to be markdown file.\n if path.suffix ~= \".md\" then\n return false\n end\n\n -- Ignore markdown files in the templates directory.\n local templates_dir = M.templates_dir(workspace)\n if templates_dir ~= nil then\n if templates_dir:is_parent_of(path) then\n return false\n end\n end\n\n return true\nend\n\n--- Get the current note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note|?\n---@diagnostic disable-next-line: unused-local\nM.current_note = function(bufnr, opts)\n bufnr = bufnr or 0\n local Note = require \"obsidian.note\"\n if not M.path_is_note(vim.api.nvim_buf_get_name(bufnr)) then\n return nil\n end\n\n opts = opts or {}\n if not opts.max_lines then\n opts.max_lines = Obsidian.opts.search_max_lines\n end\n return Note.from_buffer(bufnr, opts)\nend\n\n---builtin functions that are impure, interacts with editor state, like vim.api\n\n---Toggle the checkbox on the current line.\n---\n---@param states table|nil Optional table containing checkbox states (e.g., {\" \", \"x\"}).\n---@param line_num number|nil Optional line number to toggle the checkbox on. Defaults to the current line.\nM.toggle_checkbox = function(states, line_num)\n if not util.in_node { \"list\", \"paragraph\" } or util.in_node \"block_quote\" then\n return\n end\n line_num = line_num or unpack(vim.api.nvim_win_get_cursor(0))\n local line = vim.api.nvim_buf_get_lines(0, line_num - 1, line_num, false)[1]\n\n local checkboxes = states or { \" \", \"x\" }\n\n if util.is_checkbox(line) then\n for i, check_char in ipairs(checkboxes) do\n if string.match(line, \"^.* %[\" .. vim.pesc(check_char) .. \"%].*\") then\n i = i % #checkboxes\n line = string.gsub(line, vim.pesc(\"[\" .. check_char .. \"]\"), \"[\" .. checkboxes[i + 1] .. \"]\", 1)\n break\n end\n end\n elseif Obsidian.opts.checkbox.create_new then\n local unordered_list_pattern = \"^(%s*)[-*+] (.*)\"\n if string.match(line, unordered_list_pattern) then\n line = string.gsub(line, unordered_list_pattern, \"%1- [ ] %2\")\n else\n line = string.gsub(line, \"^(%s*)\", \"%1- [ ] \")\n end\n else\n goto out\n end\n\n vim.api.nvim_buf_set_lines(0, line_num - 1, line_num, true, { line })\n ::out::\nend\n\n---@return [number, number, number, number] tuple containing { buf, win, row, col }\nM.get_active_window_cursor_location = function()\n local buf = vim.api.nvim_win_get_buf(0)\n local win = vim.api.nvim_get_current_win()\n local row, col = unpack(vim.api.nvim_win_get_cursor(win))\n local location = { buf, win, row, col }\n return location\nend\n\n--- Create a formatted markdown / wiki link for a note.\n---\n---@param note obsidian.Note|obsidian.Path|string The note/path to link to.\n---@param opts { label: string|?, link_style: obsidian.config.LinkStyle|?, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|? Options.\n---\n---@return string\nM.format_link = function(note, opts)\n local config = require \"obsidian.config\"\n opts = opts or {}\n\n ---@type string, string, string|integer|?\n local rel_path, label, note_id\n if type(note) == \"string\" or Path.is_path_obj(note) then\n ---@cast note string|obsidian.Path\n -- rel_path = tostring(self:vault_relative_path(note, { strict = true }))\n rel_path = assert(Path.new(note):vault_relative_path { strict = true })\n label = opts.label or tostring(note)\n note_id = opts.id\n else\n ---@cast note obsidian.Note\n -- rel_path = tostring(self:vault_relative_path(note.path, { strict = true }))\n rel_path = assert(note.path:vault_relative_path { strict = true })\n label = opts.label or note:display_name()\n note_id = opts.id or note.id\n end\n\n local link_style = opts.link_style\n if link_style == nil then\n link_style = Obsidian.opts.preferred_link_style\n end\n\n local new_opts = { path = rel_path, label = label, id = note_id, anchor = opts.anchor, block = opts.block }\n\n if link_style == config.LinkStyle.markdown then\n return Obsidian.opts.markdown_link_func(new_opts)\n elseif link_style == config.LinkStyle.wiki or link_style == nil then\n return Obsidian.opts.wiki_link_func(new_opts)\n else\n error(string.format(\"Invalid link style '%s'\", link_style))\n end\nend\n\n---Return the full link under cursror\n---\n---@return string? link\n---@return obsidian.search.RefTypes? link_type\nM.cursor_link = function()\n local line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- 0-indexed column to 1-indexed lua string position\n\n local refs = search.find_refs(line, { include_naked_urls = true, include_file_urls = true, include_block_ids = true })\n\n local match = iter(refs):find(function(match)\n local open, close = unpack(match)\n return cur_col >= open and cur_col <= close\n end)\n if match then\n return line:sub(match[1], match[2]), match[3]\n end\nend\n\n---Get the tag under the cursor, if there is one.\n---@return string?\nM.cursor_tag = function()\n local current_line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- nvim_win_get_cursor returns 0-indexed column\n\n for match in iter(search.find_tags(current_line)) do\n local open, close, _ = unpack(match)\n if open <= cur_col and cur_col <= close then\n return string.sub(current_line, open + 1, close)\n end\n end\n\n return nil\nend\n\n--- Get the heading under the cursor, if there is one.\n---@return { header: string, level: integer, anchor: string }|?\nM.cursor_heading = function()\n return util.parse_header(vim.api.nvim_get_current_line())\nend\n\n------------------\n--- buffer api ---\n------------------\n\n--- Check if a buffer is empty.\n---\n---@param bufnr integer|?\n---\n---@return boolean\nM.buffer_is_empty = function(bufnr)\n bufnr = bufnr or 0\n if vim.api.nvim_buf_line_count(bufnr) > 1 then\n return false\n else\n local first_text = vim.api.nvim_buf_get_text(bufnr, 0, 0, 0, 0, {})\n if vim.tbl_isempty(first_text) or first_text[1] == \"\" then\n return true\n else\n return false\n end\n end\nend\n\n--- Open a buffer for the corresponding path.\n---\n---@param path string|obsidian.Path\n---@param opts { line: integer|?, col: integer|?, cmd: string|? }|?\n---@return integer bufnr\nM.open_buffer = function(path, opts)\n path = Path.new(path):resolve()\n opts = opts and opts or {}\n local cmd = vim.trim(opts.cmd and opts.cmd or \"e\")\n\n ---@type integer|?\n local result_bufnr\n\n -- Check for buffer in windows and use 'drop' command if one is found.\n for _, winnr in ipairs(vim.api.nvim_list_wins()) do\n local bufnr = vim.api.nvim_win_get_buf(winnr)\n local bufname = vim.api.nvim_buf_get_name(bufnr)\n if bufname == tostring(path) then\n cmd = \"drop\"\n result_bufnr = bufnr\n break\n end\n end\n\n vim.cmd(string.format(\"%s %s\", cmd, vim.fn.fnameescape(tostring(path))))\n if opts.line then\n vim.api.nvim_win_set_cursor(0, { tonumber(opts.line), opts.col and opts.col or 0 })\n end\n\n if not result_bufnr then\n result_bufnr = vim.api.nvim_get_current_buf()\n end\n\n return result_bufnr\nend\n\n---Get an iterator of (bufnr, bufname) over all named buffers. The buffer names will be absolute paths.\n---\n---@return function () -> (integer, string)|?\nM.get_named_buffers = function()\n local idx = 0\n local buffers = vim.api.nvim_list_bufs()\n\n ---@return integer|?\n ---@return string|?\n return function()\n while idx < #buffers do\n idx = idx + 1\n local bufnr = buffers[idx]\n if vim.api.nvim_buf_is_loaded(bufnr) then\n return bufnr, vim.api.nvim_buf_get_name(bufnr)\n end\n end\n end\nend\n\n----------------\n--- text api ---\n----------------\n\n--- Get the current visual selection of text and exit visual mode.\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return { lines: string[], selection: string, csrow: integer, cscol: integer, cerow: integer, cecol: integer }|?\nM.get_visual_selection = function(opts)\n opts = opts or {}\n -- Adapted from fzf-lua:\n -- https://github.com/ibhagwan/fzf-lua/blob/6ee73fdf2a79bbd74ec56d980262e29993b46f2b/lua/fzf-lua/utils.lua#L434-L466\n -- this will exit visual mode\n -- use 'gv' to reselect the text\n local _, csrow, cscol, cerow, cecol\n local mode = vim.fn.mode()\n if opts.strict and not vim.endswith(string.lower(mode), \"v\") then\n return\n end\n\n if mode == \"v\" or mode == \"V\" or mode == \"\u0016\" then\n -- if we are in visual mode use the live position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \".\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"v\")\n if mode == \"V\" then\n -- visual line doesn't provide columns\n cscol, cecol = 0, 999\n end\n -- exit visual mode\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", true)\n else\n -- otherwise, use the last known visual position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \"'<\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"'>\")\n end\n\n -- Swap vars if needed\n if cerow < csrow then\n csrow, cerow = cerow, csrow\n cscol, cecol = cecol, cscol\n elseif cerow == csrow and cecol < cscol then\n cscol, cecol = cecol, cscol\n end\n\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n if vim.tbl_isempty(lines) then\n return\n end\n\n -- When the whole line is selected via visual line mode (\"V\"), cscol / cecol will be equal to \"v:maxcol\"\n -- for some odd reason. So change that to what they should be here. See ':h getpos' for more info.\n local maxcol = vim.api.nvim_get_vvar \"maxcol\"\n if cscol == maxcol then\n cscol = string.len(lines[1])\n end\n if cecol == maxcol then\n cecol = string.len(lines[#lines])\n end\n\n ---@type string\n local selection\n local n = #lines\n if n <= 0 then\n selection = \"\"\n elseif n == 1 then\n selection = string.sub(lines[1], cscol, cecol)\n elseif n == 2 then\n selection = string.sub(lines[1], cscol) .. \"\\n\" .. string.sub(lines[n], 1, cecol)\n else\n selection = string.sub(lines[1], cscol)\n .. \"\\n\"\n .. table.concat(lines, \"\\n\", 2, n - 1)\n .. \"\\n\"\n .. string.sub(lines[n], 1, cecol)\n end\n\n return {\n lines = lines,\n selection = selection,\n csrow = csrow,\n cscol = cscol,\n cerow = cerow,\n cecol = cecol,\n }\nend\n\n------------------\n--- UI helpers ---\n------------------\n\n---Get the strategy for opening notes\n---\n---@param opt obsidian.config.OpenStrategy\n---@return string\nM.get_open_strategy = function(opt)\n local OpenStrategy = require(\"obsidian.config\").OpenStrategy\n\n -- either 'leaf', 'row' for vertically split windows, or 'col' for horizontally split windows\n local cur_layout = vim.fn.winlayout()[1]\n\n if vim.startswith(OpenStrategy.hsplit, opt) then\n if cur_layout ~= \"col\" then\n return \"split \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit, opt) then\n if cur_layout ~= \"row\" then\n return \"vsplit \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit_force, opt) then\n return \"vsplit \"\n elseif vim.startswith(OpenStrategy.hsplit_force, opt) then\n return \"hsplit \"\n elseif vim.startswith(OpenStrategy.current, opt) then\n return \"e \"\n else\n log.err(\"undefined open strategy '%s'\", opt)\n return \"e \"\n end\nend\n\n----------------------------\n--- Integration helpers ----\n----------------------------\n\n--- Get the path to where a plugin is installed.\n---\n---@param name string\n---@return string|?\nlocal get_src_root = function(name)\n return vim.iter(vim.api.nvim_list_runtime_paths()):find(function(path)\n return vim.endswith(path, name)\n end)\nend\n\n--- Get info about a plugin.\n---\n---@param name string\n---\n---@return { commit: string|?, path: string }|?\nM.get_plugin_info = function(name)\n local src_root = get_src_root(name)\n if not src_root then\n return\n end\n local out = { path = src_root }\n local obj = vim.system({ \"git\", \"rev-parse\", \"HEAD\" }, { cwd = src_root }):wait(1000)\n if obj.code == 0 then\n out.commit = vim.trim(obj.stdout)\n else\n out.commit = \"unknown\"\n end\n return out\nend\n\n--- Get info about a external dependency.\n---\n---@param cmd string\n---@return string|?\nM.get_external_dependency_info = function(cmd)\n local obj = vim.system({ cmd, \"--version\" }, {}):wait(1000)\n if obj.code ~= 0 then\n return\n end\n local version = vim.version.parse(obj.stdout)\n if version then\n return (\"%d.%d.%d\"):format(version.major, version.minor, version.patch)\n end\nend\n\n------------------\n--- UI helpers ---\n------------------\n\nlocal INPUT_CANCELLED = \"~~~INPUT-CANCELLED~~~\"\n\n--- Prompt user for an input. Returns nil if canceled, otherwise a string (possibly empty).\n---\n---@param prompt string\n---@param opts { completion: string|?, default: string|? }|?\n---\n---@return string|?\nM.input = function(prompt, opts)\n opts = opts or {}\n\n if not vim.endswith(prompt, \" \") then\n prompt = prompt .. \" \"\n end\n\n local input = vim.trim(\n vim.fn.input { prompt = prompt, completion = opts.completion, default = opts.default, cancelreturn = INPUT_CANCELLED }\n )\n\n if input ~= INPUT_CANCELLED then\n return input\n else\n return nil\n end\nend\n\n--- Prompt user for a confirmation.\n---\n---@param prompt string\n---\n---@return boolean\nM.confirm = function(prompt)\n if not vim.endswith(util.rstrip_whitespace(prompt), \"[Y/n]\") then\n prompt = util.rstrip_whitespace(prompt) .. \" [Y/n] \"\n end\n\n local confirmation = M.input(prompt)\n if confirmation == nil then\n return false\n end\n\n confirmation = string.lower(confirmation)\n\n if confirmation == \"\" or confirmation == \"y\" or confirmation == \"yes\" then\n return true\n else\n return false\n end\nend\n\n---@enum OSType\nM.OSType = {\n Linux = \"Linux\",\n Wsl = \"Wsl\",\n Windows = \"Windows\",\n Darwin = \"Darwin\",\n FreeBSD = \"FreeBSD\",\n}\n\nM._current_os = nil\n\n---Get the running operating system.\n---Reference https://vi.stackexchange.com/a/2577/33116\n---@return OSType\nM.get_os = function()\n if M._current_os ~= nil then\n return M._current_os\n end\n\n local this_os\n if vim.fn.has \"win32\" == 1 then\n this_os = M.OSType.Windows\n else\n local sysname = vim.uv.os_uname().sysname\n local release = vim.uv.os_uname().release:lower()\n if sysname:lower() == \"linux\" and string.find(release, \"microsoft\") then\n this_os = M.OSType.Wsl\n else\n this_os = sysname\n end\n end\n\n assert(this_os)\n M._current_os = this_os\n return this_os\nend\n\n--- Get a nice icon for a file or URL, if possible.\n---\n---@param path string\n---\n---@return string|?, string|? (icon, hl_group) The icon and highlight group.\nM.get_icon = function(path)\n if util.is_url(path) then\n local icon = \"\"\n local _, hl_group = M.get_icon \"blah.html\"\n return icon, hl_group\n else\n local ok, res = pcall(function()\n local icon, hl_group = require(\"nvim-web-devicons\").get_icon(path, nil, { default = true })\n return { icon, hl_group }\n end)\n if ok and type(res) == \"table\" then\n local icon, hlgroup = unpack(res)\n return icon, hlgroup\n elseif vim.endswith(path, \".md\") then\n return \"\"\n end\n end\n return nil\nend\n\n--- Resolve a basename to full path inside the vault.\n---\n---@param src string\n---@return string\nM.resolve_image_path = function(src)\n local img_folder = Obsidian.opts.attachments.img_folder\n\n ---@cast img_folder -nil\n if vim.startswith(img_folder, \".\") then\n local dirname = Path.new(vim.fs.dirname(vim.api.nvim_buf_get_name(0)))\n return tostring(dirname / img_folder / src)\n else\n return tostring(Obsidian.dir / img_folder / src)\n end\nend\n\n--- Follow a link. If the link argument is `nil` we attempt to follow a link under the cursor.\n---\n---@param link string\n---@param opts { open_strategy: obsidian.config.OpenStrategy|? }|?\nM.follow_link = function(link, opts)\n opts = opts and opts or {}\n local Note = require \"obsidian.note\"\n\n search.resolve_link_async(link, function(results)\n if #results == 0 then\n return\n end\n\n ---@param res obsidian.ResolveLinkResult\n local function follow_link(res)\n if res.url ~= nil then\n Obsidian.opts.follow_url_func(res.url)\n return\n end\n\n if util.is_img(res.location) then\n local path = Obsidian.dir / res.location\n Obsidian.opts.follow_img_func(tostring(path))\n return\n end\n\n if res.note ~= nil then\n -- Go to resolved note.\n return res.note:open { line = res.line, col = res.col, open_strategy = opts.open_strategy }\n end\n\n if res.link_type == search.RefTypes.Wiki or res.link_type == search.RefTypes.WikiWithAlias then\n -- Prompt to create a new note.\n if M.confirm(\"Create new note '\" .. res.location .. \"'?\") then\n -- Create a new note.\n ---@type string|?, string[]\n local id, aliases\n if res.name == res.location then\n aliases = {}\n else\n aliases = { res.name }\n id = res.location\n end\n\n local note = Note.create { title = res.name, id = id, aliases = aliases }\n return note:open {\n open_strategy = opts.open_strategy,\n callback = function(bufnr)\n note:write_to_buffer { bufnr = bufnr }\n end,\n }\n else\n log.warn \"Aborted\"\n return\n end\n end\n\n return log.err(\"Failed to resolve file '\" .. res.location .. \"'\")\n end\n\n if #results == 1 then\n return vim.schedule(function()\n follow_link(results[1])\n end)\n else\n return vim.schedule(function()\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple matches to '%s', but no picker is configured\", link)\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, res in ipairs(results) do\n local icon, icon_hl\n if res.url ~= nil then\n icon, icon_hl = M.get_icon(res.url)\n end\n table.insert(entries, {\n value = res,\n display = res.name,\n filename = res.path and tostring(res.path) or nil,\n icon = icon,\n icon_hl = icon_hl,\n })\n end\n\n picker:pick(entries, {\n prompt_title = \"Follow link\",\n callback = function(res)\n follow_link(res)\n end,\n })\n end)\n end\n end)\nend\n--------------------------\n---- Mapping functions ---\n--------------------------\n\n---@param direction \"next\" | \"prev\"\nM.nav_link = function(direction)\n vim.validate(\"direction\", direction, \"string\", false, \"nav_link must be called with a direction\")\n local cursor_line, cursor_col = unpack(vim.api.nvim_win_get_cursor(0))\n local Note = require \"obsidian.note\"\n\n search.find_links(Note.from_buffer(0), {}, function(matches)\n if direction == \"next\" then\n for i = 1, #matches do\n local match = matches[i]\n if (match.line > cursor_line) or (cursor_line == match.line and cursor_col < match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n\n if direction == \"prev\" then\n for i = #matches, 1, -1 do\n local match = matches[i]\n if (match.line < cursor_line) or (cursor_line == match.line and cursor_col > match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n end)\nend\n\nM.smart_action = function()\n local legacy = Obsidian.opts.legacy_commands\n -- follow link if possible\n if M.cursor_link() then\n return legacy and \"ObsidianFollowLink\" or \"Obsidian follow_link\"\n end\n\n -- show notes with tag if possible\n if M.cursor_tag() then\n return legacy and \"ObsidianTags\" or \"Obsidian tags\"\n end\n\n if M.cursor_heading() then\n return \"za\"\n end\n\n -- toggle task if possible\n -- cycles through your custom UI checkboxes, default: [ ] [~] [>] [x]\n return legacy and \"ObsidianToggleCheckbox\" or \"Obsidian toggle_checkbox\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/paste_img.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal img = require \"obsidian.img_paste\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not img.clipboard_is_img() then\n return log.err \"There is no image data in the clipboard\"\n end\n\n ---@type string|?\n local default_name = Obsidian.opts.attachments.img_name_func()\n\n local should_confirm = Obsidian.opts.attachments.confirm_img_paste\n\n ---@type string\n local fname = vim.trim(data.args)\n\n -- Get filename to save to.\n if fname == nil or fname == \"\" then\n if default_name and not should_confirm then\n fname = default_name\n else\n local input = api.input(\"Enter file name: \", { default = default_name, completion = \"file\" })\n if not input then\n return log.warn \"Paste aborted\"\n end\n fname = input\n end\n end\n\n local path = api.resolve_image_path(fname)\n\n img.paste(path)\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/open.lua", "local api = require \"obsidian.api\"\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\nlocal log = require \"obsidian.log\"\n\n---@param path? string|obsidian.Path\nlocal function open_in_app(path)\n local vault_name = vim.fs.basename(tostring(Obsidian.workspace.root))\n if not path then\n return Obsidian.opts.open.func(\"obsidian://open?vault=\" .. vim.uri_encode(vault_name))\n end\n path = tostring(path)\n local this_os = api.get_os()\n\n -- Normalize path for windows.\n if this_os == api.OSType.Windows then\n path = string.gsub(path, \"/\", \"\\\\\")\n end\n\n local encoded_vault = vim.uri_encode(vault_name)\n local encoded_path = vim.uri_encode(path)\n\n local uri\n if Obsidian.opts.open.use_advanced_uri then\n local line = vim.api.nvim_win_get_cursor(0)[1] or 1\n uri = (\"obsidian://advanced-uri?vault=%s&filepath=%s&line=%i\"):format(encoded_vault, encoded_path, line)\n else\n uri = (\"obsidian://open?vault=%s&file=%s\"):format(encoded_vault, encoded_path)\n end\n print(uri)\n\n Obsidian.opts.open.func(uri)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type string|?\n local search_term\n\n if data.args and data.args:len() > 0 then\n search_term = data.args\n else\n -- Check for a note reference under the cursor.\n local link_string, _ = api.cursor_link()\n search_term = link_string\n end\n\n if search_term then\n search.resolve_link_async(search_term, function(results)\n if vim.tbl_isempty(results) then\n return log.err \"Note under cusros is not resolved\"\n end\n vim.schedule(function()\n open_in_app(results[1].path)\n end)\n end)\n else\n -- Otherwise use the path of the current buffer.\n local bufname = vim.api.nvim_buf_get_name(0)\n local path = Path.new(bufname):vault_relative_path()\n open_in_app(path)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/init.lua", "local iter = vim.iter\nlocal log = require \"obsidian.log\"\nlocal legacycommands = require \"obsidian.commands.init-legacy\"\nlocal search = require \"obsidian.search\"\n\nlocal M = { commands = {} }\n\nlocal function in_note()\n return vim.bo.filetype == \"markdown\"\nend\n\n---@param commands obsidian.CommandConfig[]\n---@param is_visual boolean\n---@param is_note boolean\n---@return string[]\nlocal function get_commands_by_context(commands, is_visual, is_note)\n local choices = vim.tbl_values(commands)\n return vim\n .iter(choices)\n :filter(function(config)\n if is_visual then\n return config.range ~= nil\n else\n return config.range == nil\n end\n end)\n :filter(function(config)\n if is_note then\n return true\n else\n return not config.note_action\n end\n end)\n :map(function(config)\n return config.name\n end)\n :totable()\nend\n\nlocal function show_menu(data)\n local is_visual, is_note = data.range ~= 0, in_note()\n local choices = get_commands_by_context(M.commands, is_visual, is_note)\n\n vim.ui.select(choices, { prompt = \"Obsidian Commands\" }, function(item)\n if item then\n return vim.cmd.Obsidian(item)\n else\n vim.notify(\"Aborted\", 3)\n end\n end)\nend\n\n---@class obsidian.CommandConfig\n---@field complete function|string|?\n---@field nargs string|integer|?\n---@field range boolean|?\n---@field func function|? (obsidian.Client, table) -> nil\n---@field name string?\n---@field note_action boolean?\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfig\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n local mod = require(\"obsidian.commands.\" .. name)\n return mod(client, data)\n end\n end\n config.name = name\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n vim.api.nvim_create_user_command(\"Obsidian\", function(data)\n if #data.fargs == 0 then\n show_menu(data)\n return\n end\n M.handle_command(client, data)\n end, {\n nargs = \"*\",\n complete = function(_, cmdline, _)\n return M.get_completions(client, cmdline)\n end,\n range = 2,\n })\nend\n\nM.install_legacy = legacycommands.install\n\n---@param client obsidian.Client\nM.handle_command = function(client, data)\n local cmd = data.fargs[1]\n table.remove(data.fargs, 1)\n data.args = table.concat(data.fargs, \" \")\n local nargs = #data.fargs\n\n local cmdconfig = M.commands[cmd]\n if cmdconfig == nil then\n log.err(\"Command '\" .. cmd .. \"' not found\")\n return\n end\n\n local exp_nargs = cmdconfig.nargs\n local range_allowed = cmdconfig.range\n\n if exp_nargs == \"?\" then\n if nargs > 1 then\n log.err(\"Command '\" .. cmd .. \"' expects 0 or 1 arguments, but \" .. nargs .. \" were provided\")\n return\n end\n elseif exp_nargs == \"+\" then\n if nargs == 0 then\n log.err(\"Command '\" .. cmd .. \"' expects at least one argument, but none were provided\")\n return\n end\n elseif exp_nargs ~= \"*\" and exp_nargs ~= nargs then\n log.err(\"Command '\" .. cmd .. \"' expects \" .. exp_nargs .. \" arguments, but \" .. nargs .. \" were provided\")\n return\n end\n\n if not range_allowed and data.range > 0 then\n log.error(\"Command '\" .. cmd .. \"' does not accept a range\")\n return\n end\n\n cmdconfig.func(client, data)\nend\n\n---@param client obsidian.Client\n---@param cmdline string\nM.get_completions = function(client, cmdline)\n local obspat = \"^['<,'>]*Obsidian[!]?\"\n local splitcmd = vim.split(cmdline, \" \", { plain = true, trimempty = true })\n local obsidiancmd = splitcmd[2]\n if cmdline:match(obspat .. \"%s$\") then\n local is_visual = vim.startswith(cmdline, \"'<,'>\")\n return get_commands_by_context(M.commands, is_visual, in_note())\n end\n if cmdline:match(obspat .. \"%s%S+$\") then\n return vim.tbl_filter(function(s)\n return s:sub(1, #obsidiancmd) == obsidiancmd\n end, vim.tbl_keys(M.commands))\n end\n local cmdconfig = M.commands[obsidiancmd]\n if cmdconfig == nil then\n return\n end\n if cmdline:match(obspat .. \"%s%S*%s%S*$\") then\n local cmd_arg = table.concat(vim.list_slice(splitcmd, 3), \" \")\n local complete_type = type(cmdconfig.complete)\n if complete_type == \"function\" then\n return cmdconfig.complete(cmd_arg)\n end\n if complete_type == \"string\" then\n return vim.fn.getcompletion(cmd_arg, cmdconfig.complete)\n end\n end\nend\n\n--TODO: Note completion is currently broken (see: https://github.com/epwalsh/obsidian.nvim/issues/753)\n---@return string[]\nM.note_complete = function(cmd_arg)\n local query\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\n------------------------\n---- general action ----\n------------------------\n\nM.register(\"check\", { nargs = 0 })\n\nM.register(\"today\", { nargs = \"?\" })\n\nM.register(\"yesterday\", { nargs = 0 })\n\nM.register(\"tomorrow\", { nargs = 0 })\n\nM.register(\"dailies\", { nargs = \"*\" })\n\nM.register(\"new\", { nargs = \"?\" })\n\nM.register(\"open\", { nargs = \"?\", complete = M.note_complete })\n\nM.register(\"tags\", { nargs = \"*\" })\n\nM.register(\"search\", { nargs = \"?\" })\n\nM.register(\"new_from_template\", { nargs = \"*\" })\n\nM.register(\"quick_switch\", { nargs = \"?\" })\n\nM.register(\"workspace\", { nargs = \"?\" })\n\n---------------------\n---- note action ----\n---------------------\n\nM.register(\"backlinks\", { nargs = 0, note_action = true })\n\nM.register(\"template\", { nargs = \"?\", note_action = true })\n\nM.register(\"link_new\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"link\", { nargs = \"?\", range = true, complete = M.note_complete, note_action = true })\n\nM.register(\"links\", { nargs = 0, note_action = true })\n\nM.register(\"follow_link\", { nargs = \"?\", note_action = true })\n\nM.register(\"toggle_checkbox\", { nargs = 0, range = true, note_action = true })\n\nM.register(\"rename\", { nargs = \"?\", note_action = true })\n\nM.register(\"paste_img\", { nargs = \"?\", note_action = true })\n\nM.register(\"extract_note\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"toc\", { nargs = 0, note_action = true })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/log.lua", "---@class obsidian.Logger\nlocal log = {}\n\nlog._log_level = vim.log.levels.INFO\n\n---@param t table\n---@return boolean\nlocal function has_tostring(t)\n local mt = getmetatable(t)\n return mt ~= nil and mt.__tostring ~= nil\nend\n\n---@param msg string\n---@return any[]\nlocal function message_args(msg, ...)\n local args = { ... }\n local num_directives = select(2, string.gsub(msg, \"%%\", \"\")) - 2 * select(2, string.gsub(msg, \"%%%%\", \"\"))\n\n -- Some elements might be nil, so we can't use 'ipairs'.\n local out = {}\n for i = 1, #args do\n local v = args[i]\n if v == nil then\n out[i] = tostring(v)\n elseif type(v) == \"table\" and not has_tostring(v) then\n out[i] = vim.inspect(v)\n else\n out[i] = v\n end\n end\n\n -- If were short formatting args relative to the number of directives, add \"nil\" strings on.\n if #out < num_directives then\n for i = #out + 1, num_directives do\n out[i] = \"nil\"\n end\n end\n\n return out\nend\n\n---@param level integer\nlog.set_level = function(level)\n log._log_level = level\nend\n\n--- Log a message.\n---\n---@param msg any\n---@param level integer|?\nlog.log = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---Log a message only once.\n---\n---@param msg any\n---@param level integer|?\nlog.log_once = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---@param msg string\nlog.debug = function(msg, ...)\n log.log(msg, vim.log.levels.DEBUG, ...)\nend\n\n---@param msg string\nlog.info = function(msg, ...)\n log.log(msg, vim.log.levels.INFO, ...)\nend\n\n---@param msg string\nlog.warn = function(msg, ...)\n log.log(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.warn_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.err = function(msg, ...)\n log.log(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error = log.err\n\n---@param msg string\nlog.err_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error_once = log.err\n\nreturn log\n"], ["/obsidian.nvim/lua/obsidian/templates.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nlocal M = {}\n\n--- Resolve a template name to a path.\n---\n---@param template_name string|obsidian.Path\n---@param templates_dir obsidian.Path\n---\n---@return obsidian.Path\nM.resolve_template = function(template_name, templates_dir)\n ---@type obsidian.Path|?\n local template_path\n local paths_to_check = { templates_dir / tostring(template_name), Path:new(template_name) }\n for _, path in ipairs(paths_to_check) do\n if path:is_file() then\n template_path = path\n break\n elseif not vim.endswith(tostring(path), \".md\") then\n local path_with_suffix = Path:new(tostring(path) .. \".md\")\n if path_with_suffix:is_file() then\n template_path = path_with_suffix\n break\n end\n end\n end\n\n if template_path == nil then\n error(string.format(\"Template '%s' not found\", template_name))\n end\n\n return template_path\nend\n\n--- Substitute variables inside the given text.\n---\n---@param text string\n---@param ctx obsidian.TemplateContext\n---\n---@return string\nM.substitute_template_variables = function(text, ctx)\n local methods = vim.deepcopy(ctx.template_opts.substitutions or {})\n\n if not methods[\"date\"] then\n methods[\"date\"] = function()\n local date_format = ctx.template_opts.date_format or \"%Y-%m-%d\"\n return tostring(os.date(date_format))\n end\n end\n\n if not methods[\"time\"] then\n methods[\"time\"] = function()\n local time_format = ctx.template_opts.time_format or \"%H:%M\"\n return tostring(os.date(time_format))\n end\n end\n\n if not methods[\"title\"] and ctx.partial_note then\n methods[\"title\"] = ctx.partial_note.title or ctx.partial_note:display_name()\n end\n\n if not methods[\"id\"] and ctx.partial_note then\n methods[\"id\"] = tostring(ctx.partial_note.id)\n end\n\n if not methods[\"path\"] and ctx.partial_note and ctx.partial_note.path then\n methods[\"path\"] = tostring(ctx.partial_note.path)\n end\n\n -- Replace known variables.\n for key, subst in pairs(methods) do\n while true do\n local m_start, m_end = string.find(text, \"{{\" .. key .. \"}}\", nil, true)\n if not m_start or not m_end then\n break\n end\n ---@type string\n local value\n if type(subst) == \"string\" then\n value = subst\n else\n value = subst(ctx)\n -- cache the result\n methods[key] = value\n end\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n -- Find unknown variables and prompt for them.\n for m_start, m_end in util.gfind(text, \"{{[^}]+}}\") do\n local key = vim.trim(string.sub(text, m_start + 2, m_end - 2))\n local value = api.input(string.format(\"Enter value for '%s' ( to skip): \", key))\n if value and string.len(value) > 0 then\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n return text\nend\n\n--- Clone template to a new note.\n---\n---@param ctx obsidian.CloneTemplateContext\n---\n---@return obsidian.Note\nM.clone_template = function(ctx)\n local note_path = Path.new(ctx.destination_path)\n assert(note_path:parent()):mkdir { parents = true, exist_ok = true }\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local template_file, read_err = io.open(tostring(template_path), \"r\")\n if not template_file then\n error(string.format(\"Unable to read template at '%s': %s\", template_path, tostring(read_err)))\n end\n\n local note_file, write_err = io.open(tostring(note_path), \"w\")\n if not note_file then\n error(string.format(\"Unable to write note at '%s': %s\", note_path, tostring(write_err)))\n end\n\n for line in template_file:lines \"L\" do\n line = M.substitute_template_variables(line, ctx)\n note_file:write(line)\n end\n\n assert(template_file:close())\n assert(note_file:close())\n\n local new_note = Note.from_file(note_path)\n\n if ctx.partial_note then\n -- Transfer fields from `ctx.partial_note`.\n new_note.id = ctx.partial_note.id\n if new_note.title == nil then\n new_note.title = ctx.partial_note.title\n end\n for _, alias in ipairs(ctx.partial_note.aliases) do\n new_note:add_alias(alias)\n end\n for _, tag in ipairs(ctx.partial_note.tags) do\n new_note:add_tag(tag)\n end\n end\n\n return new_note\nend\n\n---Insert a template at the given location.\n---\n---@param ctx obsidian.InsertTemplateContext\n---\n---@return obsidian.Note\nM.insert_template = function(ctx)\n local buf, win, row, _ = unpack(ctx.location)\n if ctx.partial_note == nil then\n ctx.partial_note = Note.from_buffer(buf)\n end\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local insert_lines = {}\n local template_file = io.open(tostring(template_path), \"r\")\n if template_file then\n local lines = template_file:lines()\n for line in lines do\n local new_lines = M.substitute_template_variables(line, ctx)\n if string.find(new_lines, \"[\\r\\n]\") then\n local line_start = 1\n for line_end in util.gfind(new_lines, \"[\\r\\n]\") do\n local new_line = string.sub(new_lines, line_start, line_end - 1)\n table.insert(insert_lines, new_line)\n line_start = line_end + 1\n end\n local last_line = string.sub(new_lines, line_start)\n if string.len(last_line) > 0 then\n table.insert(insert_lines, last_line)\n end\n else\n table.insert(insert_lines, new_lines)\n end\n end\n template_file:close()\n else\n error(string.format(\"Template file '%s' not found\", template_path))\n end\n\n vim.api.nvim_buf_set_lines(buf, row - 1, row - 1, false, insert_lines)\n local new_cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(win))\n vim.api.nvim_win_set_cursor(0, { new_cursor_row, 0 })\n\n require(\"obsidian.ui\").update(0)\n\n return Note.from_buffer(buf)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/search.lua", "local Path = require \"obsidian.path\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\nlocal run_job_async = require(\"obsidian.async\").run_job_async\nlocal compat = require \"obsidian.compat\"\nlocal log = require \"obsidian.log\"\nlocal block_on = require(\"obsidian.async\").block_on\n\nlocal M = {}\n\nM._BASE_CMD = { \"rg\", \"--no-config\", \"--type=md\" }\nM._SEARCH_CMD = compat.flatten { M._BASE_CMD, \"--json\" }\nM._FIND_CMD = compat.flatten { M._BASE_CMD, \"--files\" }\n\n---@enum obsidian.search.RefTypes\nM.RefTypes = {\n WikiWithAlias = \"WikiWithAlias\",\n Wiki = \"Wiki\",\n Markdown = \"Markdown\",\n NakedUrl = \"NakedUrl\",\n FileUrl = \"FileUrl\",\n MailtoUrl = \"MailtoUrl\",\n Tag = \"Tag\",\n BlockID = \"BlockID\",\n Highlight = \"Highlight\",\n}\n\n---@enum obsidian.search.Patterns\nM.Patterns = {\n -- Tags\n TagCharsOptional = \"[A-Za-z0-9_/-]*\",\n TagCharsRequired = \"[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\", -- assumes tag is at least 2 chars\n Tag = \"#[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\",\n\n -- Miscellaneous\n Highlight = \"==[^=]+==\", -- ==text==\n\n -- References\n WikiWithAlias = \"%[%[[^][%|]+%|[^%]]+%]%]\", -- [[xxx|yyy]]\n Wiki = \"%[%[[^][%|]+%]%]\", -- [[xxx]]\n Markdown = \"%[[^][]+%]%([^%)]+%)\", -- [yyy](xxx)\n NakedUrl = \"https?://[a-zA-Z0-9._-@]+[a-zA-Z0-9._#/=&?:+%%-@]+[a-zA-Z0-9/]\", -- https://xyz.com\n FileUrl = \"file:/[/{2}]?.*\", -- file:///\n MailtoUrl = \"mailto:.*\", -- mailto:emailaddress\n BlockID = util.BLOCK_PATTERN .. \"$\", -- ^hello-world\n}\n\n---@type table\nM.PatternConfig = {\n [M.RefTypes.Tag] = { ignore_if_escape_prefix = true },\n}\n\n--- Find all matches of a pattern\n---\n---@param s string\n---@param pattern_names obsidian.search.RefTypes[]\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_matches = function(s, pattern_names)\n -- First find all inline code blocks so we can skip reference matches inside of those.\n local inline_code_blocks = {}\n for m_start, m_end in util.gfind(s, \"`[^`]*`\") do\n inline_code_blocks[#inline_code_blocks + 1] = { m_start, m_end }\n end\n\n local matches = {}\n for pattern_name in iter(pattern_names) do\n local pattern = M.Patterns[pattern_name]\n local pattern_cfg = M.PatternConfig[pattern_name]\n local search_start = 1\n while search_start < #s do\n local m_start, m_end = string.find(s, pattern, search_start)\n if m_start ~= nil and m_end ~= nil then\n -- Check if we're inside a code block.\n local inside_code_block = false\n for code_block_boundary in iter(inline_code_blocks) do\n if code_block_boundary[1] < m_start and m_end < code_block_boundary[2] then\n inside_code_block = true\n break\n end\n end\n\n if not inside_code_block then\n -- Check if this match overlaps with any others (e.g. a naked URL match would be contained in\n -- a markdown URL).\n local overlap = false\n for match in iter(matches) do\n if (match[1] <= m_start and m_start <= match[2]) or (match[1] <= m_end and m_end <= match[2]) then\n overlap = true\n break\n end\n end\n\n -- Check if we should skip to an escape sequence before the pattern.\n local skip_due_to_escape = false\n if\n pattern_cfg ~= nil\n and pattern_cfg.ignore_if_escape_prefix\n and string.sub(s, m_start - 1, m_start - 1) == [[\\]]\n then\n skip_due_to_escape = true\n end\n\n if not overlap and not skip_due_to_escape then\n matches[#matches + 1] = { m_start, m_end, pattern_name }\n end\n end\n\n search_start = m_end\n else\n break\n end\n end\n end\n\n -- Sort results by position.\n table.sort(matches, function(a, b)\n return a[1] < b[1]\n end)\n\n return matches\nend\n\n--- Find inline highlights\n---\n---@param s string\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_highlight = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Highlight })) do\n -- Remove highlights that begin/end with whitespace\n local match_start, match_end, _ = unpack(match)\n local text = string.sub(s, match_start + 2, match_end - 2)\n if vim.trim(text) == text then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n---@class obsidian.search.FindRefsOpts\n---\n---@field include_naked_urls boolean|?\n---@field include_tags boolean|?\n---@field include_file_urls boolean|?\n---@field include_block_ids boolean|?\n\n--- Find refs and URLs.\n---@param s string the string to search\n---@param opts obsidian.search.FindRefsOpts|?\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_refs = function(s, opts)\n opts = opts and opts or {}\n\n local pattern_names = { M.RefTypes.WikiWithAlias, M.RefTypes.Wiki, M.RefTypes.Markdown }\n if opts.include_naked_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.NakedUrl\n end\n if opts.include_tags then\n pattern_names[#pattern_names + 1] = M.RefTypes.Tag\n end\n if opts.include_file_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.FileUrl\n end\n if opts.include_block_ids then\n pattern_names[#pattern_names + 1] = M.RefTypes.BlockID\n end\n\n return M.find_matches(s, pattern_names)\nend\n\n--- Find all tags in a string.\n---@param s string the string to search\n---\n---@return {[1]: integer, [2]: integer, [3]: obsidian.search.RefTypes}[]\nM.find_tags = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Tag })) do\n local st, ed, m_type = unpack(match)\n local match_string = s:sub(st, ed)\n if m_type == M.RefTypes.Tag and not util.is_hex_color(match_string) then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n--- Replace references of the form '[[xxx|xxx]]', '[[xxx]]', or '[xxx](xxx)' with their title.\n---\n---@param s string\n---\n---@return string\nM.replace_refs = function(s)\n local out, _ = string.gsub(s, \"%[%[[^%|%]]+%|([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[%[([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[([^%]]+)%]%([^%)]+%)\", \"%1\")\n return out\nend\n\n--- Find all refs in a string and replace with their titles.\n---\n---@param s string\n--\n---@return string\n---@return table\n---@return string[]\nM.find_and_replace_refs = function(s)\n local pieces = {}\n local refs = {}\n local is_ref = {}\n local matches = M.find_refs(s)\n local last_end = 1\n for _, match in pairs(matches) do\n local m_start, m_end, _ = unpack(match)\n assert(type(m_start) == \"number\")\n if last_end < m_start then\n table.insert(pieces, string.sub(s, last_end, m_start - 1))\n table.insert(is_ref, false)\n end\n local ref_str = string.sub(s, m_start, m_end)\n table.insert(pieces, M.replace_refs(ref_str))\n table.insert(refs, ref_str)\n table.insert(is_ref, true)\n last_end = m_end + 1\n end\n\n local indices = {}\n local length = 0\n for i, piece in ipairs(pieces) do\n local i_end = length + string.len(piece)\n if is_ref[i] then\n table.insert(indices, { length + 1, i_end })\n end\n length = i_end\n end\n\n return table.concat(pieces, \"\"), indices, refs\nend\n\n--- Find all code block boundaries in a list of lines.\n---\n---@param lines string[]\n---\n---@return { [1]: integer, [2]: integer }[]\nM.find_code_blocks = function(lines)\n ---@type { [1]: integer, [2]: integer }[]\n local blocks = {}\n ---@type integer|?\n local start_idx\n for i, line in ipairs(lines) do\n if string.match(line, \"^%s*```.*```%s*$\") then\n table.insert(blocks, { i, i })\n start_idx = nil\n elseif string.match(line, \"^%s*```\") then\n if start_idx ~= nil then\n table.insert(blocks, { start_idx, i })\n start_idx = nil\n else\n start_idx = i\n end\n end\n end\n return blocks\nend\n\n---@class obsidian.search.SearchOpts\n---\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field fixed_strings boolean|?\n---@field ignore_case boolean|?\n---@field smart_case boolean|?\n---@field exclude string[]|? paths to exclude\n---@field max_count_per_file integer|?\n---@field escape_path boolean|?\n---@field include_non_markdown boolean|?\n\nlocal SearchOpts = {}\nM.SearchOpts = SearchOpts\n\nSearchOpts.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\nend\n\n---@param one obsidian.search.SearchOpts|table\n---@param other obsidian.search.SearchOpts|table\n---@return obsidian.search.SearchOpts\nSearchOpts.merge = function(one, other)\n return vim.tbl_extend(\"force\", SearchOpts.as_tbl(one), SearchOpts.as_tbl(other))\nend\n\n---@param opts obsidian.search.SearchOpts\n---@param path string\nSearchOpts.add_exclude = function(opts, path)\n if opts.exclude == nil then\n opts.exclude = {}\n end\n opts.exclude[#opts.exclude + 1] = path\nend\n\n---@param opts obsidian.search.SearchOpts\n---@return string[]\nSearchOpts.to_ripgrep_opts = function(opts)\n local ret = {}\n\n if opts.sort_by ~= nil then\n local sort = \"sortr\" -- default sort is reverse\n if opts.sort_reversed == false then\n sort = \"sort\"\n end\n ret[#ret + 1] = \"--\" .. sort .. \"=\" .. opts.sort_by\n end\n\n if opts.fixed_strings then\n ret[#ret + 1] = \"--fixed-strings\"\n end\n\n if opts.ignore_case then\n ret[#ret + 1] = \"--ignore-case\"\n end\n\n if opts.smart_case then\n ret[#ret + 1] = \"--smart-case\"\n end\n\n if opts.exclude ~= nil then\n assert(type(opts.exclude) == \"table\")\n for path in iter(opts.exclude) do\n ret[#ret + 1] = \"-g!\" .. path\n end\n end\n\n if opts.max_count_per_file ~= nil then\n ret[#ret + 1] = \"-m=\" .. opts.max_count_per_file\n end\n\n return ret\nend\n\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_search_cmd = function(dir, term, opts)\n opts = opts and opts or {}\n\n local search_terms\n if type(term) == \"string\" then\n search_terms = { \"-e\", term }\n else\n search_terms = {}\n for t in iter(term) do\n search_terms[#search_terms + 1] = \"-e\"\n search_terms[#search_terms + 1] = t\n end\n end\n\n local path = tostring(Path.new(dir):resolve { strict = true })\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(path))\n end\n\n return compat.flatten {\n M._SEARCH_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n search_terms,\n path,\n }\nend\n\n--- Build the 'rg' command for finding files.\n---\n---@param path string|?\n---@param term string|?\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_find_cmd = function(path, term, opts)\n opts = opts and opts or {}\n\n local additional_opts = {}\n\n if term ~= nil then\n if opts.include_non_markdown then\n term = \"*\" .. term .. \"*\"\n elseif not vim.endswith(term, \".md\") then\n term = \"*\" .. term .. \"*.md\"\n else\n term = \"*\" .. term\n end\n additional_opts[#additional_opts + 1] = \"-g\"\n additional_opts[#additional_opts + 1] = term\n end\n\n if opts.ignore_case then\n additional_opts[#additional_opts + 1] = \"--glob-case-insensitive\"\n end\n\n if path ~= nil and path ~= \".\" then\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(tostring(path)))\n end\n additional_opts[#additional_opts + 1] = path\n end\n\n return compat.flatten { M._FIND_CMD, SearchOpts.to_ripgrep_opts(opts), additional_opts }\nend\n\n--- Build the 'rg' grep command for pickers.\n---\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_grep_cmd = function(opts)\n opts = opts and opts or {}\n\n return compat.flatten {\n M._BASE_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n \"--column\",\n \"--line-number\",\n \"--no-heading\",\n \"--with-filename\",\n \"--color=never\",\n }\nend\n\n---@class MatchPath\n---\n---@field text string\n\n---@class MatchText\n---\n---@field text string\n\n---@class SubMatch\n---\n---@field match MatchText\n---@field start integer\n---@field end integer\n\n---@class MatchData\n---\n---@field path MatchPath\n---@field lines MatchText\n---@field line_number integer 0-indexed\n---@field absolute_offset integer\n---@field submatches SubMatch[]\n\n--- Search markdown files in a directory for a given term. Each match is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(match: MatchData)\n---@param on_exit fun(exit_code: integer)|?\nM.search_async = function(dir, term, opts, on_match, on_exit)\n local cmd = M.build_search_cmd(dir, term, opts)\n run_job_async(cmd, function(line)\n local data = vim.json.decode(line)\n if data[\"type\"] == \"match\" then\n local match_data = data.data\n on_match(match_data)\n end\n end, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\n--- Find markdown files in a directory matching a given term. Each matching path is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(path: string)\n---@param on_exit fun(exit_code: integer)|?\nM.find_async = function(dir, term, opts, on_match, on_exit)\n local norm_dir = Path.new(dir):resolve { strict = true }\n local cmd = M.build_find_cmd(tostring(norm_dir), term, opts)\n run_job_async(cmd, on_match, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\nlocal search_defualts = {\n sort = false,\n include_templates = false,\n ignore_case = false,\n}\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nlocal _prepare_search_opts = function(opts, additional_opts)\n opts = opts or search_defualts\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n M.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = M.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---@param callback fun(path: obsidian.Path)\n---@param exit_callback fun(paths: obsidian.Path[])\nlocal _search_async = function(term, search_opts, find_opts, callback, exit_callback)\n local found = {}\n local result = {}\n local cmds_done = 0\n\n local function dedup_send(path)\n local key = tostring(path:resolve { strict = true })\n if not found[key] then\n found[key] = true\n result[#result + 1] = path\n callback(path)\n end\n end\n\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text)\n dedup_send(path)\n end\n\n local function on_find_match(path_match)\n local path = Path.new(path_match)\n dedup_send(path)\n end\n\n local function on_exit()\n cmds_done = cmds_done + 1\n if cmds_done == 2 then\n exit_callback(result)\n end\n end\n\n M.search_async(\n Obsidian.dir,\n term,\n _prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n M.find_async(Obsidian.dir, term, _prepare_search_opts(find_opts, { ignore_case = true }), on_find_match, on_exit)\nend\n\n--- An async version of `find_notes()` that runs the callback with an array of all matching notes.\n---\n---@param term string The term to search for\n---@param callback fun(notes: obsidian.Note[])\n---@param opts { search: obsidian.SearchOpts|?, notes: obsidian.note.LoadOpts|? }|?\nM.find_notes_async = function(term, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n\n ---@type table\n local paths = {}\n local num_results = 0\n local err_count = 0\n local first_err\n local first_err_path\n local notes = {}\n local Note = require \"obsidian.note\"\n\n ---@param path obsidian.Path\n local function on_path(path)\n local ok, res = pcall(Note.from_file, path, opts.notes)\n\n if ok then\n num_results = num_results + 1\n paths[tostring(path)] = num_results\n notes[#notes + 1] = res\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n end\n end\n\n local on_exit = function()\n -- Then sort by original order.\n table.sort(notes, function(a, b)\n return paths[tostring(a.path)] < paths[tostring(b.path)]\n end)\n\n -- Check for errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n callback(notes)\n end\n\n _search_async(term, opts.search, nil, on_path, on_exit)\nend\n\nM.find_notes = function(term, opts)\n opts = opts or {}\n opts.timeout = opts.timeout or 1000\n return block_on(function(cb)\n return M.find_notes_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n---@param query string\n---@param callback fun(results: obsidian.Note[])\n---@param opts { notes: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note|?\nlocal _resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n local Note = require \"obsidian.note\"\n\n -- Autocompletion for command args will have this format.\n local note_path, count = string.gsub(query, \"^.*  \", \"\")\n if count > 0 then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n local full_path = Obsidian.dir / note_path\n callback { Note.from_file(full_path, opts.notes) }\n end\n\n -- Query might be a path.\n local fname = query\n if not vim.endswith(fname, \".md\") then\n fname = fname .. \".md\"\n end\n\n local paths_to_check = { Path.new(fname), Obsidian.dir / fname }\n\n if Obsidian.opts.notes_subdir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.notes_subdir / fname\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.daily_notes.folder / fname\n end\n\n if Obsidian.buf_dir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.buf_dir / fname\n end\n\n for _, path in pairs(paths_to_check) do\n if path:is_file() then\n return callback { Note.from_file(path, opts.notes) }\n end\n end\n\n M.find_notes_async(query, function(results)\n local query_lwr = string.lower(query)\n\n -- We'll gather both exact matches (of ID, filename, and aliases) and fuzzy matches.\n -- If we end up with any exact matches, we'll return those. Otherwise we fall back to fuzzy\n -- matches.\n ---@type obsidian.Note[]\n local exact_matches = {}\n ---@type obsidian.Note[]\n local fuzzy_matches = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local reference_ids = note:reference_ids { lowercase = true }\n\n -- Check for exact match.\n if vim.list_contains(reference_ids, query_lwr) then\n table.insert(exact_matches, note)\n else\n -- Fall back to fuzzy match.\n for ref_id in iter(reference_ids) do\n if util.string_contains(ref_id, query_lwr) then\n table.insert(fuzzy_matches, note)\n break\n end\n end\n end\n end\n\n if #exact_matches > 0 then\n return callback(exact_matches)\n else\n return callback(fuzzy_matches)\n end\n end, { search = { sort = true, ignore_case = true }, notes = opts.notes })\nend\n\n--- Resolve a note, opens a picker to choose a single note when there are multiple matches.\n---\n---@param query string\n---@param callback fun(obsidian.Note)\n---@param opts { notes: obsidian.note.LoadOpts|?, prompt_title: string|?, pick: boolean }|?\n---\n---@return obsidian.Note|?\nM.resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.pick = vim.F.if_nil(opts.pick, true)\n\n _resolve_note_async(query, function(notes)\n if opts.pick then\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", query)\n return\n elseif #notes == 1 then\n return callback(notes[1])\n end\n\n -- Fall back to picker.\n vim.schedule(function()\n -- Otherwise run the preferred picker to search for notes.\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple notes matching '%s', but no picker is configured\", query)\n return\n end\n\n picker:pick_note(notes, {\n prompt_title = opts.prompt_title,\n callback = callback,\n })\n end)\n else\n callback(notes)\n end\n end, { notes = opts.notes })\nend\n\n---@class obsidian.ResolveLinkResult\n---\n---@field location string\n---@field name string\n---@field link_type obsidian.search.RefTypes\n---@field path obsidian.Path|?\n---@field note obsidian.Note|?\n---@field url string|?\n---@field line integer|?\n---@field col integer|?\n---@field anchor obsidian.note.HeaderAnchor|?\n---@field block obsidian.note.Block|?\n\n--- Resolve a link.\n---\n---@param link string\n---@param callback fun(results: obsidian.ResolveLinkResult[])\nM.resolve_link_async = function(link, callback)\n local Note = require \"obsidian.note\"\n\n local location, name, link_type\n location, name, link_type = util.parse_link(link, { include_naked_urls = true, include_file_urls = true })\n\n if location == nil or name == nil or link_type == nil then\n return callback {}\n end\n\n ---@type obsidian.ResolveLinkResult\n local res = { location = location, name = name, link_type = link_type }\n\n if util.is_url(location) then\n res.url = location\n return callback { res }\n end\n\n -- The Obsidian app will follow URL-encoded links, so we should to.\n location = vim.uri_decode(location)\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n --- Finalize the `obsidian.ResolveLinkResult` for a note while resolving block or anchor link to line.\n ---\n ---@param note obsidian.Note\n ---@return obsidian.ResolveLinkResult\n local function finalize_result(note)\n ---@type integer|?, obsidian.note.Block|?, obsidian.note.HeaderAnchor|?\n local line, block_match, anchor_match\n if block_link ~= nil then\n block_match = note:resolve_block(block_link)\n if block_match then\n line = block_match.line\n end\n elseif anchor_link ~= nil then\n anchor_match = note:resolve_anchor_link(anchor_link)\n if anchor_match then\n line = anchor_match.line\n end\n end\n\n return vim.tbl_extend(\n \"force\",\n res,\n { path = note.path, note = note, line = line, block = block_match, anchor = anchor_match }\n )\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = anchor_link and true or false,\n collect_blocks = block_link and true or false,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n res.location = vim.api.nvim_buf_get_name(0)\n local note = Note.from_buffer(0, load_opts)\n return callback { finalize_result(note) }\n end\n\n res.location = location\n\n M.resolve_note_async(location, function(notes)\n if #notes == 0 then\n local path = Path.new(location)\n if path:exists() then\n res.path = path\n return callback { res }\n else\n return callback { res }\n end\n end\n\n local matches = {}\n for _, note in ipairs(notes) do\n table.insert(matches, finalize_result(note))\n end\n\n return callback(matches)\n end, { notes = load_opts, pick = false })\nend\n\n---@class obsidian.LinkMatch\n---@field link string\n---@field line integer\n---@field start integer 0-indexed\n---@field end integer 0-indexed\n\n-- Gather all unique links from the a note.\n--\n---@param note obsidian.Note\n---@param opts { on_match: fun(link: obsidian.LinkMatch) }\n---@param callback fun(links: obsidian.LinkMatch[])\nM.find_links = function(note, opts, callback)\n ---@type obsidian.LinkMatch[]\n local matches = {}\n ---@type table\n local found = {}\n local lines = io.lines(tostring(note.path))\n\n for lnum, line in util.enumerate(lines) do\n for ref_match in vim.iter(M.find_refs(line, { include_naked_urls = true, include_file_urls = true })) do\n local m_start, m_end = unpack(ref_match)\n local link = string.sub(line, m_start, m_end)\n if not found[link] then\n local match = {\n link = link,\n line = lnum,\n start = m_start - 1,\n [\"end\"] = m_end - 1,\n }\n matches[#matches + 1] = match\n found[link] = true\n if opts.on_match then\n opts.on_match(match)\n end\n end\n end\n end\n\n callback(matches)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/link.lua", "local search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n ---@type string\n local search_term\n if data.args ~= nil and string.len(data.args) > 0 then\n search_term = data.args\n else\n search_term = viz.selection\n end\n\n ---@param note obsidian.Note\n local function insert_ref(note)\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = viz.selection })\n .. string.sub(line, viz.cecol + 1)\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\n require(\"obsidian.ui\").update(0)\n end\n\n search.resolve_note_async(search_term, function(note)\n vim.schedule(function()\n insert_ref(note)\n end)\n end, { prompt_title = \"Select note to link\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/refs.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.RefsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field in_buffer_only boolean\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\n---@field block_link string|?\n---@field anchor_link string|?\n---@field new_text_to_option table\nlocal RefsSourceCompletionContext = abc.new_class()\n\nRefsSourceCompletionContext.new = function()\n return RefsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.RefsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal RefsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.RefsSourceBase\nRefsSourceBase.new = function()\n return RefsSourceBase.init()\nend\n\nRefsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = RefsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n completion_context.in_buffer_only = false\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n self:strip_links(cc)\n self:determine_buffer_only_search_scope(cc)\n\n if cc.in_buffer_only then\n local note = api.current_note(0, { collect_anchor_links = true, collect_blocks = true })\n if note then\n self:process_search_results(cc, { note })\n else\n cc.completion_resolve_callback(self.incomplete_response)\n end\n else\n local search_ops = cc.client.search_defaults()\n search_ops.ignore_case = true\n\n search.find_notes_async(cc.search, function(results)\n self:process_search_results(cc, results)\n end, {\n search = search_ops,\n notes = { collect_anchor_links = cc.anchor_link ~= nil, collect_blocks = cc.block_link ~= nil },\n })\n end\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction RefsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\n---Collect matching block links.\n---@param note obsidian.Note\n---@param block_link string?\n---@return obsidian.note.Block[]|?\nfunction RefsSourceBase:collect_matching_blocks(note, block_link)\n ---@type obsidian.note.Block[]|?\n local matching_blocks\n if block_link then\n assert(note.blocks)\n matching_blocks = {}\n for block_id, block_data in pairs(note.blocks) do\n if vim.startswith(\"#\" .. block_id, block_link) then\n table.insert(matching_blocks, block_data)\n end\n end\n\n if #matching_blocks == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_blocks, { id = util.standardize_block(block_link), line = 1 })\n end\n end\n\n return matching_blocks\nend\n\n---Collect matching anchor links.\n---@param note obsidian.Note\n---@param anchor_link string?\n---@return obsidian.note.HeaderAnchor[]?\nfunction RefsSourceBase:collect_matching_anchors(note, anchor_link)\n ---@type obsidian.note.HeaderAnchor[]|?\n local matching_anchors\n if anchor_link then\n assert(note.anchor_links)\n matching_anchors = {}\n for anchor, anchor_data in pairs(note.anchor_links) do\n if vim.startswith(anchor, anchor_link) then\n table.insert(matching_anchors, anchor_data)\n end\n end\n\n if #matching_anchors == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_anchors, { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 })\n end\n end\n\n return matching_anchors\nend\n\n--- Strips block and anchor links from the current search string\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:strip_links(cc)\n cc.search, cc.block_link = util.strip_block_links(cc.search)\n cc.search, cc.anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, we'll match against all block links.\n if not cc.block_link and vim.endswith(cc.search, \"#^\") then\n cc.block_link = \"#^\"\n cc.search = string.sub(cc.search, 1, -3)\n end\n\n -- If anchor link is incomplete, we'll match against all anchor links.\n if not cc.anchor_link and vim.endswith(cc.search, \"#\") then\n cc.anchor_link = \"#\"\n cc.search = string.sub(cc.search, 1, -2)\n end\nend\n\n--- Determines whatever the in_buffer_only should be enabled\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:determine_buffer_only_search_scope(cc)\n if (cc.anchor_link or cc.block_link) and string.len(cc.search) == 0 then\n -- Search over headers/blocks in current buffer only.\n cc.in_buffer_only = true\n end\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param results obsidian.Note[]\nfunction RefsSourceBase:process_search_results(cc, results)\n assert(cc)\n assert(results)\n\n local completion_items = {}\n\n cc.new_text_to_option = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local matching_blocks = self:collect_matching_blocks(note, cc.block_link)\n local matching_anchors = self:collect_matching_anchors(note, cc.anchor_link)\n\n if cc.in_buffer_only then\n self:update_completion_options(cc, nil, nil, matching_anchors, matching_blocks, note)\n else\n -- Collect all valid aliases for the note, including ID, title, and filename.\n ---@type string[]\n local aliases\n if not cc.in_buffer_only then\n aliases = util.tbl_unique { tostring(note.id), note:display_name(), unpack(note.aliases) }\n if note.title ~= nil then\n table.insert(aliases, note.title)\n end\n end\n\n for alias in iter(aliases) do\n self:update_completion_options(cc, alias, nil, matching_anchors, matching_blocks, note)\n local alias_case_matched = util.match_case(cc.search, alias)\n\n if\n alias_case_matched ~= nil\n and alias_case_matched ~= alias\n and not vim.list_contains(note.aliases, alias_case_matched)\n and Obsidian.opts.completion.match_case\n then\n self:update_completion_options(cc, alias_case_matched, nil, matching_anchors, matching_blocks, note)\n end\n end\n\n if note.alt_alias ~= nil then\n self:update_completion_options(cc, note:display_name(), note.alt_alias, matching_anchors, matching_blocks, note)\n end\n end\n end\n\n for _, option in pairs(cc.new_text_to_option) do\n -- TODO: need a better label, maybe just the note's display name?\n ---@type string\n local label\n if cc.ref_type == completion.RefType.Wiki then\n label = string.format(\"[[%s]]\", option.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n label = string.format(\"[%s](…)\", option.label)\n else\n error \"not implemented\"\n end\n\n table.insert(completion_items, {\n documentation = option.documentation,\n sortText = option.sort_text,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = option.new_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n })\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = completion_items }))\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param label string|?\n---@param alt_label string|?\n---@param note obsidian.Note\nfunction RefsSourceBase:update_completion_options(cc, label, alt_label, matching_anchors, matching_blocks, note)\n ---@type { label: string|?, alt_label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }[]\n local new_options = {}\n if matching_anchors ~= nil then\n for anchor in iter(matching_anchors) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor })\n end\n elseif matching_blocks ~= nil then\n for block in iter(matching_blocks) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block })\n end\n else\n if label then\n table.insert(new_options, { label = label, alt_label = alt_label })\n end\n\n -- Add all blocks and anchors, let cmp sort it out.\n for _, anchor_data in pairs(note.anchor_links or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor_data })\n end\n for _, block_data in pairs(note.blocks or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block_data })\n end\n end\n\n -- De-duplicate options relative to their `new_text`.\n for _, option in ipairs(new_options) do\n ---@type obsidian.config.LinkStyle\n local link_style\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n else\n error \"not implemented\"\n end\n\n ---@type string, string, string, table|?\n local final_label, sort_text, new_text, documentation\n if option.label then\n new_text = api.format_link(\n note,\n { label = option.label, link_style = link_style, anchor = option.anchor, block = option.block }\n )\n\n final_label = assert(option.alt_label or option.label)\n if option.anchor then\n final_label = final_label .. option.anchor.anchor\n elseif option.block then\n final_label = final_label .. \"#\" .. option.block.id\n end\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = note:display_info {\n label = new_text,\n anchor = option.anchor,\n block = option.block,\n },\n }\n elseif option.anchor then\n -- In buffer anchor link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.anchor.header .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.anchor.header .. \"](\" .. option.anchor.anchor .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = option.anchor.anchor\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n elseif option.block then\n -- In buffer block link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.block.id .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.block.id .. \"](#\" .. option.block.id .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = \"#\" .. option.block.id\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n else\n error \"should not happen\"\n end\n\n if cc.new_text_to_option[new_text] then\n cc.new_text_to_option[new_text].sort_text = cc.new_text_to_option[new_text].sort_text .. \" \" .. sort_text\n else\n cc.new_text_to_option[new_text] =\n { label = final_label, new_text = new_text, sort_text = sort_text, documentation = documentation }\n end\n end\nend\n\nreturn RefsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/config.lua", "local log = require \"obsidian.log\"\n\nlocal config = {}\n\n---@class obsidian.config\n---@field workspaces obsidian.workspace.WorkspaceSpec[]\n---@field log_level? integer\n---@field notes_subdir? string\n---@field templates? obsidian.config.TemplateOpts\n---@field new_notes_location? obsidian.config.NewNotesLocation\n---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func? fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path\n---@field wiki_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field markdown_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field preferred_link_style? obsidian.config.LinkStyle\n---@field follow_url_func? fun(url: string)\n---@field follow_img_func? fun(img: string)\n---@field note_frontmatter_func? (fun(note: obsidian.Note): table)\n---@field disable_frontmatter? (fun(fname: string?): boolean)|boolean\n---@field backlinks? obsidian.config.BacklinkOpts\n---@field completion? obsidian.config.CompletionOpts\n---@field picker? obsidian.config.PickerOpts\n---@field daily_notes? obsidian.config.DailyNotesOpts\n---@field sort_by? obsidian.config.SortBy\n---@field sort_reversed? boolean\n---@field search_max_lines? integer\n---@field open_notes_in? obsidian.config.OpenStrategy\n---@field ui? obsidian.config.UIOpts | table\n---@field attachments? obsidian.config.AttachmentsOpts\n---@field callbacks? obsidian.config.CallbackConfig\n---@field legacy_commands? boolean\n---@field statusline? obsidian.config.StatuslineOpts\n---@field footer? obsidian.config.FooterOpts\n---@field open? obsidian.config.OpenOpts\n---@field checkbox? obsidian.config.CheckboxOpts\n---@field comment? obsidian.config.CommentOpts\n\n---@class obsidian.config.ClientOpts\n---@field dir string|?\n---@field workspaces obsidian.workspace.WorkspaceSpec[]|?\n---@field log_level integer\n---@field notes_subdir string|?\n---@field templates obsidian.config.TemplateOpts\n---@field new_notes_location obsidian.config.NewNotesLocation\n---@field note_id_func (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func (fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path)|?\n---@field wiki_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field markdown_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field preferred_link_style obsidian.config.LinkStyle\n---@field follow_url_func fun(url: string)|?\n---@field follow_img_func fun(img: string)|?\n---@field note_frontmatter_func (fun(note: obsidian.Note): table)|?\n---@field disable_frontmatter (fun(fname: string?): boolean)|boolean|?\n---@field backlinks obsidian.config.BacklinkOpts\n---@field completion obsidian.config.CompletionOpts\n---@field picker obsidian.config.PickerOpts\n---@field daily_notes obsidian.config.DailyNotesOpts\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field search_max_lines integer\n---@field open_notes_in obsidian.config.OpenStrategy\n---@field ui obsidian.config.UIOpts | table\n---@field attachments obsidian.config.AttachmentsOpts\n---@field callbacks obsidian.config.CallbackConfig\n---@field legacy_commands boolean\n---@field statusline obsidian.config.StatuslineOpts\n---@field footer obsidian.config.FooterOpts\n---@field open obsidian.config.OpenOpts\n---@field checkbox obsidian.config.CheckboxOpts\n---@field comment obsidian.config.CommentOpts\n\n---@enum obsidian.config.OpenStrategy\nconfig.OpenStrategy = {\n current = \"current\",\n vsplit = \"vsplit\",\n hsplit = \"hsplit\",\n vsplit_force = \"vsplit_force\",\n hsplit_force = \"hsplit_force\",\n}\n\n---@enum obsidian.config.SortBy\nconfig.SortBy = {\n path = \"path\",\n modified = \"modified\",\n accessed = \"accessed\",\n created = \"created\",\n}\n\n---@enum obsidian.config.NewNotesLocation\nconfig.NewNotesLocation = {\n current_dir = \"current_dir\",\n notes_subdir = \"notes_subdir\",\n}\n\n---@enum obsidian.config.LinkStyle\nconfig.LinkStyle = {\n wiki = \"wiki\",\n markdown = \"markdown\",\n}\n\n---@enum obsidian.config.Picker\nconfig.Picker = {\n telescope = \"telescope.nvim\",\n fzf_lua = \"fzf-lua\",\n mini = \"mini.pick\",\n snacks = \"snacks.pick\",\n}\n\n--- Get defaults.\n---\n---@return obsidian.config.ClientOpts\nconfig.default = {\n legacy_commands = true,\n workspaces = {},\n log_level = vim.log.levels.INFO,\n notes_subdir = nil,\n new_notes_location = config.NewNotesLocation.current_dir,\n note_id_func = nil,\n wiki_link_func = require(\"obsidian.builtin\").wiki_link_id_prefix,\n markdown_link_func = require(\"obsidian.builtin\").markdown_link,\n preferred_link_style = config.LinkStyle.wiki,\n follow_url_func = vim.ui.open,\n follow_img_func = vim.ui.open,\n note_frontmatter_func = nil,\n disable_frontmatter = false,\n sort_by = \"modified\",\n sort_reversed = true,\n search_max_lines = 1000,\n open_notes_in = \"current\",\n\n ---@class obsidian.config.TemplateOpts\n ---\n ---@field folder string|obsidian.Path|?\n ---@field date_format string|?\n ---@field time_format string|?\n --- A map for custom variables, the key should be the variable and the value a function.\n --- Functions are called with obsidian.TemplateContext objects as their sole parameter.\n --- See: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Template#substitutions\n ---@field substitutions table|?\n ---@field customizations table|?\n templates = {\n folder = nil,\n date_format = nil,\n time_format = nil,\n substitutions = {},\n\n ---@class obsidian.config.CustomTemplateOpts\n ---\n ---@field notes_subdir? string\n ---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n customizations = {},\n },\n\n ---@class obsidian.config.BacklinkOpts\n ---\n ---@field parse_headers boolean\n backlinks = {\n parse_headers = true,\n },\n\n ---@class obsidian.config.CompletionOpts\n ---\n ---@field nvim_cmp? boolean\n ---@field blink? boolean\n ---@field min_chars? integer\n ---@field match_case? boolean\n ---@field create_new? boolean\n completion = (function()\n local has_nvim_cmp, _ = pcall(require, \"cmp\")\n return {\n nvim_cmp = has_nvim_cmp,\n min_chars = 2,\n match_case = true,\n create_new = true,\n }\n end)(),\n\n ---@class obsidian.config.PickerNoteMappingOpts\n ---\n ---@field new? string\n ---@field insert_link? string\n\n ---@class obsidian.config.PickerTagMappingOpts\n ---\n ---@field tag_note? string\n ---@field insert_tag? string\n\n ---@class obsidian.config.PickerOpts\n ---\n ---@field name obsidian.config.Picker|?\n ---@field note_mappings? obsidian.config.PickerNoteMappingOpts\n ---@field tag_mappings? obsidian.config.PickerTagMappingOpts\n picker = {\n name = nil,\n note_mappings = {\n new = \"\",\n insert_link = \"\",\n },\n tag_mappings = {\n tag_note = \"\",\n insert_tag = \"\",\n },\n },\n\n ---@class obsidian.config.DailyNotesOpts\n ---\n ---@field folder? string\n ---@field date_format? string\n ---@field alias_format? string\n ---@field template? string\n ---@field default_tags? string[]\n ---@field workdays_only? boolean\n daily_notes = {\n folder = nil,\n date_format = nil,\n alias_format = nil,\n default_tags = { \"daily-notes\" },\n workdays_only = true,\n },\n\n ---@class obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.CheckboxSpec : obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.UIStyleSpec\n ---@field hl_group string\n\n ---@class obsidian.config.UIOpts\n ---\n ---@field enable boolean\n ---@field ignore_conceal_warn boolean\n ---@field update_debounce integer\n ---@field max_file_length integer|?\n ---@field checkboxes table\n ---@field bullets obsidian.config.UICharSpec|?\n ---@field external_link_icon obsidian.config.UICharSpec\n ---@field reference_text obsidian.config.UIStyleSpec\n ---@field highlight_text obsidian.config.UIStyleSpec\n ---@field tags obsidian.config.UIStyleSpec\n ---@field block_ids obsidian.config.UIStyleSpec\n ---@field hl_groups table\n ui = {\n enable = true,\n ignore_conceal_warn = false,\n update_debounce = 200,\n max_file_length = 5000,\n checkboxes = {\n [\" \"] = { char = \"󰄱\", hl_group = \"obsidiantodo\" },\n [\"~\"] = { char = \"󰰱\", hl_group = \"obsidiantilde\" },\n [\"!\"] = { char = \"\", hl_group = \"obsidianimportant\" },\n [\">\"] = { char = \"\", hl_group = \"obsidianrightarrow\" },\n [\"x\"] = { char = \"\", hl_group = \"obsidiandone\" },\n },\n bullets = { char = \"•\", hl_group = \"ObsidianBullet\" },\n external_link_icon = { char = \"\", hl_group = \"ObsidianExtLinkIcon\" },\n reference_text = { hl_group = \"ObsidianRefText\" },\n highlight_text = { hl_group = \"ObsidianHighlightText\" },\n tags = { hl_group = \"ObsidianTag\" },\n block_ids = { hl_group = \"ObsidianBlockID\" },\n hl_groups = {\n ObsidianTodo = { bold = true, fg = \"#f78c6c\" },\n ObsidianDone = { bold = true, fg = \"#89ddff\" },\n ObsidianRightArrow = { bold = true, fg = \"#f78c6c\" },\n ObsidianTilde = { bold = true, fg = \"#ff5370\" },\n ObsidianImportant = { bold = true, fg = \"#d73128\" },\n ObsidianBullet = { bold = true, fg = \"#89ddff\" },\n ObsidianRefText = { underline = true, fg = \"#c792ea\" },\n ObsidianExtLinkIcon = { fg = \"#c792ea\" },\n ObsidianTag = { italic = true, fg = \"#89ddff\" },\n ObsidianBlockID = { italic = true, fg = \"#89ddff\" },\n ObsidianHighlightText = { bg = \"#75662e\" },\n },\n },\n\n ---@class obsidian.config.AttachmentsOpts\n ---\n ---Default folder to save images to, relative to the vault root (/) or current dir (.), see https://github.com/obsidian-nvim/obsidian.nvim/wiki/Images#change-image-save-location\n ---@field img_folder? string\n ---\n ---Default name for pasted images\n ---@field img_name_func? fun(): string\n ---\n ---Default text to insert for pasted images\n ---@field img_text_func? fun(path: obsidian.Path): string\n ---\n ---Whether to confirm the paste or not. Defaults to true.\n ---@field confirm_img_paste? boolean\n attachments = {\n img_folder = \"assets/imgs\",\n img_text_func = require(\"obsidian.builtin\").img_text_func,\n img_name_func = function()\n return string.format(\"Pasted image %s\", os.date \"%Y%m%d%H%M%S\")\n end,\n confirm_img_paste = true,\n },\n\n ---@class obsidian.config.CallbackConfig\n ---\n ---Runs right after the `obsidian.Client` is initialized.\n ---@field post_setup? fun(client: obsidian.Client)\n ---\n ---Runs when entering a note buffer.\n ---@field enter_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs when leaving a note buffer.\n ---@field leave_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs right before writing a note buffer.\n ---@field pre_write_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs anytime the workspace is set/changed.\n ---@field post_set_workspace? fun(client: obsidian.Client, workspace: obsidian.Workspace)\n callbacks = {},\n\n ---@class obsidian.config.StatuslineOpts\n ---\n ---@field format? string\n ---@field enabled? boolean\n statusline = {\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n enabled = true,\n },\n\n ---@class obsidian.config.FooterOpts\n ---\n ---@field enabled? boolean\n ---@field format? string\n ---@field hl_group? string\n ---@field separator? string|false Set false to disable separator; set an empty string to insert a blank line separator.\n footer = {\n enabled = true,\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n hl_group = \"Comment\",\n separator = string.rep(\"-\", 80),\n },\n\n ---@class obsidian.config.OpenOpts\n ---\n ---Opens the file with current line number\n ---@field use_advanced_uri? boolean\n ---\n ---Function to do the opening, default to vim.ui.open\n ---@field func? fun(uri: string)\n open = {\n use_advanced_uri = false,\n func = vim.ui.open,\n },\n\n ---@class obsidian.config.CheckboxOpts\n ---\n ---@field enabled? boolean\n ---\n ---Order of checkbox state chars, e.g. { \" \", \"x\" }\n ---@field order? string[]\n ---\n ---Whether to create new checkbox on paragraphs\n ---@field create_new? boolean\n checkbox = {\n enabled = true,\n create_new = true,\n order = { \" \", \"~\", \"!\", \">\", \"x\" },\n },\n\n ---@class obsidian.config.CommentOpts\n ---@field enabled boolean\n comment = {\n enabled = false,\n },\n}\n\nlocal tbl_override = function(defaults, overrides)\n local out = vim.tbl_extend(\"force\", defaults, overrides)\n for k, v in pairs(out) do\n if v == vim.NIL then\n out[k] = nil\n end\n end\n return out\nend\n\nlocal function deprecate(name, alternative, version)\n vim.deprecate(name, alternative, version, \"obsidian.nvim\", false)\nend\n\n--- Normalize options.\n---\n---@param opts table\n---@param defaults obsidian.config.ClientOpts|?\n---\n---@return obsidian.config.ClientOpts\nconfig.normalize = function(opts, defaults)\n local builtin = require \"obsidian.builtin\"\n local util = require \"obsidian.util\"\n\n if not defaults then\n defaults = config.default\n end\n\n -------------------------------------------------------------------------------------\n -- Rename old fields for backwards compatibility and warn about deprecated fields. --\n -------------------------------------------------------------------------------------\n\n if opts.ui and opts.ui.tick then\n opts.ui.update_debounce = opts.ui.tick\n opts.ui.tick = nil\n end\n\n if not opts.picker then\n opts.picker = {}\n if opts.finder then\n opts.picker.name = opts.finder\n opts.finder = nil\n end\n if opts.finder_mappings then\n opts.picker.note_mappings = opts.finder_mappings\n opts.finder_mappings = nil\n end\n if opts.picker.mappings and not opts.picker.note_mappings then\n opts.picker.note_mappings = opts.picker.mappings\n opts.picker.mappings = nil\n end\n end\n\n if opts.wiki_link_func == nil and opts.completion ~= nil then\n local warn = false\n\n if opts.completion.prepend_note_id then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n opts.completion.prepend_note_id = nil\n warn = true\n elseif opts.completion.prepend_note_path then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n opts.completion.prepend_note_path = nil\n warn = true\n elseif opts.completion.use_path_only then\n opts.wiki_link_func = builtin.wiki_link_path_only\n opts.completion.use_path_only = nil\n warn = true\n end\n\n if warn then\n log.warn_once(\n \"The config options 'completion.prepend_note_id', 'completion.prepend_note_path', and 'completion.use_path_only' \"\n .. \"are deprecated. Please use 'wiki_link_func' instead.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/406\"\n )\n end\n end\n\n if opts.wiki_link_func == \"prepend_note_id\" then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n elseif opts.wiki_link_func == \"prepend_note_path\" then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n elseif opts.wiki_link_func == \"use_path_only\" then\n opts.wiki_link_func = builtin.wiki_link_path_only\n elseif opts.wiki_link_func == \"use_alias_only\" then\n opts.wiki_link_func = builtin.wiki_link_alias_only\n elseif type(opts.wiki_link_func) == \"string\" then\n error(string.format(\"invalid option '%s' for 'wiki_link_func'\", opts.wiki_link_func))\n end\n\n if opts.completion ~= nil and opts.completion.preferred_link_style ~= nil then\n opts.preferred_link_style = opts.completion.preferred_link_style\n opts.completion.preferred_link_style = nil\n log.warn_once(\n \"The config option 'completion.preferred_link_style' is deprecated, please use the top-level \"\n .. \"'preferred_link_style' instead.\"\n )\n end\n\n if opts.completion ~= nil and opts.completion.new_notes_location ~= nil then\n opts.new_notes_location = opts.completion.new_notes_location\n opts.completion.new_notes_location = nil\n log.warn_once(\n \"The config option 'completion.new_notes_location' is deprecated, please use the top-level \"\n .. \"'new_notes_location' instead.\"\n )\n end\n\n if opts.detect_cwd ~= nil then\n opts.detect_cwd = nil\n log.warn_once(\n \"The 'detect_cwd' field is deprecated and no longer has any affect.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/366 for more details.\"\n )\n end\n\n if opts.open_app_foreground ~= nil then\n opts.open_app_foreground = nil\n log.warn_once [[The config option 'open_app_foreground' is deprecated, please use the `func` field in `open` module:\n\n```lua\n{\n open = {\n func = function(uri)\n vim.ui.open(uri, { cmd = { \"open\", \"-a\", \"/Applications/Obsidian.app\" } })\n end\n }\n}\n```]]\n end\n\n if opts.use_advanced_uri ~= nil then\n opts.use_advanced_uri = nil\n log.warn_once [[The config option 'use_advanced_uri' is deprecated, please use in `open` module instead]]\n end\n\n if opts.overwrite_mappings ~= nil then\n log.warn_once \"The 'overwrite_mappings' config option is deprecated and no longer has any affect.\"\n opts.overwrite_mappings = nil\n end\n\n if opts.mappings ~= nil then\n log.warn_once [[The 'mappings' config option is deprecated and no longer has any affect.\nSee: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Keymaps]]\n opts.overwrite_mappings = nil\n end\n\n if opts.tags ~= nil then\n log.warn_once \"The 'tags' config option is deprecated and no longer has any affect.\"\n opts.tags = nil\n end\n\n if opts.templates and opts.templates.subdir then\n opts.templates.folder = opts.templates.subdir\n opts.templates.subdir = nil\n end\n\n if opts.image_name_func then\n if opts.attachments == nil then\n opts.attachments = {}\n end\n opts.attachments.img_name_func = opts.image_name_func\n opts.image_name_func = nil\n end\n\n if opts.statusline and opts.statusline.enabled then\n deprecate(\"statusline.{enabled,format} and vim.g.obsidian\", \"footer.{enabled,format}\", \"4.0\")\n end\n\n --------------------------\n -- Merge with defaults. --\n --------------------------\n\n ---@type obsidian.config.ClientOpts\n opts = tbl_override(defaults, opts)\n\n opts.backlinks = tbl_override(defaults.backlinks, opts.backlinks)\n opts.completion = tbl_override(defaults.completion, opts.completion)\n opts.picker = tbl_override(defaults.picker, opts.picker)\n opts.daily_notes = tbl_override(defaults.daily_notes, opts.daily_notes)\n opts.templates = tbl_override(defaults.templates, opts.templates)\n opts.ui = tbl_override(defaults.ui, opts.ui)\n opts.attachments = tbl_override(defaults.attachments, opts.attachments)\n opts.statusline = tbl_override(defaults.statusline, opts.statusline)\n opts.footer = tbl_override(defaults.footer, opts.footer)\n opts.open = tbl_override(defaults.open, opts.open)\n opts.checkbox = tbl_override(defaults.checkbox, opts.checkbox)\n opts.comment = tbl_override(defaults.comment, opts.comment)\n\n ---------------\n -- Validate. --\n ---------------\n\n if opts.legacy_commands then\n deprecate(\n \"legacy_commands\",\n [[move from commands like `ObsidianBacklinks` to `Obsidian backlinks`\nand set `opts.legacy_commands` to false to get rid of this warning.\nsee https://github.com/obsidian-nvim/obsidian.nvim/wiki/Commands for details.\n ]],\n \"4.0\"\n )\n end\n\n if opts.sort_by ~= nil and not vim.tbl_contains(vim.tbl_values(config.SortBy), opts.sort_by) then\n error(\"Invalid 'sort_by' option '\" .. opts.sort_by .. \"' in obsidian.nvim config.\")\n end\n\n if not util.islist(opts.workspaces) then\n error \"Invalid obsidian.nvim config, the 'config.workspaces' should be an array/list.\"\n elseif vim.tbl_isempty(opts.workspaces) then\n error \"At least one workspace is required!\\nPlease specify a workspace \"\n end\n\n for i, workspace in ipairs(opts.workspaces) do\n local path = type(workspace.path) == \"function\" and workspace.path() or workspace.path\n ---@cast path -function\n opts.workspaces[i].path = vim.fn.resolve(vim.fs.normalize(path))\n end\n\n -- Convert dir to workspace format.\n if opts.dir ~= nil then\n table.insert(opts.workspaces, 1, { path = opts.dir })\n end\n\n return opts\nend\n\nreturn config\n"], ["/obsidian.nvim/lua/obsidian/commands/tags.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param tags string[]\nlocal function gather_tag_picker_list(client, picker, tags)\n client:find_tags_async(tags, function(tag_locations)\n -- Format results into picker entries, filtering out results that aren't exact matches or sub-tags.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, tag_loc in ipairs(tag_locations) do\n for _, tag in ipairs(tags) do\n if tag_loc.tag:lower() == tag:lower() or vim.startswith(tag_loc.tag:lower(), tag:lower() .. \"/\") then\n local display = string.format(\"%s [%s] %s\", tag_loc.note:display_name(), tag_loc.line, tag_loc.text)\n entries[#entries + 1] = {\n value = { path = tag_loc.path, line = tag_loc.line, col = tag_loc.tag_start },\n display = display,\n ordinal = display,\n filename = tostring(tag_loc.path),\n lnum = tag_loc.line,\n col = tag_loc.tag_start,\n }\n break\n end\n end\n end\n\n if vim.tbl_isempty(entries) then\n if #tags == 1 then\n log.warn \"Tag not found\"\n else\n log.warn \"Tags not found\"\n end\n return\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = \"#\" .. table.concat(tags, \", #\"),\n callback = function(value)\n api.open_buffer(value.path, { line = value.line, col = value.col })\n end,\n })\n end)\n end, { search = { sort = true } })\nend\n\n---@param client obsidian.Client\n---@param data CommandArgs\nreturn function(client, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local tags = data.fargs or {}\n\n if vim.tbl_isempty(tags) then\n local tag = api.cursor_tag()\n if tag then\n tags = { tag }\n end\n end\n\n if not vim.tbl_isempty(tags) then\n return gather_tag_picker_list(client, picker, util.tbl_unique(tags))\n else\n client:list_tags_async(nil, function(all_tags)\n vim.schedule(function()\n -- Open picker with tags.\n picker:pick_tag(all_tags, {\n callback = function(...)\n gather_tag_picker_list(client, picker, { ... })\n end,\n allow_multiple = true,\n })\n end)\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/pickers/picker.lua", "local abc = require \"obsidian.abc\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal strings = require \"plenary.strings\"\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---@class obsidian.Picker : obsidian.ABC\n---\n---@field calling_bufnr integer\nlocal Picker = abc.new_class()\n\nPicker.new = function()\n local self = Picker.init()\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n return self\nend\n\n-------------------------------------------------------------------\n--- Abstract methods that need to be implemented by subclasses. ---\n-------------------------------------------------------------------\n\n---@class obsidian.PickerMappingOpts\n---\n---@field desc string\n---@field callback fun(...)\n---@field fallback_to_query boolean|?\n---@field keep_open boolean|?\n---@field allow_multiple boolean|?\n\n---@alias obsidian.PickerMappingTable table\n\n---@class obsidian.PickerFindOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Find files in a directory.\n---\n---@param opts obsidian.PickerFindOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `callback`: Callback to run with the selected entry.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.find_files = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerGrepOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field query string|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable\n---@field selection_mappings obsidian.PickerMappingTable\n\n--- Grep for a string.\n---\n---@param opts obsidian.PickerGrepOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.grep = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerEntry\n---\n---@field value any\n---@field ordinal string|?\n---@field display string|?\n---@field filename string|?\n---@field valid boolean|?\n---@field lnum integer|?\n---@field col integer|?\n---@field icon string|?\n---@field icon_hl string|?\n\n---@class obsidian.PickerPickOpts\n---\n---@field prompt_title string|?\n---@field callback fun(value: any, ...: any)|?\n---@field allow_multiple boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Pick from a list of items.\n---\n---@param values string[]|obsidian.PickerEntry[] Items to pick from.\n---@param opts obsidian.PickerPickOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected item(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.pick = function(self, values, opts)\n error \"not implemented\"\nend\n\n------------------------------------------------------------------\n--- Concrete methods with a default implementation subclasses. ---\n------------------------------------------------------------------\n\n--- Find notes by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.find_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Notes\",\n dir = Obsidian.dir,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Find templates by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string) }|? Options.\n---\n--- Options:\n--- `callback`: Callback to run with the selected template path.\nPicker.find_templates = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local templates_dir = api.templates_dir()\n\n if templates_dir == nil then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Templates\",\n callback = opts.callback,\n dir = templates_dir,\n no_default_mappings = true,\n }\nend\n\n--- Grep search in notes.\n---\n---@param opts { prompt_title: string|?, query: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.grep_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n self:grep {\n prompt_title = opts.prompt_title or \"Grep notes\",\n dir = Obsidian.dir,\n query = opts.query,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Open picker with a list of notes.\n---\n---@param notes obsidian.Note[]\n---@param opts { prompt_title: string|?, callback: fun(note: obsidian.Note, ...: obsidian.Note), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_note = function(self, notes, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n -- Launch picker with results.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, note in ipairs(notes) do\n assert(note.path)\n local rel_path = assert(note.path:vault_relative_path { strict = true })\n local display_name = note:display_name()\n entries[#entries + 1] = {\n value = note,\n display = display_name,\n ordinal = rel_path .. \" \" .. display_name,\n filename = tostring(note.path),\n }\n end\n\n self:pick(entries, {\n prompt_title = opts.prompt_title or \"Notes\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--- Open picker with a list of tags.\n---\n---@param tags string[]\n---@param opts { prompt_title: string|?, callback: fun(tag: string, ...: string), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected tag(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_tag = function(self, tags, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local selection_mappings\n if not opts.no_default_mappings then\n selection_mappings = self:_tag_selection_mappings()\n end\n\n self:pick(tags, {\n prompt_title = opts.prompt_title or \"Tags\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--------------------------------\n--- Concrete helper methods. ---\n--------------------------------\n\n---@param key string|?\n---@return boolean\nlocal function key_is_set(key)\n if key ~= nil and string.len(key) > 0 then\n return true\n else\n return false\n end\nend\n\n--- Get query mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_query_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.new) then\n mappings[Obsidian.opts.picker.note_mappings.new] = {\n desc = \"new\",\n callback = function(query)\n ---@diagnostic disable-next-line: missing-fields\n require \"obsidian.commands.new\"(require(\"obsidian\").get_client(), { args = query })\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.insert_link) then\n mappings[Obsidian.opts.picker.note_mappings.insert_link] = {\n desc = \"insert link\",\n callback = function(note_or_path)\n ---@type obsidian.Note\n local note\n if Note.is_note_obj(note_or_path) then\n note = note_or_path\n else\n note = Note.from_file(note_or_path)\n end\n local link = api.format_link(note, {})\n vim.api.nvim_put({ link }, \"\", false, true)\n require(\"obsidian.ui\").update(0)\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `pick_tag()`.\n---@return obsidian.PickerMappingTable\nPicker._tag_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.tag_mappings then\n if key_is_set(Obsidian.opts.picker.tag_mappings.tag_note) then\n mappings[Obsidian.opts.picker.tag_mappings.tag_note] = {\n desc = \"tag note\",\n callback = function(...)\n local tags = { ... }\n\n local note = api.current_note(self.calling_bufnr)\n if not note then\n log.warn(\"'%s' is not a note in your workspace\", vim.api.nvim_buf_get_name(self.calling_bufnr))\n return\n end\n\n -- Add the tag and save the new frontmatter to the buffer.\n local tags_added = {}\n local tags_not_added = {}\n for _, tag in ipairs(tags) do\n if note:add_tag(tag) then\n table.insert(tags_added, tag)\n else\n table.insert(tags_not_added, tag)\n end\n end\n\n if #tags_added > 0 then\n if note:update_frontmatter(self.calling_bufnr) then\n log.info(\"Added tags %s to frontmatter\", tags_added)\n else\n log.warn \"Frontmatter unchanged\"\n end\n end\n\n if #tags_not_added > 0 then\n log.warn(\"Note already has tags %s\", tags_not_added)\n end\n end,\n fallback_to_query = true,\n keep_open = true,\n allow_multiple = true,\n }\n end\n\n if key_is_set(Obsidian.opts.picker.tag_mappings.insert_tag) then\n mappings[Obsidian.opts.picker.tag_mappings.insert_tag] = {\n desc = \"insert tag\",\n callback = function(tag)\n vim.api.nvim_put({ \"#\" .. tag }, \"\", false, true)\n end,\n fallback_to_query = true,\n }\n end\n end\n\n return mappings\nend\n\n---@param opts { prompt_title: string, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|? }|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nPicker._build_prompt = function(self, opts)\n opts = opts or {}\n\n ---@type string\n local prompt = opts.prompt_title or \"Find\"\n if string.len(prompt) > 50 then\n prompt = string.sub(prompt, 1, 50) .. \"…\"\n end\n\n prompt = prompt .. \" | confirm\"\n\n if opts.query_mappings then\n local keys = vim.tbl_keys(opts.query_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.query_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n if opts.selection_mappings then\n local keys = vim.tbl_keys(opts.selection_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.selection_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n return prompt\nend\n\n---@param entry obsidian.PickerEntry\n---\n---@return string, { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n---@diagnostic disable-next-line: unused-local\nPicker._make_display = function(self, entry)\n ---@type string\n local display = \"\"\n ---@type { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n local highlights = {}\n\n if entry.filename ~= nil then\n local icon, icon_hl\n if entry.icon then\n icon = entry.icon\n icon_hl = entry.icon_hl\n else\n icon, icon_hl = api.get_icon(entry.filename)\n end\n\n if icon ~= nil then\n display = display .. icon .. \" \"\n if icon_hl ~= nil then\n highlights[#highlights + 1] = { { 0, strings.strdisplaywidth(icon) }, icon_hl }\n end\n end\n\n display = display .. Path.new(entry.filename):vault_relative_path { strict = true }\n\n if entry.lnum ~= nil then\n display = display .. \":\" .. entry.lnum\n\n if entry.col ~= nil then\n display = display .. \":\" .. entry.col\n end\n end\n\n if entry.display ~= nil then\n display = display .. \":\" .. entry.display\n end\n elseif entry.display ~= nil then\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. entry.display\n else\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. tostring(entry.value)\n end\n\n return assert(display), highlights\nend\n\n---@return string[]\nPicker._build_find_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = { sort_by = Obsidian.opts.sort_by, sort_reversed = Obsidian.opts.sort_reversed }\n return search.build_find_cmd(\".\", nil, search_opts)\nend\n\nPicker._build_grep_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = {\n sort_by = Obsidian.opts.sort_by,\n sort_reversed = Obsidian.opts.sort_reversed,\n smart_case = true,\n fixed_strings = true,\n }\n return search.build_grep_cmd(search_opts)\nend\n\nreturn Picker\n"], ["/obsidian.nvim/lua/obsidian/commands/today.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_days = 0\n local arg = string.gsub(data.args, \" \", \"\")\n if string.len(arg) > 0 then\n local offset = tonumber(arg)\n if offset == nil then\n log.err \"Invalid argument, expected an integer offset\"\n return\n else\n offset_days = offset\n end\n end\n local note = require(\"obsidian.daily\").daily(offset_days, {})\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/client.lua", "--- *obsidian-api*\n---\n--- The Obsidian.nvim Lua API.\n---\n--- ==============================================================================\n---\n--- Table of contents\n---\n---@toc\n\nlocal Path = require \"obsidian.path\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal Note = require \"obsidian.note\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal block_on = require(\"obsidian.async\").block_on\nlocal iter = vim.iter\n\n---@class obsidian.SearchOpts\n---\n---@field sort boolean|?\n---@field include_templates boolean|?\n---@field ignore_case boolean|?\n---@field default function?\n\n--- The Obsidian client is the main API for programmatically interacting with obsidian.nvim's features\n--- in Lua. To get the client instance, run:\n---\n--- `local client = require(\"obsidian\").get_client()`\n---\n---@toc_entry obsidian.Client\n---\n---@class obsidian.Client : obsidian.ABC\nlocal Client = {}\n\nlocal depreacted_lookup = {\n dir = \"dir\",\n buf_dir = \"buf_dir\",\n current_workspace = \"workspace\",\n opts = \"opts\",\n}\n\nClient.__index = function(_, k)\n if depreacted_lookup[k] then\n local msg = string.format(\n [[client.%s is depreacted, use Obsidian.%s instead.\nclient is going to be removed in the future as well.]],\n k,\n depreacted_lookup[k]\n )\n log.warn(msg)\n return Obsidian[depreacted_lookup[k]]\n elseif rawget(Client, k) then\n return rawget(Client, k)\n end\nend\n\n--- Create a new Obsidian client without additional setup.\n--- This is mostly used for testing. In practice you usually want to obtain the existing\n--- client through:\n---\n--- `require(\"obsidian\").get_client()`\n---\n---@return obsidian.Client\nClient.new = function()\n return setmetatable({}, Client)\nend\n\n--- Get the default search options.\n---\n---@return obsidian.SearchOpts\nClient.search_defaults = function()\n return {\n sort = false,\n include_templates = false,\n ignore_case = false,\n }\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---\n---@return obsidian.SearchOpts\n---\n---@private\nClient._search_opts_from_arg = function(self, opts)\n if opts == nil then\n opts = self:search_defaults()\n elseif type(opts) == \"boolean\" then\n local sort = opts\n opts = self:search_defaults()\n opts.sort = sort\n end\n return opts\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nClient._prepare_search_opts = function(self, opts, additional_opts)\n opts = self:_search_opts_from_arg(opts)\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n search.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = search.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---\n---@return function\n---\n---@private\nClient._search_iter_async = function(self, term, search_opts, find_opts)\n local tx, rx = channel.mpsc()\n local found = {}\n\n local function on_exit(_)\n tx.send(nil)\n end\n\n ---@param content_match MatchData\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n ---@param path_match string\n local function on_find_match(path_match)\n local path = Path.new(path_match):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n local cmds_done = 0 -- out of the two, one for 'search' and one for 'find'\n\n search.search_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n search.find_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(find_opts, { ignore_case = true }),\n on_find_match,\n on_exit\n )\n\n return function()\n while cmds_done < 2 do\n local value = rx.recv()\n if value == nil then\n cmds_done = cmds_done + 1\n else\n return value\n end\n end\n return nil\n end\nend\n\n---@class obsidian.TagLocation\n---\n---@field tag string The tag found.\n---@field note obsidian.Note The note instance where the tag was found.\n---@field path string|obsidian.Path The path to the note where the tag was found.\n---@field line integer The line number (1-indexed) where the tag was found.\n---@field text string The text (with whitespace stripped) of the line where the tag was found.\n---@field tag_start integer|? The index within 'text' where the tag starts.\n---@field tag_end integer|? The index within 'text' where the tag ends.\n\n--- Find all tags starting with the given search term(s).\n---\n---@param term string|string[] The search term.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|? }|?\n---\n---@return obsidian.TagLocation[]\nClient.find_tags = function(self, term, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_tags_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n--- An async version of 'find_tags()'.\n---\n---@param term string|string[] The search term.\n---@param callback fun(tags: obsidian.TagLocation[])\n---@param opts { search: obsidian.SearchOpts }|?\nClient.find_tags_async = function(self, term, callback, opts)\n opts = opts or {}\n\n ---@type string[]\n local terms\n if type(term) == \"string\" then\n terms = { term }\n else\n terms = term\n end\n\n for i, t in ipairs(terms) do\n if vim.startswith(t, \"#\") then\n terms[i] = string.sub(t, 2)\n end\n end\n\n terms = util.tbl_unique(terms)\n\n -- Maps paths to tag locations.\n ---@type table\n local path_to_tag_loc = {}\n -- Caches note objects.\n ---@type table\n local path_to_note = {}\n -- Caches code block locations.\n ---@type table\n local path_to_code_blocks = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n ---@param tag string\n ---@param path string|obsidian.Path\n ---@param note obsidian.Note\n ---@param lnum integer\n ---@param text string\n ---@param col_start integer|?\n ---@param col_end integer|?\n local add_match = function(tag, path, note, lnum, text, col_start, col_end)\n if vim.startswith(tag, \"#\") then\n tag = string.sub(tag, 2)\n end\n if not path_to_tag_loc[path] then\n path_to_tag_loc[path] = {}\n end\n path_to_tag_loc[path][#path_to_tag_loc[path] + 1] = {\n tag = tag,\n path = path,\n note = note,\n line = lnum,\n text = text,\n tag_start = col_start,\n tag_end = col_end,\n }\n end\n\n -- Wraps `Note.from_file_with_contents_async()` to return a table instead of a tuple and\n -- find the code blocks.\n ---@param path obsidian.Path\n ---@return { [1]: obsidian.Note, [2]: {[1]: integer, [2]: integer}[] }\n local load_note = function(path)\n local note, contents = Note.from_file_with_contents_async(path, { max_lines = Obsidian.opts.search_max_lines })\n return { note, search.find_code_blocks(contents) }\n end\n\n ---@param match_data MatchData\n local on_match = function(match_data)\n local path = Path.new(match_data.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local note = path_to_note[path]\n local code_blocks = path_to_code_blocks[path]\n if not note or not code_blocks then\n local ok, res = pcall(load_note, path)\n if ok then\n note, code_blocks = unpack(res)\n path_to_note[path] = note\n path_to_code_blocks[path] = code_blocks\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n local line_number = match_data.line_number + 1 -- match_data.line_number is 0-indexed\n\n -- check if the match was inside a code block.\n for block in iter(code_blocks) do\n if block[1] <= line_number and line_number <= block[2] then\n return\n end\n end\n\n local line = vim.trim(match_data.lines.text)\n local n_matches = 0\n\n -- check for tag in the wild of the form '#{tag}'\n for match in iter(search.find_tags(line)) do\n local m_start, m_end, _ = unpack(match)\n local tag = string.sub(line, m_start + 1, m_end)\n if string.match(tag, \"^\" .. search.Patterns.TagCharsRequired .. \"$\") then\n add_match(tag, path, note, match_data.line_number, line, m_start, m_end)\n end\n end\n\n -- check for tags in frontmatter\n if n_matches == 0 and note.tags ~= nil and (vim.startswith(line, \"tags:\") or string.match(line, \"%s*- \")) then\n for tag in iter(note.tags) do\n tag = tostring(tag)\n for _, t in ipairs(terms) do\n if string.len(t) == 0 or util.string_contains(tag:lower(), t:lower()) then\n add_match(tag, path, note, match_data.line_number, line)\n end\n end\n end\n end\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n local search_terms = {}\n for t in iter(terms) do\n if string.len(t) > 0 then\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsOptional .. t .. search.Patterns.TagCharsOptional\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n else\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsRequired\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \" .. search.Patterns.TagCharsRequired .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\" .. search.Patterns.TagCharsRequired\n end\n end\n\n search.search_async(\n Obsidian.dir,\n search_terms,\n self:_prepare_search_opts(opts.search, { ignore_case = true }),\n on_match,\n function(_)\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.TagLocation[]\n local tags_list = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results in path order.\n for _, path in ipairs(paths) do\n local tag_locs = path_to_tag_loc[path]\n if tag_locs ~= nil then\n table.sort(tag_locs, function(a, b)\n return a.line < b.line\n end)\n for _, tag_loc in ipairs(tag_locs) do\n tags_list[#tags_list + 1] = tag_loc\n end\n end\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return tags_list\n end, callback)\nend\n\n---@class obsidian.BacklinkMatches\n---\n---@field note obsidian.Note The note instance where the backlinks were found.\n---@field path string|obsidian.Path The path to the note where the backlinks were found.\n---@field matches obsidian.BacklinkMatch[] The backlinks within the note.\n\n---@class obsidian.BacklinkMatch\n---\n---@field line integer The line number (1-indexed) where the backlink was found.\n---@field text string The text of the line where the backlink was found.\n\n--- Find all backlinks to a note.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|?, anchor: string|?, block: string|? }|?\n---\n---@return obsidian.BacklinkMatches[]\nClient.find_backlinks = function(self, note, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_backlinks_async(note, cb, { search = opts.search, anchor = opts.anchor, block = opts.block })\n end, opts.timeout)\nend\n\n--- An async version of 'find_backlinks()'.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param callback fun(backlinks: obsidian.BacklinkMatches[])\n---@param opts { search: obsidian.SearchOpts, anchor: string|?, block: string|? }|?\nClient.find_backlinks_async = function(self, note, callback, opts)\n opts = opts or {}\n\n ---@type string|?\n local block = opts.block and util.standardize_block(opts.block) or nil\n local anchor = opts.anchor and util.standardize_anchor(opts.anchor) or nil\n ---@type obsidian.note.HeaderAnchor|?\n local anchor_obj\n if anchor then\n anchor_obj = note:resolve_anchor_link(anchor)\n end\n\n -- Maps paths (string) to note object and a list of matches.\n ---@type table\n local backlink_matches = {}\n ---@type table\n local path_to_note = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n -- Prepare search terms.\n local search_terms = {}\n local note_path = Path.new(note.path)\n for raw_ref in iter { tostring(note.id), note_path.name, note_path.stem, note.path:vault_relative_path() } do\n for ref in\n iter(util.tbl_unique {\n raw_ref,\n util.urlencode(tostring(raw_ref)),\n util.urlencode(tostring(raw_ref), { keep_path_sep = true }),\n })\n do\n if ref ~= nil then\n if anchor == nil and block == nil then\n -- Wiki links without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", ref)\n search_terms[#search_terms + 1] = string.format(\"[[%s|\", ref)\n -- Markdown link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s)\", ref)\n -- Markdown link without anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s)\", ref)\n -- Wiki links with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif anchor then\n -- Note: Obsidian allow a lot of different forms of anchor links, so we can't assume\n -- it's the standardized form here.\n -- Wiki links with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif block then\n -- Wiki links with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", ref, block)\n -- Markdown link with block.\n search_terms[#search_terms + 1] = string.format(\"(%s#%s\", ref, block)\n -- Markdown link with block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#%s\", ref, block)\n end\n end\n end\n end\n for alias in iter(note.aliases) do\n if anchor == nil and block == nil then\n -- Wiki link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", alias)\n -- Wiki link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif anchor then\n -- Wiki link with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif block then\n -- Wiki link with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", alias, block)\n end\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = opts.anchor ~= nil,\n collect_blocks = opts.block ~= nil,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n ---@param match MatchData\n local function on_match(match)\n local path = Path.new(match.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local n = path_to_note[path]\n if not n then\n local ok, res = pcall(Note.from_file_async, path, load_opts)\n if ok then\n n = res\n path_to_note[path] = n\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n if anchor then\n -- Check for a match with the anchor.\n -- NOTE: no need to do this with blocks, since blocks are standardized.\n local match_text = string.sub(match.lines.text, match.submatches[1].start)\n local link_location = util.parse_link(match_text)\n if not link_location then\n log.error(\"Failed to parse reference from '%s' ('%s')\", match_text, match)\n return\n end\n\n local anchor_link = select(2, util.strip_anchor_links(link_location))\n if not anchor_link then\n return\n end\n\n if anchor_link ~= anchor and anchor_obj ~= nil then\n local resolved_anchor = note:resolve_anchor_link(anchor_link)\n if resolved_anchor == nil or resolved_anchor.header ~= anchor_obj.header then\n return\n end\n end\n end\n\n ---@type obsidian.BacklinkMatch[]\n local line_matches = backlink_matches[path]\n if line_matches == nil then\n line_matches = {}\n backlink_matches[path] = line_matches\n end\n\n line_matches[#line_matches + 1] = {\n line = match.line_number,\n text = util.rstrip_whitespace(match.lines.text),\n }\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n -- Execute search.\n search.search_async(\n Obsidian.dir,\n util.tbl_unique(search_terms),\n self:_prepare_search_opts(opts.search, { fixed_strings = true, ignore_case = true }),\n on_match,\n function()\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.BacklinkMatches[]\n local results = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results.\n for i, path in ipairs(paths) do\n results[i] = { note = path_to_note[path], path = path, matches = backlink_matches[path] }\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return vim.tbl_filter(function(bl)\n return bl.matches ~= nil\n end, results)\n end, callback)\nend\n\n--- Gather a list of all tags in the vault. If 'term' is provided, only tags that partially match the search\n--- term will be included.\n---\n---@param term string|? An optional search term to match tags\n---@param timeout integer|? Timeout in milliseconds\n---\n---@return string[]\nClient.list_tags = function(self, term, timeout)\n local tags = {}\n for _, tag_loc in ipairs(self:find_tags(term and term or \"\", { timeout = timeout })) do\n tags[tag_loc.tag] = true\n end\n return vim.tbl_keys(tags)\nend\n\n--- An async version of 'list_tags()'.\n---\n---@param term string|?\n---@param callback fun(tags: string[])\nClient.list_tags_async = function(self, term, callback)\n self:find_tags_async(term and term or \"\", function(tag_locations)\n local tags = {}\n for _, tag_loc in ipairs(tag_locations) do\n local tag = tag_loc.tag:lower()\n if not tags[tag] then\n tags[tag] = true\n end\n end\n callback(vim.tbl_keys(tags))\n end)\nend\n\nreturn Client\n"], ["/obsidian.nvim/lua/obsidian/init.lua", "local log = require \"obsidian.log\"\n\nlocal module_lookups = {\n abc = \"obsidian.abc\",\n api = \"obsidian.api\",\n async = \"obsidian.async\",\n Client = \"obsidian.client\",\n commands = \"obsidian.commands\",\n completion = \"obsidian.completion\",\n config = \"obsidian.config\",\n log = \"obsidian.log\",\n img_paste = \"obsidian.img_paste\",\n Note = \"obsidian.note\",\n Path = \"obsidian.path\",\n pickers = \"obsidian.pickers\",\n search = \"obsidian.search\",\n templates = \"obsidian.templates\",\n ui = \"obsidian.ui\",\n util = \"obsidian.util\",\n VERSION = \"obsidian.version\",\n Workspace = \"obsidian.workspace\",\n yaml = \"obsidian.yaml\",\n}\n\nlocal obsidian = setmetatable({}, {\n __index = function(t, k)\n local require_path = module_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@type obsidian.Client|?\nobsidian._client = nil\n\n---Get the current obsidian client.\n---@return obsidian.Client\nobsidian.get_client = function()\n if obsidian._client == nil then\n error \"Obsidian client has not been set! Did you forget to call 'setup()'?\"\n else\n return obsidian._client\n end\nend\n\nobsidian.register_command = require(\"obsidian.commands\").register\n\n--- Setup a new Obsidian client. This should only be called once from an Nvim session.\n---\n---@param opts obsidian.config.ClientOpts | table\n---\n---@return obsidian.Client\nobsidian.setup = function(opts)\n opts = obsidian.config.normalize(opts)\n\n ---@class obsidian.state\n ---@field picker obsidian.Picker The picker instance to use.\n ---@field workspace obsidian.Workspace The current workspace.\n ---@field dir obsidian.Path The root of the vault for the current workspace.\n ---@field buf_dir obsidian.Path|? The parent directory of the current buffer.\n ---@field opts obsidian.config.ClientOpts current options\n ---@field _opts obsidian.config.ClientOpts default options\n _G.Obsidian = {} -- init a state table\n\n local client = obsidian.Client.new(opts)\n\n Obsidian._opts = opts\n\n obsidian.Workspace.set(assert(obsidian.Workspace.get_from_opts(opts)), {})\n\n log.set_level(Obsidian.opts.log_level)\n\n -- Install commands.\n -- These will be available across all buffers, not just note buffers in the vault.\n obsidian.commands.install(client)\n\n if opts.legacy_commands then\n obsidian.commands.install_legacy(client)\n end\n\n if opts.statusline.enabled then\n require(\"obsidian.statusline\").start(client)\n end\n\n if opts.footer.enabled then\n require(\"obsidian.footer\").start(client)\n end\n\n -- Register completion sources, providers\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").register_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").register_providers(opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_setup\", { clear = true })\n\n -- wrapper for creating autocmd events\n ---@param pattern string\n ---@param buf integer\n local function exec_autocmds(pattern, buf)\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = pattern,\n data = {\n note = require(\"obsidian.note\").from_buffer(buf),\n },\n })\n end\n\n -- Complete setup and update workspace (if needed) when entering a markdown buffer.\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Set the current directory of the buffer.\n local buf_dir = vim.fs.dirname(ev.match)\n if buf_dir then\n Obsidian.buf_dir = obsidian.Path.new(buf_dir)\n end\n\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n if opts.comment.enabled then\n vim.o.commentstring = \"%%%s%%\"\n end\n\n -- Switch to the workspace and complete the workspace setup.\n if not Obsidian.workspace.locked and workspace ~= Obsidian.workspace then\n log.debug(\"Switching to workspace '%s' @ '%s'\", workspace.name, workspace.path)\n obsidian.Workspace.set(workspace)\n require(\"obsidian.ui\").update(ev.buf)\n end\n\n -- Register keymap.\n vim.keymap.set(\n \"n\",\n \"\",\n obsidian.api.smart_action,\n { expr = true, buffer = true, desc = \"Obsidian Smart Action\" }\n )\n\n vim.keymap.set(\"n\", \"]o\", function()\n obsidian.api.nav_link \"next\"\n end, { buffer = true, desc = \"Obsidian Next Link\" })\n\n vim.keymap.set(\"n\", \"[o\", function()\n obsidian.api.nav_link \"prev\"\n end, { buffer = true, desc = \"Obsidian Previous Link\" })\n\n -- Inject completion sources, providers to their plugin configurations\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").inject_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").inject_sources(opts)\n end\n\n -- Run enter-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"enter_note\", Obsidian.opts.callbacks.enter_note, client, note)\n\n exec_autocmds(\"ObsidianNoteEnter\", ev.buf)\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufLeave\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(vim.fs.dirname(ev.match), Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Run leave-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"leave_note\", Obsidian.opts.callbacks.leave_note, client, note)\n\n exec_autocmds(\"ObsidianNoteLeave\", ev.buf)\n end,\n })\n\n -- Add/update frontmatter for notes before writing.\n vim.api.nvim_create_autocmd({ \"BufWritePre\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Initialize note.\n local bufnr = ev.buf\n local note = obsidian.Note.from_buffer(bufnr)\n\n -- Run pre-write-note callback.\n obsidian.util.fire_callback(\"pre_write_note\", Obsidian.opts.callbacks.pre_write_note, client, note)\n\n exec_autocmds(\"ObsidianNoteWritePre\", ev.buf)\n\n -- Update buffer with new frontmatter.\n if note:update_frontmatter(bufnr) then\n log.info \"Updated frontmatter\"\n end\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufWritePost\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n exec_autocmds(\"ObsidianNoteWritePost\", ev.buf)\n end,\n })\n\n -- Set global client.\n obsidian._client = client\n\n obsidian.util.fire_callback(\"post_setup\", Obsidian.opts.callbacks.post_setup, client)\n\n return client\nend\n\nreturn obsidian\n"], ["/obsidian.nvim/lua/obsidian/commands/check.lua", "local Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal iter = vim.iter\n\nreturn function()\n local start_time = vim.uv.hrtime()\n local count = 0\n local errors = {}\n local warnings = {}\n\n for path in api.dir(Obsidian.dir) do\n local relative_path = Path.new(path):vault_relative_path { strict = true }\n local ok, res = pcall(Note.from_file, path)\n\n if not ok then\n errors[#errors + 1] = string.format(\"Failed to parse note '%s': \", relative_path, res)\n elseif res.has_frontmatter == false then\n warnings[#warnings + 1] = string.format(\"'%s' missing frontmatter\", relative_path)\n end\n count = count + 1\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n local messages = { \"Checked \" .. tostring(count) .. \" notes in \" .. runtime .. \"ms\" }\n local log_level = vim.log.levels.INFO\n\n if #warnings > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#warnings) .. \" warning(s):\"\n log_level = vim.log.levels.WARN\n for warning in iter(warnings) do\n messages[#messages + 1] = \"  \" .. warning\n end\n end\n\n if #errors > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#errors) .. \" error(s):\"\n for err in iter(errors) do\n messages[#messages + 1] = \"  \" .. err\n end\n log_level = vim.log.levels.ERROR\n end\n\n log.log(table.concat(messages, \"\\n\"), log_level)\nend\n"], ["/obsidian.nvim/lua/obsidian/daily/init.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\n\n--- Get the path to a daily note.\n---\n---@param datetime integer|?\n---\n---@return obsidian.Path, string (Path, ID) The path and ID of the note.\nlocal daily_note_path = function(datetime)\n datetime = datetime and datetime or os.time()\n\n ---@type obsidian.Path\n local path = Path:new(Obsidian.dir)\n\n local options = Obsidian.opts\n\n if options.daily_notes.folder ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.daily_notes.folder\n elseif options.notes_subdir ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.notes_subdir\n end\n\n local id\n if options.daily_notes.date_format ~= nil then\n id = tostring(os.date(options.daily_notes.date_format, datetime))\n else\n id = tostring(os.date(\"%Y-%m-%d\", datetime))\n end\n\n path = path / (id .. \".md\")\n\n -- ID may contain additional path components, so make sure we use the stem.\n id = path.stem\n\n return path, id\nend\n\n--- Open (or create) the daily note.\n---\n---@param datetime integer\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\n---\nlocal _daily = function(datetime, opts)\n opts = opts or {}\n\n local path, id = daily_note_path(datetime)\n\n local options = Obsidian.opts\n\n ---@type string|?\n local alias\n if options.daily_notes.alias_format ~= nil then\n alias = tostring(os.date(options.daily_notes.alias_format, datetime))\n end\n\n ---@type obsidian.Note\n local note\n if path:exists() then\n note = Note.from_file(path, opts.load)\n else\n note = Note.create {\n id = id,\n aliases = {},\n tags = options.daily_notes.default_tags or {},\n dir = path:parent(),\n }\n\n if alias then\n note:add_alias(alias)\n note.title = alias\n end\n\n if not opts.no_write then\n note:write { template = options.daily_notes.template }\n end\n end\n\n return note\nend\n\n--- Open (or create) the daily note for today.\n---\n---@return obsidian.Note\nlocal today = function()\n return _daily(os.time(), {})\nend\n\n--- Open (or create) the daily note from the last day.\n---\n---@return obsidian.Note\nlocal yesterday = function()\n local now = os.time()\n local yesterday\n\n if Obsidian.opts.daily_notes.workdays_only then\n yesterday = util.working_day_before(now)\n else\n yesterday = util.previous_day(now)\n end\n\n return _daily(yesterday, {})\nend\n\n--- Open (or create) the daily note for the next day.\n---\n---@return obsidian.Note\nlocal tomorrow = function()\n local now = os.time()\n local tomorrow\n\n if Obsidian.opts.daily_notes.workdays_only then\n tomorrow = util.working_day_after(now)\n else\n tomorrow = util.next_day(now)\n end\n\n return _daily(tomorrow, {})\nend\n\n--- Open (or create) the daily note for today + `offset_days`.\n---\n---@param offset_days integer|?\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\nlocal daily = function(offset_days, opts)\n return _daily(os.time() + (offset_days * 3600 * 24), opts)\nend\n\nreturn {\n daily_note_path = daily_note_path,\n daily = daily,\n tomorrow = tomorrow,\n yesterday = yesterday,\n today = today,\n}\n"], ["/obsidian.nvim/lua/obsidian/pickers/_snacks.lua", "local snacks_picker = require \"snacks.picker\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\nlocal function debug_once(msg, ...)\n -- vim.notify(msg .. vim.inspect(...))\nend\n\n---@param mapping table\n---@return table\nlocal function notes_mappings(mapping)\n if type(mapping) == \"table\" then\n local opts = { win = { input = { keys = {} } }, actions = {} }\n for k, v in pairs(mapping) do\n local name = string.gsub(v.desc, \" \", \"_\")\n opts.win.input.keys = {\n [k] = { name, mode = { \"n\", \"i\" }, desc = v.desc },\n }\n opts.actions[name] = function(picker, item)\n debug_once(\"mappings :\", item)\n picker:close()\n vim.schedule(function()\n v.callback(item.value or item._path)\n end)\n end\n end\n return opts\n end\n return {}\nend\n\n---@class obsidian.pickers.SnacksPicker : obsidian.Picker\nlocal SnacksPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"SnacksPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nSnacksPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"files\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"find files callback: \", item)\n opts.callback(item._path)\n else\n debug_once(\"find files jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nSnacksPicker.grep = function(self, opts)\n opts = opts or {}\n\n debug_once(\"grep opts : \", opts)\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"grep\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"grep callback: \", item)\n opts.callback(item._path or item.filename)\n else\n debug_once(\"grep jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nSnacksPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n debug_once(\"pick opts: \", opts)\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n table.insert(entries, {\n text = value,\n value = value,\n })\n elseif value.valid ~= false then\n local name = self:_make_display(value)\n table.insert(entries, {\n text = name,\n buf = self.calling_bufnr,\n filename = value.filename,\n value = value.value,\n pos = { value.lnum, value.col or 0 },\n })\n end\n end\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n tilte = opts.prompt_title,\n items = entries,\n layout = {\n preview = false,\n },\n format = \"text\",\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"pick callback: \", item)\n opts.callback(item.value)\n else\n debug_once(\"pick jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n\n snacks_picker.pick(pick_opts)\nend\n\nreturn SnacksPicker\n"], ["/obsidian.nvim/lua/obsidian/commands/quick_switch.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_notes()\n else\n search.resolve_note_async(data.args, function(note)\n note:open()\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/dailies.lua", "local log = require \"obsidian.log\"\nlocal daily = require \"obsidian.daily\"\n\n---@param arg string\n---@return number\nlocal function parse_offset(arg)\n if vim.startswith(arg, \"+\") then\n return assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%'\", arg))\n elseif vim.startswith(arg, \"-\") then\n return -assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%s'\", arg))\n else\n return assert(tonumber(arg), string.format(\"invalid offset '%s'\", arg))\n end\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_start = -5\n local offset_end = 0\n\n if data.fargs and #data.fargs > 0 then\n if #data.fargs == 1 then\n local offset = parse_offset(data.fargs[1])\n if offset >= 0 then\n offset_end = offset\n else\n offset_start = offset\n end\n elseif #data.fargs == 2 then\n local offsets = vim.tbl_map(parse_offset, data.fargs)\n table.sort(offsets)\n offset_start = offsets[1]\n offset_end = offsets[2]\n else\n error \":Obsidian dailies expected at most 2 arguments\"\n end\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local dailies = {}\n for offset = offset_end, offset_start, -1 do\n local datetime = os.time() + (offset * 3600 * 24)\n local daily_note_path = daily.daily_note_path(datetime)\n local daily_note_alias = tostring(os.date(Obsidian.opts.daily_notes.alias_format or \"%A %B %-d, %Y\", datetime))\n if offset == 0 then\n daily_note_alias = daily_note_alias .. \" @today\"\n elseif offset == -1 then\n daily_note_alias = daily_note_alias .. \" @yesterday\"\n elseif offset == 1 then\n daily_note_alias = daily_note_alias .. \" @tomorrow\"\n end\n if not daily_note_path:is_file() then\n daily_note_alias = daily_note_alias .. \" ➡️ create\"\n end\n dailies[#dailies + 1] = {\n value = offset,\n display = daily_note_alias,\n ordinal = daily_note_alias,\n filename = tostring(daily_note_path),\n }\n end\n\n picker:pick(dailies, {\n prompt_title = \"Dailies\",\n callback = function(offset)\n local note = daily.daily(offset, {})\n note:open()\n end,\n })\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/backlinks.lua", "local util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal RefTypes = require(\"obsidian.search\").RefTypes\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param note obsidian.Note\n---@param opts { anchor: string|?, block: string|? }|?\nlocal function collect_backlinks(client, picker, note, opts)\n opts = opts or {}\n\n client:find_backlinks_async(note, function(backlinks)\n if vim.tbl_isempty(backlinks) then\n if opts.anchor then\n log.info(\"No backlinks found for anchor '%s' in note '%s'\", opts.anchor, note.id)\n elseif opts.block then\n log.info(\"No backlinks found for block '%s' in note '%s'\", opts.block, note.id)\n else\n log.info(\"No backlinks found for note '%s'\", note.id)\n end\n return\n end\n\n local entries = {}\n for _, matches in ipairs(backlinks) do\n for _, match in ipairs(matches.matches) do\n entries[#entries + 1] = {\n value = { path = matches.path, line = match.line },\n filename = tostring(matches.path),\n lnum = match.line,\n }\n end\n end\n\n ---@type string\n local prompt_title\n if opts.anchor then\n prompt_title = string.format(\"Backlinks to '%s%s'\", note.id, opts.anchor)\n elseif opts.block then\n prompt_title = string.format(\"Backlinks to '%s#%s'\", note.id, util.standardize_block(opts.block))\n else\n prompt_title = string.format(\"Backlinks to '%s'\", note.id)\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = prompt_title,\n callback = function(value)\n api.open_buffer(value.path, { line = value.line })\n end,\n })\n end)\n end, { search = { sort = true }, anchor = opts.anchor, block = opts.block })\nend\n\n---@param client obsidian.Client\nreturn function(client)\n local picker = assert(Obsidian.picker)\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local cur_link, link_type = api.cursor_link()\n\n if\n cur_link ~= nil\n and link_type ~= RefTypes.NakedUrl\n and link_type ~= RefTypes.FileUrl\n and link_type ~= RefTypes.BlockID\n then\n local location = util.parse_link(cur_link, { include_block_ids = true })\n assert(location, \"cursor on a link but failed to parse, please report to repo\")\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n location = vim.api.nvim_buf_get_name(0)\n end\n\n local opts = { anchor = anchor_link, block = block_link }\n\n search.resolve_note_async(location, function(...)\n ---@type obsidian.Note[]\n local notes = { ... }\n\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", location)\n return\n elseif #notes == 1 then\n return collect_backlinks(client, picker, notes[1], opts)\n else\n return vim.schedule(function()\n picker:pick_note(notes, {\n prompt_title = \"Select note\",\n callback = function(note)\n collect_backlinks(client, picker, note, opts)\n end,\n })\n end)\n end\n end)\n else\n ---@type { anchor: string|?, block: string|? }\n local opts = {}\n ---@type obsidian.note.LoadOpts\n local load_opts = {}\n\n if cur_link and link_type == RefTypes.BlockID then\n opts.block = util.parse_link(cur_link, { include_block_ids = true })\n else\n load_opts.collect_anchor_links = true\n end\n\n local note = api.current_note(0, load_opts)\n\n -- Check if cursor is on a header, if so and header parsing is enabled, use that anchor.\n if Obsidian.opts.backlinks.parse_headers then\n local header_match = util.parse_header(vim.api.nvim_get_current_line())\n if header_match then\n opts.anchor = header_match.anchor\n end\n end\n\n if note == nil then\n log.err \"Current buffer does not appear to be a note inside the vault\"\n else\n collect_backlinks(client, picker, note, opts)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/img_paste.lua", "local Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal run_job = require(\"obsidian.async\").run_job\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\n\nlocal M = {}\n\n-- Image pasting adapted from https://github.com/ekickx/clipboard-image.nvim\n\n---@return string\nlocal function get_clip_check_command()\n local check_cmd\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n check_cmd = \"xclip -selection clipboard -o -t TARGETS\"\n elseif display_server == \"wayland\" then\n check_cmd = \"wl-paste --list-types\"\n end\n elseif this_os == api.OSType.Darwin then\n check_cmd = \"pngpaste -b 2>&1\"\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n check_cmd = 'powershell.exe \"Get-Clipboard -Format Image\"'\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return check_cmd\nend\n\n--- Check if clipboard contains image data.\n---\n---@return boolean\nfunction M.clipboard_is_img()\n local check_cmd = get_clip_check_command()\n local result_string = vim.fn.system(check_cmd)\n local content = vim.split(result_string, \"\\n\")\n\n local is_img = false\n -- See: [Data URI scheme](https://en.wikipedia.org/wiki/Data_URI_scheme)\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n if vim.tbl_contains(content, \"image/png\") then\n is_img = true\n elseif vim.tbl_contains(content, \"text/uri-list\") then\n local success =\n os.execute \"wl-paste --type text/uri-list | sed 's|file://||' | head -n1 | tr -d '[:space:]' | xargs -I{} sh -c 'wl-copy < \\\"$1\\\"' _ {}\"\n is_img = success == 0\n end\n elseif this_os == api.OSType.Darwin then\n is_img = string.sub(content[1], 1, 9) == \"iVBORw0KG\" -- Magic png number in base64\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n is_img = content ~= nil\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return is_img\nend\n\n--- TODO: refactor with run_job?\n\n--- Save image from clipboard to `path`.\n---@param path string\n---\n---@return boolean|integer|? result\nlocal function save_clipboard_image(path)\n local this_os = api.get_os()\n\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local cmd\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n cmd = string.format(\"xclip -selection clipboard -t image/png -o > '%s'\", path)\n elseif display_server == \"wayland\" then\n cmd = string.format(\"wl-paste --no-newline --type image/png > %s\", vim.fn.shellescape(path))\n return run_job { \"bash\", \"-c\", cmd }\n end\n\n local result = os.execute(cmd)\n if type(result) == \"number\" and result > 0 then\n return false\n else\n return result\n end\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n local cmd = 'powershell.exe -c \"'\n .. string.format(\"(get-clipboard -format image).save('%s', 'png')\", string.gsub(path, \"/\", \"\\\\\"))\n .. '\"'\n return os.execute(cmd)\n elseif this_os == api.OSType.Darwin then\n return run_job { \"pngpaste\", path }\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\nend\n\n--- @param path string image_path The absolute path to the image file.\nM.paste = function(path)\n if util.contains_invalid_characters(path) then\n log.warn \"Links will not work with file names containing any of these characters in Obsidian: # ^ [ ] |\"\n end\n\n ---@diagnostic disable-next-line: cast-local-type\n path = Path.new(path)\n\n -- Make sure fname ends with \".png\"\n if not path.suffix then\n ---@diagnostic disable-next-line: cast-local-type\n path = path:with_suffix \".png\"\n elseif path.suffix ~= \".png\" then\n return log.err(\"invalid suffix for image name '%s', must be '.png'\", path.suffix)\n end\n\n if Obsidian.opts.attachments.confirm_img_paste then\n -- Get confirmation from user.\n if not api.confirm(\"Saving image to '\" .. tostring(path) .. \"'. Do you want to continue?\") then\n return log.warn \"Paste aborted\"\n end\n end\n\n -- Ensure parent directory exists.\n assert(path:parent()):mkdir { exist_ok = true, parents = true }\n\n -- Paste image.\n local result = save_clipboard_image(tostring(path))\n if result == false then\n log.err \"Failed to save image\"\n return\n end\n\n local img_text = Obsidian.opts.attachments.img_text_func(path)\n vim.api.nvim_put({ img_text }, \"c\", true, false)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/template.lua", "local templates = require \"obsidian.templates\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local templates_dir = api.templates_dir()\n if not templates_dir then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n -- We need to get this upfront before the picker hijacks the current window.\n local insert_location = api.get_active_window_cursor_location()\n\n local function insert_template(name)\n templates.insert_template {\n type = \"insert_template\",\n template_name = name,\n template_opts = Obsidian.opts.templates,\n templates_dir = templates_dir,\n location = insert_location,\n }\n end\n\n if string.len(data.args) > 0 then\n local template_name = vim.trim(data.args)\n insert_template(template_name)\n return\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_templates {\n callback = function(path)\n insert_template(path)\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/workspace.lua", "local log = require \"obsidian.log\"\nlocal Workspace = require \"obsidian.workspace\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.info(\"Current workspace: '%s' @ '%s'\", Obsidian.workspace.name, Obsidian.workspace.path)\n return\n end\n\n local options = {}\n for i, spec in ipairs(Obsidian.opts.workspaces) do\n local workspace = Workspace.new_from_spec(spec)\n if workspace == Obsidian.workspace then\n options[#options + 1] = string.format(\"*[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n else\n options[#options + 1] = string.format(\"[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n end\n end\n\n picker:pick(options, {\n prompt_title = \"Workspaces\",\n callback = function(workspace_str)\n local idx = tonumber(string.match(workspace_str, \"%*?%[(%d+)]\"))\n Workspace.switch(Obsidian.opts.workspaces[idx].name, { lock = true })\n end,\n })\n else\n Workspace.switch(data.args, { lock = true })\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/async.lua", "local abc = require \"obsidian.abc\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal uv = vim.uv\n\nlocal M = {}\n\n---An abstract class that mimics Python's `concurrent.futures.Executor` class.\n---@class obsidian.Executor : obsidian.ABC\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal Executor = abc.new_class()\n\n---@return obsidian.Executor\nExecutor.new = function()\n local self = Executor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback for the executor to run.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local,unused-vararg\nExecutor.submit = function(self, fn, callback, ...)\n error \"not implemented\"\nend\n\n---Map a function over a generator or array of task args, or the keys and values in a regular table.\n---The callback is called with an array of the results once all tasks have finished.\n---The order of the results passed to the callback will be the same as the order of the corresponding task args.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param task_args table[]|table|function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nExecutor.map = function(self, fn, task_args, callback)\n local results = {}\n local num_tasks = 0\n local tasks_completed = 0\n local all_submitted = false\n local tx, rx = channel.oneshot()\n\n local function collect_results()\n rx()\n return results\n end\n\n local function get_task_done_fn(i)\n return function(...)\n tasks_completed = tasks_completed + 1\n results[i] = { ... }\n if all_submitted and tasks_completed == num_tasks then\n tx()\n end\n end\n end\n\n if type(task_args) == \"table\" and util.islist(task_args) then\n num_tasks = #task_args\n for i, args in ipairs(task_args) do\n if i == #task_args then\n all_submitted = true\n end\n if type(args) ~= \"table\" then\n args = { args }\n end\n self:submit(fn, get_task_done_fn(i), unpack(args))\n end\n elseif type(task_args) == \"table\" then\n num_tasks = vim.tbl_count(task_args)\n local i = 0\n for k, v in pairs(task_args) do\n i = i + 1\n if i == #task_args then\n all_submitted = true\n end\n self:submit(fn, get_task_done_fn(i), k, v)\n end\n elseif type(task_args) == \"function\" then\n local i = 0\n local args = { task_args() }\n local next_args = { task_args() }\n while args[1] ~= nil do\n if next_args[1] == nil then\n all_submitted = true\n end\n i = i + 1\n num_tasks = num_tasks + 1\n self:submit(fn, get_task_done_fn(i), unpack(args))\n args = next_args\n next_args = { task_args() }\n end\n else\n error(string.format(\"unexpected type '%s' for 'task_args'\", type(task_args)))\n end\n\n if num_tasks == 0 then\n if callback ~= nil then\n callback {}\n end\n else\n async.run(collect_results, callback and callback or function(_) end)\n end\nend\n\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param pause_fn function(integer)\nExecutor._join = function(self, timeout, pause_fn)\n local start_time = uv.hrtime() / 1000000 -- ns -> ms\n local pause_for = 100\n if timeout ~= nil then\n pause_for = math.min(timeout / 2, pause_for)\n end\n while self.tasks_pending > 0 or self.tasks_running > 0 do\n pause_fn(pause_for)\n if timeout ~= nil and (uv.hrtime() / 1000000) - start_time > timeout then\n error \"Timeout error from Executor.join()\"\n end\n end\nend\n\n---Block Neovim until all currently running tasks have completed, waiting at most `timeout` milliseconds\n---before raising a timeout error.\n---\n---This is useful in testing, but in general you want to avoid blocking Neovim.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join = function(self, timeout)\n self:_join(timeout, vim.wait)\nend\n\n---An async version of `.join()`.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join_async = function(self, timeout)\n self:_join(timeout, async.util.sleep)\nend\n\n---Run the callback when the executor finishes all tasks.\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param callback function\nExecutor.join_and_then = function(self, timeout, callback)\n async.run(function()\n self:join_async(timeout)\n end, callback)\nend\n\n---An Executor that uses coroutines to run user functions concurrently.\n---@class obsidian.AsyncExecutor : obsidian.Executor\n---@field max_workers integer|?\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal AsyncExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"AsyncExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.AsyncExecutor = AsyncExecutor\n\n---@param max_workers integer|?\n---@return obsidian.AsyncExecutor\nAsyncExecutor.new = function(max_workers)\n local self = AsyncExecutor.init()\n if max_workers == nil then\n max_workers = 10\n elseif max_workers < 0 then\n max_workers = nil\n elseif max_workers == 0 then\n max_workers = 1\n end\n self.max_workers = max_workers\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.AsyncExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nAsyncExecutor.submit = function(self, fn, callback, ...)\n self.tasks_pending = self.tasks_pending + 1\n local args = { ... }\n async.run(function()\n if self.max_workers ~= nil then\n while self.tasks_running >= self.max_workers do\n async.util.sleep(20)\n end\n end\n self.tasks_pending = self.tasks_pending - 1\n self.tasks_running = self.tasks_running + 1\n return fn(unpack(args))\n end, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\nend\n\n---A multi-threaded Executor which uses the Libuv threadpool.\n---@class obsidian.ThreadPoolExecutor : obsidian.Executor\n---@field tasks_running integer\nlocal ThreadPoolExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"ThreadPoolExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.ThreadPoolExecutor = ThreadPoolExecutor\n\n---@return obsidian.ThreadPoolExecutor\nThreadPoolExecutor.new = function()\n local self = ThreadPoolExecutor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.ThreadPoolExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nThreadPoolExecutor.submit = function(self, fn, callback, ...)\n self.tasks_running = self.tasks_running + 1\n local ctx = uv.new_work(fn, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\n ctx:queue(...)\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@param sync boolean\nlocal init_job = function(cmds, on_stdout, on_exit, sync)\n local stderr_lines = false\n\n local on_obj = function(obj)\n --- NOTE: commands like `rg` return a non-zero exit code when there are no matches, which is okay.\n --- So we only log no-zero exit codes as errors when there's also stderr lines.\n if obj.code > 0 and stderr_lines then\n log.err(\"Command '%s' exited with non-zero code %s. See logs for stderr.\", cmds, obj.code)\n elseif stderr_lines then\n log.warn(\"Captured stderr output while running command '%s'. See logs for details.\", cmds)\n end\n if on_exit ~= nil then\n on_exit(obj.code)\n end\n end\n\n on_stdout = util.buffer_fn(on_stdout)\n\n local function stdout(err, data)\n if err ~= nil then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n end\n if data ~= nil then\n on_stdout(data)\n end\n end\n\n local function stderr(err, data)\n if err then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n elseif data ~= nil then\n if not stderr_lines then\n log.err(\"Captured stderr output while running command '%s'\", cmds)\n stderr_lines = true\n end\n log.err(\"[stderr] %s\", data)\n end\n end\n\n return function()\n log.debug(\"Initializing job '%s'\", cmds)\n\n if sync then\n local obj = vim.system(cmds, { stdout = stdout, stderr = stderr }):wait()\n on_obj(obj)\n return obj\n else\n vim.system(cmds, { stdout = stdout, stderr = stderr }, on_obj)\n end\n end\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@return integer exit_code\nM.run_job = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, true)\n return job().code\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\nM.run_job_async = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, false)\n job()\nend\n\n---@param fn function\n---@param timeout integer (milliseconds)\nM.throttle = function(fn, timeout)\n ---@type integer\n local last_call = 0\n ---@type uv.uv_timer_t?\n local timer = nil\n\n return function(...)\n if timer ~= nil then\n timer:stop()\n end\n\n local ms_remaining = timeout - (vim.uv.now() - last_call)\n\n if ms_remaining > 0 then\n if timer == nil then\n timer = assert(vim.uv.new_timer())\n end\n\n local args = { ... }\n\n timer:start(\n ms_remaining,\n 0,\n vim.schedule_wrap(function()\n if timer ~= nil then\n timer:stop()\n timer:close()\n timer = nil\n end\n\n last_call = vim.uv.now()\n fn(unpack(args))\n end)\n )\n else\n last_call = vim.uv.now()\n fn(...)\n end\n end\nend\n\n---Run an async function in a non-async context. The async function is expected to take a single\n---callback parameters with the results. This function returns those results.\n---@param async_fn_with_callback function (function,) -> any\n---@param timeout integer|?\n---@return ...any results\nM.block_on = function(async_fn_with_callback, timeout)\n local done = false\n local result\n timeout = timeout and timeout or 2000\n\n local function collect_result(...)\n result = { ... }\n done = true\n end\n\n async_fn_with_callback(collect_result)\n\n vim.wait(timeout, function()\n return done\n end, 20, false)\n\n return unpack(result)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/blink.lua", "local util = require \"obsidian.util\"\nlocal obsidian = require \"obsidian\"\n\nlocal M = {}\n\nM.injected_once = false\n\nM.providers = {\n { name = \"obsidian\", module = \"obsidian.completion.sources.blink.refs\" },\n { name = \"obsidian_tags\", module = \"obsidian.completion.sources.blink.tags\" },\n}\n\nlocal function add_provider(blink, provider_name, proivder_module)\n local add_source_provider = blink.add_source_provider or blink.add_provider\n add_source_provider(provider_name, {\n name = provider_name,\n module = proivder_module,\n async = true,\n opts = {},\n enabled = function()\n -- Enable only in markdown buffers.\n return vim.tbl_contains({ \"markdown\" }, vim.bo.filetype)\n and vim.bo.buftype ~= \"prompt\"\n and vim.b.completion ~= false\n end,\n })\nend\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_providers(opts)\n local blink = require \"blink.cmp\"\n\n if opts.completion.create_new then\n table.insert(M.providers, { name = \"obsidian_new\", module = \"obsidian.completion.sources.blink.new\" })\n end\n\n for _, provider in pairs(M.providers) do\n add_provider(blink, provider.name, provider.module)\n end\nend\n\nlocal function add_element_to_list_if_not_exists(list, element)\n if not vim.tbl_contains(list, element) then\n table.insert(list, 1, element)\n end\nend\n\nlocal function should_return_if_not_in_workspace()\n local current_file_path = vim.api.nvim_buf_get_name(0)\n local buf_dir = vim.fs.dirname(current_file_path)\n\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return true\n else\n return false\n end\nend\n\nlocal function log_unexpected_type(config_path, unexpected_type, expected_type)\n vim.notify(\n \"blink.cmp's `\"\n .. config_path\n .. \"` configuration appears to be an '\"\n .. unexpected_type\n .. \"' type, but it \"\n .. \"should be '\"\n .. expected_type\n .. \"'. Obsidian won't update this configuration, and \"\n .. \"completion won't work with blink.cmp\",\n vim.log.levels.ERROR\n )\nend\n\n---Attempts to inject the Obsidian sources into per_filetype if that's what the user seems to use for markdown\n---@param blink_sources_per_filetype table\n---@return boolean true if it obsidian sources were injected into the sources.per_filetype\nlocal function try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype)\n -- If the per_filetype is an empty object, then it's probably not utilized by the user\n if vim.deep_equal(blink_sources_per_filetype, {}) then\n return false\n end\n\n local markdown_config = blink_sources_per_filetype[\"markdown\"]\n\n -- If the markdown key is not used, then per_filetype it's probably not utilized by the user\n if markdown_config == nil then\n return false\n end\n\n local markdown_config_type = type(markdown_config)\n if markdown_config_type == \"table\" and util.islist(markdown_config) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(markdown_config, provider.name)\n end\n return true\n elseif markdown_config_type == \"function\" then\n local original_func = markdown_config\n markdown_config = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.per_filetype[\"markdown\"] = markdown_config\n return true\n else\n log_unexpected_type(\n \".sources.per_filetype['markdown']\",\n markdown_config_type,\n \"a list or a function that returns a list of sources\"\n )\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n---Attempts to inject the Obsidian sources into default if that's what the user seems to use for markdown\n---@param blink_sources_default (fun():string[])|(string[])\n---@return boolean true if it obsidian sources were injected into the sources.default\nlocal function try_inject_blink_sources_into_default(blink_sources_default)\n local blink_default_type = type(blink_sources_default)\n if blink_default_type == \"function\" then\n local original_func = blink_sources_default\n blink_sources_default = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.default = blink_sources_default\n return true\n elseif blink_default_type == \"table\" and util.islist(blink_sources_default) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(blink_sources_default, provider.name)\n end\n\n return true\n elseif blink_default_type == \"table\" then\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n else\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list or a function that returns a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace. nvm_cmp had the capability to configure the sources\n-- per buffer, but blink.cmp doesn't have that capability. Instead, we have to inject the sources into the global\n-- configuration and set a boolean on the module to return early the next time this function is called.\n--\n-- In-case the user used functions to configure their sources, the completion will properly work just for the markdown\n-- files that are in a workspace. Otherwise, the completion will work for all markdown files.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n if M.injected_once then\n return\n end\n\n M.injected_once = true\n\n local blink_config = require \"blink.cmp.config\"\n -- 'per_filetype' sources has priority over 'default' sources.\n -- 'per_filetype' can be a table or a function which returns a table ([\"filetype\"] = { \"a\", \"b\" })\n -- 'per_filetype' has the default value of {} (even if it's not configured by the user)\n local blink_sources_per_filetype = blink_config.sources.per_filetype\n if try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype) then\n return\n end\n\n -- 'default' can be a list/array or a function which returns a list/array ({ \"a\", \"b\"})\n local blink_sources_default = blink_config.sources[\"default\"]\n if try_inject_blink_sources_into_default(blink_sources_default) then\n return\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/init-legacy.lua", "local util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal command_lookups = {\n ObsidianCheck = \"obsidian.commands.check\",\n ObsidianToggleCheckbox = \"obsidian.commands.toggle_checkbox\",\n ObsidianToday = \"obsidian.commands.today\",\n ObsidianYesterday = \"obsidian.commands.yesterday\",\n ObsidianTomorrow = \"obsidian.commands.tomorrow\",\n ObsidianDailies = \"obsidian.commands.dailies\",\n ObsidianNew = \"obsidian.commands.new\",\n ObsidianOpen = \"obsidian.commands.open\",\n ObsidianBacklinks = \"obsidian.commands.backlinks\",\n ObsidianSearch = \"obsidian.commands.search\",\n ObsidianTags = \"obsidian.commands.tags\",\n ObsidianTemplate = \"obsidian.commands.template\",\n ObsidianNewFromTemplate = \"obsidian.commands.new_from_template\",\n ObsidianQuickSwitch = \"obsidian.commands.quick_switch\",\n ObsidianLinkNew = \"obsidian.commands.link_new\",\n ObsidianLink = \"obsidian.commands.link\",\n ObsidianLinks = \"obsidian.commands.links\",\n ObsidianFollowLink = \"obsidian.commands.follow_link\",\n ObsidianWorkspace = \"obsidian.commands.workspace\",\n ObsidianRename = \"obsidian.commands.rename\",\n ObsidianPasteImg = \"obsidian.commands.paste_img\",\n ObsidianExtractNote = \"obsidian.commands.extract_note\",\n ObsidianTOC = \"obsidian.commands.toc\",\n}\n\nlocal M = setmetatable({\n commands = {},\n}, {\n __index = function(t, k)\n local require_path = command_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@class obsidian.CommandConfigLegacy\n---@field opts table\n---@field complete function|?\n---@field func function|? (obsidian.Client, table) -> nil\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfigLegacy\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n return M[name](client, data)\n end\n end\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n for command_name, command_config in pairs(M.commands) do\n local func = function(data)\n command_config.func(client, data)\n end\n\n if command_config.complete ~= nil then\n command_config.opts.complete = function(arg_lead, cmd_line, cursor_pos)\n return command_config.complete(client, arg_lead, cmd_line, cursor_pos)\n end\n end\n\n vim.api.nvim_create_user_command(command_name, func, command_config.opts)\n end\nend\n\n---@param client obsidian.Client\n---@return string[]\nM.complete_args_search = function(client, _, cmd_line, _)\n local query\n local cmd_arg, _ = util.lstrip_whitespace(string.gsub(cmd_line, \"^.*Obsidian[A-Za-z0-9]+\", \"\"))\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\nM.register(\"ObsidianCheck\", { opts = { nargs = 0, desc = \"Check for issues in your vault\" } })\n\nM.register(\"ObsidianToday\", { opts = { nargs = \"?\", desc = \"Open today's daily note\" } })\n\nM.register(\"ObsidianYesterday\", { opts = { nargs = 0, desc = \"Open the daily note for the previous working day\" } })\n\nM.register(\"ObsidianTomorrow\", { opts = { nargs = 0, desc = \"Open the daily note for the next working day\" } })\n\nM.register(\"ObsidianDailies\", { opts = { nargs = \"*\", desc = \"Open a picker with daily notes\" } })\n\nM.register(\"ObsidianNew\", { opts = { nargs = \"?\", desc = \"Create a new note\" } })\n\nM.register(\n \"ObsidianOpen\",\n { opts = { nargs = \"?\", desc = \"Open in the Obsidian app\" }, complete = M.complete_args_search }\n)\n\nM.register(\"ObsidianBacklinks\", { opts = { nargs = 0, desc = \"Collect backlinks\" } })\n\nM.register(\"ObsidianTags\", { opts = { nargs = \"*\", range = true, desc = \"Find tags\" } })\n\nM.register(\"ObsidianSearch\", { opts = { nargs = \"?\", desc = \"Search vault\" } })\n\nM.register(\"ObsidianTemplate\", { opts = { nargs = \"?\", desc = \"Insert a template\" } })\n\nM.register(\"ObsidianNewFromTemplate\", { opts = { nargs = \"*\", desc = \"Create a new note from a template\" } })\n\nM.register(\"ObsidianQuickSwitch\", { opts = { nargs = \"?\", desc = \"Switch notes\" } })\n\nM.register(\"ObsidianLinkNew\", { opts = { nargs = \"?\", range = true, desc = \"Link selected text to a new note\" } })\n\nM.register(\"ObsidianLink\", {\n opts = { nargs = \"?\", range = true, desc = \"Link selected text to an existing note\" },\n complete = M.complete_args_search,\n})\n\nM.register(\"ObsidianLinks\", { opts = { nargs = 0, desc = \"Collect all links within the current buffer\" } })\n\nM.register(\"ObsidianFollowLink\", { opts = { nargs = \"?\", desc = \"Follow reference or link under cursor\" } })\n\nM.register(\"ObsidianToggleCheckbox\", { opts = { nargs = 0, desc = \"Toggle checkbox\", range = true } })\n\nM.register(\"ObsidianWorkspace\", { opts = { nargs = \"?\", desc = \"Check or switch workspace\" } })\n\nM.register(\"ObsidianRename\", { opts = { nargs = \"?\", desc = \"Rename note and update all references to it\" } })\n\nM.register(\"ObsidianPasteImg\", { opts = { nargs = \"?\", desc = \"Paste an image from the clipboard\" } })\n\nM.register(\n \"ObsidianExtractNote\",\n { opts = { nargs = \"?\", range = true, desc = \"Extract selected text to a new note and link to it\" } }\n)\n\nM.register(\"ObsidianTOC\", { opts = { nargs = 0, desc = \"Load the table of contents into a picker\" } })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/tags.lua", "local Note = require \"obsidian.note\"\nlocal Patterns = require(\"obsidian.search\").Patterns\n\nlocal M = {}\n\n---@type { pattern: string, offset: integer }[]\nlocal TAG_PATTERNS = {\n { pattern = \"[%s%(]#\" .. Patterns.TagCharsOptional .. \"$\", offset = 2 },\n { pattern = \"^#\" .. Patterns.TagCharsOptional .. \"$\", offset = 1 },\n}\n\nM.find_tags_start = function(input)\n for _, pattern in ipairs(TAG_PATTERNS) do\n local match = string.match(input, pattern.pattern)\n if match then\n return string.sub(match, pattern.offset + 1)\n end\n end\nend\n\n--- Find the boundaries of the YAML frontmatter within the buffer.\n---@param bufnr integer\n---@return integer|?, integer|?\nlocal get_frontmatter_boundaries = function(bufnr)\n local note = Note.from_buffer(bufnr)\n if note.frontmatter_end_line ~= nil then\n return 1, note.frontmatter_end_line\n end\nend\n\n---@return boolean, string|?, boolean|?\nM.can_complete = function(request)\n local search = M.find_tags_start(request.context.cursor_before_line)\n if not search or string.len(search) == 0 then\n return false\n end\n\n -- Check if we're inside frontmatter.\n local in_frontmatter = false\n local line = request.context.cursor.line\n local frontmatter_start, frontmatter_end = get_frontmatter_boundaries(request.context.bufnr)\n if\n frontmatter_start ~= nil\n and frontmatter_start <= (line + 1)\n and frontmatter_end ~= nil\n and line <= frontmatter_end\n then\n in_frontmatter = true\n end\n\n return true, search, in_frontmatter\nend\n\nM.get_trigger_characters = function()\n return { \"#\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n -- return [=[\\%(^\\|[^#]\\)\\zs#[a-zA-Z0-9_/-]\\+]=]\n return \"#[a-zA-Z0-9_/-]\\\\+\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/workspace.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\nlocal config = require \"obsidian.config\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.workspace.WorkspaceSpec\n---\n---@field path string|(fun(): string)\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts?\n\n---@class obsidian.workspace.WorkspaceOpts\n---\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts|?\n\n--- Each workspace represents a working directory (usually an Obsidian vault) along with\n--- a set of configuration options specific to the workspace.\n---\n--- Workspaces are a little more general than Obsidian vaults as you can have a workspace\n--- outside of a vault or as a subdirectory of a vault.\n---\n---@toc_entry obsidian.Workspace\n---\n---@class obsidian.Workspace : obsidian.ABC\n---\n---@field name string An arbitrary name for the workspace.\n---@field path obsidian.Path The normalized path to the workspace.\n---@field root obsidian.Path The normalized path to the vault root of the workspace. This usually matches 'path'.\n---@field overrides table|obsidian.config.ClientOpts|?\n---@field locked boolean|?\nlocal Workspace = abc.new_class {\n __tostring = function(self)\n return string.format(\"Workspace(name='%s', path='%s', root='%s')\", self.name, self.path, self.root)\n end,\n __eq = function(a, b)\n local a_fields = a:as_tbl()\n a_fields.locked = nil\n local b_fields = b:as_tbl()\n b_fields.locked = nil\n return vim.deep_equal(a_fields, b_fields)\n end,\n}\n\n--- Find the vault root from a given directory.\n---\n--- This will traverse the directory tree upwards until a '.obsidian/' folder is found to\n--- indicate the root of a vault, otherwise the given directory is used as-is.\n---\n---@param base_dir string|obsidian.Path\n---\n---@return obsidian.Path|?\nlocal function find_vault_root(base_dir)\n local vault_indicator_folder = \".obsidian\"\n base_dir = Path.new(base_dir)\n local dirs = Path.new(base_dir):parents()\n table.insert(dirs, 1, base_dir)\n\n for _, dir in ipairs(dirs) do\n local maybe_vault = dir / vault_indicator_folder\n if maybe_vault:is_dir() then\n return dir\n end\n end\n\n return nil\nend\n\n--- Create a new 'Workspace' object. This assumes the workspace already exists on the filesystem.\n---\n---@param path string|obsidian.Path Workspace path.\n---@param opts obsidian.workspace.WorkspaceOpts|?\n---\n---@return obsidian.Workspace\nWorkspace.new = function(path, opts)\n opts = opts and opts or {}\n\n local self = Workspace.init()\n self.path = Path.new(path):resolve { strict = true }\n self.name = assert(opts.name or self.path.name)\n self.overrides = opts.overrides\n\n if opts.strict then\n self.root = self.path\n else\n local vault_root = find_vault_root(self.path)\n if vault_root then\n self.root = vault_root\n else\n self.root = self.path\n end\n end\n\n return self\nend\n\n--- Initialize a new 'Workspace' object from a workspace spec.\n---\n---@param spec obsidian.workspace.WorkspaceSpec\n---\n---@return obsidian.Workspace\nWorkspace.new_from_spec = function(spec)\n ---@type string|obsidian.Path\n local path\n if type(spec.path) == \"function\" then\n path = spec.path()\n else\n ---@diagnostic disable-next-line: cast-local-type\n path = spec.path\n end\n\n ---@diagnostic disable-next-line: param-type-mismatch\n return Workspace.new(path, {\n name = spec.name,\n strict = spec.strict,\n overrides = spec.overrides,\n })\nend\n\n--- Lock the workspace.\nWorkspace.lock = function(self)\n self.locked = true\nend\n\n--- Unlock the workspace.\nWorkspace._unlock = function(self)\n self.locked = false\nend\n\n--- Get the workspace corresponding to the directory (or a parent of), if there\n--- is one.\n---\n---@param cur_dir string|obsidian.Path\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_dir = function(cur_dir, workspaces)\n local ok\n ok, cur_dir = pcall(function()\n return Path.new(cur_dir):resolve { strict = true }\n end)\n\n if not ok then\n return\n end\n\n for _, spec in ipairs(workspaces) do\n local w = Workspace.new_from_spec(spec)\n if w.path == cur_dir or w.path:is_parent_of(cur_dir) then\n return w\n end\n end\nend\n\n--- Get the workspace corresponding to the current working directory (or a parent of), if there\n--- is one.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_cwd = function(workspaces)\n local cwd = assert(vim.fn.getcwd())\n return Workspace.get_workspace_for_dir(cwd, workspaces)\nend\n\n--- Returns the default workspace.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|nil\nWorkspace.get_default_workspace = function(workspaces)\n if not vim.tbl_isempty(workspaces) then\n return Workspace.new_from_spec(workspaces[1])\n else\n return nil\n end\nend\n\n--- Resolves current workspace from the client config.\n---\n---@param opts obsidian.config.ClientOpts\n---\n---@return obsidian.Workspace|?\nWorkspace.get_from_opts = function(opts)\n local current_workspace = Workspace.get_workspace_for_cwd(opts.workspaces)\n\n if not current_workspace then\n current_workspace = Workspace.get_default_workspace(opts.workspaces)\n end\n\n return current_workspace\nend\n\n--- Get the normalize opts for a given workspace.\n---\n---@param workspace obsidian.Workspace|?\n---\n---@return obsidian.config.ClientOpts\nWorkspace.normalize_opts = function(workspace)\n if workspace then\n return config.normalize(workspace.overrides and workspace.overrides or {}, Obsidian._opts)\n else\n return Obsidian.opts\n end\nend\n\n---@param workspace obsidian.Workspace\n---@param opts { lock: boolean|? }|?\nWorkspace.set = function(workspace, opts)\n opts = opts and opts or {}\n\n local dir = workspace.root\n local options = Workspace.normalize_opts(workspace) -- TODO: test\n\n Obsidian.workspace = workspace\n Obsidian.dir = dir\n Obsidian.opts = options\n\n -- Ensure directories exist.\n dir:mkdir { parents = true, exists_ok = true }\n\n if options.notes_subdir ~= nil then\n local notes_subdir = dir / Obsidian.opts.notes_subdir\n notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n local daily_notes_subdir = Obsidian.dir / Obsidian.opts.daily_notes.folder\n daily_notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n -- Setup UI add-ons.\n local has_no_renderer = not (api.get_plugin_info \"render-markdown.nvim\" or api.get_plugin_info \"markview.nvim\")\n if has_no_renderer and Obsidian.opts.ui.enable then\n require(\"obsidian.ui\").setup(Obsidian.workspace, Obsidian.opts.ui)\n end\n\n if opts.lock then\n Obsidian.workspace:lock()\n end\n\n Obsidian.picker = require(\"obsidian.pickers\").get(Obsidian.opts.picker.name)\n\n util.fire_callback(\"post_set_workspace\", Obsidian.opts.callbacks.post_set_workspace, workspace)\n\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = \"ObsidianWorkpspaceSet\",\n data = { workspace = workspace },\n })\nend\n\n---@param workspace obsidian.Workspace|string The workspace object or the name of an existing workspace.\n---@param opts { lock: boolean|? }|?\nWorkspace.switch = function(workspace, opts)\n opts = opts and opts or {}\n\n if workspace == Obsidian.workspace.name then\n log.info(\"Already in workspace '%s' @ '%s'\", workspace, Obsidian.workspace.path)\n return\n end\n\n for _, ws in ipairs(Obsidian.opts.workspaces) do\n if ws.name == workspace then\n return Workspace.set(Workspace.new_from_spec(ws), opts)\n end\n end\n\n error(string.format(\"Workspace '%s' not found\", workspace))\nend\n\nreturn Workspace\n"], ["/obsidian.nvim/lua/obsidian/path.lua", "local abc = require \"obsidian.abc\"\n\nlocal function coerce(v)\n if v == vim.NIL then\n return nil\n else\n return v\n end\nend\n\n---@param path table\n---@param k string\n---@param factory fun(obsidian.Path): any\nlocal function cached_get(path, k, factory)\n local cache_key = \"__\" .. k\n local v = rawget(path, cache_key)\n if v == nil then\n v = factory(path)\n if v == nil then\n v = vim.NIL\n end\n path[cache_key] = v\n end\n return coerce(v)\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_name(path)\n local name = vim.fs.basename(path.filename)\n if not name or string.len(name) == 0 then\n return\n else\n return name\n end\nend\n\n---@param path obsidian.Path\n---@return string[]\n---@private\nlocal function get_suffixes(path)\n ---@type string[]\n local suffixes = {}\n local name = path.name\n while name and string.len(name) > 0 do\n local s, e, suffix = string.find(name, \"(%.[^%.]+)$\")\n if s and e and suffix then\n name = string.sub(name, 1, s - 1)\n table.insert(suffixes, suffix)\n else\n break\n end\n end\n\n -- reverse the list.\n ---@type string[]\n local out = {}\n for i = #suffixes, 1, -1 do\n table.insert(out, suffixes[i])\n end\n return out\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_suffix(path)\n local suffixes = path.suffixes\n if #suffixes > 0 then\n return suffixes[#suffixes]\n else\n return nil\n end\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_stem(path)\n local name, suffix = path.name, path.suffix\n if not name then\n return\n elseif not suffix then\n return name\n else\n return string.sub(name, 1, string.len(name) - string.len(suffix))\n end\nend\n\n--- A `Path` class that provides a subset of the functionality of the Python `pathlib` library while\n--- staying true to its API. It improves on a number of bugs in `plenary.path`.\n---\n---@toc_entry obsidian.Path\n---\n---@class obsidian.Path : obsidian.ABC\n---\n---@field filename string The underlying filename as a string.\n---@field name string|? The final path component, if any.\n---@field suffix string|? The final extension of the path, if any.\n---@field suffixes string[] A list of all of the path's extensions.\n---@field stem string|? The final path component, without its suffix.\nlocal Path = abc.new_class()\n\nPath.mt = {\n __tostring = function(self)\n return self.filename\n end,\n __eq = function(a, b)\n return a.filename == b.filename\n end,\n __div = function(self, other)\n return self:joinpath(other)\n end,\n __index = function(self, k)\n local raw = rawget(Path, k)\n if raw then\n return raw\n end\n\n local factory\n if k == \"name\" then\n factory = get_name\n elseif k == \"suffix\" then\n factory = get_suffix\n elseif k == \"suffixes\" then\n factory = get_suffixes\n elseif k == \"stem\" then\n factory = get_stem\n end\n\n if factory then\n return cached_get(self, k, factory)\n end\n end,\n}\n\n--- Check if an object is an `obsidian.Path` object.\n---\n---@param path any\n---\n---@return boolean\nPath.is_path_obj = function(path)\n if getmetatable(path) == Path.mt then\n return true\n else\n return false\n end\nend\n\n-------------------------------------------------------------------------------\n--- Constructors.\n-------------------------------------------------------------------------------\n\n--- Create a new path from a string.\n---\n---@param ... string|obsidian.Path\n---\n---@return obsidian.Path\nPath.new = function(...)\n local self = Path.init()\n\n local args = { ... }\n local arg\n if #args == 1 then\n arg = tostring(args[1])\n elseif #args == 2 and args[1] == Path then\n arg = tostring(args[2])\n else\n error \"expected one argument\"\n end\n\n if Path.is_path_obj(arg) then\n ---@cast arg obsidian.Path\n return arg\n end\n\n self.filename = vim.fs.normalize(tostring(arg))\n\n return self\nend\n\n--- Get a temporary path with a unique name.\n---\n---@param opts { suffix: string|? }|?\n---\n---@return obsidian.Path\nPath.temp = function(opts)\n opts = opts or {}\n local tmpname = vim.fn.tempname()\n if opts.suffix then\n tmpname = tmpname .. opts.suffix\n end\n return Path.new(tmpname)\nend\n\n--- Get a path corresponding to the current working directory as given by `vim.uv.cwd()`.\n---\n---@return obsidian.Path\nPath.cwd = function()\n return assert(Path.new(vim.uv.cwd()))\nend\n\n--- Get a path corresponding to a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buffer = function(bufnr)\n return Path.new(vim.api.nvim_buf_get_name(bufnr or 0))\nend\n\n--- Get a path corresponding to the parent of a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buf_dir = function(bufnr)\n return assert(Path.buffer(bufnr):parent())\nend\n\n-------------------------------------------------------------------------------\n--- Pure path methods.\n-------------------------------------------------------------------------------\n\n--- Return a new path with the suffix changed.\n---\n---@param suffix string\n---@param should_append boolean|? should the suffix append a suffix instead of replacing one which may be there?\n---\n---@return obsidian.Path\nPath.with_suffix = function(self, suffix, should_append)\n if not vim.startswith(suffix, \".\") and string.len(suffix) > 1 then\n error(string.format(\"invalid suffix '%s'\", suffix))\n elseif self.stem == nil then\n error(string.format(\"path '%s' has no stem\", self.filename))\n end\n\n local new_name = ((should_append == true) and self.name or self.stem) .. suffix\n\n ---@type obsidian.Path|?\n local parent = nil\n if self.name ~= self.filename then\n parent = self:parent()\n end\n\n if parent then\n return parent / new_name\n else\n return Path.new(new_name)\n end\nend\n\n--- Returns true if the path is already in absolute form.\n---\n---@return boolean\nPath.is_absolute = function(self)\n local api = require \"obsidian.api\"\n if\n vim.startswith(self.filename, \"/\")\n or (\n (api.get_os() == api.OSType.Windows or api.get_os() == api.OSType.Wsl)\n and string.match(self.filename, \"^[%a]:/.*$\")\n )\n then\n return true\n else\n return false\n end\nend\n\n---@param ... obsidian.Path|string\n---@return obsidian.Path\nPath.joinpath = function(self, ...)\n local args = vim.iter({ ... }):map(tostring):totable()\n return Path.new(vim.fs.joinpath(self.filename, unpack(args)))\nend\n\n--- Try to resolve a version of the path relative to the other.\n--- An error is raised when it's not possible.\n---\n---@param other obsidian.Path|string\n---\n---@return obsidian.Path\nPath.relative_to = function(self, other)\n other = Path.new(other)\n\n local other_fname = other.filename\n if not vim.endswith(other_fname, \"/\") then\n other_fname = other_fname .. \"/\"\n end\n\n if vim.startswith(self.filename, other_fname) then\n return Path.new(string.sub(self.filename, string.len(other_fname) + 1))\n end\n\n -- Edge cases when the paths are relative or under-specified, see tests.\n if not self:is_absolute() and not vim.startswith(self.filename, \"./\") and vim.startswith(other_fname, \"./\") then\n if other_fname == \"./\" then\n return self\n end\n\n local self_rel_to_cwd = Path.new \"./\" / self\n if vim.startswith(self_rel_to_cwd.filename, other_fname) then\n return Path.new(string.sub(self_rel_to_cwd.filename, string.len(other_fname) + 1))\n end\n end\n\n error(string.format(\"'%s' is not in the subpath of '%s'\", self.filename, other.filename))\nend\n\n--- The logical parent of the path.\n---\n---@return obsidian.Path|?\nPath.parent = function(self)\n local parent = vim.fs.dirname(self.filename)\n if parent ~= nil then\n return Path.new(parent)\n else\n return nil\n end\nend\n\n--- Get a list of the parent directories.\n---\n---@return obsidian.Path[]\nPath.parents = function(self)\n return vim.iter(vim.fs.parents(self.filename)):map(Path.new):totable()\nend\n\n--- Check if the path is a parent of other. This is a pure path method, so it only checks by\n--- comparing strings. Therefore in practice you probably want to `:resolve()` each path before\n--- using this.\n---\n---@param other obsidian.Path|string\n---\n---@return boolean\nPath.is_parent_of = function(self, other)\n other = Path.new(other)\n for _, parent in ipairs(other:parents()) do\n if parent == self then\n return true\n end\n end\n return false\nend\n\n---@return string?\n---@private\nPath.abspath = function(self)\n local path = vim.loop.fs_realpath(vim.fn.resolve(self.filename))\n return path\nend\n\n-------------------------------------------------------------------------------\n--- Concrete path methods.\n-------------------------------------------------------------------------------\n\n--- Make the path absolute, resolving any symlinks.\n--- If `strict` is true and the path doesn't exist, an error is raised.\n---\n---@param opts { strict: boolean }|?\n---\n---@return obsidian.Path\nPath.resolve = function(self, opts)\n opts = opts or {}\n\n local realpath = self:abspath()\n if realpath then\n return Path.new(realpath)\n elseif opts.strict then\n error(\"FileNotFoundError: \" .. self.filename)\n end\n\n -- File doesn't exist, but some parents might. Traverse up until we find a parent that\n -- does exist, and then put the path back together from there.\n local parents = self:parents()\n for _, parent in ipairs(parents) do\n local parent_realpath = parent:abspath()\n if parent_realpath then\n return Path.new(parent_realpath) / self:relative_to(parent)\n end\n end\n\n return self\nend\n\n--- Get OS stat results.\n---\n---@return table|?\nPath.stat = function(self)\n local realpath = self:abspath()\n if realpath then\n local stat, _ = vim.uv.fs_stat(realpath)\n return stat\n end\nend\n\n--- Check if the path points to an existing file or directory.\n---\n---@return boolean\nPath.exists = function(self)\n local stat = self:stat()\n return stat ~= nil\nend\n\n--- Check if the path points to an existing file.\n---\n---@return boolean\nPath.is_file = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"file\"\n end\nend\n\n--- Check if the path points to an existing directory.\n---\n---@return boolean\nPath.is_dir = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"directory\"\n end\nend\n\n--- Create a new directory at the given path.\n---\n---@param opts { mode: integer|?, parents: boolean|?, exist_ok: boolean|? }|?\nPath.mkdir = function(self, opts)\n opts = opts or {}\n\n local mode = opts.mode or 448 -- 0700 -> decimal\n ---@diagnostic disable-next-line: undefined-field\n if opts.exists_ok then -- for compat with the plenary.path API.\n opts.exist_ok = true\n end\n\n if self:is_dir() then\n if not opts.exist_ok then\n error(\"FileExistsError: \" .. self.filename)\n else\n return\n end\n end\n\n if vim.uv.fs_mkdir(self.filename, mode) then\n return\n end\n\n if not opts.parents then\n error(\"FileNotFoundError: \" .. tostring(self:parent()))\n end\n\n local parents = self:parents()\n for i = #parents, 1, -1 do\n if not parents[i]:is_dir() then\n parents[i]:mkdir { exist_ok = true, mode = mode }\n end\n end\n\n self:mkdir { mode = mode }\nend\n\n--- Remove the corresponding directory. This directory must be empty.\nPath.rmdir = function(self)\n local resolved = self:resolve { strict = false }\n\n if not resolved:is_dir() then\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_rmdir(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n-- TODO: not implemented and not used, after we get to 0.11 we can simply use vim.fs.rm\n--- Recursively remove an entire directory and its contents.\nPath.rmtree = function(self) end\n\n--- Create a file at this given path.\n---\n---@param opts { mode: integer|?, exist_ok: boolean|? }|?\nPath.touch = function(self, opts)\n opts = opts or {}\n local mode = opts.mode or 420\n\n local resolved = self:resolve { strict = false }\n if resolved:exists() then\n local new_time = os.time()\n vim.uv.fs_utime(resolved.filename, new_time, new_time)\n return\n end\n\n local parent = resolved:parent()\n if parent and not parent:exists() then\n error(\"FileNotFoundError: \" .. parent.filename)\n end\n\n local fd, err_name, err_msg = vim.uv.fs_open(resolved.filename, \"w\", mode)\n if not fd then\n error(err_name .. \": \" .. err_msg)\n end\n vim.uv.fs_close(fd)\nend\n\n--- Rename this file or directory to the given target.\n---\n---@param target obsidian.Path|string\n---\n---@return obsidian.Path\nPath.rename = function(self, target)\n local resolved = self:resolve { strict = false }\n target = Path.new(target)\n\n local ok, err_name, err_msg = vim.uv.fs_rename(resolved.filename, target.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\n\n return target\nend\n\n--- Remove the file.\n---\n---@param opts { missing_ok: boolean|? }|?\nPath.unlink = function(self, opts)\n opts = opts or {}\n\n local resolved = self:resolve { strict = false }\n\n if not resolved:exists() then\n if not opts.missing_ok then\n error(\"FileNotFoundError: \" .. resolved.filename)\n end\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_unlink(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n--- Make a path relative to the vault root, if possible, return a string\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return string?\nPath.vault_relative_path = function(self, opts)\n opts = opts or {}\n\n -- NOTE: we don't try to resolve the `path` here because that would make the path absolute,\n -- which may result in the wrong relative path if the current working directory is not within\n -- the vault.\n\n local ok, relative_path = pcall(function()\n return self:relative_to(Obsidian.workspace.root)\n end)\n\n if ok and relative_path then\n return tostring(relative_path)\n elseif not self:is_absolute() then\n return tostring(self)\n elseif opts.strict then\n error(string.format(\"failed to resolve '%s' relative to vault root '%s'\", self, Obsidian.workspace.root))\n end\nend\n\nreturn Path\n"], ["/obsidian.nvim/lua/obsidian/util.lua", "local compat = require \"obsidian.compat\"\nlocal ts, string, table = vim.treesitter, string, table\nlocal util = {}\n\nsetmetatable(util, {\n __index = function(_, k)\n return require(\"obsidian.api\")[k] or require(\"obsidian.builtin\")[k]\n end,\n})\n\n-------------------\n--- File tools ----\n-------------------\n\n---@param file string\n---@param contents string\nutil.write_file = function(file, contents)\n local fd = assert(io.open(file, \"w+\"))\n fd:write(contents)\n fd:close()\nend\n\n-------------------\n--- Iter tools ----\n-------------------\n\n---Create an enumeration iterator over an iterable.\n---@param iterable table|string|function\n---@return function\nutil.enumerate = function(iterable)\n local iterator = vim.iter(iterable)\n local i = 0\n\n return function()\n local next = iterator()\n if next == nil then\n return nil, nil\n else\n i = i + 1\n return i, next\n end\n end\nend\n\n---Zip two iterables together.\n---@param iterable1 table|string|function\n---@param iterable2 table|string|function\n---@return function\nutil.zip = function(iterable1, iterable2)\n local iterator1 = vim.iter(iterable1)\n local iterator2 = vim.iter(iterable2)\n\n return function()\n local next1 = iterator1()\n local next2 = iterator2()\n if next1 == nil or next2 == nil then\n return nil\n else\n return next1, next2\n end\n end\nend\n\n-------------------\n--- Table tools ---\n-------------------\n\n---Check if an object is an array-like table.\n--- TODO: after 0.12 replace with vim.islist\n---\n---@param t any\n---@return boolean\nutil.islist = function(t)\n return compat.is_list(t)\nend\n\n---Return a new list table with only the unique values of the original table.\n---\n---@param t table\n---@return any[]\nutil.tbl_unique = function(t)\n local found = {}\n for _, val in pairs(t) do\n found[val] = true\n end\n return vim.tbl_keys(found)\nend\n\n--------------------\n--- String Tools ---\n--------------------\n\n---Iterate over all matches of 'pattern' in 's'. 'gfind' is to 'find' as 'gsub' is to 'sub'.\n---@param s string\n---@param pattern string\n---@param init integer|?\n---@param plain boolean|?\nutil.gfind = function(s, pattern, init, plain)\n init = init and init or 1\n\n return function()\n if init < #s then\n local m_start, m_end = string.find(s, pattern, init, plain)\n if m_start ~= nil and m_end ~= nil then\n init = m_end + 1\n return m_start, m_end\n end\n end\n return nil\n end\nend\n\nlocal char_to_hex = function(c)\n return string.format(\"%%%02X\", string.byte(c))\nend\n\n--- Encode a string into URL-safe version.\n---\n---@param str string\n---@param opts { keep_path_sep: boolean|? }|?\n---\n---@return string\nutil.urlencode = function(str, opts)\n opts = opts or {}\n local url = str\n url = url:gsub(\"\\n\", \"\\r\\n\")\n url = url:gsub(\"([%(%)%*%?%[%]%$\\\"':<>|\\\\'{}])\", char_to_hex)\n if not opts.keep_path_sep then\n url = url:gsub(\"/\", char_to_hex)\n end\n\n -- Spaces in URLs are always safely encoded with `%20`, but not always safe\n -- with `+`. For example, `+` in a query param's value will be interpreted\n -- as a literal plus-sign if the decoder is using JavaScript's `decodeURI`\n -- function.\n url = url:gsub(\" \", \"%%20\")\n return url\nend\n\nutil.is_hex_color = function(s)\n return (s:match \"^#%x%x%x$\" or s:match \"^#%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x%x%x$\")\n ~= nil\nend\n\n---Match the case of 'key' to the given 'prefix' of the key.\n---\n---@param prefix string\n---@param key string\n---@return string|?\nutil.match_case = function(prefix, key)\n local out_chars = {}\n for i = 1, string.len(key) do\n local c_key = string.sub(key, i, i)\n local c_pre = string.sub(prefix, i, i)\n if c_pre:lower() == c_key:lower() then\n table.insert(out_chars, c_pre)\n elseif c_pre:len() > 0 then\n return nil\n else\n table.insert(out_chars, c_key)\n end\n end\n return table.concat(out_chars, \"\")\nend\n\n---Check if a string is a checkbox list item\n---\n---Supported checboox lists:\n--- - [ ] foo\n--- - [x] foo\n--- + [x] foo\n--- * [ ] foo\n--- 1. [ ] foo\n--- 1) [ ] foo\n---\n---@param s string\n---@return boolean\nutil.is_checkbox = function(s)\n -- - [ ] and * [ ] and + [ ]\n if string.match(s, \"^%s*[-+*]%s+%[.%]\") ~= nil then\n return true\n end\n -- 1. [ ] and 1) [ ]\n if string.match(s, \"^%s*%d+[%.%)]%s+%[.%]\") ~= nil then\n return true\n end\n return false\nend\n\n---Check if a string is a valid URL.\n---@param s string\n---@return boolean\nutil.is_url = function(s)\n local search = require \"obsidian.search\"\n\n if\n string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.NakedUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.FileUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.MailtoUrl] .. \"$\")\n then\n return true\n else\n return false\n end\nend\n\n---Checks if a given string represents an image file based on its suffix.\n---\n---@param s string: The input string to check.\n---@return boolean: Returns true if the string ends with a supported image suffix, false otherwise.\nutil.is_img = function(s)\n for _, suffix in ipairs { \".png\", \".jpg\", \".jpeg\", \".heic\", \".gif\", \".svg\", \".ico\" } do\n if vim.endswith(s, suffix) then\n return true\n end\n end\n return false\nend\n\n-- This function removes a single backslash within double square brackets\nutil.unescape_single_backslash = function(text)\n return text:gsub(\"(%[%[[^\\\\]+)\\\\(%|[^\\\\]+]])\", \"%1%2\")\nend\n\nutil.string_enclosing_chars = { [[\"]], [[']] }\n\n---Count the indentation of a line.\n---@param str string\n---@return integer\nutil.count_indent = function(str)\n local indent = 0\n for i = 1, #str do\n local c = string.sub(str, i, i)\n -- space or tab both count as 1 indent\n if c == \" \" or c == \"\t\" then\n indent = indent + 1\n else\n break\n end\n end\n return indent\nend\n\n---Check if a string is only whitespace.\n---@param str string\n---@return boolean\nutil.is_whitespace = function(str)\n return string.match(str, \"^%s+$\") ~= nil\nend\n\n---Get the substring of `str` starting from the first character and up to the stop character,\n---ignoring any enclosing characters (like double quotes) and stop characters that are within the\n---enclosing characters. For example, if `str = [=[\"foo\", \"bar\"]=]` and `stop_char = \",\"`, this\n---would return the string `[=[foo]=]`.\n---\n---@param str string\n---@param stop_chars string[]\n---@param keep_stop_char boolean|?\n---@return string|?, string\nutil.next_item = function(str, stop_chars, keep_stop_char)\n local og_str = str\n\n -- Check for enclosing characters.\n local enclosing_char = nil\n local first_char = string.sub(str, 1, 1)\n for _, c in ipairs(util.string_enclosing_chars) do\n if first_char == c then\n enclosing_char = c\n str = string.sub(str, 2)\n break\n end\n end\n\n local result\n local hits\n\n for _, stop_char in ipairs(stop_chars) do\n -- First check for next item when `stop_char` is present.\n if enclosing_char ~= nil then\n result, hits = string.gsub(\n str,\n \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*\" .. stop_char .. \".*\",\n \"%1%2\"\n )\n result = enclosing_char .. result .. enclosing_char\n else\n result, hits = string.gsub(str, \"([^\" .. stop_char .. \"]+)\" .. stop_char .. \".*\", \"%1\")\n end\n if hits ~= 0 then\n local i = string.find(str, stop_char, string.len(result), true)\n if keep_stop_char then\n return result .. stop_char, string.sub(str, i + 1)\n else\n return result, string.sub(str, i + 1)\n end\n end\n\n -- Now check for next item without the `stop_char` after.\n if not keep_stop_char and enclosing_char ~= nil then\n result, hits = string.gsub(str, \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*$\", \"%1%2\")\n result = enclosing_char .. result .. enclosing_char\n elseif not keep_stop_char then\n result = str\n hits = 1\n else\n result = nil\n hits = 0\n end\n if hits ~= 0 then\n if keep_stop_char then\n result = result .. stop_char\n end\n return result, \"\"\n end\n end\n\n return nil, og_str\nend\n\n---Strip whitespace from the right end of a string.\n---@param str string\n---@return string\nutil.rstrip_whitespace = function(str)\n str = string.gsub(str, \"%s+$\", \"\")\n return str\nend\n\n---Strip whitespace from the left end of a string.\n---@param str string\n---@param limit integer|?\n---@return string\nutil.lstrip_whitespace = function(str, limit)\n if limit ~= nil then\n local num_found = 0\n while num_found < limit do\n str = string.gsub(str, \"^%s\", \"\")\n num_found = num_found + 1\n end\n else\n str = string.gsub(str, \"^%s+\", \"\")\n end\n return str\nend\n\n---Strip enclosing characters like quotes from a string.\n---@param str string\n---@return string\nutil.strip_enclosing_chars = function(str)\n local c_start = string.sub(str, 1, 1)\n local c_end = string.sub(str, #str, #str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if c_start == enclosing_char and c_end == enclosing_char then\n str = string.sub(str, 2, #str - 1)\n break\n end\n end\n return str\nend\n\n---Check if a string has enclosing characters like quotes.\n---@param str string\n---@return boolean\nutil.has_enclosing_chars = function(str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if vim.startswith(str, enclosing_char) and vim.endswith(str, enclosing_char) then\n return true\n end\n end\n return false\nend\n\n---Strip YAML comments from a string.\n---@param str string\n---@return string\nutil.strip_comments = function(str)\n if vim.startswith(str, \"# \") then\n return \"\"\n elseif not util.has_enclosing_chars(str) then\n return select(1, string.gsub(str, [[%s+#%s.*$]], \"\"))\n else\n return str\n end\nend\n\n---Check if a string contains a substring.\n---@param str string\n---@param substr string\n---@return boolean\nutil.string_contains = function(str, substr)\n local i = string.find(str, substr, 1, true)\n return i ~= nil\nend\n\n--------------------\n--- Date helpers ---\n--------------------\n\n---Determines if the given date is a working day (not weekend)\n---\n---@param time integer\n---\n---@return boolean\nutil.is_working_day = function(time)\n local is_saturday = (os.date(\"%w\", time) == \"6\")\n local is_sunday = (os.date(\"%w\", time) == \"0\")\n return not (is_saturday or is_sunday)\nend\n\n--- Returns the previous day from given time\n---\n--- @param time integer\n--- @return integer\nutil.previous_day = function(time)\n return time - (24 * 60 * 60)\nend\n---\n--- Returns the next day from given time\n---\n--- @param time integer\n--- @return integer\nutil.next_day = function(time)\n return time + (24 * 60 * 60)\nend\n\n---Determines the last working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_before = function(time)\n local previous_day = util.previous_day(time)\n if util.is_working_day(previous_day) then\n return previous_day\n else\n return util.working_day_before(previous_day)\n end\nend\n\n---Determines the next working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_after = function(time)\n local next_day = util.next_day(time)\n if util.is_working_day(next_day) then\n return next_day\n else\n return util.working_day_after(next_day)\n end\nend\n\n---@param link string\n---@param opts { include_naked_urls: boolean|?, include_file_urls: boolean|?, include_block_ids: boolean|?, link_type: obsidian.search.RefTypes|? }|?\n---\n---@return string|?, string|?, obsidian.search.RefTypes|?\nutil.parse_link = function(link, opts)\n local search = require \"obsidian.search\"\n\n opts = opts and opts or {}\n\n local link_type = opts.link_type\n if link_type == nil then\n for match in\n vim.iter(search.find_refs(link, {\n include_naked_urls = opts.include_naked_urls,\n include_file_urls = opts.include_file_urls,\n include_block_ids = opts.include_block_ids,\n }))\n do\n local _, _, m_type = unpack(match)\n if m_type then\n link_type = m_type\n break\n end\n end\n end\n\n if link_type == nil then\n return nil\n end\n\n local link_location, link_name\n if link_type == search.RefTypes.Markdown then\n link_location = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%2\")\n link_name = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%1\")\n elseif link_type == search.RefTypes.NakedUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.FileUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.WikiWithAlias then\n link = util.unescape_single_backslash(link)\n -- remove boundary brackets, e.g. '[[XXX|YYY]]' -> 'XXX|YYY'\n link = link:sub(3, #link - 2)\n -- split on the \"|\"\n local split_idx = link:find \"|\"\n link_location = link:sub(1, split_idx - 1)\n link_name = link:sub(split_idx + 1)\n elseif link_type == search.RefTypes.Wiki then\n -- remove boundary brackets, e.g. '[[YYY]]' -> 'YYY'\n link = link:sub(3, #link - 2)\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.BlockID then\n link_location = util.standardize_block(link)\n link_name = link\n else\n error(\"not implemented for \" .. link_type)\n end\n\n return link_location, link_name, link_type\nend\n\n------------------------------------\n-- Miscellaneous helper functions --\n------------------------------------\n---@param anchor obsidian.note.HeaderAnchor\n---@return string\nutil.format_anchor_label = function(anchor)\n return string.format(\" ❯ %s\", anchor.header)\nend\n\n-- We are very loose here because obsidian allows pretty much anything\nutil.ANCHOR_LINK_PATTERN = \"#[%w%d\\128-\\255][^#]*\"\n\nutil.BLOCK_PATTERN = \"%^[%w%d][%w%d-]*\"\n\nutil.BLOCK_LINK_PATTERN = \"#\" .. util.BLOCK_PATTERN\n\n--- Strip anchor links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_anchor_links = function(line)\n ---@type string|?\n local anchor\n\n while true do\n local anchor_match = string.match(line, util.ANCHOR_LINK_PATTERN .. \"$\")\n if anchor_match then\n anchor = anchor or \"\"\n anchor = anchor_match .. anchor\n line = string.sub(line, 1, -anchor_match:len() - 1)\n else\n break\n end\n end\n\n return line, anchor and util.standardize_anchor(anchor)\nend\n\n--- Parse a block line from a line.\n---\n---@param line string\n---\n---@return string|?\nutil.parse_block = function(line)\n local block_match = string.match(line, util.BLOCK_PATTERN .. \"$\")\n return block_match\nend\n\n--- Strip block links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_block_links = function(line)\n local block_match = string.match(line, util.BLOCK_LINK_PATTERN .. \"$\")\n if block_match then\n line = string.sub(line, 1, -block_match:len() - 1)\n end\n return line, block_match\nend\n\n--- Standardize a block identifier.\n---@param block_id string\n---@return string\nutil.standardize_block = function(block_id)\n if vim.startswith(block_id, \"#\") then\n block_id = string.sub(block_id, 2)\n end\n\n if not vim.startswith(block_id, \"^\") then\n block_id = \"^\" .. block_id\n end\n\n return block_id\nend\n\n--- Check if a line is a markdown header.\n---@param line string\n---@return boolean\nutil.is_header = function(line)\n if string.match(line, \"^#+%s+[%w]+\") then\n return true\n else\n return false\n end\nend\n\n--- Get the header level of a line.\n---@param line string\n---@return integer\nutil.header_level = function(line)\n local headers, match_count = string.gsub(line, \"^(#+)%s+[%w]+.*\", \"%1\")\n if match_count > 0 then\n return string.len(headers)\n else\n return 0\n end\nend\n\n---@param line string\n---@return { header: string, level: integer, anchor: string }|?\nutil.parse_header = function(line)\n local header_start, header = string.match(line, \"^(#+)%s+([^%s]+.*)$\")\n if header_start and header then\n header = vim.trim(header)\n return {\n header = vim.trim(header),\n level = string.len(header_start),\n anchor = util.header_to_anchor(header),\n }\n else\n return nil\n end\nend\n\n--- Standardize a header anchor link.\n---\n---@param anchor string\n---\n---@return string\nutil.standardize_anchor = function(anchor)\n -- Lowercase everything.\n anchor = string.lower(anchor)\n -- Replace whitespace with \"-\".\n anchor = string.gsub(anchor, \"%s\", \"-\")\n -- Remove every non-alphanumeric character.\n anchor = string.gsub(anchor, \"[^#%w\\128-\\255_-]\", \"\")\n return anchor\nend\n\n--- Transform a markdown header into an link, e.g. \"# Hello World\" -> \"#hello-world\".\n---\n---@param header string\n---\n---@return string\nutil.header_to_anchor = function(header)\n -- Remove leading '#' and strip whitespace.\n local anchor = vim.trim(string.gsub(header, [[^#+%s+]], \"\"))\n return util.standardize_anchor(\"#\" .. anchor)\nend\n\n---@alias datetime_cadence \"daily\"\n\n--- Parse possible relative date macros like '@tomorrow'.\n---\n---@param macro string\n---\n---@return { macro: string, offset: integer, cadence: datetime_cadence }[]\nutil.resolve_date_macro = function(macro)\n ---@type { macro: string, offset: integer, cadence: datetime_cadence }[]\n local out = {}\n for m, offset_days in pairs { today = 0, tomorrow = 1, yesterday = -1 } do\n m = \"@\" .. m\n if vim.startswith(m, macro) then\n out[#out + 1] = { macro = m, offset = offset_days, cadence = \"daily\" }\n end\n end\n return out\nend\n\n--- Check if a string contains invalid characters.\n---\n--- @param fname string\n---\n--- @return boolean\nutil.contains_invalid_characters = function(fname)\n local invalid_chars = \"#^%[%]|\"\n return string.find(fname, \"[\" .. invalid_chars .. \"]\") ~= nil\nend\n\n---Check if a string is NaN\n---\n---@param v any\n---@return boolean\nutil.isNan = function(v)\n return tostring(v) == tostring(0 / 0)\nend\n\n---Higher order function, make sure a function is called with complete lines\n---@param fn fun(string)?\n---@return fun(string)\nutil.buffer_fn = function(fn)\n if not fn then\n return function() end\n end\n local buffer = \"\"\n return function(data)\n buffer = buffer .. data\n local lines = vim.split(buffer, \"\\n\")\n if #lines > 1 then\n for i = 1, #lines - 1 do\n fn(lines[i])\n end\n buffer = lines[#lines] -- Store remaining partial line\n end\n end\nend\n\n---@param event string\n---@param callback fun(...)\n---@param ... any\n---@return boolean success\nutil.fire_callback = function(event, callback, ...)\n local log = require \"obsidian.log\"\n if not callback then\n return false\n end\n local ok, err = pcall(callback, ...)\n if ok then\n return true\n else\n log.error(\"Error running %s callback: %s\", event, err)\n return false\n end\nend\n\n---@param node_type string | string[]\n---@return boolean\nutil.in_node = function(node_type)\n local function in_node(t)\n local node = ts.get_node()\n while node do\n if node:type() == t then\n return true\n end\n node = node:parent()\n end\n return false\n end\n if type(node_type) == \"string\" then\n return in_node(node_type)\n elseif type(node_type) == \"table\" then\n for _, t in ipairs(node_type) do\n local is_in_node = in_node(t)\n if is_in_node then\n return true\n end\n end\n end\n return false\nend\n\nreturn util\n"], ["/obsidian.nvim/lua/obsidian/commands/search.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n picker:grep_notes { query = data.args }\nend\n"], ["/obsidian.nvim/lua/obsidian/ui.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal M = {}\n\nlocal NAMESPACE = \"ObsidianUI\"\n\n---@param ui_opts obsidian.config.UIOpts\nlocal function install_hl_groups(ui_opts)\n for group_name, opts in pairs(ui_opts.hl_groups) do\n vim.api.nvim_set_hl(0, group_name, opts)\n end\nend\n\n-- We cache marks locally to help avoid redrawing marks when its not necessary. The main reason\n-- we need to do this is because the conceal char we get back from `nvim_buf_get_extmarks()` gets mangled.\n-- For example, \"󰄱\" is turned into \"1\\1\\15\".\n-- TODO: if we knew how to un-mangle the conceal char we wouldn't need the cache.\n\nM._buf_mark_cache = vim.defaulttable()\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\n---@return ExtMark|?\nlocal function cache_get(bufnr, ns_id, mark_id)\n local buf_ns_cache = M._buf_mark_cache[bufnr][ns_id]\n return buf_ns_cache[mark_id]\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark ExtMark\n---@return ExtMark|?\nlocal function cache_set(bufnr, ns_id, mark)\n assert(mark.id ~= nil)\n M._buf_mark_cache[bufnr][ns_id][mark.id] = mark\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\nlocal function cache_evict(bufnr, ns_id, mark_id)\n M._buf_mark_cache[bufnr][ns_id][mark_id] = nil\nend\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function cache_clear(bufnr, ns_id)\n M._buf_mark_cache[bufnr][ns_id] = {}\nend\n\n---@class ExtMark : obsidian.ABC\n---@field id integer|? ID of the mark, only set for marks that are actually materialized in the buffer.\n---@field row integer 0-based row index to place the mark.\n---@field col integer 0-based col index to place the mark.\n---@field opts ExtMarkOpts Optional parameters passed directly to `nvim_buf_set_extmark()`.\nlocal ExtMark = abc.new_class {\n __eq = function(a, b)\n return a.row == b.row and a.col == b.col and a.opts == b.opts\n end,\n}\n\nM.ExtMark = ExtMark\n\n---@class ExtMarkOpts : obsidian.ABC\n---@field end_row integer\n---@field end_col integer\n---@field conceal string|?\n---@field hl_group string|?\n---@field spell boolean|?\nlocal ExtMarkOpts = abc.new_class()\n\nM.ExtMarkOpts = ExtMarkOpts\n\n---@param data table\n---@return ExtMarkOpts\nExtMarkOpts.from_tbl = function(data)\n local self = ExtMarkOpts.init()\n self.end_row = data.end_row\n self.end_col = data.end_col\n self.conceal = data.conceal\n self.hl_group = data.hl_group\n self.spell = data.spell\n return self\nend\n\n---@param self ExtMarkOpts\n---@return table\nExtMarkOpts.to_tbl = function(self)\n return {\n end_row = self.end_row,\n end_col = self.end_col,\n conceal = self.conceal,\n hl_group = self.hl_group,\n spell = self.spell,\n }\nend\n\n---@param id integer|?\n---@param row integer\n---@param col integer\n---@param opts ExtMarkOpts\n---@return ExtMark\nExtMark.new = function(id, row, col, opts)\n local self = ExtMark.init()\n self.id = id\n self.row = row\n self.col = col\n self.opts = opts\n return self\nend\n\n---Materialize the ExtMark if needed. After calling this the 'id' will be set if it wasn't already.\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return ExtMark\nExtMark.materialize = function(self, bufnr, ns_id)\n if self.id == nil then\n self.id = vim.api.nvim_buf_set_extmark(bufnr, ns_id, self.row, self.col, self.opts:to_tbl())\n end\n cache_set(bufnr, ns_id, self)\n return self\nend\n\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return boolean\nExtMark.clear = function(self, bufnr, ns_id)\n if self.id ~= nil then\n cache_evict(bufnr, ns_id, self.id)\n return vim.api.nvim_buf_del_extmark(bufnr, ns_id, self.id)\n else\n return false\n end\nend\n\n---Collect all existing (materialized) marks within a region.\n---@param bufnr integer\n---@param ns_id integer\n---@param region_start integer|integer[]|?\n---@param region_end integer|integer[]|?\n---@return ExtMark[]\nExtMark.collect = function(bufnr, ns_id, region_start, region_end)\n region_start = region_start and region_start or 0\n region_end = region_end and region_end or -1\n local marks = {}\n for data in iter(vim.api.nvim_buf_get_extmarks(bufnr, ns_id, region_start, region_end, { details = true })) do\n local mark = ExtMark.new(data[1], data[2], data[3], ExtMarkOpts.from_tbl(data[4]))\n -- NOTE: since the conceal char we get back from `nvim_buf_get_extmarks()` is mangled, e.g.\n -- \"󰄱\" is turned into \"1\\1\\15\", we used the cached version.\n local cached_mark = cache_get(bufnr, ns_id, mark.id)\n if cached_mark ~= nil then\n mark.opts.conceal = cached_mark.opts.conceal\n end\n cache_set(bufnr, ns_id, mark)\n marks[#marks + 1] = mark\n end\n return marks\nend\n\n---Clear all existing (materialized) marks with a line region.\n---@param bufnr integer\n---@param ns_id integer\n---@param line_start integer\n---@param line_end integer\nExtMark.clear_range = function(bufnr, ns_id, line_start, line_end)\n return vim.api.nvim_buf_clear_namespace(bufnr, ns_id, line_start, line_end)\nend\n\n---Clear all existing (materialized) marks on a line.\n---@param bufnr integer\n---@param ns_id integer\n---@param line integer\nExtMark.clear_line = function(bufnr, ns_id, line)\n return ExtMark.clear_range(bufnr, ns_id, line, line + 1)\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_check_extmarks(marks, line, lnum, ui_opts)\n for char, opts in pairs(ui_opts.checkboxes) do\n if string.match(line, \"^%s*- %[\" .. vim.pesc(char) .. \"%]\") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 5,\n conceal = opts.char,\n hl_group = opts.hl_group,\n }\n )\n return marks\n end\n end\n\n if ui_opts.bullets ~= nil and string.match(line, \"^%s*[-%*%+] \") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 1,\n conceal = ui_opts.bullets.char,\n hl_group = ui_opts.bullets.hl_group,\n }\n )\n end\n\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_ref_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_refs(line, { include_naked_urls = true, include_tags = true, include_block_ids = true })\n for match in iter(matches) do\n local m_start, m_end, m_type = unpack(match)\n if m_type == search.RefTypes.WikiWithAlias then\n -- Reference of the form [[xxx|yyy]]\n local pipe_loc = string.find(line, \"|\", m_start, true)\n assert(pipe_loc)\n -- Conceal everything from '[[' up to '|'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = pipe_loc,\n conceal = \"\",\n }\n )\n -- Highlight the alias 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n pipe_loc,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Wiki then\n -- Reference of the form [[xxx]]\n -- Conceal the opening '[['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'xxx'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Markdown then\n -- Reference of the form [yyy](xxx)\n local closing_bracket_loc = string.find(line, \"]\", m_start, true)\n assert(closing_bracket_loc)\n local is_url = util.is_url(string.sub(line, closing_bracket_loc + 2, m_end - 1))\n -- Conceal the opening '['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc - 1,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the ']('\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc + 1,\n conceal = is_url and \" \" or \"\",\n }\n )\n -- Conceal the URL part 'xxx' with the external URL character\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 1,\n conceal = is_url and ui_opts.external_link_icon.char or \"\",\n hl_group = ui_opts.external_link_icon.hl_group,\n }\n )\n -- Conceal the closing ')'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = is_url and \" \" or \"\",\n }\n )\n elseif m_type == search.RefTypes.NakedUrl then\n -- A \"naked\" URL is just a URL by itself, like 'https://github.com/'\n local domain_start_loc = string.find(line, \"://\", m_start, true)\n assert(domain_start_loc)\n domain_start_loc = domain_start_loc + 3\n -- Conceal the \"https?://\" part\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = domain_start_loc - 1,\n conceal = \"\",\n }\n )\n -- Highlight the whole thing.\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.Tag then\n -- A tag is like '#tag'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.tags.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.BlockID then\n -- A block ID, like '^hello-world'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.block_ids.hl_group,\n spell = false,\n }\n )\n end\n end\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_highlight(line)\n for match in iter(matches) do\n local m_start, m_end, _ = unpack(match)\n -- Conceal opening '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight text in the middle\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.highlight_text.hl_group,\n spell = false,\n }\n )\n -- Conceal closing '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n end\n return marks\nend\n\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal get_line_marks = function(line, lnum, ui_opts)\n local marks = {}\n get_line_check_extmarks(marks, line, lnum, ui_opts)\n get_line_ref_extmarks(marks, line, lnum, ui_opts)\n get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n return marks\nend\n\n---@param bufnr integer\n---@param ui_opts obsidian.config.UIOpts\nlocal function update_extmarks(bufnr, ns_id, ui_opts)\n local start_time = vim.uv.hrtime()\n local n_marks_added = 0\n local n_marks_cleared = 0\n\n -- Collect all current marks, grouped by line.\n local cur_marks_by_line = vim.defaulttable()\n for mark in iter(ExtMark.collect(bufnr, ns_id)) do\n local cur_line_marks = cur_marks_by_line[mark.row]\n cur_line_marks[#cur_line_marks + 1] = mark\n end\n\n -- Iterate over lines (skipping code blocks) and update marks.\n local inside_code_block = false\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, true)\n for i, line in ipairs(lines) do\n local lnum = i - 1\n local cur_line_marks = cur_marks_by_line[lnum]\n\n local function clear_line()\n ExtMark.clear_line(bufnr, ns_id, lnum)\n n_marks_cleared = n_marks_cleared + #cur_line_marks\n for mark in iter(cur_line_marks) do\n cache_evict(bufnr, ns_id, mark.id)\n end\n end\n\n -- Check if inside a code block or at code block boundary. If not, update marks.\n if string.match(line, \"^%s*```[^`]*$\") then\n inside_code_block = not inside_code_block\n -- Remove any existing marks here on the boundary of a code block.\n clear_line()\n elseif not inside_code_block then\n -- Get all marks that should be materialized.\n -- Some of these might already be materialized, which we'll check below and avoid re-drawing\n -- if that's the case.\n local new_line_marks = get_line_marks(line, lnum, ui_opts)\n if #new_line_marks > 0 then\n -- Materialize new marks.\n for mark in iter(new_line_marks) do\n if not vim.list_contains(cur_line_marks, mark) then\n mark:materialize(bufnr, ns_id)\n n_marks_added = n_marks_added + 1\n end\n end\n\n -- Clear old marks.\n for mark in iter(cur_line_marks) do\n if not vim.list_contains(new_line_marks, mark) then\n mark:clear(bufnr, ns_id)\n n_marks_cleared = n_marks_cleared + 1\n end\n end\n else\n -- Remove any existing marks here since there are no new marks.\n clear_line()\n end\n else\n -- Remove any existing marks here since we're inside a code block.\n clear_line()\n end\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n log.debug(\"Added %d new marks, cleared %d old marks in %dms\", n_marks_added, n_marks_cleared, runtime)\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param bufnr integer|?\n---@return boolean\nlocal function should_update(ui_opts, bufnr)\n if ui_opts.enable == false then\n return false\n end\n\n bufnr = bufnr or 0\n\n if not vim.endswith(vim.api.nvim_buf_get_name(bufnr), \".md\") then\n return false\n end\n\n if ui_opts.max_file_length ~= nil and vim.fn.line \"$\" > ui_opts.max_file_length then\n return false\n end\n\n return true\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param throttle boolean\n---@return function\nlocal function get_extmarks_autocmd_callback(ui_opts, throttle)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n\n local callback = function(ev)\n if not should_update(ui_opts, ev.bufnr) then\n return\n end\n update_extmarks(ev.buf, ns_id, ui_opts)\n end\n\n if throttle then\n return require(\"obsidian.async\").throttle(callback, ui_opts.update_debounce)\n else\n return callback\n end\nend\n\n---Manually update extmarks.\n---\n---@param bufnr integer|?\nM.update = function(bufnr)\n bufnr = bufnr or 0\n local ui_opts = Obsidian.opts.ui\n if not should_update(ui_opts, bufnr) then\n return\n end\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n update_extmarks(bufnr, ns_id, ui_opts)\nend\n\n---@param workspace obsidian.Workspace\n---@param ui_opts obsidian.config.UIOpts\nM.setup = function(workspace, ui_opts)\n if ui_opts.enable == false then\n return\n end\n\n local group = vim.api.nvim_create_augroup(\"ObsidianUI\" .. workspace.name, { clear = true })\n\n install_hl_groups(ui_opts)\n\n local pattern = tostring(workspace.root) .. \"/**.md\"\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = function()\n local conceallevel = vim.opt_local.conceallevel:get()\n\n if (conceallevel < 1 or conceallevel > 2) and not ui_opts.ignore_conceal_warn then\n log.warn_once(\n \"Obsidian additional syntax features require 'conceallevel' to be set to 1 or 2, \"\n .. \"but you have 'conceallevel' set to '%s'.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/issues/286 for more details.\\n\"\n .. \"If you don't want Obsidian's additional UI features, you can disable them and suppress \"\n .. \"this warning by setting 'ui.enable = false' in your Obsidian nvim config.\",\n conceallevel\n )\n end\n\n -- delete the autocommand\n return true\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, false),\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\", \"TextChanged\", \"TextChangedI\", \"TextChangedP\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, true),\n })\n\n vim.api.nvim_create_autocmd({ \"BufUnload\" }, {\n group = group,\n pattern = pattern,\n callback = function(ev)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n cache_clear(ev.buf, ns_id)\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/footer/init.lua", "local M = {}\nlocal api = require \"obsidian.api\"\n\nlocal ns_id = vim.api.nvim_create_namespace \"ObsidianFooter\"\n\n--- Register buffer-specific variables\nM.start = function(client)\n local refresh_info = function(buf)\n local note = api.current_note(buf)\n if not note then\n return\n end\n local info = {}\n local wc = vim.fn.wordcount()\n info.words = wc.words\n info.chars = wc.chars\n info.properties = vim.tbl_count(note:frontmatter())\n info.backlinks = #client:find_backlinks(note)\n return info\n end\n\n local function update_obsidian_footer(buf)\n local info = refresh_info(buf)\n if info == nil then\n return\n end\n local footer_text = assert(Obsidian.opts.footer.format)\n for k, v in pairs(info) do\n footer_text = footer_text:gsub(\"{{\" .. k .. \"}}\", v)\n end\n local row0 = #vim.api.nvim_buf_get_lines(buf, 0, -2, false)\n local col0 = 0\n local separator = Obsidian.opts.footer.separator\n local hl_group = Obsidian.opts.footer.hl_group\n local footer_contents = { { footer_text, hl_group } }\n local footer_chunks\n if separator then\n local footer_separator = { { separator, hl_group } }\n footer_chunks = { footer_separator, footer_contents }\n else\n footer_chunks = { footer_contents }\n end\n local opts = { virt_lines = footer_chunks }\n vim.api.nvim_buf_clear_namespace(buf, ns_id, 0, -1)\n vim.api.nvim_buf_set_extmark(buf, ns_id, row0, col0, opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_footer\", {})\n local attached_bufs = {}\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n desc = \"Initialize obsidian footer\",\n pattern = \"ObsidianNoteEnter\",\n callback = function(ev)\n if attached_bufs[ev.buf] then\n return\n end\n vim.schedule(function()\n update_obsidian_footer(ev.buf)\n end)\n local id = vim.api.nvim_create_autocmd({\n \"FileChangedShellPost\",\n \"TextChanged\",\n \"TextChangedI\",\n \"TextChangedP\",\n }, {\n group = group,\n desc = \"Update obsidian footer\",\n buffer = ev.buf,\n callback = vim.schedule_wrap(function()\n update_obsidian_footer(ev.buf)\n end),\n })\n attached_bufs[ev.buf] = id\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/_telescope.lua", "local telescope = require \"telescope.builtin\"\nlocal telescope_actions = require \"telescope.actions\"\nlocal actions_state = require \"telescope.actions.state\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.pickers.TelescopePicker : obsidian.Picker\nlocal TelescopePicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"TelescopePicker()\"\n end,\n}, Picker)\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@return table|?\nlocal function get_entry(prompt_bufnr, keep_open)\n local entry = actions_state.get_selected_entry()\n if entry and not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return entry\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param allow_multiple boolean|?\n---@return table[]|?\nlocal function get_selected(prompt_bufnr, keep_open, allow_multiple)\n local picker = actions_state.get_current_picker(prompt_bufnr)\n local entries = picker:get_multi_selection()\n if entries and #entries > 0 then\n if #entries > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n\n return entries\n else\n local entry = get_entry(prompt_bufnr, keep_open)\n\n if entry then\n return { entry }\n end\n end\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param initial_query string|?\n---@return string|?\nlocal function get_query(prompt_bufnr, keep_open, initial_query)\n local query = actions_state.get_current_line()\n if not query or string.len(query) == 0 then\n query = initial_query\n end\n if query and string.len(query) > 0 then\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return query\n else\n return nil\n end\nend\n\n---@param opts { entry_key: string|?, callback: fun(path: string)|?, allow_multiple: boolean|?, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|?, initial_query: string|? }\nlocal function attach_picker_mappings(map, opts)\n -- Docs for telescope actions:\n -- https://github.com/nvim-telescope/telescope.nvim/blob/master/lua/telescope/actions/init.lua\n\n local function entry_to_value(entry)\n if opts.entry_key then\n return entry[opts.entry_key]\n else\n return entry\n end\n end\n\n if opts.query_mappings then\n for key, mapping in pairs(opts.query_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local query = get_query(prompt_bufnr, false, opts.initial_query)\n if query then\n mapping.callback(query)\n end\n end)\n end\n end\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, mapping.keep_open, mapping.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n mapping.callback(unpack(values))\n elseif mapping.fallback_to_query then\n local query = get_query(prompt_bufnr, mapping.keep_open)\n if query then\n mapping.callback(query)\n end\n end\n end)\n end\n end\n\n if opts.callback then\n map({ \"i\", \"n\" }, \"\", function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, false, opts.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n opts.callback(unpack(values))\n end\n end)\n end\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nTelescopePicker.find_files = function(self, opts)\n opts = opts or {}\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n telescope.find_files {\n prompt_title = prompt_title,\n cwd = opts.dir and tostring(opts.dir) or tostring(Obsidian.dir),\n find_command = self:_build_find_cmd(),\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nTelescopePicker.grep = function(self, opts)\n opts = opts or {}\n\n local cwd = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n initial_query = opts.query,\n })\n return true\n end\n\n if opts.query and string.len(opts.query) > 0 then\n telescope.grep_string {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n search = opts.query,\n attach_mappings = attach_mappings,\n }\n else\n telescope.live_grep {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n attach_mappings = attach_mappings,\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\nTelescopePicker.pick = function(self, values, opts)\n local pickers = require \"telescope.pickers\"\n local finders = require \"telescope.finders\"\n local conf = require \"telescope.config\"\n local make_entry = require \"telescope.make_entry\"\n\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local picker_opts = {\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"value\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\n\n local displayer = function(entry)\n return self:_make_display(entry.raw)\n end\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local previewer\n if type(values[1]) == \"table\" then\n previewer = conf.values.grep_previewer(picker_opts)\n -- Get theme to use.\n if conf.pickers then\n for _, picker_name in ipairs { \"grep_string\", \"live_grep\", \"find_files\" } do\n local picker_conf = conf.pickers[picker_name]\n if picker_conf and picker_conf.theme then\n picker_opts =\n vim.tbl_extend(\"force\", picker_opts, require(\"telescope.themes\")[\"get_\" .. picker_conf.theme] {})\n break\n end\n end\n end\n end\n\n local make_entry_from_string = make_entry.gen_from_string(picker_opts)\n\n pickers\n .new(picker_opts, {\n prompt_title = prompt_title,\n finder = finders.new_table {\n results = values,\n entry_maker = function(v)\n if type(v) == \"string\" then\n return make_entry_from_string(v)\n else\n local ordinal = v.ordinal\n if ordinal == nil then\n ordinal = \"\"\n if type(v.display) == \"string\" then\n ordinal = ordinal .. v.display\n end\n if v.filename ~= nil then\n ordinal = ordinal .. \" \" .. v.filename\n end\n end\n\n return {\n value = v.value,\n display = displayer,\n ordinal = ordinal,\n filename = v.filename,\n valid = v.valid,\n lnum = v.lnum,\n col = v.col,\n raw = v,\n }\n end\n end,\n },\n sorter = conf.values.generic_sorter(picker_opts),\n previewer = previewer,\n })\n :find()\nend\n\nreturn TelescopePicker\n"], ["/obsidian.nvim/lua/obsidian/commands/follow_link.lua", "local api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local opts = {}\n if data.args and string.len(data.args) > 0 then\n opts.open_strategy = data.args\n end\n\n local link = api.cursor_link()\n\n if link then\n api.follow_link(link, opts)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/pickers/_fzf.lua", "local fzf = require \"fzf-lua\"\nlocal fzf_actions = require \"fzf-lua.actions\"\nlocal entry_to_file = require(\"fzf-lua.path\").entry_to_file\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@param prompt_title string|?\n---@return string|?\nlocal function format_prompt(prompt_title)\n if not prompt_title then\n return\n else\n return prompt_title .. \" ❯ \"\n end\nend\n\n---@param keymap string\n---@return string\nlocal function format_keymap(keymap)\n keymap = string.lower(keymap)\n keymap = string.gsub(keymap, vim.pesc \"\", \"\")\n return keymap\nend\n\n---@class obsidian.pickers.FzfPicker : obsidian.Picker\nlocal FzfPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"FzfPicker()\"\n end,\n}, Picker)\n\n---@param opts { callback: fun(path: string)|?, no_default_mappings: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_path_actions(opts)\n local actions = {\n default = function(selected, fzf_opts)\n if not opts.no_default_mappings then\n fzf_actions.file_edit_or_qf(selected, fzf_opts)\n end\n\n if opts.callback then\n local path = entry_to_file(selected[1], fzf_opts).path\n opts.callback(path)\n end\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected, fzf_opts)\n local path = entry_to_file(selected[1], fzf_opts).path\n mapping.callback(path)\n end\n end\n end\n\n return actions\nend\n\n---@param display_to_value_map table\n---@param opts { callback: fun(path: string)|?, allow_multiple: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_value_actions(display_to_value_map, opts)\n ---@param allow_multiple boolean|?\n ---@return any[]|?\n local function get_values(selected, allow_multiple)\n if not selected then\n return\n end\n\n local values = vim.tbl_map(function(k)\n return display_to_value_map[k]\n end, selected)\n\n values = vim.tbl_filter(function(v)\n return v ~= nil\n end, values)\n\n if #values > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if #values > 0 then\n return values\n else\n return nil\n end\n end\n\n local actions = {\n default = function(selected)\n if not opts.callback then\n return\n end\n\n local values = get_values(selected, opts.allow_multiple)\n if not values then\n return\n end\n\n opts.callback(unpack(values))\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected)\n local values = get_values(selected, mapping.allow_multiple)\n if not values then\n return\n end\n\n mapping.callback(unpack(values))\n end\n end\n end\n\n return actions\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nFzfPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path.new(opts.dir) or Obsidian.dir\n\n fzf.files {\n cwd = tostring(dir),\n cmd = table.concat(self:_build_find_cmd(), \" \"),\n actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n },\n prompt = format_prompt(opts.prompt_title),\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nFzfPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n local cmd = table.concat(self:_build_grep_cmd(), \" \")\n local actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n if opts.query and string.len(opts.query) > 0 then\n fzf.grep {\n cwd = tostring(dir),\n search = opts.query,\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n else\n fzf.live_grep {\n cwd = tostring(dir),\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nFzfPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n ---@type table\n local display_to_value_map = {}\n\n ---@type string[]\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n display_to_value_map[value] = value\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n local display = self:_make_display(value)\n display_to_value_map[display] = value.value\n entries[#entries + 1] = display\n end\n end\n\n fzf.fzf_exec(entries, {\n prompt = format_prompt(\n self:_build_prompt { prompt_title = opts.prompt_title, selection_mappings = opts.selection_mappings }\n ),\n actions = get_value_actions(display_to_value_map, {\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n selection_mappings = opts.selection_mappings,\n }),\n })\nend\n\nreturn FzfPicker\n"], ["/obsidian.nvim/lua/obsidian/health.lua", "local M = {}\nlocal VERSION = require \"obsidian.version\"\nlocal api = require \"obsidian.api\"\n\nlocal error = vim.health.error\nlocal warn = vim.health.warn\nlocal ok = vim.health.ok\n\nlocal function info(...)\n local t = { ... }\n local format = table.remove(t, 1)\n local str = #t == 0 and format or string.format(format, unpack(t))\n return ok(str)\nend\n\n---@private\n---@param name string\nlocal function start(name)\n vim.health.start(string.format(\"obsidian.nvim [%s]\", name))\nend\n\n---@param plugin string\n---@param optional boolean\n---@return boolean\nlocal function has_plugin(plugin, optional)\n local plugin_info = api.get_plugin_info(plugin)\n if plugin_info then\n info(\"%s: %s\", plugin, plugin_info.commit or \"unknown\")\n return true\n else\n if not optional then\n vim.health.error(\" \" .. plugin .. \" not installed\")\n end\n return false\n end\nend\n\nlocal function has_executable(name, optional)\n if vim.fn.executable(name) == 1 then\n local version = api.get_external_dependency_info(name)\n if version then\n info(\"%s: %s\", name, version)\n else\n info(\"%s: found\", name)\n end\n return true\n else\n if not optional then\n error(string.format(\"%s not found\", name))\n end\n return false\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_plugin(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of_executable(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_executable(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param minimum string\n---@param recommended string\nlocal function neovim(minimum, recommended)\n if vim.fn.has(\"nvim-\" .. minimum) == 0 then\n error(\"neovim < \" .. minimum)\n elseif vim.fn.has(\"nvim-\" .. recommended) == 0 then\n warn(\"neovim < \" .. recommended .. \" some features will not work\")\n else\n ok(\"neovim >= \" .. recommended)\n end\nend\n\nfunction M.check()\n local os = api.get_os()\n neovim(\"0.10\", \"0.11\")\n start \"Version\"\n info(\"obsidian.nvim v%s (%s)\", VERSION, api.get_plugin_info(\"obsidian.nvim\").commit)\n\n start \"Environment\"\n info(\"operating system: %s\", os)\n\n start \"Config\"\n info(\" • dir: %s\", Obsidian.dir)\n\n start \"Pickers\"\n\n has_one_of {\n \"telescope.nvim\",\n \"fzf-lua\",\n \"mini.nvim\",\n \"mini.pick\",\n \"snacks.nvim\",\n }\n\n start \"Completion\"\n\n has_one_of {\n \"nvim-cmp\",\n \"blink.cmp\",\n }\n\n start \"Dependencies\"\n has_executable(\"rg\", false)\n has_plugin(\"plenary.nvim\", false)\n\n if os == api.OSType.Wsl then\n has_executable(\"wsl-open\", true)\n elseif os == api.OSType.Linux then\n has_one_of_executable {\n \"xclip\",\n \"wl-paste\",\n }\n elseif os == api.OSType.Darwin then\n has_executable(\"pngpaste\", true)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/yaml/parser.lua", "local Line = require \"obsidian.yaml.line\"\nlocal abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\n\nlocal m = {}\n\n---@class obsidian.yaml.ParserOpts\n---@field luanil boolean\nlocal ParserOpts = {}\n\nm.ParserOpts = ParserOpts\n\n---@return obsidian.yaml.ParserOpts\nParserOpts.default = function()\n return {\n luanil = true,\n }\nend\n\n---@param opts table\n---@return obsidian.yaml.ParserOpts\nParserOpts.normalize = function(opts)\n ---@type obsidian.yaml.ParserOpts\n opts = vim.tbl_extend(\"force\", ParserOpts.default(), opts)\n return opts\nend\n\n---@class obsidian.yaml.Parser : obsidian.ABC\n---@field opts obsidian.yaml.ParserOpts\nlocal Parser = abc.new_class()\n\nm.Parser = Parser\n\n---@enum YamlType\nlocal YamlType = {\n Scalar = \"Scalar\", -- a boolean, string, number, or NULL\n Mapping = \"Mapping\",\n Array = \"Array\",\n ArrayItem = \"ArrayItem\",\n EmptyLine = \"EmptyLine\",\n}\n\nm.YamlType = YamlType\n\n---@class vim.NIL\n\n---Create a new Parser.\n---@param opts obsidian.yaml.ParserOpts|?\n---@return obsidian.yaml.Parser\nm.new = function(opts)\n local self = Parser.init()\n self.opts = ParserOpts.normalize(opts and opts or {})\n return self\nend\n\n---Parse a YAML string.\n---@param str string\n---@return any\nParser.parse = function(self, str)\n -- Collect and pre-process lines.\n local lines = {}\n local base_indent = 0\n for raw_line in str:gmatch \"[^\\r\\n]+\" do\n local ok, result = pcall(Line.new, raw_line, base_indent)\n if ok then\n local line = result\n if #lines == 0 then\n base_indent = line.indent\n line.indent = 0\n end\n table.insert(lines, line)\n else\n local err = result\n error(self:_error_msg(tostring(err), #lines + 1))\n end\n end\n\n -- Now iterate over the root elements, differing to `self:_parse_next()` to recurse into child elements.\n ---@type any\n local root_value = nil\n ---@type table|?\n local parent = nil\n local current_indent = 0\n local i = 1\n while i <= #lines do\n local line = lines[i]\n\n if line:is_empty() then\n -- Empty line, skip it.\n i = i + 1\n elseif line.indent == current_indent then\n local value\n local value_type\n i, value, value_type = self:_parse_next(lines, i)\n assert(value_type ~= YamlType.EmptyLine)\n if root_value == nil and line.indent == 0 then\n -- Set the root value.\n if value_type == YamlType.ArrayItem then\n root_value = { value }\n else\n root_value = value\n end\n\n -- The parent must always be a table (array or mapping), so set that to the root value now\n -- if we have a table.\n if type(root_value) == \"table\" then\n parent = root_value\n end\n elseif util.islist(parent) and value_type == YamlType.ArrayItem then\n -- Add value to parent array.\n parent[#parent + 1] = value\n elseif type(parent) == \"table\" and value_type == YamlType.Mapping then\n assert(parent ~= nil) -- for type checking\n -- Add value to parent mapping.\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if parent[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i, line.content))\n else\n parent[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value\", i, line.content))\n end\n else\n error(self:_error_msg(\"invalid indentation\", i))\n end\n current_indent = line.indent\n end\n\n return root_value\nend\n\n---Parse the next single item, recursing to child blocks if necessary.\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@param text string|?\n---@return integer, any, string\nParser._parse_next = function(self, lines, i, text)\n local line = lines[i]\n if text == nil then\n -- Skip empty lines.\n while line:is_empty() and i <= #lines do\n i = i + 1\n line = lines[i]\n end\n if line:is_empty() then\n return i, nil, YamlType.EmptyLine\n end\n text = util.strip_comments(line.content)\n end\n\n local _, ok, value\n\n -- First just check for a string enclosed in quotes.\n if util.has_enclosing_chars(text) then\n _, _, value = self:_parse_string(i, text)\n return i + 1, value, YamlType.Scalar\n end\n\n -- Check for array item, like `- foo`.\n ok, i, value = self:_try_parse_array_item(lines, i, text)\n if ok then\n return i, value, YamlType.ArrayItem\n end\n\n -- Check for a block string field, like `foo: |`.\n ok, i, value = self:_try_parse_block_string(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Check for any other `key: value` fields.\n ok, i, value = self:_try_parse_field(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Otherwise we have an inline value.\n local value_type\n value, value_type = self:_parse_inline_value(i, text)\n return i + 1, value, value_type\nend\n\n---@return vim.NIL|nil\nParser._new_null = function(self)\n if self.opts.luanil then\n return nil\n else\n return vim.NIL\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param msg string\n---@param line_num integer\n---@param line_text string|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nParser._error_msg = function(self, msg, line_num, line_text)\n local full_msg = \"[line=\" .. tostring(line_num) .. \"] \" .. msg\n if line_text ~= nil then\n full_msg = full_msg .. \" (text='\" .. line_text .. \"')\"\n end\n return full_msg\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_field = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n\n local _, key, value\n\n -- First look for start of mapping, array, block, etc, e.g. 'foo:'\n _, _, key = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*):$\")\n if not key then\n -- Then try inline field, e.g. 'foo: bar'\n _, _, key, value = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*): (.*)\")\n end\n\n value = value and vim.trim(value) or nil\n if value == \"\" then\n value = nil\n end\n\n if key ~= nil and value ~= nil then\n -- This is a mapping, e.g. `foo: 1`.\n local out = {}\n value = self:_parse_inline_value(i, value)\n local j = i + 1\n -- Check for multi-line string here.\n local next_line = lines[j]\n if type(value) == \"string\" and next_line ~= nil and next_line.indent > line.indent then\n local next_indent = next_line.indent\n while next_line ~= nil and next_line.indent == next_indent do\n local next_value_str = util.strip_comments(next_line.content)\n if string.len(next_value_str) > 0 then\n local next_value = self:_parse_inline_value(j, next_line.content)\n if type(next_value) ~= \"string\" then\n error(self:_error_msg(\"expected a string, found \" .. type(next_value), j, next_line.content))\n end\n value = value .. \" \" .. next_value\n end\n j = j + 1\n next_line = lines[j]\n end\n end\n out[key] = value\n return true, j, out\n elseif key ~= nil then\n local out = {}\n local next_line = lines[i + 1]\n local j = i + 1\n if next_line ~= nil and next_line.indent >= line.indent and vim.startswith(next_line.content, \"- \") then\n -- This is the start of an array.\n local array\n j, array = self:_parse_array(lines, j)\n out[key] = array\n elseif next_line ~= nil and next_line.indent > line.indent then\n -- This is the start of a mapping.\n local mapping\n j, mapping = self:_parse_mapping(j, lines)\n out[key] = mapping\n else\n -- This is an implicit null field.\n out[key] = self:_new_null()\n end\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_block_string = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n local _, _, block_key = string.find(text, \"([a-zA-Z0-9_-]+):%s?|\")\n if block_key ~= nil then\n local block_lines = {}\n local j = i + 1\n local next_line = lines[j]\n if next_line == nil then\n error(self:_error_msg(\"expected another line\", i, text))\n end\n local item_indent = next_line.indent\n while j <= #lines do\n next_line = lines[j]\n if next_line ~= nil and next_line.indent >= item_indent then\n j = j + 1\n table.insert(block_lines, util.lstrip_whitespace(next_line.raw_content, item_indent))\n else\n break\n end\n end\n local out = {}\n out[block_key] = table.concat(block_lines, \"\\n\")\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_array_item = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n if vim.startswith(text, \"- \") then\n local _, _, array_item_str = string.find(text, \"- (.*)\")\n local value\n -- Check for null entry.\n if array_item_str == \"\" then\n value = self:_new_null()\n i = i + 1\n else\n i, value = self:_parse_next(lines, i, array_item_str)\n end\n return true, i, value\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@return integer, any[]\nParser._parse_array = function(self, lines, i)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent and vim.startswith(line.content, \"- \") then\n local is_array_item, value\n is_array_item, i, value = self:_try_parse_array_item(lines, i)\n assert(is_array_item)\n out[#out + 1] = value\n elseif line:is_empty() then\n i = i + 1\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse an array but didn't find any entries\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@return integer, table\nParser._parse_mapping = function(self, i, lines)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent then\n local value, value_type\n i, value, value_type = self:_parse_next(lines, i)\n if value_type == YamlType.Mapping then\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if out[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i))\n else\n out[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value found found in table\", i))\n end\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse a mapping but didn't find any entries to parse\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return any, string\nParser._parse_inline_value = function(self, i, text)\n for parse_func_and_type in iter {\n { self._parse_number, YamlType.Scalar },\n { self._parse_null, YamlType.Scalar },\n { self._parse_boolean, YamlType.Scalar },\n { self._parse_inline_array, YamlType.Array },\n { self._parse_inline_mapping, YamlType.Mapping },\n { self._parse_string, YamlType.Scalar },\n } do\n local parse_func, parse_type = unpack(parse_func_and_type)\n local ok, errmsg, res = parse_func(self, i, text)\n if ok then\n return res, parse_type\n elseif errmsg ~= nil then\n error(errmsg)\n end\n end\n -- Should never get here because we always fall back to parsing as a string.\n error(self:_error_msg(\"unable to parse\", i))\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, any[]|?\nParser._parse_inline_array = function(self, i, text)\n local str\n if vim.startswith(text, \"[\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"]\") then\n str = string.sub(str, 1, -2)\n else\n return false, nil, nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n local item_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n item_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n item_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n item_str, str = util.next_item(str, { \",\" }, false)\n end\n if item_str == nil then\n return false, self:_error_msg(\"invalid inline array\", i, text), nil\n end\n out[#out + 1] = self:_parse_inline_value(i, item_str)\n\n if vim.startswith(str, \",\") then\n str = string.sub(str, 2)\n end\n str = util.lstrip_whitespace(str)\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, table|?\nParser._parse_inline_mapping = function(self, i, text)\n local str\n if vim.startswith(text, \"{\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"}\") then\n str = string.sub(str, 1, -2)\n else\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n -- Parse the key.\n local key_str\n key_str, str = util.next_item(str, { \":\" }, false)\n if key_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local _, _, key = self:_parse_string(i, key_str)\n\n -- Parse the value.\n str = util.lstrip_whitespace(str)\n local value_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n value_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n value_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n value_str, str = util.next_item(str, { \",\" }, false)\n end\n if value_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local value = self:_parse_inline_value(i, value_str)\n if out[key] == nil then\n out[key] = value\n else\n return false, self:_error_msg(\"duplicate key '\" .. key .. \"' found in inline mapping\", i, text), nil\n end\n\n if vim.startswith(str, \",\") then\n str = util.lstrip_whitespace(string.sub(str, 2))\n end\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, string\n---@diagnostic disable-next-line: unused-local\nParser._parse_string = function(self, i, text)\n if vim.startswith(text, [[\"]]) and vim.endswith(text, [[\"]]) then\n -- when the text is enclosed with double-quotes we need to un-escape certain characters.\n text = string.gsub(text, vim.pesc [[\\\"]], [[\"]])\n end\n return true, nil, util.strip_enclosing_chars(vim.trim(text))\nend\n\n---Parse a string value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return string\nParser.parse_string = function(self, text)\n local _, _, str = self:_parse_string(1, util.strip_comments(text))\n return str\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, number|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_number = function(self, i, text)\n local out = tonumber(text)\n if out == nil or util.isNan(out) then\n return false, nil, nil\n else\n return true, nil, out\n end\nend\n\n---Parse a number value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return number\nParser.parse_number = function(self, text)\n local ok, errmsg, res = self:_parse_number(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a number\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, boolean|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_boolean = function(self, i, text)\n if text == \"true\" then\n return true, nil, true\n elseif text == \"false\" then\n return true, nil, false\n else\n return false, nil, nil\n end\nend\n\n---Parse a boolean value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean\nParser.parse_boolean = function(self, text)\n local ok, errmsg, res = self:_parse_boolean(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a boolean\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean, string|?, vim.NIL|nil\n---@diagnostic disable-next-line: unused-local\nParser._parse_null = function(self, i, text)\n if text == \"null\" or text == \"\" then\n return true, nil, self:_new_null()\n else\n return false, nil, nil\n end\nend\n\n---Parse a NULL value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return vim.NIL|nil\nParser.parse_null = function(self, text)\n local ok, errmsg, res = self:_parse_null(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a null value\", 1, text)\n error(errmsg)\n else\n return res\n end\nend\n\n---Deserialize a YAML string.\nm.loads = function(str)\n local parser = m.new()\n return parser:parse(str)\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/commands/links.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local picker = Obsidian.picker\n if not picker then\n return log.err \"No picker configured\"\n end\n\n local note = api.current_note(0)\n assert(note, \"not in a note\")\n\n search.find_links(note, {}, function(entries)\n entries = vim.tbl_map(function(match)\n return match.link\n end, entries)\n\n -- Launch picker.\n picker:pick(entries, {\n prompt_title = \"Links\",\n callback = function(link)\n api.follow_link(link)\n end,\n })\n end)\nend\n"], ["/obsidian.nvim/lua/obsidian/statusline/init.lua", "local M = {}\nlocal uv = vim.uv\nlocal api = require \"obsidian.api\"\n\n--- Register the global variable that updates itself\nM.start = function(client)\n local current_note\n\n local refresh = function()\n local note = api.current_note()\n if not note then -- no note\n return \"\"\n elseif current_note == note then -- no refresh\n return\n else -- refresh\n current_note = note\n end\n\n client:find_backlinks_async(\n note,\n vim.schedule_wrap(function(backlinks)\n local format = assert(Obsidian.opts.statusline.format)\n local wc = vim.fn.wordcount()\n local info = {\n words = wc.words,\n chars = wc.chars,\n backlinks = #backlinks,\n properties = vim.tbl_count(note:frontmatter()),\n }\n for k, v in pairs(info) do\n format = format:gsub(\"{{\" .. k .. \"}}\", v)\n end\n vim.g.obsidian = format\n end)\n )\n end\n\n local timer = uv:new_timer()\n assert(timer, \"Failed to create timer\")\n timer:start(0, 1000, vim.schedule_wrap(refresh))\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/yaml/init.lua", "local util = require \"obsidian.util\"\nlocal parser = require \"obsidian.yaml.parser\"\n\nlocal yaml = {}\n\n---Deserialize a YAML string.\n---@param str string\n---@return any\nyaml.loads = function(str)\n return parser.loads(str)\nend\n\n---@param s string\n---@return boolean\nlocal should_quote = function(s)\n -- TODO: this probably doesn't cover all edge cases.\n -- See https://www.yaml.info/learn/quote.html\n -- Check if it starts with a special character.\n if string.match(s, [[^[\"'\\\\[{&!-].*]]) then\n return true\n -- Check if it has a colon followed by whitespace.\n elseif string.find(s, \": \", 1, true) then\n return true\n -- Check if it's an empty string.\n elseif s == \"\" or string.match(s, \"^[%s]+$\") then\n return true\n else\n return false\n end\nend\n\n---@return string[]\nlocal dumps\ndumps = function(x, indent, order)\n local indent_str = string.rep(\" \", indent)\n\n if type(x) == \"string\" then\n if should_quote(x) then\n x = string.gsub(x, '\"', '\\\\\"')\n return { indent_str .. [[\"]] .. x .. [[\"]] }\n else\n return { indent_str .. x }\n end\n end\n\n if type(x) == \"boolean\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"number\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"table\" then\n local out = {}\n\n if util.islist(x) then\n for _, v in ipairs(x) do\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. \"- \" .. util.lstrip_whitespace(item_lines[1]))\n for i = 2, #item_lines do\n table.insert(out, item_lines[i])\n end\n end\n else\n -- Gather and sort keys so we can keep the order deterministic.\n local keys = {}\n for k, _ in pairs(x) do\n table.insert(keys, k)\n end\n table.sort(keys, order)\n for _, k in ipairs(keys) do\n local v = x[k]\n if type(v) == \"string\" or type(v) == \"boolean\" or type(v) == \"number\" then\n table.insert(out, indent_str .. tostring(k) .. \": \" .. dumps(v, 0)[1])\n elseif type(v) == \"table\" and vim.tbl_isempty(v) then\n table.insert(out, indent_str .. tostring(k) .. \": []\")\n else\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. tostring(k) .. \":\")\n for _, line in ipairs(item_lines) do\n table.insert(out, line)\n end\n end\n end\n end\n\n return out\n end\n\n error(\"Can't convert object with type \" .. type(x) .. \" to YAML\")\nend\n\n---Dump an object to YAML lines.\n---@param x any\n---@param order function\n---@return string[]\nyaml.dumps_lines = function(x, order)\n return dumps(x, 0, order)\nend\n\n---Dump an object to a YAML string.\n---@param x any\n---@param order function|?\n---@return string\nyaml.dumps = function(x, order)\n return table.concat(dumps(x, 0, order), \"\\n\")\nend\n\nreturn yaml\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/tags.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal iter = vim.iter\nlocal obsidian = require \"obsidian\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.TagsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field in_frontmatter boolean|?\nlocal TagsSourceCompletionContext = abc.new_class()\n\nTagsSourceCompletionContext.new = function()\n return TagsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.TagsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal TagsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.TagsSourceBase\nTagsSourceBase.new = function()\n return TagsSourceBase.init()\nend\n\nTagsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = TagsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n local search_opts = cc.client.search_defaults()\n search_opts.sort = false\n\n cc.client:find_tags_async(cc.search, function(tag_locs)\n local tags = {}\n for tag_loc in iter(tag_locs) do\n tags[tag_loc.tag] = true\n end\n\n local items = {}\n for tag, _ in pairs(tags) do\n -- Generate context-appropriate text\n local insert_text, label_text\n if cc.in_frontmatter then\n -- Frontmatter: insert tag without # (YAML format)\n insert_text = tag\n label_text = \"Tag: \" .. tag\n else\n -- Document body: insert tag with # (Obsidian format)\n insert_text = \"#\" .. tag\n label_text = \"Tag: #\" .. tag\n end\n\n -- Calculate the range to replace (the entire #tag pattern)\n local cursor_before = cc.request.context.cursor_before_line\n local hash_start = string.find(cursor_before, \"#[^%s]*$\")\n local insert_start = hash_start and (hash_start - 1) or #cursor_before\n local insert_end = #cursor_before\n\n items[#items + 1] = {\n sortText = \"#\" .. tag,\n label = label_text,\n kind = vim.lsp.protocol.CompletionItemKind.Text,\n textEdit = {\n newText = insert_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_end,\n },\n },\n },\n data = {\n bufnr = cc.request.context.bufnr,\n in_frontmatter = cc.in_frontmatter,\n line = cc.request.context.cursor.line,\n tag = tag,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\n end, { search = search_opts })\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction TagsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.in_frontmatter = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\nreturn TagsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/completion/refs.lua", "local util = require \"obsidian.util\"\n\nlocal M = {}\n\n---@enum obsidian.completion.RefType\nM.RefType = {\n Wiki = 1,\n Markdown = 2,\n}\n\n---Backtrack through a string to find the first occurrence of '[['.\n---\n---@param input string\n---@return string|?, string|?, obsidian.completion.RefType|?\nlocal find_search_start = function(input)\n for i = string.len(input), 1, -1 do\n local substr = string.sub(input, i)\n if vim.startswith(substr, \"]\") or vim.endswith(substr, \"]\") then\n return nil\n elseif vim.startswith(substr, \"[[\") then\n return substr, string.sub(substr, 3)\n elseif vim.startswith(substr, \"[\") and string.sub(input, i - 1, i - 1) ~= \"[\" then\n return substr, string.sub(substr, 2)\n end\n end\n return nil\nend\n\n---Check if a completion request can/should be carried out. Returns a boolean\n---and, if true, the search string and the column indices of where the completion\n---items should be inserted.\n---\n---@return boolean, string|?, integer|?, integer|?, obsidian.completion.RefType|?\nM.can_complete = function(request)\n local input, search = find_search_start(request.context.cursor_before_line)\n if input == nil or search == nil then\n return false\n elseif string.len(search) == 0 or util.is_whitespace(search) then\n return false\n end\n\n if vim.startswith(input, \"[[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 2)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]]\" and 1 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Wiki\n elseif vim.startswith(input, \"[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 1)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]\" and 0 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Markdown\n else\n return false\n end\nend\n\nM.get_trigger_characters = function()\n return { \"[\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n return [=[\\%(^\\|[^\\[]\\)\\zs\\[\\{1,2}[^\\]]\\+\\]\\{,2}]=]\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/toc.lua", "local util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local note = assert(api.current_note(0, { collect_anchor_links = true }))\n\n ---@type obsidian.PickerEntry[]\n local picker_entries = {}\n for _, anchor in pairs(note.anchor_links) do\n local display = string.rep(\"#\", anchor.level) .. \" \" .. anchor.header\n table.insert(\n picker_entries,\n { value = display, display = display, filename = tostring(note.path), lnum = anchor.line }\n )\n end\n\n -- De-duplicate and sort.\n picker_entries = util.tbl_unique(picker_entries)\n table.sort(picker_entries, function(a, b)\n return a.lnum < b.lnum\n end)\n\n local picker = assert(Obsidian.picker)\n picker:pick(picker_entries, { prompt_title = \"Table of Contents\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/builtin.lua", "---builtin functions that are default values for config options\nlocal M = {}\nlocal util = require \"obsidian.util\"\n\n---Create a new unique Zettel ID.\n---\n---@return string\nM.zettel_id = function()\n local suffix = \"\"\n for _ = 1, 4 do\n suffix = suffix .. string.char(math.random(65, 90))\n end\n return tostring(os.time()) .. \"-\" .. suffix\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_alias_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = string.format(\"#%s\", opts.anchor.header)\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.label, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = opts.anchor.anchor\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.path, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.label ~= opts.path then\n return string.format(\"[[%s%s|%s%s]]\", opts.path, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.path, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_id_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.id == nil then\n return string.format(\"[[%s%s]]\", opts.label, anchor)\n elseif opts.label ~= opts.id then\n return string.format(\"[[%s%s|%s%s]]\", opts.id, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.id, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.markdown_link = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n local path = util.urlencode(opts.path, { keep_path_sep = true })\n return string.format(\"[%s%s](%s%s)\", opts.label, header, path, anchor)\nend\n\n---@param path string\n---@return string\nM.img_text_func = function(path)\n local format_string = {\n markdown = \"![](%s)\",\n wiki = \"![[%s]]\",\n }\n local style = Obsidian.opts.preferred_link_style\n local name = vim.fs.basename(tostring(path))\n\n if style == \"markdown\" then\n name = require(\"obsidian.util\").urlencode(name)\n end\n\n return string.format(format_string[style], name)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/nvim_cmp.lua", "local M = {}\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_sources(opts)\n local cmp = require \"cmp\"\n\n cmp.register_source(\"obsidian\", require(\"obsidian.completion.sources.nvim_cmp.refs\").new())\n cmp.register_source(\"obsidian_tags\", require(\"obsidian.completion.sources.nvim_cmp.tags\").new())\n if opts.completion.create_new then\n cmp.register_source(\"obsidian_new\", require(\"obsidian.completion.sources.nvim_cmp.new\").new())\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace and configures nvim_cmp sources for the current buffer.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n local cmp = require \"cmp\"\n\n local sources = {\n { name = \"obsidian\" },\n { name = \"obsidian_tags\" },\n }\n if opts.completion.create_new then\n table.insert(sources, { name = \"obsidian_new\" })\n end\n for _, source in pairs(cmp.get_config().sources) do\n if source.name ~= \"obsidian\" and source.name ~= \"obsidian_new\" and source.name ~= \"obsidian_tags\" then\n table.insert(sources, source)\n end\n end\n ---@diagnostic disable-next-line: missing-fields\n cmp.setup.buffer { sources = sources }\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/_mini.lua", "local mini_pick = require \"mini.pick\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\n---@param entry string\n---@return string\nlocal function clean_path(entry)\n local path_end = assert(string.find(entry, \":\", 1, true))\n return string.sub(entry, 1, path_end - 1)\nend\n\n---@class obsidian.pickers.MiniPicker : obsidian.Picker\nlocal MiniPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"MiniPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nMiniPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local path = mini_pick.builtin.cli({\n command = self:_build_find_cmd(),\n }, {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n })\n\n if path and opts.callback then\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nMiniPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local pick_opts = {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n }\n\n ---@type string|?\n local result\n if opts.query and string.len(opts.query) > 0 then\n result = mini_pick.builtin.grep({ pattern = opts.query }, pick_opts)\n else\n result = mini_pick.builtin.grep_live({}, pick_opts)\n end\n\n if result and opts.callback then\n local path = clean_path(result)\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nMiniPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n entries[#entries + 1] = {\n value = value.value,\n text = self:_make_display(value),\n path = value.filename,\n lnum = value.lnum,\n col = value.col,\n }\n end\n end\n\n local entry = mini_pick.start {\n source = {\n name = opts.prompt_title,\n items = entries,\n choose = function() end,\n },\n }\n\n if entry and opts.callback then\n if type(entry) == \"string\" then\n opts.callback(entry)\n else\n opts.callback(entry.value)\n end\n end\nend\n\nreturn MiniPicker\n"], ["/obsidian.nvim/lua/obsidian/commands/toggle_checkbox.lua", "local toggle_checkbox = require(\"obsidian.api\").toggle_checkbox\n\n---@param data CommandArgs\nreturn function(_, data)\n local start_line, end_line\n local checkboxes = Obsidian.opts.checkbox.order\n start_line = data.line1\n end_line = data.line2\n\n local buf = vim.api.nvim_get_current_buf()\n\n for line_nb = start_line, end_line do\n local current_line = vim.api.nvim_buf_get_lines(buf, line_nb - 1, line_nb, false)[1]\n if current_line and current_line:match \"%S\" then\n toggle_checkbox(checkboxes, line_nb)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/yaml/line.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\n\n---@class obsidian.yaml.Line : obsidian.ABC\n---@field content string\n---@field raw_content string\n---@field indent integer\nlocal Line = abc.new_class {\n __tostring = function(self)\n return string.format(\"Line('%s')\", self.raw_content)\n end,\n}\n\n---Create a new Line instance from a raw line string.\n---@param raw_line string\n---@param base_indent integer|?\n---@return obsidian.yaml.Line\nLine.new = function(raw_line, base_indent)\n local self = Line.init()\n self.indent = util.count_indent(raw_line)\n if base_indent ~= nil then\n if base_indent > self.indent then\n error \"relative indentation for line is less than base indentation\"\n end\n self.indent = self.indent - base_indent\n end\n self.raw_content = util.lstrip_whitespace(raw_line, base_indent)\n self.content = vim.trim(self.raw_content)\n return self\nend\n\n---Check if a line is empty.\n---@param self obsidian.yaml.Line\n---@return boolean\nLine.is_empty = function(self)\n if util.strip_comments(self.content) == \"\" then\n return true\n else\n return false\n end\nend\n\nreturn Line\n"], ["/obsidian.nvim/minimal.lua", "vim.env.LAZY_STDPATH = \".repro\"\nload(vim.fn.system \"curl -s https://raw.githubusercontent.com/folke/lazy.nvim/main/bootstrap.lua\")()\n\nvim.fn.mkdir(\".repro/vault\", \"p\")\n\nvim.o.conceallevel = 2\n\nlocal plugins = {\n {\n \"obsidian-nvim/obsidian.nvim\",\n dependencies = { \"nvim-lua/plenary.nvim\" },\n opts = {\n completion = {\n blink = true,\n nvim_cmp = false,\n },\n workspaces = {\n {\n name = \"test\",\n path = vim.fs.joinpath(vim.uv.cwd(), \".repro\", \"vault\"),\n },\n },\n },\n },\n\n -- **Choose your renderer**\n -- { \"MeanderingProgrammer/render-markdown.nvim\", dependencies = { \"echasnovski/mini.icons\" }, opts = {} },\n -- { \"OXY2DEV/markview.nvim\", lazy = false },\n\n -- **Choose your picker**\n -- \"nvim-telescope/telescope.nvim\",\n -- \"folke/snacks.nvim\",\n -- \"ibhagwan/fzf-lua\",\n -- \"echasnovski/mini.pick\",\n\n -- **Choose your completion engine**\n -- {\n -- \"hrsh7th/nvim-cmp\",\n -- config = function()\n -- local cmp = require \"cmp\"\n -- cmp.setup {\n -- mapping = cmp.mapping.preset.insert {\n -- [\"\"] = cmp.mapping.abort(),\n -- [\"\"] = cmp.mapping.confirm { select = true },\n -- },\n -- }\n -- end,\n -- },\n -- {\n -- \"saghen/blink.cmp\",\n -- opts = {\n -- fuzzy = { implementation = \"lua\" }, -- no need to build binary\n -- keymap = {\n -- preset = \"default\",\n -- },\n -- },\n -- },\n}\n\nrequire(\"lazy.minit\").repro { spec = plugins }\n\nvim.cmd \"checkhealth obsidian\"\n"], ["/obsidian.nvim/lua/obsidian/types.lua", "-- Useful type definitions go here.\n\n---@class CommandArgs\n---The table passed to user commands.\n---For details see `:help nvim_create_user_command()` and the command attribute docs\n---\n---@field name string Command name\n---@field args string The args passed to the command, if any \n---@field fargs table The args split by unescaped whitespace (when more than one argument is allowed), if any \n---@field nargs string Number of arguments |:command-nargs|\n---@field bang boolean \"true\" if the command was executed with a ! modifier \n---@field line1 number The starting line of the command range \n---@field line2 number The final line of the command range \n---@field range number The number of items in the command range: 0, 1, or 2 \n---@field count number Any count supplied \n---@field reg string The optional register, if specified \n---@field mods string Command modifiers, if any \n---@field smods table Command modifiers in a structured format. Has the same structure as the \"mods\" key of\n---@field raw_print boolean HACK: for debug command and info\n\n---@class obsidian.InsertTemplateContext\n---The table passed to user substitution functions when inserting templates into a buffer.\n---\n---@field type \"insert_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field location [number, number, number, number] `{ buf, win, row, col }` location from which the request was made.\n---@field partial_note? obsidian.Note An optional note with fields to copy from.\n\n---@class obsidian.CloneTemplateContext\n---The table passed to user substitution functions when cloning template files to create new notes.\n---\n---@field type \"clone_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field destination_path obsidian.Path The path the cloned template will be written to.\n---@field partial_note obsidian.Note The note being written.\n\n---@alias obsidian.TemplateContext obsidian.InsertTemplateContext | obsidian.CloneTemplateContext\n---The table passed to user substitution functions. Use `ctx.type` to distinguish between the different kinds.\n"], ["/obsidian.nvim/lua/obsidian/pickers/init.lua", "local PickerName = require(\"obsidian.config\").Picker\n\nlocal M = {}\n\n--- Get the default Picker.\n---\n---@param picker_name obsidian.config.Picker|?\n---\n---@return obsidian.Picker|?\nM.get = function(picker_name)\n picker_name = picker_name and picker_name or Obsidian.opts.picker.name\n if picker_name then\n picker_name = string.lower(picker_name)\n else\n for _, name in ipairs { PickerName.telescope, PickerName.fzf_lua, PickerName.mini, PickerName.snacks } do\n local ok, res = pcall(M.get, name)\n if ok then\n return res\n end\n end\n return nil\n end\n\n if picker_name == string.lower(PickerName.telescope) then\n return require(\"obsidian.pickers._telescope\").new()\n elseif picker_name == string.lower(PickerName.mini) then\n return require(\"obsidian.pickers._mini\").new()\n elseif picker_name == string.lower(PickerName.fzf_lua) then\n return require(\"obsidian.pickers._fzf\").new()\n elseif picker_name == string.lower(PickerName.snacks) then\n return require(\"obsidian.pickers._snacks\").new()\n elseif picker_name then\n error(\"not implemented for \" .. picker_name)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/abc.lua", "local M = {}\n\n---@class obsidian.ABC\n---@field init function an init function which essentially calls 'setmetatable({}, mt)'.\n---@field as_tbl function get a raw table with only the instance's fields\n---@field mt table the metatable\n\n---Create a new class.\n---\n---This handles the boilerplate of setting up metatables correctly and consistently when defining new classes,\n---and comes with some better default metamethods, like '.__eq' which will recursively compare all fields\n---that don't start with a double underscore.\n---\n---When you use this you should call `.init()` within your constructors instead of `setmetatable()`.\n---For example:\n---\n---```lua\n--- local Foo = new_class()\n---\n--- Foo.new = function(x)\n--- local self = Foo.init()\n--- self.x = x\n--- return self\n--- end\n---```\n---\n---The metatable for classes created this way is accessed with the field `.mt`. This way you can easily\n---add/override metamethods to your classes. Continuing the example above:\n---\n---```lua\n--- Foo.mt.__tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end\n---\n--- local foo = Foo.new(1)\n--- print(foo)\n---```\n---\n---Alternatively you can pass metamethods directly to 'new_class()'. For example:\n---\n---```lua\n--- local Foo = new_class {\n--- __tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end,\n--- }\n---```\n---\n---@param metamethods table|? {string, function} - Metamethods\n---@param base_class table|? A base class to start from\n---@return obsidian.ABC\nM.new_class = function(metamethods, base_class)\n local class = base_class and base_class or {}\n\n -- Metatable for the class so that all instances have the same metatable.\n class.mt = vim.tbl_extend(\"force\", {\n __index = class,\n __eq = function(a, b)\n -- In order to use 'vim.deep_equal' we need to pull out the raw fields first.\n -- If we passed 'a' and 'b' directly to 'vim.deep_equal' we'd get a stack overflow due\n -- to infinite recursion, since 'vim.deep_equal' calls the '.__eq' metamethod.\n local a_fields = a:as_tbl()\n local b_fields = b:as_tbl()\n return vim.deep_equal(a_fields, b_fields)\n end,\n }, metamethods and metamethods or {})\n\n class.init = function(t)\n local self = setmetatable(t and t or {}, class.mt)\n return self\n end\n\n class.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\n end\n\n return class\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.new = function()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\nNewNoteSource.get_keyword_pattern = completion.get_keyword_pattern\n\nNewNoteSource.incomplete_response = nvim_cmp_util.incomplete_response\nNewNoteSource.complete_response = nvim_cmp_util.complete_response\n\n---Invoke completion (required).\n---@param request cmp.SourceCompletionApiParams\n---@param callback fun(response: lsp.CompletionResponse|nil)\nfunction NewNoteSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\n---Creates a new note using the default template for the completion item.\n---Executed after the item was selected.\n---@param completion_item lsp.CompletionItem\n---@param callback fun(completion_item: lsp.CompletionItem|nil)\nfunction NewNoteSource:execute(completion_item, callback)\n return callback(self:process_execute(completion_item))\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.incomplete_response = blink_util.incomplete_response\nNewNoteSource.complete_response = blink_util.complete_response\n\nfunction NewNoteSource.new()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction NewNoteSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\n---Implements the execute method of the completion provider\n---@param _ blink.cmp.Context\n---@param item blink.cmp.CompletionItem\n---@param callback fun(),\n---@param default_implementation fun(context?: blink.cmp.Context, item?: blink.cmp.CompletionItem)): ((fun(): nil) | nil)\nfunction NewNoteSource:execute(_, item, callback, default_implementation)\n self:process_execute(item)\n default_implementation() -- Ensure completion is still executed\n callback() -- Required (as per blink documentation)\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/compat.lua", "local compat = {}\n\nlocal has_nvim_0_11 = false\nif vim.fn.has \"nvim-0.11\" == 1 then\n has_nvim_0_11 = true\nend\n\ncompat.is_list = function(t)\n if has_nvim_0_11 then\n return vim.islist(t)\n else\n return vim.tbl_islist(t)\n end\nend\n\ncompat.flatten = function(t)\n if has_nvim_0_11 then\n ---@diagnostic disable-next-line: undefined-field\n return vim.iter(t):flatten():totable()\n else\n return vim.tbl_flatten(t)\n end\nend\n\nreturn compat\n"], ["/obsidian.nvim/lua/obsidian/yaml/yq.lua", "local m = {}\n\n---@param str string\n---@return any\nm.loads = function(str)\n local as_json = vim.fn.system(\"yq -o=json\", str)\n local data = vim.json.decode(as_json, { luanil = { object = true, array = true } })\n return data\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/commands/yesterday.lua", "return function()\n local note = require(\"obsidian.daily\").yesterday()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/tomorrow.lua", "return function()\n local note = require(\"obsidian.daily\").tomorrow()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.incomplete_response = blink_util.incomplete_response\nTagsSource.complete_response = blink_util.complete_response\n\nfunction TagsSource.new()\n return TagsSource.init(TagsSourceBase)\nend\n\n---Implements the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction TagsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.blink.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.incomplete_response = blink_util.incomplete_response\nRefsSource.complete_response = blink_util.complete_response\n\nfunction RefsSource.new()\n return RefsSource.init(RefsSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction RefsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/util.lua", "local M = {}\n\n---Generates the completion request from a blink context\n---@param context blink.cmp.Context\n---@return obsidian.completion.sources.base.Request\nM.generate_completion_request_from_editor_state = function(context)\n local row = context.cursor[1]\n local col = context.cursor[2] + 1\n local cursor_before_line = context.line:sub(1, col - 1)\n local cursor_after_line = context.line:sub(col)\n\n return {\n context = {\n bufnr = context.bufnr,\n cursor_before_line = cursor_before_line,\n cursor_after_line = cursor_after_line,\n cursor = {\n row = row,\n col = col,\n line = row + 1,\n },\n },\n }\nend\n\nM.incomplete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = true,\n items = {},\n}\n\nM.complete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = false,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.nvim_cmp.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.new = function()\n return RefsSource.init(RefsSourceBase)\nend\n\nRefsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nRefsSource.incomplete_response = nvim_cmp_util.incomplete_response\nRefsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction RefsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.new = function()\n return TagsSource.init(TagsSourceBase)\nend\n\nTagsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nTagsSource.incomplete_response = nvim_cmp_util.incomplete_response\nTagsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction TagsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/after/ftplugin/markdown.lua", "local obsidian = require \"obsidian\"\nlocal buf = vim.api.nvim_get_current_buf()\nlocal buf_dir = vim.fs.dirname(vim.api.nvim_buf_get_name(buf))\n\nlocal workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\nif not workspace then\n return -- if not in any workspace.\nend\n\nlocal win = vim.api.nvim_get_current_win()\n\nvim.treesitter.start(buf, \"markdown\") -- for when user don't use nvim-treesitter\nvim.wo[win].foldmethod = \"expr\"\nvim.wo[win].foldexpr = \"v:lua.vim.treesitter.foldexpr()\"\nvim.wo[win].foldlevel = 99\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/util.lua", "local M = {}\n\nM.incomplete_response = { isIncomplete = true }\n\nM.complete_response = {\n isIncomplete = true,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/init.lua", "local M = {\n refs = require \"obsidian.completion.refs\",\n tags = require \"obsidian.completion.tags\",\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/types.lua", "---@class obsidian.completion.sources.base.Request.Context.Position\n---@field public col integer\n---@field public row integer\n\n---A request context class that partially matches cmp.Context to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request.Context\n---@field public bufnr integer\n---@field public cursor obsidian.completion.sources.base.Request.Context.Position|lsp.Position\n---@field public cursor_after_line string\n---@field public cursor_before_line string\n\n---A request class that partially matches cmp.Request to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request\n---@field public context obsidian.completion.sources.base.Request.Context\n"], ["/obsidian.nvim/lua/obsidian/version.lua", "return \"3.12.0\"\n"]], "task_instance_info": {"created_time": "2025-08-21 00:50:03", "created_task_model": "DeepSeek-R1", "function_skeleton": "function (_, data) ---@type obsidian.Note end", "code_description": "This code segment functions to: Handle user input for resource creation parameters, initialize a new resource with validation for empty or aborted inputs, and prepare the resource for immediate editing by loading it into an active workspace interface."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nfunction(_, data)\n ---@type obsidian.Note\n local client = api.current_client()\n local note = client:new_note(data)\n log.debug(\"Created new note '%s'\", note.id)\n return note\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-50-21"}, "editdistance_info": {"edit_distance": 12.931, "calculate_time": "2025-08-21 00:50:21", "true_code_clean": "function(_, data)\n local note\n if data.args:len() > 0 then\n note = Note.create { title = data.args }\n else\n local title = api.input(\"Enter title or path (optional): \", { completion = \"file\" })\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n note = Note.create { title = title }\n end\n note:open { sync = true }\n note:write_to_buffer()\nend", "predict_code_clean": "function(_, data)\n local client = api.current_client()\n local note = client:new_note(data)\n log.debug(\"Created new note '%s'\", note.id)\n return note\nend"}} {"repo_name": "obsidian.nvim", "file_name": "/obsidian.nvim/lua/obsidian/statusline/init.lua", "inference_info": {"prefix_code": "local M = {}\nlocal uv = vim.uv\nlocal api = require \"obsidian.api\"\n\n--- Register the global variable that updates itself\nM.start = function(client)\n local current_note\n\n local refresh = ", "suffix_code": "\n\n local timer = uv:new_timer()\n assert(timer, \"Failed to create timer\")\n timer:start(0, 1000, vim.schedule_wrap(refresh))\nend\n\nreturn M\n", "middle_code": "function()\n local note = api.current_note()\n if not note then \n return \"\"\n elseif current_note == note then \n return\n else \n current_note = note\n end\n client:find_backlinks_async(\n note,\n vim.schedule_wrap(function(backlinks)\n local format = assert(Obsidian.opts.statusline.format)\n local wc = vim.fn.wordcount()\n local info = {\n words = wc.words,\n chars = wc.chars,\n backlinks = #backlinks,\n properties = vim.tbl_count(note:frontmatter()),\n }\n for k, v in pairs(info) do\n format = format:gsub(\"{{\" .. k .. \"}}\", v)\n end\n vim.g.obsidian = format\n end)\n )\n end", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/obsidian.nvim/lua/obsidian/footer/init.lua", "local M = {}\nlocal api = require \"obsidian.api\"\n\nlocal ns_id = vim.api.nvim_create_namespace \"ObsidianFooter\"\n\n--- Register buffer-specific variables\nM.start = function(client)\n local refresh_info = function(buf)\n local note = api.current_note(buf)\n if not note then\n return\n end\n local info = {}\n local wc = vim.fn.wordcount()\n info.words = wc.words\n info.chars = wc.chars\n info.properties = vim.tbl_count(note:frontmatter())\n info.backlinks = #client:find_backlinks(note)\n return info\n end\n\n local function update_obsidian_footer(buf)\n local info = refresh_info(buf)\n if info == nil then\n return\n end\n local footer_text = assert(Obsidian.opts.footer.format)\n for k, v in pairs(info) do\n footer_text = footer_text:gsub(\"{{\" .. k .. \"}}\", v)\n end\n local row0 = #vim.api.nvim_buf_get_lines(buf, 0, -2, false)\n local col0 = 0\n local separator = Obsidian.opts.footer.separator\n local hl_group = Obsidian.opts.footer.hl_group\n local footer_contents = { { footer_text, hl_group } }\n local footer_chunks\n if separator then\n local footer_separator = { { separator, hl_group } }\n footer_chunks = { footer_separator, footer_contents }\n else\n footer_chunks = { footer_contents }\n end\n local opts = { virt_lines = footer_chunks }\n vim.api.nvim_buf_clear_namespace(buf, ns_id, 0, -1)\n vim.api.nvim_buf_set_extmark(buf, ns_id, row0, col0, opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_footer\", {})\n local attached_bufs = {}\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n desc = \"Initialize obsidian footer\",\n pattern = \"ObsidianNoteEnter\",\n callback = function(ev)\n if attached_bufs[ev.buf] then\n return\n end\n vim.schedule(function()\n update_obsidian_footer(ev.buf)\n end)\n local id = vim.api.nvim_create_autocmd({\n \"FileChangedShellPost\",\n \"TextChanged\",\n \"TextChangedI\",\n \"TextChangedP\",\n }, {\n group = group,\n desc = \"Update obsidian footer\",\n buffer = ev.buf,\n callback = vim.schedule_wrap(function()\n update_obsidian_footer(ev.buf)\n end),\n })\n attached_bufs[ev.buf] = id\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/backlinks.lua", "local util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal RefTypes = require(\"obsidian.search\").RefTypes\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param note obsidian.Note\n---@param opts { anchor: string|?, block: string|? }|?\nlocal function collect_backlinks(client, picker, note, opts)\n opts = opts or {}\n\n client:find_backlinks_async(note, function(backlinks)\n if vim.tbl_isempty(backlinks) then\n if opts.anchor then\n log.info(\"No backlinks found for anchor '%s' in note '%s'\", opts.anchor, note.id)\n elseif opts.block then\n log.info(\"No backlinks found for block '%s' in note '%s'\", opts.block, note.id)\n else\n log.info(\"No backlinks found for note '%s'\", note.id)\n end\n return\n end\n\n local entries = {}\n for _, matches in ipairs(backlinks) do\n for _, match in ipairs(matches.matches) do\n entries[#entries + 1] = {\n value = { path = matches.path, line = match.line },\n filename = tostring(matches.path),\n lnum = match.line,\n }\n end\n end\n\n ---@type string\n local prompt_title\n if opts.anchor then\n prompt_title = string.format(\"Backlinks to '%s%s'\", note.id, opts.anchor)\n elseif opts.block then\n prompt_title = string.format(\"Backlinks to '%s#%s'\", note.id, util.standardize_block(opts.block))\n else\n prompt_title = string.format(\"Backlinks to '%s'\", note.id)\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = prompt_title,\n callback = function(value)\n api.open_buffer(value.path, { line = value.line })\n end,\n })\n end)\n end, { search = { sort = true }, anchor = opts.anchor, block = opts.block })\nend\n\n---@param client obsidian.Client\nreturn function(client)\n local picker = assert(Obsidian.picker)\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local cur_link, link_type = api.cursor_link()\n\n if\n cur_link ~= nil\n and link_type ~= RefTypes.NakedUrl\n and link_type ~= RefTypes.FileUrl\n and link_type ~= RefTypes.BlockID\n then\n local location = util.parse_link(cur_link, { include_block_ids = true })\n assert(location, \"cursor on a link but failed to parse, please report to repo\")\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n location = vim.api.nvim_buf_get_name(0)\n end\n\n local opts = { anchor = anchor_link, block = block_link }\n\n search.resolve_note_async(location, function(...)\n ---@type obsidian.Note[]\n local notes = { ... }\n\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", location)\n return\n elseif #notes == 1 then\n return collect_backlinks(client, picker, notes[1], opts)\n else\n return vim.schedule(function()\n picker:pick_note(notes, {\n prompt_title = \"Select note\",\n callback = function(note)\n collect_backlinks(client, picker, note, opts)\n end,\n })\n end)\n end\n end)\n else\n ---@type { anchor: string|?, block: string|? }\n local opts = {}\n ---@type obsidian.note.LoadOpts\n local load_opts = {}\n\n if cur_link and link_type == RefTypes.BlockID then\n opts.block = util.parse_link(cur_link, { include_block_ids = true })\n else\n load_opts.collect_anchor_links = true\n end\n\n local note = api.current_note(0, load_opts)\n\n -- Check if cursor is on a header, if so and header parsing is enabled, use that anchor.\n if Obsidian.opts.backlinks.parse_headers then\n local header_match = util.parse_header(vim.api.nvim_get_current_line())\n if header_match then\n opts.anchor = header_match.anchor\n end\n end\n\n if note == nil then\n log.err \"Current buffer does not appear to be a note inside the vault\"\n else\n collect_backlinks(client, picker, note, opts)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/config.lua", "local log = require \"obsidian.log\"\n\nlocal config = {}\n\n---@class obsidian.config\n---@field workspaces obsidian.workspace.WorkspaceSpec[]\n---@field log_level? integer\n---@field notes_subdir? string\n---@field templates? obsidian.config.TemplateOpts\n---@field new_notes_location? obsidian.config.NewNotesLocation\n---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func? fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path\n---@field wiki_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field markdown_link_func? fun(opts: {path: string, label: string, id: string|?}): string\n---@field preferred_link_style? obsidian.config.LinkStyle\n---@field follow_url_func? fun(url: string)\n---@field follow_img_func? fun(img: string)\n---@field note_frontmatter_func? (fun(note: obsidian.Note): table)\n---@field disable_frontmatter? (fun(fname: string?): boolean)|boolean\n---@field backlinks? obsidian.config.BacklinkOpts\n---@field completion? obsidian.config.CompletionOpts\n---@field picker? obsidian.config.PickerOpts\n---@field daily_notes? obsidian.config.DailyNotesOpts\n---@field sort_by? obsidian.config.SortBy\n---@field sort_reversed? boolean\n---@field search_max_lines? integer\n---@field open_notes_in? obsidian.config.OpenStrategy\n---@field ui? obsidian.config.UIOpts | table\n---@field attachments? obsidian.config.AttachmentsOpts\n---@field callbacks? obsidian.config.CallbackConfig\n---@field legacy_commands? boolean\n---@field statusline? obsidian.config.StatuslineOpts\n---@field footer? obsidian.config.FooterOpts\n---@field open? obsidian.config.OpenOpts\n---@field checkbox? obsidian.config.CheckboxOpts\n---@field comment? obsidian.config.CommentOpts\n\n---@class obsidian.config.ClientOpts\n---@field dir string|?\n---@field workspaces obsidian.workspace.WorkspaceSpec[]|?\n---@field log_level integer\n---@field notes_subdir string|?\n---@field templates obsidian.config.TemplateOpts\n---@field new_notes_location obsidian.config.NewNotesLocation\n---@field note_id_func (fun(title: string|?, path: obsidian.Path|?): string)|?\n---@field note_path_func (fun(spec: { id: string, dir: obsidian.Path, title: string|? }): string|obsidian.Path)|?\n---@field wiki_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field markdown_link_func (fun(opts: {path: string, label: string, id: string|?}): string)\n---@field preferred_link_style obsidian.config.LinkStyle\n---@field follow_url_func fun(url: string)|?\n---@field follow_img_func fun(img: string)|?\n---@field note_frontmatter_func (fun(note: obsidian.Note): table)|?\n---@field disable_frontmatter (fun(fname: string?): boolean)|boolean|?\n---@field backlinks obsidian.config.BacklinkOpts\n---@field completion obsidian.config.CompletionOpts\n---@field picker obsidian.config.PickerOpts\n---@field daily_notes obsidian.config.DailyNotesOpts\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field search_max_lines integer\n---@field open_notes_in obsidian.config.OpenStrategy\n---@field ui obsidian.config.UIOpts | table\n---@field attachments obsidian.config.AttachmentsOpts\n---@field callbacks obsidian.config.CallbackConfig\n---@field legacy_commands boolean\n---@field statusline obsidian.config.StatuslineOpts\n---@field footer obsidian.config.FooterOpts\n---@field open obsidian.config.OpenOpts\n---@field checkbox obsidian.config.CheckboxOpts\n---@field comment obsidian.config.CommentOpts\n\n---@enum obsidian.config.OpenStrategy\nconfig.OpenStrategy = {\n current = \"current\",\n vsplit = \"vsplit\",\n hsplit = \"hsplit\",\n vsplit_force = \"vsplit_force\",\n hsplit_force = \"hsplit_force\",\n}\n\n---@enum obsidian.config.SortBy\nconfig.SortBy = {\n path = \"path\",\n modified = \"modified\",\n accessed = \"accessed\",\n created = \"created\",\n}\n\n---@enum obsidian.config.NewNotesLocation\nconfig.NewNotesLocation = {\n current_dir = \"current_dir\",\n notes_subdir = \"notes_subdir\",\n}\n\n---@enum obsidian.config.LinkStyle\nconfig.LinkStyle = {\n wiki = \"wiki\",\n markdown = \"markdown\",\n}\n\n---@enum obsidian.config.Picker\nconfig.Picker = {\n telescope = \"telescope.nvim\",\n fzf_lua = \"fzf-lua\",\n mini = \"mini.pick\",\n snacks = \"snacks.pick\",\n}\n\n--- Get defaults.\n---\n---@return obsidian.config.ClientOpts\nconfig.default = {\n legacy_commands = true,\n workspaces = {},\n log_level = vim.log.levels.INFO,\n notes_subdir = nil,\n new_notes_location = config.NewNotesLocation.current_dir,\n note_id_func = nil,\n wiki_link_func = require(\"obsidian.builtin\").wiki_link_id_prefix,\n markdown_link_func = require(\"obsidian.builtin\").markdown_link,\n preferred_link_style = config.LinkStyle.wiki,\n follow_url_func = vim.ui.open,\n follow_img_func = vim.ui.open,\n note_frontmatter_func = nil,\n disable_frontmatter = false,\n sort_by = \"modified\",\n sort_reversed = true,\n search_max_lines = 1000,\n open_notes_in = \"current\",\n\n ---@class obsidian.config.TemplateOpts\n ---\n ---@field folder string|obsidian.Path|?\n ---@field date_format string|?\n ---@field time_format string|?\n --- A map for custom variables, the key should be the variable and the value a function.\n --- Functions are called with obsidian.TemplateContext objects as their sole parameter.\n --- See: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Template#substitutions\n ---@field substitutions table|?\n ---@field customizations table|?\n templates = {\n folder = nil,\n date_format = nil,\n time_format = nil,\n substitutions = {},\n\n ---@class obsidian.config.CustomTemplateOpts\n ---\n ---@field notes_subdir? string\n ---@field note_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n customizations = {},\n },\n\n ---@class obsidian.config.BacklinkOpts\n ---\n ---@field parse_headers boolean\n backlinks = {\n parse_headers = true,\n },\n\n ---@class obsidian.config.CompletionOpts\n ---\n ---@field nvim_cmp? boolean\n ---@field blink? boolean\n ---@field min_chars? integer\n ---@field match_case? boolean\n ---@field create_new? boolean\n completion = (function()\n local has_nvim_cmp, _ = pcall(require, \"cmp\")\n return {\n nvim_cmp = has_nvim_cmp,\n min_chars = 2,\n match_case = true,\n create_new = true,\n }\n end)(),\n\n ---@class obsidian.config.PickerNoteMappingOpts\n ---\n ---@field new? string\n ---@field insert_link? string\n\n ---@class obsidian.config.PickerTagMappingOpts\n ---\n ---@field tag_note? string\n ---@field insert_tag? string\n\n ---@class obsidian.config.PickerOpts\n ---\n ---@field name obsidian.config.Picker|?\n ---@field note_mappings? obsidian.config.PickerNoteMappingOpts\n ---@field tag_mappings? obsidian.config.PickerTagMappingOpts\n picker = {\n name = nil,\n note_mappings = {\n new = \"\",\n insert_link = \"\",\n },\n tag_mappings = {\n tag_note = \"\",\n insert_tag = \"\",\n },\n },\n\n ---@class obsidian.config.DailyNotesOpts\n ---\n ---@field folder? string\n ---@field date_format? string\n ---@field alias_format? string\n ---@field template? string\n ---@field default_tags? string[]\n ---@field workdays_only? boolean\n daily_notes = {\n folder = nil,\n date_format = nil,\n alias_format = nil,\n default_tags = { \"daily-notes\" },\n workdays_only = true,\n },\n\n ---@class obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.CheckboxSpec : obsidian.config.UICharSpec\n ---@field char string\n ---@field hl_group string\n\n ---@class obsidian.config.UIStyleSpec\n ---@field hl_group string\n\n ---@class obsidian.config.UIOpts\n ---\n ---@field enable boolean\n ---@field ignore_conceal_warn boolean\n ---@field update_debounce integer\n ---@field max_file_length integer|?\n ---@field checkboxes table\n ---@field bullets obsidian.config.UICharSpec|?\n ---@field external_link_icon obsidian.config.UICharSpec\n ---@field reference_text obsidian.config.UIStyleSpec\n ---@field highlight_text obsidian.config.UIStyleSpec\n ---@field tags obsidian.config.UIStyleSpec\n ---@field block_ids obsidian.config.UIStyleSpec\n ---@field hl_groups table\n ui = {\n enable = true,\n ignore_conceal_warn = false,\n update_debounce = 200,\n max_file_length = 5000,\n checkboxes = {\n [\" \"] = { char = \"󰄱\", hl_group = \"obsidiantodo\" },\n [\"~\"] = { char = \"󰰱\", hl_group = \"obsidiantilde\" },\n [\"!\"] = { char = \"\", hl_group = \"obsidianimportant\" },\n [\">\"] = { char = \"\", hl_group = \"obsidianrightarrow\" },\n [\"x\"] = { char = \"\", hl_group = \"obsidiandone\" },\n },\n bullets = { char = \"•\", hl_group = \"ObsidianBullet\" },\n external_link_icon = { char = \"\", hl_group = \"ObsidianExtLinkIcon\" },\n reference_text = { hl_group = \"ObsidianRefText\" },\n highlight_text = { hl_group = \"ObsidianHighlightText\" },\n tags = { hl_group = \"ObsidianTag\" },\n block_ids = { hl_group = \"ObsidianBlockID\" },\n hl_groups = {\n ObsidianTodo = { bold = true, fg = \"#f78c6c\" },\n ObsidianDone = { bold = true, fg = \"#89ddff\" },\n ObsidianRightArrow = { bold = true, fg = \"#f78c6c\" },\n ObsidianTilde = { bold = true, fg = \"#ff5370\" },\n ObsidianImportant = { bold = true, fg = \"#d73128\" },\n ObsidianBullet = { bold = true, fg = \"#89ddff\" },\n ObsidianRefText = { underline = true, fg = \"#c792ea\" },\n ObsidianExtLinkIcon = { fg = \"#c792ea\" },\n ObsidianTag = { italic = true, fg = \"#89ddff\" },\n ObsidianBlockID = { italic = true, fg = \"#89ddff\" },\n ObsidianHighlightText = { bg = \"#75662e\" },\n },\n },\n\n ---@class obsidian.config.AttachmentsOpts\n ---\n ---Default folder to save images to, relative to the vault root (/) or current dir (.), see https://github.com/obsidian-nvim/obsidian.nvim/wiki/Images#change-image-save-location\n ---@field img_folder? string\n ---\n ---Default name for pasted images\n ---@field img_name_func? fun(): string\n ---\n ---Default text to insert for pasted images\n ---@field img_text_func? fun(path: obsidian.Path): string\n ---\n ---Whether to confirm the paste or not. Defaults to true.\n ---@field confirm_img_paste? boolean\n attachments = {\n img_folder = \"assets/imgs\",\n img_text_func = require(\"obsidian.builtin\").img_text_func,\n img_name_func = function()\n return string.format(\"Pasted image %s\", os.date \"%Y%m%d%H%M%S\")\n end,\n confirm_img_paste = true,\n },\n\n ---@class obsidian.config.CallbackConfig\n ---\n ---Runs right after the `obsidian.Client` is initialized.\n ---@field post_setup? fun(client: obsidian.Client)\n ---\n ---Runs when entering a note buffer.\n ---@field enter_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs when leaving a note buffer.\n ---@field leave_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs right before writing a note buffer.\n ---@field pre_write_note? fun(client: obsidian.Client, note: obsidian.Note)\n ---\n ---Runs anytime the workspace is set/changed.\n ---@field post_set_workspace? fun(client: obsidian.Client, workspace: obsidian.Workspace)\n callbacks = {},\n\n ---@class obsidian.config.StatuslineOpts\n ---\n ---@field format? string\n ---@field enabled? boolean\n statusline = {\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n enabled = true,\n },\n\n ---@class obsidian.config.FooterOpts\n ---\n ---@field enabled? boolean\n ---@field format? string\n ---@field hl_group? string\n ---@field separator? string|false Set false to disable separator; set an empty string to insert a blank line separator.\n footer = {\n enabled = true,\n format = \"{{backlinks}} backlinks {{properties}} properties {{words}} words {{chars}} chars\",\n hl_group = \"Comment\",\n separator = string.rep(\"-\", 80),\n },\n\n ---@class obsidian.config.OpenOpts\n ---\n ---Opens the file with current line number\n ---@field use_advanced_uri? boolean\n ---\n ---Function to do the opening, default to vim.ui.open\n ---@field func? fun(uri: string)\n open = {\n use_advanced_uri = false,\n func = vim.ui.open,\n },\n\n ---@class obsidian.config.CheckboxOpts\n ---\n ---@field enabled? boolean\n ---\n ---Order of checkbox state chars, e.g. { \" \", \"x\" }\n ---@field order? string[]\n ---\n ---Whether to create new checkbox on paragraphs\n ---@field create_new? boolean\n checkbox = {\n enabled = true,\n create_new = true,\n order = { \" \", \"~\", \"!\", \">\", \"x\" },\n },\n\n ---@class obsidian.config.CommentOpts\n ---@field enabled boolean\n comment = {\n enabled = false,\n },\n}\n\nlocal tbl_override = function(defaults, overrides)\n local out = vim.tbl_extend(\"force\", defaults, overrides)\n for k, v in pairs(out) do\n if v == vim.NIL then\n out[k] = nil\n end\n end\n return out\nend\n\nlocal function deprecate(name, alternative, version)\n vim.deprecate(name, alternative, version, \"obsidian.nvim\", false)\nend\n\n--- Normalize options.\n---\n---@param opts table\n---@param defaults obsidian.config.ClientOpts|?\n---\n---@return obsidian.config.ClientOpts\nconfig.normalize = function(opts, defaults)\n local builtin = require \"obsidian.builtin\"\n local util = require \"obsidian.util\"\n\n if not defaults then\n defaults = config.default\n end\n\n -------------------------------------------------------------------------------------\n -- Rename old fields for backwards compatibility and warn about deprecated fields. --\n -------------------------------------------------------------------------------------\n\n if opts.ui and opts.ui.tick then\n opts.ui.update_debounce = opts.ui.tick\n opts.ui.tick = nil\n end\n\n if not opts.picker then\n opts.picker = {}\n if opts.finder then\n opts.picker.name = opts.finder\n opts.finder = nil\n end\n if opts.finder_mappings then\n opts.picker.note_mappings = opts.finder_mappings\n opts.finder_mappings = nil\n end\n if opts.picker.mappings and not opts.picker.note_mappings then\n opts.picker.note_mappings = opts.picker.mappings\n opts.picker.mappings = nil\n end\n end\n\n if opts.wiki_link_func == nil and opts.completion ~= nil then\n local warn = false\n\n if opts.completion.prepend_note_id then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n opts.completion.prepend_note_id = nil\n warn = true\n elseif opts.completion.prepend_note_path then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n opts.completion.prepend_note_path = nil\n warn = true\n elseif opts.completion.use_path_only then\n opts.wiki_link_func = builtin.wiki_link_path_only\n opts.completion.use_path_only = nil\n warn = true\n end\n\n if warn then\n log.warn_once(\n \"The config options 'completion.prepend_note_id', 'completion.prepend_note_path', and 'completion.use_path_only' \"\n .. \"are deprecated. Please use 'wiki_link_func' instead.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/406\"\n )\n end\n end\n\n if opts.wiki_link_func == \"prepend_note_id\" then\n opts.wiki_link_func = builtin.wiki_link_id_prefix\n elseif opts.wiki_link_func == \"prepend_note_path\" then\n opts.wiki_link_func = builtin.wiki_link_path_prefix\n elseif opts.wiki_link_func == \"use_path_only\" then\n opts.wiki_link_func = builtin.wiki_link_path_only\n elseif opts.wiki_link_func == \"use_alias_only\" then\n opts.wiki_link_func = builtin.wiki_link_alias_only\n elseif type(opts.wiki_link_func) == \"string\" then\n error(string.format(\"invalid option '%s' for 'wiki_link_func'\", opts.wiki_link_func))\n end\n\n if opts.completion ~= nil and opts.completion.preferred_link_style ~= nil then\n opts.preferred_link_style = opts.completion.preferred_link_style\n opts.completion.preferred_link_style = nil\n log.warn_once(\n \"The config option 'completion.preferred_link_style' is deprecated, please use the top-level \"\n .. \"'preferred_link_style' instead.\"\n )\n end\n\n if opts.completion ~= nil and opts.completion.new_notes_location ~= nil then\n opts.new_notes_location = opts.completion.new_notes_location\n opts.completion.new_notes_location = nil\n log.warn_once(\n \"The config option 'completion.new_notes_location' is deprecated, please use the top-level \"\n .. \"'new_notes_location' instead.\"\n )\n end\n\n if opts.detect_cwd ~= nil then\n opts.detect_cwd = nil\n log.warn_once(\n \"The 'detect_cwd' field is deprecated and no longer has any affect.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/pull/366 for more details.\"\n )\n end\n\n if opts.open_app_foreground ~= nil then\n opts.open_app_foreground = nil\n log.warn_once [[The config option 'open_app_foreground' is deprecated, please use the `func` field in `open` module:\n\n```lua\n{\n open = {\n func = function(uri)\n vim.ui.open(uri, { cmd = { \"open\", \"-a\", \"/Applications/Obsidian.app\" } })\n end\n }\n}\n```]]\n end\n\n if opts.use_advanced_uri ~= nil then\n opts.use_advanced_uri = nil\n log.warn_once [[The config option 'use_advanced_uri' is deprecated, please use in `open` module instead]]\n end\n\n if opts.overwrite_mappings ~= nil then\n log.warn_once \"The 'overwrite_mappings' config option is deprecated and no longer has any affect.\"\n opts.overwrite_mappings = nil\n end\n\n if opts.mappings ~= nil then\n log.warn_once [[The 'mappings' config option is deprecated and no longer has any affect.\nSee: https://github.com/obsidian-nvim/obsidian.nvim/wiki/Keymaps]]\n opts.overwrite_mappings = nil\n end\n\n if opts.tags ~= nil then\n log.warn_once \"The 'tags' config option is deprecated and no longer has any affect.\"\n opts.tags = nil\n end\n\n if opts.templates and opts.templates.subdir then\n opts.templates.folder = opts.templates.subdir\n opts.templates.subdir = nil\n end\n\n if opts.image_name_func then\n if opts.attachments == nil then\n opts.attachments = {}\n end\n opts.attachments.img_name_func = opts.image_name_func\n opts.image_name_func = nil\n end\n\n if opts.statusline and opts.statusline.enabled then\n deprecate(\"statusline.{enabled,format} and vim.g.obsidian\", \"footer.{enabled,format}\", \"4.0\")\n end\n\n --------------------------\n -- Merge with defaults. --\n --------------------------\n\n ---@type obsidian.config.ClientOpts\n opts = tbl_override(defaults, opts)\n\n opts.backlinks = tbl_override(defaults.backlinks, opts.backlinks)\n opts.completion = tbl_override(defaults.completion, opts.completion)\n opts.picker = tbl_override(defaults.picker, opts.picker)\n opts.daily_notes = tbl_override(defaults.daily_notes, opts.daily_notes)\n opts.templates = tbl_override(defaults.templates, opts.templates)\n opts.ui = tbl_override(defaults.ui, opts.ui)\n opts.attachments = tbl_override(defaults.attachments, opts.attachments)\n opts.statusline = tbl_override(defaults.statusline, opts.statusline)\n opts.footer = tbl_override(defaults.footer, opts.footer)\n opts.open = tbl_override(defaults.open, opts.open)\n opts.checkbox = tbl_override(defaults.checkbox, opts.checkbox)\n opts.comment = tbl_override(defaults.comment, opts.comment)\n\n ---------------\n -- Validate. --\n ---------------\n\n if opts.legacy_commands then\n deprecate(\n \"legacy_commands\",\n [[move from commands like `ObsidianBacklinks` to `Obsidian backlinks`\nand set `opts.legacy_commands` to false to get rid of this warning.\nsee https://github.com/obsidian-nvim/obsidian.nvim/wiki/Commands for details.\n ]],\n \"4.0\"\n )\n end\n\n if opts.sort_by ~= nil and not vim.tbl_contains(vim.tbl_values(config.SortBy), opts.sort_by) then\n error(\"Invalid 'sort_by' option '\" .. opts.sort_by .. \"' in obsidian.nvim config.\")\n end\n\n if not util.islist(opts.workspaces) then\n error \"Invalid obsidian.nvim config, the 'config.workspaces' should be an array/list.\"\n elseif vim.tbl_isempty(opts.workspaces) then\n error \"At least one workspace is required!\\nPlease specify a workspace \"\n end\n\n for i, workspace in ipairs(opts.workspaces) do\n local path = type(workspace.path) == \"function\" and workspace.path() or workspace.path\n ---@cast path -function\n opts.workspaces[i].path = vim.fn.resolve(vim.fs.normalize(path))\n end\n\n -- Convert dir to workspace format.\n if opts.dir ~= nil then\n table.insert(opts.workspaces, 1, { path = opts.dir })\n end\n\n return opts\nend\n\nreturn config\n"], ["/obsidian.nvim/lua/obsidian/client.lua", "--- *obsidian-api*\n---\n--- The Obsidian.nvim Lua API.\n---\n--- ==============================================================================\n---\n--- Table of contents\n---\n---@toc\n\nlocal Path = require \"obsidian.path\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal Note = require \"obsidian.note\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal block_on = require(\"obsidian.async\").block_on\nlocal iter = vim.iter\n\n---@class obsidian.SearchOpts\n---\n---@field sort boolean|?\n---@field include_templates boolean|?\n---@field ignore_case boolean|?\n---@field default function?\n\n--- The Obsidian client is the main API for programmatically interacting with obsidian.nvim's features\n--- in Lua. To get the client instance, run:\n---\n--- `local client = require(\"obsidian\").get_client()`\n---\n---@toc_entry obsidian.Client\n---\n---@class obsidian.Client : obsidian.ABC\nlocal Client = {}\n\nlocal depreacted_lookup = {\n dir = \"dir\",\n buf_dir = \"buf_dir\",\n current_workspace = \"workspace\",\n opts = \"opts\",\n}\n\nClient.__index = function(_, k)\n if depreacted_lookup[k] then\n local msg = string.format(\n [[client.%s is depreacted, use Obsidian.%s instead.\nclient is going to be removed in the future as well.]],\n k,\n depreacted_lookup[k]\n )\n log.warn(msg)\n return Obsidian[depreacted_lookup[k]]\n elseif rawget(Client, k) then\n return rawget(Client, k)\n end\nend\n\n--- Create a new Obsidian client without additional setup.\n--- This is mostly used for testing. In practice you usually want to obtain the existing\n--- client through:\n---\n--- `require(\"obsidian\").get_client()`\n---\n---@return obsidian.Client\nClient.new = function()\n return setmetatable({}, Client)\nend\n\n--- Get the default search options.\n---\n---@return obsidian.SearchOpts\nClient.search_defaults = function()\n return {\n sort = false,\n include_templates = false,\n ignore_case = false,\n }\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---\n---@return obsidian.SearchOpts\n---\n---@private\nClient._search_opts_from_arg = function(self, opts)\n if opts == nil then\n opts = self:search_defaults()\n elseif type(opts) == \"boolean\" then\n local sort = opts\n opts = self:search_defaults()\n opts.sort = sort\n end\n return opts\nend\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nClient._prepare_search_opts = function(self, opts, additional_opts)\n opts = self:_search_opts_from_arg(opts)\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n search.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = search.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---\n---@return function\n---\n---@private\nClient._search_iter_async = function(self, term, search_opts, find_opts)\n local tx, rx = channel.mpsc()\n local found = {}\n\n local function on_exit(_)\n tx.send(nil)\n end\n\n ---@param content_match MatchData\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n ---@param path_match string\n local function on_find_match(path_match)\n local path = Path.new(path_match):resolve { strict = true }\n if not found[path.filename] then\n found[path.filename] = true\n tx.send(path)\n end\n end\n\n local cmds_done = 0 -- out of the two, one for 'search' and one for 'find'\n\n search.search_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n search.find_async(\n Obsidian.dir,\n term,\n self:_prepare_search_opts(find_opts, { ignore_case = true }),\n on_find_match,\n on_exit\n )\n\n return function()\n while cmds_done < 2 do\n local value = rx.recv()\n if value == nil then\n cmds_done = cmds_done + 1\n else\n return value\n end\n end\n return nil\n end\nend\n\n---@class obsidian.TagLocation\n---\n---@field tag string The tag found.\n---@field note obsidian.Note The note instance where the tag was found.\n---@field path string|obsidian.Path The path to the note where the tag was found.\n---@field line integer The line number (1-indexed) where the tag was found.\n---@field text string The text (with whitespace stripped) of the line where the tag was found.\n---@field tag_start integer|? The index within 'text' where the tag starts.\n---@field tag_end integer|? The index within 'text' where the tag ends.\n\n--- Find all tags starting with the given search term(s).\n---\n---@param term string|string[] The search term.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|? }|?\n---\n---@return obsidian.TagLocation[]\nClient.find_tags = function(self, term, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_tags_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n--- An async version of 'find_tags()'.\n---\n---@param term string|string[] The search term.\n---@param callback fun(tags: obsidian.TagLocation[])\n---@param opts { search: obsidian.SearchOpts }|?\nClient.find_tags_async = function(self, term, callback, opts)\n opts = opts or {}\n\n ---@type string[]\n local terms\n if type(term) == \"string\" then\n terms = { term }\n else\n terms = term\n end\n\n for i, t in ipairs(terms) do\n if vim.startswith(t, \"#\") then\n terms[i] = string.sub(t, 2)\n end\n end\n\n terms = util.tbl_unique(terms)\n\n -- Maps paths to tag locations.\n ---@type table\n local path_to_tag_loc = {}\n -- Caches note objects.\n ---@type table\n local path_to_note = {}\n -- Caches code block locations.\n ---@type table\n local path_to_code_blocks = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n ---@param tag string\n ---@param path string|obsidian.Path\n ---@param note obsidian.Note\n ---@param lnum integer\n ---@param text string\n ---@param col_start integer|?\n ---@param col_end integer|?\n local add_match = function(tag, path, note, lnum, text, col_start, col_end)\n if vim.startswith(tag, \"#\") then\n tag = string.sub(tag, 2)\n end\n if not path_to_tag_loc[path] then\n path_to_tag_loc[path] = {}\n end\n path_to_tag_loc[path][#path_to_tag_loc[path] + 1] = {\n tag = tag,\n path = path,\n note = note,\n line = lnum,\n text = text,\n tag_start = col_start,\n tag_end = col_end,\n }\n end\n\n -- Wraps `Note.from_file_with_contents_async()` to return a table instead of a tuple and\n -- find the code blocks.\n ---@param path obsidian.Path\n ---@return { [1]: obsidian.Note, [2]: {[1]: integer, [2]: integer}[] }\n local load_note = function(path)\n local note, contents = Note.from_file_with_contents_async(path, { max_lines = Obsidian.opts.search_max_lines })\n return { note, search.find_code_blocks(contents) }\n end\n\n ---@param match_data MatchData\n local on_match = function(match_data)\n local path = Path.new(match_data.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local note = path_to_note[path]\n local code_blocks = path_to_code_blocks[path]\n if not note or not code_blocks then\n local ok, res = pcall(load_note, path)\n if ok then\n note, code_blocks = unpack(res)\n path_to_note[path] = note\n path_to_code_blocks[path] = code_blocks\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n local line_number = match_data.line_number + 1 -- match_data.line_number is 0-indexed\n\n -- check if the match was inside a code block.\n for block in iter(code_blocks) do\n if block[1] <= line_number and line_number <= block[2] then\n return\n end\n end\n\n local line = vim.trim(match_data.lines.text)\n local n_matches = 0\n\n -- check for tag in the wild of the form '#{tag}'\n for match in iter(search.find_tags(line)) do\n local m_start, m_end, _ = unpack(match)\n local tag = string.sub(line, m_start + 1, m_end)\n if string.match(tag, \"^\" .. search.Patterns.TagCharsRequired .. \"$\") then\n add_match(tag, path, note, match_data.line_number, line, m_start, m_end)\n end\n end\n\n -- check for tags in frontmatter\n if n_matches == 0 and note.tags ~= nil and (vim.startswith(line, \"tags:\") or string.match(line, \"%s*- \")) then\n for tag in iter(note.tags) do\n tag = tostring(tag)\n for _, t in ipairs(terms) do\n if string.len(t) == 0 or util.string_contains(tag:lower(), t:lower()) then\n add_match(tag, path, note, match_data.line_number, line)\n end\n end\n end\n end\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n local search_terms = {}\n for t in iter(terms) do\n if string.len(t) > 0 then\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsOptional .. t .. search.Patterns.TagCharsOptional\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\"\n .. search.Patterns.TagCharsOptional\n .. t\n .. search.Patterns.TagCharsOptional\n else\n -- tag in the wild\n search_terms[#search_terms + 1] = \"#\" .. search.Patterns.TagCharsRequired\n -- frontmatter tag in multiline list\n search_terms[#search_terms + 1] = \"\\\\s*- \" .. search.Patterns.TagCharsRequired .. \"$\"\n -- frontmatter tag in inline list\n search_terms[#search_terms + 1] = \"tags: .*\" .. search.Patterns.TagCharsRequired\n end\n end\n\n search.search_async(\n Obsidian.dir,\n search_terms,\n self:_prepare_search_opts(opts.search, { ignore_case = true }),\n on_match,\n function(_)\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.TagLocation[]\n local tags_list = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results in path order.\n for _, path in ipairs(paths) do\n local tag_locs = path_to_tag_loc[path]\n if tag_locs ~= nil then\n table.sort(tag_locs, function(a, b)\n return a.line < b.line\n end)\n for _, tag_loc in ipairs(tag_locs) do\n tags_list[#tags_list + 1] = tag_loc\n end\n end\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return tags_list\n end, callback)\nend\n\n---@class obsidian.BacklinkMatches\n---\n---@field note obsidian.Note The note instance where the backlinks were found.\n---@field path string|obsidian.Path The path to the note where the backlinks were found.\n---@field matches obsidian.BacklinkMatch[] The backlinks within the note.\n\n---@class obsidian.BacklinkMatch\n---\n---@field line integer The line number (1-indexed) where the backlink was found.\n---@field text string The text of the line where the backlink was found.\n\n--- Find all backlinks to a note.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param opts { search: obsidian.SearchOpts|?, timeout: integer|?, anchor: string|?, block: string|? }|?\n---\n---@return obsidian.BacklinkMatches[]\nClient.find_backlinks = function(self, note, opts)\n opts = opts or {}\n return block_on(function(cb)\n return self:find_backlinks_async(note, cb, { search = opts.search, anchor = opts.anchor, block = opts.block })\n end, opts.timeout)\nend\n\n--- An async version of 'find_backlinks()'.\n---\n---@param note obsidian.Note The note to find backlinks for.\n---@param callback fun(backlinks: obsidian.BacklinkMatches[])\n---@param opts { search: obsidian.SearchOpts, anchor: string|?, block: string|? }|?\nClient.find_backlinks_async = function(self, note, callback, opts)\n opts = opts or {}\n\n ---@type string|?\n local block = opts.block and util.standardize_block(opts.block) or nil\n local anchor = opts.anchor and util.standardize_anchor(opts.anchor) or nil\n ---@type obsidian.note.HeaderAnchor|?\n local anchor_obj\n if anchor then\n anchor_obj = note:resolve_anchor_link(anchor)\n end\n\n -- Maps paths (string) to note object and a list of matches.\n ---@type table\n local backlink_matches = {}\n ---@type table\n local path_to_note = {}\n -- Keeps track of the order of the paths.\n ---@type table\n local path_order = {}\n local num_paths = 0\n local err_count = 0\n local first_err = nil\n local first_err_path = nil\n\n local executor = AsyncExecutor.new()\n\n -- Prepare search terms.\n local search_terms = {}\n local note_path = Path.new(note.path)\n for raw_ref in iter { tostring(note.id), note_path.name, note_path.stem, note.path:vault_relative_path() } do\n for ref in\n iter(util.tbl_unique {\n raw_ref,\n util.urlencode(tostring(raw_ref)),\n util.urlencode(tostring(raw_ref), { keep_path_sep = true }),\n })\n do\n if ref ~= nil then\n if anchor == nil and block == nil then\n -- Wiki links without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", ref)\n search_terms[#search_terms + 1] = string.format(\"[[%s|\", ref)\n -- Markdown link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s)\", ref)\n -- Markdown link without anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s)\", ref)\n -- Wiki links with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor/block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif anchor then\n -- Note: Obsidian allow a lot of different forms of anchor links, so we can't assume\n -- it's the standardized form here.\n -- Wiki links with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", ref)\n -- Markdown link with anchor.\n search_terms[#search_terms + 1] = string.format(\"(%s#\", ref)\n -- Markdown link with anchor and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#\", ref)\n elseif block then\n -- Wiki links with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", ref, block)\n -- Markdown link with block.\n search_terms[#search_terms + 1] = string.format(\"(%s#%s\", ref, block)\n -- Markdown link with block and is relative to root.\n search_terms[#search_terms + 1] = string.format(\"(/%s#%s\", ref, block)\n end\n end\n end\n end\n for alias in iter(note.aliases) do\n if anchor == nil and block == nil then\n -- Wiki link without anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s]]\", alias)\n -- Wiki link with anchor/block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif anchor then\n -- Wiki link with anchor.\n search_terms[#search_terms + 1] = string.format(\"[[%s#\", alias)\n elseif block then\n -- Wiki link with block.\n search_terms[#search_terms + 1] = string.format(\"[[%s#%s\", alias, block)\n end\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = opts.anchor ~= nil,\n collect_blocks = opts.block ~= nil,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n ---@param match MatchData\n local function on_match(match)\n local path = Path.new(match.path.text):resolve { strict = true }\n\n if path_order[path] == nil then\n num_paths = num_paths + 1\n path_order[path] = num_paths\n end\n\n executor:submit(function()\n -- Load note.\n local n = path_to_note[path]\n if not n then\n local ok, res = pcall(Note.from_file_async, path, load_opts)\n if ok then\n n = res\n path_to_note[path] = n\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n return\n end\n end\n\n if anchor then\n -- Check for a match with the anchor.\n -- NOTE: no need to do this with blocks, since blocks are standardized.\n local match_text = string.sub(match.lines.text, match.submatches[1].start)\n local link_location = util.parse_link(match_text)\n if not link_location then\n log.error(\"Failed to parse reference from '%s' ('%s')\", match_text, match)\n return\n end\n\n local anchor_link = select(2, util.strip_anchor_links(link_location))\n if not anchor_link then\n return\n end\n\n if anchor_link ~= anchor and anchor_obj ~= nil then\n local resolved_anchor = note:resolve_anchor_link(anchor_link)\n if resolved_anchor == nil or resolved_anchor.header ~= anchor_obj.header then\n return\n end\n end\n end\n\n ---@type obsidian.BacklinkMatch[]\n local line_matches = backlink_matches[path]\n if line_matches == nil then\n line_matches = {}\n backlink_matches[path] = line_matches\n end\n\n line_matches[#line_matches + 1] = {\n line = match.line_number,\n text = util.rstrip_whitespace(match.lines.text),\n }\n end)\n end\n\n local tx, rx = channel.oneshot()\n\n -- Execute search.\n search.search_async(\n Obsidian.dir,\n util.tbl_unique(search_terms),\n self:_prepare_search_opts(opts.search, { fixed_strings = true, ignore_case = true }),\n on_match,\n function()\n tx()\n end\n )\n\n async.run(function()\n rx()\n executor:join_async()\n\n ---@type obsidian.BacklinkMatches[]\n local results = {}\n\n -- Order by path.\n local paths = {}\n for path, idx in pairs(path_order) do\n paths[idx] = path\n end\n\n -- Gather results.\n for i, path in ipairs(paths) do\n results[i] = { note = path_to_note[path], path = path, matches = backlink_matches[path] }\n end\n\n -- Log any errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n return vim.tbl_filter(function(bl)\n return bl.matches ~= nil\n end, results)\n end, callback)\nend\n\n--- Gather a list of all tags in the vault. If 'term' is provided, only tags that partially match the search\n--- term will be included.\n---\n---@param term string|? An optional search term to match tags\n---@param timeout integer|? Timeout in milliseconds\n---\n---@return string[]\nClient.list_tags = function(self, term, timeout)\n local tags = {}\n for _, tag_loc in ipairs(self:find_tags(term and term or \"\", { timeout = timeout })) do\n tags[tag_loc.tag] = true\n end\n return vim.tbl_keys(tags)\nend\n\n--- An async version of 'list_tags()'.\n---\n---@param term string|?\n---@param callback fun(tags: string[])\nClient.list_tags_async = function(self, term, callback)\n self:find_tags_async(term and term or \"\", function(tag_locations)\n local tags = {}\n for _, tag_loc in ipairs(tag_locations) do\n local tag = tag_loc.tag:lower()\n if not tags[tag] then\n tags[tag] = true\n end\n end\n callback(vim.tbl_keys(tags))\n end)\nend\n\nreturn Client\n"], ["/obsidian.nvim/lua/obsidian/note.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal yaml = require \"obsidian.yaml\"\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\nlocal enumerate = util.enumerate\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal config = require \"obsidian.config\"\n\nlocal SKIP_UPDATING_FRONTMATTER = { \"README.md\", \"CONTRIBUTING.md\", \"CHANGELOG.md\" }\n\nlocal DEFAULT_MAX_LINES = 500\n\nlocal CODE_BLOCK_PATTERN = \"^%s*```[%w_-]*$\"\n\n--- @class obsidian.note.NoteCreationOpts\n--- @field notes_subdir string\n--- @field note_id_func fun()\n--- @field new_notes_location string\n\n--- @class obsidian.note.NoteOpts\n--- @field title string|? The note's title\n--- @field id string|? An ID to assign the note. If not specified one will be generated.\n--- @field dir string|obsidian.Path|? An optional directory to place the note in. Relative paths will be interpreted\n--- relative to the workspace / vault root. If the directory doesn't exist it will\n--- be created, regardless of the value of the `should_write` option.\n--- @field aliases string[]|? Aliases for the note\n--- @field tags string[]|? Tags for this note\n--- @field should_write boolean|? Don't write the note to disk\n--- @field template string|? The name of the template\n\n---@class obsidian.note.NoteSaveOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- Whether to insert/update frontmatter. Defaults to `true`.\n---@field insert_frontmatter? boolean\n--- Override the frontmatter. Defaults to the result of `self:frontmatter()`.\n---@field frontmatter? table\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload the updated file.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.NoteWriteOpts\n--- Specify a path to save to. Defaults to `self.path`.\n---@field path? string|obsidian.Path\n--- The name of a template to use if the note file doesn't already exist.\n---@field template? string\n--- A function to update the contents of the note. This takes a list of lines representing the text to be written\n--- excluding frontmatter, and returns the lines that will actually be written (again excluding frontmatter).\n---@field update_content? fun(lines: string[]): string[]\n--- Whether to call |checktime| on open buffers pointing to the written note. Defaults to true.\n--- When enabled, Neovim will warn the user if changes would be lost and/or reload each buffer's content.\n--- See `:help checktime` to learn more.\n---@field check_buffers? boolean\n\n---@class obsidian.note.HeaderAnchor\n---\n---@field anchor string\n---@field header string\n---@field level integer\n---@field line integer\n---@field parent obsidian.note.HeaderAnchor|?\n\n---@class obsidian.note.Block\n---\n---@field id string\n---@field line integer\n---@field block string\n\n--- A class that represents a note within a vault.\n---\n---@toc_entry obsidian.Note\n---\n---@class obsidian.Note : obsidian.ABC\n---\n---@field id string\n---@field aliases string[]\n---@field title string|?\n---@field tags string[]\n---@field path obsidian.Path|?\n---@field metadata table|?\n---@field has_frontmatter boolean|?\n---@field frontmatter_end_line integer|?\n---@field contents string[]|?\n---@field anchor_links table|?\n---@field blocks table?\n---@field alt_alias string|?\n---@field bufnr integer|?\nlocal Note = abc.new_class {\n __tostring = function(self)\n return string.format(\"Note('%s')\", self.id)\n end,\n}\n\nNote.is_note_obj = function(note)\n if getmetatable(note) == Note.mt then\n return true\n else\n return false\n end\nend\n\n--- Generate a unique ID for a new note. This respects the user's `note_id_func` if configured,\n--- otherwise falls back to generated a Zettelkasten style ID.\n---\n--- @param title? string\n--- @param path? obsidian.Path\n--- @param alt_id_func? (fun(title: string|?, path: obsidian.Path|?): string)\n---@return string\nlocal function generate_id(title, path, alt_id_func)\n if alt_id_func ~= nil then\n local new_id = alt_id_func(title, path)\n if new_id == nil or string.len(new_id) == 0 then\n error(string.format(\"Your 'note_id_func' must return a non-empty string, got '%s'!\", tostring(new_id)))\n end\n -- Remote '.md' suffix if it's there (we add that later).\n new_id = new_id:gsub(\"%.md$\", \"\", 1)\n return new_id\n else\n return require(\"obsidian.builtin\").zettel_id()\n end\nend\n\n--- Generate the file path for a new note given its ID, parent directory, and title.\n--- This respects the user's `note_path_func` if configured, otherwise essentially falls back to\n--- `note_opts.dir / (note_opts.id .. \".md\")`.\n---\n--- @param title string|? The title for the note\n--- @param id string The note ID\n--- @param dir obsidian.Path The note path\n---@return obsidian.Path\n---@private\nNote._generate_path = function(title, id, dir)\n ---@type obsidian.Path\n local path\n\n if Obsidian.opts.note_path_func ~= nil then\n path = Path.new(Obsidian.opts.note_path_func { id = id, dir = dir, title = title })\n -- Ensure path is either absolute or inside `opts.dir`.\n -- NOTE: `opts.dir` should always be absolute, but for extra safety we handle the case where\n -- it's not.\n if not path:is_absolute() and (dir:is_absolute() or not dir:is_parent_of(path)) then\n path = dir / path\n end\n else\n path = dir / tostring(id)\n end\n\n -- Ensure there is only one \".md\" suffix. This might arise if `note_path_func`\n -- supplies an unusual implementation returning something like /bad/note/id.md.md.md\n while path.filename:match \"%.md$\" do\n path.filename = path.filename:gsub(\"%.md$\", \"\")\n end\n\n return path:with_suffix(\".md\", true)\nend\n\n--- Selects the strategy to use when resolving the note title, id, and path\n--- @param opts obsidian.note.NoteOpts The note creation options\n--- @return obsidian.note.NoteCreationOpts The strategy to use for creating the note\n--- @private\nNote._get_creation_opts = function(opts)\n --- @type obsidian.note.NoteCreationOpts\n local default = {\n notes_subdir = Obsidian.opts.notes_subdir,\n note_id_func = Obsidian.opts.note_id_func,\n new_notes_location = Obsidian.opts.new_notes_location,\n }\n\n local resolve_template = require(\"obsidian.templates\").resolve_template\n local success, template_path = pcall(resolve_template, opts.template, api.templates_dir())\n\n if not success then\n return default\n end\n\n local stem = template_path.stem:lower()\n\n -- Check if the configuration has a custom key for this template\n for key, cfg in pairs(Obsidian.opts.templates.customizations) do\n if key:lower() == stem then\n return {\n notes_subdir = cfg.notes_subdir,\n note_id_func = cfg.note_id_func,\n new_notes_location = config.NewNotesLocation.notes_subdir,\n }\n end\n end\n return default\nend\n\n--- Resolves the title, ID, and path for a new note.\n---\n---@param title string|?\n---@param id string|?\n---@param dir string|obsidian.Path|? The directory for the note\n---@param strategy obsidian.note.NoteCreationOpts Strategy for resolving note path and title\n---@return string|?,string,obsidian.Path\n---@private\nNote._resolve_title_id_path = function(title, id, dir, strategy)\n if title then\n title = vim.trim(title)\n if title == \"\" then\n title = nil\n end\n end\n\n if id then\n id = vim.trim(id)\n if id == \"\" then\n id = nil\n end\n end\n\n ---@param s string\n ---@param strict_paths_only boolean\n ---@return string|?, boolean, string|?\n local parse_as_path = function(s, strict_paths_only)\n local is_path = false\n ---@type string|?\n local parent\n\n if s:match \"%.md\" then\n -- Remove suffix.\n s = s:sub(1, s:len() - 3)\n is_path = true\n end\n\n -- Pull out any parent dirs from title.\n local parts = vim.split(s, \"/\")\n if #parts > 1 then\n s = parts[#parts]\n if not strict_paths_only then\n is_path = true\n end\n parent = table.concat(parts, \"/\", 1, #parts - 1)\n end\n\n if s == \"\" then\n return nil, is_path, parent\n else\n return s, is_path, parent\n end\n end\n\n local parent, _, title_is_path\n if id then\n id, _, parent = parse_as_path(id, false)\n elseif title then\n title, title_is_path, parent = parse_as_path(title, true)\n if title_is_path then\n id = title\n end\n end\n\n -- Resolve base directory.\n ---@type obsidian.Path\n local base_dir\n if parent then\n base_dir = Obsidian.dir / parent\n elseif dir ~= nil then\n base_dir = Path.new(dir)\n if not base_dir:is_absolute() then\n base_dir = Obsidian.dir / base_dir\n else\n base_dir = base_dir:resolve()\n end\n else\n local bufpath = Path.buffer(0):resolve()\n if\n strategy.new_notes_location == config.NewNotesLocation.current_dir\n -- note is actually in the workspace.\n and Obsidian.dir:is_parent_of(bufpath)\n -- note is not in dailies folder\n and (\n Obsidian.opts.daily_notes.folder == nil\n or not (Obsidian.dir / Obsidian.opts.daily_notes.folder):is_parent_of(bufpath)\n )\n then\n base_dir = Obsidian.buf_dir or assert(bufpath:parent())\n else\n base_dir = Obsidian.dir\n if strategy.notes_subdir then\n base_dir = base_dir / strategy.notes_subdir\n end\n end\n end\n\n -- Make sure `base_dir` is absolute at this point.\n assert(base_dir:is_absolute(), (\"failed to resolve note directory '%s'\"):format(base_dir))\n\n -- Generate new ID if needed.\n if not id then\n id = generate_id(title, base_dir, strategy.note_id_func)\n end\n\n dir = base_dir\n\n -- Generate path.\n local path = Note._generate_path(title, id, dir)\n\n return title, id, path\nend\n\n--- Creates a new note\n---\n--- @param opts obsidian.note.NoteOpts Options\n--- @return obsidian.Note\nNote.create = function(opts)\n local new_title, new_id, path =\n Note._resolve_title_id_path(opts.title, opts.id, opts.dir, Note._get_creation_opts(opts))\n opts = vim.tbl_extend(\"keep\", opts, { aliases = {}, tags = {} })\n\n -- Add the title as an alias.\n --- @type string[]\n local aliases = opts.aliases\n if new_title ~= nil and new_title:len() > 0 and not vim.list_contains(aliases, new_title) then\n aliases[#aliases + 1] = new_title\n end\n\n local note = Note.new(new_id, aliases, opts.tags, path)\n\n if new_title then\n note.title = new_title\n end\n\n -- Ensure the parent directory exists.\n local parent = path:parent()\n assert(parent)\n parent:mkdir { parents = true, exist_ok = true }\n\n -- Write to disk.\n if opts.should_write then\n note:write { template = opts.template }\n end\n\n return note\nend\n\n--- Instantiates a new Note object\n---\n--- Keep in mind that you have to call `note:save(...)` to create/update the note on disk.\n---\n--- @param id string|number\n--- @param aliases string[]\n--- @param tags string[]\n--- @param path string|obsidian.Path|?\n--- @return obsidian.Note\nNote.new = function(id, aliases, tags, path)\n local self = Note.init()\n self.id = id\n self.aliases = aliases and aliases or {}\n self.tags = tags and tags or {}\n self.path = path and Path.new(path) or nil\n self.metadata = nil\n self.has_frontmatter = nil\n self.frontmatter_end_line = nil\n return self\nend\n\n--- Get markdown display info about the note.\n---\n---@param opts { label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|?\n---\n---@return string\nNote.display_info = function(self, opts)\n opts = opts and opts or {}\n\n ---@type string[]\n local info = {}\n\n if opts.label ~= nil and string.len(opts.label) > 0 then\n info[#info + 1] = (\"%s\"):format(opts.label)\n info[#info + 1] = \"--------\"\n end\n\n if self.path ~= nil then\n info[#info + 1] = (\"**path:** `%s`\"):format(self.path)\n end\n\n info[#info + 1] = (\"**id:** `%s`\"):format(self.id)\n\n if #self.aliases > 0 then\n info[#info + 1] = (\"**aliases:** '%s'\"):format(table.concat(self.aliases, \"', '\"))\n end\n\n if #self.tags > 0 then\n info[#info + 1] = (\"**tags:** `#%s`\"):format(table.concat(self.tags, \"`, `#\"))\n end\n\n if opts.anchor or opts.block then\n info[#info + 1] = \"--------\"\n\n if opts.anchor then\n info[#info + 1] = (\"...\\n%s %s\\n...\"):format(string.rep(\"#\", opts.anchor.level), opts.anchor.header)\n elseif opts.block then\n info[#info + 1] = (\"...\\n%s\\n...\"):format(opts.block.block)\n end\n end\n\n return table.concat(info, \"\\n\")\nend\n\n--- Check if the note exists on the file system.\n---\n---@return boolean\nNote.exists = function(self)\n ---@diagnostic disable-next-line: return-type-mismatch\n return self.path ~= nil and self.path:is_file()\nend\n\n--- Get the filename associated with the note.\n---\n---@return string|?\nNote.fname = function(self)\n if self.path == nil then\n return nil\n else\n return vim.fs.basename(tostring(self.path))\n end\nend\n\n--- Get a list of all of the different string that can identify this note via references,\n--- including the ID, aliases, and filename.\n---@param opts { lowercase: boolean|? }|?\n---@return string[]\nNote.reference_ids = function(self, opts)\n opts = opts or {}\n ---@type string[]\n local ref_ids = { tostring(self.id), self:display_name() }\n if self.path then\n table.insert(ref_ids, self.path.name)\n table.insert(ref_ids, self.path.stem)\n end\n\n vim.list_extend(ref_ids, self.aliases)\n\n if opts.lowercase then\n ref_ids = vim.tbl_map(string.lower, ref_ids)\n end\n\n return util.tbl_unique(ref_ids)\nend\n\n--- Check if a note has a given alias.\n---\n---@param alias string\n---\n---@return boolean\nNote.has_alias = function(self, alias)\n return vim.list_contains(self.aliases, alias)\nend\n\n--- Check if a note has a given tag.\n---\n---@param tag string\n---\n---@return boolean\nNote.has_tag = function(self, tag)\n return vim.list_contains(self.tags, tag)\nend\n\n--- Add an alias to the note.\n---\n---@param alias string\n---\n---@return boolean added True if the alias was added, false if it was already present.\nNote.add_alias = function(self, alias)\n if not self:has_alias(alias) then\n table.insert(self.aliases, alias)\n return true\n else\n return false\n end\nend\n\n--- Add a tag to the note.\n---\n---@param tag string\n---\n---@return boolean added True if the tag was added, false if it was already present.\nNote.add_tag = function(self, tag)\n if not self:has_tag(tag) then\n table.insert(self.tags, tag)\n return true\n else\n return false\n end\nend\n\n--- Add or update a field in the frontmatter.\n---\n---@param key string\n---@param value any\nNote.add_field = function(self, key, value)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Updating field '%s' this way is not allowed. Please update the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n self.metadata = {}\n end\n\n self.metadata[key] = value\nend\n\n--- Get a field in the frontmatter.\n---\n---@param key string\n---\n---@return any result\nNote.get_field = function(self, key)\n if key == \"id\" or key == \"aliases\" or key == \"tags\" then\n error \"Getting field '%s' this way is not allowed. Please use the corresponding attribute directly instead\"\n end\n\n if not self.metadata then\n return nil\n end\n\n return self.metadata[key]\nend\n\n---@class obsidian.note.LoadOpts\n---@field max_lines integer|?\n---@field load_contents boolean|?\n---@field collect_anchor_links boolean|?\n---@field collect_blocks boolean|?\n\n--- Initialize a note from a file.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file = function(path, opts)\n if path == nil then\n error \"note path cannot be nil\"\n end\n path = tostring(Path.new(path):resolve { strict = true })\n return Note.from_lines(io.lines(path), path, opts)\nend\n\n--- An async version of `.from_file()`, i.e. it needs to be called in an async context.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_file_async = function(path, opts)\n path = Path.new(path):resolve { strict = true }\n local f = io.open(tostring(path), \"r\")\n assert(f)\n local ok, res = pcall(Note.from_lines, f:lines \"*l\", path, opts)\n f:close()\n if ok then\n return res\n else\n error(res)\n end\nend\n\n--- Like `.from_file_async()` but also returns the contents of the file as a list of lines.\n---\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note,string[]\nNote.from_file_with_contents_async = function(path, opts)\n opts = vim.tbl_extend(\"force\", opts or {}, { load_contents = true })\n local note = Note.from_file_async(path, opts)\n assert(note.contents ~= nil)\n return note, note.contents\nend\n\n--- Initialize a note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_buffer = function(bufnr, opts)\n bufnr = bufnr or vim.api.nvim_get_current_buf()\n local path = vim.api.nvim_buf_get_name(bufnr)\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)\n local note = Note.from_lines(iter(lines), path, opts)\n note.bufnr = bufnr\n return note\nend\n\n--- Get the display name for note.\n---\n---@return string\nNote.display_name = function(self)\n if self.title then\n return self.title\n elseif #self.aliases > 0 then\n return self.aliases[#self.aliases]\n end\n return tostring(self.id)\nend\n\n--- Initialize a note from an iterator of lines.\n---\n---@param lines fun(): string|? | Iter\n---@param path string|obsidian.Path\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note\nNote.from_lines = function(lines, path, opts)\n opts = opts or {}\n path = Path.new(path):resolve()\n\n local max_lines = opts.max_lines or DEFAULT_MAX_LINES\n\n local id = nil\n local title = nil\n local aliases = {}\n local tags = {}\n\n ---@type string[]|?\n local contents\n if opts.load_contents then\n contents = {}\n end\n\n ---@type table|?\n local anchor_links\n ---@type obsidian.note.HeaderAnchor[]|?\n local anchor_stack\n if opts.collect_anchor_links then\n anchor_links = {}\n anchor_stack = {}\n end\n\n ---@type table|?\n local blocks\n if opts.collect_blocks then\n blocks = {}\n end\n\n ---@param anchor_data obsidian.note.HeaderAnchor\n ---@return obsidian.note.HeaderAnchor|?\n local function get_parent_anchor(anchor_data)\n assert(anchor_links)\n assert(anchor_stack)\n for i = #anchor_stack, 1, -1 do\n local parent = anchor_stack[i]\n if parent.level < anchor_data.level then\n return parent\n end\n end\n end\n\n ---@param anchor string\n ---@param data obsidian.note.HeaderAnchor|?\n local function format_nested_anchor(anchor, data)\n local out = anchor\n if not data then\n return out\n end\n\n local parent = data.parent\n while parent ~= nil do\n out = parent.anchor .. out\n data = get_parent_anchor(parent)\n if data then\n parent = data.parent\n else\n parent = nil\n end\n end\n\n return out\n end\n\n -- Iterate over lines in the file, collecting frontmatter and parsing the title.\n local frontmatter_lines = {}\n local has_frontmatter, in_frontmatter, at_boundary = false, false, false -- luacheck: ignore (false positive)\n local frontmatter_end_line = nil\n local in_code_block = false\n for line_idx, line in enumerate(lines) do\n line = util.rstrip_whitespace(line)\n\n if line_idx == 1 and Note._is_frontmatter_boundary(line) then\n has_frontmatter = true\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n frontmatter_end_line = line_idx\n else\n at_boundary = false\n end\n\n if string.match(line, CODE_BLOCK_PATTERN) then\n in_code_block = not in_code_block\n end\n\n if in_frontmatter and not at_boundary then\n table.insert(frontmatter_lines, line)\n elseif not in_frontmatter and not at_boundary and not in_code_block then\n -- Check for title/header and collect anchor link.\n local header_match = util.parse_header(line)\n if header_match then\n if not title and header_match.level == 1 then\n title = header_match.header\n end\n\n -- Collect anchor link.\n if opts.collect_anchor_links then\n assert(anchor_links)\n assert(anchor_stack)\n -- We collect up to two anchor for each header. One standalone, e.g. '#header1', and\n -- one with the parents, e.g. '#header1#header2'.\n -- This is our standalone one:\n ---@type obsidian.note.HeaderAnchor\n local data = {\n anchor = header_match.anchor,\n line = line_idx,\n header = header_match.header,\n level = header_match.level,\n }\n data.parent = get_parent_anchor(data)\n\n anchor_links[header_match.anchor] = data\n table.insert(anchor_stack, data)\n\n -- Now if there's a parent we collect the nested version. All of the data will be the same\n -- except the anchor key.\n if data.parent ~= nil then\n local nested_anchor = format_nested_anchor(header_match.anchor, data)\n anchor_links[nested_anchor] = vim.tbl_extend(\"force\", data, { anchor = nested_anchor })\n end\n end\n end\n\n -- Check for block.\n if opts.collect_blocks then\n local block = util.parse_block(line)\n if block then\n blocks[block] = { id = block, line = line_idx, block = line }\n end\n end\n end\n\n -- Collect contents.\n if contents ~= nil then\n table.insert(contents, line)\n end\n\n -- Check if we can stop reading lines now.\n if\n line_idx > max_lines\n or (title and not opts.load_contents and not opts.collect_anchor_links and not opts.collect_blocks)\n then\n break\n end\n end\n\n if title ~= nil then\n -- Remove references and links from title\n title = search.replace_refs(title)\n end\n\n -- Parse the frontmatter YAML.\n local metadata = nil\n if #frontmatter_lines > 0 then\n local frontmatter = table.concat(frontmatter_lines, \"\\n\")\n local ok, data = pcall(yaml.loads, frontmatter)\n if type(data) ~= \"table\" then\n data = {}\n end\n if ok then\n ---@diagnostic disable-next-line: param-type-mismatch\n for k, v in pairs(data) do\n if k == \"id\" then\n if type(v) == \"string\" or type(v) == \"number\" then\n id = v\n else\n log.warn(\"Invalid 'id' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"aliases\" then\n if type(v) == \"table\" then\n for alias in iter(v) do\n if type(alias) == \"string\" then\n table.insert(aliases, alias)\n else\n log.warn(\n \"Invalid alias value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(alias)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n table.insert(aliases, v)\n else\n log.warn(\"Invalid 'aliases' in frontmatter for \" .. tostring(path))\n end\n elseif k == \"tags\" then\n if type(v) == \"table\" then\n for tag in iter(v) do\n if type(tag) == \"string\" then\n table.insert(tags, tag)\n else\n log.warn(\n \"Invalid tag value found in frontmatter for \"\n .. tostring(path)\n .. \". Expected string, found \"\n .. type(tag)\n .. \".\"\n )\n end\n end\n elseif type(v) == \"string\" then\n tags = vim.split(v, \" \")\n else\n log.warn(\"Invalid 'tags' in frontmatter for '%s'\", path)\n end\n else\n if metadata == nil then\n metadata = {}\n end\n metadata[k] = v\n end\n end\n end\n end\n\n -- ID should default to the filename without the extension.\n if id == nil or id == path.name then\n id = path.stem\n end\n assert(id)\n\n local n = Note.new(id, aliases, tags, path)\n n.title = title\n n.metadata = metadata\n n.has_frontmatter = has_frontmatter\n n.frontmatter_end_line = frontmatter_end_line\n n.contents = contents\n n.anchor_links = anchor_links\n n.blocks = blocks\n return n\nend\n\n--- Check if a line matches a frontmatter boundary.\n---\n---@param line string\n---\n---@return boolean\n---\n---@private\nNote._is_frontmatter_boundary = function(line)\n return line:match \"^---+$\" ~= nil\nend\n\n--- Get the frontmatter table to save.\n---\n---@return table\nNote.frontmatter = function(self)\n local out = { id = self.id, aliases = self.aliases, tags = self.tags }\n if self.metadata ~= nil and not vim.tbl_isempty(self.metadata) then\n for k, v in pairs(self.metadata) do\n out[k] = v\n end\n end\n return out\nend\n\n--- Get frontmatter lines that can be written to a buffer.\n---\n---@param eol boolean|?\n---@param frontmatter table|?\n---\n---@return string[]\nNote.frontmatter_lines = function(self, eol, frontmatter)\n local new_lines = { \"---\" }\n\n local frontmatter_ = frontmatter and frontmatter or self:frontmatter()\n if vim.tbl_isempty(frontmatter_) then\n return {}\n end\n\n for line in\n iter(yaml.dumps_lines(frontmatter_, function(a, b)\n local a_idx = nil\n local b_idx = nil\n for i, k in ipairs { \"id\", \"aliases\", \"tags\" } do\n if a == k then\n a_idx = i\n end\n if b == k then\n b_idx = i\n end\n end\n if a_idx ~= nil and b_idx ~= nil then\n return a_idx < b_idx\n elseif a_idx ~= nil then\n return true\n elseif b_idx ~= nil then\n return false\n else\n return a < b\n end\n end))\n do\n table.insert(new_lines, line)\n end\n\n table.insert(new_lines, \"---\")\n if not self.has_frontmatter then\n -- Make sure there's an empty line between end of the frontmatter and the contents.\n table.insert(new_lines, \"\")\n end\n\n if eol then\n return vim.tbl_map(function(l)\n return l .. \"\\n\"\n end, new_lines)\n else\n return new_lines\n end\nend\n\n--- Update the frontmatter in a buffer for the note.\n---\n---@param bufnr integer|?\n---\n---@return boolean updated If the the frontmatter was updated.\nNote.update_frontmatter = function(self, bufnr)\n if not self:should_save_frontmatter() then\n return false\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n return self:save_to_buffer { bufnr = bufnr, frontmatter = frontmatter }\nend\n\n--- Checks if the parameter note is in the blacklist of files which shouldn't have\n--- frontmatter applied\n---\n--- @param note obsidian.Note The note\n--- @return boolean true if so\nlocal is_in_frontmatter_blacklist = function(note)\n local fname = note:fname()\n return (fname ~= nil and vim.list_contains(SKIP_UPDATING_FRONTMATTER, fname))\nend\n\n--- Determines whether a note's frontmatter is managed by obsidian.nvim.\n---\n---@return boolean\nNote.should_save_frontmatter = function(self)\n -- Check if the note is a template.\n local templates_dir = api.templates_dir()\n if templates_dir ~= nil then\n templates_dir = templates_dir:resolve()\n for _, parent in ipairs(self.path:parents()) do\n if parent == templates_dir then\n return false\n end\n end\n end\n\n if is_in_frontmatter_blacklist(self) then\n return false\n elseif type(Obsidian.opts.disable_frontmatter) == \"boolean\" then\n return not Obsidian.opts.disable_frontmatter\n elseif type(Obsidian.opts.disable_frontmatter) == \"function\" then\n return not Obsidian.opts.disable_frontmatter(self.path:vault_relative_path { strict = true })\n else\n return true\n end\nend\n\n--- Write the note to disk.\n---\n---@param opts? obsidian.note.NoteWriteOpts\n---@return obsidian.Note\nNote.write = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n local path = assert(self.path, \"A path must be provided\")\n path = Path.new(path)\n\n ---@type string\n local verb\n if path:is_file() then\n verb = \"Updated\"\n else\n verb = \"Created\"\n if opts.template ~= nil then\n self = Template.clone_template {\n type = \"clone_template\",\n template_name = opts.template,\n destination_path = path,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n partial_note = self,\n }\n end\n end\n\n local frontmatter = nil\n if Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n self:save {\n path = path,\n insert_frontmatter = self:should_save_frontmatter(),\n frontmatter = frontmatter,\n update_content = opts.update_content,\n check_buffers = opts.check_buffers,\n }\n\n log.info(\"%s note '%s' at '%s'\", verb, self.id, self.path:vault_relative_path(self.path) or self.path)\n\n return self\nend\n\n--- Save the note to a file.\n--- In general this only updates the frontmatter and header, leaving the rest of the contents unchanged\n--- unless you use the `update_content()` callback.\n---\n---@param opts? obsidian.note.NoteSaveOpts\nNote.save = function(self, opts)\n opts = vim.tbl_extend(\"keep\", opts or {}, { check_buffers = true })\n\n if self.path == nil then\n error \"a path is required\"\n end\n\n local save_path = Path.new(assert(opts.path or self.path)):resolve()\n assert(save_path:parent()):mkdir { parents = true, exist_ok = true }\n\n -- Read contents from existing file or buffer, if there is one.\n -- TODO: check for open buffer?\n ---@type string[]\n local content = {}\n ---@type string[]\n local existing_frontmatter = {}\n if self.path ~= nil and self.path:is_file() then\n -- with(open(tostring(self.path)), function(reader)\n local in_frontmatter, at_boundary = false, false -- luacheck: ignore (false positive)\n for idx, line in enumerate(io.lines(tostring(self.path))) do\n if idx == 1 and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = true\n elseif in_frontmatter and Note._is_frontmatter_boundary(line) then\n at_boundary = true\n in_frontmatter = false\n else\n at_boundary = false\n end\n\n if not in_frontmatter and not at_boundary then\n table.insert(content, line)\n else\n table.insert(existing_frontmatter, line)\n end\n end\n -- end)\n elseif self.title ~= nil then\n -- Add a header.\n table.insert(content, \"# \" .. self.title)\n end\n\n -- Pass content through callback.\n if opts.update_content then\n content = opts.update_content(content)\n end\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n -- Replace frontmatter.\n new_lines = compat.flatten { self:frontmatter_lines(false, opts.frontmatter), content }\n else\n -- Use existing frontmatter.\n new_lines = compat.flatten { existing_frontmatter, content }\n end\n\n util.write_file(tostring(save_path), table.concat(new_lines, \"\\n\"))\n\n if opts.check_buffers then\n -- `vim.fn.bufnr` returns the **max** bufnr loaded from the same path.\n if vim.fn.bufnr(save_path.filename) ~= -1 then\n -- But we want to call |checktime| on **all** buffers loaded from the path.\n vim.cmd.checktime(save_path.filename)\n end\n end\nend\n\n--- Write the note to a buffer.\n---\n---@param opts { bufnr: integer|?, template: string|? }|? Options.\n---\n--- Options:\n--- - `bufnr`: Override the buffer to write to. Defaults to current buffer.\n--- - `template`: The name of a template to use if the buffer is empty.\n---\n---@return boolean updated If the buffer was updated.\nNote.write_to_buffer = function(self, opts)\n local Template = require \"obsidian.templates\"\n opts = opts or {}\n\n if opts.template and api.buffer_is_empty(opts.bufnr) then\n self = Template.insert_template {\n type = \"insert_template\",\n template_name = opts.template,\n template_opts = Obsidian.opts.templates,\n templates_dir = assert(api.templates_dir(), \"Templates folder is not defined or does not exist\"),\n location = api.get_active_window_cursor_location(),\n partial_note = self,\n }\n end\n\n local frontmatter = nil\n local should_save_frontmatter = self:should_save_frontmatter()\n if should_save_frontmatter and Obsidian.opts.note_frontmatter_func ~= nil then\n frontmatter = Obsidian.opts.note_frontmatter_func(self)\n end\n\n return self:save_to_buffer {\n bufnr = opts.bufnr,\n insert_frontmatter = should_save_frontmatter,\n frontmatter = frontmatter,\n }\nend\n\n--- Save the note to the buffer\n---\n---@param opts { bufnr: integer|?, insert_frontmatter: boolean|?, frontmatter: table|? }|? Options.\n---\n---@return boolean updated True if the buffer lines were updated, false otherwise.\nNote.save_to_buffer = function(self, opts)\n opts = opts or {}\n\n local bufnr = opts.bufnr\n if not bufnr then\n bufnr = self.bufnr or 0\n end\n\n local cur_buf_note = Note.from_buffer(bufnr)\n\n ---@type string[]\n local new_lines\n if opts.insert_frontmatter ~= false then\n new_lines = self:frontmatter_lines(nil, opts.frontmatter)\n else\n new_lines = {}\n end\n\n if api.buffer_is_empty(bufnr) and self.title ~= nil then\n table.insert(new_lines, \"# \" .. self.title)\n end\n\n ---@type string[]\n local cur_lines = {}\n if cur_buf_note.frontmatter_end_line ~= nil then\n cur_lines = vim.api.nvim_buf_get_lines(bufnr, 0, cur_buf_note.frontmatter_end_line, false)\n end\n\n if not vim.deep_equal(cur_lines, new_lines) then\n vim.api.nvim_buf_set_lines(\n bufnr,\n 0,\n cur_buf_note.frontmatter_end_line and cur_buf_note.frontmatter_end_line or 0,\n false,\n new_lines\n )\n return true\n else\n return false\n end\nend\n\n--- Try to resolve an anchor link to a line number in the note's file.\n---\n---@param anchor_link string\n---@return obsidian.note.HeaderAnchor|?\nNote.resolve_anchor_link = function(self, anchor_link)\n anchor_link = util.standardize_anchor(anchor_link)\n\n if self.anchor_links ~= nil then\n return self.anchor_links[anchor_link]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_anchor_links = true })\n self.anchor_links = n.anchor_links\n return n:resolve_anchor_link(anchor_link)\nend\n\n--- Try to resolve a block identifier.\n---\n---@param block_id string\n---\n---@return obsidian.note.Block|?\nNote.resolve_block = function(self, block_id)\n block_id = util.standardize_block(block_id)\n\n if self.blocks ~= nil then\n return self.blocks[block_id]\n end\n\n assert(self.path, \"'note.path' is not set\")\n local n = Note.from_file(self.path, { collect_blocks = true })\n self.blocks = n.blocks\n return self.blocks[block_id]\nend\n\n--- Open a note in a buffer.\n---@param opts { line: integer|?, col: integer|?, open_strategy: obsidian.config.OpenStrategy|?, sync: boolean|?, callback: fun(bufnr: integer)|? }|?\nNote.open = function(self, opts)\n opts = opts or {}\n\n local path = self.path\n\n local function open_it()\n local open_cmd = api.get_open_strategy(opts.open_strategy and opts.open_strategy or Obsidian.opts.open_notes_in)\n ---@cast path obsidian.Path\n local bufnr = api.open_buffer(path, { line = opts.line, col = opts.col, cmd = open_cmd })\n if opts.callback then\n opts.callback(bufnr)\n end\n end\n\n if opts.sync then\n open_it()\n else\n vim.schedule(open_it)\n end\nend\n\nreturn Note\n"], ["/obsidian.nvim/lua/obsidian/api.lua", "local M = {}\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal iter, string, table = vim.iter, string, table\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\n\n---@param dir string | obsidian.Path\n---@return Iter\nM.dir = function(dir)\n dir = tostring(dir)\n local dir_opts = {\n depth = 10,\n skip = function(p)\n return not vim.startswith(p, \".\") and p ~= vim.fs.basename(tostring(M.templates_dir()))\n end,\n follow = true,\n }\n\n return vim\n .iter(vim.fs.dir(dir, dir_opts))\n :filter(function(path)\n return vim.endswith(path, \".md\")\n end)\n :map(function(path)\n return vim.fs.joinpath(dir, path)\n end)\nend\n\n--- Get the templates folder.\n---\n---@return obsidian.Path|?\nM.templates_dir = function(workspace)\n local opts = Obsidian.opts\n\n local Workspace = require \"obsidian.workspace\"\n\n if workspace and workspace ~= Obsidian.workspace then\n opts = Workspace.normalize_opts(workspace)\n end\n\n if opts.templates == nil or opts.templates.folder == nil then\n return nil\n end\n\n local paths_to_check = { Obsidian.workspace.root / opts.templates.folder, Path.new(opts.templates.folder) }\n for _, path in ipairs(paths_to_check) do\n if path:is_dir() then\n return path\n end\n end\n\n log.err_once(\"'%s' is not a valid templates directory\", opts.templates.folder)\n return nil\nend\n\n--- Check if a path represents a note in the workspace.\n---\n---@param path string|obsidian.Path\n---@param workspace obsidian.Workspace|?\n---\n---@return boolean\nM.path_is_note = function(path, workspace)\n path = Path.new(path):resolve()\n workspace = workspace or Obsidian.workspace\n\n local in_vault = path.filename:find(vim.pesc(tostring(workspace.root))) ~= nil\n if not in_vault then\n return false\n end\n\n -- Notes have to be markdown file.\n if path.suffix ~= \".md\" then\n return false\n end\n\n -- Ignore markdown files in the templates directory.\n local templates_dir = M.templates_dir(workspace)\n if templates_dir ~= nil then\n if templates_dir:is_parent_of(path) then\n return false\n end\n end\n\n return true\nend\n\n--- Get the current note from a buffer.\n---\n---@param bufnr integer|?\n---@param opts obsidian.note.LoadOpts|?\n---\n---@return obsidian.Note|?\n---@diagnostic disable-next-line: unused-local\nM.current_note = function(bufnr, opts)\n bufnr = bufnr or 0\n local Note = require \"obsidian.note\"\n if not M.path_is_note(vim.api.nvim_buf_get_name(bufnr)) then\n return nil\n end\n\n opts = opts or {}\n if not opts.max_lines then\n opts.max_lines = Obsidian.opts.search_max_lines\n end\n return Note.from_buffer(bufnr, opts)\nend\n\n---builtin functions that are impure, interacts with editor state, like vim.api\n\n---Toggle the checkbox on the current line.\n---\n---@param states table|nil Optional table containing checkbox states (e.g., {\" \", \"x\"}).\n---@param line_num number|nil Optional line number to toggle the checkbox on. Defaults to the current line.\nM.toggle_checkbox = function(states, line_num)\n if not util.in_node { \"list\", \"paragraph\" } or util.in_node \"block_quote\" then\n return\n end\n line_num = line_num or unpack(vim.api.nvim_win_get_cursor(0))\n local line = vim.api.nvim_buf_get_lines(0, line_num - 1, line_num, false)[1]\n\n local checkboxes = states or { \" \", \"x\" }\n\n if util.is_checkbox(line) then\n for i, check_char in ipairs(checkboxes) do\n if string.match(line, \"^.* %[\" .. vim.pesc(check_char) .. \"%].*\") then\n i = i % #checkboxes\n line = string.gsub(line, vim.pesc(\"[\" .. check_char .. \"]\"), \"[\" .. checkboxes[i + 1] .. \"]\", 1)\n break\n end\n end\n elseif Obsidian.opts.checkbox.create_new then\n local unordered_list_pattern = \"^(%s*)[-*+] (.*)\"\n if string.match(line, unordered_list_pattern) then\n line = string.gsub(line, unordered_list_pattern, \"%1- [ ] %2\")\n else\n line = string.gsub(line, \"^(%s*)\", \"%1- [ ] \")\n end\n else\n goto out\n end\n\n vim.api.nvim_buf_set_lines(0, line_num - 1, line_num, true, { line })\n ::out::\nend\n\n---@return [number, number, number, number] tuple containing { buf, win, row, col }\nM.get_active_window_cursor_location = function()\n local buf = vim.api.nvim_win_get_buf(0)\n local win = vim.api.nvim_get_current_win()\n local row, col = unpack(vim.api.nvim_win_get_cursor(win))\n local location = { buf, win, row, col }\n return location\nend\n\n--- Create a formatted markdown / wiki link for a note.\n---\n---@param note obsidian.Note|obsidian.Path|string The note/path to link to.\n---@param opts { label: string|?, link_style: obsidian.config.LinkStyle|?, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }|? Options.\n---\n---@return string\nM.format_link = function(note, opts)\n local config = require \"obsidian.config\"\n opts = opts or {}\n\n ---@type string, string, string|integer|?\n local rel_path, label, note_id\n if type(note) == \"string\" or Path.is_path_obj(note) then\n ---@cast note string|obsidian.Path\n -- rel_path = tostring(self:vault_relative_path(note, { strict = true }))\n rel_path = assert(Path.new(note):vault_relative_path { strict = true })\n label = opts.label or tostring(note)\n note_id = opts.id\n else\n ---@cast note obsidian.Note\n -- rel_path = tostring(self:vault_relative_path(note.path, { strict = true }))\n rel_path = assert(note.path:vault_relative_path { strict = true })\n label = opts.label or note:display_name()\n note_id = opts.id or note.id\n end\n\n local link_style = opts.link_style\n if link_style == nil then\n link_style = Obsidian.opts.preferred_link_style\n end\n\n local new_opts = { path = rel_path, label = label, id = note_id, anchor = opts.anchor, block = opts.block }\n\n if link_style == config.LinkStyle.markdown then\n return Obsidian.opts.markdown_link_func(new_opts)\n elseif link_style == config.LinkStyle.wiki or link_style == nil then\n return Obsidian.opts.wiki_link_func(new_opts)\n else\n error(string.format(\"Invalid link style '%s'\", link_style))\n end\nend\n\n---Return the full link under cursror\n---\n---@return string? link\n---@return obsidian.search.RefTypes? link_type\nM.cursor_link = function()\n local line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- 0-indexed column to 1-indexed lua string position\n\n local refs = search.find_refs(line, { include_naked_urls = true, include_file_urls = true, include_block_ids = true })\n\n local match = iter(refs):find(function(match)\n local open, close = unpack(match)\n return cur_col >= open and cur_col <= close\n end)\n if match then\n return line:sub(match[1], match[2]), match[3]\n end\nend\n\n---Get the tag under the cursor, if there is one.\n---@return string?\nM.cursor_tag = function()\n local current_line = vim.api.nvim_get_current_line()\n local _, cur_col = unpack(vim.api.nvim_win_get_cursor(0))\n cur_col = cur_col + 1 -- nvim_win_get_cursor returns 0-indexed column\n\n for match in iter(search.find_tags(current_line)) do\n local open, close, _ = unpack(match)\n if open <= cur_col and cur_col <= close then\n return string.sub(current_line, open + 1, close)\n end\n end\n\n return nil\nend\n\n--- Get the heading under the cursor, if there is one.\n---@return { header: string, level: integer, anchor: string }|?\nM.cursor_heading = function()\n return util.parse_header(vim.api.nvim_get_current_line())\nend\n\n------------------\n--- buffer api ---\n------------------\n\n--- Check if a buffer is empty.\n---\n---@param bufnr integer|?\n---\n---@return boolean\nM.buffer_is_empty = function(bufnr)\n bufnr = bufnr or 0\n if vim.api.nvim_buf_line_count(bufnr) > 1 then\n return false\n else\n local first_text = vim.api.nvim_buf_get_text(bufnr, 0, 0, 0, 0, {})\n if vim.tbl_isempty(first_text) or first_text[1] == \"\" then\n return true\n else\n return false\n end\n end\nend\n\n--- Open a buffer for the corresponding path.\n---\n---@param path string|obsidian.Path\n---@param opts { line: integer|?, col: integer|?, cmd: string|? }|?\n---@return integer bufnr\nM.open_buffer = function(path, opts)\n path = Path.new(path):resolve()\n opts = opts and opts or {}\n local cmd = vim.trim(opts.cmd and opts.cmd or \"e\")\n\n ---@type integer|?\n local result_bufnr\n\n -- Check for buffer in windows and use 'drop' command if one is found.\n for _, winnr in ipairs(vim.api.nvim_list_wins()) do\n local bufnr = vim.api.nvim_win_get_buf(winnr)\n local bufname = vim.api.nvim_buf_get_name(bufnr)\n if bufname == tostring(path) then\n cmd = \"drop\"\n result_bufnr = bufnr\n break\n end\n end\n\n vim.cmd(string.format(\"%s %s\", cmd, vim.fn.fnameescape(tostring(path))))\n if opts.line then\n vim.api.nvim_win_set_cursor(0, { tonumber(opts.line), opts.col and opts.col or 0 })\n end\n\n if not result_bufnr then\n result_bufnr = vim.api.nvim_get_current_buf()\n end\n\n return result_bufnr\nend\n\n---Get an iterator of (bufnr, bufname) over all named buffers. The buffer names will be absolute paths.\n---\n---@return function () -> (integer, string)|?\nM.get_named_buffers = function()\n local idx = 0\n local buffers = vim.api.nvim_list_bufs()\n\n ---@return integer|?\n ---@return string|?\n return function()\n while idx < #buffers do\n idx = idx + 1\n local bufnr = buffers[idx]\n if vim.api.nvim_buf_is_loaded(bufnr) then\n return bufnr, vim.api.nvim_buf_get_name(bufnr)\n end\n end\n end\nend\n\n----------------\n--- text api ---\n----------------\n\n--- Get the current visual selection of text and exit visual mode.\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return { lines: string[], selection: string, csrow: integer, cscol: integer, cerow: integer, cecol: integer }|?\nM.get_visual_selection = function(opts)\n opts = opts or {}\n -- Adapted from fzf-lua:\n -- https://github.com/ibhagwan/fzf-lua/blob/6ee73fdf2a79bbd74ec56d980262e29993b46f2b/lua/fzf-lua/utils.lua#L434-L466\n -- this will exit visual mode\n -- use 'gv' to reselect the text\n local _, csrow, cscol, cerow, cecol\n local mode = vim.fn.mode()\n if opts.strict and not vim.endswith(string.lower(mode), \"v\") then\n return\n end\n\n if mode == \"v\" or mode == \"V\" or mode == \"\u0016\" then\n -- if we are in visual mode use the live position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \".\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"v\")\n if mode == \"V\" then\n -- visual line doesn't provide columns\n cscol, cecol = 0, 999\n end\n -- exit visual mode\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", true)\n else\n -- otherwise, use the last known visual position\n _, csrow, cscol, _ = unpack(vim.fn.getpos \"'<\")\n _, cerow, cecol, _ = unpack(vim.fn.getpos \"'>\")\n end\n\n -- Swap vars if needed\n if cerow < csrow then\n csrow, cerow = cerow, csrow\n cscol, cecol = cecol, cscol\n elseif cerow == csrow and cecol < cscol then\n cscol, cecol = cecol, cscol\n end\n\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n if vim.tbl_isempty(lines) then\n return\n end\n\n -- When the whole line is selected via visual line mode (\"V\"), cscol / cecol will be equal to \"v:maxcol\"\n -- for some odd reason. So change that to what they should be here. See ':h getpos' for more info.\n local maxcol = vim.api.nvim_get_vvar \"maxcol\"\n if cscol == maxcol then\n cscol = string.len(lines[1])\n end\n if cecol == maxcol then\n cecol = string.len(lines[#lines])\n end\n\n ---@type string\n local selection\n local n = #lines\n if n <= 0 then\n selection = \"\"\n elseif n == 1 then\n selection = string.sub(lines[1], cscol, cecol)\n elseif n == 2 then\n selection = string.sub(lines[1], cscol) .. \"\\n\" .. string.sub(lines[n], 1, cecol)\n else\n selection = string.sub(lines[1], cscol)\n .. \"\\n\"\n .. table.concat(lines, \"\\n\", 2, n - 1)\n .. \"\\n\"\n .. string.sub(lines[n], 1, cecol)\n end\n\n return {\n lines = lines,\n selection = selection,\n csrow = csrow,\n cscol = cscol,\n cerow = cerow,\n cecol = cecol,\n }\nend\n\n------------------\n--- UI helpers ---\n------------------\n\n---Get the strategy for opening notes\n---\n---@param opt obsidian.config.OpenStrategy\n---@return string\nM.get_open_strategy = function(opt)\n local OpenStrategy = require(\"obsidian.config\").OpenStrategy\n\n -- either 'leaf', 'row' for vertically split windows, or 'col' for horizontally split windows\n local cur_layout = vim.fn.winlayout()[1]\n\n if vim.startswith(OpenStrategy.hsplit, opt) then\n if cur_layout ~= \"col\" then\n return \"split \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit, opt) then\n if cur_layout ~= \"row\" then\n return \"vsplit \"\n else\n return \"e \"\n end\n elseif vim.startswith(OpenStrategy.vsplit_force, opt) then\n return \"vsplit \"\n elseif vim.startswith(OpenStrategy.hsplit_force, opt) then\n return \"hsplit \"\n elseif vim.startswith(OpenStrategy.current, opt) then\n return \"e \"\n else\n log.err(\"undefined open strategy '%s'\", opt)\n return \"e \"\n end\nend\n\n----------------------------\n--- Integration helpers ----\n----------------------------\n\n--- Get the path to where a plugin is installed.\n---\n---@param name string\n---@return string|?\nlocal get_src_root = function(name)\n return vim.iter(vim.api.nvim_list_runtime_paths()):find(function(path)\n return vim.endswith(path, name)\n end)\nend\n\n--- Get info about a plugin.\n---\n---@param name string\n---\n---@return { commit: string|?, path: string }|?\nM.get_plugin_info = function(name)\n local src_root = get_src_root(name)\n if not src_root then\n return\n end\n local out = { path = src_root }\n local obj = vim.system({ \"git\", \"rev-parse\", \"HEAD\" }, { cwd = src_root }):wait(1000)\n if obj.code == 0 then\n out.commit = vim.trim(obj.stdout)\n else\n out.commit = \"unknown\"\n end\n return out\nend\n\n--- Get info about a external dependency.\n---\n---@param cmd string\n---@return string|?\nM.get_external_dependency_info = function(cmd)\n local obj = vim.system({ cmd, \"--version\" }, {}):wait(1000)\n if obj.code ~= 0 then\n return\n end\n local version = vim.version.parse(obj.stdout)\n if version then\n return (\"%d.%d.%d\"):format(version.major, version.minor, version.patch)\n end\nend\n\n------------------\n--- UI helpers ---\n------------------\n\nlocal INPUT_CANCELLED = \"~~~INPUT-CANCELLED~~~\"\n\n--- Prompt user for an input. Returns nil if canceled, otherwise a string (possibly empty).\n---\n---@param prompt string\n---@param opts { completion: string|?, default: string|? }|?\n---\n---@return string|?\nM.input = function(prompt, opts)\n opts = opts or {}\n\n if not vim.endswith(prompt, \" \") then\n prompt = prompt .. \" \"\n end\n\n local input = vim.trim(\n vim.fn.input { prompt = prompt, completion = opts.completion, default = opts.default, cancelreturn = INPUT_CANCELLED }\n )\n\n if input ~= INPUT_CANCELLED then\n return input\n else\n return nil\n end\nend\n\n--- Prompt user for a confirmation.\n---\n---@param prompt string\n---\n---@return boolean\nM.confirm = function(prompt)\n if not vim.endswith(util.rstrip_whitespace(prompt), \"[Y/n]\") then\n prompt = util.rstrip_whitespace(prompt) .. \" [Y/n] \"\n end\n\n local confirmation = M.input(prompt)\n if confirmation == nil then\n return false\n end\n\n confirmation = string.lower(confirmation)\n\n if confirmation == \"\" or confirmation == \"y\" or confirmation == \"yes\" then\n return true\n else\n return false\n end\nend\n\n---@enum OSType\nM.OSType = {\n Linux = \"Linux\",\n Wsl = \"Wsl\",\n Windows = \"Windows\",\n Darwin = \"Darwin\",\n FreeBSD = \"FreeBSD\",\n}\n\nM._current_os = nil\n\n---Get the running operating system.\n---Reference https://vi.stackexchange.com/a/2577/33116\n---@return OSType\nM.get_os = function()\n if M._current_os ~= nil then\n return M._current_os\n end\n\n local this_os\n if vim.fn.has \"win32\" == 1 then\n this_os = M.OSType.Windows\n else\n local sysname = vim.uv.os_uname().sysname\n local release = vim.uv.os_uname().release:lower()\n if sysname:lower() == \"linux\" and string.find(release, \"microsoft\") then\n this_os = M.OSType.Wsl\n else\n this_os = sysname\n end\n end\n\n assert(this_os)\n M._current_os = this_os\n return this_os\nend\n\n--- Get a nice icon for a file or URL, if possible.\n---\n---@param path string\n---\n---@return string|?, string|? (icon, hl_group) The icon and highlight group.\nM.get_icon = function(path)\n if util.is_url(path) then\n local icon = \"\"\n local _, hl_group = M.get_icon \"blah.html\"\n return icon, hl_group\n else\n local ok, res = pcall(function()\n local icon, hl_group = require(\"nvim-web-devicons\").get_icon(path, nil, { default = true })\n return { icon, hl_group }\n end)\n if ok and type(res) == \"table\" then\n local icon, hlgroup = unpack(res)\n return icon, hlgroup\n elseif vim.endswith(path, \".md\") then\n return \"\"\n end\n end\n return nil\nend\n\n--- Resolve a basename to full path inside the vault.\n---\n---@param src string\n---@return string\nM.resolve_image_path = function(src)\n local img_folder = Obsidian.opts.attachments.img_folder\n\n ---@cast img_folder -nil\n if vim.startswith(img_folder, \".\") then\n local dirname = Path.new(vim.fs.dirname(vim.api.nvim_buf_get_name(0)))\n return tostring(dirname / img_folder / src)\n else\n return tostring(Obsidian.dir / img_folder / src)\n end\nend\n\n--- Follow a link. If the link argument is `nil` we attempt to follow a link under the cursor.\n---\n---@param link string\n---@param opts { open_strategy: obsidian.config.OpenStrategy|? }|?\nM.follow_link = function(link, opts)\n opts = opts and opts or {}\n local Note = require \"obsidian.note\"\n\n search.resolve_link_async(link, function(results)\n if #results == 0 then\n return\n end\n\n ---@param res obsidian.ResolveLinkResult\n local function follow_link(res)\n if res.url ~= nil then\n Obsidian.opts.follow_url_func(res.url)\n return\n end\n\n if util.is_img(res.location) then\n local path = Obsidian.dir / res.location\n Obsidian.opts.follow_img_func(tostring(path))\n return\n end\n\n if res.note ~= nil then\n -- Go to resolved note.\n return res.note:open { line = res.line, col = res.col, open_strategy = opts.open_strategy }\n end\n\n if res.link_type == search.RefTypes.Wiki or res.link_type == search.RefTypes.WikiWithAlias then\n -- Prompt to create a new note.\n if M.confirm(\"Create new note '\" .. res.location .. \"'?\") then\n -- Create a new note.\n ---@type string|?, string[]\n local id, aliases\n if res.name == res.location then\n aliases = {}\n else\n aliases = { res.name }\n id = res.location\n end\n\n local note = Note.create { title = res.name, id = id, aliases = aliases }\n return note:open {\n open_strategy = opts.open_strategy,\n callback = function(bufnr)\n note:write_to_buffer { bufnr = bufnr }\n end,\n }\n else\n log.warn \"Aborted\"\n return\n end\n end\n\n return log.err(\"Failed to resolve file '\" .. res.location .. \"'\")\n end\n\n if #results == 1 then\n return vim.schedule(function()\n follow_link(results[1])\n end)\n else\n return vim.schedule(function()\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple matches to '%s', but no picker is configured\", link)\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, res in ipairs(results) do\n local icon, icon_hl\n if res.url ~= nil then\n icon, icon_hl = M.get_icon(res.url)\n end\n table.insert(entries, {\n value = res,\n display = res.name,\n filename = res.path and tostring(res.path) or nil,\n icon = icon,\n icon_hl = icon_hl,\n })\n end\n\n picker:pick(entries, {\n prompt_title = \"Follow link\",\n callback = function(res)\n follow_link(res)\n end,\n })\n end)\n end\n end)\nend\n--------------------------\n---- Mapping functions ---\n--------------------------\n\n---@param direction \"next\" | \"prev\"\nM.nav_link = function(direction)\n vim.validate(\"direction\", direction, \"string\", false, \"nav_link must be called with a direction\")\n local cursor_line, cursor_col = unpack(vim.api.nvim_win_get_cursor(0))\n local Note = require \"obsidian.note\"\n\n search.find_links(Note.from_buffer(0), {}, function(matches)\n if direction == \"next\" then\n for i = 1, #matches do\n local match = matches[i]\n if (match.line > cursor_line) or (cursor_line == match.line and cursor_col < match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n\n if direction == \"prev\" then\n for i = #matches, 1, -1 do\n local match = matches[i]\n if (match.line < cursor_line) or (cursor_line == match.line and cursor_col > match.start) then\n return vim.api.nvim_win_set_cursor(0, { match.line, match.start })\n end\n end\n end\n end)\nend\n\nM.smart_action = function()\n local legacy = Obsidian.opts.legacy_commands\n -- follow link if possible\n if M.cursor_link() then\n return legacy and \"ObsidianFollowLink\" or \"Obsidian follow_link\"\n end\n\n -- show notes with tag if possible\n if M.cursor_tag() then\n return legacy and \"ObsidianTags\" or \"Obsidian tags\"\n end\n\n if M.cursor_heading() then\n return \"za\"\n end\n\n -- toggle task if possible\n -- cycles through your custom UI checkboxes, default: [ ] [~] [>] [x]\n return legacy and \"ObsidianToggleCheckbox\" or \"Obsidian toggle_checkbox\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/async.lua", "local abc = require \"obsidian.abc\"\nlocal async = require \"plenary.async\"\nlocal channel = require(\"plenary.async.control\").channel\nlocal log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal uv = vim.uv\n\nlocal M = {}\n\n---An abstract class that mimics Python's `concurrent.futures.Executor` class.\n---@class obsidian.Executor : obsidian.ABC\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal Executor = abc.new_class()\n\n---@return obsidian.Executor\nExecutor.new = function()\n local self = Executor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback for the executor to run.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local,unused-vararg\nExecutor.submit = function(self, fn, callback, ...)\n error \"not implemented\"\nend\n\n---Map a function over a generator or array of task args, or the keys and values in a regular table.\n---The callback is called with an array of the results once all tasks have finished.\n---The order of the results passed to the callback will be the same as the order of the corresponding task args.\n---\n---@param self obsidian.Executor\n---@param fn function\n---@param task_args table[]|table|function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nExecutor.map = function(self, fn, task_args, callback)\n local results = {}\n local num_tasks = 0\n local tasks_completed = 0\n local all_submitted = false\n local tx, rx = channel.oneshot()\n\n local function collect_results()\n rx()\n return results\n end\n\n local function get_task_done_fn(i)\n return function(...)\n tasks_completed = tasks_completed + 1\n results[i] = { ... }\n if all_submitted and tasks_completed == num_tasks then\n tx()\n end\n end\n end\n\n if type(task_args) == \"table\" and util.islist(task_args) then\n num_tasks = #task_args\n for i, args in ipairs(task_args) do\n if i == #task_args then\n all_submitted = true\n end\n if type(args) ~= \"table\" then\n args = { args }\n end\n self:submit(fn, get_task_done_fn(i), unpack(args))\n end\n elseif type(task_args) == \"table\" then\n num_tasks = vim.tbl_count(task_args)\n local i = 0\n for k, v in pairs(task_args) do\n i = i + 1\n if i == #task_args then\n all_submitted = true\n end\n self:submit(fn, get_task_done_fn(i), k, v)\n end\n elseif type(task_args) == \"function\" then\n local i = 0\n local args = { task_args() }\n local next_args = { task_args() }\n while args[1] ~= nil do\n if next_args[1] == nil then\n all_submitted = true\n end\n i = i + 1\n num_tasks = num_tasks + 1\n self:submit(fn, get_task_done_fn(i), unpack(args))\n args = next_args\n next_args = { task_args() }\n end\n else\n error(string.format(\"unexpected type '%s' for 'task_args'\", type(task_args)))\n end\n\n if num_tasks == 0 then\n if callback ~= nil then\n callback {}\n end\n else\n async.run(collect_results, callback and callback or function(_) end)\n end\nend\n\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param pause_fn function(integer)\nExecutor._join = function(self, timeout, pause_fn)\n local start_time = uv.hrtime() / 1000000 -- ns -> ms\n local pause_for = 100\n if timeout ~= nil then\n pause_for = math.min(timeout / 2, pause_for)\n end\n while self.tasks_pending > 0 or self.tasks_running > 0 do\n pause_fn(pause_for)\n if timeout ~= nil and (uv.hrtime() / 1000000) - start_time > timeout then\n error \"Timeout error from Executor.join()\"\n end\n end\nend\n\n---Block Neovim until all currently running tasks have completed, waiting at most `timeout` milliseconds\n---before raising a timeout error.\n---\n---This is useful in testing, but in general you want to avoid blocking Neovim.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join = function(self, timeout)\n self:_join(timeout, vim.wait)\nend\n\n---An async version of `.join()`.\n---\n---@param self obsidian.Executor\n---@param timeout integer|?\nExecutor.join_async = function(self, timeout)\n self:_join(timeout, async.util.sleep)\nend\n\n---Run the callback when the executor finishes all tasks.\n---@param self obsidian.Executor\n---@param timeout integer|?\n---@param callback function\nExecutor.join_and_then = function(self, timeout, callback)\n async.run(function()\n self:join_async(timeout)\n end, callback)\nend\n\n---An Executor that uses coroutines to run user functions concurrently.\n---@class obsidian.AsyncExecutor : obsidian.Executor\n---@field max_workers integer|?\n---@field tasks_running integer\n---@field tasks_pending integer\nlocal AsyncExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"AsyncExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.AsyncExecutor = AsyncExecutor\n\n---@param max_workers integer|?\n---@return obsidian.AsyncExecutor\nAsyncExecutor.new = function(max_workers)\n local self = AsyncExecutor.init()\n if max_workers == nil then\n max_workers = 10\n elseif max_workers < 0 then\n max_workers = nil\n elseif max_workers == 0 then\n max_workers = 1\n end\n self.max_workers = max_workers\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.AsyncExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nAsyncExecutor.submit = function(self, fn, callback, ...)\n self.tasks_pending = self.tasks_pending + 1\n local args = { ... }\n async.run(function()\n if self.max_workers ~= nil then\n while self.tasks_running >= self.max_workers do\n async.util.sleep(20)\n end\n end\n self.tasks_pending = self.tasks_pending - 1\n self.tasks_running = self.tasks_running + 1\n return fn(unpack(args))\n end, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\nend\n\n---A multi-threaded Executor which uses the Libuv threadpool.\n---@class obsidian.ThreadPoolExecutor : obsidian.Executor\n---@field tasks_running integer\nlocal ThreadPoolExecutor = abc.new_class({\n __tostring = function(self)\n return string.format(\"ThreadPoolExecutor(max_workers=%s)\", self.max_workers)\n end,\n}, Executor.new())\n\nM.ThreadPoolExecutor = ThreadPoolExecutor\n\n---@return obsidian.ThreadPoolExecutor\nThreadPoolExecutor.new = function()\n local self = ThreadPoolExecutor.init()\n self.tasks_running = 0\n self.tasks_pending = 0\n return self\nend\n\n---Submit a one-off function with a callback to the thread pool.\n---\n---@param self obsidian.ThreadPoolExecutor\n---@param fn function\n---@param callback function|?\n---@diagnostic disable-next-line: unused-local\nThreadPoolExecutor.submit = function(self, fn, callback, ...)\n self.tasks_running = self.tasks_running + 1\n local ctx = uv.new_work(fn, function(...)\n self.tasks_running = self.tasks_running - 1\n if callback ~= nil then\n callback(...)\n end\n end)\n ctx:queue(...)\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@param sync boolean\nlocal init_job = function(cmds, on_stdout, on_exit, sync)\n local stderr_lines = false\n\n local on_obj = function(obj)\n --- NOTE: commands like `rg` return a non-zero exit code when there are no matches, which is okay.\n --- So we only log no-zero exit codes as errors when there's also stderr lines.\n if obj.code > 0 and stderr_lines then\n log.err(\"Command '%s' exited with non-zero code %s. See logs for stderr.\", cmds, obj.code)\n elseif stderr_lines then\n log.warn(\"Captured stderr output while running command '%s'. See logs for details.\", cmds)\n end\n if on_exit ~= nil then\n on_exit(obj.code)\n end\n end\n\n on_stdout = util.buffer_fn(on_stdout)\n\n local function stdout(err, data)\n if err ~= nil then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n end\n if data ~= nil then\n on_stdout(data)\n end\n end\n\n local function stderr(err, data)\n if err then\n return log.err(\"Error running command '%s'\\n:%s\", cmds, err)\n elseif data ~= nil then\n if not stderr_lines then\n log.err(\"Captured stderr output while running command '%s'\", cmds)\n stderr_lines = true\n end\n log.err(\"[stderr] %s\", data)\n end\n end\n\n return function()\n log.debug(\"Initializing job '%s'\", cmds)\n\n if sync then\n local obj = vim.system(cmds, { stdout = stdout, stderr = stderr }):wait()\n on_obj(obj)\n return obj\n else\n vim.system(cmds, { stdout = stdout, stderr = stderr }, on_obj)\n end\n end\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\n---@return integer exit_code\nM.run_job = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, true)\n return job().code\nend\n\n---@param cmds string[]\n---@param on_stdout function|? (string) -> nil\n---@param on_exit function|? (integer) -> nil\nM.run_job_async = function(cmds, on_stdout, on_exit)\n local job = init_job(cmds, on_stdout, on_exit, false)\n job()\nend\n\n---@param fn function\n---@param timeout integer (milliseconds)\nM.throttle = function(fn, timeout)\n ---@type integer\n local last_call = 0\n ---@type uv.uv_timer_t?\n local timer = nil\n\n return function(...)\n if timer ~= nil then\n timer:stop()\n end\n\n local ms_remaining = timeout - (vim.uv.now() - last_call)\n\n if ms_remaining > 0 then\n if timer == nil then\n timer = assert(vim.uv.new_timer())\n end\n\n local args = { ... }\n\n timer:start(\n ms_remaining,\n 0,\n vim.schedule_wrap(function()\n if timer ~= nil then\n timer:stop()\n timer:close()\n timer = nil\n end\n\n last_call = vim.uv.now()\n fn(unpack(args))\n end)\n )\n else\n last_call = vim.uv.now()\n fn(...)\n end\n end\nend\n\n---Run an async function in a non-async context. The async function is expected to take a single\n---callback parameters with the results. This function returns those results.\n---@param async_fn_with_callback function (function,) -> any\n---@param timeout integer|?\n---@return ...any results\nM.block_on = function(async_fn_with_callback, timeout)\n local done = false\n local result\n timeout = timeout and timeout or 2000\n\n local function collect_result(...)\n result = { ... }\n done = true\n end\n\n async_fn_with_callback(collect_result)\n\n vim.wait(timeout, function()\n return done\n end, 20, false)\n\n return unpack(result)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/init.lua", "local iter = vim.iter\nlocal log = require \"obsidian.log\"\nlocal legacycommands = require \"obsidian.commands.init-legacy\"\nlocal search = require \"obsidian.search\"\n\nlocal M = { commands = {} }\n\nlocal function in_note()\n return vim.bo.filetype == \"markdown\"\nend\n\n---@param commands obsidian.CommandConfig[]\n---@param is_visual boolean\n---@param is_note boolean\n---@return string[]\nlocal function get_commands_by_context(commands, is_visual, is_note)\n local choices = vim.tbl_values(commands)\n return vim\n .iter(choices)\n :filter(function(config)\n if is_visual then\n return config.range ~= nil\n else\n return config.range == nil\n end\n end)\n :filter(function(config)\n if is_note then\n return true\n else\n return not config.note_action\n end\n end)\n :map(function(config)\n return config.name\n end)\n :totable()\nend\n\nlocal function show_menu(data)\n local is_visual, is_note = data.range ~= 0, in_note()\n local choices = get_commands_by_context(M.commands, is_visual, is_note)\n\n vim.ui.select(choices, { prompt = \"Obsidian Commands\" }, function(item)\n if item then\n return vim.cmd.Obsidian(item)\n else\n vim.notify(\"Aborted\", 3)\n end\n end)\nend\n\n---@class obsidian.CommandConfig\n---@field complete function|string|?\n---@field nargs string|integer|?\n---@field range boolean|?\n---@field func function|? (obsidian.Client, table) -> nil\n---@field name string?\n---@field note_action boolean?\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfig\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n local mod = require(\"obsidian.commands.\" .. name)\n return mod(client, data)\n end\n end\n config.name = name\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n vim.api.nvim_create_user_command(\"Obsidian\", function(data)\n if #data.fargs == 0 then\n show_menu(data)\n return\n end\n M.handle_command(client, data)\n end, {\n nargs = \"*\",\n complete = function(_, cmdline, _)\n return M.get_completions(client, cmdline)\n end,\n range = 2,\n })\nend\n\nM.install_legacy = legacycommands.install\n\n---@param client obsidian.Client\nM.handle_command = function(client, data)\n local cmd = data.fargs[1]\n table.remove(data.fargs, 1)\n data.args = table.concat(data.fargs, \" \")\n local nargs = #data.fargs\n\n local cmdconfig = M.commands[cmd]\n if cmdconfig == nil then\n log.err(\"Command '\" .. cmd .. \"' not found\")\n return\n end\n\n local exp_nargs = cmdconfig.nargs\n local range_allowed = cmdconfig.range\n\n if exp_nargs == \"?\" then\n if nargs > 1 then\n log.err(\"Command '\" .. cmd .. \"' expects 0 or 1 arguments, but \" .. nargs .. \" were provided\")\n return\n end\n elseif exp_nargs == \"+\" then\n if nargs == 0 then\n log.err(\"Command '\" .. cmd .. \"' expects at least one argument, but none were provided\")\n return\n end\n elseif exp_nargs ~= \"*\" and exp_nargs ~= nargs then\n log.err(\"Command '\" .. cmd .. \"' expects \" .. exp_nargs .. \" arguments, but \" .. nargs .. \" were provided\")\n return\n end\n\n if not range_allowed and data.range > 0 then\n log.error(\"Command '\" .. cmd .. \"' does not accept a range\")\n return\n end\n\n cmdconfig.func(client, data)\nend\n\n---@param client obsidian.Client\n---@param cmdline string\nM.get_completions = function(client, cmdline)\n local obspat = \"^['<,'>]*Obsidian[!]?\"\n local splitcmd = vim.split(cmdline, \" \", { plain = true, trimempty = true })\n local obsidiancmd = splitcmd[2]\n if cmdline:match(obspat .. \"%s$\") then\n local is_visual = vim.startswith(cmdline, \"'<,'>\")\n return get_commands_by_context(M.commands, is_visual, in_note())\n end\n if cmdline:match(obspat .. \"%s%S+$\") then\n return vim.tbl_filter(function(s)\n return s:sub(1, #obsidiancmd) == obsidiancmd\n end, vim.tbl_keys(M.commands))\n end\n local cmdconfig = M.commands[obsidiancmd]\n if cmdconfig == nil then\n return\n end\n if cmdline:match(obspat .. \"%s%S*%s%S*$\") then\n local cmd_arg = table.concat(vim.list_slice(splitcmd, 3), \" \")\n local complete_type = type(cmdconfig.complete)\n if complete_type == \"function\" then\n return cmdconfig.complete(cmd_arg)\n end\n if complete_type == \"string\" then\n return vim.fn.getcompletion(cmd_arg, cmdconfig.complete)\n end\n end\nend\n\n--TODO: Note completion is currently broken (see: https://github.com/epwalsh/obsidian.nvim/issues/753)\n---@return string[]\nM.note_complete = function(cmd_arg)\n local query\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\n------------------------\n---- general action ----\n------------------------\n\nM.register(\"check\", { nargs = 0 })\n\nM.register(\"today\", { nargs = \"?\" })\n\nM.register(\"yesterday\", { nargs = 0 })\n\nM.register(\"tomorrow\", { nargs = 0 })\n\nM.register(\"dailies\", { nargs = \"*\" })\n\nM.register(\"new\", { nargs = \"?\" })\n\nM.register(\"open\", { nargs = \"?\", complete = M.note_complete })\n\nM.register(\"tags\", { nargs = \"*\" })\n\nM.register(\"search\", { nargs = \"?\" })\n\nM.register(\"new_from_template\", { nargs = \"*\" })\n\nM.register(\"quick_switch\", { nargs = \"?\" })\n\nM.register(\"workspace\", { nargs = \"?\" })\n\n---------------------\n---- note action ----\n---------------------\n\nM.register(\"backlinks\", { nargs = 0, note_action = true })\n\nM.register(\"template\", { nargs = \"?\", note_action = true })\n\nM.register(\"link_new\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"link\", { nargs = \"?\", range = true, complete = M.note_complete, note_action = true })\n\nM.register(\"links\", { nargs = 0, note_action = true })\n\nM.register(\"follow_link\", { nargs = \"?\", note_action = true })\n\nM.register(\"toggle_checkbox\", { nargs = 0, range = true, note_action = true })\n\nM.register(\"rename\", { nargs = \"?\", note_action = true })\n\nM.register(\"paste_img\", { nargs = \"?\", note_action = true })\n\nM.register(\"extract_note\", { mode = \"v\", nargs = \"?\", range = true, note_action = true })\n\nM.register(\"toc\", { nargs = 0, note_action = true })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/search.lua", "local Path = require \"obsidian.path\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\nlocal run_job_async = require(\"obsidian.async\").run_job_async\nlocal compat = require \"obsidian.compat\"\nlocal log = require \"obsidian.log\"\nlocal block_on = require(\"obsidian.async\").block_on\n\nlocal M = {}\n\nM._BASE_CMD = { \"rg\", \"--no-config\", \"--type=md\" }\nM._SEARCH_CMD = compat.flatten { M._BASE_CMD, \"--json\" }\nM._FIND_CMD = compat.flatten { M._BASE_CMD, \"--files\" }\n\n---@enum obsidian.search.RefTypes\nM.RefTypes = {\n WikiWithAlias = \"WikiWithAlias\",\n Wiki = \"Wiki\",\n Markdown = \"Markdown\",\n NakedUrl = \"NakedUrl\",\n FileUrl = \"FileUrl\",\n MailtoUrl = \"MailtoUrl\",\n Tag = \"Tag\",\n BlockID = \"BlockID\",\n Highlight = \"Highlight\",\n}\n\n---@enum obsidian.search.Patterns\nM.Patterns = {\n -- Tags\n TagCharsOptional = \"[A-Za-z0-9_/-]*\",\n TagCharsRequired = \"[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\", -- assumes tag is at least 2 chars\n Tag = \"#[A-Za-z]+[A-Za-z0-9_/-]*[A-Za-z0-9]+\",\n\n -- Miscellaneous\n Highlight = \"==[^=]+==\", -- ==text==\n\n -- References\n WikiWithAlias = \"%[%[[^][%|]+%|[^%]]+%]%]\", -- [[xxx|yyy]]\n Wiki = \"%[%[[^][%|]+%]%]\", -- [[xxx]]\n Markdown = \"%[[^][]+%]%([^%)]+%)\", -- [yyy](xxx)\n NakedUrl = \"https?://[a-zA-Z0-9._-@]+[a-zA-Z0-9._#/=&?:+%%-@]+[a-zA-Z0-9/]\", -- https://xyz.com\n FileUrl = \"file:/[/{2}]?.*\", -- file:///\n MailtoUrl = \"mailto:.*\", -- mailto:emailaddress\n BlockID = util.BLOCK_PATTERN .. \"$\", -- ^hello-world\n}\n\n---@type table\nM.PatternConfig = {\n [M.RefTypes.Tag] = { ignore_if_escape_prefix = true },\n}\n\n--- Find all matches of a pattern\n---\n---@param s string\n---@param pattern_names obsidian.search.RefTypes[]\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_matches = function(s, pattern_names)\n -- First find all inline code blocks so we can skip reference matches inside of those.\n local inline_code_blocks = {}\n for m_start, m_end in util.gfind(s, \"`[^`]*`\") do\n inline_code_blocks[#inline_code_blocks + 1] = { m_start, m_end }\n end\n\n local matches = {}\n for pattern_name in iter(pattern_names) do\n local pattern = M.Patterns[pattern_name]\n local pattern_cfg = M.PatternConfig[pattern_name]\n local search_start = 1\n while search_start < #s do\n local m_start, m_end = string.find(s, pattern, search_start)\n if m_start ~= nil and m_end ~= nil then\n -- Check if we're inside a code block.\n local inside_code_block = false\n for code_block_boundary in iter(inline_code_blocks) do\n if code_block_boundary[1] < m_start and m_end < code_block_boundary[2] then\n inside_code_block = true\n break\n end\n end\n\n if not inside_code_block then\n -- Check if this match overlaps with any others (e.g. a naked URL match would be contained in\n -- a markdown URL).\n local overlap = false\n for match in iter(matches) do\n if (match[1] <= m_start and m_start <= match[2]) or (match[1] <= m_end and m_end <= match[2]) then\n overlap = true\n break\n end\n end\n\n -- Check if we should skip to an escape sequence before the pattern.\n local skip_due_to_escape = false\n if\n pattern_cfg ~= nil\n and pattern_cfg.ignore_if_escape_prefix\n and string.sub(s, m_start - 1, m_start - 1) == [[\\]]\n then\n skip_due_to_escape = true\n end\n\n if not overlap and not skip_due_to_escape then\n matches[#matches + 1] = { m_start, m_end, pattern_name }\n end\n end\n\n search_start = m_end\n else\n break\n end\n end\n end\n\n -- Sort results by position.\n table.sort(matches, function(a, b)\n return a[1] < b[1]\n end)\n\n return matches\nend\n\n--- Find inline highlights\n---\n---@param s string\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_highlight = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Highlight })) do\n -- Remove highlights that begin/end with whitespace\n local match_start, match_end, _ = unpack(match)\n local text = string.sub(s, match_start + 2, match_end - 2)\n if vim.trim(text) == text then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n---@class obsidian.search.FindRefsOpts\n---\n---@field include_naked_urls boolean|?\n---@field include_tags boolean|?\n---@field include_file_urls boolean|?\n---@field include_block_ids boolean|?\n\n--- Find refs and URLs.\n---@param s string the string to search\n---@param opts obsidian.search.FindRefsOpts|?\n---\n---@return { [1]: integer, [2]: integer, [3]: obsidian.search.RefTypes }[]\nM.find_refs = function(s, opts)\n opts = opts and opts or {}\n\n local pattern_names = { M.RefTypes.WikiWithAlias, M.RefTypes.Wiki, M.RefTypes.Markdown }\n if opts.include_naked_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.NakedUrl\n end\n if opts.include_tags then\n pattern_names[#pattern_names + 1] = M.RefTypes.Tag\n end\n if opts.include_file_urls then\n pattern_names[#pattern_names + 1] = M.RefTypes.FileUrl\n end\n if opts.include_block_ids then\n pattern_names[#pattern_names + 1] = M.RefTypes.BlockID\n end\n\n return M.find_matches(s, pattern_names)\nend\n\n--- Find all tags in a string.\n---@param s string the string to search\n---\n---@return {[1]: integer, [2]: integer, [3]: obsidian.search.RefTypes}[]\nM.find_tags = function(s)\n local matches = {}\n for match in iter(M.find_matches(s, { M.RefTypes.Tag })) do\n local st, ed, m_type = unpack(match)\n local match_string = s:sub(st, ed)\n if m_type == M.RefTypes.Tag and not util.is_hex_color(match_string) then\n matches[#matches + 1] = match\n end\n end\n return matches\nend\n\n--- Replace references of the form '[[xxx|xxx]]', '[[xxx]]', or '[xxx](xxx)' with their title.\n---\n---@param s string\n---\n---@return string\nM.replace_refs = function(s)\n local out, _ = string.gsub(s, \"%[%[[^%|%]]+%|([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[%[([^%]]+)%]%]\", \"%1\")\n out, _ = out:gsub(\"%[([^%]]+)%]%([^%)]+%)\", \"%1\")\n return out\nend\n\n--- Find all refs in a string and replace with their titles.\n---\n---@param s string\n--\n---@return string\n---@return table\n---@return string[]\nM.find_and_replace_refs = function(s)\n local pieces = {}\n local refs = {}\n local is_ref = {}\n local matches = M.find_refs(s)\n local last_end = 1\n for _, match in pairs(matches) do\n local m_start, m_end, _ = unpack(match)\n assert(type(m_start) == \"number\")\n if last_end < m_start then\n table.insert(pieces, string.sub(s, last_end, m_start - 1))\n table.insert(is_ref, false)\n end\n local ref_str = string.sub(s, m_start, m_end)\n table.insert(pieces, M.replace_refs(ref_str))\n table.insert(refs, ref_str)\n table.insert(is_ref, true)\n last_end = m_end + 1\n end\n\n local indices = {}\n local length = 0\n for i, piece in ipairs(pieces) do\n local i_end = length + string.len(piece)\n if is_ref[i] then\n table.insert(indices, { length + 1, i_end })\n end\n length = i_end\n end\n\n return table.concat(pieces, \"\"), indices, refs\nend\n\n--- Find all code block boundaries in a list of lines.\n---\n---@param lines string[]\n---\n---@return { [1]: integer, [2]: integer }[]\nM.find_code_blocks = function(lines)\n ---@type { [1]: integer, [2]: integer }[]\n local blocks = {}\n ---@type integer|?\n local start_idx\n for i, line in ipairs(lines) do\n if string.match(line, \"^%s*```.*```%s*$\") then\n table.insert(blocks, { i, i })\n start_idx = nil\n elseif string.match(line, \"^%s*```\") then\n if start_idx ~= nil then\n table.insert(blocks, { start_idx, i })\n start_idx = nil\n else\n start_idx = i\n end\n end\n end\n return blocks\nend\n\n---@class obsidian.search.SearchOpts\n---\n---@field sort_by obsidian.config.SortBy|?\n---@field sort_reversed boolean|?\n---@field fixed_strings boolean|?\n---@field ignore_case boolean|?\n---@field smart_case boolean|?\n---@field exclude string[]|? paths to exclude\n---@field max_count_per_file integer|?\n---@field escape_path boolean|?\n---@field include_non_markdown boolean|?\n\nlocal SearchOpts = {}\nM.SearchOpts = SearchOpts\n\nSearchOpts.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\nend\n\n---@param one obsidian.search.SearchOpts|table\n---@param other obsidian.search.SearchOpts|table\n---@return obsidian.search.SearchOpts\nSearchOpts.merge = function(one, other)\n return vim.tbl_extend(\"force\", SearchOpts.as_tbl(one), SearchOpts.as_tbl(other))\nend\n\n---@param opts obsidian.search.SearchOpts\n---@param path string\nSearchOpts.add_exclude = function(opts, path)\n if opts.exclude == nil then\n opts.exclude = {}\n end\n opts.exclude[#opts.exclude + 1] = path\nend\n\n---@param opts obsidian.search.SearchOpts\n---@return string[]\nSearchOpts.to_ripgrep_opts = function(opts)\n local ret = {}\n\n if opts.sort_by ~= nil then\n local sort = \"sortr\" -- default sort is reverse\n if opts.sort_reversed == false then\n sort = \"sort\"\n end\n ret[#ret + 1] = \"--\" .. sort .. \"=\" .. opts.sort_by\n end\n\n if opts.fixed_strings then\n ret[#ret + 1] = \"--fixed-strings\"\n end\n\n if opts.ignore_case then\n ret[#ret + 1] = \"--ignore-case\"\n end\n\n if opts.smart_case then\n ret[#ret + 1] = \"--smart-case\"\n end\n\n if opts.exclude ~= nil then\n assert(type(opts.exclude) == \"table\")\n for path in iter(opts.exclude) do\n ret[#ret + 1] = \"-g!\" .. path\n end\n end\n\n if opts.max_count_per_file ~= nil then\n ret[#ret + 1] = \"-m=\" .. opts.max_count_per_file\n end\n\n return ret\nend\n\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_search_cmd = function(dir, term, opts)\n opts = opts and opts or {}\n\n local search_terms\n if type(term) == \"string\" then\n search_terms = { \"-e\", term }\n else\n search_terms = {}\n for t in iter(term) do\n search_terms[#search_terms + 1] = \"-e\"\n search_terms[#search_terms + 1] = t\n end\n end\n\n local path = tostring(Path.new(dir):resolve { strict = true })\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(path))\n end\n\n return compat.flatten {\n M._SEARCH_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n search_terms,\n path,\n }\nend\n\n--- Build the 'rg' command for finding files.\n---\n---@param path string|?\n---@param term string|?\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_find_cmd = function(path, term, opts)\n opts = opts and opts or {}\n\n local additional_opts = {}\n\n if term ~= nil then\n if opts.include_non_markdown then\n term = \"*\" .. term .. \"*\"\n elseif not vim.endswith(term, \".md\") then\n term = \"*\" .. term .. \"*.md\"\n else\n term = \"*\" .. term\n end\n additional_opts[#additional_opts + 1] = \"-g\"\n additional_opts[#additional_opts + 1] = term\n end\n\n if opts.ignore_case then\n additional_opts[#additional_opts + 1] = \"--glob-case-insensitive\"\n end\n\n if path ~= nil and path ~= \".\" then\n if opts.escape_path then\n path = assert(vim.fn.fnameescape(tostring(path)))\n end\n additional_opts[#additional_opts + 1] = path\n end\n\n return compat.flatten { M._FIND_CMD, SearchOpts.to_ripgrep_opts(opts), additional_opts }\nend\n\n--- Build the 'rg' grep command for pickers.\n---\n---@param opts obsidian.search.SearchOpts|?\n---\n---@return string[]\nM.build_grep_cmd = function(opts)\n opts = opts and opts or {}\n\n return compat.flatten {\n M._BASE_CMD,\n SearchOpts.to_ripgrep_opts(opts),\n \"--column\",\n \"--line-number\",\n \"--no-heading\",\n \"--with-filename\",\n \"--color=never\",\n }\nend\n\n---@class MatchPath\n---\n---@field text string\n\n---@class MatchText\n---\n---@field text string\n\n---@class SubMatch\n---\n---@field match MatchText\n---@field start integer\n---@field end integer\n\n---@class MatchData\n---\n---@field path MatchPath\n---@field lines MatchText\n---@field line_number integer 0-indexed\n---@field absolute_offset integer\n---@field submatches SubMatch[]\n\n--- Search markdown files in a directory for a given term. Each match is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string|string[]\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(match: MatchData)\n---@param on_exit fun(exit_code: integer)|?\nM.search_async = function(dir, term, opts, on_match, on_exit)\n local cmd = M.build_search_cmd(dir, term, opts)\n run_job_async(cmd, function(line)\n local data = vim.json.decode(line)\n if data[\"type\"] == \"match\" then\n local match_data = data.data\n on_match(match_data)\n end\n end, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\n--- Find markdown files in a directory matching a given term. Each matching path is passed to the `on_match` callback.\n---\n---@param dir string|obsidian.Path\n---@param term string\n---@param opts obsidian.search.SearchOpts|?\n---@param on_match fun(path: string)\n---@param on_exit fun(exit_code: integer)|?\nM.find_async = function(dir, term, opts, on_match, on_exit)\n local norm_dir = Path.new(dir):resolve { strict = true }\n local cmd = M.build_find_cmd(tostring(norm_dir), term, opts)\n run_job_async(cmd, on_match, function(code)\n if on_exit ~= nil then\n on_exit(code)\n end\n end)\nend\n\nlocal search_defualts = {\n sort = false,\n include_templates = false,\n ignore_case = false,\n}\n\n---@param opts obsidian.SearchOpts|boolean|?\n---@param additional_opts obsidian.search.SearchOpts|?\n---\n---@return obsidian.search.SearchOpts\n---\n---@private\nlocal _prepare_search_opts = function(opts, additional_opts)\n opts = opts or search_defualts\n\n local search_opts = {}\n\n if opts.sort then\n search_opts.sort_by = Obsidian.opts.sort_by\n search_opts.sort_reversed = Obsidian.opts.sort_reversed\n end\n\n if not opts.include_templates and Obsidian.opts.templates ~= nil and Obsidian.opts.templates.folder ~= nil then\n M.SearchOpts.add_exclude(search_opts, tostring(Obsidian.opts.templates.folder))\n end\n\n if opts.ignore_case then\n search_opts.ignore_case = true\n end\n\n if additional_opts ~= nil then\n search_opts = M.SearchOpts.merge(search_opts, additional_opts)\n end\n\n return search_opts\nend\n\n---@param term string\n---@param search_opts obsidian.SearchOpts|boolean|?\n---@param find_opts obsidian.SearchOpts|boolean|?\n---@param callback fun(path: obsidian.Path)\n---@param exit_callback fun(paths: obsidian.Path[])\nlocal _search_async = function(term, search_opts, find_opts, callback, exit_callback)\n local found = {}\n local result = {}\n local cmds_done = 0\n\n local function dedup_send(path)\n local key = tostring(path:resolve { strict = true })\n if not found[key] then\n found[key] = true\n result[#result + 1] = path\n callback(path)\n end\n end\n\n local function on_search_match(content_match)\n local path = Path.new(content_match.path.text)\n dedup_send(path)\n end\n\n local function on_find_match(path_match)\n local path = Path.new(path_match)\n dedup_send(path)\n end\n\n local function on_exit()\n cmds_done = cmds_done + 1\n if cmds_done == 2 then\n exit_callback(result)\n end\n end\n\n M.search_async(\n Obsidian.dir,\n term,\n _prepare_search_opts(search_opts, { fixed_strings = true, max_count_per_file = 1 }),\n on_search_match,\n on_exit\n )\n\n M.find_async(Obsidian.dir, term, _prepare_search_opts(find_opts, { ignore_case = true }), on_find_match, on_exit)\nend\n\n--- An async version of `find_notes()` that runs the callback with an array of all matching notes.\n---\n---@param term string The term to search for\n---@param callback fun(notes: obsidian.Note[])\n---@param opts { search: obsidian.SearchOpts|?, notes: obsidian.note.LoadOpts|? }|?\nM.find_notes_async = function(term, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n\n ---@type table\n local paths = {}\n local num_results = 0\n local err_count = 0\n local first_err\n local first_err_path\n local notes = {}\n local Note = require \"obsidian.note\"\n\n ---@param path obsidian.Path\n local function on_path(path)\n local ok, res = pcall(Note.from_file, path, opts.notes)\n\n if ok then\n num_results = num_results + 1\n paths[tostring(path)] = num_results\n notes[#notes + 1] = res\n else\n err_count = err_count + 1\n if first_err == nil then\n first_err = res\n first_err_path = path\n end\n end\n end\n\n local on_exit = function()\n -- Then sort by original order.\n table.sort(notes, function(a, b)\n return paths[tostring(a.path)] < paths[tostring(b.path)]\n end)\n\n -- Check for errors.\n if first_err ~= nil and first_err_path ~= nil then\n log.err(\n \"%d error(s) occurred during search. First error from note at '%s':\\n%s\",\n err_count,\n first_err_path,\n first_err\n )\n end\n\n callback(notes)\n end\n\n _search_async(term, opts.search, nil, on_path, on_exit)\nend\n\nM.find_notes = function(term, opts)\n opts = opts or {}\n opts.timeout = opts.timeout or 1000\n return block_on(function(cb)\n return M.find_notes_async(term, cb, { search = opts.search })\n end, opts.timeout)\nend\n\n---@param query string\n---@param callback fun(results: obsidian.Note[])\n---@param opts { notes: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note|?\nlocal _resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.notes = opts.notes or {}\n if not opts.notes.max_lines then\n opts.notes.max_lines = Obsidian.opts.search_max_lines\n end\n local Note = require \"obsidian.note\"\n\n -- Autocompletion for command args will have this format.\n local note_path, count = string.gsub(query, \"^.*  \", \"\")\n if count > 0 then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n local full_path = Obsidian.dir / note_path\n callback { Note.from_file(full_path, opts.notes) }\n end\n\n -- Query might be a path.\n local fname = query\n if not vim.endswith(fname, \".md\") then\n fname = fname .. \".md\"\n end\n\n local paths_to_check = { Path.new(fname), Obsidian.dir / fname }\n\n if Obsidian.opts.notes_subdir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.notes_subdir / fname\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.dir / Obsidian.opts.daily_notes.folder / fname\n end\n\n if Obsidian.buf_dir ~= nil then\n paths_to_check[#paths_to_check + 1] = Obsidian.buf_dir / fname\n end\n\n for _, path in pairs(paths_to_check) do\n if path:is_file() then\n return callback { Note.from_file(path, opts.notes) }\n end\n end\n\n M.find_notes_async(query, function(results)\n local query_lwr = string.lower(query)\n\n -- We'll gather both exact matches (of ID, filename, and aliases) and fuzzy matches.\n -- If we end up with any exact matches, we'll return those. Otherwise we fall back to fuzzy\n -- matches.\n ---@type obsidian.Note[]\n local exact_matches = {}\n ---@type obsidian.Note[]\n local fuzzy_matches = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local reference_ids = note:reference_ids { lowercase = true }\n\n -- Check for exact match.\n if vim.list_contains(reference_ids, query_lwr) then\n table.insert(exact_matches, note)\n else\n -- Fall back to fuzzy match.\n for ref_id in iter(reference_ids) do\n if util.string_contains(ref_id, query_lwr) then\n table.insert(fuzzy_matches, note)\n break\n end\n end\n end\n end\n\n if #exact_matches > 0 then\n return callback(exact_matches)\n else\n return callback(fuzzy_matches)\n end\n end, { search = { sort = true, ignore_case = true }, notes = opts.notes })\nend\n\n--- Resolve a note, opens a picker to choose a single note when there are multiple matches.\n---\n---@param query string\n---@param callback fun(obsidian.Note)\n---@param opts { notes: obsidian.note.LoadOpts|?, prompt_title: string|?, pick: boolean }|?\n---\n---@return obsidian.Note|?\nM.resolve_note_async = function(query, callback, opts)\n opts = opts or {}\n opts.pick = vim.F.if_nil(opts.pick, true)\n\n _resolve_note_async(query, function(notes)\n if opts.pick then\n if #notes == 0 then\n log.err(\"No notes matching '%s'\", query)\n return\n elseif #notes == 1 then\n return callback(notes[1])\n end\n\n -- Fall back to picker.\n vim.schedule(function()\n -- Otherwise run the preferred picker to search for notes.\n local picker = Obsidian.picker\n if not picker then\n log.err(\"Found multiple notes matching '%s', but no picker is configured\", query)\n return\n end\n\n picker:pick_note(notes, {\n prompt_title = opts.prompt_title,\n callback = callback,\n })\n end)\n else\n callback(notes)\n end\n end, { notes = opts.notes })\nend\n\n---@class obsidian.ResolveLinkResult\n---\n---@field location string\n---@field name string\n---@field link_type obsidian.search.RefTypes\n---@field path obsidian.Path|?\n---@field note obsidian.Note|?\n---@field url string|?\n---@field line integer|?\n---@field col integer|?\n---@field anchor obsidian.note.HeaderAnchor|?\n---@field block obsidian.note.Block|?\n\n--- Resolve a link.\n---\n---@param link string\n---@param callback fun(results: obsidian.ResolveLinkResult[])\nM.resolve_link_async = function(link, callback)\n local Note = require \"obsidian.note\"\n\n local location, name, link_type\n location, name, link_type = util.parse_link(link, { include_naked_urls = true, include_file_urls = true })\n\n if location == nil or name == nil or link_type == nil then\n return callback {}\n end\n\n ---@type obsidian.ResolveLinkResult\n local res = { location = location, name = name, link_type = link_type }\n\n if util.is_url(location) then\n res.url = location\n return callback { res }\n end\n\n -- The Obsidian app will follow URL-encoded links, so we should to.\n location = vim.uri_decode(location)\n\n -- Remove block links from the end if there are any.\n -- TODO: handle block links.\n ---@type string|?\n local block_link\n location, block_link = util.strip_block_links(location)\n\n -- Remove anchor links from the end if there are any.\n ---@type string|?\n local anchor_link\n location, anchor_link = util.strip_anchor_links(location)\n\n --- Finalize the `obsidian.ResolveLinkResult` for a note while resolving block or anchor link to line.\n ---\n ---@param note obsidian.Note\n ---@return obsidian.ResolveLinkResult\n local function finalize_result(note)\n ---@type integer|?, obsidian.note.Block|?, obsidian.note.HeaderAnchor|?\n local line, block_match, anchor_match\n if block_link ~= nil then\n block_match = note:resolve_block(block_link)\n if block_match then\n line = block_match.line\n end\n elseif anchor_link ~= nil then\n anchor_match = note:resolve_anchor_link(anchor_link)\n if anchor_match then\n line = anchor_match.line\n end\n end\n\n return vim.tbl_extend(\n \"force\",\n res,\n { path = note.path, note = note, line = line, block = block_match, anchor = anchor_match }\n )\n end\n\n ---@type obsidian.note.LoadOpts\n local load_opts = {\n collect_anchor_links = anchor_link and true or false,\n collect_blocks = block_link and true or false,\n max_lines = Obsidian.opts.search_max_lines,\n }\n\n -- Assume 'location' is current buffer path if empty, like for TOCs.\n if string.len(location) == 0 then\n res.location = vim.api.nvim_buf_get_name(0)\n local note = Note.from_buffer(0, load_opts)\n return callback { finalize_result(note) }\n end\n\n res.location = location\n\n M.resolve_note_async(location, function(notes)\n if #notes == 0 then\n local path = Path.new(location)\n if path:exists() then\n res.path = path\n return callback { res }\n else\n return callback { res }\n end\n end\n\n local matches = {}\n for _, note in ipairs(notes) do\n table.insert(matches, finalize_result(note))\n end\n\n return callback(matches)\n end, { notes = load_opts, pick = false })\nend\n\n---@class obsidian.LinkMatch\n---@field link string\n---@field line integer\n---@field start integer 0-indexed\n---@field end integer 0-indexed\n\n-- Gather all unique links from the a note.\n--\n---@param note obsidian.Note\n---@param opts { on_match: fun(link: obsidian.LinkMatch) }\n---@param callback fun(links: obsidian.LinkMatch[])\nM.find_links = function(note, opts, callback)\n ---@type obsidian.LinkMatch[]\n local matches = {}\n ---@type table\n local found = {}\n local lines = io.lines(tostring(note.path))\n\n for lnum, line in util.enumerate(lines) do\n for ref_match in vim.iter(M.find_refs(line, { include_naked_urls = true, include_file_urls = true })) do\n local m_start, m_end = unpack(ref_match)\n local link = string.sub(line, m_start, m_end)\n if not found[link] then\n local match = {\n link = link,\n line = lnum,\n start = m_start - 1,\n [\"end\"] = m_end - 1,\n }\n matches[#matches + 1] = match\n found[link] = true\n if opts.on_match then\n opts.on_match(match)\n end\n end\n end\n end\n\n callback(matches)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/rename.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal AsyncExecutor = require(\"obsidian.async\").AsyncExecutor\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal util = require \"obsidian.util\"\nlocal compat = require \"obsidian.compat\"\nlocal api = require \"obsidian.api\"\nlocal enumerate, zip = util.enumerate, util.zip\n\nlocal resolve_note = function(query, opts)\n opts = opts or {}\n return require(\"obsidian.async\").block_on(function(cb)\n print(query)\n return search.resolve_note_async(query, cb, { notes = opts.notes })\n end, 5000)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n -- Resolve the note to rename.\n ---@type boolean\n local is_current_buf\n ---@type integer|?\n local cur_note_bufnr\n ---@type obsidian.Path\n local cur_note_path\n ---@type obsidian.Note\n local cur_note, cur_note_id\n\n local cur_link = api.cursor_link()\n if not cur_link then\n -- rename current note\n is_current_buf = true\n cur_note_bufnr = assert(vim.fn.bufnr())\n cur_note_path = Path.buffer(cur_note_bufnr)\n cur_note = Note.from_file(cur_note_path)\n cur_note_id = tostring(cur_note.id)\n else\n -- rename note under the cursor\n local link_id = util.parse_link(cur_link)\n local notes = { resolve_note(link_id) }\n if #notes == 0 then\n log.err(\"Failed to resolve '%s' to a note\", cur_link)\n return\n elseif #notes > 1 then\n log.err(\"Failed to resolve '%s' to a single note, found %d matches\", cur_link, #notes)\n return\n else\n cur_note = notes[1]\n end\n\n is_current_buf = false\n cur_note_id = tostring(cur_note.id)\n cur_note_path = cur_note.path\n for bufnr, bufpath in api.get_named_buffers() do\n if bufpath == cur_note_path then\n cur_note_bufnr = bufnr\n break\n end\n end\n end\n\n -- Validate args.\n local dry_run = false\n ---@type string|?\n local arg\n\n if data.args == \"--dry-run\" then\n dry_run = true\n data.args = nil\n end\n\n if data.args ~= nil and string.len(data.args) > 0 then\n arg = vim.trim(data.args)\n else\n arg = api.input(\"Enter new note ID/name/path: \", { completion = \"file\", default = cur_note_id })\n if not arg or string.len(arg) == 0 then\n log.warn \"Rename aborted\"\n return\n end\n end\n\n if vim.endswith(arg, \" --dry-run\") then\n dry_run = true\n arg = vim.trim(string.sub(arg, 1, -string.len \" --dry-run\" - 1))\n end\n\n assert(cur_note_path)\n local dirname = assert(cur_note_path:parent(), string.format(\"failed to resolve parent of '%s'\", cur_note_path))\n\n -- Parse new note ID / path from args.\n local parts = vim.split(arg, \"/\", { plain = true })\n local new_note_id = parts[#parts]\n if new_note_id == \"\" then\n log.err \"Invalid new note ID\"\n return\n elseif vim.endswith(new_note_id, \".md\") then\n new_note_id = string.sub(new_note_id, 1, -4)\n end\n\n ---@type obsidian.Path\n local new_note_path\n if #parts > 1 then\n parts[#parts] = nil\n new_note_path = Obsidian.dir:joinpath(unpack(compat.flatten { parts, new_note_id })):with_suffix \".md\"\n else\n new_note_path = (dirname / new_note_id):with_suffix \".md\"\n end\n\n if new_note_id == cur_note_id then\n log.warn \"New note ID is the same, doing nothing\"\n return\n end\n\n -- Get confirmation before continuing.\n local confirmation\n if not dry_run then\n confirmation = api.confirm(\n \"Renaming '\"\n .. cur_note_id\n .. \"' to '\"\n .. new_note_id\n .. \"'...\\n\"\n .. \"This will write all buffers and potentially modify a lot of files. If you're using version control \"\n .. \"with your vault it would be a good idea to commit the current state of your vault before running this.\\n\"\n .. \"You can also do a dry run of this by running ':Obsidian rename \"\n .. arg\n .. \" --dry-run'.\\n\"\n .. \"Do you want to continue?\"\n )\n else\n confirmation = api.confirm(\n \"Dry run: renaming '\" .. cur_note_id .. \"' to '\" .. new_note_id .. \"'...\\n\" .. \"Do you want to continue?\"\n )\n end\n\n if not confirmation then\n log.warn \"Rename aborted\"\n return\n end\n\n ---@param fn function\n local function quietly(fn, ...)\n local ok, res = pcall(fn, ...)\n if not ok then\n error(res)\n end\n end\n\n -- Write all buffers.\n quietly(vim.cmd.wall)\n\n -- Rename the note file and remove or rename the corresponding buffer, if there is one.\n if cur_note_bufnr ~= nil then\n if is_current_buf then\n -- If we're renaming the note of a current buffer, save as the new path.\n if not dry_run then\n quietly(vim.cmd.saveas, tostring(new_note_path))\n local new_bufnr_current_note = vim.fn.bufnr(tostring(cur_note_path))\n quietly(vim.cmd.bdelete, new_bufnr_current_note)\n vim.fn.delete(tostring(cur_note_path))\n else\n log.info(\"Dry run: saving current buffer as '\" .. tostring(new_note_path) .. \"' and removing old file\")\n end\n else\n -- For the non-current buffer the best we can do is delete the buffer (we've already saved it above)\n -- and then make a file-system call to rename the file.\n if not dry_run then\n quietly(vim.cmd.bdelete, cur_note_bufnr)\n cur_note_path:rename(new_note_path)\n else\n log.info(\n \"Dry run: removing buffer '\"\n .. tostring(cur_note_path)\n .. \"' and renaming file to '\"\n .. tostring(new_note_path)\n .. \"'\"\n )\n end\n end\n else\n -- When the note is not loaded into a buffer we just need to rename the file.\n if not dry_run then\n cur_note_path:rename(new_note_path)\n else\n log.info(\"Dry run: renaming file '\" .. tostring(cur_note_path) .. \"' to '\" .. tostring(new_note_path) .. \"'\")\n end\n end\n\n -- We need to update its frontmatter note_id\n -- to account for the rename.\n cur_note.id = new_note_id\n cur_note.path = Path.new(new_note_path)\n if not dry_run then\n cur_note:save()\n else\n log.info(\"Dry run: updating frontmatter of '\" .. tostring(new_note_path) .. \"'\")\n end\n\n local cur_note_rel_path = assert(cur_note_path:vault_relative_path { strict = true })\n local new_note_rel_path = assert(new_note_path:vault_relative_path { strict = true })\n\n -- Search notes on disk for any references to `cur_note_id`.\n -- We look for the following forms of references:\n -- * '[[cur_note_id]]'\n -- * '[[cur_note_id|ALIAS]]'\n -- * '[[cur_note_id\\|ALIAS]]' (a wiki link within a table)\n -- * '[ALIAS](cur_note_id)'\n -- And all of the above with relative paths (from the vault root) to the note instead of just the note ID,\n -- with and without the \".md\" suffix.\n -- Another possible form is [[ALIAS]], but we don't change the note's aliases when renaming\n -- so those links will still be valid.\n ---@param ref_link string\n ---@return string[]\n local function get_ref_forms(ref_link)\n return {\n \"[[\" .. ref_link .. \"]]\",\n \"[[\" .. ref_link .. \"|\",\n \"[[\" .. ref_link .. \"\\\\|\",\n \"[[\" .. ref_link .. \"#\",\n \"](\" .. ref_link .. \")\",\n \"](\" .. ref_link .. \"#\",\n }\n end\n\n local reference_forms = compat.flatten {\n get_ref_forms(cur_note_id),\n get_ref_forms(cur_note_rel_path),\n get_ref_forms(string.sub(cur_note_rel_path, 1, -4)),\n }\n local replace_with = compat.flatten {\n get_ref_forms(new_note_id),\n get_ref_forms(new_note_rel_path),\n get_ref_forms(string.sub(new_note_rel_path, 1, -4)),\n }\n\n local executor = AsyncExecutor.new()\n\n local file_count = 0\n local replacement_count = 0\n local all_tasks_submitted = false\n\n ---@param path string\n ---@return integer\n local function replace_refs(path)\n --- Read lines, replacing refs as we go.\n local count = 0\n local lines = {}\n local f = io.open(path, \"r\")\n assert(f)\n for line_num, line in enumerate(f:lines \"*L\") do\n for ref, replacement in zip(reference_forms, replace_with) do\n local n\n line, n = string.gsub(line, vim.pesc(ref), replacement)\n if dry_run and n > 0 then\n log.info(\n \"Dry run: '\"\n .. tostring(path)\n .. \"':\"\n .. line_num\n .. \" Replacing \"\n .. n\n .. \" occurrence(s) of '\"\n .. ref\n .. \"' with '\"\n .. replacement\n .. \"'\"\n )\n end\n count = count + n\n end\n lines[#lines + 1] = line\n end\n f:close()\n\n --- Write the new lines back.\n if not dry_run and count > 0 then\n f = io.open(path, \"w\")\n assert(f)\n f:write(unpack(lines))\n f:close()\n end\n\n return count\n end\n\n local function on_search_match(match)\n local path = tostring(Path.new(match.path.text):resolve { strict = true })\n file_count = file_count + 1\n executor:submit(replace_refs, function(count)\n replacement_count = replacement_count + count\n end, path)\n end\n\n search.search_async(\n Obsidian.dir,\n reference_forms,\n { fixed_strings = true, max_count_per_file = 1 },\n on_search_match,\n function(_)\n all_tasks_submitted = true\n end\n )\n\n -- Wait for all tasks to get submitted.\n vim.wait(2000, function()\n return all_tasks_submitted\n end, 50, false)\n\n -- Then block until all tasks are finished.\n executor:join(2000)\n\n local prefix = dry_run and \"Dry run: replaced \" or \"Replaced \"\n log.info(prefix .. replacement_count .. \" reference(s) across \" .. file_count .. \" file(s)\")\n\n -- In case the files of any current buffers were changed.\n vim.cmd.checktime()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/init-legacy.lua", "local util = require \"obsidian.util\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal command_lookups = {\n ObsidianCheck = \"obsidian.commands.check\",\n ObsidianToggleCheckbox = \"obsidian.commands.toggle_checkbox\",\n ObsidianToday = \"obsidian.commands.today\",\n ObsidianYesterday = \"obsidian.commands.yesterday\",\n ObsidianTomorrow = \"obsidian.commands.tomorrow\",\n ObsidianDailies = \"obsidian.commands.dailies\",\n ObsidianNew = \"obsidian.commands.new\",\n ObsidianOpen = \"obsidian.commands.open\",\n ObsidianBacklinks = \"obsidian.commands.backlinks\",\n ObsidianSearch = \"obsidian.commands.search\",\n ObsidianTags = \"obsidian.commands.tags\",\n ObsidianTemplate = \"obsidian.commands.template\",\n ObsidianNewFromTemplate = \"obsidian.commands.new_from_template\",\n ObsidianQuickSwitch = \"obsidian.commands.quick_switch\",\n ObsidianLinkNew = \"obsidian.commands.link_new\",\n ObsidianLink = \"obsidian.commands.link\",\n ObsidianLinks = \"obsidian.commands.links\",\n ObsidianFollowLink = \"obsidian.commands.follow_link\",\n ObsidianWorkspace = \"obsidian.commands.workspace\",\n ObsidianRename = \"obsidian.commands.rename\",\n ObsidianPasteImg = \"obsidian.commands.paste_img\",\n ObsidianExtractNote = \"obsidian.commands.extract_note\",\n ObsidianTOC = \"obsidian.commands.toc\",\n}\n\nlocal M = setmetatable({\n commands = {},\n}, {\n __index = function(t, k)\n local require_path = command_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@class obsidian.CommandConfigLegacy\n---@field opts table\n---@field complete function|?\n---@field func function|? (obsidian.Client, table) -> nil\n\n---Register a new command.\n---@param name string\n---@param config obsidian.CommandConfigLegacy\nM.register = function(name, config)\n if not config.func then\n config.func = function(client, data)\n return M[name](client, data)\n end\n end\n M.commands[name] = config\nend\n\n---Install all commands.\n---\n---@param client obsidian.Client\nM.install = function(client)\n for command_name, command_config in pairs(M.commands) do\n local func = function(data)\n command_config.func(client, data)\n end\n\n if command_config.complete ~= nil then\n command_config.opts.complete = function(arg_lead, cmd_line, cursor_pos)\n return command_config.complete(client, arg_lead, cmd_line, cursor_pos)\n end\n end\n\n vim.api.nvim_create_user_command(command_name, func, command_config.opts)\n end\nend\n\n---@param client obsidian.Client\n---@return string[]\nM.complete_args_search = function(client, _, cmd_line, _)\n local query\n local cmd_arg, _ = util.lstrip_whitespace(string.gsub(cmd_line, \"^.*Obsidian[A-Za-z0-9]+\", \"\"))\n if string.len(cmd_arg) > 0 then\n if string.find(cmd_arg, \"|\", 1, true) then\n return {}\n else\n query = cmd_arg\n end\n else\n local _, csrow, cscol, _ = unpack(assert(vim.fn.getpos \"'<\"))\n local _, cerow, cecol, _ = unpack(assert(vim.fn.getpos \"'>\"))\n local lines = vim.fn.getline(csrow, cerow)\n assert(type(lines) == \"table\")\n\n if #lines > 1 then\n lines[1] = string.sub(lines[1], cscol)\n lines[#lines] = string.sub(lines[#lines], 1, cecol)\n elseif #lines == 1 then\n lines[1] = string.sub(lines[1], cscol, cecol)\n else\n return {}\n end\n\n query = table.concat(lines, \" \")\n end\n\n local completions = {}\n local query_lower = string.lower(query)\n for note in iter(search.find_notes(query, { search = { sort = true } })) do\n local note_path = assert(note.path:vault_relative_path { strict = true })\n if string.find(string.lower(note:display_name()), query_lower, 1, true) then\n table.insert(completions, note:display_name() .. \"  \" .. tostring(note_path))\n else\n for _, alias in pairs(note.aliases) do\n if string.find(string.lower(alias), query_lower, 1, true) then\n table.insert(completions, alias .. \"  \" .. tostring(note_path))\n break\n end\n end\n end\n end\n\n return completions\nend\n\nM.register(\"ObsidianCheck\", { opts = { nargs = 0, desc = \"Check for issues in your vault\" } })\n\nM.register(\"ObsidianToday\", { opts = { nargs = \"?\", desc = \"Open today's daily note\" } })\n\nM.register(\"ObsidianYesterday\", { opts = { nargs = 0, desc = \"Open the daily note for the previous working day\" } })\n\nM.register(\"ObsidianTomorrow\", { opts = { nargs = 0, desc = \"Open the daily note for the next working day\" } })\n\nM.register(\"ObsidianDailies\", { opts = { nargs = \"*\", desc = \"Open a picker with daily notes\" } })\n\nM.register(\"ObsidianNew\", { opts = { nargs = \"?\", desc = \"Create a new note\" } })\n\nM.register(\n \"ObsidianOpen\",\n { opts = { nargs = \"?\", desc = \"Open in the Obsidian app\" }, complete = M.complete_args_search }\n)\n\nM.register(\"ObsidianBacklinks\", { opts = { nargs = 0, desc = \"Collect backlinks\" } })\n\nM.register(\"ObsidianTags\", { opts = { nargs = \"*\", range = true, desc = \"Find tags\" } })\n\nM.register(\"ObsidianSearch\", { opts = { nargs = \"?\", desc = \"Search vault\" } })\n\nM.register(\"ObsidianTemplate\", { opts = { nargs = \"?\", desc = \"Insert a template\" } })\n\nM.register(\"ObsidianNewFromTemplate\", { opts = { nargs = \"*\", desc = \"Create a new note from a template\" } })\n\nM.register(\"ObsidianQuickSwitch\", { opts = { nargs = \"?\", desc = \"Switch notes\" } })\n\nM.register(\"ObsidianLinkNew\", { opts = { nargs = \"?\", range = true, desc = \"Link selected text to a new note\" } })\n\nM.register(\"ObsidianLink\", {\n opts = { nargs = \"?\", range = true, desc = \"Link selected text to an existing note\" },\n complete = M.complete_args_search,\n})\n\nM.register(\"ObsidianLinks\", { opts = { nargs = 0, desc = \"Collect all links within the current buffer\" } })\n\nM.register(\"ObsidianFollowLink\", { opts = { nargs = \"?\", desc = \"Follow reference or link under cursor\" } })\n\nM.register(\"ObsidianToggleCheckbox\", { opts = { nargs = 0, desc = \"Toggle checkbox\", range = true } })\n\nM.register(\"ObsidianWorkspace\", { opts = { nargs = \"?\", desc = \"Check or switch workspace\" } })\n\nM.register(\"ObsidianRename\", { opts = { nargs = \"?\", desc = \"Rename note and update all references to it\" } })\n\nM.register(\"ObsidianPasteImg\", { opts = { nargs = \"?\", desc = \"Paste an image from the clipboard\" } })\n\nM.register(\n \"ObsidianExtractNote\",\n { opts = { nargs = \"?\", range = true, desc = \"Extract selected text to a new note and link to it\" } }\n)\n\nM.register(\"ObsidianTOC\", { opts = { nargs = 0, desc = \"Load the table of contents into a picker\" } })\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/picker.lua", "local abc = require \"obsidian.abc\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal strings = require \"plenary.strings\"\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---@class obsidian.Picker : obsidian.ABC\n---\n---@field calling_bufnr integer\nlocal Picker = abc.new_class()\n\nPicker.new = function()\n local self = Picker.init()\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n return self\nend\n\n-------------------------------------------------------------------\n--- Abstract methods that need to be implemented by subclasses. ---\n-------------------------------------------------------------------\n\n---@class obsidian.PickerMappingOpts\n---\n---@field desc string\n---@field callback fun(...)\n---@field fallback_to_query boolean|?\n---@field keep_open boolean|?\n---@field allow_multiple boolean|?\n\n---@alias obsidian.PickerMappingTable table\n\n---@class obsidian.PickerFindOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Find files in a directory.\n---\n---@param opts obsidian.PickerFindOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `callback`: Callback to run with the selected entry.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.find_files = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerGrepOpts\n---\n---@field prompt_title string|?\n---@field dir string|obsidian.Path|?\n---@field query string|?\n---@field callback fun(path: string)|?\n---@field no_default_mappings boolean|?\n---@field query_mappings obsidian.PickerMappingTable\n---@field selection_mappings obsidian.PickerMappingTable\n\n--- Grep for a string.\n---\n---@param opts obsidian.PickerGrepOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `dir`: Directory to search in.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.grep = function(self, opts)\n error \"not implemented\"\nend\n\n---@class obsidian.PickerEntry\n---\n---@field value any\n---@field ordinal string|?\n---@field display string|?\n---@field filename string|?\n---@field valid boolean|?\n---@field lnum integer|?\n---@field col integer|?\n---@field icon string|?\n---@field icon_hl string|?\n\n---@class obsidian.PickerPickOpts\n---\n---@field prompt_title string|?\n---@field callback fun(value: any, ...: any)|?\n---@field allow_multiple boolean|?\n---@field query_mappings obsidian.PickerMappingTable|?\n---@field selection_mappings obsidian.PickerMappingTable|?\n\n--- Pick from a list of items.\n---\n---@param values string[]|obsidian.PickerEntry[] Items to pick from.\n---@param opts obsidian.PickerPickOpts|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected item(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `query_mappings`: Mappings that run with the query prompt.\n--- `selection_mappings`: Mappings that run with the current selection.\n---\n---@diagnostic disable-next-line: unused-local\nPicker.pick = function(self, values, opts)\n error \"not implemented\"\nend\n\n------------------------------------------------------------------\n--- Concrete methods with a default implementation subclasses. ---\n------------------------------------------------------------------\n\n--- Find notes by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.find_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Notes\",\n dir = Obsidian.dir,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Find templates by filename.\n---\n---@param opts { prompt_title: string|?, callback: fun(path: string) }|? Options.\n---\n--- Options:\n--- `callback`: Callback to run with the selected template path.\nPicker.find_templates = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local templates_dir = api.templates_dir()\n\n if templates_dir == nil then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n return self:find_files {\n prompt_title = opts.prompt_title or \"Templates\",\n callback = opts.callback,\n dir = templates_dir,\n no_default_mappings = true,\n }\nend\n\n--- Grep search in notes.\n---\n---@param opts { prompt_title: string|?, query: string|?, callback: fun(path: string)|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `query`: Initial query to grep for.\n--- `callback`: Callback to run with the selected path.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.grep_notes = function(self, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n self:grep {\n prompt_title = opts.prompt_title or \"Grep notes\",\n dir = Obsidian.dir,\n query = opts.query,\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n }\nend\n\n--- Open picker with a list of notes.\n---\n---@param notes obsidian.Note[]\n---@param opts { prompt_title: string|?, callback: fun(note: obsidian.Note, ...: obsidian.Note), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected note(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_note = function(self, notes, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local query_mappings\n local selection_mappings\n if not opts.no_default_mappings then\n query_mappings = self:_note_query_mappings()\n selection_mappings = self:_note_selection_mappings()\n end\n\n -- Launch picker with results.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, note in ipairs(notes) do\n assert(note.path)\n local rel_path = assert(note.path:vault_relative_path { strict = true })\n local display_name = note:display_name()\n entries[#entries + 1] = {\n value = note,\n display = display_name,\n ordinal = rel_path .. \" \" .. display_name,\n filename = tostring(note.path),\n }\n end\n\n self:pick(entries, {\n prompt_title = opts.prompt_title or \"Notes\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n query_mappings = query_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--- Open picker with a list of tags.\n---\n---@param tags string[]\n---@param opts { prompt_title: string|?, callback: fun(tag: string, ...: string), allow_multiple: boolean|?, no_default_mappings: boolean|? }|? Options.\n---\n--- Options:\n--- `prompt_title`: Title for the prompt window.\n--- `callback`: Callback to run with the selected tag(s).\n--- `allow_multiple`: Allow multiple selections to pass to the callback.\n--- `no_default_mappings`: Don't apply picker's default mappings.\nPicker.pick_tag = function(self, tags, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n local selection_mappings\n if not opts.no_default_mappings then\n selection_mappings = self:_tag_selection_mappings()\n end\n\n self:pick(tags, {\n prompt_title = opts.prompt_title or \"Tags\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = selection_mappings,\n })\nend\n\n--------------------------------\n--- Concrete helper methods. ---\n--------------------------------\n\n---@param key string|?\n---@return boolean\nlocal function key_is_set(key)\n if key ~= nil and string.len(key) > 0 then\n return true\n else\n return false\n end\nend\n\n--- Get query mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_query_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.new) then\n mappings[Obsidian.opts.picker.note_mappings.new] = {\n desc = \"new\",\n callback = function(query)\n ---@diagnostic disable-next-line: missing-fields\n require \"obsidian.commands.new\"(require(\"obsidian\").get_client(), { args = query })\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `find_notes()` or `grep_notes()`.\n---@return obsidian.PickerMappingTable\nPicker._note_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.note_mappings and key_is_set(Obsidian.opts.picker.note_mappings.insert_link) then\n mappings[Obsidian.opts.picker.note_mappings.insert_link] = {\n desc = \"insert link\",\n callback = function(note_or_path)\n ---@type obsidian.Note\n local note\n if Note.is_note_obj(note_or_path) then\n note = note_or_path\n else\n note = Note.from_file(note_or_path)\n end\n local link = api.format_link(note, {})\n vim.api.nvim_put({ link }, \"\", false, true)\n require(\"obsidian.ui\").update(0)\n end,\n }\n end\n\n return mappings\nend\n\n--- Get selection mappings to use for `pick_tag()`.\n---@return obsidian.PickerMappingTable\nPicker._tag_selection_mappings = function(self)\n ---@type obsidian.PickerMappingTable\n local mappings = {}\n\n if Obsidian.opts.picker.tag_mappings then\n if key_is_set(Obsidian.opts.picker.tag_mappings.tag_note) then\n mappings[Obsidian.opts.picker.tag_mappings.tag_note] = {\n desc = \"tag note\",\n callback = function(...)\n local tags = { ... }\n\n local note = api.current_note(self.calling_bufnr)\n if not note then\n log.warn(\"'%s' is not a note in your workspace\", vim.api.nvim_buf_get_name(self.calling_bufnr))\n return\n end\n\n -- Add the tag and save the new frontmatter to the buffer.\n local tags_added = {}\n local tags_not_added = {}\n for _, tag in ipairs(tags) do\n if note:add_tag(tag) then\n table.insert(tags_added, tag)\n else\n table.insert(tags_not_added, tag)\n end\n end\n\n if #tags_added > 0 then\n if note:update_frontmatter(self.calling_bufnr) then\n log.info(\"Added tags %s to frontmatter\", tags_added)\n else\n log.warn \"Frontmatter unchanged\"\n end\n end\n\n if #tags_not_added > 0 then\n log.warn(\"Note already has tags %s\", tags_not_added)\n end\n end,\n fallback_to_query = true,\n keep_open = true,\n allow_multiple = true,\n }\n end\n\n if key_is_set(Obsidian.opts.picker.tag_mappings.insert_tag) then\n mappings[Obsidian.opts.picker.tag_mappings.insert_tag] = {\n desc = \"insert tag\",\n callback = function(tag)\n vim.api.nvim_put({ \"#\" .. tag }, \"\", false, true)\n end,\n fallback_to_query = true,\n }\n end\n end\n\n return mappings\nend\n\n---@param opts { prompt_title: string, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|? }|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nPicker._build_prompt = function(self, opts)\n opts = opts or {}\n\n ---@type string\n local prompt = opts.prompt_title or \"Find\"\n if string.len(prompt) > 50 then\n prompt = string.sub(prompt, 1, 50) .. \"…\"\n end\n\n prompt = prompt .. \" | confirm\"\n\n if opts.query_mappings then\n local keys = vim.tbl_keys(opts.query_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.query_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n if opts.selection_mappings then\n local keys = vim.tbl_keys(opts.selection_mappings)\n table.sort(keys)\n for _, key in ipairs(keys) do\n local mapping = opts.selection_mappings[key]\n prompt = prompt .. \" | \" .. key .. \" \" .. mapping.desc\n end\n end\n\n return prompt\nend\n\n---@param entry obsidian.PickerEntry\n---\n---@return string, { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n---@diagnostic disable-next-line: unused-local\nPicker._make_display = function(self, entry)\n ---@type string\n local display = \"\"\n ---@type { [1]: { [1]: integer, [2]: integer }, [2]: string }[]\n local highlights = {}\n\n if entry.filename ~= nil then\n local icon, icon_hl\n if entry.icon then\n icon = entry.icon\n icon_hl = entry.icon_hl\n else\n icon, icon_hl = api.get_icon(entry.filename)\n end\n\n if icon ~= nil then\n display = display .. icon .. \" \"\n if icon_hl ~= nil then\n highlights[#highlights + 1] = { { 0, strings.strdisplaywidth(icon) }, icon_hl }\n end\n end\n\n display = display .. Path.new(entry.filename):vault_relative_path { strict = true }\n\n if entry.lnum ~= nil then\n display = display .. \":\" .. entry.lnum\n\n if entry.col ~= nil then\n display = display .. \":\" .. entry.col\n end\n end\n\n if entry.display ~= nil then\n display = display .. \":\" .. entry.display\n end\n elseif entry.display ~= nil then\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. entry.display\n else\n if entry.icon ~= nil then\n display = entry.icon .. \" \"\n end\n display = display .. tostring(entry.value)\n end\n\n return assert(display), highlights\nend\n\n---@return string[]\nPicker._build_find_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = { sort_by = Obsidian.opts.sort_by, sort_reversed = Obsidian.opts.sort_reversed }\n return search.build_find_cmd(\".\", nil, search_opts)\nend\n\nPicker._build_grep_cmd = function(self)\n local search = require \"obsidian.search\"\n local search_opts = {\n sort_by = Obsidian.opts.sort_by,\n sort_reversed = Obsidian.opts.sort_reversed,\n smart_case = true,\n fixed_strings = true,\n }\n return search.build_grep_cmd(search_opts)\nend\n\nreturn Picker\n"], ["/obsidian.nvim/lua/obsidian/templates.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nlocal M = {}\n\n--- Resolve a template name to a path.\n---\n---@param template_name string|obsidian.Path\n---@param templates_dir obsidian.Path\n---\n---@return obsidian.Path\nM.resolve_template = function(template_name, templates_dir)\n ---@type obsidian.Path|?\n local template_path\n local paths_to_check = { templates_dir / tostring(template_name), Path:new(template_name) }\n for _, path in ipairs(paths_to_check) do\n if path:is_file() then\n template_path = path\n break\n elseif not vim.endswith(tostring(path), \".md\") then\n local path_with_suffix = Path:new(tostring(path) .. \".md\")\n if path_with_suffix:is_file() then\n template_path = path_with_suffix\n break\n end\n end\n end\n\n if template_path == nil then\n error(string.format(\"Template '%s' not found\", template_name))\n end\n\n return template_path\nend\n\n--- Substitute variables inside the given text.\n---\n---@param text string\n---@param ctx obsidian.TemplateContext\n---\n---@return string\nM.substitute_template_variables = function(text, ctx)\n local methods = vim.deepcopy(ctx.template_opts.substitutions or {})\n\n if not methods[\"date\"] then\n methods[\"date\"] = function()\n local date_format = ctx.template_opts.date_format or \"%Y-%m-%d\"\n return tostring(os.date(date_format))\n end\n end\n\n if not methods[\"time\"] then\n methods[\"time\"] = function()\n local time_format = ctx.template_opts.time_format or \"%H:%M\"\n return tostring(os.date(time_format))\n end\n end\n\n if not methods[\"title\"] and ctx.partial_note then\n methods[\"title\"] = ctx.partial_note.title or ctx.partial_note:display_name()\n end\n\n if not methods[\"id\"] and ctx.partial_note then\n methods[\"id\"] = tostring(ctx.partial_note.id)\n end\n\n if not methods[\"path\"] and ctx.partial_note and ctx.partial_note.path then\n methods[\"path\"] = tostring(ctx.partial_note.path)\n end\n\n -- Replace known variables.\n for key, subst in pairs(methods) do\n while true do\n local m_start, m_end = string.find(text, \"{{\" .. key .. \"}}\", nil, true)\n if not m_start or not m_end then\n break\n end\n ---@type string\n local value\n if type(subst) == \"string\" then\n value = subst\n else\n value = subst(ctx)\n -- cache the result\n methods[key] = value\n end\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n -- Find unknown variables and prompt for them.\n for m_start, m_end in util.gfind(text, \"{{[^}]+}}\") do\n local key = vim.trim(string.sub(text, m_start + 2, m_end - 2))\n local value = api.input(string.format(\"Enter value for '%s' ( to skip): \", key))\n if value and string.len(value) > 0 then\n text = string.sub(text, 1, m_start - 1) .. value .. string.sub(text, m_end + 1)\n end\n end\n\n return text\nend\n\n--- Clone template to a new note.\n---\n---@param ctx obsidian.CloneTemplateContext\n---\n---@return obsidian.Note\nM.clone_template = function(ctx)\n local note_path = Path.new(ctx.destination_path)\n assert(note_path:parent()):mkdir { parents = true, exist_ok = true }\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local template_file, read_err = io.open(tostring(template_path), \"r\")\n if not template_file then\n error(string.format(\"Unable to read template at '%s': %s\", template_path, tostring(read_err)))\n end\n\n local note_file, write_err = io.open(tostring(note_path), \"w\")\n if not note_file then\n error(string.format(\"Unable to write note at '%s': %s\", note_path, tostring(write_err)))\n end\n\n for line in template_file:lines \"L\" do\n line = M.substitute_template_variables(line, ctx)\n note_file:write(line)\n end\n\n assert(template_file:close())\n assert(note_file:close())\n\n local new_note = Note.from_file(note_path)\n\n if ctx.partial_note then\n -- Transfer fields from `ctx.partial_note`.\n new_note.id = ctx.partial_note.id\n if new_note.title == nil then\n new_note.title = ctx.partial_note.title\n end\n for _, alias in ipairs(ctx.partial_note.aliases) do\n new_note:add_alias(alias)\n end\n for _, tag in ipairs(ctx.partial_note.tags) do\n new_note:add_tag(tag)\n end\n end\n\n return new_note\nend\n\n---Insert a template at the given location.\n---\n---@param ctx obsidian.InsertTemplateContext\n---\n---@return obsidian.Note\nM.insert_template = function(ctx)\n local buf, win, row, _ = unpack(ctx.location)\n if ctx.partial_note == nil then\n ctx.partial_note = Note.from_buffer(buf)\n end\n\n local template_path = M.resolve_template(ctx.template_name, ctx.templates_dir)\n\n local insert_lines = {}\n local template_file = io.open(tostring(template_path), \"r\")\n if template_file then\n local lines = template_file:lines()\n for line in lines do\n local new_lines = M.substitute_template_variables(line, ctx)\n if string.find(new_lines, \"[\\r\\n]\") then\n local line_start = 1\n for line_end in util.gfind(new_lines, \"[\\r\\n]\") do\n local new_line = string.sub(new_lines, line_start, line_end - 1)\n table.insert(insert_lines, new_line)\n line_start = line_end + 1\n end\n local last_line = string.sub(new_lines, line_start)\n if string.len(last_line) > 0 then\n table.insert(insert_lines, last_line)\n end\n else\n table.insert(insert_lines, new_lines)\n end\n end\n template_file:close()\n else\n error(string.format(\"Template file '%s' not found\", template_path))\n end\n\n vim.api.nvim_buf_set_lines(buf, row - 1, row - 1, false, insert_lines)\n local new_cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(win))\n vim.api.nvim_win_set_cursor(0, { new_cursor_row, 0 })\n\n require(\"obsidian.ui\").update(0)\n\n return Note.from_buffer(buf)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/init.lua", "local log = require \"obsidian.log\"\n\nlocal module_lookups = {\n abc = \"obsidian.abc\",\n api = \"obsidian.api\",\n async = \"obsidian.async\",\n Client = \"obsidian.client\",\n commands = \"obsidian.commands\",\n completion = \"obsidian.completion\",\n config = \"obsidian.config\",\n log = \"obsidian.log\",\n img_paste = \"obsidian.img_paste\",\n Note = \"obsidian.note\",\n Path = \"obsidian.path\",\n pickers = \"obsidian.pickers\",\n search = \"obsidian.search\",\n templates = \"obsidian.templates\",\n ui = \"obsidian.ui\",\n util = \"obsidian.util\",\n VERSION = \"obsidian.version\",\n Workspace = \"obsidian.workspace\",\n yaml = \"obsidian.yaml\",\n}\n\nlocal obsidian = setmetatable({}, {\n __index = function(t, k)\n local require_path = module_lookups[k]\n if not require_path then\n return\n end\n\n local mod = require(require_path)\n t[k] = mod\n\n return mod\n end,\n})\n\n---@type obsidian.Client|?\nobsidian._client = nil\n\n---Get the current obsidian client.\n---@return obsidian.Client\nobsidian.get_client = function()\n if obsidian._client == nil then\n error \"Obsidian client has not been set! Did you forget to call 'setup()'?\"\n else\n return obsidian._client\n end\nend\n\nobsidian.register_command = require(\"obsidian.commands\").register\n\n--- Setup a new Obsidian client. This should only be called once from an Nvim session.\n---\n---@param opts obsidian.config.ClientOpts | table\n---\n---@return obsidian.Client\nobsidian.setup = function(opts)\n opts = obsidian.config.normalize(opts)\n\n ---@class obsidian.state\n ---@field picker obsidian.Picker The picker instance to use.\n ---@field workspace obsidian.Workspace The current workspace.\n ---@field dir obsidian.Path The root of the vault for the current workspace.\n ---@field buf_dir obsidian.Path|? The parent directory of the current buffer.\n ---@field opts obsidian.config.ClientOpts current options\n ---@field _opts obsidian.config.ClientOpts default options\n _G.Obsidian = {} -- init a state table\n\n local client = obsidian.Client.new(opts)\n\n Obsidian._opts = opts\n\n obsidian.Workspace.set(assert(obsidian.Workspace.get_from_opts(opts)), {})\n\n log.set_level(Obsidian.opts.log_level)\n\n -- Install commands.\n -- These will be available across all buffers, not just note buffers in the vault.\n obsidian.commands.install(client)\n\n if opts.legacy_commands then\n obsidian.commands.install_legacy(client)\n end\n\n if opts.statusline.enabled then\n require(\"obsidian.statusline\").start(client)\n end\n\n if opts.footer.enabled then\n require(\"obsidian.footer\").start(client)\n end\n\n -- Register completion sources, providers\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").register_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").register_providers(opts)\n end\n\n local group = vim.api.nvim_create_augroup(\"obsidian_setup\", { clear = true })\n\n -- wrapper for creating autocmd events\n ---@param pattern string\n ---@param buf integer\n local function exec_autocmds(pattern, buf)\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = pattern,\n data = {\n note = require(\"obsidian.note\").from_buffer(buf),\n },\n })\n end\n\n -- Complete setup and update workspace (if needed) when entering a markdown buffer.\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Set the current directory of the buffer.\n local buf_dir = vim.fs.dirname(ev.match)\n if buf_dir then\n Obsidian.buf_dir = obsidian.Path.new(buf_dir)\n end\n\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n if opts.comment.enabled then\n vim.o.commentstring = \"%%%s%%\"\n end\n\n -- Switch to the workspace and complete the workspace setup.\n if not Obsidian.workspace.locked and workspace ~= Obsidian.workspace then\n log.debug(\"Switching to workspace '%s' @ '%s'\", workspace.name, workspace.path)\n obsidian.Workspace.set(workspace)\n require(\"obsidian.ui\").update(ev.buf)\n end\n\n -- Register keymap.\n vim.keymap.set(\n \"n\",\n \"\",\n obsidian.api.smart_action,\n { expr = true, buffer = true, desc = \"Obsidian Smart Action\" }\n )\n\n vim.keymap.set(\"n\", \"]o\", function()\n obsidian.api.nav_link \"next\"\n end, { buffer = true, desc = \"Obsidian Next Link\" })\n\n vim.keymap.set(\"n\", \"[o\", function()\n obsidian.api.nav_link \"prev\"\n end, { buffer = true, desc = \"Obsidian Previous Link\" })\n\n -- Inject completion sources, providers to their plugin configurations\n if opts.completion.nvim_cmp then\n require(\"obsidian.completion.plugin_initializers.nvim_cmp\").inject_sources(opts)\n elseif opts.completion.blink then\n require(\"obsidian.completion.plugin_initializers.blink\").inject_sources(opts)\n end\n\n -- Run enter-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"enter_note\", Obsidian.opts.callbacks.enter_note, client, note)\n\n exec_autocmds(\"ObsidianNoteEnter\", ev.buf)\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufLeave\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n -- Check if we're in *any* workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(vim.fs.dirname(ev.match), Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Run leave-note callback.\n local note = obsidian.Note.from_buffer(ev.buf)\n obsidian.util.fire_callback(\"leave_note\", Obsidian.opts.callbacks.leave_note, client, note)\n\n exec_autocmds(\"ObsidianNoteLeave\", ev.buf)\n end,\n })\n\n -- Add/update frontmatter for notes before writing.\n vim.api.nvim_create_autocmd({ \"BufWritePre\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n -- Initialize note.\n local bufnr = ev.buf\n local note = obsidian.Note.from_buffer(bufnr)\n\n -- Run pre-write-note callback.\n obsidian.util.fire_callback(\"pre_write_note\", Obsidian.opts.callbacks.pre_write_note, client, note)\n\n exec_autocmds(\"ObsidianNoteWritePre\", ev.buf)\n\n -- Update buffer with new frontmatter.\n if note:update_frontmatter(bufnr) then\n log.info \"Updated frontmatter\"\n end\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufWritePost\" }, {\n group = group,\n pattern = \"*.md\",\n callback = function(ev)\n local buf_dir = vim.fs.dirname(ev.match)\n\n -- Check if we're in a workspace.\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return\n end\n\n -- Check if current buffer is actually a note within the workspace.\n if not obsidian.api.path_is_note(ev.match) then\n return\n end\n\n exec_autocmds(\"ObsidianNoteWritePost\", ev.buf)\n end,\n })\n\n -- Set global client.\n obsidian._client = client\n\n obsidian.util.fire_callback(\"post_setup\", Obsidian.opts.callbacks.post_setup, client)\n\n return client\nend\n\nreturn obsidian\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/refs.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.RefsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field in_buffer_only boolean\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\n---@field block_link string|?\n---@field anchor_link string|?\n---@field new_text_to_option table\nlocal RefsSourceCompletionContext = abc.new_class()\n\nRefsSourceCompletionContext.new = function()\n return RefsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.RefsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal RefsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.RefsSourceBase\nRefsSourceBase.new = function()\n return RefsSourceBase.init()\nend\n\nRefsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = RefsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n completion_context.in_buffer_only = false\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n self:strip_links(cc)\n self:determine_buffer_only_search_scope(cc)\n\n if cc.in_buffer_only then\n local note = api.current_note(0, { collect_anchor_links = true, collect_blocks = true })\n if note then\n self:process_search_results(cc, { note })\n else\n cc.completion_resolve_callback(self.incomplete_response)\n end\n else\n local search_ops = cc.client.search_defaults()\n search_ops.ignore_case = true\n\n search.find_notes_async(cc.search, function(results)\n self:process_search_results(cc, results)\n end, {\n search = search_ops,\n notes = { collect_anchor_links = cc.anchor_link ~= nil, collect_blocks = cc.block_link ~= nil },\n })\n end\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction RefsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\n---Collect matching block links.\n---@param note obsidian.Note\n---@param block_link string?\n---@return obsidian.note.Block[]|?\nfunction RefsSourceBase:collect_matching_blocks(note, block_link)\n ---@type obsidian.note.Block[]|?\n local matching_blocks\n if block_link then\n assert(note.blocks)\n matching_blocks = {}\n for block_id, block_data in pairs(note.blocks) do\n if vim.startswith(\"#\" .. block_id, block_link) then\n table.insert(matching_blocks, block_data)\n end\n end\n\n if #matching_blocks == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_blocks, { id = util.standardize_block(block_link), line = 1 })\n end\n end\n\n return matching_blocks\nend\n\n---Collect matching anchor links.\n---@param note obsidian.Note\n---@param anchor_link string?\n---@return obsidian.note.HeaderAnchor[]?\nfunction RefsSourceBase:collect_matching_anchors(note, anchor_link)\n ---@type obsidian.note.HeaderAnchor[]|?\n local matching_anchors\n if anchor_link then\n assert(note.anchor_links)\n matching_anchors = {}\n for anchor, anchor_data in pairs(note.anchor_links) do\n if vim.startswith(anchor, anchor_link) then\n table.insert(matching_anchors, anchor_data)\n end\n end\n\n if #matching_anchors == 0 then\n -- Unmatched, create a mock one.\n table.insert(matching_anchors, { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 })\n end\n end\n\n return matching_anchors\nend\n\n--- Strips block and anchor links from the current search string\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:strip_links(cc)\n cc.search, cc.block_link = util.strip_block_links(cc.search)\n cc.search, cc.anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, we'll match against all block links.\n if not cc.block_link and vim.endswith(cc.search, \"#^\") then\n cc.block_link = \"#^\"\n cc.search = string.sub(cc.search, 1, -3)\n end\n\n -- If anchor link is incomplete, we'll match against all anchor links.\n if not cc.anchor_link and vim.endswith(cc.search, \"#\") then\n cc.anchor_link = \"#\"\n cc.search = string.sub(cc.search, 1, -2)\n end\nend\n\n--- Determines whatever the in_buffer_only should be enabled\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\nfunction RefsSourceBase:determine_buffer_only_search_scope(cc)\n if (cc.anchor_link or cc.block_link) and string.len(cc.search) == 0 then\n -- Search over headers/blocks in current buffer only.\n cc.in_buffer_only = true\n end\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param results obsidian.Note[]\nfunction RefsSourceBase:process_search_results(cc, results)\n assert(cc)\n assert(results)\n\n local completion_items = {}\n\n cc.new_text_to_option = {}\n\n for note in iter(results) do\n ---@cast note obsidian.Note\n\n local matching_blocks = self:collect_matching_blocks(note, cc.block_link)\n local matching_anchors = self:collect_matching_anchors(note, cc.anchor_link)\n\n if cc.in_buffer_only then\n self:update_completion_options(cc, nil, nil, matching_anchors, matching_blocks, note)\n else\n -- Collect all valid aliases for the note, including ID, title, and filename.\n ---@type string[]\n local aliases\n if not cc.in_buffer_only then\n aliases = util.tbl_unique { tostring(note.id), note:display_name(), unpack(note.aliases) }\n if note.title ~= nil then\n table.insert(aliases, note.title)\n end\n end\n\n for alias in iter(aliases) do\n self:update_completion_options(cc, alias, nil, matching_anchors, matching_blocks, note)\n local alias_case_matched = util.match_case(cc.search, alias)\n\n if\n alias_case_matched ~= nil\n and alias_case_matched ~= alias\n and not vim.list_contains(note.aliases, alias_case_matched)\n and Obsidian.opts.completion.match_case\n then\n self:update_completion_options(cc, alias_case_matched, nil, matching_anchors, matching_blocks, note)\n end\n end\n\n if note.alt_alias ~= nil then\n self:update_completion_options(cc, note:display_name(), note.alt_alias, matching_anchors, matching_blocks, note)\n end\n end\n end\n\n for _, option in pairs(cc.new_text_to_option) do\n -- TODO: need a better label, maybe just the note's display name?\n ---@type string\n local label\n if cc.ref_type == completion.RefType.Wiki then\n label = string.format(\"[[%s]]\", option.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n label = string.format(\"[%s](…)\", option.label)\n else\n error \"not implemented\"\n end\n\n table.insert(completion_items, {\n documentation = option.documentation,\n sortText = option.sort_text,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = option.new_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n })\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = completion_items }))\nend\n\n---@param cc obsidian.completion.sources.base.RefsSourceCompletionContext\n---@param label string|?\n---@param alt_label string|?\n---@param note obsidian.Note\nfunction RefsSourceBase:update_completion_options(cc, label, alt_label, matching_anchors, matching_blocks, note)\n ---@type { label: string|?, alt_label: string|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }[]\n local new_options = {}\n if matching_anchors ~= nil then\n for anchor in iter(matching_anchors) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor })\n end\n elseif matching_blocks ~= nil then\n for block in iter(matching_blocks) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block })\n end\n else\n if label then\n table.insert(new_options, { label = label, alt_label = alt_label })\n end\n\n -- Add all blocks and anchors, let cmp sort it out.\n for _, anchor_data in pairs(note.anchor_links or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, anchor = anchor_data })\n end\n for _, block_data in pairs(note.blocks or {}) do\n table.insert(new_options, { label = label, alt_label = alt_label, block = block_data })\n end\n end\n\n -- De-duplicate options relative to their `new_text`.\n for _, option in ipairs(new_options) do\n ---@type obsidian.config.LinkStyle\n local link_style\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n else\n error \"not implemented\"\n end\n\n ---@type string, string, string, table|?\n local final_label, sort_text, new_text, documentation\n if option.label then\n new_text = api.format_link(\n note,\n { label = option.label, link_style = link_style, anchor = option.anchor, block = option.block }\n )\n\n final_label = assert(option.alt_label or option.label)\n if option.anchor then\n final_label = final_label .. option.anchor.anchor\n elseif option.block then\n final_label = final_label .. \"#\" .. option.block.id\n end\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = note:display_info {\n label = new_text,\n anchor = option.anchor,\n block = option.block,\n },\n }\n elseif option.anchor then\n -- In buffer anchor link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.anchor.header .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.anchor.header .. \"](\" .. option.anchor.anchor .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = option.anchor.anchor\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n elseif option.block then\n -- In buffer block link.\n -- TODO: allow users to customize this?\n if cc.ref_type == completion.RefType.Wiki then\n new_text = \"[[#\" .. option.block.id .. \"]]\"\n elseif cc.ref_type == completion.RefType.Markdown then\n new_text = \"[#\" .. option.block.id .. \"](#\" .. option.block.id .. \")\"\n else\n error \"not implemented\"\n end\n\n final_label = \"#\" .. option.block.id\n sort_text = final_label\n\n documentation = {\n kind = \"markdown\",\n value = string.format(\"`%s`\", new_text),\n }\n else\n error \"should not happen\"\n end\n\n if cc.new_text_to_option[new_text] then\n cc.new_text_to_option[new_text].sort_text = cc.new_text_to_option[new_text].sort_text .. \" \" .. sort_text\n else\n cc.new_text_to_option[new_text] =\n { label = final_label, new_text = new_text, sort_text = sort_text, documentation = documentation }\n end\n end\nend\n\nreturn RefsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/new.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal obsidian = require \"obsidian\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\nlocal LinkStyle = require(\"obsidian.config\").LinkStyle\nlocal Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.NewNoteSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field insert_start integer|?\n---@field insert_end integer|?\n---@field ref_type obsidian.completion.RefType|?\nlocal NewNoteSourceCompletionContext = abc.new_class()\n\nNewNoteSourceCompletionContext.new = function()\n return NewNoteSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.NewNoteSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal NewNoteSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.NewNoteSourceBase\nNewNoteSourceBase.new = function()\n return NewNoteSourceBase.init()\nend\n\nNewNoteSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = NewNoteSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\nfunction NewNoteSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n ---@type string|?\n local block_link\n cc.search, block_link = util.strip_block_links(cc.search)\n\n ---@type string|?\n local anchor_link\n cc.search, anchor_link = util.strip_anchor_links(cc.search)\n\n -- If block link is incomplete, do nothing.\n if not block_link and vim.endswith(cc.search, \"#^\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- If anchor link is incomplete, do nothing.\n if not anchor_link and vim.endswith(cc.search, \"#\") then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Probably just a block/anchor link within current note.\n if string.len(cc.search) == 0 then\n cc.completion_resolve_callback(self.incomplete_response)\n return\n end\n\n -- Create a mock block.\n ---@type obsidian.note.Block|?\n local block\n if block_link then\n block = { block = \"\", id = util.standardize_block(block_link), line = 1 }\n end\n\n -- Create a mock anchor.\n ---@type obsidian.note.HeaderAnchor|?\n local anchor\n if anchor_link then\n anchor = { anchor = anchor_link, header = string.sub(anchor_link, 2), level = 1, line = 1 }\n end\n\n ---@type { label: string, note: obsidian.Note, template: string|? }[]\n local new_notes_opts = {}\n\n local note = Note.create { title = cc.search }\n if note.title and string.len(note.title) > 0 then\n new_notes_opts[#new_notes_opts + 1] = { label = cc.search, note = note }\n end\n\n -- Check for datetime macros.\n for _, dt_offset in ipairs(util.resolve_date_macro(cc.search)) do\n if dt_offset.cadence == \"daily\" then\n note = require(\"obsidian.daily\").daily(dt_offset.offset, { no_write = true })\n if not note:exists() then\n new_notes_opts[#new_notes_opts + 1] =\n { label = dt_offset.macro, note = note, template = Obsidian.opts.daily_notes.template }\n end\n end\n end\n\n -- Completion items.\n local items = {}\n\n for _, new_note_opts in ipairs(new_notes_opts) do\n local new_note = new_note_opts.note\n\n assert(new_note.path)\n\n ---@type obsidian.config.LinkStyle, string\n local link_style, label\n if cc.ref_type == completion.RefType.Wiki then\n link_style = LinkStyle.wiki\n label = string.format(\"[[%s]] (create)\", new_note_opts.label)\n elseif cc.ref_type == completion.RefType.Markdown then\n link_style = LinkStyle.markdown\n label = string.format(\"[%s](…) (create)\", new_note_opts.label)\n else\n error \"not implemented\"\n end\n\n local new_text = api.format_link(new_note, { link_style = link_style, anchor = anchor, block = block })\n local documentation = {\n kind = \"markdown\",\n value = new_note:display_info {\n label = \"Create: \" .. new_text,\n },\n }\n\n items[#items + 1] = {\n documentation = documentation,\n sortText = new_note_opts.label,\n label = label,\n kind = vim.lsp.protocol.CompletionItemKind.Reference,\n textEdit = {\n newText = new_text,\n range = {\n start = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = cc.insert_end + 1,\n },\n },\n },\n data = {\n note = new_note,\n template = new_note_opts.template,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.NewNoteSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction NewNoteSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.insert_start, cc.insert_end, cc.ref_type = completion.can_complete(cc.request)\n\n if cc.search ~= nil then\n cc.search = util.lstrip_whitespace(cc.search)\n end\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n return true\nend\n\n--- Runs a generalized version of the execute method\n---@param item any\n---@return table|? callback_return_value\nfunction NewNoteSourceBase:process_execute(item)\n local data = item.data\n\n if data == nil then\n return nil\n end\n\n -- Make sure `data.note` is actually an `obsidian.Note` object. If it gets serialized at some\n -- point (seems to happen on Linux), it will lose its metatable.\n if not Note.is_note_obj(data.note) then\n data.note = setmetatable(data.note, Note.mt)\n data.note.path = setmetatable(data.note.path, Path.mt)\n end\n\n data.note:write { template = data.template }\n return {}\nend\n\nreturn NewNoteSourceBase\n"], ["/obsidian.nvim/lua/obsidian/pickers/_snacks.lua", "local snacks_picker = require \"snacks.picker\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\nlocal function debug_once(msg, ...)\n -- vim.notify(msg .. vim.inspect(...))\nend\n\n---@param mapping table\n---@return table\nlocal function notes_mappings(mapping)\n if type(mapping) == \"table\" then\n local opts = { win = { input = { keys = {} } }, actions = {} }\n for k, v in pairs(mapping) do\n local name = string.gsub(v.desc, \" \", \"_\")\n opts.win.input.keys = {\n [k] = { name, mode = { \"n\", \"i\" }, desc = v.desc },\n }\n opts.actions[name] = function(picker, item)\n debug_once(\"mappings :\", item)\n picker:close()\n vim.schedule(function()\n v.callback(item.value or item._path)\n end)\n end\n end\n return opts\n end\n return {}\nend\n\n---@class obsidian.pickers.SnacksPicker : obsidian.Picker\nlocal SnacksPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"SnacksPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nSnacksPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"files\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"find files callback: \", item)\n opts.callback(item._path)\n else\n debug_once(\"find files jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nSnacksPicker.grep = function(self, opts)\n opts = opts or {}\n\n debug_once(\"grep opts : \", opts)\n\n ---@type obsidian.Path\n local dir = opts.dir.filename and Path:new(opts.dir.filename) or Obsidian.dir\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n source = \"grep\",\n title = opts.prompt_title,\n cwd = tostring(dir),\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"grep callback: \", item)\n opts.callback(item._path or item.filename)\n else\n debug_once(\"grep jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n snacks_picker.pick(pick_opts)\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nSnacksPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n debug_once(\"pick opts: \", opts)\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n table.insert(entries, {\n text = value,\n value = value,\n })\n elseif value.valid ~= false then\n local name = self:_make_display(value)\n table.insert(entries, {\n text = name,\n buf = self.calling_bufnr,\n filename = value.filename,\n value = value.value,\n pos = { value.lnum, value.col or 0 },\n })\n end\n end\n\n local map = vim.tbl_deep_extend(\"force\", {}, notes_mappings(opts.selection_mappings))\n\n local pick_opts = vim.tbl_extend(\"force\", map or {}, {\n tilte = opts.prompt_title,\n items = entries,\n layout = {\n preview = false,\n },\n format = \"text\",\n confirm = function(picker, item, action)\n picker:close()\n if item then\n if opts.callback then\n debug_once(\"pick callback: \", item)\n opts.callback(item.value)\n else\n debug_once(\"pick jump: \", item)\n snacks_picker.actions.jump(picker, item, action)\n end\n end\n end,\n })\n\n snacks_picker.pick(pick_opts)\nend\n\nreturn SnacksPicker\n"], ["/obsidian.nvim/lua/obsidian/ui.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal iter = vim.iter\n\nlocal M = {}\n\nlocal NAMESPACE = \"ObsidianUI\"\n\n---@param ui_opts obsidian.config.UIOpts\nlocal function install_hl_groups(ui_opts)\n for group_name, opts in pairs(ui_opts.hl_groups) do\n vim.api.nvim_set_hl(0, group_name, opts)\n end\nend\n\n-- We cache marks locally to help avoid redrawing marks when its not necessary. The main reason\n-- we need to do this is because the conceal char we get back from `nvim_buf_get_extmarks()` gets mangled.\n-- For example, \"󰄱\" is turned into \"1\\1\\15\".\n-- TODO: if we knew how to un-mangle the conceal char we wouldn't need the cache.\n\nM._buf_mark_cache = vim.defaulttable()\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\n---@return ExtMark|?\nlocal function cache_get(bufnr, ns_id, mark_id)\n local buf_ns_cache = M._buf_mark_cache[bufnr][ns_id]\n return buf_ns_cache[mark_id]\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark ExtMark\n---@return ExtMark|?\nlocal function cache_set(bufnr, ns_id, mark)\n assert(mark.id ~= nil)\n M._buf_mark_cache[bufnr][ns_id][mark.id] = mark\nend\n\n---@param bufnr integer\n---@param ns_id integer\n---@param mark_id integer\nlocal function cache_evict(bufnr, ns_id, mark_id)\n M._buf_mark_cache[bufnr][ns_id][mark_id] = nil\nend\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function cache_clear(bufnr, ns_id)\n M._buf_mark_cache[bufnr][ns_id] = {}\nend\n\n---@class ExtMark : obsidian.ABC\n---@field id integer|? ID of the mark, only set for marks that are actually materialized in the buffer.\n---@field row integer 0-based row index to place the mark.\n---@field col integer 0-based col index to place the mark.\n---@field opts ExtMarkOpts Optional parameters passed directly to `nvim_buf_set_extmark()`.\nlocal ExtMark = abc.new_class {\n __eq = function(a, b)\n return a.row == b.row and a.col == b.col and a.opts == b.opts\n end,\n}\n\nM.ExtMark = ExtMark\n\n---@class ExtMarkOpts : obsidian.ABC\n---@field end_row integer\n---@field end_col integer\n---@field conceal string|?\n---@field hl_group string|?\n---@field spell boolean|?\nlocal ExtMarkOpts = abc.new_class()\n\nM.ExtMarkOpts = ExtMarkOpts\n\n---@param data table\n---@return ExtMarkOpts\nExtMarkOpts.from_tbl = function(data)\n local self = ExtMarkOpts.init()\n self.end_row = data.end_row\n self.end_col = data.end_col\n self.conceal = data.conceal\n self.hl_group = data.hl_group\n self.spell = data.spell\n return self\nend\n\n---@param self ExtMarkOpts\n---@return table\nExtMarkOpts.to_tbl = function(self)\n return {\n end_row = self.end_row,\n end_col = self.end_col,\n conceal = self.conceal,\n hl_group = self.hl_group,\n spell = self.spell,\n }\nend\n\n---@param id integer|?\n---@param row integer\n---@param col integer\n---@param opts ExtMarkOpts\n---@return ExtMark\nExtMark.new = function(id, row, col, opts)\n local self = ExtMark.init()\n self.id = id\n self.row = row\n self.col = col\n self.opts = opts\n return self\nend\n\n---Materialize the ExtMark if needed. After calling this the 'id' will be set if it wasn't already.\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return ExtMark\nExtMark.materialize = function(self, bufnr, ns_id)\n if self.id == nil then\n self.id = vim.api.nvim_buf_set_extmark(bufnr, ns_id, self.row, self.col, self.opts:to_tbl())\n end\n cache_set(bufnr, ns_id, self)\n return self\nend\n\n---@param self ExtMark\n---@param bufnr integer\n---@param ns_id integer\n---@return boolean\nExtMark.clear = function(self, bufnr, ns_id)\n if self.id ~= nil then\n cache_evict(bufnr, ns_id, self.id)\n return vim.api.nvim_buf_del_extmark(bufnr, ns_id, self.id)\n else\n return false\n end\nend\n\n---Collect all existing (materialized) marks within a region.\n---@param bufnr integer\n---@param ns_id integer\n---@param region_start integer|integer[]|?\n---@param region_end integer|integer[]|?\n---@return ExtMark[]\nExtMark.collect = function(bufnr, ns_id, region_start, region_end)\n region_start = region_start and region_start or 0\n region_end = region_end and region_end or -1\n local marks = {}\n for data in iter(vim.api.nvim_buf_get_extmarks(bufnr, ns_id, region_start, region_end, { details = true })) do\n local mark = ExtMark.new(data[1], data[2], data[3], ExtMarkOpts.from_tbl(data[4]))\n -- NOTE: since the conceal char we get back from `nvim_buf_get_extmarks()` is mangled, e.g.\n -- \"󰄱\" is turned into \"1\\1\\15\", we used the cached version.\n local cached_mark = cache_get(bufnr, ns_id, mark.id)\n if cached_mark ~= nil then\n mark.opts.conceal = cached_mark.opts.conceal\n end\n cache_set(bufnr, ns_id, mark)\n marks[#marks + 1] = mark\n end\n return marks\nend\n\n---Clear all existing (materialized) marks with a line region.\n---@param bufnr integer\n---@param ns_id integer\n---@param line_start integer\n---@param line_end integer\nExtMark.clear_range = function(bufnr, ns_id, line_start, line_end)\n return vim.api.nvim_buf_clear_namespace(bufnr, ns_id, line_start, line_end)\nend\n\n---Clear all existing (materialized) marks on a line.\n---@param bufnr integer\n---@param ns_id integer\n---@param line integer\nExtMark.clear_line = function(bufnr, ns_id, line)\n return ExtMark.clear_range(bufnr, ns_id, line, line + 1)\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_check_extmarks(marks, line, lnum, ui_opts)\n for char, opts in pairs(ui_opts.checkboxes) do\n if string.match(line, \"^%s*- %[\" .. vim.pesc(char) .. \"%]\") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 5,\n conceal = opts.char,\n hl_group = opts.hl_group,\n }\n )\n return marks\n end\n end\n\n if ui_opts.bullets ~= nil and string.match(line, \"^%s*[-%*%+] \") then\n local indent = util.count_indent(line)\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n indent,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = indent + 1,\n conceal = ui_opts.bullets.char,\n hl_group = ui_opts.bullets.hl_group,\n }\n )\n end\n\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_ref_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_refs(line, { include_naked_urls = true, include_tags = true, include_block_ids = true })\n for match in iter(matches) do\n local m_start, m_end, m_type = unpack(match)\n if m_type == search.RefTypes.WikiWithAlias then\n -- Reference of the form [[xxx|yyy]]\n local pipe_loc = string.find(line, \"|\", m_start, true)\n assert(pipe_loc)\n -- Conceal everything from '[[' up to '|'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = pipe_loc,\n conceal = \"\",\n }\n )\n -- Highlight the alias 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n pipe_loc,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Wiki then\n -- Reference of the form [[xxx]]\n -- Conceal the opening '[['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'xxx'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the closing ']]'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n elseif m_type == search.RefTypes.Markdown then\n -- Reference of the form [yyy](xxx)\n local closing_bracket_loc = string.find(line, \"]\", m_start, true)\n assert(closing_bracket_loc)\n local is_url = util.is_url(string.sub(line, closing_bracket_loc + 2, m_end - 1))\n -- Conceal the opening '['\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start,\n conceal = \"\",\n }\n )\n -- Highlight the ref 'yyy'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc - 1,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n -- Conceal the ']('\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = closing_bracket_loc + 1,\n conceal = is_url and \" \" or \"\",\n }\n )\n -- Conceal the URL part 'xxx' with the external URL character\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n closing_bracket_loc + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 1,\n conceal = is_url and ui_opts.external_link_icon.char or \"\",\n hl_group = ui_opts.external_link_icon.hl_group,\n }\n )\n -- Conceal the closing ')'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = is_url and \" \" or \"\",\n }\n )\n elseif m_type == search.RefTypes.NakedUrl then\n -- A \"naked\" URL is just a URL by itself, like 'https://github.com/'\n local domain_start_loc = string.find(line, \"://\", m_start, true)\n assert(domain_start_loc)\n domain_start_loc = domain_start_loc + 3\n -- Conceal the \"https?://\" part\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = domain_start_loc - 1,\n conceal = \"\",\n }\n )\n -- Highlight the whole thing.\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.reference_text.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.Tag then\n -- A tag is like '#tag'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.tags.hl_group,\n spell = false,\n }\n )\n elseif m_type == search.RefTypes.BlockID then\n -- A block ID, like '^hello-world'\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n hl_group = ui_opts.block_ids.hl_group,\n spell = false,\n }\n )\n end\n end\n return marks\nend\n\n---@param marks ExtMark[]\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal function get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n local matches = search.find_highlight(line)\n for match in iter(matches) do\n local m_start, m_end, _ = unpack(match)\n -- Conceal opening '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start - 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_start + 1,\n conceal = \"\",\n }\n )\n -- Highlight text in the middle\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_start + 1,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end - 2,\n hl_group = ui_opts.highlight_text.hl_group,\n spell = false,\n }\n )\n -- Conceal closing '=='\n marks[#marks + 1] = ExtMark.new(\n nil,\n lnum,\n m_end - 2,\n ExtMarkOpts.from_tbl {\n end_row = lnum,\n end_col = m_end,\n conceal = \"\",\n }\n )\n end\n return marks\nend\n\n---@param lnum integer\n---@param ui_opts obsidian.config.UIOpts\n---@return ExtMark[]\nlocal get_line_marks = function(line, lnum, ui_opts)\n local marks = {}\n get_line_check_extmarks(marks, line, lnum, ui_opts)\n get_line_ref_extmarks(marks, line, lnum, ui_opts)\n get_line_highlight_extmarks(marks, line, lnum, ui_opts)\n return marks\nend\n\n---@param bufnr integer\n---@param ui_opts obsidian.config.UIOpts\nlocal function update_extmarks(bufnr, ns_id, ui_opts)\n local start_time = vim.uv.hrtime()\n local n_marks_added = 0\n local n_marks_cleared = 0\n\n -- Collect all current marks, grouped by line.\n local cur_marks_by_line = vim.defaulttable()\n for mark in iter(ExtMark.collect(bufnr, ns_id)) do\n local cur_line_marks = cur_marks_by_line[mark.row]\n cur_line_marks[#cur_line_marks + 1] = mark\n end\n\n -- Iterate over lines (skipping code blocks) and update marks.\n local inside_code_block = false\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, true)\n for i, line in ipairs(lines) do\n local lnum = i - 1\n local cur_line_marks = cur_marks_by_line[lnum]\n\n local function clear_line()\n ExtMark.clear_line(bufnr, ns_id, lnum)\n n_marks_cleared = n_marks_cleared + #cur_line_marks\n for mark in iter(cur_line_marks) do\n cache_evict(bufnr, ns_id, mark.id)\n end\n end\n\n -- Check if inside a code block or at code block boundary. If not, update marks.\n if string.match(line, \"^%s*```[^`]*$\") then\n inside_code_block = not inside_code_block\n -- Remove any existing marks here on the boundary of a code block.\n clear_line()\n elseif not inside_code_block then\n -- Get all marks that should be materialized.\n -- Some of these might already be materialized, which we'll check below and avoid re-drawing\n -- if that's the case.\n local new_line_marks = get_line_marks(line, lnum, ui_opts)\n if #new_line_marks > 0 then\n -- Materialize new marks.\n for mark in iter(new_line_marks) do\n if not vim.list_contains(cur_line_marks, mark) then\n mark:materialize(bufnr, ns_id)\n n_marks_added = n_marks_added + 1\n end\n end\n\n -- Clear old marks.\n for mark in iter(cur_line_marks) do\n if not vim.list_contains(new_line_marks, mark) then\n mark:clear(bufnr, ns_id)\n n_marks_cleared = n_marks_cleared + 1\n end\n end\n else\n -- Remove any existing marks here since there are no new marks.\n clear_line()\n end\n else\n -- Remove any existing marks here since we're inside a code block.\n clear_line()\n end\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n log.debug(\"Added %d new marks, cleared %d old marks in %dms\", n_marks_added, n_marks_cleared, runtime)\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param bufnr integer|?\n---@return boolean\nlocal function should_update(ui_opts, bufnr)\n if ui_opts.enable == false then\n return false\n end\n\n bufnr = bufnr or 0\n\n if not vim.endswith(vim.api.nvim_buf_get_name(bufnr), \".md\") then\n return false\n end\n\n if ui_opts.max_file_length ~= nil and vim.fn.line \"$\" > ui_opts.max_file_length then\n return false\n end\n\n return true\nend\n\n---@param ui_opts obsidian.config.UIOpts\n---@param throttle boolean\n---@return function\nlocal function get_extmarks_autocmd_callback(ui_opts, throttle)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n\n local callback = function(ev)\n if not should_update(ui_opts, ev.bufnr) then\n return\n end\n update_extmarks(ev.buf, ns_id, ui_opts)\n end\n\n if throttle then\n return require(\"obsidian.async\").throttle(callback, ui_opts.update_debounce)\n else\n return callback\n end\nend\n\n---Manually update extmarks.\n---\n---@param bufnr integer|?\nM.update = function(bufnr)\n bufnr = bufnr or 0\n local ui_opts = Obsidian.opts.ui\n if not should_update(ui_opts, bufnr) then\n return\n end\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n update_extmarks(bufnr, ns_id, ui_opts)\nend\n\n---@param workspace obsidian.Workspace\n---@param ui_opts obsidian.config.UIOpts\nM.setup = function(workspace, ui_opts)\n if ui_opts.enable == false then\n return\n end\n\n local group = vim.api.nvim_create_augroup(\"ObsidianUI\" .. workspace.name, { clear = true })\n\n install_hl_groups(ui_opts)\n\n local pattern = tostring(workspace.root) .. \"/**.md\"\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = function()\n local conceallevel = vim.opt_local.conceallevel:get()\n\n if (conceallevel < 1 or conceallevel > 2) and not ui_opts.ignore_conceal_warn then\n log.warn_once(\n \"Obsidian additional syntax features require 'conceallevel' to be set to 1 or 2, \"\n .. \"but you have 'conceallevel' set to '%s'.\\n\"\n .. \"See https://github.com/epwalsh/obsidian.nvim/issues/286 for more details.\\n\"\n .. \"If you don't want Obsidian's additional UI features, you can disable them and suppress \"\n .. \"this warning by setting 'ui.enable = false' in your Obsidian nvim config.\",\n conceallevel\n )\n end\n\n -- delete the autocommand\n return true\n end,\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, false),\n })\n\n vim.api.nvim_create_autocmd({ \"BufEnter\", \"TextChanged\", \"TextChangedI\", \"TextChangedP\" }, {\n group = group,\n pattern = pattern,\n callback = get_extmarks_autocmd_callback(ui_opts, true),\n })\n\n vim.api.nvim_create_autocmd({ \"BufUnload\" }, {\n group = group,\n pattern = pattern,\n callback = function(ev)\n local ns_id = vim.api.nvim_create_namespace(NAMESPACE)\n cache_clear(ev.buf, ns_id)\n end,\n })\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/tags.lua", "local abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal iter = vim.iter\nlocal obsidian = require \"obsidian\"\n\n---Used to track variables that are used between reusable method calls. This is required, because each\n---call to the sources's completion hook won't create a new source object, but will reuse the same one.\n---@class obsidian.completion.sources.base.TagsSourceCompletionContext : obsidian.ABC\n---@field client obsidian.Client\n---@field completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@field request obsidian.completion.sources.base.Request\n---@field search string|?\n---@field in_frontmatter boolean|?\nlocal TagsSourceCompletionContext = abc.new_class()\n\nTagsSourceCompletionContext.new = function()\n return TagsSourceCompletionContext.init()\nend\n\n---@class obsidian.completion.sources.base.TagsSourceBase : obsidian.ABC\n---@field incomplete_response table\n---@field complete_response table\nlocal TagsSourceBase = abc.new_class()\n\n---@return obsidian.completion.sources.base.TagsSourceBase\nTagsSourceBase.new = function()\n return TagsSourceBase.init()\nend\n\nTagsSourceBase.get_trigger_characters = completion.get_trigger_characters\n\n---Sets up a new completion context that is used to pass around variables between completion source methods\n---@param completion_resolve_callback (fun(self: any)) blink or nvim_cmp completion resolve callback\n---@param request obsidian.completion.sources.base.Request\n---@return obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:new_completion_context(completion_resolve_callback, request)\n local completion_context = TagsSourceCompletionContext.new()\n\n -- Sets up the completion callback, which will be called when the (possibly incomplete) completion items are ready\n completion_context.completion_resolve_callback = completion_resolve_callback\n\n -- This request object will be used to determine the current cursor location and the text around it\n completion_context.request = request\n\n completion_context.client = assert(obsidian.get_client())\n\n return completion_context\nend\n\n--- Runs a generalized version of the complete (nvim_cmp) or get_completions (blink) methods\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\nfunction TagsSourceBase:process_completion(cc)\n if not self:can_complete_request(cc) then\n return\n end\n\n local search_opts = cc.client.search_defaults()\n search_opts.sort = false\n\n cc.client:find_tags_async(cc.search, function(tag_locs)\n local tags = {}\n for tag_loc in iter(tag_locs) do\n tags[tag_loc.tag] = true\n end\n\n local items = {}\n for tag, _ in pairs(tags) do\n -- Generate context-appropriate text\n local insert_text, label_text\n if cc.in_frontmatter then\n -- Frontmatter: insert tag without # (YAML format)\n insert_text = tag\n label_text = \"Tag: \" .. tag\n else\n -- Document body: insert tag with # (Obsidian format)\n insert_text = \"#\" .. tag\n label_text = \"Tag: #\" .. tag\n end\n\n -- Calculate the range to replace (the entire #tag pattern)\n local cursor_before = cc.request.context.cursor_before_line\n local hash_start = string.find(cursor_before, \"#[^%s]*$\")\n local insert_start = hash_start and (hash_start - 1) or #cursor_before\n local insert_end = #cursor_before\n\n items[#items + 1] = {\n sortText = \"#\" .. tag,\n label = label_text,\n kind = vim.lsp.protocol.CompletionItemKind.Text,\n textEdit = {\n newText = insert_text,\n range = {\n [\"start\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_start,\n },\n [\"end\"] = {\n line = cc.request.context.cursor.row - 1,\n character = insert_end,\n },\n },\n },\n data = {\n bufnr = cc.request.context.bufnr,\n in_frontmatter = cc.in_frontmatter,\n line = cc.request.context.cursor.line,\n tag = tag,\n },\n }\n end\n\n cc.completion_resolve_callback(vim.tbl_deep_extend(\"force\", self.complete_response, { items = items }))\n end, { search = search_opts })\nend\n\n--- Returns whatever it's possible to complete the search and sets up the search related variables in cc\n---@param cc obsidian.completion.sources.base.TagsSourceCompletionContext\n---@return boolean success provides a chance to return early if the request didn't meet the requirements\nfunction TagsSourceBase:can_complete_request(cc)\n local can_complete\n can_complete, cc.search, cc.in_frontmatter = completion.can_complete(cc.request)\n\n if not (can_complete and cc.search ~= nil and #cc.search >= Obsidian.opts.completion.min_chars) then\n cc.completion_resolve_callback(self.incomplete_response)\n return false\n end\n\n return true\nend\n\nreturn TagsSourceBase\n"], ["/obsidian.nvim/lua/obsidian/commands/tags.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\n---@param client obsidian.Client\n---@param picker obsidian.Picker\n---@param tags string[]\nlocal function gather_tag_picker_list(client, picker, tags)\n client:find_tags_async(tags, function(tag_locations)\n -- Format results into picker entries, filtering out results that aren't exact matches or sub-tags.\n ---@type obsidian.PickerEntry[]\n local entries = {}\n for _, tag_loc in ipairs(tag_locations) do\n for _, tag in ipairs(tags) do\n if tag_loc.tag:lower() == tag:lower() or vim.startswith(tag_loc.tag:lower(), tag:lower() .. \"/\") then\n local display = string.format(\"%s [%s] %s\", tag_loc.note:display_name(), tag_loc.line, tag_loc.text)\n entries[#entries + 1] = {\n value = { path = tag_loc.path, line = tag_loc.line, col = tag_loc.tag_start },\n display = display,\n ordinal = display,\n filename = tostring(tag_loc.path),\n lnum = tag_loc.line,\n col = tag_loc.tag_start,\n }\n break\n end\n end\n end\n\n if vim.tbl_isempty(entries) then\n if #tags == 1 then\n log.warn \"Tag not found\"\n else\n log.warn \"Tags not found\"\n end\n return\n end\n\n vim.schedule(function()\n picker:pick(entries, {\n prompt_title = \"#\" .. table.concat(tags, \", #\"),\n callback = function(value)\n api.open_buffer(value.path, { line = value.line, col = value.col })\n end,\n })\n end)\n end, { search = { sort = true } })\nend\n\n---@param client obsidian.Client\n---@param data CommandArgs\nreturn function(client, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n local tags = data.fargs or {}\n\n if vim.tbl_isempty(tags) then\n local tag = api.cursor_tag()\n if tag then\n tags = { tag }\n end\n end\n\n if not vim.tbl_isempty(tags) then\n return gather_tag_picker_list(client, picker, util.tbl_unique(tags))\n else\n client:list_tags_async(nil, function(all_tags)\n vim.schedule(function()\n -- Open picker with tags.\n picker:pick_tag(all_tags, {\n callback = function(...)\n gather_tag_picker_list(client, picker, { ... })\n end,\n allow_multiple = true,\n })\n end)\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/path.lua", "local abc = require \"obsidian.abc\"\n\nlocal function coerce(v)\n if v == vim.NIL then\n return nil\n else\n return v\n end\nend\n\n---@param path table\n---@param k string\n---@param factory fun(obsidian.Path): any\nlocal function cached_get(path, k, factory)\n local cache_key = \"__\" .. k\n local v = rawget(path, cache_key)\n if v == nil then\n v = factory(path)\n if v == nil then\n v = vim.NIL\n end\n path[cache_key] = v\n end\n return coerce(v)\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_name(path)\n local name = vim.fs.basename(path.filename)\n if not name or string.len(name) == 0 then\n return\n else\n return name\n end\nend\n\n---@param path obsidian.Path\n---@return string[]\n---@private\nlocal function get_suffixes(path)\n ---@type string[]\n local suffixes = {}\n local name = path.name\n while name and string.len(name) > 0 do\n local s, e, suffix = string.find(name, \"(%.[^%.]+)$\")\n if s and e and suffix then\n name = string.sub(name, 1, s - 1)\n table.insert(suffixes, suffix)\n else\n break\n end\n end\n\n -- reverse the list.\n ---@type string[]\n local out = {}\n for i = #suffixes, 1, -1 do\n table.insert(out, suffixes[i])\n end\n return out\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_suffix(path)\n local suffixes = path.suffixes\n if #suffixes > 0 then\n return suffixes[#suffixes]\n else\n return nil\n end\nend\n\n---@param path obsidian.Path\n---@return string|?\n---@private\nlocal function get_stem(path)\n local name, suffix = path.name, path.suffix\n if not name then\n return\n elseif not suffix then\n return name\n else\n return string.sub(name, 1, string.len(name) - string.len(suffix))\n end\nend\n\n--- A `Path` class that provides a subset of the functionality of the Python `pathlib` library while\n--- staying true to its API. It improves on a number of bugs in `plenary.path`.\n---\n---@toc_entry obsidian.Path\n---\n---@class obsidian.Path : obsidian.ABC\n---\n---@field filename string The underlying filename as a string.\n---@field name string|? The final path component, if any.\n---@field suffix string|? The final extension of the path, if any.\n---@field suffixes string[] A list of all of the path's extensions.\n---@field stem string|? The final path component, without its suffix.\nlocal Path = abc.new_class()\n\nPath.mt = {\n __tostring = function(self)\n return self.filename\n end,\n __eq = function(a, b)\n return a.filename == b.filename\n end,\n __div = function(self, other)\n return self:joinpath(other)\n end,\n __index = function(self, k)\n local raw = rawget(Path, k)\n if raw then\n return raw\n end\n\n local factory\n if k == \"name\" then\n factory = get_name\n elseif k == \"suffix\" then\n factory = get_suffix\n elseif k == \"suffixes\" then\n factory = get_suffixes\n elseif k == \"stem\" then\n factory = get_stem\n end\n\n if factory then\n return cached_get(self, k, factory)\n end\n end,\n}\n\n--- Check if an object is an `obsidian.Path` object.\n---\n---@param path any\n---\n---@return boolean\nPath.is_path_obj = function(path)\n if getmetatable(path) == Path.mt then\n return true\n else\n return false\n end\nend\n\n-------------------------------------------------------------------------------\n--- Constructors.\n-------------------------------------------------------------------------------\n\n--- Create a new path from a string.\n---\n---@param ... string|obsidian.Path\n---\n---@return obsidian.Path\nPath.new = function(...)\n local self = Path.init()\n\n local args = { ... }\n local arg\n if #args == 1 then\n arg = tostring(args[1])\n elseif #args == 2 and args[1] == Path then\n arg = tostring(args[2])\n else\n error \"expected one argument\"\n end\n\n if Path.is_path_obj(arg) then\n ---@cast arg obsidian.Path\n return arg\n end\n\n self.filename = vim.fs.normalize(tostring(arg))\n\n return self\nend\n\n--- Get a temporary path with a unique name.\n---\n---@param opts { suffix: string|? }|?\n---\n---@return obsidian.Path\nPath.temp = function(opts)\n opts = opts or {}\n local tmpname = vim.fn.tempname()\n if opts.suffix then\n tmpname = tmpname .. opts.suffix\n end\n return Path.new(tmpname)\nend\n\n--- Get a path corresponding to the current working directory as given by `vim.uv.cwd()`.\n---\n---@return obsidian.Path\nPath.cwd = function()\n return assert(Path.new(vim.uv.cwd()))\nend\n\n--- Get a path corresponding to a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buffer = function(bufnr)\n return Path.new(vim.api.nvim_buf_get_name(bufnr or 0))\nend\n\n--- Get a path corresponding to the parent of a buffer.\n---\n---@param bufnr integer|? The buffer number or `0` / `nil` for the current buffer.\n---\n---@return obsidian.Path\nPath.buf_dir = function(bufnr)\n return assert(Path.buffer(bufnr):parent())\nend\n\n-------------------------------------------------------------------------------\n--- Pure path methods.\n-------------------------------------------------------------------------------\n\n--- Return a new path with the suffix changed.\n---\n---@param suffix string\n---@param should_append boolean|? should the suffix append a suffix instead of replacing one which may be there?\n---\n---@return obsidian.Path\nPath.with_suffix = function(self, suffix, should_append)\n if not vim.startswith(suffix, \".\") and string.len(suffix) > 1 then\n error(string.format(\"invalid suffix '%s'\", suffix))\n elseif self.stem == nil then\n error(string.format(\"path '%s' has no stem\", self.filename))\n end\n\n local new_name = ((should_append == true) and self.name or self.stem) .. suffix\n\n ---@type obsidian.Path|?\n local parent = nil\n if self.name ~= self.filename then\n parent = self:parent()\n end\n\n if parent then\n return parent / new_name\n else\n return Path.new(new_name)\n end\nend\n\n--- Returns true if the path is already in absolute form.\n---\n---@return boolean\nPath.is_absolute = function(self)\n local api = require \"obsidian.api\"\n if\n vim.startswith(self.filename, \"/\")\n or (\n (api.get_os() == api.OSType.Windows or api.get_os() == api.OSType.Wsl)\n and string.match(self.filename, \"^[%a]:/.*$\")\n )\n then\n return true\n else\n return false\n end\nend\n\n---@param ... obsidian.Path|string\n---@return obsidian.Path\nPath.joinpath = function(self, ...)\n local args = vim.iter({ ... }):map(tostring):totable()\n return Path.new(vim.fs.joinpath(self.filename, unpack(args)))\nend\n\n--- Try to resolve a version of the path relative to the other.\n--- An error is raised when it's not possible.\n---\n---@param other obsidian.Path|string\n---\n---@return obsidian.Path\nPath.relative_to = function(self, other)\n other = Path.new(other)\n\n local other_fname = other.filename\n if not vim.endswith(other_fname, \"/\") then\n other_fname = other_fname .. \"/\"\n end\n\n if vim.startswith(self.filename, other_fname) then\n return Path.new(string.sub(self.filename, string.len(other_fname) + 1))\n end\n\n -- Edge cases when the paths are relative or under-specified, see tests.\n if not self:is_absolute() and not vim.startswith(self.filename, \"./\") and vim.startswith(other_fname, \"./\") then\n if other_fname == \"./\" then\n return self\n end\n\n local self_rel_to_cwd = Path.new \"./\" / self\n if vim.startswith(self_rel_to_cwd.filename, other_fname) then\n return Path.new(string.sub(self_rel_to_cwd.filename, string.len(other_fname) + 1))\n end\n end\n\n error(string.format(\"'%s' is not in the subpath of '%s'\", self.filename, other.filename))\nend\n\n--- The logical parent of the path.\n---\n---@return obsidian.Path|?\nPath.parent = function(self)\n local parent = vim.fs.dirname(self.filename)\n if parent ~= nil then\n return Path.new(parent)\n else\n return nil\n end\nend\n\n--- Get a list of the parent directories.\n---\n---@return obsidian.Path[]\nPath.parents = function(self)\n return vim.iter(vim.fs.parents(self.filename)):map(Path.new):totable()\nend\n\n--- Check if the path is a parent of other. This is a pure path method, so it only checks by\n--- comparing strings. Therefore in practice you probably want to `:resolve()` each path before\n--- using this.\n---\n---@param other obsidian.Path|string\n---\n---@return boolean\nPath.is_parent_of = function(self, other)\n other = Path.new(other)\n for _, parent in ipairs(other:parents()) do\n if parent == self then\n return true\n end\n end\n return false\nend\n\n---@return string?\n---@private\nPath.abspath = function(self)\n local path = vim.loop.fs_realpath(vim.fn.resolve(self.filename))\n return path\nend\n\n-------------------------------------------------------------------------------\n--- Concrete path methods.\n-------------------------------------------------------------------------------\n\n--- Make the path absolute, resolving any symlinks.\n--- If `strict` is true and the path doesn't exist, an error is raised.\n---\n---@param opts { strict: boolean }|?\n---\n---@return obsidian.Path\nPath.resolve = function(self, opts)\n opts = opts or {}\n\n local realpath = self:abspath()\n if realpath then\n return Path.new(realpath)\n elseif opts.strict then\n error(\"FileNotFoundError: \" .. self.filename)\n end\n\n -- File doesn't exist, but some parents might. Traverse up until we find a parent that\n -- does exist, and then put the path back together from there.\n local parents = self:parents()\n for _, parent in ipairs(parents) do\n local parent_realpath = parent:abspath()\n if parent_realpath then\n return Path.new(parent_realpath) / self:relative_to(parent)\n end\n end\n\n return self\nend\n\n--- Get OS stat results.\n---\n---@return table|?\nPath.stat = function(self)\n local realpath = self:abspath()\n if realpath then\n local stat, _ = vim.uv.fs_stat(realpath)\n return stat\n end\nend\n\n--- Check if the path points to an existing file or directory.\n---\n---@return boolean\nPath.exists = function(self)\n local stat = self:stat()\n return stat ~= nil\nend\n\n--- Check if the path points to an existing file.\n---\n---@return boolean\nPath.is_file = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"file\"\n end\nend\n\n--- Check if the path points to an existing directory.\n---\n---@return boolean\nPath.is_dir = function(self)\n local stat = self:stat()\n if stat == nil then\n return false\n else\n return stat.type == \"directory\"\n end\nend\n\n--- Create a new directory at the given path.\n---\n---@param opts { mode: integer|?, parents: boolean|?, exist_ok: boolean|? }|?\nPath.mkdir = function(self, opts)\n opts = opts or {}\n\n local mode = opts.mode or 448 -- 0700 -> decimal\n ---@diagnostic disable-next-line: undefined-field\n if opts.exists_ok then -- for compat with the plenary.path API.\n opts.exist_ok = true\n end\n\n if self:is_dir() then\n if not opts.exist_ok then\n error(\"FileExistsError: \" .. self.filename)\n else\n return\n end\n end\n\n if vim.uv.fs_mkdir(self.filename, mode) then\n return\n end\n\n if not opts.parents then\n error(\"FileNotFoundError: \" .. tostring(self:parent()))\n end\n\n local parents = self:parents()\n for i = #parents, 1, -1 do\n if not parents[i]:is_dir() then\n parents[i]:mkdir { exist_ok = true, mode = mode }\n end\n end\n\n self:mkdir { mode = mode }\nend\n\n--- Remove the corresponding directory. This directory must be empty.\nPath.rmdir = function(self)\n local resolved = self:resolve { strict = false }\n\n if not resolved:is_dir() then\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_rmdir(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n-- TODO: not implemented and not used, after we get to 0.11 we can simply use vim.fs.rm\n--- Recursively remove an entire directory and its contents.\nPath.rmtree = function(self) end\n\n--- Create a file at this given path.\n---\n---@param opts { mode: integer|?, exist_ok: boolean|? }|?\nPath.touch = function(self, opts)\n opts = opts or {}\n local mode = opts.mode or 420\n\n local resolved = self:resolve { strict = false }\n if resolved:exists() then\n local new_time = os.time()\n vim.uv.fs_utime(resolved.filename, new_time, new_time)\n return\n end\n\n local parent = resolved:parent()\n if parent and not parent:exists() then\n error(\"FileNotFoundError: \" .. parent.filename)\n end\n\n local fd, err_name, err_msg = vim.uv.fs_open(resolved.filename, \"w\", mode)\n if not fd then\n error(err_name .. \": \" .. err_msg)\n end\n vim.uv.fs_close(fd)\nend\n\n--- Rename this file or directory to the given target.\n---\n---@param target obsidian.Path|string\n---\n---@return obsidian.Path\nPath.rename = function(self, target)\n local resolved = self:resolve { strict = false }\n target = Path.new(target)\n\n local ok, err_name, err_msg = vim.uv.fs_rename(resolved.filename, target.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\n\n return target\nend\n\n--- Remove the file.\n---\n---@param opts { missing_ok: boolean|? }|?\nPath.unlink = function(self, opts)\n opts = opts or {}\n\n local resolved = self:resolve { strict = false }\n\n if not resolved:exists() then\n if not opts.missing_ok then\n error(\"FileNotFoundError: \" .. resolved.filename)\n end\n return\n end\n\n local ok, err_name, err_msg = vim.uv.fs_unlink(resolved.filename)\n if not ok then\n error(err_name .. \": \" .. err_msg)\n end\nend\n\n--- Make a path relative to the vault root, if possible, return a string\n---\n---@param opts { strict: boolean|? }|?\n---\n---@return string?\nPath.vault_relative_path = function(self, opts)\n opts = opts or {}\n\n -- NOTE: we don't try to resolve the `path` here because that would make the path absolute,\n -- which may result in the wrong relative path if the current working directory is not within\n -- the vault.\n\n local ok, relative_path = pcall(function()\n return self:relative_to(Obsidian.workspace.root)\n end)\n\n if ok and relative_path then\n return tostring(relative_path)\n elseif not self:is_absolute() then\n return tostring(self)\n elseif opts.strict then\n error(string.format(\"failed to resolve '%s' relative to vault root '%s'\", self, Obsidian.workspace.root))\n end\nend\n\nreturn Path\n"], ["/obsidian.nvim/lua/obsidian/health.lua", "local M = {}\nlocal VERSION = require \"obsidian.version\"\nlocal api = require \"obsidian.api\"\n\nlocal error = vim.health.error\nlocal warn = vim.health.warn\nlocal ok = vim.health.ok\n\nlocal function info(...)\n local t = { ... }\n local format = table.remove(t, 1)\n local str = #t == 0 and format or string.format(format, unpack(t))\n return ok(str)\nend\n\n---@private\n---@param name string\nlocal function start(name)\n vim.health.start(string.format(\"obsidian.nvim [%s]\", name))\nend\n\n---@param plugin string\n---@param optional boolean\n---@return boolean\nlocal function has_plugin(plugin, optional)\n local plugin_info = api.get_plugin_info(plugin)\n if plugin_info then\n info(\"%s: %s\", plugin, plugin_info.commit or \"unknown\")\n return true\n else\n if not optional then\n vim.health.error(\" \" .. plugin .. \" not installed\")\n end\n return false\n end\nend\n\nlocal function has_executable(name, optional)\n if vim.fn.executable(name) == 1 then\n local version = api.get_external_dependency_info(name)\n if version then\n info(\"%s: %s\", name, version)\n else\n info(\"%s: found\", name)\n end\n return true\n else\n if not optional then\n error(string.format(\"%s not found\", name))\n end\n return false\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_plugin(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param plugins string[]\nlocal function has_one_of_executable(plugins)\n local found\n for _, name in ipairs(plugins) do\n if has_executable(name, true) then\n found = true\n end\n end\n if not found then\n vim.health.warn(\"It is recommended to install at least one of \" .. vim.inspect(plugins))\n end\nend\n\n---@param minimum string\n---@param recommended string\nlocal function neovim(minimum, recommended)\n if vim.fn.has(\"nvim-\" .. minimum) == 0 then\n error(\"neovim < \" .. minimum)\n elseif vim.fn.has(\"nvim-\" .. recommended) == 0 then\n warn(\"neovim < \" .. recommended .. \" some features will not work\")\n else\n ok(\"neovim >= \" .. recommended)\n end\nend\n\nfunction M.check()\n local os = api.get_os()\n neovim(\"0.10\", \"0.11\")\n start \"Version\"\n info(\"obsidian.nvim v%s (%s)\", VERSION, api.get_plugin_info(\"obsidian.nvim\").commit)\n\n start \"Environment\"\n info(\"operating system: %s\", os)\n\n start \"Config\"\n info(\" • dir: %s\", Obsidian.dir)\n\n start \"Pickers\"\n\n has_one_of {\n \"telescope.nvim\",\n \"fzf-lua\",\n \"mini.nvim\",\n \"mini.pick\",\n \"snacks.nvim\",\n }\n\n start \"Completion\"\n\n has_one_of {\n \"nvim-cmp\",\n \"blink.cmp\",\n }\n\n start \"Dependencies\"\n has_executable(\"rg\", false)\n has_plugin(\"plenary.nvim\", false)\n\n if os == api.OSType.Wsl then\n has_executable(\"wsl-open\", true)\n elseif os == api.OSType.Linux then\n has_one_of_executable {\n \"xclip\",\n \"wl-paste\",\n }\n elseif os == api.OSType.Darwin then\n has_executable(\"pngpaste\", true)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/util.lua", "local compat = require \"obsidian.compat\"\nlocal ts, string, table = vim.treesitter, string, table\nlocal util = {}\n\nsetmetatable(util, {\n __index = function(_, k)\n return require(\"obsidian.api\")[k] or require(\"obsidian.builtin\")[k]\n end,\n})\n\n-------------------\n--- File tools ----\n-------------------\n\n---@param file string\n---@param contents string\nutil.write_file = function(file, contents)\n local fd = assert(io.open(file, \"w+\"))\n fd:write(contents)\n fd:close()\nend\n\n-------------------\n--- Iter tools ----\n-------------------\n\n---Create an enumeration iterator over an iterable.\n---@param iterable table|string|function\n---@return function\nutil.enumerate = function(iterable)\n local iterator = vim.iter(iterable)\n local i = 0\n\n return function()\n local next = iterator()\n if next == nil then\n return nil, nil\n else\n i = i + 1\n return i, next\n end\n end\nend\n\n---Zip two iterables together.\n---@param iterable1 table|string|function\n---@param iterable2 table|string|function\n---@return function\nutil.zip = function(iterable1, iterable2)\n local iterator1 = vim.iter(iterable1)\n local iterator2 = vim.iter(iterable2)\n\n return function()\n local next1 = iterator1()\n local next2 = iterator2()\n if next1 == nil or next2 == nil then\n return nil\n else\n return next1, next2\n end\n end\nend\n\n-------------------\n--- Table tools ---\n-------------------\n\n---Check if an object is an array-like table.\n--- TODO: after 0.12 replace with vim.islist\n---\n---@param t any\n---@return boolean\nutil.islist = function(t)\n return compat.is_list(t)\nend\n\n---Return a new list table with only the unique values of the original table.\n---\n---@param t table\n---@return any[]\nutil.tbl_unique = function(t)\n local found = {}\n for _, val in pairs(t) do\n found[val] = true\n end\n return vim.tbl_keys(found)\nend\n\n--------------------\n--- String Tools ---\n--------------------\n\n---Iterate over all matches of 'pattern' in 's'. 'gfind' is to 'find' as 'gsub' is to 'sub'.\n---@param s string\n---@param pattern string\n---@param init integer|?\n---@param plain boolean|?\nutil.gfind = function(s, pattern, init, plain)\n init = init and init or 1\n\n return function()\n if init < #s then\n local m_start, m_end = string.find(s, pattern, init, plain)\n if m_start ~= nil and m_end ~= nil then\n init = m_end + 1\n return m_start, m_end\n end\n end\n return nil\n end\nend\n\nlocal char_to_hex = function(c)\n return string.format(\"%%%02X\", string.byte(c))\nend\n\n--- Encode a string into URL-safe version.\n---\n---@param str string\n---@param opts { keep_path_sep: boolean|? }|?\n---\n---@return string\nutil.urlencode = function(str, opts)\n opts = opts or {}\n local url = str\n url = url:gsub(\"\\n\", \"\\r\\n\")\n url = url:gsub(\"([%(%)%*%?%[%]%$\\\"':<>|\\\\'{}])\", char_to_hex)\n if not opts.keep_path_sep then\n url = url:gsub(\"/\", char_to_hex)\n end\n\n -- Spaces in URLs are always safely encoded with `%20`, but not always safe\n -- with `+`. For example, `+` in a query param's value will be interpreted\n -- as a literal plus-sign if the decoder is using JavaScript's `decodeURI`\n -- function.\n url = url:gsub(\" \", \"%%20\")\n return url\nend\n\nutil.is_hex_color = function(s)\n return (s:match \"^#%x%x%x$\" or s:match \"^#%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x$\" or s:match \"^#%x%x%x%x%x%x%x%x$\")\n ~= nil\nend\n\n---Match the case of 'key' to the given 'prefix' of the key.\n---\n---@param prefix string\n---@param key string\n---@return string|?\nutil.match_case = function(prefix, key)\n local out_chars = {}\n for i = 1, string.len(key) do\n local c_key = string.sub(key, i, i)\n local c_pre = string.sub(prefix, i, i)\n if c_pre:lower() == c_key:lower() then\n table.insert(out_chars, c_pre)\n elseif c_pre:len() > 0 then\n return nil\n else\n table.insert(out_chars, c_key)\n end\n end\n return table.concat(out_chars, \"\")\nend\n\n---Check if a string is a checkbox list item\n---\n---Supported checboox lists:\n--- - [ ] foo\n--- - [x] foo\n--- + [x] foo\n--- * [ ] foo\n--- 1. [ ] foo\n--- 1) [ ] foo\n---\n---@param s string\n---@return boolean\nutil.is_checkbox = function(s)\n -- - [ ] and * [ ] and + [ ]\n if string.match(s, \"^%s*[-+*]%s+%[.%]\") ~= nil then\n return true\n end\n -- 1. [ ] and 1) [ ]\n if string.match(s, \"^%s*%d+[%.%)]%s+%[.%]\") ~= nil then\n return true\n end\n return false\nend\n\n---Check if a string is a valid URL.\n---@param s string\n---@return boolean\nutil.is_url = function(s)\n local search = require \"obsidian.search\"\n\n if\n string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.NakedUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.FileUrl] .. \"$\")\n or string.match(vim.trim(s), \"^\" .. search.Patterns[search.RefTypes.MailtoUrl] .. \"$\")\n then\n return true\n else\n return false\n end\nend\n\n---Checks if a given string represents an image file based on its suffix.\n---\n---@param s string: The input string to check.\n---@return boolean: Returns true if the string ends with a supported image suffix, false otherwise.\nutil.is_img = function(s)\n for _, suffix in ipairs { \".png\", \".jpg\", \".jpeg\", \".heic\", \".gif\", \".svg\", \".ico\" } do\n if vim.endswith(s, suffix) then\n return true\n end\n end\n return false\nend\n\n-- This function removes a single backslash within double square brackets\nutil.unescape_single_backslash = function(text)\n return text:gsub(\"(%[%[[^\\\\]+)\\\\(%|[^\\\\]+]])\", \"%1%2\")\nend\n\nutil.string_enclosing_chars = { [[\"]], [[']] }\n\n---Count the indentation of a line.\n---@param str string\n---@return integer\nutil.count_indent = function(str)\n local indent = 0\n for i = 1, #str do\n local c = string.sub(str, i, i)\n -- space or tab both count as 1 indent\n if c == \" \" or c == \"\t\" then\n indent = indent + 1\n else\n break\n end\n end\n return indent\nend\n\n---Check if a string is only whitespace.\n---@param str string\n---@return boolean\nutil.is_whitespace = function(str)\n return string.match(str, \"^%s+$\") ~= nil\nend\n\n---Get the substring of `str` starting from the first character and up to the stop character,\n---ignoring any enclosing characters (like double quotes) and stop characters that are within the\n---enclosing characters. For example, if `str = [=[\"foo\", \"bar\"]=]` and `stop_char = \",\"`, this\n---would return the string `[=[foo]=]`.\n---\n---@param str string\n---@param stop_chars string[]\n---@param keep_stop_char boolean|?\n---@return string|?, string\nutil.next_item = function(str, stop_chars, keep_stop_char)\n local og_str = str\n\n -- Check for enclosing characters.\n local enclosing_char = nil\n local first_char = string.sub(str, 1, 1)\n for _, c in ipairs(util.string_enclosing_chars) do\n if first_char == c then\n enclosing_char = c\n str = string.sub(str, 2)\n break\n end\n end\n\n local result\n local hits\n\n for _, stop_char in ipairs(stop_chars) do\n -- First check for next item when `stop_char` is present.\n if enclosing_char ~= nil then\n result, hits = string.gsub(\n str,\n \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*\" .. stop_char .. \".*\",\n \"%1%2\"\n )\n result = enclosing_char .. result .. enclosing_char\n else\n result, hits = string.gsub(str, \"([^\" .. stop_char .. \"]+)\" .. stop_char .. \".*\", \"%1\")\n end\n if hits ~= 0 then\n local i = string.find(str, stop_char, string.len(result), true)\n if keep_stop_char then\n return result .. stop_char, string.sub(str, i + 1)\n else\n return result, string.sub(str, i + 1)\n end\n end\n\n -- Now check for next item without the `stop_char` after.\n if not keep_stop_char and enclosing_char ~= nil then\n result, hits = string.gsub(str, \"([^\" .. enclosing_char .. \"]+)([^\\\\]?)\" .. enclosing_char .. \"%s*$\", \"%1%2\")\n result = enclosing_char .. result .. enclosing_char\n elseif not keep_stop_char then\n result = str\n hits = 1\n else\n result = nil\n hits = 0\n end\n if hits ~= 0 then\n if keep_stop_char then\n result = result .. stop_char\n end\n return result, \"\"\n end\n end\n\n return nil, og_str\nend\n\n---Strip whitespace from the right end of a string.\n---@param str string\n---@return string\nutil.rstrip_whitespace = function(str)\n str = string.gsub(str, \"%s+$\", \"\")\n return str\nend\n\n---Strip whitespace from the left end of a string.\n---@param str string\n---@param limit integer|?\n---@return string\nutil.lstrip_whitespace = function(str, limit)\n if limit ~= nil then\n local num_found = 0\n while num_found < limit do\n str = string.gsub(str, \"^%s\", \"\")\n num_found = num_found + 1\n end\n else\n str = string.gsub(str, \"^%s+\", \"\")\n end\n return str\nend\n\n---Strip enclosing characters like quotes from a string.\n---@param str string\n---@return string\nutil.strip_enclosing_chars = function(str)\n local c_start = string.sub(str, 1, 1)\n local c_end = string.sub(str, #str, #str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if c_start == enclosing_char and c_end == enclosing_char then\n str = string.sub(str, 2, #str - 1)\n break\n end\n end\n return str\nend\n\n---Check if a string has enclosing characters like quotes.\n---@param str string\n---@return boolean\nutil.has_enclosing_chars = function(str)\n for _, enclosing_char in ipairs(util.string_enclosing_chars) do\n if vim.startswith(str, enclosing_char) and vim.endswith(str, enclosing_char) then\n return true\n end\n end\n return false\nend\n\n---Strip YAML comments from a string.\n---@param str string\n---@return string\nutil.strip_comments = function(str)\n if vim.startswith(str, \"# \") then\n return \"\"\n elseif not util.has_enclosing_chars(str) then\n return select(1, string.gsub(str, [[%s+#%s.*$]], \"\"))\n else\n return str\n end\nend\n\n---Check if a string contains a substring.\n---@param str string\n---@param substr string\n---@return boolean\nutil.string_contains = function(str, substr)\n local i = string.find(str, substr, 1, true)\n return i ~= nil\nend\n\n--------------------\n--- Date helpers ---\n--------------------\n\n---Determines if the given date is a working day (not weekend)\n---\n---@param time integer\n---\n---@return boolean\nutil.is_working_day = function(time)\n local is_saturday = (os.date(\"%w\", time) == \"6\")\n local is_sunday = (os.date(\"%w\", time) == \"0\")\n return not (is_saturday or is_sunday)\nend\n\n--- Returns the previous day from given time\n---\n--- @param time integer\n--- @return integer\nutil.previous_day = function(time)\n return time - (24 * 60 * 60)\nend\n---\n--- Returns the next day from given time\n---\n--- @param time integer\n--- @return integer\nutil.next_day = function(time)\n return time + (24 * 60 * 60)\nend\n\n---Determines the last working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_before = function(time)\n local previous_day = util.previous_day(time)\n if util.is_working_day(previous_day) then\n return previous_day\n else\n return util.working_day_before(previous_day)\n end\nend\n\n---Determines the next working day before a given time\n---\n---@param time integer\n---@return integer\nutil.working_day_after = function(time)\n local next_day = util.next_day(time)\n if util.is_working_day(next_day) then\n return next_day\n else\n return util.working_day_after(next_day)\n end\nend\n\n---@param link string\n---@param opts { include_naked_urls: boolean|?, include_file_urls: boolean|?, include_block_ids: boolean|?, link_type: obsidian.search.RefTypes|? }|?\n---\n---@return string|?, string|?, obsidian.search.RefTypes|?\nutil.parse_link = function(link, opts)\n local search = require \"obsidian.search\"\n\n opts = opts and opts or {}\n\n local link_type = opts.link_type\n if link_type == nil then\n for match in\n vim.iter(search.find_refs(link, {\n include_naked_urls = opts.include_naked_urls,\n include_file_urls = opts.include_file_urls,\n include_block_ids = opts.include_block_ids,\n }))\n do\n local _, _, m_type = unpack(match)\n if m_type then\n link_type = m_type\n break\n end\n end\n end\n\n if link_type == nil then\n return nil\n end\n\n local link_location, link_name\n if link_type == search.RefTypes.Markdown then\n link_location = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%2\")\n link_name = link:gsub(\"^%[(.-)%]%((.*)%)$\", \"%1\")\n elseif link_type == search.RefTypes.NakedUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.FileUrl then\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.WikiWithAlias then\n link = util.unescape_single_backslash(link)\n -- remove boundary brackets, e.g. '[[XXX|YYY]]' -> 'XXX|YYY'\n link = link:sub(3, #link - 2)\n -- split on the \"|\"\n local split_idx = link:find \"|\"\n link_location = link:sub(1, split_idx - 1)\n link_name = link:sub(split_idx + 1)\n elseif link_type == search.RefTypes.Wiki then\n -- remove boundary brackets, e.g. '[[YYY]]' -> 'YYY'\n link = link:sub(3, #link - 2)\n link_location = link\n link_name = link\n elseif link_type == search.RefTypes.BlockID then\n link_location = util.standardize_block(link)\n link_name = link\n else\n error(\"not implemented for \" .. link_type)\n end\n\n return link_location, link_name, link_type\nend\n\n------------------------------------\n-- Miscellaneous helper functions --\n------------------------------------\n---@param anchor obsidian.note.HeaderAnchor\n---@return string\nutil.format_anchor_label = function(anchor)\n return string.format(\" ❯ %s\", anchor.header)\nend\n\n-- We are very loose here because obsidian allows pretty much anything\nutil.ANCHOR_LINK_PATTERN = \"#[%w%d\\128-\\255][^#]*\"\n\nutil.BLOCK_PATTERN = \"%^[%w%d][%w%d-]*\"\n\nutil.BLOCK_LINK_PATTERN = \"#\" .. util.BLOCK_PATTERN\n\n--- Strip anchor links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_anchor_links = function(line)\n ---@type string|?\n local anchor\n\n while true do\n local anchor_match = string.match(line, util.ANCHOR_LINK_PATTERN .. \"$\")\n if anchor_match then\n anchor = anchor or \"\"\n anchor = anchor_match .. anchor\n line = string.sub(line, 1, -anchor_match:len() - 1)\n else\n break\n end\n end\n\n return line, anchor and util.standardize_anchor(anchor)\nend\n\n--- Parse a block line from a line.\n---\n---@param line string\n---\n---@return string|?\nutil.parse_block = function(line)\n local block_match = string.match(line, util.BLOCK_PATTERN .. \"$\")\n return block_match\nend\n\n--- Strip block links from a line.\n---@param line string\n---@return string, string|?\nutil.strip_block_links = function(line)\n local block_match = string.match(line, util.BLOCK_LINK_PATTERN .. \"$\")\n if block_match then\n line = string.sub(line, 1, -block_match:len() - 1)\n end\n return line, block_match\nend\n\n--- Standardize a block identifier.\n---@param block_id string\n---@return string\nutil.standardize_block = function(block_id)\n if vim.startswith(block_id, \"#\") then\n block_id = string.sub(block_id, 2)\n end\n\n if not vim.startswith(block_id, \"^\") then\n block_id = \"^\" .. block_id\n end\n\n return block_id\nend\n\n--- Check if a line is a markdown header.\n---@param line string\n---@return boolean\nutil.is_header = function(line)\n if string.match(line, \"^#+%s+[%w]+\") then\n return true\n else\n return false\n end\nend\n\n--- Get the header level of a line.\n---@param line string\n---@return integer\nutil.header_level = function(line)\n local headers, match_count = string.gsub(line, \"^(#+)%s+[%w]+.*\", \"%1\")\n if match_count > 0 then\n return string.len(headers)\n else\n return 0\n end\nend\n\n---@param line string\n---@return { header: string, level: integer, anchor: string }|?\nutil.parse_header = function(line)\n local header_start, header = string.match(line, \"^(#+)%s+([^%s]+.*)$\")\n if header_start and header then\n header = vim.trim(header)\n return {\n header = vim.trim(header),\n level = string.len(header_start),\n anchor = util.header_to_anchor(header),\n }\n else\n return nil\n end\nend\n\n--- Standardize a header anchor link.\n---\n---@param anchor string\n---\n---@return string\nutil.standardize_anchor = function(anchor)\n -- Lowercase everything.\n anchor = string.lower(anchor)\n -- Replace whitespace with \"-\".\n anchor = string.gsub(anchor, \"%s\", \"-\")\n -- Remove every non-alphanumeric character.\n anchor = string.gsub(anchor, \"[^#%w\\128-\\255_-]\", \"\")\n return anchor\nend\n\n--- Transform a markdown header into an link, e.g. \"# Hello World\" -> \"#hello-world\".\n---\n---@param header string\n---\n---@return string\nutil.header_to_anchor = function(header)\n -- Remove leading '#' and strip whitespace.\n local anchor = vim.trim(string.gsub(header, [[^#+%s+]], \"\"))\n return util.standardize_anchor(\"#\" .. anchor)\nend\n\n---@alias datetime_cadence \"daily\"\n\n--- Parse possible relative date macros like '@tomorrow'.\n---\n---@param macro string\n---\n---@return { macro: string, offset: integer, cadence: datetime_cadence }[]\nutil.resolve_date_macro = function(macro)\n ---@type { macro: string, offset: integer, cadence: datetime_cadence }[]\n local out = {}\n for m, offset_days in pairs { today = 0, tomorrow = 1, yesterday = -1 } do\n m = \"@\" .. m\n if vim.startswith(m, macro) then\n out[#out + 1] = { macro = m, offset = offset_days, cadence = \"daily\" }\n end\n end\n return out\nend\n\n--- Check if a string contains invalid characters.\n---\n--- @param fname string\n---\n--- @return boolean\nutil.contains_invalid_characters = function(fname)\n local invalid_chars = \"#^%[%]|\"\n return string.find(fname, \"[\" .. invalid_chars .. \"]\") ~= nil\nend\n\n---Check if a string is NaN\n---\n---@param v any\n---@return boolean\nutil.isNan = function(v)\n return tostring(v) == tostring(0 / 0)\nend\n\n---Higher order function, make sure a function is called with complete lines\n---@param fn fun(string)?\n---@return fun(string)\nutil.buffer_fn = function(fn)\n if not fn then\n return function() end\n end\n local buffer = \"\"\n return function(data)\n buffer = buffer .. data\n local lines = vim.split(buffer, \"\\n\")\n if #lines > 1 then\n for i = 1, #lines - 1 do\n fn(lines[i])\n end\n buffer = lines[#lines] -- Store remaining partial line\n end\n end\nend\n\n---@param event string\n---@param callback fun(...)\n---@param ... any\n---@return boolean success\nutil.fire_callback = function(event, callback, ...)\n local log = require \"obsidian.log\"\n if not callback then\n return false\n end\n local ok, err = pcall(callback, ...)\n if ok then\n return true\n else\n log.error(\"Error running %s callback: %s\", event, err)\n return false\n end\nend\n\n---@param node_type string | string[]\n---@return boolean\nutil.in_node = function(node_type)\n local function in_node(t)\n local node = ts.get_node()\n while node do\n if node:type() == t then\n return true\n end\n node = node:parent()\n end\n return false\n end\n if type(node_type) == \"string\" then\n return in_node(node_type)\n elseif type(node_type) == \"table\" then\n for _, t in ipairs(node_type) do\n local is_in_node = in_node(t)\n if is_in_node then\n return true\n end\n end\n end\n return false\nend\n\nreturn util\n"], ["/obsidian.nvim/lua/obsidian/pickers/_fzf.lua", "local fzf = require \"fzf-lua\"\nlocal fzf_actions = require \"fzf-lua.actions\"\nlocal entry_to_file = require(\"fzf-lua.path\").entry_to_file\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@param prompt_title string|?\n---@return string|?\nlocal function format_prompt(prompt_title)\n if not prompt_title then\n return\n else\n return prompt_title .. \" ❯ \"\n end\nend\n\n---@param keymap string\n---@return string\nlocal function format_keymap(keymap)\n keymap = string.lower(keymap)\n keymap = string.gsub(keymap, vim.pesc \"\", \"\")\n return keymap\nend\n\n---@class obsidian.pickers.FzfPicker : obsidian.Picker\nlocal FzfPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"FzfPicker()\"\n end,\n}, Picker)\n\n---@param opts { callback: fun(path: string)|?, no_default_mappings: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_path_actions(opts)\n local actions = {\n default = function(selected, fzf_opts)\n if not opts.no_default_mappings then\n fzf_actions.file_edit_or_qf(selected, fzf_opts)\n end\n\n if opts.callback then\n local path = entry_to_file(selected[1], fzf_opts).path\n opts.callback(path)\n end\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected, fzf_opts)\n local path = entry_to_file(selected[1], fzf_opts).path\n mapping.callback(path)\n end\n end\n end\n\n return actions\nend\n\n---@param display_to_value_map table\n---@param opts { callback: fun(path: string)|?, allow_multiple: boolean|?, selection_mappings: obsidian.PickerMappingTable|? }\nlocal function get_value_actions(display_to_value_map, opts)\n ---@param allow_multiple boolean|?\n ---@return any[]|?\n local function get_values(selected, allow_multiple)\n if not selected then\n return\n end\n\n local values = vim.tbl_map(function(k)\n return display_to_value_map[k]\n end, selected)\n\n values = vim.tbl_filter(function(v)\n return v ~= nil\n end, values)\n\n if #values > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if #values > 0 then\n return values\n else\n return nil\n end\n end\n\n local actions = {\n default = function(selected)\n if not opts.callback then\n return\n end\n\n local values = get_values(selected, opts.allow_multiple)\n if not values then\n return\n end\n\n opts.callback(unpack(values))\n end,\n }\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n actions[format_keymap(key)] = function(selected)\n local values = get_values(selected, mapping.allow_multiple)\n if not values then\n return\n end\n\n mapping.callback(unpack(values))\n end\n end\n end\n\n return actions\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nFzfPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path.new(opts.dir) or Obsidian.dir\n\n fzf.files {\n cwd = tostring(dir),\n cmd = table.concat(self:_build_find_cmd(), \" \"),\n actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n },\n prompt = format_prompt(opts.prompt_title),\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nFzfPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n local cmd = table.concat(self:_build_grep_cmd(), \" \")\n local actions = get_path_actions {\n callback = opts.callback,\n no_default_mappings = opts.no_default_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n if opts.query and string.len(opts.query) > 0 then\n fzf.grep {\n cwd = tostring(dir),\n search = opts.query,\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n else\n fzf.live_grep {\n cwd = tostring(dir),\n cmd = cmd,\n actions = actions,\n prompt = format_prompt(opts.prompt_title),\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nFzfPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts or {}\n\n ---@type table\n local display_to_value_map = {}\n\n ---@type string[]\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n display_to_value_map[value] = value\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n local display = self:_make_display(value)\n display_to_value_map[display] = value.value\n entries[#entries + 1] = display\n end\n end\n\n fzf.fzf_exec(entries, {\n prompt = format_prompt(\n self:_build_prompt { prompt_title = opts.prompt_title, selection_mappings = opts.selection_mappings }\n ),\n actions = get_value_actions(display_to_value_map, {\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n selection_mappings = opts.selection_mappings,\n }),\n })\nend\n\nreturn FzfPicker\n"], ["/obsidian.nvim/lua/obsidian/pickers/_telescope.lua", "local telescope = require \"telescope.builtin\"\nlocal telescope_actions = require \"telescope.actions\"\nlocal actions_state = require \"telescope.actions.state\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.pickers.TelescopePicker : obsidian.Picker\nlocal TelescopePicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"TelescopePicker()\"\n end,\n}, Picker)\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@return table|?\nlocal function get_entry(prompt_bufnr, keep_open)\n local entry = actions_state.get_selected_entry()\n if entry and not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return entry\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param allow_multiple boolean|?\n---@return table[]|?\nlocal function get_selected(prompt_bufnr, keep_open, allow_multiple)\n local picker = actions_state.get_current_picker(prompt_bufnr)\n local entries = picker:get_multi_selection()\n if entries and #entries > 0 then\n if #entries > 1 and not allow_multiple then\n log.err \"This mapping does not allow multiple entries\"\n return\n end\n\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n\n return entries\n else\n local entry = get_entry(prompt_bufnr, keep_open)\n\n if entry then\n return { entry }\n end\n end\nend\n\n---@param prompt_bufnr integer\n---@param keep_open boolean|?\n---@param initial_query string|?\n---@return string|?\nlocal function get_query(prompt_bufnr, keep_open, initial_query)\n local query = actions_state.get_current_line()\n if not query or string.len(query) == 0 then\n query = initial_query\n end\n if query and string.len(query) > 0 then\n if not keep_open then\n telescope_actions.close(prompt_bufnr)\n end\n return query\n else\n return nil\n end\nend\n\n---@param opts { entry_key: string|?, callback: fun(path: string)|?, allow_multiple: boolean|?, query_mappings: obsidian.PickerMappingTable|?, selection_mappings: obsidian.PickerMappingTable|?, initial_query: string|? }\nlocal function attach_picker_mappings(map, opts)\n -- Docs for telescope actions:\n -- https://github.com/nvim-telescope/telescope.nvim/blob/master/lua/telescope/actions/init.lua\n\n local function entry_to_value(entry)\n if opts.entry_key then\n return entry[opts.entry_key]\n else\n return entry\n end\n end\n\n if opts.query_mappings then\n for key, mapping in pairs(opts.query_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local query = get_query(prompt_bufnr, false, opts.initial_query)\n if query then\n mapping.callback(query)\n end\n end)\n end\n end\n\n if opts.selection_mappings then\n for key, mapping in pairs(opts.selection_mappings) do\n map({ \"i\", \"n\" }, key, function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, mapping.keep_open, mapping.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n mapping.callback(unpack(values))\n elseif mapping.fallback_to_query then\n local query = get_query(prompt_bufnr, mapping.keep_open)\n if query then\n mapping.callback(query)\n end\n end\n end)\n end\n end\n\n if opts.callback then\n map({ \"i\", \"n\" }, \"\", function(prompt_bufnr)\n local entries = get_selected(prompt_bufnr, false, opts.allow_multiple)\n if entries then\n local values = vim.tbl_map(entry_to_value, entries)\n opts.callback(unpack(values))\n end\n end)\n end\nend\n\n---@param opts obsidian.PickerFindOpts|? Options.\nTelescopePicker.find_files = function(self, opts)\n opts = opts or {}\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n telescope.find_files {\n prompt_title = prompt_title,\n cwd = opts.dir and tostring(opts.dir) or tostring(Obsidian.dir),\n find_command = self:_build_find_cmd(),\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nTelescopePicker.grep = function(self, opts)\n opts = opts or {}\n\n local cwd = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"path\",\n callback = opts.callback,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n initial_query = opts.query,\n })\n return true\n end\n\n if opts.query and string.len(opts.query) > 0 then\n telescope.grep_string {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n search = opts.query,\n attach_mappings = attach_mappings,\n }\n else\n telescope.live_grep {\n prompt_title = prompt_title,\n cwd = tostring(cwd),\n vimgrep_arguments = self:_build_grep_cmd(),\n attach_mappings = attach_mappings,\n }\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\nTelescopePicker.pick = function(self, values, opts)\n local pickers = require \"telescope.pickers\"\n local finders = require \"telescope.finders\"\n local conf = require \"telescope.config\"\n local make_entry = require \"telescope.make_entry\"\n\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local picker_opts = {\n attach_mappings = function(_, map)\n attach_picker_mappings(map, {\n entry_key = \"value\",\n callback = opts.callback,\n allow_multiple = opts.allow_multiple,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n })\n return true\n end,\n }\n\n local displayer = function(entry)\n return self:_make_display(entry.raw)\n end\n\n local prompt_title = self:_build_prompt {\n prompt_title = opts.prompt_title,\n query_mappings = opts.query_mappings,\n selection_mappings = opts.selection_mappings,\n }\n\n local previewer\n if type(values[1]) == \"table\" then\n previewer = conf.values.grep_previewer(picker_opts)\n -- Get theme to use.\n if conf.pickers then\n for _, picker_name in ipairs { \"grep_string\", \"live_grep\", \"find_files\" } do\n local picker_conf = conf.pickers[picker_name]\n if picker_conf and picker_conf.theme then\n picker_opts =\n vim.tbl_extend(\"force\", picker_opts, require(\"telescope.themes\")[\"get_\" .. picker_conf.theme] {})\n break\n end\n end\n end\n end\n\n local make_entry_from_string = make_entry.gen_from_string(picker_opts)\n\n pickers\n .new(picker_opts, {\n prompt_title = prompt_title,\n finder = finders.new_table {\n results = values,\n entry_maker = function(v)\n if type(v) == \"string\" then\n return make_entry_from_string(v)\n else\n local ordinal = v.ordinal\n if ordinal == nil then\n ordinal = \"\"\n if type(v.display) == \"string\" then\n ordinal = ordinal .. v.display\n end\n if v.filename ~= nil then\n ordinal = ordinal .. \" \" .. v.filename\n end\n end\n\n return {\n value = v.value,\n display = displayer,\n ordinal = ordinal,\n filename = v.filename,\n valid = v.valid,\n lnum = v.lnum,\n col = v.col,\n raw = v,\n }\n end\n end,\n },\n sorter = conf.values.generic_sorter(picker_opts),\n previewer = previewer,\n })\n :find()\nend\n\nreturn TelescopePicker\n"], ["/obsidian.nvim/lua/obsidian/commands/dailies.lua", "local log = require \"obsidian.log\"\nlocal daily = require \"obsidian.daily\"\n\n---@param arg string\n---@return number\nlocal function parse_offset(arg)\n if vim.startswith(arg, \"+\") then\n return assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%'\", arg))\n elseif vim.startswith(arg, \"-\") then\n return -assert(tonumber(string.sub(arg, 2)), string.format(\"invalid offset '%s'\", arg))\n else\n return assert(tonumber(arg), string.format(\"invalid offset '%s'\", arg))\n end\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_start = -5\n local offset_end = 0\n\n if data.fargs and #data.fargs > 0 then\n if #data.fargs == 1 then\n local offset = parse_offset(data.fargs[1])\n if offset >= 0 then\n offset_end = offset\n else\n offset_start = offset\n end\n elseif #data.fargs == 2 then\n local offsets = vim.tbl_map(parse_offset, data.fargs)\n table.sort(offsets)\n offset_start = offsets[1]\n offset_end = offsets[2]\n else\n error \":Obsidian dailies expected at most 2 arguments\"\n end\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type obsidian.PickerEntry[]\n local dailies = {}\n for offset = offset_end, offset_start, -1 do\n local datetime = os.time() + (offset * 3600 * 24)\n local daily_note_path = daily.daily_note_path(datetime)\n local daily_note_alias = tostring(os.date(Obsidian.opts.daily_notes.alias_format or \"%A %B %-d, %Y\", datetime))\n if offset == 0 then\n daily_note_alias = daily_note_alias .. \" @today\"\n elseif offset == -1 then\n daily_note_alias = daily_note_alias .. \" @yesterday\"\n elseif offset == 1 then\n daily_note_alias = daily_note_alias .. \" @tomorrow\"\n end\n if not daily_note_path:is_file() then\n daily_note_alias = daily_note_alias .. \" ➡️ create\"\n end\n dailies[#dailies + 1] = {\n value = offset,\n display = daily_note_alias,\n ordinal = daily_note_alias,\n filename = tostring(daily_note_path),\n }\n end\n\n picker:pick(dailies, {\n prompt_title = \"Dailies\",\n callback = function(offset)\n local note = daily.daily(offset, {})\n note:open()\n end,\n })\nend\n"], ["/obsidian.nvim/lua/obsidian/yaml/parser.lua", "local Line = require \"obsidian.yaml.line\"\nlocal abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\nlocal iter = vim.iter\n\nlocal m = {}\n\n---@class obsidian.yaml.ParserOpts\n---@field luanil boolean\nlocal ParserOpts = {}\n\nm.ParserOpts = ParserOpts\n\n---@return obsidian.yaml.ParserOpts\nParserOpts.default = function()\n return {\n luanil = true,\n }\nend\n\n---@param opts table\n---@return obsidian.yaml.ParserOpts\nParserOpts.normalize = function(opts)\n ---@type obsidian.yaml.ParserOpts\n opts = vim.tbl_extend(\"force\", ParserOpts.default(), opts)\n return opts\nend\n\n---@class obsidian.yaml.Parser : obsidian.ABC\n---@field opts obsidian.yaml.ParserOpts\nlocal Parser = abc.new_class()\n\nm.Parser = Parser\n\n---@enum YamlType\nlocal YamlType = {\n Scalar = \"Scalar\", -- a boolean, string, number, or NULL\n Mapping = \"Mapping\",\n Array = \"Array\",\n ArrayItem = \"ArrayItem\",\n EmptyLine = \"EmptyLine\",\n}\n\nm.YamlType = YamlType\n\n---@class vim.NIL\n\n---Create a new Parser.\n---@param opts obsidian.yaml.ParserOpts|?\n---@return obsidian.yaml.Parser\nm.new = function(opts)\n local self = Parser.init()\n self.opts = ParserOpts.normalize(opts and opts or {})\n return self\nend\n\n---Parse a YAML string.\n---@param str string\n---@return any\nParser.parse = function(self, str)\n -- Collect and pre-process lines.\n local lines = {}\n local base_indent = 0\n for raw_line in str:gmatch \"[^\\r\\n]+\" do\n local ok, result = pcall(Line.new, raw_line, base_indent)\n if ok then\n local line = result\n if #lines == 0 then\n base_indent = line.indent\n line.indent = 0\n end\n table.insert(lines, line)\n else\n local err = result\n error(self:_error_msg(tostring(err), #lines + 1))\n end\n end\n\n -- Now iterate over the root elements, differing to `self:_parse_next()` to recurse into child elements.\n ---@type any\n local root_value = nil\n ---@type table|?\n local parent = nil\n local current_indent = 0\n local i = 1\n while i <= #lines do\n local line = lines[i]\n\n if line:is_empty() then\n -- Empty line, skip it.\n i = i + 1\n elseif line.indent == current_indent then\n local value\n local value_type\n i, value, value_type = self:_parse_next(lines, i)\n assert(value_type ~= YamlType.EmptyLine)\n if root_value == nil and line.indent == 0 then\n -- Set the root value.\n if value_type == YamlType.ArrayItem then\n root_value = { value }\n else\n root_value = value\n end\n\n -- The parent must always be a table (array or mapping), so set that to the root value now\n -- if we have a table.\n if type(root_value) == \"table\" then\n parent = root_value\n end\n elseif util.islist(parent) and value_type == YamlType.ArrayItem then\n -- Add value to parent array.\n parent[#parent + 1] = value\n elseif type(parent) == \"table\" and value_type == YamlType.Mapping then\n assert(parent ~= nil) -- for type checking\n -- Add value to parent mapping.\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if parent[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i, line.content))\n else\n parent[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value\", i, line.content))\n end\n else\n error(self:_error_msg(\"invalid indentation\", i))\n end\n current_indent = line.indent\n end\n\n return root_value\nend\n\n---Parse the next single item, recursing to child blocks if necessary.\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@param text string|?\n---@return integer, any, string\nParser._parse_next = function(self, lines, i, text)\n local line = lines[i]\n if text == nil then\n -- Skip empty lines.\n while line:is_empty() and i <= #lines do\n i = i + 1\n line = lines[i]\n end\n if line:is_empty() then\n return i, nil, YamlType.EmptyLine\n end\n text = util.strip_comments(line.content)\n end\n\n local _, ok, value\n\n -- First just check for a string enclosed in quotes.\n if util.has_enclosing_chars(text) then\n _, _, value = self:_parse_string(i, text)\n return i + 1, value, YamlType.Scalar\n end\n\n -- Check for array item, like `- foo`.\n ok, i, value = self:_try_parse_array_item(lines, i, text)\n if ok then\n return i, value, YamlType.ArrayItem\n end\n\n -- Check for a block string field, like `foo: |`.\n ok, i, value = self:_try_parse_block_string(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Check for any other `key: value` fields.\n ok, i, value = self:_try_parse_field(lines, i, text)\n if ok then\n return i, value, YamlType.Mapping\n end\n\n -- Otherwise we have an inline value.\n local value_type\n value, value_type = self:_parse_inline_value(i, text)\n return i + 1, value, value_type\nend\n\n---@return vim.NIL|nil\nParser._new_null = function(self)\n if self.opts.luanil then\n return nil\n else\n return vim.NIL\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param msg string\n---@param line_num integer\n---@param line_text string|?\n---@return string\n---@diagnostic disable-next-line: unused-local\nParser._error_msg = function(self, msg, line_num, line_text)\n local full_msg = \"[line=\" .. tostring(line_num) .. \"] \" .. msg\n if line_text ~= nil then\n full_msg = full_msg .. \" (text='\" .. line_text .. \"')\"\n end\n return full_msg\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_field = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n\n local _, key, value\n\n -- First look for start of mapping, array, block, etc, e.g. 'foo:'\n _, _, key = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*):$\")\n if not key then\n -- Then try inline field, e.g. 'foo: bar'\n _, _, key, value = string.find(text, \"([a-zA-Z0-9_-]+[a-zA-Z0-9_ -]*): (.*)\")\n end\n\n value = value and vim.trim(value) or nil\n if value == \"\" then\n value = nil\n end\n\n if key ~= nil and value ~= nil then\n -- This is a mapping, e.g. `foo: 1`.\n local out = {}\n value = self:_parse_inline_value(i, value)\n local j = i + 1\n -- Check for multi-line string here.\n local next_line = lines[j]\n if type(value) == \"string\" and next_line ~= nil and next_line.indent > line.indent then\n local next_indent = next_line.indent\n while next_line ~= nil and next_line.indent == next_indent do\n local next_value_str = util.strip_comments(next_line.content)\n if string.len(next_value_str) > 0 then\n local next_value = self:_parse_inline_value(j, next_line.content)\n if type(next_value) ~= \"string\" then\n error(self:_error_msg(\"expected a string, found \" .. type(next_value), j, next_line.content))\n end\n value = value .. \" \" .. next_value\n end\n j = j + 1\n next_line = lines[j]\n end\n end\n out[key] = value\n return true, j, out\n elseif key ~= nil then\n local out = {}\n local next_line = lines[i + 1]\n local j = i + 1\n if next_line ~= nil and next_line.indent >= line.indent and vim.startswith(next_line.content, \"- \") then\n -- This is the start of an array.\n local array\n j, array = self:_parse_array(lines, j)\n out[key] = array\n elseif next_line ~= nil and next_line.indent > line.indent then\n -- This is the start of a mapping.\n local mapping\n j, mapping = self:_parse_mapping(j, lines)\n out[key] = mapping\n else\n -- This is an implicit null field.\n out[key] = self:_new_null()\n end\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_block_string = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n local _, _, block_key = string.find(text, \"([a-zA-Z0-9_-]+):%s?|\")\n if block_key ~= nil then\n local block_lines = {}\n local j = i + 1\n local next_line = lines[j]\n if next_line == nil then\n error(self:_error_msg(\"expected another line\", i, text))\n end\n local item_indent = next_line.indent\n while j <= #lines do\n next_line = lines[j]\n if next_line ~= nil and next_line.indent >= item_indent then\n j = j + 1\n table.insert(block_lines, util.lstrip_whitespace(next_line.raw_content, item_indent))\n else\n break\n end\n end\n local out = {}\n out[block_key] = table.concat(block_lines, \"\\n\")\n return true, j, out\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@param text string|?\n---@return boolean, integer, any\nParser._try_parse_array_item = function(self, lines, i, text)\n local line = lines[i]\n text = text and text or util.strip_comments(line.content)\n if vim.startswith(text, \"- \") then\n local _, _, array_item_str = string.find(text, \"- (.*)\")\n local value\n -- Check for null entry.\n if array_item_str == \"\" then\n value = self:_new_null()\n i = i + 1\n else\n i, value = self:_parse_next(lines, i, array_item_str)\n end\n return true, i, value\n else\n return false, i, nil\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param lines obsidian.yaml.Line[]\n---@param i integer\n---@return integer, any[]\nParser._parse_array = function(self, lines, i)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent and vim.startswith(line.content, \"- \") then\n local is_array_item, value\n is_array_item, i, value = self:_try_parse_array_item(lines, i)\n assert(is_array_item)\n out[#out + 1] = value\n elseif line:is_empty() then\n i = i + 1\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse an array but didn't find any entries\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param lines obsidian.yaml.Line[]\n---@return integer, table\nParser._parse_mapping = function(self, i, lines)\n local out = {}\n local item_indent = lines[i].indent\n while i <= #lines do\n local line = lines[i]\n if line.indent == item_indent then\n local value, value_type\n i, value, value_type = self:_parse_next(lines, i)\n if value_type == YamlType.Mapping then\n for key, item in pairs(value) do\n -- Check for duplicate keys.\n if out[key] ~= nil then\n error(self:_error_msg(\"duplicate key '\" .. key .. \"' found in table\", i))\n else\n out[key] = item\n end\n end\n else\n error(self:_error_msg(\"unexpected value found found in table\", i))\n end\n else\n break\n end\n end\n if vim.tbl_isempty(out) then\n error(self:_error_msg(\"tried to parse a mapping but didn't find any entries to parse\", i))\n end\n return i, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return any, string\nParser._parse_inline_value = function(self, i, text)\n for parse_func_and_type in iter {\n { self._parse_number, YamlType.Scalar },\n { self._parse_null, YamlType.Scalar },\n { self._parse_boolean, YamlType.Scalar },\n { self._parse_inline_array, YamlType.Array },\n { self._parse_inline_mapping, YamlType.Mapping },\n { self._parse_string, YamlType.Scalar },\n } do\n local parse_func, parse_type = unpack(parse_func_and_type)\n local ok, errmsg, res = parse_func(self, i, text)\n if ok then\n return res, parse_type\n elseif errmsg ~= nil then\n error(errmsg)\n end\n end\n -- Should never get here because we always fall back to parsing as a string.\n error(self:_error_msg(\"unable to parse\", i))\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, any[]|?\nParser._parse_inline_array = function(self, i, text)\n local str\n if vim.startswith(text, \"[\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"]\") then\n str = string.sub(str, 1, -2)\n else\n return false, nil, nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n local item_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n item_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n item_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n item_str, str = util.next_item(str, { \",\" }, false)\n end\n if item_str == nil then\n return false, self:_error_msg(\"invalid inline array\", i, text), nil\n end\n out[#out + 1] = self:_parse_inline_value(i, item_str)\n\n if vim.startswith(str, \",\") then\n str = string.sub(str, 2)\n end\n str = util.lstrip_whitespace(str)\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, table|?\nParser._parse_inline_mapping = function(self, i, text)\n local str\n if vim.startswith(text, \"{\") then\n str = string.sub(text, 2)\n else\n return false, nil, nil\n end\n\n if vim.endswith(str, \"}\") then\n str = string.sub(str, 1, -2)\n else\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n\n local out = {}\n while string.len(str) > 0 do\n -- Parse the key.\n local key_str\n key_str, str = util.next_item(str, { \":\" }, false)\n if key_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local _, _, key = self:_parse_string(i, key_str)\n\n -- Parse the value.\n str = util.lstrip_whitespace(str)\n local value_str\n if vim.startswith(str, \"[\") then\n -- Nested inline array.\n value_str, str = util.next_item(str, { \"]\" }, true)\n elseif vim.startswith(str, \"{\") then\n -- Nested inline mapping.\n value_str, str = util.next_item(str, { \"}\" }, true)\n else\n -- Regular item.\n value_str, str = util.next_item(str, { \",\" }, false)\n end\n if value_str == nil then\n return false, self:_error_msg(\"invalid inline mapping\", i, text), nil\n end\n local value = self:_parse_inline_value(i, value_str)\n if out[key] == nil then\n out[key] = value\n else\n return false, self:_error_msg(\"duplicate key '\" .. key .. \"' found in inline mapping\", i, text), nil\n end\n\n if vim.startswith(str, \",\") then\n str = util.lstrip_whitespace(string.sub(str, 2))\n end\n end\n\n return true, nil, out\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, string\n---@diagnostic disable-next-line: unused-local\nParser._parse_string = function(self, i, text)\n if vim.startswith(text, [[\"]]) and vim.endswith(text, [[\"]]) then\n -- when the text is enclosed with double-quotes we need to un-escape certain characters.\n text = string.gsub(text, vim.pesc [[\\\"]], [[\"]])\n end\n return true, nil, util.strip_enclosing_chars(vim.trim(text))\nend\n\n---Parse a string value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return string\nParser.parse_string = function(self, text)\n local _, _, str = self:_parse_string(1, util.strip_comments(text))\n return str\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, number|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_number = function(self, i, text)\n local out = tonumber(text)\n if out == nil or util.isNan(out) then\n return false, nil, nil\n else\n return true, nil, out\n end\nend\n\n---Parse a number value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return number\nParser.parse_number = function(self, text)\n local ok, errmsg, res = self:_parse_number(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a number\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param i integer\n---@param text string\n---@return boolean, string|?, boolean|?\n---@diagnostic disable-next-line: unused-local\nParser._parse_boolean = function(self, i, text)\n if text == \"true\" then\n return true, nil, true\n elseif text == \"false\" then\n return true, nil, false\n else\n return false, nil, nil\n end\nend\n\n---Parse a boolean value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean\nParser.parse_boolean = function(self, text)\n local ok, errmsg, res = self:_parse_boolean(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a boolean\", 1, text)\n error(errmsg)\n else\n assert(res ~= nil)\n return res\n end\nend\n\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return boolean, string|?, vim.NIL|nil\n---@diagnostic disable-next-line: unused-local\nParser._parse_null = function(self, i, text)\n if text == \"null\" or text == \"\" then\n return true, nil, self:_new_null()\n else\n return false, nil, nil\n end\nend\n\n---Parse a NULL value.\n---@param self obsidian.yaml.Parser\n---@param text string\n---@return vim.NIL|nil\nParser.parse_null = function(self, text)\n local ok, errmsg, res = self:_parse_null(1, vim.trim(util.strip_comments(text)))\n if not ok then\n errmsg = errmsg and errmsg or self:_error_msg(\"failed to parse a null value\", 1, text)\n error(errmsg)\n else\n return res\n end\nend\n\n---Deserialize a YAML string.\nm.loads = function(str)\n local parser = m.new()\n return parser:parse(str)\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/commands/open.lua", "local api = require \"obsidian.api\"\nlocal Path = require \"obsidian.path\"\nlocal search = require \"obsidian.search\"\nlocal log = require \"obsidian.log\"\n\n---@param path? string|obsidian.Path\nlocal function open_in_app(path)\n local vault_name = vim.fs.basename(tostring(Obsidian.workspace.root))\n if not path then\n return Obsidian.opts.open.func(\"obsidian://open?vault=\" .. vim.uri_encode(vault_name))\n end\n path = tostring(path)\n local this_os = api.get_os()\n\n -- Normalize path for windows.\n if this_os == api.OSType.Windows then\n path = string.gsub(path, \"/\", \"\\\\\")\n end\n\n local encoded_vault = vim.uri_encode(vault_name)\n local encoded_path = vim.uri_encode(path)\n\n local uri\n if Obsidian.opts.open.use_advanced_uri then\n local line = vim.api.nvim_win_get_cursor(0)[1] or 1\n uri = (\"obsidian://advanced-uri?vault=%s&filepath=%s&line=%i\"):format(encoded_vault, encoded_path, line)\n else\n uri = (\"obsidian://open?vault=%s&file=%s\"):format(encoded_vault, encoded_path)\n end\n print(uri)\n\n Obsidian.opts.open.func(uri)\nend\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type string|?\n local search_term\n\n if data.args and data.args:len() > 0 then\n search_term = data.args\n else\n -- Check for a note reference under the cursor.\n local link_string, _ = api.cursor_link()\n search_term = link_string\n end\n\n if search_term then\n search.resolve_link_async(search_term, function(results)\n if vim.tbl_isempty(results) then\n return log.err \"Note under cusros is not resolved\"\n end\n vim.schedule(function()\n open_in_app(results[1].path)\n end)\n end)\n else\n -- Otherwise use the path of the current buffer.\n local bufname = vim.api.nvim_buf_get_name(0)\n local path = Path.new(bufname):vault_relative_path()\n open_in_app(path)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/blink.lua", "local util = require \"obsidian.util\"\nlocal obsidian = require \"obsidian\"\n\nlocal M = {}\n\nM.injected_once = false\n\nM.providers = {\n { name = \"obsidian\", module = \"obsidian.completion.sources.blink.refs\" },\n { name = \"obsidian_tags\", module = \"obsidian.completion.sources.blink.tags\" },\n}\n\nlocal function add_provider(blink, provider_name, proivder_module)\n local add_source_provider = blink.add_source_provider or blink.add_provider\n add_source_provider(provider_name, {\n name = provider_name,\n module = proivder_module,\n async = true,\n opts = {},\n enabled = function()\n -- Enable only in markdown buffers.\n return vim.tbl_contains({ \"markdown\" }, vim.bo.filetype)\n and vim.bo.buftype ~= \"prompt\"\n and vim.b.completion ~= false\n end,\n })\nend\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_providers(opts)\n local blink = require \"blink.cmp\"\n\n if opts.completion.create_new then\n table.insert(M.providers, { name = \"obsidian_new\", module = \"obsidian.completion.sources.blink.new\" })\n end\n\n for _, provider in pairs(M.providers) do\n add_provider(blink, provider.name, provider.module)\n end\nend\n\nlocal function add_element_to_list_if_not_exists(list, element)\n if not vim.tbl_contains(list, element) then\n table.insert(list, 1, element)\n end\nend\n\nlocal function should_return_if_not_in_workspace()\n local current_file_path = vim.api.nvim_buf_get_name(0)\n local buf_dir = vim.fs.dirname(current_file_path)\n\n local workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\n if not workspace then\n return true\n else\n return false\n end\nend\n\nlocal function log_unexpected_type(config_path, unexpected_type, expected_type)\n vim.notify(\n \"blink.cmp's `\"\n .. config_path\n .. \"` configuration appears to be an '\"\n .. unexpected_type\n .. \"' type, but it \"\n .. \"should be '\"\n .. expected_type\n .. \"'. Obsidian won't update this configuration, and \"\n .. \"completion won't work with blink.cmp\",\n vim.log.levels.ERROR\n )\nend\n\n---Attempts to inject the Obsidian sources into per_filetype if that's what the user seems to use for markdown\n---@param blink_sources_per_filetype table\n---@return boolean true if it obsidian sources were injected into the sources.per_filetype\nlocal function try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype)\n -- If the per_filetype is an empty object, then it's probably not utilized by the user\n if vim.deep_equal(blink_sources_per_filetype, {}) then\n return false\n end\n\n local markdown_config = blink_sources_per_filetype[\"markdown\"]\n\n -- If the markdown key is not used, then per_filetype it's probably not utilized by the user\n if markdown_config == nil then\n return false\n end\n\n local markdown_config_type = type(markdown_config)\n if markdown_config_type == \"table\" and util.islist(markdown_config) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(markdown_config, provider.name)\n end\n return true\n elseif markdown_config_type == \"function\" then\n local original_func = markdown_config\n markdown_config = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.per_filetype[\"markdown\"] = markdown_config\n return true\n else\n log_unexpected_type(\n \".sources.per_filetype['markdown']\",\n markdown_config_type,\n \"a list or a function that returns a list of sources\"\n )\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n---Attempts to inject the Obsidian sources into default if that's what the user seems to use for markdown\n---@param blink_sources_default (fun():string[])|(string[])\n---@return boolean true if it obsidian sources were injected into the sources.default\nlocal function try_inject_blink_sources_into_default(blink_sources_default)\n local blink_default_type = type(blink_sources_default)\n if blink_default_type == \"function\" then\n local original_func = blink_sources_default\n blink_sources_default = function()\n local original_results = original_func()\n\n if should_return_if_not_in_workspace() then\n return original_results\n end\n\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(original_results, provider.name)\n end\n return original_results\n end\n\n -- Overwrite the original config function with the newly generated one\n require(\"blink.cmp.config\").sources.default = blink_sources_default\n return true\n elseif blink_default_type == \"table\" and util.islist(blink_sources_default) then\n for _, provider in pairs(M.providers) do\n add_element_to_list_if_not_exists(blink_sources_default, provider.name)\n end\n\n return true\n elseif blink_default_type == \"table\" then\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n else\n log_unexpected_type(\".sources.default\", blink_default_type, \"a list or a function that returns a list\")\n return true -- logged the error, returns as if this was successful to avoid further errors\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace. nvm_cmp had the capability to configure the sources\n-- per buffer, but blink.cmp doesn't have that capability. Instead, we have to inject the sources into the global\n-- configuration and set a boolean on the module to return early the next time this function is called.\n--\n-- In-case the user used functions to configure their sources, the completion will properly work just for the markdown\n-- files that are in a workspace. Otherwise, the completion will work for all markdown files.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n if M.injected_once then\n return\n end\n\n M.injected_once = true\n\n local blink_config = require \"blink.cmp.config\"\n -- 'per_filetype' sources has priority over 'default' sources.\n -- 'per_filetype' can be a table or a function which returns a table ([\"filetype\"] = { \"a\", \"b\" })\n -- 'per_filetype' has the default value of {} (even if it's not configured by the user)\n local blink_sources_per_filetype = blink_config.sources.per_filetype\n if try_inject_blink_sources_into_per_filetype(blink_sources_per_filetype) then\n return\n end\n\n -- 'default' can be a list/array or a function which returns a list/array ({ \"a\", \"b\"})\n local blink_sources_default = blink_config.sources[\"default\"]\n if try_inject_blink_sources_into_default(blink_sources_default) then\n return\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/yaml/init.lua", "local util = require \"obsidian.util\"\nlocal parser = require \"obsidian.yaml.parser\"\n\nlocal yaml = {}\n\n---Deserialize a YAML string.\n---@param str string\n---@return any\nyaml.loads = function(str)\n return parser.loads(str)\nend\n\n---@param s string\n---@return boolean\nlocal should_quote = function(s)\n -- TODO: this probably doesn't cover all edge cases.\n -- See https://www.yaml.info/learn/quote.html\n -- Check if it starts with a special character.\n if string.match(s, [[^[\"'\\\\[{&!-].*]]) then\n return true\n -- Check if it has a colon followed by whitespace.\n elseif string.find(s, \": \", 1, true) then\n return true\n -- Check if it's an empty string.\n elseif s == \"\" or string.match(s, \"^[%s]+$\") then\n return true\n else\n return false\n end\nend\n\n---@return string[]\nlocal dumps\ndumps = function(x, indent, order)\n local indent_str = string.rep(\" \", indent)\n\n if type(x) == \"string\" then\n if should_quote(x) then\n x = string.gsub(x, '\"', '\\\\\"')\n return { indent_str .. [[\"]] .. x .. [[\"]] }\n else\n return { indent_str .. x }\n end\n end\n\n if type(x) == \"boolean\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"number\" then\n return { indent_str .. tostring(x) }\n end\n\n if type(x) == \"table\" then\n local out = {}\n\n if util.islist(x) then\n for _, v in ipairs(x) do\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. \"- \" .. util.lstrip_whitespace(item_lines[1]))\n for i = 2, #item_lines do\n table.insert(out, item_lines[i])\n end\n end\n else\n -- Gather and sort keys so we can keep the order deterministic.\n local keys = {}\n for k, _ in pairs(x) do\n table.insert(keys, k)\n end\n table.sort(keys, order)\n for _, k in ipairs(keys) do\n local v = x[k]\n if type(v) == \"string\" or type(v) == \"boolean\" or type(v) == \"number\" then\n table.insert(out, indent_str .. tostring(k) .. \": \" .. dumps(v, 0)[1])\n elseif type(v) == \"table\" and vim.tbl_isempty(v) then\n table.insert(out, indent_str .. tostring(k) .. \": []\")\n else\n local item_lines = dumps(v, indent + 2)\n table.insert(out, indent_str .. tostring(k) .. \":\")\n for _, line in ipairs(item_lines) do\n table.insert(out, line)\n end\n end\n end\n end\n\n return out\n end\n\n error(\"Can't convert object with type \" .. type(x) .. \" to YAML\")\nend\n\n---Dump an object to YAML lines.\n---@param x any\n---@param order function\n---@return string[]\nyaml.dumps_lines = function(x, order)\n return dumps(x, 0, order)\nend\n\n---Dump an object to a YAML string.\n---@param x any\n---@param order function|?\n---@return string\nyaml.dumps = function(x, order)\n return table.concat(dumps(x, 0, order), \"\\n\")\nend\n\nreturn yaml\n"], ["/obsidian.nvim/lua/obsidian/img_paste.lua", "local Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal run_job = require(\"obsidian.async\").run_job\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\n\nlocal M = {}\n\n-- Image pasting adapted from https://github.com/ekickx/clipboard-image.nvim\n\n---@return string\nlocal function get_clip_check_command()\n local check_cmd\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n check_cmd = \"xclip -selection clipboard -o -t TARGETS\"\n elseif display_server == \"wayland\" then\n check_cmd = \"wl-paste --list-types\"\n end\n elseif this_os == api.OSType.Darwin then\n check_cmd = \"pngpaste -b 2>&1\"\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n check_cmd = 'powershell.exe \"Get-Clipboard -Format Image\"'\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return check_cmd\nend\n\n--- Check if clipboard contains image data.\n---\n---@return boolean\nfunction M.clipboard_is_img()\n local check_cmd = get_clip_check_command()\n local result_string = vim.fn.system(check_cmd)\n local content = vim.split(result_string, \"\\n\")\n\n local is_img = false\n -- See: [Data URI scheme](https://en.wikipedia.org/wiki/Data_URI_scheme)\n local this_os = api.get_os()\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n if vim.tbl_contains(content, \"image/png\") then\n is_img = true\n elseif vim.tbl_contains(content, \"text/uri-list\") then\n local success =\n os.execute \"wl-paste --type text/uri-list | sed 's|file://||' | head -n1 | tr -d '[:space:]' | xargs -I{} sh -c 'wl-copy < \\\"$1\\\"' _ {}\"\n is_img = success == 0\n end\n elseif this_os == api.OSType.Darwin then\n is_img = string.sub(content[1], 1, 9) == \"iVBORw0KG\" -- Magic png number in base64\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n is_img = content ~= nil\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\n return is_img\nend\n\n--- TODO: refactor with run_job?\n\n--- Save image from clipboard to `path`.\n---@param path string\n---\n---@return boolean|integer|? result\nlocal function save_clipboard_image(path)\n local this_os = api.get_os()\n\n if this_os == api.OSType.Linux or this_os == api.OSType.FreeBSD then\n local cmd\n local display_server = os.getenv \"XDG_SESSION_TYPE\"\n if display_server == \"x11\" or display_server == \"tty\" then\n cmd = string.format(\"xclip -selection clipboard -t image/png -o > '%s'\", path)\n elseif display_server == \"wayland\" then\n cmd = string.format(\"wl-paste --no-newline --type image/png > %s\", vim.fn.shellescape(path))\n return run_job { \"bash\", \"-c\", cmd }\n end\n\n local result = os.execute(cmd)\n if type(result) == \"number\" and result > 0 then\n return false\n else\n return result\n end\n elseif this_os == api.OSType.Windows or this_os == api.OSType.Wsl then\n local cmd = 'powershell.exe -c \"'\n .. string.format(\"(get-clipboard -format image).save('%s', 'png')\", string.gsub(path, \"/\", \"\\\\\"))\n .. '\"'\n return os.execute(cmd)\n elseif this_os == api.OSType.Darwin then\n return run_job { \"pngpaste\", path }\n else\n error(\"image saving not implemented for OS '\" .. this_os .. \"'\")\n end\nend\n\n--- @param path string image_path The absolute path to the image file.\nM.paste = function(path)\n if util.contains_invalid_characters(path) then\n log.warn \"Links will not work with file names containing any of these characters in Obsidian: # ^ [ ] |\"\n end\n\n ---@diagnostic disable-next-line: cast-local-type\n path = Path.new(path)\n\n -- Make sure fname ends with \".png\"\n if not path.suffix then\n ---@diagnostic disable-next-line: cast-local-type\n path = path:with_suffix \".png\"\n elseif path.suffix ~= \".png\" then\n return log.err(\"invalid suffix for image name '%s', must be '.png'\", path.suffix)\n end\n\n if Obsidian.opts.attachments.confirm_img_paste then\n -- Get confirmation from user.\n if not api.confirm(\"Saving image to '\" .. tostring(path) .. \"'. Do you want to continue?\") then\n return log.warn \"Paste aborted\"\n end\n end\n\n -- Ensure parent directory exists.\n assert(path:parent()):mkdir { exist_ok = true, parents = true }\n\n -- Paste image.\n local result = save_clipboard_image(tostring(path))\n if result == false then\n log.err \"Failed to save image\"\n return\n end\n\n local img_text = Obsidian.opts.attachments.img_text_func(path)\n vim.api.nvim_put({ img_text }, \"c\", true, false)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/link.lua", "local search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n ---@type string\n local search_term\n if data.args ~= nil and string.len(data.args) > 0 then\n search_term = data.args\n else\n search_term = viz.selection\n end\n\n ---@param note obsidian.Note\n local function insert_ref(note)\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = viz.selection })\n .. string.sub(line, viz.cecol + 1)\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\n require(\"obsidian.ui\").update(0)\n end\n\n search.resolve_note_async(search_term, function(note)\n vim.schedule(function()\n insert_ref(note)\n end)\n end, { prompt_title = \"Select note to link\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/toc.lua", "local util = require \"obsidian.util\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local note = assert(api.current_note(0, { collect_anchor_links = true }))\n\n ---@type obsidian.PickerEntry[]\n local picker_entries = {}\n for _, anchor in pairs(note.anchor_links) do\n local display = string.rep(\"#\", anchor.level) .. \" \" .. anchor.header\n table.insert(\n picker_entries,\n { value = display, display = display, filename = tostring(note.path), lnum = anchor.line }\n )\n end\n\n -- De-duplicate and sort.\n picker_entries = util.tbl_unique(picker_entries)\n table.sort(picker_entries, function(a, b)\n return a.lnum < b.lnum\n end)\n\n local picker = assert(Obsidian.picker)\n picker:pick(picker_entries, { prompt_title = \"Table of Contents\" })\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/links.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\nlocal api = require \"obsidian.api\"\n\nreturn function()\n local picker = Obsidian.picker\n if not picker then\n return log.err \"No picker configured\"\n end\n\n local note = api.current_note(0)\n assert(note, \"not in a note\")\n\n search.find_links(note, {}, function(entries)\n entries = vim.tbl_map(function(match)\n return match.link\n end, entries)\n\n -- Launch picker.\n picker:pick(entries, {\n prompt_title = \"Links\",\n callback = function(link)\n api.follow_link(link)\n end,\n })\n end)\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/check.lua", "local Note = require \"obsidian.note\"\nlocal Path = require \"obsidian.path\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal iter = vim.iter\n\nreturn function()\n local start_time = vim.uv.hrtime()\n local count = 0\n local errors = {}\n local warnings = {}\n\n for path in api.dir(Obsidian.dir) do\n local relative_path = Path.new(path):vault_relative_path { strict = true }\n local ok, res = pcall(Note.from_file, path)\n\n if not ok then\n errors[#errors + 1] = string.format(\"Failed to parse note '%s': \", relative_path, res)\n elseif res.has_frontmatter == false then\n warnings[#warnings + 1] = string.format(\"'%s' missing frontmatter\", relative_path)\n end\n count = count + 1\n end\n\n local runtime = math.floor((vim.uv.hrtime() - start_time) / 1000000)\n local messages = { \"Checked \" .. tostring(count) .. \" notes in \" .. runtime .. \"ms\" }\n local log_level = vim.log.levels.INFO\n\n if #warnings > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#warnings) .. \" warning(s):\"\n log_level = vim.log.levels.WARN\n for warning in iter(warnings) do\n messages[#messages + 1] = \"  \" .. warning\n end\n end\n\n if #errors > 0 then\n messages[#messages + 1] = \"\\nThere were \" .. tostring(#errors) .. \" error(s):\"\n for err in iter(errors) do\n messages[#messages + 1] = \"  \" .. err\n end\n log_level = vim.log.levels.ERROR\n end\n\n log.log(table.concat(messages, \"\\n\"), log_level)\nend\n"], ["/obsidian.nvim/lua/obsidian/pickers/_mini.lua", "local mini_pick = require \"mini.pick\"\n\nlocal Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal Picker = require \"obsidian.pickers.picker\"\n\n---@param entry string\n---@return string\nlocal function clean_path(entry)\n local path_end = assert(string.find(entry, \":\", 1, true))\n return string.sub(entry, 1, path_end - 1)\nend\n\n---@class obsidian.pickers.MiniPicker : obsidian.Picker\nlocal MiniPicker = abc.new_class({\n ---@diagnostic disable-next-line: unused-local\n __tostring = function(self)\n return \"MiniPicker()\"\n end,\n}, Picker)\n\n---@param opts obsidian.PickerFindOpts|? Options.\nMiniPicker.find_files = function(self, opts)\n opts = opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local path = mini_pick.builtin.cli({\n command = self:_build_find_cmd(),\n }, {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n })\n\n if path and opts.callback then\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param opts obsidian.PickerGrepOpts|? Options.\nMiniPicker.grep = function(self, opts)\n opts = opts and opts or {}\n\n ---@type obsidian.Path\n local dir = opts.dir and Path:new(opts.dir) or Obsidian.dir\n\n local pick_opts = {\n source = {\n name = opts.prompt_title,\n cwd = tostring(dir),\n choose = function(path)\n if not opts.no_default_mappings then\n mini_pick.default_choose(path)\n end\n end,\n },\n }\n\n ---@type string|?\n local result\n if opts.query and string.len(opts.query) > 0 then\n result = mini_pick.builtin.grep({ pattern = opts.query }, pick_opts)\n else\n result = mini_pick.builtin.grep_live({}, pick_opts)\n end\n\n if result and opts.callback then\n local path = clean_path(result)\n opts.callback(tostring(dir / path))\n end\nend\n\n---@param values string[]|obsidian.PickerEntry[]\n---@param opts obsidian.PickerPickOpts|? Options.\n---@diagnostic disable-next-line: unused-local\nMiniPicker.pick = function(self, values, opts)\n self.calling_bufnr = vim.api.nvim_get_current_buf()\n\n opts = opts and opts or {}\n\n local entries = {}\n for _, value in ipairs(values) do\n if type(value) == \"string\" then\n entries[#entries + 1] = value\n elseif value.valid ~= false then\n entries[#entries + 1] = {\n value = value.value,\n text = self:_make_display(value),\n path = value.filename,\n lnum = value.lnum,\n col = value.col,\n }\n end\n end\n\n local entry = mini_pick.start {\n source = {\n name = opts.prompt_title,\n items = entries,\n choose = function() end,\n },\n }\n\n if entry and opts.callback then\n if type(entry) == \"string\" then\n opts.callback(entry)\n else\n opts.callback(entry.value)\n end\n end\nend\n\nreturn MiniPicker\n"], ["/obsidian.nvim/lua/obsidian/daily/init.lua", "local Path = require \"obsidian.path\"\nlocal Note = require \"obsidian.note\"\nlocal util = require \"obsidian.util\"\n\n--- Get the path to a daily note.\n---\n---@param datetime integer|?\n---\n---@return obsidian.Path, string (Path, ID) The path and ID of the note.\nlocal daily_note_path = function(datetime)\n datetime = datetime and datetime or os.time()\n\n ---@type obsidian.Path\n local path = Path:new(Obsidian.dir)\n\n local options = Obsidian.opts\n\n if options.daily_notes.folder ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.daily_notes.folder\n elseif options.notes_subdir ~= nil then\n ---@type obsidian.Path\n ---@diagnostic disable-next-line: assign-type-mismatch\n path = path / options.notes_subdir\n end\n\n local id\n if options.daily_notes.date_format ~= nil then\n id = tostring(os.date(options.daily_notes.date_format, datetime))\n else\n id = tostring(os.date(\"%Y-%m-%d\", datetime))\n end\n\n path = path / (id .. \".md\")\n\n -- ID may contain additional path components, so make sure we use the stem.\n id = path.stem\n\n return path, id\nend\n\n--- Open (or create) the daily note.\n---\n---@param datetime integer\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\n---\nlocal _daily = function(datetime, opts)\n opts = opts or {}\n\n local path, id = daily_note_path(datetime)\n\n local options = Obsidian.opts\n\n ---@type string|?\n local alias\n if options.daily_notes.alias_format ~= nil then\n alias = tostring(os.date(options.daily_notes.alias_format, datetime))\n end\n\n ---@type obsidian.Note\n local note\n if path:exists() then\n note = Note.from_file(path, opts.load)\n else\n note = Note.create {\n id = id,\n aliases = {},\n tags = options.daily_notes.default_tags or {},\n dir = path:parent(),\n }\n\n if alias then\n note:add_alias(alias)\n note.title = alias\n end\n\n if not opts.no_write then\n note:write { template = options.daily_notes.template }\n end\n end\n\n return note\nend\n\n--- Open (or create) the daily note for today.\n---\n---@return obsidian.Note\nlocal today = function()\n return _daily(os.time(), {})\nend\n\n--- Open (or create) the daily note from the last day.\n---\n---@return obsidian.Note\nlocal yesterday = function()\n local now = os.time()\n local yesterday\n\n if Obsidian.opts.daily_notes.workdays_only then\n yesterday = util.working_day_before(now)\n else\n yesterday = util.previous_day(now)\n end\n\n return _daily(yesterday, {})\nend\n\n--- Open (or create) the daily note for the next day.\n---\n---@return obsidian.Note\nlocal tomorrow = function()\n local now = os.time()\n local tomorrow\n\n if Obsidian.opts.daily_notes.workdays_only then\n tomorrow = util.working_day_after(now)\n else\n tomorrow = util.next_day(now)\n end\n\n return _daily(tomorrow, {})\nend\n\n--- Open (or create) the daily note for today + `offset_days`.\n---\n---@param offset_days integer|?\n---@param opts { no_write: boolean|?, load: obsidian.note.LoadOpts|? }|?\n---\n---@return obsidian.Note\nlocal daily = function(offset_days, opts)\n return _daily(os.time() + (offset_days * 3600 * 24), opts)\nend\n\nreturn {\n daily_note_path = daily_note_path,\n daily = daily,\n tomorrow = tomorrow,\n yesterday = yesterday,\n today = today,\n}\n"], ["/obsidian.nvim/lua/obsidian/abc.lua", "local M = {}\n\n---@class obsidian.ABC\n---@field init function an init function which essentially calls 'setmetatable({}, mt)'.\n---@field as_tbl function get a raw table with only the instance's fields\n---@field mt table the metatable\n\n---Create a new class.\n---\n---This handles the boilerplate of setting up metatables correctly and consistently when defining new classes,\n---and comes with some better default metamethods, like '.__eq' which will recursively compare all fields\n---that don't start with a double underscore.\n---\n---When you use this you should call `.init()` within your constructors instead of `setmetatable()`.\n---For example:\n---\n---```lua\n--- local Foo = new_class()\n---\n--- Foo.new = function(x)\n--- local self = Foo.init()\n--- self.x = x\n--- return self\n--- end\n---```\n---\n---The metatable for classes created this way is accessed with the field `.mt`. This way you can easily\n---add/override metamethods to your classes. Continuing the example above:\n---\n---```lua\n--- Foo.mt.__tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end\n---\n--- local foo = Foo.new(1)\n--- print(foo)\n---```\n---\n---Alternatively you can pass metamethods directly to 'new_class()'. For example:\n---\n---```lua\n--- local Foo = new_class {\n--- __tostring = function(self)\n--- return string.format(\"Foo(%d)\", self.x)\n--- end,\n--- }\n---```\n---\n---@param metamethods table|? {string, function} - Metamethods\n---@param base_class table|? A base class to start from\n---@return obsidian.ABC\nM.new_class = function(metamethods, base_class)\n local class = base_class and base_class or {}\n\n -- Metatable for the class so that all instances have the same metatable.\n class.mt = vim.tbl_extend(\"force\", {\n __index = class,\n __eq = function(a, b)\n -- In order to use 'vim.deep_equal' we need to pull out the raw fields first.\n -- If we passed 'a' and 'b' directly to 'vim.deep_equal' we'd get a stack overflow due\n -- to infinite recursion, since 'vim.deep_equal' calls the '.__eq' metamethod.\n local a_fields = a:as_tbl()\n local b_fields = b:as_tbl()\n return vim.deep_equal(a_fields, b_fields)\n end,\n }, metamethods and metamethods or {})\n\n class.init = function(t)\n local self = setmetatable(t and t or {}, class.mt)\n return self\n end\n\n class.as_tbl = function(self)\n local fields = {}\n for k, v in pairs(self) do\n if not vim.startswith(k, \"__\") then\n fields[k] = v\n end\n end\n return fields\n end\n\n return class\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/workspace.lua", "local Path = require \"obsidian.path\"\nlocal abc = require \"obsidian.abc\"\nlocal api = require \"obsidian.api\"\nlocal util = require \"obsidian.util\"\nlocal config = require \"obsidian.config\"\nlocal log = require \"obsidian.log\"\n\n---@class obsidian.workspace.WorkspaceSpec\n---\n---@field path string|(fun(): string)\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts?\n\n---@class obsidian.workspace.WorkspaceOpts\n---\n---@field name string|?\n---@field strict boolean|? If true, the workspace root will be fixed to 'path' instead of the vault root (if different).\n---@field overrides table|obsidian.config.ClientOpts|?\n\n--- Each workspace represents a working directory (usually an Obsidian vault) along with\n--- a set of configuration options specific to the workspace.\n---\n--- Workspaces are a little more general than Obsidian vaults as you can have a workspace\n--- outside of a vault or as a subdirectory of a vault.\n---\n---@toc_entry obsidian.Workspace\n---\n---@class obsidian.Workspace : obsidian.ABC\n---\n---@field name string An arbitrary name for the workspace.\n---@field path obsidian.Path The normalized path to the workspace.\n---@field root obsidian.Path The normalized path to the vault root of the workspace. This usually matches 'path'.\n---@field overrides table|obsidian.config.ClientOpts|?\n---@field locked boolean|?\nlocal Workspace = abc.new_class {\n __tostring = function(self)\n return string.format(\"Workspace(name='%s', path='%s', root='%s')\", self.name, self.path, self.root)\n end,\n __eq = function(a, b)\n local a_fields = a:as_tbl()\n a_fields.locked = nil\n local b_fields = b:as_tbl()\n b_fields.locked = nil\n return vim.deep_equal(a_fields, b_fields)\n end,\n}\n\n--- Find the vault root from a given directory.\n---\n--- This will traverse the directory tree upwards until a '.obsidian/' folder is found to\n--- indicate the root of a vault, otherwise the given directory is used as-is.\n---\n---@param base_dir string|obsidian.Path\n---\n---@return obsidian.Path|?\nlocal function find_vault_root(base_dir)\n local vault_indicator_folder = \".obsidian\"\n base_dir = Path.new(base_dir)\n local dirs = Path.new(base_dir):parents()\n table.insert(dirs, 1, base_dir)\n\n for _, dir in ipairs(dirs) do\n local maybe_vault = dir / vault_indicator_folder\n if maybe_vault:is_dir() then\n return dir\n end\n end\n\n return nil\nend\n\n--- Create a new 'Workspace' object. This assumes the workspace already exists on the filesystem.\n---\n---@param path string|obsidian.Path Workspace path.\n---@param opts obsidian.workspace.WorkspaceOpts|?\n---\n---@return obsidian.Workspace\nWorkspace.new = function(path, opts)\n opts = opts and opts or {}\n\n local self = Workspace.init()\n self.path = Path.new(path):resolve { strict = true }\n self.name = assert(opts.name or self.path.name)\n self.overrides = opts.overrides\n\n if opts.strict then\n self.root = self.path\n else\n local vault_root = find_vault_root(self.path)\n if vault_root then\n self.root = vault_root\n else\n self.root = self.path\n end\n end\n\n return self\nend\n\n--- Initialize a new 'Workspace' object from a workspace spec.\n---\n---@param spec obsidian.workspace.WorkspaceSpec\n---\n---@return obsidian.Workspace\nWorkspace.new_from_spec = function(spec)\n ---@type string|obsidian.Path\n local path\n if type(spec.path) == \"function\" then\n path = spec.path()\n else\n ---@diagnostic disable-next-line: cast-local-type\n path = spec.path\n end\n\n ---@diagnostic disable-next-line: param-type-mismatch\n return Workspace.new(path, {\n name = spec.name,\n strict = spec.strict,\n overrides = spec.overrides,\n })\nend\n\n--- Lock the workspace.\nWorkspace.lock = function(self)\n self.locked = true\nend\n\n--- Unlock the workspace.\nWorkspace._unlock = function(self)\n self.locked = false\nend\n\n--- Get the workspace corresponding to the directory (or a parent of), if there\n--- is one.\n---\n---@param cur_dir string|obsidian.Path\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_dir = function(cur_dir, workspaces)\n local ok\n ok, cur_dir = pcall(function()\n return Path.new(cur_dir):resolve { strict = true }\n end)\n\n if not ok then\n return\n end\n\n for _, spec in ipairs(workspaces) do\n local w = Workspace.new_from_spec(spec)\n if w.path == cur_dir or w.path:is_parent_of(cur_dir) then\n return w\n end\n end\nend\n\n--- Get the workspace corresponding to the current working directory (or a parent of), if there\n--- is one.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|?\nWorkspace.get_workspace_for_cwd = function(workspaces)\n local cwd = assert(vim.fn.getcwd())\n return Workspace.get_workspace_for_dir(cwd, workspaces)\nend\n\n--- Returns the default workspace.\n---\n---@param workspaces obsidian.workspace.WorkspaceSpec[]\n---\n---@return obsidian.Workspace|nil\nWorkspace.get_default_workspace = function(workspaces)\n if not vim.tbl_isempty(workspaces) then\n return Workspace.new_from_spec(workspaces[1])\n else\n return nil\n end\nend\n\n--- Resolves current workspace from the client config.\n---\n---@param opts obsidian.config.ClientOpts\n---\n---@return obsidian.Workspace|?\nWorkspace.get_from_opts = function(opts)\n local current_workspace = Workspace.get_workspace_for_cwd(opts.workspaces)\n\n if not current_workspace then\n current_workspace = Workspace.get_default_workspace(opts.workspaces)\n end\n\n return current_workspace\nend\n\n--- Get the normalize opts for a given workspace.\n---\n---@param workspace obsidian.Workspace|?\n---\n---@return obsidian.config.ClientOpts\nWorkspace.normalize_opts = function(workspace)\n if workspace then\n return config.normalize(workspace.overrides and workspace.overrides or {}, Obsidian._opts)\n else\n return Obsidian.opts\n end\nend\n\n---@param workspace obsidian.Workspace\n---@param opts { lock: boolean|? }|?\nWorkspace.set = function(workspace, opts)\n opts = opts and opts or {}\n\n local dir = workspace.root\n local options = Workspace.normalize_opts(workspace) -- TODO: test\n\n Obsidian.workspace = workspace\n Obsidian.dir = dir\n Obsidian.opts = options\n\n -- Ensure directories exist.\n dir:mkdir { parents = true, exists_ok = true }\n\n if options.notes_subdir ~= nil then\n local notes_subdir = dir / Obsidian.opts.notes_subdir\n notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n if Obsidian.opts.daily_notes.folder ~= nil then\n local daily_notes_subdir = Obsidian.dir / Obsidian.opts.daily_notes.folder\n daily_notes_subdir:mkdir { parents = true, exists_ok = true }\n end\n\n -- Setup UI add-ons.\n local has_no_renderer = not (api.get_plugin_info \"render-markdown.nvim\" or api.get_plugin_info \"markview.nvim\")\n if has_no_renderer and Obsidian.opts.ui.enable then\n require(\"obsidian.ui\").setup(Obsidian.workspace, Obsidian.opts.ui)\n end\n\n if opts.lock then\n Obsidian.workspace:lock()\n end\n\n Obsidian.picker = require(\"obsidian.pickers\").get(Obsidian.opts.picker.name)\n\n util.fire_callback(\"post_set_workspace\", Obsidian.opts.callbacks.post_set_workspace, workspace)\n\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = \"ObsidianWorkpspaceSet\",\n data = { workspace = workspace },\n })\nend\n\n---@param workspace obsidian.Workspace|string The workspace object or the name of an existing workspace.\n---@param opts { lock: boolean|? }|?\nWorkspace.switch = function(workspace, opts)\n opts = opts and opts or {}\n\n if workspace == Obsidian.workspace.name then\n log.info(\"Already in workspace '%s' @ '%s'\", workspace, Obsidian.workspace.path)\n return\n end\n\n for _, ws in ipairs(Obsidian.opts.workspaces) do\n if ws.name == workspace then\n return Workspace.set(Workspace.new_from_spec(ws), opts)\n end\n end\n\n error(string.format(\"Workspace '%s' not found\", workspace))\nend\n\nreturn Workspace\n"], ["/obsidian.nvim/lua/obsidian/commands/extract_note.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---Extract the selected text into a new note\n---and replace the selection with a link to the new note.\n---\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"Obsidian extract_note must be called with visual selection\"\n return\n end\n\n local content = vim.split(viz.selection, \"\\n\", { plain = true })\n\n ---@type string|?\n local title\n if data.args ~= nil and string.len(data.args) > 0 then\n title = vim.trim(data.args)\n else\n title = api.input \"Enter title (optional): \"\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n end\n\n -- create the new note.\n local note = Note.create { title = title }\n\n -- replace selection with link to new note\n local link = api.format_link(note)\n vim.api.nvim_buf_set_text(0, viz.csrow - 1, viz.cscol - 1, viz.cerow - 1, viz.cecol, { link })\n\n require(\"obsidian.ui\").update(0)\n\n -- add the selected text to the end of the new note\n note:open { sync = true }\n vim.api.nvim_buf_set_lines(0, -1, -1, false, content)\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/tags.lua", "local Note = require \"obsidian.note\"\nlocal Patterns = require(\"obsidian.search\").Patterns\n\nlocal M = {}\n\n---@type { pattern: string, offset: integer }[]\nlocal TAG_PATTERNS = {\n { pattern = \"[%s%(]#\" .. Patterns.TagCharsOptional .. \"$\", offset = 2 },\n { pattern = \"^#\" .. Patterns.TagCharsOptional .. \"$\", offset = 1 },\n}\n\nM.find_tags_start = function(input)\n for _, pattern in ipairs(TAG_PATTERNS) do\n local match = string.match(input, pattern.pattern)\n if match then\n return string.sub(match, pattern.offset + 1)\n end\n end\nend\n\n--- Find the boundaries of the YAML frontmatter within the buffer.\n---@param bufnr integer\n---@return integer|?, integer|?\nlocal get_frontmatter_boundaries = function(bufnr)\n local note = Note.from_buffer(bufnr)\n if note.frontmatter_end_line ~= nil then\n return 1, note.frontmatter_end_line\n end\nend\n\n---@return boolean, string|?, boolean|?\nM.can_complete = function(request)\n local search = M.find_tags_start(request.context.cursor_before_line)\n if not search or string.len(search) == 0 then\n return false\n end\n\n -- Check if we're inside frontmatter.\n local in_frontmatter = false\n local line = request.context.cursor.line\n local frontmatter_start, frontmatter_end = get_frontmatter_boundaries(request.context.bufnr)\n if\n frontmatter_start ~= nil\n and frontmatter_start <= (line + 1)\n and frontmatter_end ~= nil\n and line <= frontmatter_end\n then\n in_frontmatter = true\n end\n\n return true, search, in_frontmatter\nend\n\nM.get_trigger_characters = function()\n return { \"#\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n -- return [=[\\%(^\\|[^#]\\)\\zs#[a-zA-Z0-9_/-]\\+]=]\n return \"#[a-zA-Z0-9_/-]\\\\+\"\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/log.lua", "---@class obsidian.Logger\nlocal log = {}\n\nlog._log_level = vim.log.levels.INFO\n\n---@param t table\n---@return boolean\nlocal function has_tostring(t)\n local mt = getmetatable(t)\n return mt ~= nil and mt.__tostring ~= nil\nend\n\n---@param msg string\n---@return any[]\nlocal function message_args(msg, ...)\n local args = { ... }\n local num_directives = select(2, string.gsub(msg, \"%%\", \"\")) - 2 * select(2, string.gsub(msg, \"%%%%\", \"\"))\n\n -- Some elements might be nil, so we can't use 'ipairs'.\n local out = {}\n for i = 1, #args do\n local v = args[i]\n if v == nil then\n out[i] = tostring(v)\n elseif type(v) == \"table\" and not has_tostring(v) then\n out[i] = vim.inspect(v)\n else\n out[i] = v\n end\n end\n\n -- If were short formatting args relative to the number of directives, add \"nil\" strings on.\n if #out < num_directives then\n for i = #out + 1, num_directives do\n out[i] = \"nil\"\n end\n end\n\n return out\nend\n\n---@param level integer\nlog.set_level = function(level)\n log._log_level = level\nend\n\n--- Log a message.\n---\n---@param msg any\n---@param level integer|?\nlog.log = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---Log a message only once.\n---\n---@param msg any\n---@param level integer|?\nlog.log_once = function(msg, level, ...)\n if level == nil or log._log_level == nil or level >= log._log_level then\n msg = string.format(tostring(msg), unpack(message_args(msg, ...)))\n if vim.in_fast_event() then\n vim.schedule(function()\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end)\n else\n vim.notify_once(msg, level, { title = \"Obsidian.nvim\" })\n end\n end\nend\n\n---@param msg string\nlog.debug = function(msg, ...)\n log.log(msg, vim.log.levels.DEBUG, ...)\nend\n\n---@param msg string\nlog.info = function(msg, ...)\n log.log(msg, vim.log.levels.INFO, ...)\nend\n\n---@param msg string\nlog.warn = function(msg, ...)\n log.log(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.warn_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.WARN, ...)\nend\n\n---@param msg string\nlog.err = function(msg, ...)\n log.log(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error = log.err\n\n---@param msg string\nlog.err_once = function(msg, ...)\n log.log_once(msg, vim.log.levels.ERROR, ...)\nend\n\nlog.error_once = log.err\n\nreturn log\n"], ["/obsidian.nvim/lua/obsidian/commands/new_from_template.lua", "local log = require \"obsidian.log\"\nlocal util = require \"obsidian.util\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n ---@type string?\n local title = table.concat(data.fargs, \" \", 1, #data.fargs - 1)\n local template = data.fargs[#data.fargs]\n\n if title ~= nil and template ~= nil then\n local note = Note.create { title = title, template = template, should_write = true }\n note:open { sync = true }\n return\n end\n\n picker:find_templates {\n callback = function(template_name)\n if title == nil or title == \"\" then\n -- Must use pcall in case of KeyboardInterrupt\n -- We cannot place `title` where `safe_title` is because it would be redeclaring it\n local success, safe_title = pcall(util.input, \"Enter title or path (optional): \", { completion = \"file\" })\n title = safe_title\n if not success or not safe_title then\n log.warn \"Aborted\"\n return\n elseif safe_title == \"\" then\n title = nil\n end\n end\n\n if template_name == nil or template_name == \"\" then\n log.warn \"Aborted\"\n return\n end\n\n ---@type obsidian.Note\n local note = Note.create { title = title, template = template_name, should_write = true }\n note:open { sync = false }\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/builtin.lua", "---builtin functions that are default values for config options\nlocal M = {}\nlocal util = require \"obsidian.util\"\n\n---Create a new unique Zettel ID.\n---\n---@return string\nM.zettel_id = function()\n local suffix = \"\"\n for _ = 1, 4 do\n suffix = suffix .. string.char(math.random(65, 90))\n end\n return tostring(os.time()) .. \"-\" .. suffix\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_alias_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = string.format(\"#%s\", opts.anchor.header)\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.label, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_only = function(opts)\n ---@type string\n local header_or_block = \"\"\n if opts.anchor then\n header_or_block = opts.anchor.anchor\n elseif opts.block then\n header_or_block = string.format(\"#%s\", opts.block.id)\n end\n return string.format(\"[[%s%s]]\", opts.path, header_or_block)\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_path_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.label ~= opts.path then\n return string.format(\"[[%s%s|%s%s]]\", opts.path, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.path, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.wiki_link_id_prefix = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n if opts.id == nil then\n return string.format(\"[[%s%s]]\", opts.label, anchor)\n elseif opts.label ~= opts.id then\n return string.format(\"[[%s%s|%s%s]]\", opts.id, anchor, opts.label, header)\n else\n return string.format(\"[[%s%s]]\", opts.id, anchor)\n end\nend\n\n---@param opts { path: string, label: string, id: string|integer|?, anchor: obsidian.note.HeaderAnchor|?, block: obsidian.note.Block|? }\n---@return string\nM.markdown_link = function(opts)\n local anchor = \"\"\n local header = \"\"\n if opts.anchor then\n anchor = opts.anchor.anchor\n header = util.format_anchor_label(opts.anchor)\n elseif opts.block then\n anchor = \"#\" .. opts.block.id\n header = \"#\" .. opts.block.id\n end\n\n local path = util.urlencode(opts.path, { keep_path_sep = true })\n return string.format(\"[%s%s](%s%s)\", opts.label, header, path, anchor)\nend\n\n---@param path string\n---@return string\nM.img_text_func = function(path)\n local format_string = {\n markdown = \"![](%s)\",\n wiki = \"![[%s]]\",\n }\n local style = Obsidian.opts.preferred_link_style\n local name = vim.fs.basename(tostring(path))\n\n if style == \"markdown\" then\n name = require(\"obsidian.util\").urlencode(name)\n end\n\n return string.format(format_string[style], name)\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/refs.lua", "local util = require \"obsidian.util\"\n\nlocal M = {}\n\n---@enum obsidian.completion.RefType\nM.RefType = {\n Wiki = 1,\n Markdown = 2,\n}\n\n---Backtrack through a string to find the first occurrence of '[['.\n---\n---@param input string\n---@return string|?, string|?, obsidian.completion.RefType|?\nlocal find_search_start = function(input)\n for i = string.len(input), 1, -1 do\n local substr = string.sub(input, i)\n if vim.startswith(substr, \"]\") or vim.endswith(substr, \"]\") then\n return nil\n elseif vim.startswith(substr, \"[[\") then\n return substr, string.sub(substr, 3)\n elseif vim.startswith(substr, \"[\") and string.sub(input, i - 1, i - 1) ~= \"[\" then\n return substr, string.sub(substr, 2)\n end\n end\n return nil\nend\n\n---Check if a completion request can/should be carried out. Returns a boolean\n---and, if true, the search string and the column indices of where the completion\n---items should be inserted.\n---\n---@return boolean, string|?, integer|?, integer|?, obsidian.completion.RefType|?\nM.can_complete = function(request)\n local input, search = find_search_start(request.context.cursor_before_line)\n if input == nil or search == nil then\n return false\n elseif string.len(search) == 0 or util.is_whitespace(search) then\n return false\n end\n\n if vim.startswith(input, \"[[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 2)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]]\" and 1 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Wiki\n elseif vim.startswith(input, \"[\") then\n local suffix = string.sub(request.context.cursor_after_line, 1, 1)\n local cursor_col = request.context.cursor.col\n local insert_end_offset = suffix == \"]\" and 0 or -1\n return true, search, cursor_col - 1 - #input, cursor_col + insert_end_offset, M.RefType.Markdown\n else\n return false\n end\nend\n\nM.get_trigger_characters = function()\n return { \"[\" }\nend\n\nM.get_keyword_pattern = function()\n -- Note that this is a vim pattern, not a Lua pattern. See ':help pattern'.\n -- The enclosing [=[ ... ]=] is just a way to mark the boundary of a\n -- string in Lua.\n return [=[\\%(^\\|[^\\[]\\)\\zs\\[\\{1,2}[^\\]]\\+\\]\\{,2}]=]\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/workspace.lua", "local log = require \"obsidian.log\"\nlocal Workspace = require \"obsidian.workspace\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.info(\"Current workspace: '%s' @ '%s'\", Obsidian.workspace.name, Obsidian.workspace.path)\n return\n end\n\n local options = {}\n for i, spec in ipairs(Obsidian.opts.workspaces) do\n local workspace = Workspace.new_from_spec(spec)\n if workspace == Obsidian.workspace then\n options[#options + 1] = string.format(\"*[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n else\n options[#options + 1] = string.format(\"[%d] %s @ '%s'\", i, workspace.name, workspace.path)\n end\n end\n\n picker:pick(options, {\n prompt_title = \"Workspaces\",\n callback = function(workspace_str)\n local idx = tonumber(string.match(workspace_str, \"%*?%[(%d+)]\"))\n Workspace.switch(Obsidian.opts.workspaces[idx].name, { lock = true })\n end,\n })\n else\n Workspace.switch(data.args, { lock = true })\n end\nend\n"], ["/obsidian.nvim/minimal.lua", "vim.env.LAZY_STDPATH = \".repro\"\nload(vim.fn.system \"curl -s https://raw.githubusercontent.com/folke/lazy.nvim/main/bootstrap.lua\")()\n\nvim.fn.mkdir(\".repro/vault\", \"p\")\n\nvim.o.conceallevel = 2\n\nlocal plugins = {\n {\n \"obsidian-nvim/obsidian.nvim\",\n dependencies = { \"nvim-lua/plenary.nvim\" },\n opts = {\n completion = {\n blink = true,\n nvim_cmp = false,\n },\n workspaces = {\n {\n name = \"test\",\n path = vim.fs.joinpath(vim.uv.cwd(), \".repro\", \"vault\"),\n },\n },\n },\n },\n\n -- **Choose your renderer**\n -- { \"MeanderingProgrammer/render-markdown.nvim\", dependencies = { \"echasnovski/mini.icons\" }, opts = {} },\n -- { \"OXY2DEV/markview.nvim\", lazy = false },\n\n -- **Choose your picker**\n -- \"nvim-telescope/telescope.nvim\",\n -- \"folke/snacks.nvim\",\n -- \"ibhagwan/fzf-lua\",\n -- \"echasnovski/mini.pick\",\n\n -- **Choose your completion engine**\n -- {\n -- \"hrsh7th/nvim-cmp\",\n -- config = function()\n -- local cmp = require \"cmp\"\n -- cmp.setup {\n -- mapping = cmp.mapping.preset.insert {\n -- [\"\"] = cmp.mapping.abort(),\n -- [\"\"] = cmp.mapping.confirm { select = true },\n -- },\n -- }\n -- end,\n -- },\n -- {\n -- \"saghen/blink.cmp\",\n -- opts = {\n -- fuzzy = { implementation = \"lua\" }, -- no need to build binary\n -- keymap = {\n -- preset = \"default\",\n -- },\n -- },\n -- },\n}\n\nrequire(\"lazy.minit\").repro { spec = plugins }\n\nvim.cmd \"checkhealth obsidian\"\n"], ["/obsidian.nvim/lua/obsidian/commands/template.lua", "local templates = require \"obsidian.templates\"\nlocal log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local templates_dir = api.templates_dir()\n if not templates_dir then\n log.err \"Templates folder is not defined or does not exist\"\n return\n end\n\n -- We need to get this upfront before the picker hijacks the current window.\n local insert_location = api.get_active_window_cursor_location()\n\n local function insert_template(name)\n templates.insert_template {\n type = \"insert_template\",\n template_name = name,\n template_opts = Obsidian.opts.templates,\n templates_dir = templates_dir,\n location = insert_location,\n }\n end\n\n if string.len(data.args) > 0 then\n local template_name = vim.trim(data.args)\n insert_template(template_name)\n return\n end\n\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_templates {\n callback = function(path)\n insert_template(path)\n end,\n }\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/link_new.lua", "local log = require \"obsidian.log\"\nlocal api = require \"obsidian.api\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local viz = api.get_visual_selection()\n if not viz then\n log.err \"ObsidianLink must be called with visual selection\"\n return\n elseif #viz.lines ~= 1 then\n log.err \"Only in-line visual selections allowed\"\n return\n end\n\n local line = assert(viz.lines[1])\n\n local title\n if string.len(data.args) > 0 then\n title = data.args\n else\n title = viz.selection\n end\n\n local note = Note.create { title = title }\n\n local new_line = string.sub(line, 1, viz.cscol - 1)\n .. api.format_link(note, { label = title })\n .. string.sub(line, viz.cecol + 1)\n\n vim.api.nvim_buf_set_lines(0, viz.csrow - 1, viz.csrow, false, { new_line })\nend\n"], ["/obsidian.nvim/lua/obsidian/types.lua", "-- Useful type definitions go here.\n\n---@class CommandArgs\n---The table passed to user commands.\n---For details see `:help nvim_create_user_command()` and the command attribute docs\n---\n---@field name string Command name\n---@field args string The args passed to the command, if any \n---@field fargs table The args split by unescaped whitespace (when more than one argument is allowed), if any \n---@field nargs string Number of arguments |:command-nargs|\n---@field bang boolean \"true\" if the command was executed with a ! modifier \n---@field line1 number The starting line of the command range \n---@field line2 number The final line of the command range \n---@field range number The number of items in the command range: 0, 1, or 2 \n---@field count number Any count supplied \n---@field reg string The optional register, if specified \n---@field mods string Command modifiers, if any \n---@field smods table Command modifiers in a structured format. Has the same structure as the \"mods\" key of\n---@field raw_print boolean HACK: for debug command and info\n\n---@class obsidian.InsertTemplateContext\n---The table passed to user substitution functions when inserting templates into a buffer.\n---\n---@field type \"insert_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field location [number, number, number, number] `{ buf, win, row, col }` location from which the request was made.\n---@field partial_note? obsidian.Note An optional note with fields to copy from.\n\n---@class obsidian.CloneTemplateContext\n---The table passed to user substitution functions when cloning template files to create new notes.\n---\n---@field type \"clone_template\"\n---@field template_name string|obsidian.Path The name or path of the template being used.\n---@field template_opts obsidian.config.TemplateOpts The template options being used.\n---@field templates_dir obsidian.Path The folder containing the template file.\n---@field destination_path obsidian.Path The path the cloned template will be written to.\n---@field partial_note obsidian.Note The note being written.\n\n---@alias obsidian.TemplateContext obsidian.InsertTemplateContext | obsidian.CloneTemplateContext\n---The table passed to user substitution functions. Use `ctx.type` to distinguish between the different kinds.\n"], ["/obsidian.nvim/lua/obsidian/commands/quick_switch.lua", "local log = require \"obsidian.log\"\nlocal search = require \"obsidian.search\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not data.args or string.len(data.args) == 0 then\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n\n picker:find_notes()\n else\n search.resolve_note_async(data.args, function(note)\n note:open()\n end)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/util.lua", "local M = {}\n\n---Generates the completion request from a blink context\n---@param context blink.cmp.Context\n---@return obsidian.completion.sources.base.Request\nM.generate_completion_request_from_editor_state = function(context)\n local row = context.cursor[1]\n local col = context.cursor[2] + 1\n local cursor_before_line = context.line:sub(1, col - 1)\n local cursor_after_line = context.line:sub(col)\n\n return {\n context = {\n bufnr = context.bufnr,\n cursor_before_line = cursor_before_line,\n cursor_after_line = cursor_after_line,\n cursor = {\n row = row,\n col = col,\n line = row + 1,\n },\n },\n }\nend\n\nM.incomplete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = true,\n items = {},\n}\n\nM.complete_response = {\n is_incomplete_forward = true,\n is_incomplete_backward = false,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/pickers/init.lua", "local PickerName = require(\"obsidian.config\").Picker\n\nlocal M = {}\n\n--- Get the default Picker.\n---\n---@param picker_name obsidian.config.Picker|?\n---\n---@return obsidian.Picker|?\nM.get = function(picker_name)\n picker_name = picker_name and picker_name or Obsidian.opts.picker.name\n if picker_name then\n picker_name = string.lower(picker_name)\n else\n for _, name in ipairs { PickerName.telescope, PickerName.fzf_lua, PickerName.mini, PickerName.snacks } do\n local ok, res = pcall(M.get, name)\n if ok then\n return res\n end\n end\n return nil\n end\n\n if picker_name == string.lower(PickerName.telescope) then\n return require(\"obsidian.pickers._telescope\").new()\n elseif picker_name == string.lower(PickerName.mini) then\n return require(\"obsidian.pickers._mini\").new()\n elseif picker_name == string.lower(PickerName.fzf_lua) then\n return require(\"obsidian.pickers._fzf\").new()\n elseif picker_name == string.lower(PickerName.snacks) then\n return require(\"obsidian.pickers._snacks\").new()\n elseif picker_name then\n error(\"not implemented for \" .. picker_name)\n end\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/paste_img.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal img = require \"obsidian.img_paste\"\n\n---@param data CommandArgs\nreturn function(_, data)\n if not img.clipboard_is_img() then\n return log.err \"There is no image data in the clipboard\"\n end\n\n ---@type string|?\n local default_name = Obsidian.opts.attachments.img_name_func()\n\n local should_confirm = Obsidian.opts.attachments.confirm_img_paste\n\n ---@type string\n local fname = vim.trim(data.args)\n\n -- Get filename to save to.\n if fname == nil or fname == \"\" then\n if default_name and not should_confirm then\n fname = default_name\n else\n local input = api.input(\"Enter file name: \", { default = default_name, completion = \"file\" })\n if not input then\n return log.warn \"Paste aborted\"\n end\n fname = input\n end\n end\n\n local path = api.resolve_image_path(fname)\n\n img.paste(path)\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/new.lua", "local api = require \"obsidian.api\"\nlocal log = require \"obsidian.log\"\nlocal Note = require \"obsidian.note\"\n\n---@param data CommandArgs\nreturn function(_, data)\n ---@type obsidian.Note\n local note\n if data.args:len() > 0 then\n note = Note.create { title = data.args }\n else\n local title = api.input(\"Enter title or path (optional): \", { completion = \"file\" })\n if not title then\n log.warn \"Aborted\"\n return\n elseif title == \"\" then\n title = nil\n end\n note = Note.create { title = title }\n end\n\n -- Open the note in a new buffer.\n note:open { sync = true }\n note:write_to_buffer()\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/plugin_initializers/nvim_cmp.lua", "local M = {}\n\n-- Ran once on the plugin startup\n---@param opts obsidian.config.ClientOpts\nfunction M.register_sources(opts)\n local cmp = require \"cmp\"\n\n cmp.register_source(\"obsidian\", require(\"obsidian.completion.sources.nvim_cmp.refs\").new())\n cmp.register_source(\"obsidian_tags\", require(\"obsidian.completion.sources.nvim_cmp.tags\").new())\n if opts.completion.create_new then\n cmp.register_source(\"obsidian_new\", require(\"obsidian.completion.sources.nvim_cmp.new\").new())\n end\nend\n\n-- Triggered for each opened markdown buffer that's in a workspace and configures nvim_cmp sources for the current buffer.\n---@param opts obsidian.config.ClientOpts\nfunction M.inject_sources(opts)\n local cmp = require \"cmp\"\n\n local sources = {\n { name = \"obsidian\" },\n { name = \"obsidian_tags\" },\n }\n if opts.completion.create_new then\n table.insert(sources, { name = \"obsidian_new\" })\n end\n for _, source in pairs(cmp.get_config().sources) do\n if source.name ~= \"obsidian\" and source.name ~= \"obsidian_new\" and source.name ~= \"obsidian_tags\" then\n table.insert(sources, source)\n end\n end\n ---@diagnostic disable-next-line: missing-fields\n cmp.setup.buffer { sources = sources }\nend\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/commands/toggle_checkbox.lua", "local toggle_checkbox = require(\"obsidian.api\").toggle_checkbox\n\n---@param data CommandArgs\nreturn function(_, data)\n local start_line, end_line\n local checkboxes = Obsidian.opts.checkbox.order\n start_line = data.line1\n end_line = data.line2\n\n local buf = vim.api.nvim_get_current_buf()\n\n for line_nb = start_line, end_line do\n local current_line = vim.api.nvim_buf_get_lines(buf, line_nb - 1, line_nb, false)[1]\n if current_line and current_line:match \"%S\" then\n toggle_checkbox(checkboxes, line_nb)\n end\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/today.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local offset_days = 0\n local arg = string.gsub(data.args, \" \", \"\")\n if string.len(arg) > 0 then\n local offset = tonumber(arg)\n if offset == nil then\n log.err \"Invalid argument, expected an integer offset\"\n return\n else\n offset_days = offset\n end\n end\n local note = require(\"obsidian.daily\").daily(offset_days, {})\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/yaml/line.lua", "local abc = require \"obsidian.abc\"\nlocal util = require \"obsidian.util\"\n\n---@class obsidian.yaml.Line : obsidian.ABC\n---@field content string\n---@field raw_content string\n---@field indent integer\nlocal Line = abc.new_class {\n __tostring = function(self)\n return string.format(\"Line('%s')\", self.raw_content)\n end,\n}\n\n---Create a new Line instance from a raw line string.\n---@param raw_line string\n---@param base_indent integer|?\n---@return obsidian.yaml.Line\nLine.new = function(raw_line, base_indent)\n local self = Line.init()\n self.indent = util.count_indent(raw_line)\n if base_indent ~= nil then\n if base_indent > self.indent then\n error \"relative indentation for line is less than base indentation\"\n end\n self.indent = self.indent - base_indent\n end\n self.raw_content = util.lstrip_whitespace(raw_line, base_indent)\n self.content = vim.trim(self.raw_content)\n return self\nend\n\n---Check if a line is empty.\n---@param self obsidian.yaml.Line\n---@return boolean\nLine.is_empty = function(self)\n if util.strip_comments(self.content) == \"\" then\n return true\n else\n return false\n end\nend\n\nreturn Line\n"], ["/obsidian.nvim/lua/obsidian/compat.lua", "local compat = {}\n\nlocal has_nvim_0_11 = false\nif vim.fn.has \"nvim-0.11\" == 1 then\n has_nvim_0_11 = true\nend\n\ncompat.is_list = function(t)\n if has_nvim_0_11 then\n return vim.islist(t)\n else\n return vim.tbl_islist(t)\n end\nend\n\ncompat.flatten = function(t)\n if has_nvim_0_11 then\n ---@diagnostic disable-next-line: undefined-field\n return vim.iter(t):flatten():totable()\n else\n return vim.tbl_flatten(t)\n end\nend\n\nreturn compat\n"], ["/obsidian.nvim/after/ftplugin/markdown.lua", "local obsidian = require \"obsidian\"\nlocal buf = vim.api.nvim_get_current_buf()\nlocal buf_dir = vim.fs.dirname(vim.api.nvim_buf_get_name(buf))\n\nlocal workspace = obsidian.Workspace.get_workspace_for_dir(buf_dir, Obsidian.opts.workspaces)\nif not workspace then\n return -- if not in any workspace.\nend\n\nlocal win = vim.api.nvim_get_current_win()\n\nvim.treesitter.start(buf, \"markdown\") -- for when user don't use nvim-treesitter\nvim.wo[win].foldmethod = \"expr\"\nvim.wo[win].foldexpr = \"v:lua.vim.treesitter.foldexpr()\"\nvim.wo[win].foldlevel = 99\n"], ["/obsidian.nvim/lua/obsidian/commands/follow_link.lua", "local api = require \"obsidian.api\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local opts = {}\n if data.args and string.len(data.args) > 0 then\n opts.open_strategy = data.args\n end\n\n local link = api.cursor_link()\n\n if link then\n api.follow_link(link, opts)\n end\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.new = function()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\nNewNoteSource.get_keyword_pattern = completion.get_keyword_pattern\n\nNewNoteSource.incomplete_response = nvim_cmp_util.incomplete_response\nNewNoteSource.complete_response = nvim_cmp_util.complete_response\n\n---Invoke completion (required).\n---@param request cmp.SourceCompletionApiParams\n---@param callback fun(response: lsp.CompletionResponse|nil)\nfunction NewNoteSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\n---Creates a new note using the default template for the completion item.\n---Executed after the item was selected.\n---@param completion_item lsp.CompletionItem\n---@param callback fun(completion_item: lsp.CompletionItem|nil)\nfunction NewNoteSource:execute(completion_item, callback)\n return callback(self:process_execute(completion_item))\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.blink.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.incomplete_response = blink_util.incomplete_response\nRefsSource.complete_response = blink_util.complete_response\n\nfunction RefsSource.new()\n return RefsSource.init(RefsSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction RefsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/new.lua", "local NewNoteSourceBase = require \"obsidian.completion.sources.base.new\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.NewNoteSource : obsidian.completion.sources.base.NewNoteSourceBase\nlocal NewNoteSource = abc.new_class()\n\nNewNoteSource.incomplete_response = blink_util.incomplete_response\nNewNoteSource.complete_response = blink_util.complete_response\n\nfunction NewNoteSource.new()\n return NewNoteSource.init(NewNoteSourceBase)\nend\n\n---Implement the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction NewNoteSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\n---Implements the execute method of the completion provider\n---@param _ blink.cmp.Context\n---@param item blink.cmp.CompletionItem\n---@param callback fun(),\n---@param default_implementation fun(context?: blink.cmp.Context, item?: blink.cmp.CompletionItem)): ((fun(): nil) | nil)\nfunction NewNoteSource:execute(_, item, callback, default_implementation)\n self:process_execute(item)\n default_implementation() -- Ensure completion is still executed\n callback() -- Required (as per blink documentation)\nend\n\nreturn NewNoteSource\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/blink/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal blink_util = require \"obsidian.completion.sources.blink.util\"\n\n---@class obsidian.completion.sources.blink.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.incomplete_response = blink_util.incomplete_response\nTagsSource.complete_response = blink_util.complete_response\n\nfunction TagsSource.new()\n return TagsSource.init(TagsSourceBase)\nend\n\n---Implements the get_completions method of the completion provider\n---@param context blink.cmp.Context\n---@param resolve fun(self: blink.cmp.CompletionResponse): nil\nfunction TagsSource:get_completions(context, resolve)\n local request = blink_util.generate_completion_request_from_editor_state(context)\n local cc = self:new_completion_context(resolve, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/yaml/yq.lua", "local m = {}\n\n---@param str string\n---@return any\nm.loads = function(str)\n local as_json = vim.fn.system(\"yq -o=json\", str)\n local data = vim.json.decode(as_json, { luanil = { object = true, array = true } })\n return data\nend\n\nreturn m\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/refs.lua", "local RefsSourceBase = require \"obsidian.completion.sources.base.refs\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.refs\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.CompletionItem\n---@field label string\n---@field new_text string\n---@field sort_text string\n---@field documentation table|?\n\n---@class obsidian.completion.sources.nvim_cmp.RefsSource : obsidian.completion.sources.base.RefsSourceBase\nlocal RefsSource = abc.new_class()\n\nRefsSource.new = function()\n return RefsSource.init(RefsSourceBase)\nend\n\nRefsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nRefsSource.incomplete_response = nvim_cmp_util.incomplete_response\nRefsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction RefsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn RefsSource\n"], ["/obsidian.nvim/lua/obsidian/commands/yesterday.lua", "return function()\n local note = require(\"obsidian.daily\").yesterday()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/tomorrow.lua", "return function()\n local note = require(\"obsidian.daily\").tomorrow()\n note:open()\nend\n"], ["/obsidian.nvim/lua/obsidian/commands/search.lua", "local log = require \"obsidian.log\"\n\n---@param data CommandArgs\nreturn function(_, data)\n local picker = Obsidian.picker\n if not picker then\n log.err \"No picker configured\"\n return\n end\n picker:grep_notes { query = data.args }\nend\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/util.lua", "local M = {}\n\nM.incomplete_response = { isIncomplete = true }\n\nM.complete_response = {\n isIncomplete = true,\n items = {},\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/nvim_cmp/tags.lua", "local TagsSourceBase = require \"obsidian.completion.sources.base.tags\"\nlocal abc = require \"obsidian.abc\"\nlocal completion = require \"obsidian.completion.tags\"\nlocal nvim_cmp_util = require \"obsidian.completion.sources.nvim_cmp.util\"\n\n---@class obsidian.completion.sources.nvim_cmp.TagsSource : obsidian.completion.sources.base.TagsSourceBase\nlocal TagsSource = abc.new_class()\n\nTagsSource.new = function()\n return TagsSource.init(TagsSourceBase)\nend\n\nTagsSource.get_keyword_pattern = completion.get_keyword_pattern\n\nTagsSource.incomplete_response = nvim_cmp_util.incomplete_response\nTagsSource.complete_response = nvim_cmp_util.complete_response\n\nfunction TagsSource:complete(request, callback)\n local cc = self:new_completion_context(callback, request)\n self:process_completion(cc)\nend\n\nreturn TagsSource\n"], ["/obsidian.nvim/lua/obsidian/completion/init.lua", "local M = {\n refs = require \"obsidian.completion.refs\",\n tags = require \"obsidian.completion.tags\",\n}\n\nreturn M\n"], ["/obsidian.nvim/lua/obsidian/completion/sources/base/types.lua", "---@class obsidian.completion.sources.base.Request.Context.Position\n---@field public col integer\n---@field public row integer\n\n---A request context class that partially matches cmp.Context to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request.Context\n---@field public bufnr integer\n---@field public cursor obsidian.completion.sources.base.Request.Context.Position|lsp.Position\n---@field public cursor_after_line string\n---@field public cursor_before_line string\n\n---A request class that partially matches cmp.Request to serve as a common interface for completion sources\n---@class obsidian.completion.sources.base.Request\n---@field public context obsidian.completion.sources.base.Request.Context\n"], ["/obsidian.nvim/lua/obsidian/version.lua", "return \"3.12.0\"\n"]], "task_instance_info": {"created_time": "2025-08-21 00:50:03", "created_task_model": "DeepSeek-R1", "function_skeleton": "function () end", "code_description": "This code segment functions to: Track and update metadata for the current document by collecting word statistics, backlink references, and frontmatter properties to dynamically generate formatted status information."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nfunction()\n local path = api.current_note(client)\n if path then\n current_note = path\n else\n current_note = nil\n end\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-50-24"}, "editdistance_info": {"edit_distance": 11.976, "calculate_time": "2025-08-21 00:50:24", "true_code_clean": "function()\n local note = api.current_note()\n if not note then \n return \"\"\n elseif current_note == note then \n return\n else \n current_note = note\n end\n client:find_backlinks_async(\n note,\n vim.schedule_wrap(function(backlinks)\n local format = assert(Obsidian.opts.statusline.format)\n local wc = vim.fn.wordcount()\n local info = {\n words = wc.words,\n chars = wc.chars,\n backlinks = #backlinks,\n properties = vim.tbl_count(note:frontmatter()),\n }\n for k, v in pairs(info) do\n format = format:gsub(\"{{\" .. k .. \"}}\", v)\n end\n vim.g.obsidian = format\n end)\n )\n end", "predict_code_clean": "function()\n local path = api.current_note(client)\n if path then\n current_note = path\n else\n current_note = nil\n end\nend"}}