diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..e0c117f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# see https://github.com/CppCXY/EmmyLuaCodeStyle +[*.yml] +quote_style = double + +[*.lua] + +indent_style = space +indent_size = 4 +quote_style = double + +continuation_indent = 4 +max_line_length = 120 + +end_of_line = lf + diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index bf708a2..afbe5d6 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -23,6 +23,15 @@ env: ROAM_WAIT_TIME: 500 jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: JohnnyMorganz/stylua-action@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + version: latest + args: --check lua/ spec/ tests: strategy: fail-fast: false diff --git a/lua/org-roam/api.lua b/lua/org-roam/api.lua index 794651a..6b3fd00 100644 --- a/lua/org-roam/api.lua +++ b/lua/org-roam/api.lua @@ -7,24 +7,24 @@ ---@param roam OrgRoam ---@return org-roam.Api return function(roam) - local AliasApi = require("org-roam.api.alias")(roam) + local AliasApi = require("org-roam.api.alias")(roam) local CompletionApi = require("org-roam.api.completion")(roam) - local NodeApi = require("org-roam.api.node")(roam) - local OriginApi = require("org-roam.api.origin")(roam) + local NodeApi = require("org-roam.api.node")(roam) + local OriginApi = require("org-roam.api.origin")(roam) ---@class org-roam.Api - local M = {} + local M = {} - M.add_alias = AliasApi.add_alias - M.add_origin = OriginApi.add_origin - M.capture_node = NodeApi.capture - M.complete_node = CompletionApi.complete_node_under_cursor - M.find_node = NodeApi.find - M.goto_next_node = OriginApi.goto_next_node - M.goto_prev_node = OriginApi.goto_prev_node - M.insert_node = NodeApi.insert - M.remove_alias = AliasApi.remove_alias - M.remove_origin = OriginApi.remove_origin + M.add_alias = AliasApi.add_alias + M.add_origin = OriginApi.add_origin + M.capture_node = NodeApi.capture + M.complete_node = CompletionApi.complete_node_under_cursor + M.find_node = NodeApi.find + M.goto_next_node = OriginApi.goto_next_node + M.goto_prev_node = OriginApi.goto_prev_node + M.insert_node = NodeApi.insert + M.remove_alias = AliasApi.remove_alias + M.remove_origin = OriginApi.remove_origin return M end diff --git a/lua/org-roam/api/alias.lua b/lua/org-roam/api/alias.lua index 096f876..a7be3ce 100644 --- a/lua/org-roam/api/alias.lua +++ b/lua/org-roam/api/alias.lua @@ -20,52 +20,57 @@ local function roam_add_alias(roam, opts) return Promise.new(function(resolve, reject) utils.node_under_cursor(function(node) -- Mark unsuccessful and exit - if not node then return resolve(false) end + if not node then + return resolve(false) + end - roam.database:load_file({ path = node.file }):next(function(results) - -- Get the OrgFile instance - local file = results.file + roam.database + :load_file({ path = node.file }) + :next(function(results) + -- Get the OrgFile instance + local file = results.file - -- Look for a file or headline that matches our node - local entry = utils.find_id_match(file, node.id) + -- Look for a file or headline that matches our node + local entry = utils.find_id_match(file, node.id) - if entry then - -- Get list of aliases that already exist - local aliases = entry:get_property(ALIASES_PROP_NAME) or "" + if entry then + -- Get list of aliases that already exist + local aliases = entry:get_property(ALIASES_PROP_NAME) or "" - local alias = vim.trim(opts.alias or vim.fn.input({ - prompt = "Alias: ", - })) + local alias = vim.trim(opts.alias or vim.fn.input({ + prompt = "Alias: ", + })) - -- Skip if not given a non-empty alias - if alias == "" then - notify.echo_info("canceled adding alias") + -- Skip if not given a non-empty alias + if alias == "" then + notify.echo_info("canceled adding alias") - -- Mark unsuccessful - resolve(false) + -- Mark unsuccessful + resolve(false) - return file - end + return file + end - -- Escape double quotes and backslashes within alias as - -- we're going to wrap it - alias = utils.wrap_prop_value(alias) + -- Escape double quotes and backslashes within alias as + -- we're going to wrap it + alias = utils.wrap_prop_value(alias) - -- Append our new alias to the end - aliases = vim.trim(string.format("%s \"%s\"", aliases, alias)) + -- Append our new alias to the end + aliases = vim.trim(string.format('%s "%s"', aliases, alias)) - -- Update the entry - entry:set_property(ALIASES_PROP_NAME, aliases) + -- Update the entry + entry:set_property(ALIASES_PROP_NAME, aliases) - -- Mark successful - resolve(true) - else - -- Mark unsuccessful - resolve(false) - end + -- Mark successful + resolve(true) + else + -- Mark unsuccessful + resolve(false) + end - return file - end):catch(reject) + return file + end) + :catch(reject) end, { win = opts.win }) end) end @@ -78,83 +83,91 @@ local function roam_remove_alias(roam, opts) return Promise.new(function(resolve, reject) utils.node_under_cursor(function(node) -- Mark unsuccessful and exit - if not node then return resolve(false) end + if not node then + return resolve(false) + end - roam.database:load_file({ path = node.file }):next(function(results) - -- Get the OrgFile instance - local file = results.file + roam.database + :load_file({ path = node.file }) + :next(function(results) + -- Get the OrgFile instance + local file = results.file - -- Look for a file or headline that matches our node - local entry = utils.find_id_match(file, node.id) + -- Look for a file or headline that matches our node + local entry = utils.find_id_match(file, node.id) - if entry and opts.all then - entry:set_property(ALIASES_PROP_NAME, nil) + if entry and opts.all then + entry:set_property(ALIASES_PROP_NAME, nil) - -- Mark successful - resolve(true) - elseif entry then - local aliases = entry:get_property(ALIASES_PROP_NAME) or "" - - -- If we have nothing to remove, exit successfully - if vim.trim(aliases) == "" then + -- Mark successful resolve(true) - return file - end + elseif entry then + local aliases = entry:get_property(ALIASES_PROP_NAME) or "" - local function on_cancel() - notify.echo_info("canceled removing alias") - - -- Mark unsuccessful - resolve(false) - end + -- If we have nothing to remove, exit successfully + if vim.trim(aliases) == "" then + resolve(true) + return file + end - ---@param alias string - local function on_choice(alias) - local remaining = vim.tbl_filter(function(item) - return item ~= "" and item ~= alias - end, utils.parse_prop_value(aliases)) + local function on_cancel() + notify.echo_info("canceled removing alias") - -- Break up our alias into pieces, filter out the specified alias, - -- and then reconstruct back (wrapping in quotes) into aliases string - aliases = vim.trim(table.concat(vim.tbl_map(function(item) - return "\"" .. utils.wrap_prop_value(item) .. "\"" - end, remaining), " ")) + -- Mark unsuccessful + resolve(false) + end - -- Update the entry - if aliases == "" then - entry:set_property(ALIASES_PROP_NAME, nil) - else - entry:set_property(ALIASES_PROP_NAME, aliases) + ---@param alias string + local function on_choice(alias) + local remaining = vim.tbl_filter(function(item) + return item ~= "" and item ~= alias + end, utils.parse_prop_value(aliases)) + + -- Break up our alias into pieces, filter out the specified alias, + -- and then reconstruct back (wrapping in quotes) into aliases string + aliases = vim.trim(table.concat( + vim.tbl_map(function(item) + return '"' .. utils.wrap_prop_value(item) .. '"' + end, remaining), + " " + )) + + -- Update the entry + if aliases == "" then + entry:set_property(ALIASES_PROP_NAME, nil) + else + entry:set_property(ALIASES_PROP_NAME, aliases) + end + + -- Mark successful + resolve(true) end - -- Mark successful - resolve(true) - end + -- Build our prompt, updating it to a left-hand side + -- style if we have neovim 0.10+ which supports inlining + local prompt = "(alias {sel}/{cnt})" + if vim.fn.has("nvim-0.10") == 1 then + prompt = "{sel}/{cnt} alias> " + end - -- Build our prompt, updating it to a left-hand side - -- style if we have neovim 0.10+ which supports inlining - local prompt = "(alias {sel}/{cnt})" - if vim.fn.has("nvim-0.10") == 1 then - prompt = "{sel}/{cnt} alias> " + -- Open a selection dialog for the alias to remove + Select:new({ + auto_select = true, + init_input = opts.alias, + items = utils.parse_prop_value(aliases), + prompt = prompt, + }) + :on_cancel(on_cancel) + :on_choice(on_choice) + :open() + else + -- Mark unsuccessful + resolve(false) end - -- Open a selection dialog for the alias to remove - Select:new({ - auto_select = true, - init_input = opts.alias, - items = utils.parse_prop_value(aliases), - prompt = prompt, - }) - :on_cancel(on_cancel) - :on_choice(on_choice) - :open() - else - -- Mark unsuccessful - resolve(false) - end - - return file - end):catch(reject) + return file + end) + :catch(reject) end, { win = opts.win }) end) end diff --git a/lua/org-roam/api/completion.lua b/lua/org-roam/api/completion.lua index 38b69b7..3e17d31 100644 --- a/lua/org-roam/api/completion.lua +++ b/lua/org-roam/api/completion.lua @@ -29,11 +29,7 @@ local function roam_complete_node_under_cursor(roam, opts) local row = cursor[1] - 1 -- make zero-indexed local line = vim.api.nvim_buf_get_lines(bufnr, row, row + 1, true)[1] - selection = string.sub( - line, - link.range.start.column + 1, - link.range.end_.column + 1 - ) + selection = string.sub(line, link.range.start.column + 1, link.range.end_.column + 1) -- Set initial input to be the link's existing path, -- stripping id: if already starting with that @@ -47,7 +43,8 @@ local function roam_complete_node_under_cursor(roam, opts) end return Promise.new(function(resolve) - roam.ui.select_node({ auto_select = true, init_input = input }) + roam.ui + .select_node({ auto_select = true, init_input = input }) :on_choice(function(choice) local node = roam.database:get_sync(choice.id) if not node then @@ -70,7 +67,9 @@ local function roam_complete_node_under_cursor(roam, opts) local i = 0 while i < string.len(line) do i = string.find(line, selection, i + 1, true) - if i == nil then break end + if i == nil then + break + end -- Check if the current match contains the cursor column if i - 1 <= col and i - 1 + #selection > col then @@ -87,7 +86,7 @@ local function roam_complete_node_under_cursor(roam, opts) -- Replace the text (this will place us into insert mode) vim.api.nvim_buf_set_text(bufnr, row, col, row, col + #selection, { - string.format("[[id:%s][%s]]", node.id, choice.label) + string.format("[[id:%s][%s]]", node.id, choice.label), }) -- Force ourselves back into normal mode @@ -96,7 +95,9 @@ local function roam_complete_node_under_cursor(roam, opts) -- Mark as successful resolve(true) end) - :on_cancel(function() resolve(false) end) + :on_cancel(function() + resolve(false) + end) :open() end) end diff --git a/lua/org-roam/api/node.lua b/lua/org-roam/api/node.lua index d9fb3e9..de7c614 100644 --- a/lua/org-roam/api/node.lua +++ b/lua/org-roam/api/node.lua @@ -28,8 +28,8 @@ end ---Target-specific expansions (keys only). local TARGET_EXPANSION_KEYS = { - SEP = "%[sep]", - SLUG = "%[slug]", + SEP = "%[sep]", + SLUG = "%[slug]", TITLE = "%[title]", } @@ -113,10 +113,7 @@ local function make_target_expander(roam, file, opts) return function(target) -- Resolve target-specific expansions and ensure that -- the target is relative to our roam directory - return path_utils.join( - roam.config.directory, - fill_expansions(roam, target, expansions) - ) + return path_utils.join(roam.config.directory, fill_expansions(roam, target, expansions)) end end @@ -133,10 +130,7 @@ local function build_template(roam, template_opts, opts) -- Resolve our general expansions in the target -- and update the target to be relative to our roam directory if template.target then - template.target = path_utils.join( - roam.config.directory, - fill_expansions(roam, template.target) - ) + template.target = path_utils.join(roam.config.directory, fill_expansions(roam, template.target)) end -- Always include the entire capture contents, not just @@ -148,7 +142,9 @@ local function build_template(roam, template_opts, opts) ---@param content_type "content"|"target" return template:on_compile(function(content, content_type) -- Ignore types other than content - if content_type ~= "content" then return content end + if content_type ~= "content" then + return content + end -- Figure out our template's target local target = template.target or require("orgmode.config").org_default_notes_file @@ -179,10 +175,13 @@ local function build_template(roam, template_opts, opts) -- Grab the title, which if it does not exist and we detect -- that we need it, we will prompt for it local title = opts.title - if not title and string_contains_one_of(template.target, { + if + not title + and string_contains_one_of(template.target, { TARGET_EXPANSION_KEYS.TITLE, TARGET_EXPANSION_KEYS.SLUG, - }) then + }) + then title = vim.fn.input("Enter title for node: ") -- If we did not get a title, return nil to cancel @@ -255,18 +254,23 @@ local function make_on_post_refile(roam, cb) if not id then for _, headline in ipairs(capture_opts.source_file:get_headlines()) do id = headline:get_property("id", false) - if id then break end + if id then + break + end end end -- Reload the file that was written due to a refile local filename = capture_opts.destination_file.filename - roam.database:load_file({ path = filename }) + roam.database + :load_file({ path = filename }) :next(function(...) cb(id) return ... end) - :catch(function(_) cb(nil) end) + :catch(function(_) + cb(nil) + end) end end @@ -282,44 +286,55 @@ local function roam_capture_immediate(roam, opts) }, opts) ---@param content string[]|nil - return template:compile():next(function(content) - if not content then - return notify.echo_info("canceled") - end + return template + :compile() + :next(function(content) + if not content then + return notify.echo_info("canceled") + end - local content_str = table.concat(content, "\n") + local content_str = table.concat(content, "\n") - -- Target needs to have target-specific expansions filled - local expander = make_target_expander(roam, nil, opts) - local path = expander(template.target) + -- Target needs to have target-specific expansions filled + local expander = make_target_expander(roam, nil, opts) + local path = expander(template.target) - return io.write_file(path, content_str):next(function() - return path + return io.write_file(path, content_str):next(function() + return path + end) end) - end):next(function(path) --[[ @cast path string|nil ]] - if not path then return nil end - return roam.database:load_file({ path = path }) - end):next(function(result) --[[ @cast result {file:OrgFile}|nil ]] - if not result then return nil end + :next(function(path) --[[ @cast path string|nil ]] + if not path then + return nil + end + return roam.database:load_file({ path = path }) + end) + :next(function(result) --[[ @cast result {file:OrgFile}|nil ]] + if not result then + return nil + end - local file = result.file + local file = result.file - -- Look for the id of the newly-captured file - local id = file:get_property("id") + -- Look for the id of the newly-captured file + local id = file:get_property("id") - -- If we don't find a file-level node, look for headline nodes - if not id then - for _, headline in ipairs(file:get_headlines()) do - id = headline:get_property("id", false) - if id then break end + -- If we don't find a file-level node, look for headline nodes + if not id then + for _, headline in ipairs(file:get_headlines()) do + id = headline:get_property("id", false) + if id then + break + end + end end - end - return id - end):catch(function(err) - notify.error(err) - log.error(err) - end) + return id + end) + :catch(function(err) + notify.error(err) + log.error(err) + end) end ---Returns a promise when the capture is completed. @@ -358,7 +373,9 @@ local function roam_capture(roam, opts) templates = templates, on_pre_refile = on_pre_refile, on_post_refile = on_post_refile, - on_cancel_refile = function() resolve(nil) end, + on_cancel_refile = function() + resolve(nil) + end, }) return capture:prompt() @@ -417,7 +434,9 @@ local function roam_insert(roam, opts) end_col = opts.ranges[i].end_col -- No -1 because this is exclusive -- Don't remove the first range as we will replace instead - if i == 1 then break end + if i == 1 then + break + end -- Clear the text of this range vim.api.nvim_buf_set_text(bufnr, start_row, start_col, end_row, end_col, {}) @@ -434,11 +453,12 @@ local function roam_insert(roam, opts) end return Promise.new(function(resolve) - roam.ui.select_node({ - allow_select_missing = true, - auto_select = opts.immediate, - init_input = opts.title, - }) + roam.ui + .select_node({ + allow_select_missing = true, + auto_select = opts.immediate, + init_input = opts.title, + }) :on_choice(function(choice) insert_link(choice.id, choice.label) resolve(choice.id) @@ -492,10 +512,11 @@ local function roam_find(roam, opts) end return Promise.new(function(resolve) - roam.ui.select_node({ - allow_select_missing = true, - init_input = opts.title, - }) + roam.ui + .select_node({ + allow_select_missing = true, + init_input = opts.title, + }) :on_choice(function(choice) visit_node(choice.id) resolve(choice.id) diff --git a/lua/org-roam/api/origin.lua b/lua/org-roam/api/origin.lua index 1489d23..169c75c 100644 --- a/lua/org-roam/api/origin.lua +++ b/lua/org-roam/api/origin.lua @@ -16,34 +16,44 @@ local function roam_add_origin(roam, opts) opts = opts or {} return Promise.new(function(resolve) utils.node_under_cursor(function(node) - if not node then return resolve(false) end - - roam.database:load_file({ path = node.file }):next(function(results) - -- Get the OrgFile instance - local file = results.file - - -- Look for a file or headline that matches our node - local entry = utils.find_id_match(file, node.id) - - if entry and opts.origin then - entry:set_property(ORIGIN_PROP_NAME, opts.origin) - resolve(true) - elseif entry then - -- If no origin specified, we load up a selection dialog - -- to pick a node other than the current one - roam.ui.select_node({ exclude = { node.id } }) - :on_choice(function(choice) - entry:set_property(ORIGIN_PROP_NAME, choice.id) - resolve(true) - end) - :on_cancel(function() resolve(false) end) - :open() - else + if not node then + return resolve(false) + end + + roam.database + :load_file({ path = node.file }) + :next(function(results) + -- Get the OrgFile instance + local file = results.file + + -- Look for a file or headline that matches our node + local entry = utils.find_id_match(file, node.id) + + if entry and opts.origin then + entry:set_property(ORIGIN_PROP_NAME, opts.origin) + resolve(true) + elseif entry then + -- If no origin specified, we load up a selection dialog + -- to pick a node other than the current one + roam.ui + .select_node({ exclude = { node.id } }) + :on_choice(function(choice) + entry:set_property(ORIGIN_PROP_NAME, choice.id) + resolve(true) + end) + :on_cancel(function() + resolve(false) + end) + :open() + else + resolve(false) + end + + return file + end) + :catch(function() resolve(false) - end - - return file - end):catch(function() resolve(false) end) + end) end) end) end @@ -58,16 +68,20 @@ local function roam_goto_prev_node(roam, opts) return Promise.new(function(resolve) ---@param node org-roam.core.file.Node|nil local function goto_node(node) - if not node then return resolve(nil) end + if not node then + return resolve(nil) + end utils.goto_node({ node = node, win = winnr }) resolve(node.id) end utils.node_under_cursor(function(node) - if not node or not node.origin then return resolve(nil) end - roam.database:get(node.origin) - :next(goto_node) - :catch(function() resolve(nil) end) + if not node or not node.origin then + return resolve(nil) + end + roam.database:get(node.origin):next(goto_node):catch(function() + resolve(nil) + end) end, { win = winnr }) end) end @@ -82,13 +96,17 @@ local function roam_goto_next_node(roam, opts) return Promise.new(function(resolve) ---@param node org-roam.core.file.Node|nil local function goto_node(node) - if not node then return resolve(nil) end + if not node then + return resolve(nil) + end utils.goto_node({ node = node, win = winnr }) resolve(node.id) end utils.node_under_cursor(function(node) - if not node then return resolve(nil) end + if not node then + return resolve(nil) + end roam.database:find_nodes_by_origin(node.id):next(function(nodes) if #nodes == 0 then resolve(nil) @@ -103,13 +121,16 @@ local function roam_goto_next_node(roam, opts) return n.id end, nodes) - roam.ui.select_node({ include = ids }) + roam.ui + .select_node({ include = ids }) :on_choice(function(choice) - roam.database:get(choice.id) - :next(goto_node) - :catch(function() resolve(nil) end) + roam.database:get(choice.id):next(goto_node):catch(function() + resolve(nil) + end) + end) + :on_cancel(function() + resolve(nil) end) - :on_cancel(function() resolve(nil) end) :open() return nodes @@ -123,24 +144,31 @@ end local function roam_remove_origin(roam) return Promise.new(function(resolve) utils.node_under_cursor(function(node) - if not node then return resolve(false) end - - roam.database:load_file({ path = node.file }):next(function(results) - -- Get the OrgFile instance - local file = results.file - - -- Look for a file or headline that matches our node - local entry = utils.find_id_match(file, node.id) - - if entry then - entry:set_property(ORIGIN_PROP_NAME, nil) - resolve(true) - else + if not node then + return resolve(false) + end + + roam.database + :load_file({ path = node.file }) + :next(function(results) + -- Get the OrgFile instance + local file = results.file + + -- Look for a file or headline that matches our node + local entry = utils.find_id_match(file, node.id) + + if entry then + entry:set_property(ORIGIN_PROP_NAME, nil) + resolve(true) + else + resolve(false) + end + + return file + end) + :catch(function() resolve(false) - end - - return file - end):catch(function() resolve(false) end) + end) end) end) end diff --git a/lua/org-roam/core/database.lua b/lua/org-roam/core/database.lua index 14e5947..f0b3574 100644 --- a/lua/org-roam/core/database.lua +++ b/lua/org-roam/core/database.lua @@ -264,7 +264,7 @@ function M:insert(data, opts) -- Do any pending indexing of the node self:reindex({ - nodes = { id } + nodes = { id }, }) -- Increment the changed tick counter @@ -644,7 +644,9 @@ function M:iter_nodes(opts) local MAX_NODES = opts.max_nodes or DEFAULT_MAX_NODES local MAX_DISTANCE = opts.max_distance or DEFAULT_MAX_DISTANCE - local filter = opts.filter or function() return true end + local filter = opts.filter or function() + return true + end ---@type table local visited = {} diff --git a/lua/org-roam/core/file.lua b/lua/org-roam/core/file.lua index 7504949..bebbcf1 100644 --- a/lua/org-roam/core/file.lua +++ b/lua/org-roam/core/file.lua @@ -5,28 +5,28 @@ ------------------------------------------------------------------------------- local IntervalTree = require("org-roam.core.utils.tree") -local Link = require("org-roam.core.file.link") -local Node = require("org-roam.core.file.node") -local Range = require("org-roam.core.file.range") -local utils = require("org-roam.core.file.utils") +local Link = require("org-roam.core.file.link") +local Node = require("org-roam.core.file.node") +local Range = require("org-roam.core.file.range") +local utils = require("org-roam.core.file.utils") -- Cannot serialie `math.huge`. Potentially could use `vim.v.numbermax`, but -- this is a safer and more reliable guarantee of maximum size. -local MAX_NUMBER = 2 ^ 31 +local MAX_NUMBER = 2 ^ 31 -local KEYS = { - DIR_TITLE = "TITLE", +local KEYS = { + DIR_TITLE = "TITLE", PROP_ALIASES = "ROAM_ALIASES", - PROP_ID = "ID", - PROP_ORIGIN = "ROAM_ORIGIN", + PROP_ID = "ID", + PROP_ORIGIN = "ROAM_ORIGIN", } ---@class org-roam.core.File ---@field filename string ---@field links org-roam.core.file.Link[] ---@field nodes table -local M = {} -M.__index = M +local M = {} +M.__index = M ---Creates a new org-roam file. ---@param opts {filename:string, links?:org-roam.core.file.Link[], nodes?:org-roam.core.file.Node[]} @@ -120,21 +120,24 @@ function M:from_org_file(file) table.sort(tags) local origin = trim(file:get_property(KEYS.PROP_ORIGIN)) - table.insert(nodes, Node:new({ - id = id, - origin = origin, - range = Range:new( - { row = 0, column = 0, offset = 0 }, - { row = MAX_NUMBER, column = MAX_NUMBER, offset = MAX_NUMBER } - ), - file = file.filename, - mtime = file.metadata.mtime, - title = trim(file:get_directive(KEYS.DIR_TITLE)), - aliases = utils.parse_property_value(trim(file:get_property(KEYS.PROP_ALIASES)) or ""), - tags = tags, - level = 0, - linked = {}, - })) + table.insert( + nodes, + Node:new({ + id = id, + origin = origin, + range = Range:new( + { row = 0, column = 0, offset = 0 }, + { row = MAX_NUMBER, column = MAX_NUMBER, offset = MAX_NUMBER } + ), + file = file.filename, + mtime = file.metadata.mtime, + title = trim(file:get_directive(KEYS.DIR_TITLE)), + aliases = utils.parse_property_value(trim(file:get_property(KEYS.PROP_ALIASES)) or ""), + tags = tags, + level = 0, + linked = {}, + }) + ) end -- Build up our section-level nodes @@ -150,18 +153,21 @@ function M:from_org_file(file) table.sort(tags) local origin = trim(headline:get_property(KEYS.PROP_ORIGIN)) - table.insert(nodes, Node:new({ - id = id, - origin = origin, - range = Range:from_node(headline.headline:parent()), - file = file.filename, - mtime = file.metadata.mtime, - title = headline:get_title(), - aliases = utils.parse_property_value(trim(headline:get_property(KEYS.PROP_ALIASES)) or ""), - tags = tags, - level = headline:get_level(), - linked = {}, - })) + table.insert( + nodes, + Node:new({ + id = id, + origin = origin, + range = Range:from_node(headline.headline:parent()), + file = file.filename, + mtime = file.metadata.mtime, + title = headline:get_title(), + aliases = utils.parse_property_value(trim(headline:get_property(KEYS.PROP_ALIASES)) or ""), + tags = tags, + level = headline:get_level(), + linked = {}, + }) + ) end end @@ -179,12 +185,15 @@ function M:from_org_file(file) if id and range then -- Figure out the full range from the file and add the link to our list local roam_range = Range:from_org_file_and_range(file, range) - table.insert(links, Link:new({ - kind = "regular", - range = roam_range, - path = link.url:to_string(), - description = link.desc, - })) + table.insert( + links, + Link:new({ + kind = "regular", + range = roam_range, + path = link.url:to_string(), + description = link.desc, + }) + ) -- Figure out the node that contains the link ---@type org-roam.core.file.Node|nil diff --git a/lua/org-roam/core/file/node.lua b/lua/org-roam/core/file/node.lua index 3f6d544..faa5144 100644 --- a/lua/org-roam/core/file/node.lua +++ b/lua/org-roam/core/file/node.lua @@ -142,9 +142,12 @@ function M:hash() tostring(self.level), vim.tbl_map(function(key) ---@param loc org-roam.core.file.Position - return table.concat(vim.tbl_map(function(loc) - return loc.offset - end, self.linked[key]), ",") + return table.concat( + vim.tbl_map(function(loc) + return loc.offset + end, self.linked[key]), + "," + ) end, linked_keys), })) end diff --git a/lua/org-roam/core/file/range.lua b/lua/org-roam/core/file/range.lua index 3c02505..e8162fc 100644 --- a/lua/org-roam/core/file/range.lua +++ b/lua/org-roam/core/file/range.lua @@ -39,10 +39,7 @@ end ---@param range org-roam.core.file.Range ---@return boolean function M:contains(range) - return ( - self.start.offset <= range.start.offset - and self.end_.offset >= range.end_.offset - ) + return (self.start.offset <= range.start.offset and self.end_.offset >= range.end_.offset) end ---Creates a range from a treesitter node. @@ -51,18 +48,15 @@ end function M:from_node(node) local start_row, start_col, start_offset = node:start() local end_row, end_col, end_offset = node:end_() - return M:new( - { - row = start_row, - column = start_col, - offset = start_offset - }, - { - row = end_row, - column = end_col, - offset = end_offset - } - ) + return M:new({ + row = start_row, + column = start_col, + offset = start_offset, + }, { + row = end_row, + column = end_col, + offset = end_offset, + }) end ---Converts from an nvim-orgmode OrgFile and OrgRange into an org-roam Range. @@ -87,7 +81,9 @@ function M:from_org_file_and_range(file, range) -- up until the line we are on for i = 1, range.start_line - 1 do local line = file.lines[i] - if not line then break end + if not line then + break + end start.offset = start.offset + string.len(line) + 1 end @@ -96,7 +92,9 @@ function M:from_org_file_and_range(file, range) -- up until the line we are on for i = 1, range.end_line - 1 do local line = file.lines[i] - if not line then break end + if not line then + break + end end_.offset = end_.offset + string.len(line) + 1 end diff --git a/lua/org-roam/core/file/utils.lua b/lua/org-roam/core/file/utils.lua index 88ea392..ba67814 100644 --- a/lua/org-roam/core/file/utils.lua +++ b/lua/org-roam/core/file/utils.lua @@ -14,7 +14,7 @@ local M = {} ---@return string[] function M.parse_property_value(value) local items = {} - local QUOTE = string.byte("\"") + local QUOTE = string.byte('"') local SPACE = string.byte(" ") local BACKSLASH = string.byte("\\") @@ -23,7 +23,9 @@ function M.parse_property_value(value) ---Adds an item using the current i & j local function add_item() - if i > j then return end + if i > j then + return + end local item = vim.trim(string.sub(value, i, j)) if item ~= "" then table.insert(items, item) @@ -35,10 +37,7 @@ function M.parse_property_value(value) local b = string.byte(value, idx) -- Unescaped quote is a " not preceded by \ - local unescaped_quote = b == QUOTE and ( - idx == 1 - or string.byte(value, idx - 1) ~= BACKSLASH - ) + local unescaped_quote = b == QUOTE and (idx == 1 or string.byte(value, idx - 1) ~= BACKSLASH) if unescaped_quote or (b == SPACE and not within_quote) then add_item() @@ -63,7 +62,7 @@ function M.parse_property_value(value) -- Remove any escaped quotes \" from the items return vim.tbl_map(function(item) - item = string.gsub(item, "\\\"", "\"") + item = string.gsub(item, '\\"', '"') return item end, items) end diff --git a/lua/org-roam/core/log.lua b/lua/org-roam/core/log.lua index e1826cc..2c76a6b 100644 --- a/lua/org-roam/core/log.lua +++ b/lua/org-roam/core/log.lua @@ -63,8 +63,8 @@ local default_config = { modes = { { name = "trace", hl = "Comment" }, { name = "debug", hl = "Comment" }, - { name = "info", hl = "None" }, - { name = "warn", hl = "WarningMsg" }, + { name = "info", hl = "None" }, + { name = "warn", hl = "WarningMsg" }, { name = "error", hl = "ErrorMsg" }, { name = "fatal", hl = "ErrorMsg" }, }, @@ -84,7 +84,7 @@ local default_config = { local nameupper = mode_name:upper() local lineinfo = src_path .. ":" .. src_line if is_console then - return string.format("[%-6s%s] %s: %s", nameupper, os.date "%H:%M:%S", lineinfo, msg) + return string.format("[%-6s%s] %s: %s", nameupper, os.date("%H:%M:%S"), lineinfo, msg) else return string.format("[%-6s%s] %s: %s\n", nameupper, os.date(), lineinfo, msg) end @@ -94,7 +94,6 @@ local default_config = { info_level = nil, } - ---Makes internal functions for logging that we'll use at a higher level. ---@param config org-roam.core.log.Config local function make_internal_logger(config) @@ -185,7 +184,7 @@ local function make_internal_logger(config) end if obj.config.highlights and level_config.hl then - vim.cmd "echohl NONE" + vim.cmd("echohl NONE") end end if obj.config.use_console == "sync" and not vim.in_fast_event() then diff --git a/lua/org-roam/core/ui/buffer.lua b/lua/org-roam/core/ui/buffer.lua index 6607394..b3b83e3 100644 --- a/lua/org-roam/core/ui/buffer.lua +++ b/lua/org-roam/core/ui/buffer.lua @@ -69,10 +69,7 @@ local function make_buffer(opts) assert(bufnr ~= 0, "failed to create buffer") -- Set name to something random (unless specified) - vim.api.nvim_buf_set_name( - bufnr, - opts.name or ("org-roam-" .. random.uuid_v4()) - ) + vim.api.nvim_buf_set_name(bufnr, opts.name or ("org-roam-" .. random.uuid_v4())) -- Clear out all options that we've used explicitly opts.name = nil @@ -96,16 +93,16 @@ function M:new(opts) local instance = {} setmetatable(instance, M) - local offset = opts.offset or 0 - opts.offset = nil + local offset = opts.offset or 0 + opts.offset = nil - instance.__bufnr = make_buffer(opts) - instance.__offset = offset - instance.__namespace = vim.api.nvim_create_namespace(vim.api.nvim_buf_get_name(instance.__bufnr)) - instance.__emitter = Emitter:new() - instance.__state = STATE.IDLE + instance.__bufnr = make_buffer(opts) + instance.__offset = offset + instance.__namespace = vim.api.nvim_create_namespace(vim.api.nvim_buf_get_name(instance.__bufnr)) + instance.__emitter = Emitter:new() + instance.__state = STATE.IDLE instance.__keybindings = { registered = {}, callbacks = {} } - instance.__components = {} + instance.__components = {} return instance end @@ -351,8 +348,7 @@ function M:__apply_lines(ui_lines, force) -- Check if the buffer is empty local cnt = vim.api.nvim_buf_line_count(bufnr) - local is_empty = cnt == 1 - and vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] == "" + local is_empty = cnt == 1 and vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] == "" -- Calculate the starting line for appending and highlights -- NOTE: This should always be at or after the offset! @@ -363,7 +359,9 @@ function M:__apply_lines(ui_lines, force) local offset_lines_needed = self.__offset - cnt if offset_lines_needed > 0 then local lines = {} - for _ = 1, offset_lines_needed do table.insert(lines, "") end + for _ = 1, offset_lines_needed do + table.insert(lines, "") + end vim.api.nvim_buf_set_lines(bufnr, cnt, -1, false, lines) end @@ -460,14 +458,7 @@ function M:__apply_lines(ui_lines, force) -- Apply all highlights for _, hl in ipairs(highlights) do - vim.api.nvim_buf_add_highlight( - self.__bufnr, - self.__namespace, - hl.group, - hl.line, - hl.cstart, - hl.cend - ) + vim.api.nvim_buf_add_highlight(self.__bufnr, self.__namespace, hl.group, hl.line, hl.cstart, hl.cend) end -- Extract out global lazy functions so we don't call them diff --git a/lua/org-roam/core/ui/notify.lua b/lua/org-roam/core/ui/notify.lua index efb0457..a2d923a 100644 --- a/lua/org-roam/core/ui/notify.lua +++ b/lua/org-roam/core/ui/notify.lua @@ -20,11 +20,7 @@ ---@diagnostic disable-next-line:unused-local local function notify(this, msg, level, opts) vim.schedule(function() - vim.notify( - msg, - level, - vim.tbl_extend("force", opts or {}, { title = "org-roam" }) - ) + vim.notify(msg, level, vim.tbl_extend("force", opts or {}, { title = "org-roam" })) end) end diff --git a/lua/org-roam/core/ui/select.lua b/lua/org-roam/core/ui/select.lua index 4be007a..e07ecee 100644 --- a/lua/org-roam/core/ui/select.lua +++ b/lua/org-roam/core/ui/select.lua @@ -180,19 +180,22 @@ function M:new(opts) end local bindings = clean_bindings(opts.bindings or {}) - local format = opts.format or function(item) return tostring(item) end - local match = opts.match or function(item, input) - local text = string.lower(format(item)) - input = string.lower(input) - - -- Get inclusive start/end (one-indexed) - local start, end_ = string.find(text, input, 1, true) - if start and end_ then - return { { start, end_ } } - else - return {} - end + local format = opts.format or function(item) + return tostring(item) end + local match = opts.match + or function(item, input) + local text = string.lower(format(item)) + input = string.lower(input) + + -- Get inclusive start/end (one-indexed) + local start, end_ = string.find(text, input, 1, true) + if start and end_ then + return { { start, end_ } } + else + return {} + end + end instance.__params = { items = opts.items or {}, init_input = opts.init_input or "", @@ -304,7 +307,11 @@ function M:open() winopts = { cursorline = false, }, - components = { function() return self:__render_component() end }, + components = { + function() + return self:__render_component() + end, + }, }) -- If we have some initial filter text, set it on the buffer @@ -403,22 +410,30 @@ function M:open() -- Changing selection (down) for _, lhs in ipairs(self.__params.bindings.down) do - vim.keymap.set("i", lhs, function() self:__select_move_down() end, kopts) + vim.keymap.set("i", lhs, function() + self:__select_move_down() + end, kopts) end -- Changing selection (up) for _, lhs in ipairs(self.__params.bindings.up) do - vim.keymap.set("i", lhs, function() self:__select_move_up() end, kopts) + vim.keymap.set("i", lhs, function() + self:__select_move_up() + end, kopts) end -- Register callback when selecting a choice that exists for _, lhs in ipairs(self.__params.bindings.select) do - vim.keymap.set("i", lhs, function() self:__trigger_selection() end, kopts) + vim.keymap.set("i", lhs, function() + self:__trigger_selection() + end, kopts) end -- Register callback when selecting a choice that does not exist for _, lhs in ipairs(self.__params.bindings.select_missing) do - vim.keymap.set("i", lhs, function() self:__trigger_input_selection() end, kopts) + vim.keymap.set("i", lhs, function() + self:__trigger_input_selection() + end, kopts) end self.__state.window = window @@ -626,8 +641,7 @@ function M:__refresh_filter() local is_initial_input = text == self.__params.init_input local is_nonempty = vim.trim(text) ~= "" local has_one_item = #self.__view.filtered_items == 1 - local use_missing = self.__params.allow_select_missing - and #self.__view.filtered_items == 0 + local use_missing = self.__params.allow_select_missing and #self.__view.filtered_items == 0 if is_nonempty and is_initial_input and (has_one_item or use_missing) then self:__trigger_selection() end @@ -750,8 +764,7 @@ function M:__update_prompt() end -- Create or update the mark - self.__state.prompt_id = vim.api.nvim_buf_set_extmark( - window:bufnr(), window:buffer():namespace(), 0, 0, opts) + self.__state.prompt_id = vim.api.nvim_buf_set_extmark(window:bufnr(), window:buffer():namespace(), 0, 0, opts) end ---@private @@ -774,10 +787,7 @@ end ---@private ---@return integer function M:__view_end() - return math.min( - self.__view.start + self.__view.max_rows - 1, - #self.__view.filtered_items - ) + return math.min(self.__view.start + self.__view.max_rows - 1, #self.__view.filtered_items) end ---@private @@ -825,7 +835,9 @@ function M:__render_component() local raw_item = self.__params.items[item[1]] local matches = self.__params.match(raw_item, input) - table.sort(matches, function(a, b) return a[1] < b[1] end) + table.sort(matches, function(a, b) + return a[1] < b[1] + end) -- Build up our line segments (start, end, highlight) (one-indexed, end-inclusive) ---@type {[1]:integer, [2]:integer, [3]:string} @@ -850,9 +862,12 @@ function M:__render_component() end -- Build our line as a single segment with highlight - table.insert(lines, vim.tbl_map(function(segment) - return C.hl(string.sub(text, segment[1], segment[2]), segment[3]) - end, segments)) + table.insert( + lines, + vim.tbl_map(function(segment) + return C.hl(string.sub(text, segment[1], segment[2]), segment[3]) + end, segments) + ) end return lines diff --git a/lua/org-roam/core/ui/window-picker.lua b/lua/org-roam/core/ui/window-picker.lua index 69669de..14abe56 100644 --- a/lua/org-roam/core/ui/window-picker.lua +++ b/lua/org-roam/core/ui/window-picker.lua @@ -43,7 +43,9 @@ function M:new(opts) instance.__autoselect = opts.autoselect or false instance.__chars = string.lower(opts.chars or DEFAULT_CHARS) instance.__emitter = Emitter:new() - instance.__filter = opts.filter or function() return true end + instance.__filter = opts.filter or function() + return true + end return instance end diff --git a/lua/org-roam/core/ui/window-picker/font.lua b/lua/org-roam/core/ui/window-picker/font.lua index 5791b92..79f8f55 100644 --- a/lua/org-roam/core/ui/window-picker/font.lua +++ b/lua/org-roam/core/ui/window-picker/font.lua @@ -213,77 +213,77 @@ local M = { ███╔╝ ███████╗ ╚══════╝ ]], - ['1'] = [[ + ["1"] = [[ ██╗ ███║ ╚██║ ██║ ██║ ╚═╝ ]], - ['2'] = [[ + ["2"] = [[ ██████╗ ╚════██╗ █████╔╝ ██╔═══╝ ███████╗ ╚══════╝ ]], - ['3'] = [[ + ["3"] = [[ ██████╗ ╚════██╗ █████╔╝ ╚═══██╗ ██████╔╝ ╚═════╝ ]], - ['4'] = [[ + ["4"] = [[ ██╗ ██╗ ██║ ██║ ███████║ ╚════██║ ██║ ╚═╝ ]], - ['5'] = [[ + ["5"] = [[ ███████╗ ██╔════╝ ███████╗ ╚════██║ ███████║ ╚══════╝ ]], - ['6'] = [[ + ["6"] = [[ ██████╗ ██╔════╝ ███████╗ ██╔═══██╗ ╚██████╔╝ ╚═════╝ ]], - ['7'] = [[ + ["7"] = [[ ███████╗ ╚════██║ ██╔╝ ██╔╝ ██║ ╚═╝ ]], - ['8'] = [[ + ["8"] = [[ █████╗ ██╔══██╗ ╚█████╔╝ ██╔══██╗ ╚█████╔╝ ╚════╝ ]], - ['9'] = [[ + ["9"] = [[ █████╗ ██╔══██╗ ╚██████║ ╚═══██║ █████╔╝ ╚════╝ ]], - ['0'] = [[ + ["0"] = [[ ██████╗ ██╔═████╗ ██║██╔██║ ████╔╝██║ ╚██████╔╝ ╚═════╝ ]], - [';'] = [[ + [";"] = [[ ██╗ ╚═╝ ▄█╗ diff --git a/lua/org-roam/core/ui/window-picker/hint.lua b/lua/org-roam/core/ui/window-picker/hint.lua index b1247b7..389ec9e 100644 --- a/lua/org-roam/core/ui/window-picker/hint.lua +++ b/lua/org-roam/core/ui/window-picker/hint.lua @@ -79,12 +79,7 @@ function M.__add_big_char_margin(lines) --left & right padding for _, line in ipairs(lines) do - local new_line = string.format( - "%s%s%s", - string.rep(" ", 2), - line, - string.rep(" ", 2) - ) + local new_line = string.format("%s%s%s", string.rep(" ", 2), line, string.rep(" ", 2)) table.insert(centered_lines, new_line) end diff --git a/lua/org-roam/core/ui/window.lua b/lua/org-roam/core/ui/window.lua index 405c057..33c79ff 100644 --- a/lua/org-roam/core/ui/window.lua +++ b/lua/org-roam/core/ui/window.lua @@ -24,7 +24,7 @@ local OPEN = { bottom = function(rows) rows = rows or 15 return string.format("botright split | resize %s", rows) - end + end, } local EVENTS = { @@ -89,9 +89,7 @@ function M:new(opts) setmetatable(instance, M) -- Create the buffer we will use with the window - instance.__buffer = opts.buffer or Buffer:new(vim.tbl_extend("keep", - opts.bufopts or {}, { name = opts.name } - )) + instance.__buffer = opts.buffer or Buffer:new(vim.tbl_extend("keep", opts.bufopts or {}, { name = opts.name })) -- Apply any components we've been assigned if type(opts.components) == "table" then diff --git a/lua/org-roam/core/utils/async.lua b/lua/org-roam/core/utils/async.lua index 8b87a65..b4552bf 100644 --- a/lua/org-roam/core/utils/async.lua +++ b/lua/org-roam/core/utils/async.lua @@ -95,11 +95,9 @@ function M.wrap(f, opts) f(unpack(args, 1, args.n)) - local success, err = vim.wait( - TIME, - function() return results.done end, - INTERVAL - ) + local success, err = vim.wait(TIME, function() + return results.done + end, INTERVAL) -- If we failed to wait, throw an error based on the code if not success then diff --git a/lua/org-roam/core/utils/emitter.lua b/lua/org-roam/core/utils/emitter.lua index ec778a0..f8a3ef0 100644 --- a/lua/org-roam/core/utils/emitter.lua +++ b/lua/org-roam/core/utils/emitter.lua @@ -29,11 +29,7 @@ local function call_handler(event, handler, ...) local ok, err = pcall(handler, ...) if not ok then vim.schedule(function() - log.fmt_warn( - "org-roam.core.utils.Emitter handler failed for event %s with error %s", - event, - err - ) + log.fmt_warn("org-roam.core.utils.Emitter handler failed for event %s with error %s", event, err) vim.api.nvim_err_writeln(err) end) end diff --git a/lua/org-roam/core/utils/io.lua b/lua/org-roam/core/utils/io.lua index 4f86a8d..2226324 100644 --- a/lua/org-roam/core/utils/io.lua +++ b/lua/org-roam/core/utils/io.lua @@ -55,13 +55,17 @@ function M.write_file(path, data) return Promise.new(function(resolve, reject) uv.fs_open(path, "w", DEFAULT_FILE_PERMISSIONS, function(err, fd) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end ---@cast fd -nil uv.fs_write(fd, data, -1, function(err) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end -- Force writing of data to avoid situations where @@ -69,15 +73,21 @@ function M.write_file(path, data) -- the old file contents uv.fs_fsync(fd, function(err) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end uv.fs_close(fd, function(err) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end - vim.schedule(function() resolve(nil) end) + vim.schedule(function() + resolve(nil) + end) end) end) end) @@ -107,27 +117,37 @@ function M.read_file(path) return Promise.new(function(resolve, reject) uv.fs_open(path, "r", 0, function(err, fd) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end ---@cast fd -nil uv.fs_fstat(fd, function(err, stat) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end ---@cast stat -nil uv.fs_read(fd, stat.size, 0, function(err, data) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end uv.fs_close(fd, function(err) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end - vim.schedule(function() resolve(data) end) + vim.schedule(function() + resolve(data) + end) end) end) end) @@ -167,10 +187,14 @@ function M.stat(path) return Promise.new(function(resolve, reject) uv.fs_stat(path, function(err, stat) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end - vim.schedule(function() resolve(stat) end) + vim.schedule(function() + resolve(stat) + end) end) end) end @@ -203,10 +227,14 @@ function M.unlink(path) return Promise.new(function(resolve, reject) uv.fs_unlink(path, function(err, success) if err then - return vim.schedule(function() reject(err) end) + return vim.schedule(function() + reject(err) + end) end - vim.schedule(function() resolve(success) end) + vim.schedule(function() + resolve(success) + end) end) end) end @@ -256,10 +284,10 @@ function M.walk(path, opts) entry_path = path_utils.normalize(entry_path, { expand_env = true }) return { - name = name, + name = name, filename = vim.fs.basename(name), - path = entry_path, - type = type, + path = entry_path, + type = type, } end end diff --git a/lua/org-roam/core/utils/profiler.lua b/lua/org-roam/core/utils/profiler.lua index 13f6e55..29d4af2 100644 --- a/lua/org-roam/core/utils/profiler.lua +++ b/lua/org-roam/core/utils/profiler.lua @@ -101,16 +101,9 @@ function M:print_as_string(opts) os.date("%T", recording[2]) ) elseif self:recording_cnt() == 0 then - return string.format( - "[%s] No recording available", - self.__label - ) + return string.format("[%s] No recording available", self.__label) else - return string.format( - "[%s] Invalid recording (%s)", - self.__label, - opts.recording - ) + return string.format("[%s] Invalid recording (%s)", self.__label, opts.recording) end end end @@ -140,7 +133,9 @@ function M:time_taken(opts) end -- Take the average - if cnt > 0 then total_in_secs = math.floor(total_in_secs / cnt) end + if cnt > 0 then + total_in_secs = math.floor(total_in_secs / cnt) + end else assert(self:recording_cnt() > 0, "no recording available") local recording = assert(self:recording(opts.recording), "invalid recording") diff --git a/lua/org-roam/core/utils/random.lua b/lua/org-roam/core/utils/random.lua index 6a0e82f..dd0c2ea 100644 --- a/lua/org-roam/core/utils/random.lua +++ b/lua/org-roam/core/utils/random.lua @@ -14,7 +14,7 @@ local seeded = false function M.random(m, n) if seeded == false then -- https://www.lua-users.org/wiki/MathLibraryTutorial - math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,6))) + math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 6))) seeded = true end return math.random(m, n) diff --git a/lua/org-roam/core/utils/table.lua b/lua/org-roam/core/utils/table.lua index 7621bca..bc02f87 100644 --- a/lua/org-roam/core/utils/table.lua +++ b/lua/org-roam/core/utils/table.lua @@ -51,7 +51,7 @@ function M.get(o, ...) o = o[k] if o == nil then return nil - elseif type(o) ~= 'table' and next(keys, i) then + elseif type(o) ~= "table" and next(keys, i) then return nil end end diff --git a/lua/org-roam/core/utils/tree.lua b/lua/org-roam/core/utils/tree.lua index 6d2f63e..6e89ad6 100644 --- a/lua/org-roam/core/utils/tree.lua +++ b/lua/org-roam/core/utils/tree.lua @@ -275,11 +275,7 @@ end ---@param opts? org-roam.core.utils.tree.FindOpts ---@return org-roam.core.utils.IntervalTree|nil function M:find_first(opts) - local nodes = self:find_all(vim.tbl_extend( - "keep", - { limit = 1 }, - opts or {} - )) + local nodes = self:find_all(vim.tbl_extend("keep", { limit = 1 }, opts or {})) return nodes[1] end @@ -402,16 +398,9 @@ function M:to_string(opts) local data = map(self.data) local max = opts.max - local s = string.format( - "[%s,%s] \"%s\"", - self._start, - self._end, - max and string.sub(data, 1, max) or data - ) + local s = string.format('[%s,%s] "%s"', self._start, self._end, max and string.sub(data, 1, max) or data) if self._depth > 1 then - s = string.rep(" ", (self._depth - 2) * 2) - .. "┗━ " - .. s + s = string.rep(" ", (self._depth - 2) * 2) .. "┗━ " .. s end if self.left then diff --git a/lua/org-roam/core/utils/uri.lua b/lua/org-roam/core/utils/uri.lua index d14b7ba..62bf748 100644 --- a/lua/org-roam/core/utils/uri.lua +++ b/lua/org-roam/core/utils/uri.lua @@ -156,11 +156,7 @@ function M:query_params(opts) ---@type {[string]: string} query_table = {} - local PATTERN = string.format( - "([^%s=]+)=([^%s=]*)", - delimiter, - delimiter - ) + local PATTERN = string.format("([^%s=]+)=([^%s=]*)", delimiter, delimiter) for key, value in string.gmatch(self.query, PATTERN) do query_table[key] = value end diff --git a/lua/org-roam/core/utils/utf8.lua b/lua/org-roam/core/utils/utf8.lua index 75dea29..06ff7df 100644 --- a/lua/org-roam/core/utils/utf8.lua +++ b/lua/org-roam/core/utils/utf8.lua @@ -90,19 +90,11 @@ local function utf8charbytes(s, i) i = i or 1 -- argument checking - if type(s) ~= 'string' then - error( - "bad argument #1 to 'utf8charbytes' (string expected, got " - .. type(s) - .. ')' - ) + if type(s) ~= "string" then + error("bad argument #1 to 'utf8charbytes' (string expected, got " .. type(s) .. ")") end - if type(i) ~= 'number' then - error( - "bad argument #2 to 'utf8charbytes' (number expected, got " - .. type(i) - .. ')' - ) + if type(i) ~= "number" then + error("bad argument #2 to 'utf8charbytes' (number expected, got " .. type(i) .. ")") end local c = byte(s, i) @@ -117,12 +109,12 @@ local function utf8charbytes(s, i) local c2 = byte(s, i + 1) if not c2 then - error('UTF-8 string terminated early') + error("UTF-8 string terminated early") end -- validate byte 2 if c2 < 128 or c2 > 191 then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") end return 2 @@ -132,21 +124,21 @@ local function utf8charbytes(s, i) local c3 = byte(s, i + 2) if not c2 or not c3 then - error('UTF-8 string terminated early') + error("UTF-8 string terminated early") end -- validate byte 2 if c == 224 and (c2 < 160 or c2 > 191) then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") elseif c == 237 and (c2 < 128 or c2 > 159) then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") elseif c2 < 128 or c2 > 191 then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") end -- validate byte 3 if c3 < 128 or c3 > 191 then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") end return 3 @@ -157,46 +149,42 @@ local function utf8charbytes(s, i) local c4 = byte(s, i + 3) if not c2 or not c3 or not c4 then - error('UTF-8 string terminated early') + error("UTF-8 string terminated early") end -- validate byte 2 if c == 240 and (c2 < 144 or c2 > 191) then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") elseif c == 244 and (c2 < 128 or c2 > 143) then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") elseif c2 < 128 or c2 > 191 then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") end -- validate byte 3 if c3 < 128 or c3 > 191 then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") end -- validate byte 4 if c4 < 128 or c4 > 191 then - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") end return 4 else - error('Invalid UTF-8 character') + error("Invalid UTF-8 character") end end -- returns the number of characters in a UTF-8 string local function utf8len(s) -- argument checking - if type(s) ~= 'string' then + if type(s) ~= "string" then for k, v in pairs(s) do print('"', tostring(k), '"', tostring(v), '"') end - error( - "bad argument #1 to 'utf8len' (string expected, got " - .. type(s) - .. ')' - ) + error("bad argument #1 to 'utf8len' (string expected, got " .. type(s) .. ")") end local pos = 1 @@ -228,7 +216,7 @@ local function utf8sub(s, i, j) -- can't have start before end! if startChar > endChar then - return '' + return "" end -- byte offsets to pass to string.sub @@ -302,18 +290,14 @@ end -- identical to string.reverse except that it supports UTF-8 local function utf8reverse(s) -- argument checking - if type(s) ~= 'string' then - error( - "bad argument #1 to 'utf8reverse' (string expected, got " - .. type(s) - .. ')' - ) + if type(s) ~= "string" then + error("bad argument #1 to 'utf8reverse' (string expected, got " .. type(s) .. ")") end local bytes = len(s) local pos = bytes local charbytes - local newstr = '' + local newstr = "" while pos > 0 do local c = byte(s, pos) @@ -365,7 +349,7 @@ local function utf8char(unicode) return char(Byte0, Byte1, Byte2, Byte3) end - error('Unicode cannot be greater than U+10FFFF!') + error("Unicode cannot be greater than U+10FFFF!") end local shift_6 = 2 ^ 6 @@ -408,8 +392,7 @@ utf8unicode = function(str, i, j, byte_pos) end if bytes == 4 then local byte0, byte1, byte2, byte3 = byte(ch, 1, 4) - local code0, code1, code2, code3 = - byte0 - 0xF0, byte1 - 0x80, byte2 - 0x80, byte3 - 0x80 + local code0, code1, code2, code3 = byte0 - 0xF0, byte1 - 0x80, byte2 - 0x80, byte3 - 0x80 unicode = code0 * shift_18 + code1 * shift_12 + code2 * shift_6 + code3 end @@ -477,41 +460,38 @@ local function classMatchGenerator(class, plain) for c, _, be in it do skip = be if not ignore and not plain then - if c == '%' then + if c == "%" then ignore = true - elseif c == '-' then + elseif c == "-" then table.insert(codes, utf8unicode(c)) range = true - elseif c == '^' then + elseif c == "^" then if not firstletter then - error('!!!') + error("!!!") else unmatch = true end - elseif c == ']' then + elseif c == "]" then break else if not range then table.insert(codes, utf8unicode(c)) else table.remove(codes) -- removing '-' - table.insert( - ranges, - { table.remove(codes), utf8unicode(c) } - ) + table.insert(ranges, { table.remove(codes), utf8unicode(c) }) range = false end end elseif ignore and not plain then - if c == 'a' then -- %a: represents all letters. (ONLY ASCII) - table.insert(ranges, { 65, 90 }) -- A - Z + if c == "a" then -- %a: represents all letters. (ONLY ASCII) + table.insert(ranges, { 65, 90 }) -- A - Z table.insert(ranges, { 97, 122 }) -- a - z - elseif c == 'c' then -- %c: represents all control characters. + elseif c == "c" then -- %c: represents all control characters. table.insert(ranges, { 0, 31 }) table.insert(codes, 127) - elseif c == 'd' then -- %d: represents all digits. + elseif c == "d" then -- %d: represents all digits. table.insert(ranges, { 48, 57 }) -- 0 - 9 - elseif c == 'g' then -- %g: represents all printable characters except space. + elseif c == "g" then -- %g: represents all printable characters except space. table.insert(ranges, { 1, 8 }) table.insert(ranges, { 14, 31 }) table.insert(ranges, { 33, 132 }) @@ -522,14 +502,14 @@ local function classMatchGenerator(class, plain) table.insert(ranges, { 8234, 8238 }) table.insert(ranges, { 8240, 8286 }) table.insert(ranges, { 8288, 12287 }) - elseif c == 'l' then -- %l: represents all lowercase letters. (ONLY ASCII) + elseif c == "l" then -- %l: represents all lowercase letters. (ONLY ASCII) table.insert(ranges, { 97, 122 }) -- a - z - elseif c == 'p' then -- %p: represents all punctuation characters. (ONLY ASCII) + elseif c == "p" then -- %p: represents all punctuation characters. (ONLY ASCII) table.insert(ranges, { 33, 47 }) table.insert(ranges, { 58, 64 }) table.insert(ranges, { 91, 96 }) table.insert(ranges, { 123, 126 }) - elseif c == 's' then -- %s: represents all space characters. + elseif c == "s" then -- %s: represents all space characters. table.insert(ranges, { 9, 13 }) table.insert(codes, 32) table.insert(codes, 133) @@ -541,25 +521,22 @@ local function classMatchGenerator(class, plain) table.insert(codes, 8239) table.insert(codes, 8287) table.insert(codes, 12288) - elseif c == 'u' then -- %u: represents all uppercase letters. (ONLY ASCII) - table.insert(ranges, { 65, 90 }) -- A - Z - elseif c == 'w' then -- %w: represents all alphanumeric characters. (ONLY ASCII) - table.insert(ranges, { 48, 57 }) -- 0 - 9 - table.insert(ranges, { 65, 90 }) -- A - Z + elseif c == "u" then -- %u: represents all uppercase letters. (ONLY ASCII) + table.insert(ranges, { 65, 90 }) -- A - Z + elseif c == "w" then -- %w: represents all alphanumeric characters. (ONLY ASCII) + table.insert(ranges, { 48, 57 }) -- 0 - 9 + table.insert(ranges, { 65, 90 }) -- A - Z table.insert(ranges, { 97, 122 }) -- a - z - elseif c == 'x' then -- %x: represents all hexadecimal digits. - table.insert(ranges, { 48, 57 }) -- 0 - 9 - table.insert(ranges, { 65, 70 }) -- A - F + elseif c == "x" then -- %x: represents all hexadecimal digits. + table.insert(ranges, { 48, 57 }) -- 0 - 9 + table.insert(ranges, { 65, 70 }) -- A - F table.insert(ranges, { 97, 102 }) -- a - f else if not range then table.insert(codes, utf8unicode(c)) else table.remove(codes) -- removing '-' - table.insert( - ranges, - { table.remove(codes), utf8unicode(c) } - ) + table.insert(ranges, { table.remove(codes), utf8unicode(c) }) range = false end end @@ -590,14 +567,12 @@ local function classMatchGenerator(class, plain) end if not unmatch then return function(charCode) - return binsearch(codes, charCode) or inRanges(charCode) - end, - skip + return binsearch(codes, charCode) or inRanges(charCode) + end, skip else return function(charCode) - return charCode ~= -1 - and not (binsearch(codes, charCode) or inRanges(charCode)) - end, + return charCode ~= -1 and not (binsearch(codes, charCode) or inRanges(charCode)) + end, skip end end @@ -648,10 +623,10 @@ end ]] local cache = setmetatable({}, { - __mode = 'kv', + __mode = "kv", }) local cachePlain = setmetatable({}, { - __mode = 'kv', + __mode = "kv", }) local function matcherGenerator(regex, plain) local matcher = { @@ -704,11 +679,7 @@ local function matcherGenerator(regex, plain) local function capture(id) return function(_) local l = matcher.captures[id][2] - matcher.captures[id][1] - local captured = utf8sub( - matcher.string, - matcher.captures[id][1], - matcher.captures[id][2] - ) + local captured = utf8sub(matcher.string, matcher.captures[id][1], matcher.captures[id][2]) local check = utf8sub(matcher.string, matcher.str, matcher.str + l) if captured == check then for _ = 0, l do @@ -739,24 +710,24 @@ local function matcherGenerator(regex, plain) local skip = len(bc) + len(ec) bc, ec = utf8unicode(bc), utf8unicode(ec) return function(cC) - if cC == ec and sum > 0 then - sum = sum - 1 - if sum == 0 then - matcher:nextFunc() - end - matcher:nextStr() - elseif cC == bc then - sum = sum + 1 - matcher:nextStr() + if cC == ec and sum > 0 then + sum = sum - 1 + if sum == 0 then + matcher:nextFunc() + end + matcher:nextStr() + elseif cC == bc then + sum = sum + 1 + matcher:nextStr() + else + if sum == 0 or cC == -1 then + sum = 0 + matcher:reset() else - if sum == 0 or cC == -1 then - sum = 0 - matcher:reset() - else - matcher:nextStr() - end + matcher:nextStr() end - end, + end + end, skip end @@ -764,10 +735,7 @@ local function matcherGenerator(regex, plain) matcher:fullResetOnNextStr() matcher.seqStart = matcher.str matcher:nextFunc() - if - (matcher.str > matcher.startStr and matcher.fromStart) - or matcher.str >= matcher.stringLen - then + if (matcher.str > matcher.startStr and matcher.fromStart) or matcher.str >= matcher.stringLen then matcher.stop = true matcher.seqStart = nil end @@ -786,19 +754,16 @@ local function matcherGenerator(regex, plain) for c, bs, be in it do skip = nil if plain then - table.insert( - matcher.functions, - simple(classMatchGenerator(c, plain)) - ) + table.insert(matcher.functions, simple(classMatchGenerator(c, plain))) else if ignore then - if find('123456789', c, 1, true) then + if find("123456789", c, 1, true) then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) lastFunc = nil end table.insert(matcher.functions, capture(tonumber(c))) - elseif c == 'b' then + elseif c == "b" then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) lastFunc = nil @@ -807,57 +772,57 @@ local function matcherGenerator(regex, plain) b, skip = balancer(sub(regex, be + 1, be + 9)) table.insert(matcher.functions, b) else - lastFunc = classMatchGenerator('%' .. c) + lastFunc = classMatchGenerator("%" .. c) end ignore = false else - if c == '*' then + if c == "*" then if lastFunc then table.insert(matcher.functions, star(lastFunc)) lastFunc = nil else - error('invalid regex after ' .. sub(regex, 1, bs)) + error("invalid regex after " .. sub(regex, 1, bs)) end - elseif c == '+' then + elseif c == "+" then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) table.insert(matcher.functions, star(lastFunc)) lastFunc = nil else - error('invalid regex after ' .. sub(regex, 1, bs)) + error("invalid regex after " .. sub(regex, 1, bs)) end - elseif c == '-' then + elseif c == "-" then if lastFunc then table.insert(matcher.functions, minus(lastFunc)) lastFunc = nil else - error('invalid regex after ' .. sub(regex, 1, bs)) + error("invalid regex after " .. sub(regex, 1, bs)) end - elseif c == '?' then + elseif c == "?" then if lastFunc then table.insert(matcher.functions, question(lastFunc)) lastFunc = nil else - error('invalid regex after ' .. sub(regex, 1, bs)) + error("invalid regex after " .. sub(regex, 1, bs)) end - elseif c == '^' then + elseif c == "^" then if bs == 1 then matcher.fromStart = true else - error('invalid regex after ' .. sub(regex, 1, bs)) + error("invalid regex after " .. sub(regex, 1, bs)) end - elseif c == '$' then + elseif c == "$" then if be == len(regex) then matcher.toEnd = true else - error('invalid regex after ' .. sub(regex, 1, bs)) + error("invalid regex after " .. sub(regex, 1, bs)) end - elseif c == '[' then + elseif c == "[" then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) end lastFunc, skip = classMatchGenerator(sub(regex, be + 1)) - elseif c == '(' then + elseif c == "(" then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) lastFunc = nil @@ -865,10 +830,10 @@ local function matcherGenerator(regex, plain) table.insert(matcher.captures, {}) table.insert(cs, #matcher.captures) table.insert(matcher.functions, captureStart(cs[#cs])) - if sub(regex, be + 1, be + 1) == ')' then + if sub(regex, be + 1, be + 1) == ")" then matcher.captures[#matcher.captures].empty = true end - elseif c == ')' then + elseif c == ")" then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) lastFunc = nil @@ -878,14 +843,14 @@ local function matcherGenerator(regex, plain) error('invalid capture: "(" missing') end table.insert(matcher.functions, captureStop(cap)) - elseif c == '.' then + elseif c == "." then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) end lastFunc = function(cC) return cC ~= -1 end - elseif c == '%' then + elseif c == "%" then ignore = true else if lastFunc then @@ -1018,7 +983,7 @@ end -- string.gmatch local function utf8gmatch(str, regex, all) - regex = (utf8sub(regex, 1, 1) ~= '^') and regex or '%' .. regex + regex = (utf8sub(regex, 1, 1) ~= "^") and regex or "%" .. regex local lastChar = 1 return function() local found = { utf8find(str, regex, lastChar) } @@ -1033,13 +998,13 @@ local function utf8gmatch(str, regex, all) end local function replace(repl, args) - local ret = '' - if type(repl) == 'string' then + local ret = "" + if type(repl) == "string" then local ignore = false local num for c in utf8gensub(repl) do if not ignore then - if c == '%' then + if c == "%" then ignore = true else ret = ret .. c @@ -1054,13 +1019,13 @@ local function replace(repl, args) ignore = false end end - elseif type(repl) == 'table' then - ret = repl[args[1] or args[0]] or '' - elseif type(repl) == 'function' then + elseif type(repl) == "table" then + ret = repl[args[1] or args[0]] or "" + elseif type(repl) == "function" then if #args > 0 then - ret = repl(unpack(args, 1)) or '' + ret = repl(unpack(args, 1)) or "" else - ret = repl(args[0]) or '' + ret = repl(args[0]) or "" end end return ret @@ -1068,14 +1033,13 @@ end -- string.gsub local function utf8gsub(str, regex, repl, limit) limit = limit or -1 - local ret = '' + local ret = "" local prevEnd = 1 local it = utf8gmatch(str, regex, true) local found = { it() } local n = 0 while #found > 0 and limit ~= n do - local args = - { [0] = utf8sub(str, found[1], found[2]), unpack(found, 3) } + local args = { [0] = utf8sub(str, found[1], found[2]), unpack(found, 3) } ret = ret .. utf8sub(str, prevEnd, found[1] - 1) .. replace(repl, args) prevEnd = found[2] + 1 n = n + 1 diff --git a/lua/org-roam/database.lua b/lua/org-roam/database.lua index ea76661..8cadaf5 100644 --- a/lua/org-roam/database.lua +++ b/lua/org-roam/database.lua @@ -40,8 +40,7 @@ function M:__index(key) -- Check the fields of the table, then the metatable -- of the table which includes methods defined below - local self_value = rawget(self, key) - or rawget(getmetatable(self) or {}, key) + local self_value = rawget(self, key) or rawget(getmetatable(self) or {}, key) if self_value ~= nil then return self_value end @@ -121,43 +120,49 @@ end ---@return OrgPromise<{database:org-roam.core.Database, files:OrgFiles}> function M:load(opts) opts = opts or {} - log.fmt_debug("loading all files into database (force=%s)", - opts.force or false) + log.fmt_debug("loading all files into database (force=%s)", opts.force or false) local profiler = Profiler:new({ label = "org-roam-load" }) local rec_id = profiler:start() - return self:__get_loader():load({ - force = opts.force, - }):next(function(...) - profiler:stop(rec_id) - log.fmt_debug("loading all files into database took %s", - profiler:time_taken_as_string({ recording = rec_id })) + return self:__get_loader() + :load({ + force = opts.force, + }) + :next(function(...) + profiler:stop(rec_id) + log.fmt_debug( + "loading all files into database took %s", + profiler:time_taken_as_string({ recording = rec_id }) + ) - return ... - end) + return ... + end) end ---@param opts {path:string, force?:boolean} ---@return OrgPromise<{file:OrgFile, nodes:org-roam.core.file.Node[]}> function M:load_file(opts) - log.fmt_debug("loading %s into database (force=%s)", - opts.path, opts.force or false) + log.fmt_debug("loading %s into database (force=%s)", opts.path, opts.force or false) local profiler = Profiler:new({ label = "org-roam-load-file" }) local rec_id = profiler:start() - return self:__get_loader():load_file({ - path = opts.path, - force = opts.force, - }):next(function(...) - profiler:stop(rec_id) - log.fmt_debug("loading %s into database took %s", - opts.path, - profiler:time_taken_as_string({ recording = rec_id })) + return self:__get_loader() + :load_file({ + path = opts.path, + force = opts.force, + }) + :next(function(...) + profiler:stop(rec_id) + log.fmt_debug( + "loading %s into database took %s", + opts.path, + profiler:time_taken_as_string({ recording = rec_id }) + ) - return ... - end) + return ... + end) end ---Saves the database to disk. @@ -177,8 +182,10 @@ function M:save(opts) -- If our last save was recent enough, do not actually save if not opts.force and self.__last_save >= db:changed_tick() then profiler:stop(rec_id) - log.fmt_debug("saving database took %s (nothing to save)", - profiler:time_taken_as_string({ recording = rec_id })) + log.fmt_debug( + "saving database took %s (nothing to save)", + profiler:time_taken_as_string({ recording = rec_id }) + ) return Promise.resolve(false) end @@ -186,8 +193,7 @@ function M:save(opts) return self:load():next(function() return db:write_to_disk(self.__database_path):next(function() profiler:stop(rec_id) - log.fmt_debug("saving database took %s", - profiler:time_taken_as_string({ recording = rec_id })) + log.fmt_debug("saving database took %s", profiler:time_taken_as_string({ recording = rec_id })) self.__last_save = db:changed_tick() return true @@ -200,16 +206,20 @@ end ---@return OrgPromise function M:delete_disk_cache() return Promise.new(function(resolve, reject) - io.stat(self.__database_path):next(function() - return io.unlink(self.__database_path):next(function(success) - resolve(success) - return success - end):catch(function(err) - reject(err) + io.stat(self.__database_path) + :next(function() + return io.unlink(self.__database_path) + :next(function(success) + resolve(success) + return success + end) + :catch(function(err) + reject(err) + end) + end) + :catch(function() + resolve(false) end) - end):catch(function() - resolve(false) - end) end) end diff --git a/lua/org-roam/database/loader.lua b/lua/org-roam/database/loader.lua index f64e038..46ab506 100644 --- a/lua/org-roam/database/loader.lua +++ b/lua/org-roam/database/loader.lua @@ -4,21 +4,21 @@ -- Core logic to load all components of the database. ------------------------------------------------------------------------------- -local Database = require("org-roam.core.database") -local File = require("org-roam.core.file") -local io = require("org-roam.core.utils.io") +local Database = require("org-roam.core.database") +local File = require("org-roam.core.file") +local io = require("org-roam.core.utils.io") local join_path = require("org-roam.core.utils.path").join -local log = require("org-roam.core.log") -local OrgFiles = require("orgmode.files") -local Promise = require("orgmode.utils.promise") -local schema = require("org-roam.database.schema") +local log = require("org-roam.core.log") +local OrgFiles = require("orgmode.files") +local Promise = require("orgmode.utils.promise") +local schema = require("org-roam.database.schema") ---@class org-roam.database.Loader ---@field path {database:string, files:string[]} ---@field __db org-roam.core.Database #cache of loaded database ---@field __files OrgFiles #cache of loaded org files -local M = {} -M.__index = M +local M = {} +M.__index = M ---Creates a new org-roam database loader. ---@param opts {database:string, files:string|string[]} @@ -172,9 +172,7 @@ local function insert_new_file_into_database(db, file, opts) -- -- I'm not sure if this is needed. We may never encounter -- this situation, but I'm leaving it in for now. - local has_file = not vim.tbl_isempty( - db:find_by_index(schema.FILE, file.filename) - ) + local has_file = not vim.tbl_isempty(db:find_by_index(schema.FILE, file.filename)) if has_file then return modify_file_in_database(db, file, opts) end @@ -217,21 +215,21 @@ function M:load(opts) -- Left-only means deleted -- Right-only means new -- Both means modified - local filenames = find_distinct( - db:iter_index_keys(schema.FILE):collect(), - files:filenames() - ) + local filenames = find_distinct(db:iter_index_keys(schema.FILE):collect(), files:filenames()) local promises = { remove = {}, insert = {}, modify = {} } -- For each deleted file, remove from database for _, filename in ipairs(filenames.left) do - table.insert(promises.remove, Promise.new(function(resolve) - vim.schedule(function() - log.fmt_debug("removing from database: %s", filename) - resolve(remove_file_from_database(db, filename)) + table.insert( + promises.remove, + Promise.new(function(resolve) + vim.schedule(function() + log.fmt_debug("removing from database: %s", filename) + resolve(remove_file_from_database(db, filename)) + end) end) - end)) + ) end -- For each new file, insert into database @@ -245,16 +243,19 @@ function M:load(opts) local maybe_file = files.all_files[filename] local changedtick = maybe_file and maybe_file.metadata.changedtick or 0 - table.insert(promises.insert, files:load_file(filename):next(function(file) - if file then - log.fmt_debug("inserting into database: %s", file.filename) - return insert_new_file_into_database(db, file, { - force = force_modify or file.metadata.changedtick ~= changedtick, - }) - else - return 0 - end - end)) + table.insert( + promises.insert, + files:load_file(filename):next(function(file) + if file then + log.fmt_debug("inserting into database: %s", file.filename) + return insert_new_file_into_database(db, file, { + force = force_modify or file.metadata.changedtick ~= changedtick, + }) + else + return 0 + end + end) + ) end -- For each modified file, check the modified time (any node will do) @@ -269,22 +270,31 @@ function M:load(opts) local maybe_file = files.all_files[filename] local changedtick = maybe_file and maybe_file.metadata.changedtick or 0 - table.insert(promises.modify, files:load_file(filename):next(function(file) - if file then - log.fmt_debug("modifying in database: %s", file.filename) - return modify_file_in_database(db, file, { - force = force_modify or file.metadata.changedtick ~= changedtick, - }) - else - return 0 - end - end)) + table.insert( + promises.modify, + files:load_file(filename):next(function(file) + if file then + log.fmt_debug("modifying in database: %s", file.filename) + return modify_file_in_database(db, file, { + force = force_modify or file.metadata.changedtick ~= changedtick, + }) + else + return 0 + end + end) + ) end return Promise.all(promises.remove) - :next(function() return Promise.all(promises.insert) end) - :next(function() return Promise.all(promises.modify) end) - :next(function() return { database = db, files = files } end) + :next(function() + return Promise.all(promises.insert) + end) + :next(function() + return Promise.all(promises.modify) + end) + :next(function() + return { database = db, files = files } + end) end) end @@ -315,38 +325,39 @@ function M:load_file(opts) -- This both loads the file and adds it to our file path if not there already return Promise.new(function(resolve, reject) - files:add_to_paths(opts.path):next(function(file) - -- If false, means failed to add the file - if not file then - reject("invalid path to org file: " .. opts.path) - return file - end - - -- Determine if the file already exists through nodes in the db - local ids = db:find_by_index(schema.FILE, file.filename) - local has_file = not vim.tbl_isempty(ids) - - if has_file then - log.fmt_debug("modifying in database: %s", file.filename) - modify_file_in_database(db, file, { - force = opts.force or file.metadata.changedtick ~= changedtick, - }) - else - log.fmt_debug("inserting into database: %s", file.filename) - insert_new_file_into_database(db, file, { - force = opts.force or file.metadata.changedtick ~= changedtick, + files + :add_to_paths(opts.path) + :next(function(file) + -- If false, means failed to add the file + if not file then + reject("invalid path to org file: " .. opts.path) + return file + end + + -- Determine if the file already exists through nodes in the db + local ids = db:find_by_index(schema.FILE, file.filename) + local has_file = not vim.tbl_isempty(ids) + + if has_file then + log.fmt_debug("modifying in database: %s", file.filename) + modify_file_in_database(db, file, { + force = opts.force or file.metadata.changedtick ~= changedtick, + }) + else + log.fmt_debug("inserting into database: %s", file.filename) + insert_new_file_into_database(db, file, { + force = opts.force or file.metadata.changedtick ~= changedtick, + }) + end + + resolve({ + file = file, + nodes = vim.tbl_values(db:get_many(db:find_by_index(schema.FILE, file.filename))), }) - end - - resolve({ - file = file, - nodes = vim.tbl_values( - db:get_many(db:find_by_index(schema.FILE, file.filename)) - ), - }) - return file - end):catch(reject) + return file + end) + :catch(reject) end) end) end @@ -354,33 +365,38 @@ end ---Loads database (or retrieves from cache) asynchronously. ---@return OrgPromise function M:database() - return self.__db and Promise.resolve(self.__db) or Promise.new(function(resolve) - -- Load our database from disk if it is available - io.stat(self.path.database):next(function() - return Database:load_from_disk(self.path.database):next(function(db) - schema:update(db) - self.__db = db - - resolve(db) - return db - end):catch(function(err) - log.fmt_error("Failed to load database: %s", err) - - -- Set up database with a clean slate instead - local db = Database:new() - schema:update(db) - self.__db = db - - resolve(db) - end) - end):catch(function() - local db = Database:new() - schema:update(db) - self.__db = db + return self.__db and Promise.resolve(self.__db) + or Promise.new(function(resolve) + -- Load our database from disk if it is available + io.stat(self.path.database) + :next(function() + return Database:load_from_disk(self.path.database) + :next(function(db) + schema:update(db) + self.__db = db + + resolve(db) + return db + end) + :catch(function(err) + log.fmt_error("Failed to load database: %s", err) + + -- Set up database with a clean slate instead + local db = Database:new() + schema:update(db) + self.__db = db + + resolve(db) + end) + end) + :catch(function() + local db = Database:new() + schema:update(db) + self.__db = db - return resolve(db) + return resolve(db) + end) end) - end) end ---Loads database (or retrieves from cache) synchronously. diff --git a/lua/org-roam/database/schema.lua b/lua/org-roam/database/schema.lua index 6b6b722..fc80b77 100644 --- a/lua/org-roam/database/schema.lua +++ b/lua/org-roam/database/schema.lua @@ -6,11 +6,11 @@ ---@enum org-roam.database.Schema local M = { - ALIAS = "alias", - FILE = "file", + ALIAS = "alias", + FILE = "file", ORIGIN = "origin", - TAG = "tag", - TITLE = "title", + TAG = "tag", + TITLE = "title", } ---Updates a schema (series of indexes) for the specified database. @@ -28,11 +28,11 @@ function M:update(db) local new_indexes = {} for name, indexer in pairs({ - [self.ALIAS] = field("aliases"), - [self.FILE] = field("file"), + [self.ALIAS] = field("aliases"), + [self.FILE] = field("file"), [self.ORIGIN] = field("origin"), - [self.TAG] = field("tags"), - [self.TITLE] = field("title"), + [self.TAG] = field("tags"), + [self.TITLE] = field("title"), }) do if not db:has_index(name) then db:new_index(name, indexer) diff --git a/lua/org-roam/extensions/dailies.lua b/lua/org-roam/extensions/dailies.lua index 7b20fad..3791421 100644 --- a/lua/org-roam/extensions/dailies.lua +++ b/lua/org-roam/extensions/dailies.lua @@ -19,10 +19,7 @@ local Promise = require("orgmode.utils.promise") ---@param roam OrgRoam ---@return string local function roam_dailies_dir(roam) - return vim.fs.normalize(join_path( - roam.config.directory, - roam.config.extensions.dailies.directory - )) + return vim.fs.normalize(join_path(roam.config.directory, roam.config.extensions.dailies.directory)) end ---Converts date to YYYY-MM-DD format. @@ -64,17 +61,20 @@ end ---@param roam OrgRoam ---@return string[] local function roam_dailies_files(roam) - return io.walk(roam_dailies_dir(roam)):filter(function(entry) - ---@cast entry org-roam.core.utils.io.WalkEntry - local filename = vim.fn.fnamemodify(entry.filename, ":t:r") - local ext = vim.fn.fnamemodify(entry.filename, ":e") - local is_org = ext == "org" or ext == "org_archive" - local is_date = Date.is_valid_date(filename) ~= nil - return entry.type == "file" and is_org and is_date - end):map(function(entry) - ---@cast entry org-roam.core.utils.io.WalkEntry - return entry.path - end):collect() + return io.walk(roam_dailies_dir(roam)) + :filter(function(entry) + ---@cast entry org-roam.core.utils.io.WalkEntry + local filename = vim.fn.fnamemodify(entry.filename, ":t:r") + local ext = vim.fn.fnamemodify(entry.filename, ":e") + local is_org = ext == "org" or ext == "org_archive" + local is_date = Date.is_valid_date(filename) ~= nil + return entry.type == "file" and is_org and is_date + end) + :map(function(entry) + ---@cast entry org-roam.core.utils.io.WalkEntry + return entry.path + end) + :collect() end ---Returns list of file paths representing org files within dailies @@ -90,13 +90,16 @@ end ---Returns list of pre-existing dates based on dailies filenames. ---@return OrgDate[] local function roam_dailies_dates(roam) - return vim.tbl_filter(function(d) - ---@cast d OrgDate|nil - return d ~= nil - end, vim.tbl_map(function(path) - local filename = vim.fn.fnamemodify(path, ":t:r") - return Date.from_string(filename) - end, roam_dailies_files(roam))) + return vim.tbl_filter( + function(d) + ---@cast d OrgDate|nil + return d ~= nil + end, + vim.tbl_map(function(path) + local filename = vim.fn.fnamemodify(path, ":t:r") + return Date.from_string(filename) + end, roam_dailies_files(roam)) + ) end ---Creates a new buffer representing an org roam daily note. @@ -109,10 +112,7 @@ local function make_daily_buffer(roam, date, title) assert(buf ~= 0, "failed to create daily buffer") -- Update the filename of the buffer to be `path/to/{DATE}.org` - vim.api.nvim_buf_set_name(buf, join_path( - roam_dailies_dir(roam), - date_string(date) .. ".org" - )) + vim.api.nvim_buf_set_name(buf, join_path(roam_dailies_dir(roam), date_string(date) .. ".org")) -- Set filetype to org vim.api.nvim_buf_set_option(buf, "filetype", "org") @@ -144,11 +144,7 @@ local function make_dailies_templates(roam, date) ---@return string local function format_date(content) for exp in string.gmatch(content, "%%<[^>]*>") do - content = string.gsub( - content, - vim.pesc(exp), - os.date(exp:sub(3, -2), date and date.timestamp) - ) + content = string.gsub(content, vim.pesc(exp), os.date(exp:sub(3, -2), date and date.timestamp)) end return content end @@ -160,10 +156,7 @@ local function make_dailies_templates(roam, date) -- and be populated with the specified date local target = tmpl.target if target then - tmpl.target = join_path( - roam.config.extensions.dailies.directory, - format_date(target) - ) + tmpl.target = join_path(roam.config.extensions.dailies.directory, format_date(target)) end local template = tmpl.template @@ -230,14 +223,11 @@ return function(roam) end end - return (date - and Promise.resolve(date) - or Calendar.new({ - date = date, - title = opts.title, - on_day = make_render_on_day(roam), - }):open() - ):next(function(date) + return (date and Promise.resolve(date) or Calendar.new({ + date = date, + title = opts.title, + on_day = make_render_on_day(roam), + }):open()):next(function(date) if date then return roam.api.capture_node({ origin = false, @@ -306,24 +296,26 @@ return function(roam) if date then local path = date_to_path(roam, date) return Promise.new(function(resolve) - io.stat(path):next(function(stat) - pcall(vim.api.nvim_set_current_win, win) - vim.cmd.edit(path) - resolve(date) - return stat - end):catch(function() - local buf = make_daily_buffer(roam, date) - pcall(vim.api.nvim_win_set_buf, win, buf) - - -- NOTE: Must perform detection when buffer - -- is first created in order for folding - -- and other functionality to work! - vim.api.nvim_buf_call(buf, function() - vim.cmd("filetype detect") + io.stat(path) + :next(function(stat) + pcall(vim.api.nvim_set_current_win, win) + vim.cmd.edit(path) + resolve(date) + return stat + end) + :catch(function() + local buf = make_daily_buffer(roam, date) + pcall(vim.api.nvim_win_set_buf, win, buf) + + -- NOTE: Must perform detection when buffer + -- is first created in order for folding + -- and other functionality to work! + vim.api.nvim_buf_call(buf, function() + vim.cmd("filetype detect") + end) + + return resolve(date) end) - - return resolve(date) - end) end) else return date diff --git a/lua/org-roam/setup.lua b/lua/org-roam/setup.lua index 28c5bb0..e9cc5a4 100644 --- a/lua/org-roam/setup.lua +++ b/lua/org-roam/setup.lua @@ -12,7 +12,7 @@ return function(roam) local M = setmetatable({}, { __call = function(this, config) return this.call(config) - end + end, }) ---Calls the setup function to initialize the plugin. @@ -28,10 +28,7 @@ return function(roam) -- Create the directories if they are missing local path = require("org-roam.core.utils.path") vim.fn.mkdir(roam.config.directory, "p") - vim.fn.mkdir(path.join( - roam.config.directory, - roam.config.extensions.dailies.directory - ), "p") + vim.fn.mkdir(path.join(roam.config.directory, roam.config.extensions.dailies.directory), "p") return M.__initialize_database():next(function() return roam @@ -83,8 +80,9 @@ return function(roam) function M.__initialize_database() if not M.__initialize_database_done then M.__initialize_database_done = true - return require("org-roam.setup.database")(roam) - :next(function() return nil end) + return require("org-roam.setup.database")(roam):next(function() + return nil + end) else local Promise = require("orgmode.utils.promise") return Promise.resolve(nil) diff --git a/lua/org-roam/setup/commands.lua b/lua/org-roam/setup/commands.lua index dd5e026..cbbfee9 100644 --- a/lua/org-roam/setup/commands.lua +++ b/lua/org-roam/setup/commands.lua @@ -21,13 +21,18 @@ return function(roam) local profiler = Profiler:new() profiler:start() - local promise = roam.database:save({ force = force }):next(function(...) - local tt = profiler:stop():time_taken_as_string() - notify.info("Saved database [took " .. tt .. "]") - return ... - end):catch(notify.error) + local promise = roam.database + :save({ force = force }) + :next(function(...) + local tt = profiler:stop():time_taken_as_string() + notify.info("Saved database [took " .. tt .. "]") + return ... + end) + :catch(notify.error) - if sync then promise:wait() end + if sync then + promise:wait() + end end, { bang = true, desc = "Saves the roam database to disk", @@ -44,13 +49,18 @@ return function(roam) profiler:start() log.fmt_debug("Updating database (force = %s, sync = %s)", force, sync) - local promise = roam.database:load({ force = force or "scan" }):next(function(...) - local tt = profiler:stop():time_taken_as_string() - notify.info("Updated database [took " .. tt .. "]") - return ... - end):catch(notify.error) + local promise = roam.database + :load({ force = force or "scan" }) + :next(function(...) + local tt = profiler:stop():time_taken_as_string() + notify.info("Updated database [took " .. tt .. "]") + return ... + end) + :catch(notify.error) - if sync then promise:wait() end + if sync then + promise:wait() + end end, { bang = true, desc = "Updates the roam database", @@ -71,14 +81,19 @@ return function(roam) -- Start profiling so we can report the time taken local profiler = Profiler:new() profiler:start() - return roam.database:load():next(function(...) - local tt = profiler:stop():time_taken_as_string() - notify.info("Loaded database [took " .. tt .. "]") - return ... - end):catch(notify.error) + return roam.database + :load() + :next(function(...) + local tt = profiler:stop():time_taken_as_string() + notify.info("Loaded database [took " .. tt .. "]") + return ... + end) + :catch(notify.error) end) - if sync then promise:wait() end + if sync then + promise:wait() + end end, { desc = "Resets the roam database (wipe and rebuild)", nargs = "?", diff --git a/lua/org-roam/setup/database.lua b/lua/org-roam/setup/database.lua index 34a34ff..210b800 100644 --- a/lua/org-roam/setup/database.lua +++ b/lua/org-roam/setup/database.lua @@ -18,13 +18,16 @@ return function(roam) }) -- Load the database asynchronously, forcing a full sweep of directory - return roam.database:load({ force = "scan" }):next(function() - -- If we are persisting to disk, do so now as the database may - -- have changed post-load - if roam.config.database.persist then - return roam.database:save() - else - return Promise.resolve(nil) - end - end):catch(notify.error) + return roam.database + :load({ force = "scan" }) + :next(function() + -- If we are persisting to disk, do so now as the database may + -- have changed post-load + if roam.config.database.persist then + return roam.database:save() + else + return Promise.resolve(nil) + end + end) + :catch(notify.error) end diff --git a/lua/org-roam/setup/keybindings.lua b/lua/org-roam/setup/keybindings.lua index a20cc03..da88f1d 100644 --- a/lua/org-roam/setup/keybindings.lua +++ b/lua/org-roam/setup/keybindings.lua @@ -21,8 +21,12 @@ local notify = require("org-roam.core.ui.notify") ---@param desc string ---@param cb fun() local function assign(lhs, desc, cb) - if type(cb) ~= "function" then return end - if not lhs then return end + if type(cb) ~= "function" then + return + end + if not lhs then + return + end local modes = { "n" } if type(lhs) == "table" then @@ -30,7 +34,9 @@ local function assign(lhs, desc, cb) lhs = lhs.lhs end - if vim.trim(lhs) == "" or #modes == 0 then return end + if vim.trim(lhs) == "" or #modes == 0 then + return + end for _, mode in ipairs(modes) do vim.api.nvim_set_keymap(mode, lhs, "", { @@ -77,37 +83,21 @@ local function assign_core_keybindings(roam) -- User can remove all bindings by setting this to nil local bindings = roam.config.bindings or {} - assign( - bindings.add_alias, - "Adds an alias to the roam node under cursor", - function() - roam.api.add_alias() - end - ) + assign(bindings.add_alias, "Adds an alias to the roam node under cursor", function() + roam.api.add_alias() + end) - assign( - bindings.remove_alias, - "Removes an alias from the roam node under cursor", - function() - roam.api.remove_alias() - end - ) + assign(bindings.remove_alias, "Removes an alias from the roam node under cursor", function() + roam.api.remove_alias() + end) - assign( - bindings.add_origin, - "Adds an origin to the roam node under cursor", - function() - roam.api.add_origin() - end - ) + assign(bindings.add_origin, "Adds an origin to the roam node under cursor", function() + roam.api.add_origin() + end) - assign( - bindings.remove_origin, - "Removes the origin from the roam node under cursor", - function() - roam.api.remove_origin() - end - ) + assign(bindings.remove_origin, "Removes the origin from the roam node under cursor", function() + roam.api.remove_origin() + end) assign( bindings.goto_prev_node, @@ -125,62 +115,42 @@ local function assign_core_keybindings(roam) end ) - assign( - bindings.quickfix_backlinks, - "Open quickfix of backlinks for org-roam node under cursor", - function() - roam.ui.open_quickfix_list({ - backlinks = true, - show_preview = true, - }) - end - ) - - assign( - bindings.toggle_roam_buffer, - "Toggles org-roam buffer for node under cursor", - function() - roam.ui.toggle_node_buffer({ - focus = roam.config.ui.node_buffer.focus_on_toggle, - }) - end - ) - - assign( - bindings.toggle_roam_buffer_fixed, - "Toggles org-roam buffer for a specific node, not changing", - function() - roam.ui.toggle_node_buffer({ - fixed = true, - focus = roam.config.ui.node_buffer.focus_on_toggle, - }) - end - ) + assign(bindings.quickfix_backlinks, "Open quickfix of backlinks for org-roam node under cursor", function() + roam.ui.open_quickfix_list({ + backlinks = true, + show_preview = true, + }) + end) - assign( - bindings.complete_at_point, - "Completes link to a node based on expression under cursor", - function() - roam.api.complete_node() - end - ) + assign(bindings.toggle_roam_buffer, "Toggles org-roam buffer for node under cursor", function() + roam.ui.toggle_node_buffer({ + focus = roam.config.ui.node_buffer.focus_on_toggle, + }) + end) - assign( - { lhs = bindings.capture, modes = { "n", "v" } }, - "Opens org-roam capture window", - function() - local results = get_visual_selection(roam) - local title - if type(results) == "table" then - title = results.title - elseif results == "unsupported" then - return - end - roam.api.capture_node({ - title = title, - }) + assign(bindings.toggle_roam_buffer_fixed, "Toggles org-roam buffer for a specific node, not changing", function() + roam.ui.toggle_node_buffer({ + fixed = true, + focus = roam.config.ui.node_buffer.focus_on_toggle, + }) + end) + + assign(bindings.complete_at_point, "Completes link to a node based on expression under cursor", function() + roam.api.complete_node() + end) + + assign({ lhs = bindings.capture, modes = { "n", "v" } }, "Opens org-roam capture window", function() + local results = get_visual_selection(roam) + local title + if type(results) == "table" then + title = results.title + elseif results == "unsupported" then + return end - ) + roam.api.capture_node({ + title = title, + }) + end) assign( { lhs = bindings.find_node, modes = { "n", "v" } }, @@ -244,93 +214,49 @@ local function assign_dailies_keybindings(roam) -- User can remove all bindings by setting this to nil local bindings = roam.config.extensions.dailies.bindings or {} - assign( - bindings.capture_date, - "Capture a specific date's note", - function() - roam.ext.dailies.capture_date() - end - ) + assign(bindings.capture_date, "Capture a specific date's note", function() + roam.ext.dailies.capture_date() + end) - assign( - bindings.capture_today, - "Capture today's note", - function() - roam.ext.dailies.capture_today() - end - ) + assign(bindings.capture_today, "Capture today's note", function() + roam.ext.dailies.capture_today() + end) - assign( - bindings.capture_tomorrow, - "Capture tomorrow's note", - function() - roam.ext.dailies.capture_tomorrow() - end - ) + assign(bindings.capture_tomorrow, "Capture tomorrow's note", function() + roam.ext.dailies.capture_tomorrow() + end) - assign( - bindings.capture_yesterday, - "Capture yesterday's note", - function() - roam.ext.dailies.capture_yesterday() - end - ) + assign(bindings.capture_yesterday, "Capture yesterday's note", function() + roam.ext.dailies.capture_yesterday() + end) - assign( - bindings.find_directory, - "Navigate to dailies note directory", - function() - roam.ext.dailies.find_directory() - end - ) + assign(bindings.find_directory, "Navigate to dailies note directory", function() + roam.ext.dailies.find_directory() + end) - assign( - bindings.goto_date, - "Navigate to a specific date's note", - function() - roam.ext.dailies.goto_date() - end - ) + assign(bindings.goto_date, "Navigate to a specific date's note", function() + roam.ext.dailies.goto_date() + end) - assign( - bindings.goto_today, - "Navigate to today's note", - function() - roam.ext.dailies.goto_today() - end - ) + assign(bindings.goto_today, "Navigate to today's note", function() + roam.ext.dailies.goto_today() + end) - assign( - bindings.goto_tomorrow, - "Navigate to tomorrow's note", - function() - roam.ext.dailies.goto_tomorrow() - end - ) + assign(bindings.goto_tomorrow, "Navigate to tomorrow's note", function() + roam.ext.dailies.goto_tomorrow() + end) - assign( - bindings.goto_yesterday, - "Navigate to yesterday's note", - function() - roam.ext.dailies.goto_yesterday() - end - ) + assign(bindings.goto_yesterday, "Navigate to yesterday's note", function() + roam.ext.dailies.goto_yesterday() + end) - assign( - bindings.goto_next_date, - "Navigate to the next available note", - function() - roam.ext.dailies.goto_next_date() - end - ) + assign(bindings.goto_next_date, "Navigate to the next available note", function() + roam.ext.dailies.goto_next_date() + end) - assign( - bindings.goto_prev_date, - "Navigate to the previous available note", - function() - roam.ext.dailies.goto_prev_date() - end - ) + assign(bindings.goto_prev_date, "Navigate to the previous available note", function() + roam.ext.dailies.goto_prev_date() + end) end ---@param roam OrgRoam diff --git a/lua/org-roam/setup/plugin.lua b/lua/org-roam/setup/plugin.lua index 61e22ef..9db8ec9 100644 --- a/lua/org-roam/setup/plugin.lua +++ b/lua/org-roam/setup/plugin.lua @@ -23,8 +23,7 @@ return function(roam) -- If we found a node, open the file at the start of the node if node then - log.fmt_debug("Detected node %s under at (%d,%d)", - node.id, row, col) + log.fmt_debug("Detected node %s under at (%d,%d)", node.id, row, col) local winnr = vim.api.nvim_get_current_win() vim.cmd.edit(node.file) @@ -32,10 +31,7 @@ return function(roam) vim.schedule(function() -- Ensure that we do not jump past our buffer's last line! local bufnr = vim.api.nvim_win_get_buf(winnr) - local line = math.min( - vim.api.nvim_buf_line_count(bufnr), - node.range.start.row + 1 - ) + local line = math.min(vim.api.nvim_buf_line_count(bufnr), node.range.start.row + 1) vim.api.nvim_win_set_cursor(winnr, { line, 0 }) end) diff --git a/lua/org-roam/ui.lua b/lua/org-roam/ui.lua index 10972ea..38ab1c6 100644 --- a/lua/org-roam/ui.lua +++ b/lua/org-roam/ui.lua @@ -7,16 +7,16 @@ ---@param roam OrgRoam ---@return org-roam.UserInterface return function(roam) - local NodeBufferApi = require("org-roam.ui.node-buffer")(roam) - local QuickfixApi = require("org-roam.ui.quickfix")(roam) - local SelectNodeApi = require("org-roam.ui.select-node")(roam) + local NodeBufferApi = require("org-roam.ui.node-buffer")(roam) + local QuickfixApi = require("org-roam.ui.quickfix")(roam) + local SelectNodeApi = require("org-roam.ui.select-node")(roam) ---@class org-roam.UserInterface - local M = {} + local M = {} M.open_quickfix_list = QuickfixApi.open_qflist M.toggle_node_buffer = NodeBufferApi.toggle_node_buffer - M.select_node = SelectNodeApi.select_node + M.select_node = SelectNodeApi.select_node return M end diff --git a/lua/org-roam/ui/node-buffer.lua b/lua/org-roam/ui/node-buffer.lua index fc30dbe..a774b63 100644 --- a/lua/org-roam/ui/node-buffer.lua +++ b/lua/org-roam/ui/node-buffer.lua @@ -134,7 +134,8 @@ local function roam_toggle_fixed_buffer(roam, opts) if opts.id then toggle_node_buffer(opts.id) else - roam.ui.select_node() + roam.ui + .select_node() :on_choice(function(choice) toggle_node_buffer(choice.id) end) diff --git a/lua/org-roam/ui/node-buffer/buffer.lua b/lua/org-roam/ui/node-buffer/buffer.lua index 6ca0a09..e9743f7 100644 --- a/lua/org-roam/ui/node-buffer/buffer.lua +++ b/lua/org-roam/ui/node-buffer/buffer.lua @@ -41,16 +41,16 @@ local KEYBINDINGS = { ---Mapping of kind -> highlight group. local HL = { - NODE_TITLE = "Title", - NODE_ORIGIN = "Title", - COMMENT = "Comment", - KEYBINDING = "WarningMsg", + NODE_TITLE = "Title", + NODE_ORIGIN = "Title", + COMMENT = "Comment", + KEYBINDING = "WarningMsg", SECTION_LABEL = "Title", SECTION_COUNT = "Normal", - LINK_TITLE = "Title", + LINK_TITLE = "Title", LINK_LOCATION = "WarningMsg", - NORMAL = "Normal", - PREVIEW_LINE = "PMenu", + NORMAL = "Normal", + PREVIEW_LINE = "PMenu", } ---Mapping of kind -> icon. @@ -173,7 +173,9 @@ local function load_lines_at_cursor(roam, path, cursor) return results end) - :catch(function(err) notify.error(err) end) + :catch(function(err) + notify.error(err) + end) ---@param line string return vim.tbl_map(function(line) @@ -215,7 +217,9 @@ local function render(roam, this, node, details) -- Get our bindings to display in help, in -- a defined and consistent order local bindings = vim.tbl_values(KEYBINDINGS) - table.sort(bindings, function(a, b) return a.order < b.order end) + table.sort(bindings, function(a, b) + return a.order < b.order + end) for _, binding in ipairs(bindings) do table.insert(lines, { @@ -231,10 +235,7 @@ local function render(roam, this, node, details) -- Insert a full line that contains the node's title table.insert(lines, { - C.hl( - string.format("%sNode: ", details.fixed and "Fixed " or ""), - HL.NORMAL - ), + C.hl(string.format("%sNode: ", details.fixed and "Fixed " or ""), HL.NORMAL), C.hl(node.title, HL.NODE_TITLE), }) @@ -244,13 +245,14 @@ local function render(roam, this, node, details) if origin_node then local function do_open() local win = vim.api.nvim_get_current_win() - local filter = function(winnr) return winnr ~= win end + local filter = function(winnr) + return winnr ~= win + end - WindowPicker - :new({ - autoselect = true, - filter = filter, - }) + WindowPicker:new({ + autoselect = true, + filter = filter, + }) :on_choice(function(winnr) roam.utils.goto_node({ node = origin_node, @@ -261,10 +263,7 @@ local function render(roam, this, node, details) end table.insert(lines, { - C.hl( - "Origin: ", - HL.NORMAL - ), + C.hl("Origin: ", HL.NORMAL), C.hl(origin_node.title, HL.NODE_ORIGIN), C.action(KEYBINDINGS.OPEN_LINK.key, do_open), }) @@ -295,9 +294,7 @@ local function render(roam, this, node, details) -- Get the expanded state of the first link to use for everything if is_expanded == nil then - is_expanded = - tbl_utils.get(state.expanded, backlink_node.id, row, col) - or false + is_expanded = tbl_utils.get(state.expanded, backlink_node.id, row, col) or false end if not state.expanded[backlink_node.id] then @@ -337,12 +334,7 @@ local function render(roam, this, node, details) backlink_links_cnt = backlink_links_cnt + 1 ---@type boolean - local is_expanded = tbl_utils.get( - state.expanded, - backlink_node.id, - row - 1, - col - 1 - ) or false + local is_expanded = tbl_utils.get(state.expanded, backlink_node.id, row - 1, col - 1) or false local function do_expand() if not state.expanded then @@ -363,13 +355,14 @@ local function render(roam, this, node, details) local function do_open() local win = vim.api.nvim_get_current_win() - local filter = function(winnr) return winnr ~= win end + local filter = function(winnr) + return winnr ~= win + end - WindowPicker - :new({ - autoselect = true, - filter = filter, - }) + WindowPicker:new({ + autoselect = true, + filter = filter, + }) :on_choice(function(winnr) vim.api.nvim_set_current_win(winnr) vim.cmd("e " .. backlink_node.file) @@ -406,9 +399,10 @@ local function render(roam, this, node, details) -- If we have toggled for this location, show the preview if is_expanded then - vim.list_extend(backlink_lines, load_lines_at_cursor( - roam, backlink_node.file, { row, col - 1 } - )) + vim.list_extend( + backlink_lines, + load_lines_at_cursor(roam, backlink_node.file, { row, col - 1 }) + ) end end end @@ -423,19 +417,11 @@ local function render(roam, this, node, details) -- Add some global actions: keybindings that can be used anywhere table.insert(lines, { - C.action( - KEYBINDINGS.EXPAND_ALL.key, - do_expand_all, - { global = true } - ), - C.action( - KEYBINDINGS.REFRESH_BUFFER.key, - function() - highlighter.clear_cache() - EMITTER:emit(EVENTS.REFRESH, { force = true }) - end, - { global = true } - ), + C.action(KEYBINDINGS.EXPAND_ALL.key, do_expand_all, { global = true }), + C.action(KEYBINDINGS.REFRESH_BUFFER.key, function() + highlighter.clear_cache() + EMITTER:emit(EVENTS.REFRESH, { force = true }) + end, { global = true }), }) end diff --git a/lua/org-roam/ui/select-node.lua b/lua/org-roam/ui/select-node.lua index 7fd0dc7..a9f14c0 100644 --- a/lua/org-roam/ui/select-node.lua +++ b/lua/org-roam/ui/select-node.lua @@ -51,7 +51,9 @@ local function roam_select_node(roam, opts) items = items, prompt = prompt, ---@param item {id:org-roam.core.database.Id, label:string} - format = function(item) return item.label end, + format = function(item) + return item.label + end, cancel_on_no_init_matches = true, }, opts or {}) diff --git a/lua/org-roam/utils.lua b/lua/org-roam/utils.lua index 989e59c..958f059 100644 --- a/lua/org-roam/utils.lua +++ b/lua/org-roam/utils.lua @@ -66,7 +66,7 @@ local function get_buffer_cache(bufnr) local node_tree if not vim.tbl_isempty(file.nodes) then node_tree = IntervalTree:from_list( - ---@param node org-roam.core.file.Node + ---@param node org-roam.core.file.Node vim.tbl_map(function(node) return { node.range.start.offset, @@ -81,7 +81,7 @@ local function get_buffer_cache(bufnr) local link_tree if #file.links > 0 then link_tree = IntervalTree:from_list( - ---@param link org-roam.core.file.Link + ---@param link org-roam.core.file.Link vim.tbl_map(function(link) return { link.range.start.offset, @@ -198,7 +198,7 @@ M.parse_prop_value = parse_property_value ---@param value string ---@return string function M.wrap_prop_value(value) - local text = string.gsub(string.gsub(value, "\\", "\\\\"), "\"", "\\\"") + local text = string.gsub(string.gsub(value, "\\", "\\\\"), '"', '\\"') return text end @@ -308,11 +308,17 @@ function M.get_visual_selection(opts) -- If single line, we trim everything and collapse newlines into spaces if opts.single_line then - local text = table.concat(vim.tbl_filter(function(line) - return line ~= "" - end, vim.tbl_map(function(line) - return vim.trim(line) - end, lines)), " ") + local text = table.concat( + vim.tbl_filter( + function(line) + return line ~= "" + end, + vim.tbl_map(function(line) + return vim.trim(line) + end, lines) + ), + " " + ) lines = { text } end diff --git a/spec/api_alias_spec.lua b/spec/api_alias_spec.lua index 2e6e863..9f99093 100644 --- a/spec/api_alias_spec.lua +++ b/spec/api_alias_spec.lua @@ -44,7 +44,7 @@ describe("org-roam.api.alias", function() assert.are.same({ ":PROPERTIES:", ":ID: " .. id, - ":ROAM_ALIASES: \"other test\"", + ':ROAM_ALIASES: "other test"', ":END:", "#+TITLE: Test", }, utils.read_buffer()) @@ -76,7 +76,7 @@ describe("org-roam.api.alias", function() assert.are.same({ ":PROPERTIES:", ":ID: " .. id, - ":ROAM_ALIASES: something \"other test\"", + ':ROAM_ALIASES: something "other test"', ":END:", "#+TITLE: Test", }, utils.read_buffer()) @@ -177,7 +177,7 @@ describe("org-roam.api.alias", function() assert.are.same({ ":PROPERTIES:", ":ID: " .. id, - ":ROAM_ALIASES: \"else\"", + ':ROAM_ALIASES: "else"', ":END:", "#+TITLE: Test", }, utils.read_buffer()) diff --git a/spec/api_completion_spec.lua b/spec/api_completion_spec.lua index 47624af..10ffd08 100644 --- a/spec/api_completion_spec.lua +++ b/spec/api_completion_spec.lua @@ -11,7 +11,7 @@ describe("org-roam.api.completion", function() roam = utils.init_plugin({ setup = { directory = utils.make_temp_org_files_directory(), - } + }, }) test_dir = roam.config.directory end) diff --git a/spec/api_node_spec.lua b/spec/api_node_spec.lua index f6346a0..545bea0 100644 --- a/spec/api_node_spec.lua +++ b/spec/api_node_spec.lua @@ -11,7 +11,7 @@ describe("org-roam.api.node", function() roam = utils.init_plugin({ setup = { directory = utils.make_temp_org_files_directory(), - } + }, }) one_path = utils.join_path(roam.config.directory, "one.org") @@ -29,9 +29,9 @@ describe("org-roam.api.node", function() vim.cmd.edit(one_path) utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("d"), -- select "d" template - input = "Some title", -- input "Some title" on title prompt + input = "Some title", -- input "Some title" on title prompt }) -- Start the capture process @@ -77,9 +77,9 @@ describe("org-roam.api.node", function() vim.cmd.edit(one_path) utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("v"), -- select "v" template - input = "Some title", -- input "Some title" on title prompt + input = "Some title", -- input "Some title" on title prompt }) -- Start the capture process using a custom template @@ -206,7 +206,7 @@ describe("org-roam.api.node", function() utils.write_to(test_path, { ":PROPERTIES:", ":ID: test-node-id", - ":ROAM_ALIASES: \"some test alias\"", + ':ROAM_ALIASES: "some test alias"', ":END:", }) @@ -251,7 +251,7 @@ describe("org-roam.api.node", function() vim.cmd.edit(one_path) utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("d"), -- select "d" template }) @@ -302,7 +302,7 @@ describe("org-roam.api.node", function() vim.cmd.edit(one_path) utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("v"), -- select "v" template }) @@ -431,7 +431,7 @@ describe("org-roam.api.node", function() vim.cmd.edit(one_path) utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("d"), -- select "d" template }) @@ -478,7 +478,7 @@ describe("org-roam.api.node", function() vim.cmd.edit(one_path) utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("v"), -- select "v" template }) diff --git a/spec/api_origin_spec.lua b/spec/api_origin_spec.lua index fc3455f..9d6f779 100644 --- a/spec/api_origin_spec.lua +++ b/spec/api_origin_spec.lua @@ -11,7 +11,7 @@ describe("org-roam.api.origin", function() roam = utils.init_plugin({ setup = { directory = utils.make_temp_org_files_directory(), - } + }, }) test_dir = roam.config.directory test_org_file_path = utils.make_temp_filename({ diff --git a/spec/core_database_spec.lua b/spec/core_database_spec.lua index 16e66eb..1b2b6af 100644 --- a/spec/core_database_spec.lua +++ b/spec/core_database_spec.lua @@ -32,13 +32,17 @@ describe("org-roam.core.database", function() local is_done = false local path = vim.fn.tempname() - db:write_to_disk(path):catch(function(err) - error = err - end):finally(function() - is_done = true - end) + db:write_to_disk(path) + :catch(function(err) + error = err + end) + :finally(function() + is_done = true + end) - vim.wait(10000, function() return is_done end) + vim.wait(10000, function() + return is_done + end) assert(not error, error) -- Check the file was created, and then delete it @@ -54,7 +58,9 @@ describe("org-roam.core.database", function() local id2 = db:insert("two") db:link(id1, id2) - db:new_index("first_letter", function(node) return node:sub(1, 1) end) + db:new_index("first_letter", function(node) + return node:sub(1, 1) + end) db:reindex() local path = vim.fn.tempname() @@ -82,7 +88,9 @@ describe("org-roam.core.database", function() local id2 = db:insert("two") db:link(id1, id2) - db:new_index("first_letter", function(node) return node:sub(1, 1) end) + db:new_index("first_letter", function(node) + return node:sub(1, 1) + end) db:reindex() local path = vim.fn.tempname() @@ -92,16 +100,21 @@ describe("org-roam.core.database", function() local is_done = false -- Load a fresh copy of the database and verify that nodes, edges, and indexes still exist - Database:load_from_disk(path):next(function(d) - new_db = d - return d - end):catch(function(err) - error = err - end):finally(function() - is_done = true - end) + Database:load_from_disk(path) + :next(function(d) + new_db = d + return d + end) + :catch(function(err) + error = err + end) + :finally(function() + is_done = true + end) - vim.wait(10000, function() return is_done end) + vim.wait(10000, function() + return is_done + end) assert(not error, error) ---@cast new_db -nil assert.are.equal("one", new_db:get(id1)) @@ -464,7 +477,9 @@ describe("org-roam.core.database", function() ---@param a {[1]: string, [2]: integer}[] ---@param b {[1]: string, [2]: integer}[] local function same_tuple_lists(a, b) - same_lists(a, b, function(x, y) return x[1] < y[1] end) + same_lists(a, b, function(x, y) + return x[1] < y[1] + end) end local db = Database:new() @@ -537,15 +552,18 @@ describe("org-roam.core.database", function() }, db:iter_nodes({ start_node_id = id1, max_distance = 1 }):collect()) -- Filtering should support blocking out traversal to nodes - same_tuple_lists({ - { id1, 0, n = 2 }, - { id3, 1, n = 2 }, - }, db:iter_nodes({ - start_node_id = id1, - filter = function(id, _) - return id ~= id2 and id ~= id4 - end, - }):collect()) + same_tuple_lists( + { + { id1, 0, n = 2 }, + { id3, 1, n = 2 }, + }, + db:iter_nodes({ + start_node_id = id1, + filter = function(id, _) + return id ~= id2 and id ~= id4 + end, + }):collect() + ) end) it("should support iterating through paths between nodes", function() @@ -580,25 +598,29 @@ describe("org-roam.core.database", function() -- Find paths going from 4 -> 3 local paths = db:iter_paths(id4, id3):collect() - same_lists({ - { id4, id1, id3 }, - { id4, id5, id3 }, - }, paths, function(a, b) - if #a ~= #b then - return #a < #b - end + same_lists( + { + { id4, id1, id3 }, + { id4, id5, id3 }, + }, + paths, + function(a, b) + if #a ~= #b then + return #a < #b + end - for i = 1, #a do - local aa = a[i] - local bb = b[i] + for i = 1, #a do + local aa = a[i] + local bb = b[i] - if aa ~= bb then - return aa < bb + if aa ~= bb then + return aa < bb + end end - end - return false - end) + return false + end + ) -- Limit paths going from 1 -> 3 it = db:iter_paths(id1, id3, { max_distance = 1 }) diff --git a/spec/core_file_spec.lua b/spec/core_file_spec.lua index 651f12d..aa122bc 100644 --- a/spec/core_file_spec.lua +++ b/spec/core_file_spec.lua @@ -51,7 +51,7 @@ describe("org-roam.core.file", function() }, file.links) assert.are.same({ ["1234"] = { - aliases = { "one alias", "two", "three", "\"four\"" }, + aliases = { "one alias", "two", "three", '"four"' }, file = orgfile.filename, id = "1234", level = 0, @@ -137,7 +137,7 @@ describe("org-roam.core.file", function() }, file.links) assert.are.same({ ["1234"] = { - aliases = { "one alias", "two", "three", "\"four\"" }, + aliases = { "one alias", "two", "three", '"four"' }, file = orgfile.filename, id = "1234", level = 1, @@ -215,12 +215,12 @@ describe("org-roam.core.file", function() end_ = { column = 34, offset = 171, - row = 8 + row = 8, }, start = { column = 14, offset = 151, - row = 8 + row = 8, }, }, }, @@ -232,12 +232,12 @@ describe("org-roam.core.file", function() end_ = { column = 28, offset = 396, - row = 17 + row = 17, }, start = { column = 8, offset = 376, - row = 17 + row = 17, }, }, }, @@ -249,12 +249,12 @@ describe("org-roam.core.file", function() end_ = { column = 28, offset = 601, - row = 23 + row = 23, }, start = { column = 8, offset = 581, - row = 23 + row = 23, }, }, }, @@ -266,15 +266,15 @@ describe("org-roam.core.file", function() end_ = { column = 28, offset = 891, - row = 33 + row = 33, }, start = { column = 8, offset = 871, - row = 33 + row = 33, }, }, - } + }, }, file.links) assert.are.same({ @@ -284,28 +284,32 @@ describe("org-roam.core.file", function() id = "1234", level = 0, linked = { - ["1111"] = { { - column = 14, - offset = 151, - row = 8 - } }, - ["3333"] = { { - column = 8, - offset = 581, - row = 23 - } } + ["1111"] = { + { + column = 14, + offset = 151, + row = 8, + }, + }, + ["3333"] = { + { + column = 8, + offset = 581, + row = 23, + }, + }, }, mtime = 0, range = { end_ = { column = MAX_NUMBER, offset = MAX_NUMBER, - row = MAX_NUMBER + row = MAX_NUMBER, }, start = { column = 0, offset = 0, - row = 0 + row = 0, }, }, tags = { "tag1", "tag2", "tag3" }, @@ -317,23 +321,25 @@ describe("org-roam.core.file", function() id = "5678", level = 1, linked = { - ["2222"] = { { - column = 8, - offset = 376, - row = 17 - } } + ["2222"] = { + { + column = 8, + offset = 376, + row = 17, + }, + }, }, mtime = 0, range = { end_ = { column = 0, offset = 464, - row = 20 + row = 20, }, start = { column = 0, offset = 175, - row = 10 + row = 10, }, }, tags = { "HEADLINE_TAG", "tag1", "tag2", "tag3" }, @@ -345,28 +351,30 @@ describe("org-roam.core.file", function() id = "abcd-1234", level = 2, linked = { - ["4444"] = { { - column = 8, - offset = 871, - row = 33 - } } + ["4444"] = { + { + column = 8, + offset = 871, + row = 33, + }, + }, }, mtime = 0, range = { end_ = { column = 0, offset = 958, - row = 35 + row = 35, }, start = { column = 0, offset = 678, - row = 26 + row = 26, }, }, tags = { "HEADLINE_TAG_2", "HEADLINE_TAG_3", "tag1", "tag2", "tag3" }, title = "Nested headline", - } + }, }, file.nodes) end) end) diff --git a/spec/core_file_utils_spec.lua b/spec/core_file_utils_spec.lua index d7ce1c8..0c1825b 100644 --- a/spec/core_file_utils_spec.lua +++ b/spec/core_file_utils_spec.lua @@ -8,18 +8,18 @@ describe("org-roam.core.file.utils", function() end) it("should group quoted values together", function() - local value = "a \"b c\" d" + local value = 'a "b c" d' assert.are.same({ "a", "b c", "d" }, utils.parse_property_value(value)) end) it("should support the entire value being quoted", function() - local value = "\"a b c\"" + local value = '"a b c"' assert.are.same({ "a b c" }, utils.parse_property_value(value)) end) it("should support escaped quotes within value", function() - local value = "a \"b \\\"c\\\" d\" e\\\"f" - assert.are.same({ "a", "b \"c\" d", "e\"f" }, utils.parse_property_value(value)) + local value = 'a "b \\"c\\" d" e\\"f' + assert.are.same({ "a", 'b "c" d', 'e"f' }, utils.parse_property_value(value)) end) end) end) diff --git a/spec/core_utils_io_spec.lua b/spec/core_utils_io_spec.lua index f653b2c..c4316d8 100644 --- a/spec/core_utils_io_spec.lua +++ b/spec/core_utils_io_spec.lua @@ -73,17 +73,23 @@ describe("org-roam.core.utils.io", function() local is_done = false local path = vim.fn.tempname() - utils_io.read_file(path):next(function(d) - data = d - return d - end):catch(function(err) - error = err - end):finally(function() - is_done = true + utils_io + .read_file(path) + :next(function(d) + data = d + return d + end) + :catch(function(err) + error = err + end) + :finally(function() + is_done = true + end) + + vim.wait(10000, function() + return is_done end) - vim.wait(10000, function() return is_done end) - assert.is_not_nil(error) assert.is_nil(data) end) @@ -93,17 +99,23 @@ describe("org-roam.core.utils.io", function() local is_done = false local path = create_temp_file("hello world") - utils_io.read_file(path):next(function(d) - data = d - return d - end):catch(function(err) - error = err - end):finally(function() - is_done = true + utils_io + .read_file(path) + :next(function(d) + data = d + return d + end) + :catch(function(err) + error = err + end) + :finally(function() + is_done = true + end) + + vim.wait(10000, function() + return is_done end) - vim.wait(10000, function() return is_done end) - assert.is_nil(error) assert.are.equal("hello world", data) end) @@ -137,14 +149,19 @@ describe("org-roam.core.utils.io", function() local is_done = false local path = vim.fn.tempname() - utils_io.write_file(path, "hello world"):catch(function(err) - error = err - end):finally(function() - is_done = true + utils_io + .write_file(path, "hello world") + :catch(function(err) + error = err + end) + :finally(function() + is_done = true + end) + + vim.wait(10000, function() + return is_done end) - vim.wait(10000, function() return is_done end) - local data = read_temp_file(path) assert.is_nil(error) @@ -157,14 +174,19 @@ describe("org-roam.core.utils.io", function() local path = create_temp_file("test") - utils_io.write_file(path, "hello world"):catch(function(err) - error = err - end):finally(function() - is_done = true + utils_io + .write_file(path, "hello world") + :catch(function(err) + error = err + end) + :finally(function() + is_done = true + end) + + vim.wait(10000, function() + return is_done end) - vim.wait(10000, function() return is_done end) - local data = read_temp_file(path) assert.is_nil(error) @@ -199,17 +221,23 @@ describe("org-roam.core.utils.io", function() local is_done = false local path = vim.fn.tempname() - utils_io.stat(path):next(function(s) - stat = s - return s - end):catch(function(err) - error = err - end):finally(function() - is_done = true + utils_io + .stat(path) + :next(function(s) + stat = s + return s + end) + :catch(function(err) + error = err + end) + :finally(function() + is_done = true + end) + + vim.wait(10000, function() + return is_done end) - vim.wait(10000, function() return is_done end) - assert.is_not_nil(error) assert.is_nil(stat) end) @@ -219,17 +247,23 @@ describe("org-roam.core.utils.io", function() local is_done = false local path = create_temp_file("test") - utils_io.stat(path):next(function(s) - stat = s - return s - end):catch(function(err) - error = err - end):finally(function() - is_done = true + utils_io + .stat(path) + :next(function(s) + stat = s + return s + end) + :catch(function(err) + error = err + end) + :finally(function() + is_done = true + end) + + vim.wait(10000, function() + return is_done end) - vim.wait(10000, function() return is_done end) - assert.is_nil(error) assert.is_not_nil(stat) ---@cast stat -nil @@ -270,10 +304,10 @@ describe("org-roam.core.utils.io", function() return a.path < b.path end) assert.are.same({ - { filename = "dir1", name = "dir1", path = dir1, type = "directory" }, + { filename = "dir1", name = "dir1", path = dir1, type = "directory" }, { filename = "file1", name = join("dir1", "file1"), path = file1, type = "file" }, { filename = "file2", name = join("dir1", "file2"), path = file2, type = "file" }, - { filename = "dir2", name = "dir2", path = dir2, type = "directory" }, + { filename = "dir2", name = "dir2", path = dir2, type = "directory" }, }, entries) end) diff --git a/spec/core_utils_path_spec.lua b/spec/core_utils_path_spec.lua index 45be813..ee4548f 100644 --- a/spec/core_utils_path_spec.lua +++ b/spec/core_utils_path_spec.lua @@ -8,23 +8,15 @@ describe("org-roam.core.utils.path", function() end) it("should combine paths using system separator", function() - local sep = string.lower(vim.trim(uv.os_uname().sysname)) == "windows" - and "\\" or "/" + local sep = string.lower(vim.trim(uv.os_uname().sysname)) == "windows" and "\\" or "/" - assert.are.equal( - "path" .. sep .. "to" .. sep .. "file", - path.join("path", "to", "file") - ) + assert.are.equal("path" .. sep .. "to" .. sep .. "file", path.join("path", "to", "file")) end) it("should replace ongoing path with absolute path provided", function() - local sep = string.lower(vim.trim(uv.os_uname().sysname)) == "windows" - and "\\" or "/" + local sep = string.lower(vim.trim(uv.os_uname().sysname)) == "windows" and "\\" or "/" - assert.are.equal( - sep .. "to" .. sep .. "file", - path.join("path", sep .. "to", "file") - ) + assert.are.equal(sep .. "to" .. sep .. "file", path.join("path", sep .. "to", "file")) end) it("should support replacing absolute paths with prefixes on Windows", function() @@ -32,7 +24,9 @@ describe("org-roam.core.utils.path", function() -- Force our separator to be Windows ---@diagnostic disable-next-line:duplicate-set-field - path.separator = function() return "\\" end + path.separator = function() + return "\\" + end local actual = path.join( "C:\\\\Users\\senkwich\\orgfiles\\roam\\", @@ -44,15 +38,9 @@ describe("org-roam.core.utils.path", function() -- On Mac/Linux, we don't escape \ into / if path.separator() == "\\" then - assert.are.equal( - "C:/Users/senkwich/orgfiles/roam/20240429235641-test.org", - actual - ) + assert.are.equal("C:/Users/senkwich/orgfiles/roam/20240429235641-test.org", actual) else - assert.are.equal( - "C:\\\\Users\\senkwich\\orgfiles\\roam\\20240429235641-test.org", - actual - ) + assert.are.equal("C:\\\\Users\\senkwich\\orgfiles\\roam\\20240429235641-test.org", actual) end end) diff --git a/spec/core_utils_tree_spec.lua b/spec/core_utils_tree_spec.lua index 0e315c0..ffe840c 100644 --- a/spec/core_utils_tree_spec.lua +++ b/spec/core_utils_tree_spec.lua @@ -5,9 +5,9 @@ describe("org-roam.core.utils.tree", function() -- Tree is built up using the list in order local tree = Tree:from_list({ { 20, 36, "a" }, - { 3, 41, "b" }, + { 3, 41, "b" }, { 29, 99, "c" }, - { 0, 1, "d" }, + { 0, 1, "d" }, { 10, 15, "e" }, }) @@ -31,9 +31,9 @@ describe("org-roam.core.utils.tree", function() it("should support querying for tree nodes that intersect with a point", function() local tree = Tree:from_list({ { 20, 36, "a" }, - { 3, 41, "b" }, + { 3, 41, "b" }, { 29, 99, "c" }, - { 0, 1, "d" }, + { 0, 1, "d" }, { 10, 15, "e" }, }) @@ -64,9 +64,9 @@ describe("org-roam.core.utils.tree", function() it("should support querying for tree nodes that intersect with an interval", function() local tree = Tree:from_list({ { 20, 36, "a" }, - { 3, 41, "b" }, + { 3, 41, "b" }, { 29, 99, "c" }, - { 0, 1, "d" }, + { 0, 1, "d" }, { 10, 15, "e" }, }) diff --git a/spec/core_utils_uri_spec.lua b/spec/core_utils_uri_spec.lua index 6feb214..4bee526 100644 --- a/spec/core_utils_uri_spec.lua +++ b/spec/core_utils_uri_spec.lua @@ -99,7 +99,8 @@ describe("org-roam.core.utils.uri", function() }, uri) -- Full uri with everything filled out - uri = assert(Uri:parse("https://username:12345@example.com:6789/some/path?key1=value1&key2=value2#test-fragment")) + uri = + assert(Uri:parse("https://username:12345@example.com:6789/some/path?key1=value1&key2=value2#test-fragment")) assert.are.same({ scheme = "https", path = "/some/path", @@ -298,8 +299,10 @@ describe("org-roam.core.utils.uri", function() query = "key1=value1&key2=value2", fragment = "test-fragment", }) - assert.are.equal("https://username:12345@example.com:6789/some/path?key1=value1&key2=value2#test-fragment", - uri:as_string()) + assert.are.equal( + "https://username:12345@example.com:6789/some/path?key1=value1&key2=value2#test-fragment", + uri:as_string() + ) ---------------------------------------------------------------------- -- Test example URIs from wikipedia @@ -318,8 +321,10 @@ describe("org-roam.core.utils.uri", function() query = "tag=networking&order=newest", fragment = "top", }) - assert.are.equal("https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top", - uri:as_string()) + assert.are.equal( + "https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top", + uri:as_string() + ) uri = Uri:new({ scheme = "ldap", diff --git a/spec/database_spec.lua b/spec/database_spec.lua index f35354e..c9a45b0 100644 --- a/spec/database_spec.lua +++ b/spec/database_spec.lua @@ -156,7 +156,9 @@ describe("org-roam.database", function() ---@return org-roam.core.database.Id[] local function retrieve_ids(alias) local nodes = db:find_nodes_by_alias_sync(alias) - return vim.tbl_map(function(node) return node.id end, nodes) + return vim.tbl_map(function(node) + return node.id + end, nodes) end assert.are.same({ "1" }, retrieve_ids("one")) @@ -172,7 +174,9 @@ describe("org-roam.database", function() ---@return org-roam.core.database.Id[] local function retrieve_ids(file) local nodes = db:find_nodes_by_file_sync(file) - return vim.tbl_map(function(node) return node.id end, nodes) + return vim.tbl_map(function(node) + return node.id + end, nodes) end assert.are.same({ "1" }, retrieve_ids(one_path)) @@ -188,7 +192,9 @@ describe("org-roam.database", function() ---@return org-roam.core.database.Id[] local function retrieve_ids(origin) local nodes = db:find_nodes_by_origin_sync(origin) - return vim.tbl_map(function(node) return node.id end, nodes) + return vim.tbl_map(function(node) + return node.id + end, nodes) end assert.are.same({ "2" }, retrieve_ids("1")) @@ -204,7 +210,9 @@ describe("org-roam.database", function() ---@return org-roam.core.database.Id[] local function retrieve_ids(tag) local nodes = db:find_nodes_by_tag_sync(tag) - return vim.tbl_map(function(node) return node.id end, nodes) + return vim.tbl_map(function(node) + return node.id + end, nodes) end assert.are.same({ "1" }, retrieve_ids("one")) @@ -220,7 +228,9 @@ describe("org-roam.database", function() ---@return org-roam.core.database.Id[] local function retrieve_ids(title) local nodes = db:find_nodes_by_title_sync(title) - return vim.tbl_map(function(node) return node.id end, nodes) + return vim.tbl_map(function(node) + return node.id + end, nodes) end assert.are.same({ "1" }, retrieve_ids("one")) @@ -236,9 +246,12 @@ describe("org-roam.database", function() assert.are.same({ ["3"] = 1 }, db:get_file_links_sync(two_path)) -- If we specify a depth, more links are included - assert.are.same({ ["3"] = 1, ["1"] = 2 }, db:get_file_links_sync(two_path, { - max_depth = 2, - })) + assert.are.same( + { ["3"] = 1, ["1"] = 2 }, + db:get_file_links_sync(two_path, { + max_depth = 2, + }) + ) end) it("should support retrieving backlinks by file", function() @@ -249,8 +262,11 @@ describe("org-roam.database", function() assert.are.same({ ["1"] = 1 }, db:get_file_backlinks_sync(two_path)) -- If we specify a depth, more links are included - assert.are.same({ ["1"] = 1, ["3"] = 2 }, db:get_file_backlinks_sync(two_path, { - max_depth = 2, - })) + assert.are.same( + { ["1"] = 1, ["3"] = 2 }, + db:get_file_backlinks_sync(two_path, { + max_depth = 2, + }) + ) end) end) diff --git a/spec/events_spec.lua b/spec/events_spec.lua index b0d6eea..0f8a3ee 100644 --- a/spec/events_spec.lua +++ b/spec/events_spec.lua @@ -20,7 +20,7 @@ describe("org-roam.events", function() roam = utils.init_plugin({ setup = { directory = utils.make_temp_org_files_directory(), - } + }, }) test_path_one = utils.join_path(roam.config.directory, "one.org") test_path_two = utils.join_path(roam.config.directory, "two.org") @@ -60,7 +60,9 @@ describe("org-roam.events", function() it("moving around buffer with multiple nodes should report changes", function() -- Save the file without our test directory local test_path = utils.join_path(roam.config.directory, "new.org") - utils.write_to(test_path, utils.indent([=[ + utils.write_to( + test_path, + utils.indent([=[ :PROPERTIES: :ID: 1234 :END: @@ -74,7 +76,8 @@ describe("org-roam.events", function() :END: Some inner node text. - ]=])) + ]=]) + ) -- Reload the nodes into our database roam.database:load():wait() diff --git a/spec/extensions_dailies_spec.lua b/spec/extensions_dailies_spec.lua index ddb4bec..5e26d32 100644 --- a/spec/extensions_dailies_spec.lua +++ b/spec/extensions_dailies_spec.lua @@ -13,11 +13,7 @@ describe("org-roam.extensions.dailies", function() date = os.date("%Y-%m-%d", date.timestamp) end - local path = utils.join_path( - roam.config.directory, - roam.config.extensions.dailies.directory, - date .. ".org" - ) + local path = utils.join_path(roam.config.directory, roam.config.extensions.dailies.directory, date .. ".org") utils.write_to(path, ...) @@ -38,9 +34,9 @@ describe("org-roam.extensions.dailies", function() roam.database:load():wait() utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("d"), -- select "d" template - input = "Some title", -- input "Some title" on title prompt + input = "Some title", -- input "Some title" on title prompt }) -- Mock calendar to select a specific date @@ -85,9 +81,9 @@ describe("org-roam.extensions.dailies", function() roam.database:load():wait() utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("d"), -- select "d" template - input = "Some title", -- input "Some title" on title prompt + input = "Some title", -- input "Some title" on title prompt }) -- Start the capture process @@ -131,9 +127,9 @@ describe("org-roam.extensions.dailies", function() roam.database:load():wait() utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("d"), -- select "d" template - input = "Some title", -- input "Some title" on title prompt + input = "Some title", -- input "Some title" on title prompt }) local date = os.date("%Y-%m-%d", Date.today().timestamp) @@ -177,9 +173,9 @@ describe("org-roam.extensions.dailies", function() roam.database:load():wait() utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("d"), -- select "d" template - input = "Some title", -- input "Some title" on title prompt + input = "Some title", -- input "Some title" on title prompt }) local date = os.date("%Y-%m-%d", Date.tomorrow().timestamp) @@ -223,9 +219,9 @@ describe("org-roam.extensions.dailies", function() roam.database:load():wait() utils.mock_vim_inputs({ - confirm = 1, -- confirm yes for refile + confirm = 1, -- confirm yes for refile getchar = vim.fn.char2nr("d"), -- select "d" template - input = "Some title", -- input "Some title" on title prompt + input = "Some title", -- input "Some title" on title prompt }) local date = os.date("%Y-%m-%d", Date.today():subtract({ day = 1 }).timestamp) @@ -275,9 +271,11 @@ describe("org-roam.extensions.dailies", function() }) -- Do the navigation without opening the calendar - local date = roam.ext.dailies.goto_date({ - date = "2024-04-27", - }):wait() + local date = roam.ext.dailies + .goto_date({ + date = "2024-04-27", + }) + :wait() assert.are.equal(utils.date_from_string("2024-04-27"), date) @@ -292,9 +290,11 @@ describe("org-roam.extensions.dailies", function() roam.database:load():wait() -- Do the navigation without opening the calendar - local date = roam.ext.dailies.goto_date({ - date = "2024-04-27", - }):wait() + local date = roam.ext.dailies + .goto_date({ + date = "2024-04-27", + }) + :wait() assert.are.equal(utils.date_from_string("2024-04-27"), date) diff --git a/spec/minimal_init.lua b/spec/minimal_init.lua index f1a4467..084ea22 100644 --- a/spec/minimal_init.lua +++ b/spec/minimal_init.lua @@ -56,13 +56,13 @@ for _, plugin in ipairs(plugins) do -- If plugin not yet downloaded, do that now if vim.fn.isdirectory(plugin.path) == 0 then report("Downloading " .. plugin.name .. " into: " .. plugin.path) - vim.fn.system { + vim.fn.system({ "git", "clone", "--depth=1", plugin.repo, plugin.path, - } + }) end -- Add plugin to our runtime path diff --git a/spec/setup_autocmds_spec.lua b/spec/setup_autocmds_spec.lua index 6fdb261..ef97491 100644 --- a/spec/setup_autocmds_spec.lua +++ b/spec/setup_autocmds_spec.lua @@ -21,7 +21,7 @@ describe("org-roam.setup.autocmds", function() database = { update_on_save = true, }, - } + }, }) -- Ensure we are loaded @@ -56,7 +56,7 @@ describe("org-roam.setup.autocmds", function() database = { update_on_save = false, }, - } + }, }) -- Ensure we are loaded @@ -87,7 +87,7 @@ describe("org-roam.setup.autocmds", function() database = { persist = true, }, - } + }, }) -- Look for the persistence autocmd @@ -123,7 +123,7 @@ describe("org-roam.setup.autocmds", function() database = { persist = false, }, - } + }, }) -- Look for the persistence autocmd diff --git a/spec/setup_commands_spec.lua b/spec/setup_commands_spec.lua index 36183a2..390df77 100644 --- a/spec/setup_commands_spec.lua +++ b/spec/setup_commands_spec.lua @@ -49,18 +49,21 @@ describe("org-roam.setup.commands", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done roam.database:load():wait() -- Create a new file not loaded by the plugin yet - utils.write_to(utils.join_path(directory, "one.org"), utils.indent([=[ + utils.write_to( + utils.join_path(directory, "one.org"), + utils.indent([=[ :PROPERTIES: :ID: roam-update-node :END: - ]=])) + ]=]) + ) -- Trigger the command synchronously vim.cmd("RoamUpdate sync") @@ -79,18 +82,21 @@ describe("org-roam.setup.commands", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done roam.database:load():wait() -- Create a new file not loaded by the plugin yet - utils.write_to(utils.join_path(directory, "test.org"), utils.indent([=[ + utils.write_to( + utils.join_path(directory, "test.org"), + utils.indent([=[ :PROPERTIES: :ID: roam-update-node :END: - ]=])) + ]=]) + ) -- Trigger the command synchronously vim.cmd("RoamUpdate! sync") @@ -109,18 +115,21 @@ describe("org-roam.setup.commands", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done roam.database:load():wait() -- Create a new file not loaded by the plugin yet - utils.write_to(utils.join_path(directory, "test.org"), utils.indent([=[ + utils.write_to( + utils.join_path(directory, "test.org"), + utils.indent([=[ :PROPERTIES: :ID: roam-update-node :END: - ]=])) + ]=]) + ) -- Verify the database cache file exists assert.are.equal(1, vim.fn.filereadable(roam.config.database.path)) @@ -151,7 +160,7 @@ describe("org-roam.setup.commands", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -177,7 +186,7 @@ describe("org-roam.setup.commands", function() assert.are.same({ ":PROPERTIES:", ":ID: 1", - ":ROAM_ALIASES: one \"some alias\"", + ':ROAM_ALIASES: one "some alias"', ":END:", "#+FILETAGS: :one:", "", @@ -194,7 +203,7 @@ describe("org-roam.setup.commands", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -236,7 +245,7 @@ describe("org-roam.setup.commands", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -280,7 +289,7 @@ describe("org-roam.setup.commands", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done diff --git a/spec/setup_keybindings_spec.lua b/spec/setup_keybindings_spec.lua index 6e01149..b19b1ef 100644 --- a/spec/setup_keybindings_spec.lua +++ b/spec/setup_keybindings_spec.lua @@ -20,7 +20,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -52,7 +52,7 @@ describe("org-roam.setup.keybindings", function() assert.are.same({ ":PROPERTIES:", ":ID: 1", - ":ROAM_ALIASES: one \"some alias\"", + ':ROAM_ALIASES: one "some alias"', ":END:", "#+FILETAGS: :one:", "", @@ -71,7 +71,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -121,7 +121,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -173,7 +173,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -230,7 +230,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -266,7 +266,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -297,12 +297,15 @@ describe("org-roam.setup.keybindings", function() local directory = utils.make_temp_org_files_directory() local test_path = utils.join_path(directory, "test-file.org") - utils.write_to(test_path, utils.indent([=[ + utils.write_to( + test_path, + utils.indent([=[ :PROPERTIES: :ID: test-id :ROAM_ORIGIN: 1 :END: - ]=])) + ]=]) + ) -- Configure plugin to update database on write local roam = utils.init_plugin({ @@ -311,7 +314,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -353,7 +356,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -383,7 +386,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -422,7 +425,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -463,7 +466,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -501,7 +504,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -512,9 +515,9 @@ describe("org-roam.setup.keybindings", function() -- Select the default template utils.mock_vim_inputs({ - confirm = 0, -- confirm no for refile + confirm = 0, -- confirm no for refile getchar = vim.fn.char2nr("d"), -- select "d" template - input = "Some title", -- input "Some title" on title prompt + input = "Some title", -- input "Some title" on title prompt }) -- Trigger the keybinding and wait a bit @@ -555,7 +558,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -566,7 +569,7 @@ describe("org-roam.setup.keybindings", function() -- Select the default template utils.mock_vim_inputs({ - confirm = 0, -- confirm no for refile + confirm = 0, -- confirm no for refile getchar = vim.fn.char2nr("d"), -- select "d" template }) @@ -618,7 +621,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -657,7 +660,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -709,7 +712,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -741,7 +744,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -786,7 +789,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done @@ -818,7 +821,7 @@ describe("org-roam.setup.keybindings", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) -- Ensure loading is done diff --git a/spec/setup_modifications_spec.lua b/spec/setup_modifications_spec.lua index 9d9c18d..cda406c 100644 --- a/spec/setup_modifications_spec.lua +++ b/spec/setup_modifications_spec.lua @@ -17,7 +17,7 @@ describe("org-roam.setup.modifications", function() database = { path = utils.join_path(directory, "db"), }, - } + }, }) roam.database:load():wait() diff --git a/spec/ui_quickfix_spec.lua b/spec/ui_quickfix_spec.lua index 2a03ce7..262cd47 100644 --- a/spec/ui_quickfix_spec.lua +++ b/spec/ui_quickfix_spec.lua @@ -11,7 +11,7 @@ describe("org-roam.ui.quickfix", function() roam = utils.init_plugin({ setup = { directory = utils.make_temp_org_files_directory(), - } + }, }) test_path_two = utils.join_path(roam.config.directory, "two.org") end) @@ -103,7 +103,7 @@ describe("org-roam.ui.quickfix", function() end) assert.are.same({ { module = "(backlink) one", text = "", lnum = 7, col = 1 }, - { module = "(link) three", text = "", lnum = 0, col = 0 }, + { module = "(link) three", text = "", lnum = 0, col = 0 }, }, items) end) @@ -114,10 +114,12 @@ describe("org-roam.ui.quickfix", function() vim.cmd.edit(test_path_two) -- Open the quickfix list based on the node from two.org - roam.ui.open_quickfix_list({ - backlinks = true, - show_preview = true, - }):wait() + roam.ui + .open_quickfix_list({ + backlinks = true, + show_preview = true, + }) + :wait() -- Verify the quickfix contents assert.are.same({ diff --git a/spec/ui_select_node_spec.lua b/spec/ui_select_node_spec.lua index 6e35f14..752a473 100644 --- a/spec/ui_select_node_spec.lua +++ b/spec/ui_select_node_spec.lua @@ -44,7 +44,7 @@ describe("org-roam.ui.select-node", function() roam = utils.init_plugin({ setup = { directory = utils.make_temp_org_files_directory(), - } + }, }) end) @@ -141,7 +141,8 @@ describe("org-roam.ui.select-node", function() -- will automatically select a node and close itself local selected = false local id = nil - roam.ui.select_node({ auto_select = true, init_input = "one" }) + roam.ui + .select_node({ auto_select = true, init_input = "one" }) :on_choice(function(choice) id = choice.id selected = true @@ -165,8 +166,11 @@ describe("org-roam.ui.select-node", function() -- Load up the selection interface for all nodes with autoselect, which -- will do nothing because we have more than one node local selected = false - roam.ui.select_node({ auto_select = true, init_input = "o" }) - :on_choice(function() selected = true end) + roam.ui + .select_node({ auto_select = true, init_input = "o" }) + :on_choice(function() + selected = true + end) :open() utils.wait() @@ -192,9 +196,14 @@ describe("org-roam.ui.select-node", function() -- Allow missing selection, which we will trigger by pressing local canceled = false local selected = false - roam.ui.select_node({ init_input = "four" }) - :on_choice(function() selected = true end) - :on_cancel(function() canceled = true end) + roam.ui + .select_node({ init_input = "four" }) + :on_choice(function() + selected = true + end) + :on_cancel(function() + canceled = true + end) :open() utils.wait() @@ -214,7 +223,8 @@ describe("org-roam.ui.select-node", function() -- Allow missing selection, which we will trigger by pressing local label = "" local selected = false - roam.ui.select_node({ allow_select_missing = true }) + roam.ui + .select_node({ allow_select_missing = true }) :on_choice_missing(function(_label) label = _label selected = true @@ -256,7 +266,8 @@ describe("org-roam.ui.select-node", function() -- Don't allow selecting missing local label = "" local selected = false - roam.ui.select_node() + roam.ui + .select_node() :on_choice_missing(function(_label) label = _label selected = true diff --git a/spec/utils.lua b/spec/utils.lua index dfc5e79..8337f46 100644 --- a/spec/utils.lua +++ b/spec/utils.lua @@ -40,9 +40,7 @@ local __debug_enabled = nil function M.debug_print(...) if type(__debug_enabled) ~= "boolean" then local enabled = vim.env.ROAM_DEBUG - __debug_enabled = type(enabled) == "string" - and string.lower(vim.trim(enabled)) == "true" - or false + __debug_enabled = type(enabled) == "string" and string.lower(vim.trim(enabled)) == "true" or false end if __debug_enabled then @@ -103,9 +101,12 @@ function M.indent(s) end, nonempty_lines))) end - return table.concat(vim.tbl_map(function(line) - return string.sub(line, indent + 1) - end, lines), "\n") + return table.concat( + vim.tbl_map(function(line) + return string.sub(line, indent + 1) + end, lines), + "\n" + ) end ---Creates a new orgfile, stripping common indentation. @@ -149,9 +150,13 @@ function M.fake_node(opts) return Node:new(vim.tbl_deep_extend("keep", opts or {}, { id = uuid_v4(), range = Range:new({ - row = 0, column = 0, offset = 0, + row = 0, + column = 0, + offset = 0, }, { - row = 0, column = 0, offset = 0, + row = 0, + column = 0, + offset = 0, }), file = uuid_v4() .. ".org", mtime = 0, @@ -447,7 +452,9 @@ function M.clear_autocmds(group) local success, cmds = pcall(vim.api.nvim_get_autocmds, { group = group, }) - if not success then return end + if not success then + return + end for _, cmd in ipairs(cmds or {}) do local id = cmd.id if id then @@ -506,7 +513,7 @@ function M.mock_calendar(mock) else return Promise.resolve(mock) end - end + end, } end end @@ -608,7 +615,9 @@ function M.mock_vim_inputs(opts) if type(value) == "function" then tbl[key] = value elseif type(value) ~= "nil" then - tbl[key] = function() return value end + tbl[key] = function() + return value + end end end diff --git a/stylua.toml b/stylua.toml new file mode 100644 index 0000000..456db94 --- /dev/null +++ b/stylua.toml @@ -0,0 +1,3 @@ +column_width = 120 +indent_width = 4 +indent_type = "Spaces"