diff --git a/.luarc.json b/.luarc.json index 853a21c04..8ad58abf5 100644 --- a/.luarc.json +++ b/.luarc.json @@ -3,7 +3,6 @@ "Lua.diagnostics.globals": [ "_neorgcmd_generate_completions", "_neorg_module_autocommand_triggered", - "neorg", - "vim", + "vim" ] } diff --git a/docgen/docgen.lua b/docgen/docgen.lua index d7956982d..0e4f9d13d 100644 --- a/docgen/docgen.lua +++ b/docgen/docgen.lua @@ -1,3 +1,6 @@ +local neorg = require("neorg.core") +local lib, modules, utils = neorg.lib, neorg.modules, neorg.utils + local docgen = {} -- Create the directory if it does not exist @@ -32,11 +35,8 @@ require("neorg").setup({ -- Start neorg neorg.org_file_entered(false) --- Pull in the `neorg.lib` table -require("neorg.external.helpers") - -- Extract treesitter utility functions provided by Neorg and nvim-treesitter.ts_utils -local ts = neorg.modules.get_module("core.integrations.treesitter") +local ts = modules.get_module("core.integrations.treesitter") assert(ts, "treesitter not available") --- Aggregates all the available modules. @@ -155,7 +155,7 @@ end ---@param root userdata #The root node ---@return userdata? #The `module.config.public` node docgen.get_module_config_node = function(buffer, root) - local query = neorg.utils.ts_parse_query( + local query = utils.ts_parse_query( "lua", [[ (assignment_statement @@ -238,7 +238,7 @@ end docgen.evaluate_functions = function(tbl) local new = {} - neorg.lib.map(tbl, function(_, value) + lib.map(tbl, function(_, value) if type(value) == "function" then vim.list_extend(new, value()) else @@ -254,12 +254,12 @@ end --- Returns a function which itself returns a table of links to modules -- in a markdown-like unordered list. ----@param modules Modules #A table of modules to enumerate +---@param mods Modules #A table of modules to enumerate ---@param predicate fun(Module):boolean #A predicate that determines whether or not to render this object. --- If the predicate returns false, then the object is dismissed. ---@return fun():string[] #An array of markdown strings with the enumerated modules -local function list_modules_with_predicate(modules, predicate) - local sorted = neorg.lib.unroll(modules) +local function list_modules_with_predicate(mods, predicate) + local sorted = lib.unroll(mods) table.sort(sorted, function(x, y) return x[1] < y[1] @@ -301,9 +301,9 @@ end docgen.generators = { --- Generates the Home.md file - ---@param modules Modules #A table of modules - homepage = function(modules) - local core_defaults = modules["core.defaults"] + ---@param mods Modules #A table of modules + homepage = function(mods) + local core_defaults = mods["core.defaults"] assert(core_defaults, "core.defaults module not loaded!") local structure = { @@ -350,7 +350,7 @@ docgen.generators = { } end, "", - list_modules_with_predicate(modules, function(data) + list_modules_with_predicate(mods, function(data) return vim.tbl_contains(core_defaults.parsed.config.public.enable, data.parsed.name) and not data.top_comment_data.internal end), @@ -360,7 +360,7 @@ docgen.generators = { "Some modules are not included by default as they require some manual configuration or are merely extra bells and whistles", "and are not critical to editing `.norg` files. Below is a list of all modules that are not required by default:", "", - list_modules_with_predicate(modules, function(data) + list_modules_with_predicate(mods, function(data) return not data.parsed.extension and not vim.tbl_contains(core_defaults.parsed.config.public.enable, data.parsed.name) and not data.top_comment_data.internal @@ -370,7 +370,7 @@ docgen.generators = { "", "These are modules that are only meant for developers. They are generally required in other modules:", "", - list_modules_with_predicate(modules, function(data) + list_modules_with_predicate(mods, function(data) return not data.parsed.extension and data.top_comment_data.internal end), } @@ -379,8 +379,8 @@ docgen.generators = { end, --- Generates the _Sidebar.md file - ---@param modules Modules #A table of modules - sidebar = function(modules) + ---@param mods Modules #A table of modules + sidebar = function(mods) local structure = { "
", "", @@ -395,7 +395,7 @@ docgen.generators = { local res = {} local names = {} - for n, data in pairs(modules) do + for n, data in pairs(mods) do if data.parsed.extension ~= true then table.insert(names, n) end @@ -404,7 +404,7 @@ docgen.generators = { table.sort(names) for _, name in ipairs(names) do - local data = modules[name] + local data = mods[name] if not data.parsed.internal then local insert = "" if data.top_comment_data.file then @@ -432,11 +432,11 @@ docgen.generators = { end, --- Generates the page for any Neorg module - ---@param modules Modules #The list of currently loaded modules + ---@param mods Modules #The list of currently loaded modules ---@param module Module #The module we want to generate the page for ---@param configuration string[] #An array of markdown strings detailing the configuration options for the module ---@return string[] #A table of markdown strings representing the page - module = function(modules, module, configuration) + module = function(mods, module, configuration) local structure = { '
', "", @@ -483,7 +483,7 @@ docgen.generators = { local module_list = {} for _, module_name in ipairs(required_modules) do - module_list[module_name] = modules[module_name] + module_list[module_name] = mods[module_name] end return docgen.evaluate_functions({ @@ -498,7 +498,7 @@ docgen.generators = { function() local required_by = {} - for mod, data in pairs(modules) do + for mod, data in pairs(mods) do local required_modules = data.parsed.setup().requires or {} if vim.tbl_contains(required_modules, module.parsed.name) then @@ -538,18 +538,18 @@ docgen.check_comment_integrity = function(comment) end --- Replaces all instances of a module reference (e.g. `@core.concealer`) with a link in the wiki ----@param modules Modules #The list of loaded modules +---@param mods Modules #The list of loaded modules ---@param str string #The string to perform the lookup in ---@return string #The original `str` parameter with all `@` references replaced with links -docgen.lookup_modules = function(modules, str) +docgen.lookup_modules = function(mods, str) return ( str:gsub("@([%-%.%w]+)", function(target_module_name) - if not modules[target_module_name] then + if not mods[target_module_name] then return table.concat({ "@", target_module_name }) else return table.concat({ "https://github.com/nvim-neorg/neorg/wiki/", - modules[target_module_name].top_comment_data.file, + mods[target_module_name].top_comment_data.file, }) end end) @@ -647,14 +647,14 @@ docgen.htmlify = function(configuration_option) local result = {} local code_block = true - neorg.lib.match(self.data.value:type())({ + lib.match(self.data.value:type())({ string = function() table.insert(result, table.concat({ '"', self.object, '"' })) end, table_constructor = function() table.insert(result, "") - local unrolled = neorg.lib.unroll(self.object) + local unrolled = lib.unroll(self.object) table.sort(unrolled, function(x, y) return tostring(x[1]) < tostring(y[1]) diff --git a/docgen/init.lua b/docgen/init.lua index 84cf2c0ee..3ae4852a0 100644 --- a/docgen/init.lua +++ b/docgen/init.lua @@ -1,3 +1,6 @@ +local neorg = require("neorg.core") +local lib, modules = neorg.lib, neorg.modules + local docgen = require("docgen") local fileio = require("fileio") @@ -10,7 +13,7 @@ local config = { } ---@type Modules -local modules = { +local doc_modules = { --[[ [name] = { top_comment_data... @@ -26,7 +29,7 @@ local modules = { local function concat_configuration_options(configuration_options) local result = {} - local unrolled = neorg.lib.unroll(configuration_options) + local unrolled = lib.unroll(configuration_options) table.sort(unrolled, function(x, y) return x[1] < y[1] @@ -68,12 +71,12 @@ for _, file in ipairs(docgen.aggregate_module_files()) do end -- Make Neorg load the module, which also evaluates dependencies - neorg.modules.load_module(parsed_module.name) + modules.load_module(parsed_module.name) -- Retrieve the module from the `loaded_modules` table. - parsed_module = neorg.modules.loaded_modules[parsed_module.name] + parsed_module = modules.loaded_modules[parsed_module.name] - modules[parsed_module.name] = { + doc_modules[parsed_module.name] = { top_comment_data = top_comment_data, buffer = buffer, parsed = parsed_module, @@ -83,11 +86,11 @@ for _, file in ipairs(docgen.aggregate_module_files()) do end -- Non-module pages have their own dedicated generators -fileio.write_to_wiki("Home", docgen.generators.homepage(modules)) -fileio.write_to_wiki("_Sidebar", docgen.generators.sidebar(modules)) +fileio.write_to_wiki("Home", docgen.generators.homepage(doc_modules)) +fileio.write_to_wiki("_Sidebar", docgen.generators.sidebar(doc_modules)) -- Loop through all modules and generate their respective wiki files -for module_name, module in pairs(modules) do +for module_name, module in pairs(doc_modules) do local buffer = module.buffer -- Query the root node and try to find a `module.config.public` table @@ -101,7 +104,7 @@ for module_name, module in pairs(modules) do if config_node then docgen.map_config(buffer, config_node, function(data, comments) for i, comment in ipairs(comments) do - comments[i] = docgen.lookup_modules(modules, comment:gsub("^%s*%-%-+%s*", "")) + comments[i] = docgen.lookup_modules(doc_modules, comment:gsub("^%s*%-%-+%s*", "")) end do @@ -130,7 +133,7 @@ for module_name, module in pairs(modules) do local object = docgen.to_lua_object(module.parsed, buffer, data.value, module_name) do - neorg.lib.ensure_nested(configuration_options, unpack(data.parents)) + lib.ensure_nested(configuration_options, unpack(data.parents)) local ref = vim.tbl_get(configuration_options, unpack(data.parents)) or configuration_options if data.name then ref[data.name] = { @@ -159,11 +162,11 @@ for module_name, module in pairs(modules) do -- This cannot be done earlier because then there would be no guarantee -- that all the modules have been properly indexed and parsed. for i, line in ipairs(module.top_comment_data.markdown) do - module.top_comment_data.markdown[i] = docgen.lookup_modules(modules, line) + module.top_comment_data.markdown[i] = docgen.lookup_modules(doc_modules, line) end fileio.write_to_wiki( module.top_comment_data.file, - docgen.generators.module(modules, module, concat_configuration_options(configuration_options)) + docgen.generators.module(doc_modules, module, concat_configuration_options(configuration_options)) ) end diff --git a/lua/neorg.lua b/lua/neorg.lua index cee9b5b13..d7377006e 100644 --- a/lua/neorg.lua +++ b/lua/neorg.lua @@ -4,19 +4,16 @@ --]] -- Require the most important modules -require("neorg.callbacks") -require("neorg.events") -require("neorg.modules") +local neorg = require("neorg.core") +local config, log, modules = neorg.config, neorg.log, neorg.modules -local configuration = require("neorg.config") - ---- This function takes in a user configuration, parses it, initializes everything and launches neorg if inside a .norg or .org file ----@param config table #A table that reflects the structure of configuration.user_configuration -function neorg.setup(config) - configuration.user_configuration = vim.tbl_deep_extend("force", configuration.user_configuration, config or {}) +--- This function takes in a user config, parses it, initializes everything and launches neorg if inside a .norg or .org file +---@param cfg table #A table that reflects the structure of config.user_config +function neorg.setup(cfg) + config.user_config = vim.tbl_deep_extend("force", config.user_config, cfg or {}) -- Create a new global instance of the neorg logger - require("neorg.external.log").new(configuration.user_configuration.logger or log.get_default_config(), true) + log.new(config.user_config.logger or log.get_default_config(), true) -- Make the Neorg filetype detectable through `vim.filetype`. -- TODO: Make a PR to Neovim to natively support the org and norg @@ -28,7 +25,7 @@ function neorg.setup(config) }) -- If the file we have entered has a .norg extension - if vim.fn.expand("%:e") == "norg" or not configuration.user_configuration.lazy_loading then + if vim.fn.expand("%:e") == "norg" or not config.user_config.lazy_loading then -- Then boot up the environment neorg.org_file_entered(false) else @@ -51,31 +48,31 @@ end ---@param manual boolean #If true then the environment was kickstarted manually by the user ---@param arguments string? #A list of arguments in the format of "key=value other_key=other_value" function neorg.org_file_entered(manual, arguments) - -- Extract the module list from the user configuration - local module_list = configuration.user_configuration and configuration.user_configuration.load or {} + -- Extract the module list from the user config + local module_list = config.user_config and config.user_config.load or {} -- If we have already started Neorg or if we haven't defined any modules to load then bail - if configuration.started or not module_list or vim.tbl_isempty(module_list) then + if config.started or not module_list or vim.tbl_isempty(module_list) then return end -- If the user has defined a post-load hook then execute it - if configuration.user_configuration.hook then - configuration.user_configuration.hook(manual, arguments) + if config.user_config.hook then + config.user_config.hook(manual, arguments) end -- If Neorg was loaded manually (through `:NeorgStart`) then set this flag to true - configuration.manual = manual + config.manual = manual -- If the user has supplied any Neorg environment variables -- then parse those here if arguments and arguments:len() > 0 then for key, value in arguments:gmatch("([%w%W]+)=([%w%W]+)") do - configuration.arguments[key] = value + config.arguments[key] = value end end - -- Go through each defined module and grab its configuration + -- Go through each defined module and grab its config for name, module in pairs(module_list) do -- If the module's data is not empty and we have not defined a config table then it probably means there's junk in there if not vim.tbl_isempty(module) and not module.config then @@ -86,31 +83,31 @@ function neorg.org_file_entered(manual, arguments) ) end - -- Apply the configuration - configuration.modules[name] = - vim.tbl_deep_extend("force", configuration.modules[name] or {}, module.config or {}) + -- Apply the config + config.modules[name] = + vim.tbl_deep_extend("force", config.modules[name] or {}, module.config or {}) end - -- After all configurations are merged proceed to actually load the modules - local load_module = neorg.modules.load_module + -- After all config are merged proceed to actually load the modules + local load_module = modules.load_module for name, _ in pairs(module_list) do -- If it could not be loaded then halt if not load_module(name) then log.warn("Recovering from error...") - neorg.modules.loaded_modules[name] = nil + modules.loaded_modules[name] = nil end end -- Goes through each loaded module and invokes neorg_post_load() - for _, module in pairs(neorg.modules.loaded_modules) do + for _, module in pairs(modules.loaded_modules) do module.neorg_post_load() end -- Set this variable to prevent Neorg from loading twice - configuration.started = true + config.started = true -- Lets the entire Neorg environment know that Neorg has started! - neorg.events.broadcast_event({ + modules.broadcast_event({ type = "core.started", split_type = { "core", "started" }, filename = "", @@ -130,7 +127,7 @@ end --- Returns whether or not Neorg is loaded ---@return boolean function neorg.is_loaded() - return configuration.started + return config.started end return neorg diff --git a/lua/neorg/config.lua b/lua/neorg/config.lua deleted file mode 100644 index 47f3aa227..000000000 --- a/lua/neorg/config.lua +++ /dev/null @@ -1,85 +0,0 @@ --- Configuration template -neorg.configuration = { - - user_configuration = { - lazy_loading = false, - load = { - --[[ - ["name"] = { config = { ... } } - --]] - }, - }, - - modules = {}, - manual = nil, - arguments = {}, - - norg_version = "1.1.1", - version = "5.0.0", - - neovim_version = (function() - require("neorg.external.helpers") - - local data = {} - local parsed_output = vim.api.nvim_exec("version", true) - - for _, line in ipairs(vim.split(parsed_output, "\n")) do - local key, value = line:match("^%s*(.+[^%s]):%s+(.+)$") - - if not key then - key, value = line:match("^(NVIM)%s+v%d+%.%d+%.%d+%-%w+%-(%d+).+") - end - - if not key then - key, value = line:match("(LUAJIT)%s+(.+)") - end - - if key then - key = key:lower():gsub("%p", ""):gsub("%s", "-") - - value = neorg.lib.match(key)({ - compilation = function() - local split = vim.split(value, "%s+") - - split.compiler = table.remove(split, 1) - return split - end, - features = neorg.lib.wrap(vim.split, value, "%s*%+", { - trimempty = true, - }), - nvim = tonumber(value), - _ = value:gsub('^"?', ""):gsub('"?$', ""), - }) - - data[key] = value - end - end - - return data - end)(), -} - --- Grab OS info on startup -neorg.configuration.os_info = (function() - local os = vim.loop.os_uname().sysname:lower() - - if os:find("windows_nt") then - return "windows" - elseif os == "darwin" then - return "mac" - elseif os == "linux" then - local f = io.open('/proc/version', 'r') - if f ~= nil then - local version = f:read('*all') - f:close() - if version:find('microsoft') then - return "wsl" - end - end - return "linux" - end -end)() - -neorg.configuration.pathsep = neorg.configuration.os_info == "windows" and "\\" or "/" - -return neorg.configuration diff --git a/lua/neorg/callbacks.lua b/lua/neorg/core/callbacks.lua similarity index 68% rename from lua/neorg/callbacks.lua rename to lua/neorg/core/callbacks.lua index f44549f72..23123d8a7 100644 --- a/lua/neorg/callbacks.lua +++ b/lua/neorg/core/callbacks.lua @@ -3,10 +3,7 @@ User callbacks are ways for the user to directly interact with Neorg and respond on certain events. --]] ----@diagnostic disable-next-line: lowercase-global -neorg = {} - -neorg.callbacks = { +local callbacks = { callback_list = {}, } @@ -14,18 +11,18 @@ neorg.callbacks = { ---@param event_name string #The full path to the event we want to listen on ---@param callback fun(event, content) #The function to call whenever our event gets triggered ---@param content_filter fun(event) #A filtering function to test if a certain event meets our expectations -function neorg.callbacks.on_event(event_name, callback, content_filter) +function callbacks.on_event(event_name, callback, content_filter) -- If the table doesn't exist then create it - neorg.callbacks.callback_list[event_name] = neorg.callbacks.callback_list[event_name] or {} + callbacks.callback_list[event_name] = callbacks.callback_list[event_name] or {} -- Insert the callback and content filter - table.insert(neorg.callbacks.callback_list[event_name], { callback, content_filter }) + table.insert(callbacks.callback_list[event_name], { callback, content_filter }) end --- Used internally by Neorg to call all callbacks with an event ----@param event table #An event as returned by neorg.events.create() -function neorg.callbacks.handle_callbacks(event) +---@param event table #An event as returned by modules.create_event() +function callbacks.handle_callbacks(event) -- Query the list of registered callbacks - local callback_entry = neorg.callbacks.callback_list[event.type] + local callback_entry = callbacks.callback_list[event.type] -- If the callbacks exist then if callback_entry then @@ -40,4 +37,4 @@ function neorg.callbacks.handle_callbacks(event) end end -return neorg.callbacks +return callbacks diff --git a/lua/neorg/core/config.lua b/lua/neorg/core/config.lua new file mode 100644 index 000000000..6294241a9 --- /dev/null +++ b/lua/neorg/core/config.lua @@ -0,0 +1,91 @@ +local lib = require("neorg.core.lib") + + +local function neovim_version() + local data = {} + local parsed_output = vim.api.nvim_exec("version", true) + + for _, line in ipairs(vim.split(parsed_output, "\n")) do + local key, value = line:match("^%s*(.+[^%s]):%s+(.+)$") + + if not key then + key, value = line:match("^(NVIM)%s+v%d+%.%d+%.%d+%-%w+%-(%d+).+") + end + + if not key then + key, value = line:match("(LUAJIT)%s+(.+)") + end + + if key then + key = key:lower():gsub("%p", ""):gsub("%s", "-") + + value = lib.match(key)({ + compilation = function() + local split = vim.split(value, "%s+") + + split.compiler = table.remove(split, 1) + return split + end, + features = lib.wrap(vim.split, value, "%s*%+", { + trimempty = true, + }), + nvim = tonumber(value), + _ = value:gsub('^"?', ""):gsub('"?$', ""), + }) + + data[key] = value + end + end + + return data +end + + +-- Grab OS info on startup +local function os_info() + local os = vim.loop.os_uname().sysname:lower() + + if os:find("windows_nt") then + return "windows" + elseif os == "darwin" then + return "mac" + elseif os == "linux" then + local f = io.open('/proc/version', 'r') + if f ~= nil then + local version = f:read('*all') + f:close() + if version:find('microsoft') then + return "wsl" + end + end + return "linux" + end +end + + +-- Configuration template +local config = { + user_config = { + lazy_loading = false, + load = { + --[[ + ["name"] = { config = { ... } } + --]] + }, + }, + + modules = {}, + manual = nil, + arguments = {}, + + norg_version = "1.1.1", + version = "5.0.0", + + neovim_version = neovim_version(), + os_info = os_info(), +} + +-- TODO: Is there a better way to define this inside the body of `config'? +config.pathsep = config.os_info == "windows" and "\\" or "/" + +return config diff --git a/lua/neorg/core/init.lua b/lua/neorg/core/init.lua new file mode 100644 index 000000000..3d5dc635c --- /dev/null +++ b/lua/neorg/core/init.lua @@ -0,0 +1,10 @@ +local neorg = { + callbacks = require("neorg.core.callbacks"), + config = require("neorg.core.config"), + lib = require("neorg.core.lib"), + log = require("neorg.core.log"), + modules = require("neorg.core.modules"), + utils = require("neorg.core.utils"), +} + +return neorg diff --git a/lua/neorg/core/lib.lua b/lua/neorg/core/lib.lua new file mode 100644 index 000000000..8dd49e4ee --- /dev/null +++ b/lua/neorg/core/lib.lua @@ -0,0 +1,514 @@ +local lib = { + -- TODO: Are the mod functions used anywhere? + mod = { --- Modifiers for the `map` function + exclude = {} --- Filtering modifiers that exclude certain elements from a table + } +} + + +--- Returns the item that matches the first item in statements +---@param value any #The value to compare against +---@param compare? function #A custom comparison function +---@return function #A function to invoke with a table of potential matches +function lib.match(value, compare) + -- Returning a function allows for such syntax: + -- match(something) { ..matches.. } + return function(statements) + if value == nil then + return + end + + -- Set the comparison function + -- A comparison function may be required for more complex + -- data types that need to be compared against another static value. + -- The default comparison function compares booleans as strings to ensure + -- that boolean comparisons work as intended. + compare = compare + or function(lhs, rhs) + if type(lhs) == "boolean" then + return tostring(lhs) == rhs + end + + return lhs == rhs + end + + -- Go through every statement, compare it, and perform the desired action + -- if the comparison was successful + for case, action in pairs(statements) do + -- If the case statement is a list of data then compare that + if type(case) == "table" and vim.tbl_islist(case) then + for _, subcase in ipairs(case) do + if compare(value, subcase) then + -- The action can be a function, in which case it is invoked + -- and the return value of that function is returned instead. + if type(action) == "function" then + return action(value) + end + + return action + end + end + end + + if compare(value, case) then + -- The action can be a function, in which case it is invoked + -- and the return value of that function is returned instead. + if type(action) == "function" then + return action(value) + end + + return action + end + end + + -- If we've fallen through all statements to check and haven't found + -- a single match then see if we can fall back to a `_` clause instead. + if statements._ then + local action = statements._ + + if type(action) == "function" then + return action(value) + end + + return action + end + end +end + + +--- Wrapped around `match()` that performs an action based on a condition +---@param comparison boolean #The comparison to perform +---@param when_true function|any #The value to return when `comparison` is true +---@param when_false function|any #The value to return when `comparison` is false +---@return any #The value that either `when_true` or `when_false` returned +function lib.when(comparison, when_true, when_false) + if type(comparison) ~= "boolean" then + comparison = (comparison ~= nil) + end + + return lib.match(type(comparison) == "table" and unpack(comparison) or comparison)({ + ["true"] = when_true, + ["false"] = when_false, + }) +end + + +--- Maps a function to every element of a table +-- The function can return a value, in which case that specific element will be assigned +-- the return value of that function. +---@param tbl table #The table to iterate over +---@param callback function #The callback that should be invoked on every iteration +---@return table #A modified version of the original `tbl`. +function lib.map(tbl, callback) + local copy = vim.deepcopy(tbl) + + for k, v in pairs(tbl) do + local cb = callback(k, v, tbl) + + if cb then + copy[k] = cb + end + end + + return copy +end + + +--- Iterates over all elements of a table and returns the first value returned by the callback. +---@param tbl table #The table to iterate over +---@param callback function #The callback function that should be invoked on each iteration. +--- Can return a value in which case that value will be returned from the `filter()` call. +---@return any|nil #The value returned by `callback`, if any +function lib.filter(tbl, callback) + for k, v in pairs(tbl) do + local cb = callback(k, v) + + if cb then + return cb + end + end +end + + +--- Finds any key in an array +---@param tbl array #An array of values to iterate over +---@param element any #The item to find +---@return any|nil #The found value or `nil` if nothing could be found +function lib.find(tbl, element) + return lib.filter(tbl, function(key, value) + if value == element then + return key + end + end) +end + + +--- Inserts a value into a table if it doesn't exist, else returns the existing value. +---@param tbl table #The table to insert into +---@param value number|string #The value to insert +---@return any #The item to return +function lib.insert_or(tbl, value) + local item = lib.find(tbl, value) + + return item and tbl[item] + or (function() + table.insert(tbl, value) + return value + end)() + end + + +--- Picks a set of values from a table and returns them in an array +---@param tbl table #The table to extract the keys from +---@param values array[string] #An array of strings, these being the keys you'd like to extract +---@return array[any] #The picked values from the table +function lib.pick(tbl, values) + local result = {} + + for _, value in ipairs(values) do + if tbl[value] then + table.insert(result, tbl[value]) + end + end + + return result +end + + +--- Tries to extract a variable in all nesting levels of a table. +---@param tbl table #The table to traverse +---@param value any #The value to look for - note that comparison is done through the `==` operator +---@return any|nil #The value if it was found, else nil +function lib.extract(tbl, value) + local results = {} + + for key, expected_value in pairs(tbl) do + if key == value then + table.insert(results, expected_value) + end + + if type(expected_value) == "table" then + vim.list_extend(results, lib.extract(expected_value, value)) + end + end + + return results +end + + +--- Wraps a conditional "not" function in a vim.tbl callback +---@param cb function #The function to wrap +---@vararg ... #The arguments to pass to the wrapped function +---@return function #The wrapped function in a vim.tbl callback +function lib.wrap_cond_not(cb, ...) + local params = { ... } + return function(v) + return not cb(v, unpack(params)) + end +end + + +--- Wraps a conditional function in a vim.tbl callback +---@param cb function #The function to wrap +---@vararg ... #The arguments to pass to the wrapped function +---@return function #The wrapped function in a vim.tbl callback +function lib.wrap_cond(cb, ...) + local params = { ... } + return function(v) + return cb(v, unpack(params)) + end +end + + +--- Wraps a function in a callback +---@param function_pointer function #The function to wrap +---@vararg ... #The arguments to pass to the wrapped function +---@return function #The wrapped function in a callback +function lib.wrap(function_pointer, ...) + local params = { ... } + + if type(function_pointer) ~= "function" then + local prev = function_pointer + + -- luacheck: push ignore + function_pointer = function(...) + return prev, unpack(params) + end + -- luacheck: pop + end + + return function() + return function_pointer(unpack(params)) + end +end + + +--- Repeats an arguments `index` amount of times +---@param value any #The value to repeat +---@param index number #The amount of times to repeat the argument +---@return ... #An expanded vararg with the repeated argument +function lib.reparg(value, index) + if index == 1 then + return value + end + + return value, lib.reparg(value, index - 1) +end + + +--- Lazily concatenates a string to prevent runtime errors where an object may not exist +-- Consider the following example: +-- +-- lib.when(str ~= nil, str .. " extra text", "") +-- +-- This would fail, simply because the string concatenation will still be evaluated in order +-- to be placed inside the variable. You may use: +-- +-- lib.when(str ~= nil, lib.lazy_string_concat(str, " extra text"), "") +-- +-- To mitigate this issue directly. +--- @vararg string #An unlimited number of strings +---@return string #The result of all the strings concatenateA. +function lib.lazy_string_concat(...) + return table.concat({ ... }) +end + + +--- Converts an array of values to a table of keys +---@param values string[]|number[] #An array of values to store as keys +---@param default any #The default value to assign to all key pairs +---@return table #The converted table +function lib.to_keys(values, default) + local ret = {} + + for _, value in ipairs(values) do + ret[value] = default or {} + end + + return ret +end + + +--- Constructs a new key-pair table by running a callback on all elements of an array. +---@param keys string[] #A string array with the keys to iterate over +---@param cb function #A function that gets invoked with each key and returns a value to be placed in the output table +---@return table #The newly constructed table +function lib.construct(keys, cb) + local result = {} + + for _, key in ipairs(keys) do + result[key] = cb(key) + end + + return result +end + + +--- If `val` is a function, executes it with the desired arguments, else just returns `val` +---@param val any|function #Either a function or any other value +---@vararg any #Potential arguments to give `val` if it is a function +---@return any #The returned evaluation of `val` +function lib.eval(val, ...) + if type(val) == "function" then + return val(...) + end + + return val +end + + +--- Extends a list by constructing a new one vs mutating an existing +-- list in the case of `vim.list_extend` +function lib.list_extend(list, ...) + return list and { unpack(list), unpack(lib.list_extend(...)) } or {} +end + + +--- Converts a table with `key = value` pairs to a `{ key, value }` array. +---@param tbl_with_keys table #A table with key-value pairs +---@return array #An array of `{ key, value }` pairs. +function lib.unroll(tbl_with_keys) + local res = {} + + for key, value in pairs(tbl_with_keys) do + table.insert(res, { key, value }) + end + + return res +end + + +--- Works just like pcall, except returns only a single value or nil (useful for ternary operations +-- which are not possible with a function like `pcall` that returns two values). +---@param func function #The function to invoke in a protected environment +---@vararg any #The parameters to pass to `func` +---@return any|nil #The return value of the executed function or `nil` +function lib.inline_pcall(func, ...) + local ok, ret = pcall(func, ...) + + if ok then + return ret + end + + -- return nil +end + + +--- Perform a backwards search for a character and return the index of that character +---@param str string #The string to search +---@param char string #The substring to search for +---@return number|nil #The index of the found substring or `nil` if not found +function lib.rfind(str, char) + local length = str:len() + local found_from_back = str:reverse():find(char) + return found_from_back and length - found_from_back +end + + +--- Ensure that a nested set of variables exists. +-- Useful when you want to initialise a chain of nested values before writing to them. +---@param tbl table #The table you want to modify +---@vararg string #A list of indices to recursively nest into. +function lib.ensure_nested(tbl, ...) + local ref = tbl or {} + + for _, key in ipairs({ ... }) do + ref[key] = ref[key] or {} + ref = ref[key] + end +end + + +--- Capitalizes the first letter of each word in a given string. +---@param str string #The string to capitalize +---@return string #The capitalized string. +function lib.title(str) + local result = {} + + for word in str:gmatch("[^%s]+") do + local lower = word:sub(2):lower() + + table.insert(result, word:sub(1, 1):upper() .. lower) + end + return table.concat(result, " ") +end + + +--- Wraps a number so that it fits within a given range. +---@param value number #The number to wrap +---@param min number #The lower bound +---@param max number #The higher bound +---@return number #The wrapped number, guarantees `min <= value <= max`. +function lib.number_wrap(value, min, max) + local range = max - min + 1 + local wrapped_value = ((value - min) % range) + min + + if wrapped_value < min then + wrapped_value = wrapped_value + range + end + + return wrapped_value +end + + +--- Lazily copy a table-like object. +---@param to_copy table|any #The table to copy. If any other type is provided it will be copied immediately. +---@return table #The copied table +function lib.lazy_copy(to_copy) + if type(to_copy) ~= "table" then + return vim.deepcopy(to_copy) + end + + local proxy = { + original = function() + return to_copy + end, + + collect = function(self) + return vim.tbl_deep_extend("force", to_copy, self) + end, + } + + return setmetatable(proxy, { + __index = function(_, key) + if not to_copy[key] then + return nil + end + + if type(to_copy[key]) == "table" then + local copied = lib.lazy_copy(to_copy[key]) + + rawset(proxy, key, copied) + + return copied + end + + local copied = vim.deepcopy(to_copy[key]) + rawset(proxy, key, copied) + return copied + end, + + __pairs = function(tbl) + local function stateless_iter(_, key) + local value + key, value = next(to_copy, key) + if value ~= nil then + return key, lib.lazy_copy(value) + end + end + + return stateless_iter, tbl, nil + end, + + __ipairs = function(tbl) + local function stateless_iter(_, i) + i = i + 1 + local value = to_copy[i] + if value ~= nil then + return i, lib.lazy_copy(value) + end + end + + return stateless_iter, tbl, 0 + end, + }) +end + + +--- Wrapper function to add two values +-- This function only takes in one argument because the second value +-- to add is provided as a parameter in the callback. +---@param amount number #The number to add +---@return function #A callback adding the static value to the dynamic amount +function lib.mod.add(amount) + return function(_, value) + return value + amount + end +end + + +--- Wrapper function to set a value to another value in a `map` sequence +---@param to any #A static value to set each element of the table to +---@return function #A callback that returns the static value +function lib.mod.modify(to) + return function() + return to + end +end + + +function lib.mod.exclude.first(func, alt) + return function(i, val) + return i == 1 and (alt and alt(i, val) or val) or func(i, val) + end +end + + +function lib.mod.exclude.last(func, alt) + return function(i, val, tbl) + return next(tbl, i) and func(i, val) or (alt and alt(i, val) or val) + end +end + + +return lib diff --git a/lua/neorg/core/log.lua b/lua/neorg/core/log.lua new file mode 100644 index 000000000..dd7711273 --- /dev/null +++ b/lua/neorg/core/log.lua @@ -0,0 +1,155 @@ +-- log.lua +-- +-- Inspired by rxi/log.lua +-- Modified by tjdevries and can be found at github.com/tjdevries/vlog.nvim +-- Modified again by Vhyrro for use with neorg :) +-- +-- This library is free software; you can redistribute it and/or modify it +-- under the terms of the MIT license. See LICENSE for details. + +local lib = require("neorg.core.lib") + +-- User configuration section +local default_config = { + -- Name of the plugin. Prepended to log messages + plugin = "neorg", + + -- Should print the output to neovim while running + use_console = true, + + -- Should highlighting be used in console (using echohl) + highlights = true, + + -- Should write to a file + use_file = true, + + -- Any messages above this level will be logged. + level = "warn", + + -- Level configuration + modes = { + { name = "trace", hl = "Comment", level = vim.log.levels.TRACE }, + { name = "debug", hl = "Comment", level = vim.log.levels.DEBUG }, + { name = "info", hl = "None", level = vim.log.levels.INFO }, + { name = "warn", hl = "WarningMsg", level = vim.log.levels.WARN }, + { name = "error", hl = "ErrorMsg", level = vim.log.levels.ERROR }, + { name = "fatal", hl = "ErrorMsg", level = 5 }, + }, + + -- Can limit the number of decimals displayed for floats + float_precision = 0.01, +} + +-- {{{ NO NEED TO CHANGE +local log = {} + +log.get_default_config = function() + return default_config +end + +local unpack = unpack or table.unpack + +log.new = function(config, standalone) + config = vim.tbl_deep_extend("force", default_config, config) + config.plugin = "neorg" -- Force the plugin name to be neorg + + local outfile = string.format("%s/%s.log", vim.api.nvim_call_function("stdpath", { "data" }), config.plugin) + + local obj = lib.match(standalone ~= nil)({ + ["true"] = log, + ["false"] = {}, + }) + + local levels = {} + for _, v in ipairs(config.modes) do + levels[v.name] = v.level + end + + local round = function(x, increment) + increment = increment or 1 + x = x / increment + return (x > 0 and math.floor(x + 0.5) or math.ceil(x - 0.5)) * increment + end + + local make_string = function(...) + local t = {} + for i = 1, select("#", ...) do + local x = select(i, ...) + + if type(x) == "number" and config.float_precision then + x = tostring(round(x, config.float_precision)) + elseif type(x) == "table" then + x = vim.inspect(x) + else + x = tostring(x) + end + + t[#t + 1] = x + end + return table.concat(t, " ") + end + + local log_at_level = function(level_config, message_maker, ...) + -- Return early if we"re below the config.level + if levels[level_config.name] < levels[config.level] then + return + end + local nameupper = level_config.name:upper() + + local msg = message_maker(...) + local info = debug.getinfo(2, "Sl") + local lineinfo = info.short_src .. ":" .. info.currentline + + -- Output to console + if config.use_console then + local v = string.format("(%s)\n%s\n%s", os.date("%H:%M:%S"), lineinfo, msg) + + if config.highlights and level_config.hl then + (vim.schedule_wrap(function() + vim.cmd(string.format("echohl %s", level_config.hl)) + end))() + end + + (vim.schedule_wrap(function() + vim.notify(string.format("[%s] %s", config.plugin, vim.fn.escape(v, '"')), level_config.level) + -- vim.cmd(string.format([[echom "[%s] %s"]], config.plugin, vim.fn.escape(v, '"'))) + end))() + + if config.highlights and level_config.hl then + (vim.schedule_wrap(function() + vim.cmd("echohl NONE") + end))() + end + end + + -- Output to log file + if config.use_file then + local fp = io.open(outfile, "a") + local str = string.format("[%-6s%s] %s: %s\n", nameupper, os.date(), lineinfo, msg) + fp:write(str) + fp:close() + end + end + + for _, x in ipairs(config.modes) do + obj[x.name] = function(...) + return log_at_level(x, make_string, ...) + end + + obj[("fmt_%s"):format(x.name)] = function() + return log_at_level(x, function(...) + local passed = { ... } + local fmt = table.remove(passed, 1) + local inspected = {} + for _, v in ipairs(passed) do + table.insert(inspected, vim.inspect(v)) + end + return string.format(fmt, unpack(inspected)) + end) + end + end +end + +-- }}} + +return log diff --git a/lua/neorg/core/modules.lua b/lua/neorg/core/modules.lua new file mode 100644 index 000000000..902f67205 --- /dev/null +++ b/lua/neorg/core/modules.lua @@ -0,0 +1,755 @@ +-- TODO: What goes below this line until the next notice used to belong to modules.base +-- We need to find a way to make these constructors easier to maintain and more efficient + +--[[ +-- BASE FILE FOR MODULES +-- This file contains the base module implementation +--]] + +local callbacks = require("neorg.core.callbacks") +local config = require("neorg.core.config") +local log = require("neorg.core.log") +local utils = require("neorg.core.utils") + +local modules = {} + +--- Returns a new Neorg module, exposing all the necessary function and variables +---@param name string #The name of the new mod/home/groctel/Documents/Git/Vim/neorg/lua/modules.luaule. Make sure this is unique. The recommended naming convention is category.module_name or category.subcategory.module_name +---@param imports? string[] #A list of imports to attach to the module. Import data is requestable via `module.required`. Use paths relative to the current module. +function modules.create(name, imports) + local new_module = { + + -- Invoked before any initial loading happens + setup = function() + return { success = true, requires = {}, replaces = nil, replace_merge = false } + end, + + -- Invoked after the module has been configured + load = function() end, + + -- Invoked whenever an event that the module has subscribed to triggers + -- callback function with a "event" parameter + on_event = function() end, + + -- Invoked after all plugins are loaded + neorg_post_load = function() end, + + -- The name of the module, note that modules beginning with core are neorg's inbuilt modules + name = "core.default", + + -- The path of the module, can be used in require() statements + path = "modules.core.default.module", + + -- A convenience table to place all of your private variables that you don't want to expose here. + private = {}, + + -- Every module can expose any set of information it sees fit through the public field + -- All functions and variables declared in this table will be visible to any other module loaded + public = { + -- Current Norg version that this module supports. + -- Your module will use this version if not specified, but you can override it. + -- Overriding it will mean that your module is only compatible with the overriden Norg revision. + -- E.g: setting version = "1.0.0" will mean that your module requires Norg 1.0.0+ to operate + version = config.norg_version, + }, + + -- Configuration for the module + config = { + private = { -- Private module config, cannot be changed by other modules or by the user + --[[ + config_option = false, + + ["option_group"] = { + sub_option = true + } + --]] + }, + + public = { -- Public config, can be changed by modules and the user + --[[ + config_option = false, + + ["option_group"] = { + sub_option = true + } + --]] + }, + + -- This table houses all the changes the user made to the public table, + -- useful for when you want to know exactly what the user tinkered with. + -- Shouldn't be commonly used. + custom = {}, + }, + + -- Event data regarding the current module + events = { + subscribed = { -- The events that the module is subscribed to + --[[ + ["core.test"] = { -- The name of the module that has events bound to it + ["test_event"] = true, -- Subscribes to event core.test.events.test_event + + ["other_event"] = true -- Subscribes to event core.test.events.other_event + } + --]] + }, + defined = { -- The events that the module itself has defined + --[[ + ["my_event"] = { event_data } -- Creates an event of type category.module.events.my_event + --]] + }, + }, + + -- If you ever require a module through the return value of the setup() function, + -- All of the modules' public APIs will become available here + required = { + --[[ + ["core.test"] = { + -- Their public API here... + }, + + ["core.some_other_plugin"] = { + -- Their public API here... + } + + --]] + }, + + -- Example bits of code that the user can look through + examples = { + --[[ + a_cool_test = function() + print("Some code!") + end + --]] + }, + + -- Imported submodules of the given module. + -- Contrary to `required`, which only exposes the public API of a module, + -- imported modules can be accessed in their entirety. + imported = { + --[[ + ["my.module.submodule"] = { ... }, + --]] + }, + } + + if imports then + for _, import in ipairs(imports) do + local fullpath = table.concat({ name, import }, ".") + + if not modules.load_module(fullpath) then + log.error("Unable to load import '" .. fullpath .. "'! An error occured (see traceback below):") + assert(false) -- Halt execution, no recovering from this error... + end + + new_module.imported[fullpath] = modules.loaded_modules[fullpath] + end + end + + if name then + new_module.name = name + new_module.path = "modules." .. name + end + + return new_module +end + + +--- Constructs a metamodule from a list of submodules. Metamodules are modules that can autoload batches of modules at once. +---@param name string #The name of the new metamodule. Make sure this is unique. The recommended naming convention is category.module_name or category.subcategory.module_name +-- @Param ... (varargs) - a list of module names to load. +function modules.create_meta(name, ...) + local module = modules.create(name) + + module.config.public.enable = { ... } + + module.setup = function() + return { success = true } + end + + module.load = function() + module.config.public.enable = (function() + -- If we haven't define any modules to disable then just return all enabled modules + if not module.config.public.disable then + return module.config.public.enable + end + + local ret = {} + + -- For every enabled module + for _, mod in ipairs(module.config.public.enable) do + -- If that module does not exist in the disable table (ie. it is enabled) then add it to the `ret` table + if not vim.tbl_contains(module.config.public.disable, mod) then + table.insert(ret, mod) + end + end + + -- Return the table containing all the modules we would like to enable + return ret + end)() + + -- Go through every module that we have defined in the metamodule and load it! + for _, mod in ipairs(module.config.public.enable) do + modules.load_module(mod) + end + end + + return module +end + + +-- TODO: What goes below this line until the next notice used to belong to modules +-- We need to find a way to make these functions easier to maintain + +--[[ +-- NEORG MODULE MANAGER +-- This file is responsible for loading, calling and managing modules +-- Modules are internal mini-programs that execute on certain events, they build the foundation of Neorg itself. +--]] + +--[[ +-- The reason we do not just call this variable modules.loaded_modules.count is because +-- someone could make a module called "count" and override the variable, causing bugs. +--]] +modules.loaded_module_count = 0 + +--- The table of currently loaded modules +modules.loaded_modules = {} + +--- Loads and enables a module +-- Loads a specified module. If the module subscribes to any events then they will be activated too. +---@param module table #The actual module to load +---@return boolean #Whether the module successfully loaded +function modules.load_module_from_table(module) + log.info("Loading module with name", module.name) + + -- If our module is already loaded don't try loading it again + if modules.loaded_modules[module.name] then + log.trace("Module", module.name, "already loaded. Omitting...") + return true + end + + -- Invoke the setup function. This function returns whether or not the loading of the module was successful and some metadata. + local loaded_module = module.setup and module.setup() + or { + success = true, + replaces = {}, + replace_merge = false, + requires = {}, + wants = {}, + } + + -- We do not expect module.setup() to ever return nil, that's why this check is in place + if not loaded_module then + log.error( + "Module", + module.name, + "does not handle module loading correctly; module.setup() returned nil. Omitting..." + ) + return false + end + + -- A part of the table returned by module.setup() tells us whether or not the module initialization was successful + if loaded_module.success == false then + log.trace("Module", module.name, "did not load properly.") + return false + end + + --[[ + -- This small snippet of code creates a copy of an already loaded module with the same name. + -- If the module wants to replace an already loaded module then we need to create a deepcopy of that old module + -- in order to stop it from getting overwritten. + --]] + local module_to_replace + + -- If the return value of module.setup() tells us to hotswap with another module then cache the module we want to replace with + if loaded_module.replaces and loaded_module.replaces ~= "" then + module_to_replace = vim.deepcopy(modules.loaded_modules[loaded_module.replaces]) + end + + -- Add the module into the list of loaded modules + -- The reason we do this here is so other modules don't recursively require each other in the dependency loading loop below + modules.loaded_modules[module.name] = module + + -- If the module "wants" any other modules then verify they are loaded + if loaded_module.wants and not vim.tbl_isempty(loaded_module.wants) then + log.info("Module", module.name, "wants certain modules. Ensuring they are loaded...") + + -- Loop through each dependency and ensure it's loaded + for _, required_module in ipairs(loaded_module.wants) do + log.trace("Verifying", required_module) + + -- This would've always returned false had we not added the current module to the loaded module list earlier above + if not modules.is_module_loaded(required_module) then + if config.user_config[required_module] then + log.trace( + "Wanted module", + required_module, + "isn't loaded but can be as it's defined in the user's config. Loading..." + ) + + if not modules.load_module(required_module) then + log.error( + "Unable to load wanted module for", + loaded_module.name, + "- the module didn't load successfully" + ) + + -- Make sure to clean up after ourselves if the module failed to load + modules.loaded_modules[module.name] = nil + return false + end + else + log.error( + ("Unable to load module %s, wanted dependency %s was not satisfied. Be sure to load the module and its appropriate config too!"):format( + module.name, + required_module + ) + ) + + -- Make sure to clean up after ourselves if the module failed to load + modules.loaded_modules[module.name] = nil + return false + end + end + + -- Create a reference to the dependency's public table + module.required[required_module] = modules.loaded_modules[required_module].public + end + end + + -- If any dependencies have been defined, handle them + if loaded_module.requires and vim.tbl_count(loaded_module.requires) > 0 then + log.info("Module", module.name, "has dependencies. Loading dependencies first...") + + -- Loop through each dependency and load it one by one + for _, required_module in pairs(loaded_module.requires) do + log.trace("Loading submodule", required_module) + + -- This would've always returned false had we not added the current module to the loaded module list earlier above + if not modules.is_module_loaded(required_module) then + if not modules.load_module(required_module) then + log.error( + ("Unable to load module %s, required dependency %s did not load successfully"):format( + module.name, + required_module + ) + ) + + -- Make sure to clean up after ourselves if the module failed to load + modules.loaded_modules[module.name] = nil + return false + end + else + log.trace("Module", required_module, "already loaded, skipping...") + end + + -- Create a reference to the dependency's public table + module.required[required_module] = modules.loaded_modules[required_module].public + end + end + + -- After loading all our dependencies, see if we need to hotswap another module with ourselves + if module_to_replace then + -- Make sure the names of both modules match + module.name = module_to_replace.name + + -- Whenever a module gets hotswapped, a special flag is set inside the module in order to signalize that it has been hotswapped before + -- If this flag has already been set before, then throw an error - there is no way for us to know which hotswapped module should take priority. + if module_to_replace.replaced then + log.error( + ("Unable to replace module %s - module replacement clashing detected. This error triggers when a module tries to be replaced more than two times - neorg doesn't know which replacement to prioritize."):format( + module_to_replace.name + ) + ) + + -- Make sure to clean up after ourselves if the module failed to load + modules.loaded_modules[module.name] = nil + + return false + end + + -- If the replace_merge flag is set to true in the setup() return value then recursively merge the data from the + -- previous module into our new one. This allows for practically seamless hotswapping, as it allows you to retain the data + -- of the previous module. + if loaded_module.replace_merge then + module = vim.tbl_deep_extend("force", module, { + private = module_to_replace.private, + config = module_to_replace.config, + public = module_to_replace.public, + events = module_to_replace.events, + }) + end + + -- Set the special module.replaced flag to let everyone know we've been hotswapped before + module.replaced = true + end + + log.info("Successfully loaded module", module.name) + + -- Keep track of the number of loaded modules + modules.loaded_module_count = modules.loaded_module_count + 1 + + -- NOTE(vhyrro): Left here for debugging. + -- Maybe make controllable with a switch in the future. + -- local start = vim.loop.hrtime() + + -- Call the load function + if module.load then + module.load() + end + + -- local msg = ("%fms"):format((vim.loop.hrtime() - start) / 1e6) + -- vim.notify(msg .. " " .. module.name) + + modules.broadcast_event({ + type = "core.module_loaded", + split_type = { "core", "module_loaded" }, + filename = "", + filehead = "", + cursor_position = { 0, 0 }, + referrer = "core", + line_content = "", + content = module, + broadcast = true, + }) + + return true +end + +--- Unlike `load_module_from_table()`, which loads a module from memory, `load_module()` tries to find the corresponding module file on disk and loads it into memory. +-- If the module cannot not be found, attempt to load it off of github (unimplemented). This function also applies user-defined config and keymaps to the modules themselves. +-- This is the recommended way of loading modules - `load_module_from_table()` should only really be used by neorg itself. +---@param module_name string #A path to a module on disk. A path seperator in neorg is '.', not '/' +---@param cfg table? #A config that reflects the structure of `neorg.config.user_config.load["module.name"].config` +---@return boolean #Whether the module was successfully loaded +function modules.load_module(module_name, cfg) + -- Don't bother loading the module from disk if it's already loaded + if modules.is_module_loaded(module_name) then + return true + end + + -- Attempt to require the module, does not throw an error if the module doesn't exist + local exists, module = pcall(require, "neorg.modules." .. module_name .. ".module") + + -- If the module doesn't exist then return false + if not exists then + local fallback_exists, fallback_module = pcall(require, "neorg.modules." .. module_name) + + if not fallback_exists then + log.error("Unable to load module", module_name, "-", module) + return false + end + + module = fallback_module + end + + -- If the module is nil for some reason return false + if not module then + log.error( + "Unable to load module", + module_name, + "- loaded file returned nil. Be sure to return the table created by modules.create() at the end of your module.lua file!" + ) + return false + end + + -- If the value of `module` is strictly true then it means the required file returned nothing + -- We obviously can't do anything meaningful with that! + if module == true then + log.error( + "An error has occurred when loading", + module_name, + "- loaded file didn't return anything meaningful. Be sure to return the table created by modules.create() at the end of your module.lua file!" + ) + return false + end + + -- Load the user-defined config + if cfg and not vim.tbl_isempty(cfg) then + module.config.custom = cfg + module.config.public = vim.tbl_deep_extend("force", module.config.public, config) + else + module.config.public = + vim.tbl_deep_extend("force", module.config.public, config.modules[module_name] or {}) + end + + -- Pass execution onto load_module_from_table() and let it handle the rest + return modules.load_module_from_table(module) +end + +--- Has the same principle of operation as load_module_from_table(), except it then sets up the parent module's "required" table, allowing the parent to access the child as if it were a dependency. +---@param module table #A valid table as returned by modules.create() +---@param parent_module string|table #If a string, then the parent is searched for in the loaded modules. If a table, then the module is treated as a valid module as returned by modules.create() +function modules.load_module_as_dependency_from_table(module, parent_module) + if modules.load_module_from_table(module) then + if type(parent_module) == "string" then + modules.loaded_modules[parent_module].required[module.name] = module.public + elseif type(parent_module) == "table" then + parent_module.required[module.name] = module.public + end + end +end + +--- Normally loads a module, but then sets up the parent module's "required" table, allowing the parent module to access the child as if it were a dependency. +---@param module_name string #A path to a module on disk. A path seperator in neorg is '.', not '/' +---@param parent_module string #The name of the parent module. This is the module which the dependency will be attached to. +---@param cfg table #A config that reflects the structure of neorg.config.user_config.load["module.name"].config +function modules.load_module_as_dependency(module_name, parent_module, cfg) + if modules.load_module(module_name, cfg) and modules.is_module_loaded(parent_module) then + modules.loaded_modules[parent_module].required[module_name] = modules.get_module_config(module_name) + end +end + +--- Retrieves the public API exposed by the module +---@param module_name string #The name of the module to retrieve +function modules.get_module(module_name) + if not modules.is_module_loaded(module_name) then + log.trace("Attempt to get module with name", module_name, "failed - module is not loaded.") + return + end + + return modules.loaded_modules[module_name].public +end + +--- Returns the module.config.public table if the module is loaded +---@param module_name string #The name of the module to retrieve (module must be loaded) +function modules.get_module_config(module_name) + if not modules.is_module_loaded(module_name) then + log.trace("Attempt to get module config with name", module_name, "failed - module is not loaded.") + return + end + + return modules.loaded_modules[module_name].config.public +end + +--- Returns true if module with name module_name is loaded, false otherwise +---@param module_name string #The name of an arbitrary module +function modules.is_module_loaded(module_name) + return modules.loaded_modules[module_name] ~= nil +end + +--- Reads the module's public table and looks for a version variable, then converts it from a string into a table, like so: { major = , minor = , patch = } +---@param module_name string #The name of a valid, loaded module. +-- @Return struct | nil (if any error occurs) +function modules.get_module_version(module_name) + -- If the module isn't loaded then don't bother retrieving its version + if not modules.is_module_loaded(module_name) then + log.trace("Attempt to get module version with name", module_name, "failed - module is not loaded.") + return + end + + -- Grab the version of the module + local version = modules.get_module(module_name).version + + -- If it can't be found then error out + if not version then + log.trace("Attempt to get module version with name", module_name, "failed - version variable not present.") + return + end + + return utils.parse_version_string(version) +end + +--- Executes `callback` once `module` is a valid and loaded module, else the callback gets instantly executed. +---@param module_name string #The name of the module to listen for. +---@param callback fun(module_public_table: table) #The callback to execute. +function modules.await(module_name, callback) + if modules.is_module_loaded(module_name) then + callback(assert(modules.get_module(module_name))) + return + end + + callbacks.on_event("core.module_loaded", function(_, module) + callback(module.public) + end, function(event) + return event.content.name == module_name + end) +end + + +-- TODO: What goes below this line until the next notice used to belong to modules +-- We need to find a way to make these functions easier to maintain + +--[[ +-- NEORG EVENT FILE +-- This file is responsible for dealing with event handling and broadcasting. +-- All modules that subscribe to an event will receive it once it is triggered. +--]] + + +--- The working of this function is best illustrated with an example: +-- If type == 'core.some_plugin.events.my_event', this function will return { 'core.some_plugin', 'my_event' } +---@param type string #The full path of a module event +function modules.split_event_type(type) + local start_str, end_str = type:find("%.events%.") + + local split_event_type = { type:sub(0, start_str - 1), type:sub(end_str + 1) } + + if #split_event_type ~= 2 then + log.warn("Invalid type name:", type) + return + end + + return split_event_type +end + +--- Returns an event template defined in module.events.defined +---@param module table #A reference to the module invoking the function +---@param type string #A full path to a valid event type (e.g. 'core.module.events.some_event') +function modules.get_event_template(module, type) + -- You can't get the event template of a type if the type isn't loaded + if not modules.is_module_loaded(module.name) then + log.info("Unable to get event of type", type, "with module", module.name) + return + end + + -- Split the event type into two + local split_type = modules.split_event_type(type) + + if not split_type then + log.warn("Unable to get event template for event", type, "and module", module.name) + return + end + + log.trace("Returning", split_type[2], "for module", split_type[1]) + + -- Return the defined event from the specific module + return modules.loaded_modules[module.name].events.defined[split_type[2]] +end + +--- Creates a deep copy of the modules.base_event event and returns it with a custom type and referrer +---@param module table #A reference to the module invoking the function +---@param name string #A relative path to a valid event template +function modules.define_event(module, name) + -- Create a copy of the base event and override the values with ones specified by the user + + local new_event = { + type = "core.base_event", + split_type = {}, + content = nil, + referrer = nil, + broadcast = true, + + cursor_position = {}, + filename = "", + filehead = "", + line_content = "", + buffer = 0, + window = 0, + mode = "", + } + + if name then + new_event.type = module.name .. ".events." .. name + end + + new_event.referrer = module.name + + return new_event +end + +--- Returns a copy of the event template provided by a module +---@param module table #A reference to the module invoking the function +---@param type string #A full path to a valid event type (e.g. 'core.module.events.some_event') +---@param content any #The content of the event, can be anything from a string to a table to whatever you please +---@return table #New event +function modules.create_event(module, type, content) + -- Get the module that contains the event + local module_name = modules.split_event_type(type)[1] + + -- Retrieve the template from module.events.defined + local event_template = + modules.get_event_template(modules.loaded_modules[module_name] or { name = "" }, type) + + if not event_template then + log.warn("Unable to create event of type", type, ". Returning nil...") + return + end + + -- Make a deep copy here - we don't want to override the actual base table! + local new_event = vim.deepcopy(event_template) + + new_event.type = type + new_event.content = content + new_event.referrer = module.name + + -- Override all the important values + new_event.split_type = modules.split_event_type(type) + new_event.filename = vim.fn.expand("%:t") + new_event.filehead = vim.fn.expand("%:p:h") + new_event.cursor_position = vim.api.nvim_win_get_cursor(0) + new_event.line_content = vim.api.nvim_get_current_line() + new_event.referrer = module.name + new_event.broadcast = true + new_event.buffer = vim.api.nvim_get_current_buf() + new_event.window = vim.api.nvim_get_current_win() + new_event.mode = vim.api.nvim_get_mode().mode + + return new_event +end + +--- Sends an event to all subscribed modules. The event contains the filename, filehead, cursor position and line content as a bonus. +---@param event table #An event, usually created by modules.create_event() +---@param callback function? #A callback to be invoked after all events have been asynchronously broadcast +function modules.broadcast_event(event, callback) + -- Broadcast the event to all modules + if not event.split_type then + log.error("Unable to broadcast event of type", event.type, "- invalid event name") + return + end + + -- Let the callback handler know of the event + callbacks.handle_callbacks(event) + + -- Loop through all the modules + for _, current_module in pairs(modules.loaded_modules) do + -- If the current module has any subscribed events and if it has a subscription bound to the event's module name then + if current_module.events.subscribed and current_module.events.subscribed[event.split_type[1]] then + -- Check whether we are subscribed to the event type + local evt = current_module.events.subscribed[event.split_type[1]][event.split_type[2]] + + if evt ~= nil and evt == true then + -- Run the on_event() for that module + current_module.on_event(event) + end + end + end + + -- Because the broadcasting of events is async we allow the event broadcaster to provide a callback + -- TODO: deprecate + if callback then + callback() + end +end + +--- Instead of broadcasting to all loaded modules, send_event() only sends to one module +---@param recipient string #The name of a loaded module that will be the recipient of the event +---@param event table #An event, usually created by modules.create_event() +function modules.send_event(recipient, event) + -- If the recipient is not loaded then there's no reason to send an event to it + if not modules.is_module_loaded(recipient) then + log.warn("Unable to send event to module", recipient, "- the module is not loaded.") + return + end + + -- Set the broadcast variable to false since we're not invoking broadcast_event() + event.broadcast = false + + -- Let the callback handler know of the event + callbacks.handle_callbacks(event) + + -- Get the recipient module and check whether it's subscribed to our event + local mod = modules.loaded_modules[recipient] + + if mod.events.subscribed and mod.events.subscribed[event.split_type[1]] then + local evt = mod.events.subscribed[event.split_type[1]][event.split_type[2]] + + -- If it is then trigger the module's on_event() function + if evt ~= nil and evt == true then + mod.on_event(event) + end + end +end + +return modules diff --git a/lua/neorg/core/utils.lua b/lua/neorg/core/utils.lua new file mode 100644 index 000000000..5c470b101 --- /dev/null +++ b/lua/neorg/core/utils.lua @@ -0,0 +1,182 @@ +local configuration = require("neorg.core.config") +local log = require("neorg.core.log") + +local utils = {} +local version = vim.version() -- TODO: Move to a more local scope + + +--- A version agnostic way to call the neovim treesitter query parser +--- @param language string # Language to use for the query +--- @param query_string string # Query in s-expr syntax +--- @return any # Parsed query +function utils.ts_parse_query(language, query_string) + if vim.treesitter.query.parse then + return vim.treesitter.query.parse(language, query_string) + else + return vim.treesitter.parse_query(language, query_string) + end +end + + +--- An OS agnostic way of querying the current user +function utils.get_username() + local current_os = configuration.os_info + + if not current_os then + return "" + end + + if current_os == "linux" or current_os == "mac" or current_os == "wsl" then + return os.getenv("USER") or "" + elseif current_os == "windows" then + return os.getenv("username") or "" + end + + return "" +end + + +--- Returns an array of strings, the array being a list of languages that Neorg can inject +---@param values boolean #If set to true will return an array of strings, if false will return a key-value table +function utils.get_language_list(values) + local regex_files = {} + local ts_files = {} + -- search for regex files in syntax and after/syntax + -- its best if we strip out anything but the ft name + for _, lang in pairs(vim.api.nvim_get_runtime_file("syntax/*.vim", true)) do + local lang_name = vim.fn.fnamemodify(lang, ":t:r") + table.insert(regex_files, lang_name) + end + for _, lang in pairs(vim.api.nvim_get_runtime_file("after/syntax/*.vim", true)) do + local lang_name = vim.fn.fnamemodify(lang, ":t:r") + table.insert(regex_files, lang_name) + end + -- search for available parsers + for _, parser in pairs(vim.api.nvim_get_runtime_file("parser/*.so", true)) do + local parser_name = vim.fn.fnamemodify(parser, ":t:r") + ts_files[parser_name] = true + end + local ret = {} + + for _, syntax in pairs(regex_files) do + if ts_files[syntax] then + ret[syntax] = { type = "treesitter" } + else + ret[syntax] = { type = "syntax" } + end + end + + return values and vim.tbl_keys(ret) or ret +end + + +function utils.get_language_shorthands(reverse_lookup) + local langs = { + ["bash"] = { "sh", "zsh" }, + ["c_sharp"] = { "csharp", "cs" }, + ["clojure"] = { "clj" }, + ["cmake"] = { "cmake.in" }, + ["commonlisp"] = { "cl" }, + ["cpp"] = { "hpp", "cc", "hh", "c++", "h++", "cxx", "hxx" }, + ["dockerfile"] = { "docker" }, + ["erlang"] = { "erl" }, + ["fennel"] = { "fnl" }, + ["fortran"] = { "f90", "f95" }, + ["go"] = { "golang" }, + ["godot"] = { "gdscript" }, + ["gomod"] = { "gm" }, + ["haskell"] = { "hs" }, + ["java"] = { "jsp" }, + ["javascript"] = { "js", "jsx" }, + ["julia"] = { "julia-repl" }, + ["kotlin"] = { "kt" }, + ["python"] = { "py", "gyp" }, + ["ruby"] = { "rb", "gemspec", "podspec", "thor", "irb" }, + ["rust"] = { "rs" }, + ["supercollider"] = { "sc" }, + ["typescript"] = { "ts" }, + ["verilog"] = { "v" }, + ["yaml"] = { "yml" }, + } + + return reverse_lookup and vim.tbl_add_reverse_lookup(langs) or langs +end + + +--- Checks whether Neovim is running at least at a specific version +---@param major number #The major release of Neovim +---@param minor number #The minor release of Neovim +---@param patch number #The patch number (in case you need it) +---@return boolean #Whether Neovim is running at the same or a higher version than the one given +function utils.is_minimum_version(major, minor, patch) + return major <= version.major and minor <= version.minor and patch <= version.patch +end + + +--- Parses a version string like "0.4.2" and provides back a table like { major = , minor = , patch = } +---@param version_string string #The input string +---@return table #The parsed version string, or `nil` if a failure occurred during parsing +function utils.parse_version_string(version_string) + if not version_string then + return + end + + -- Define variables that split the version up into 3 slices + local split_version, versions, ret = + vim.split(version_string, ".", true), { "major", "minor", "patch" }, { major = 0, minor = 0, patch = 0 } + + -- If the sliced version string has more than 3 elements error out + if #split_version > 3 then + log.warn( + "Attempt to parse version:", + version_string, + "failed - too many version numbers provided. Version should follow this layout: .." + ) + return + end + + -- Loop through all the versions and check whether they are valid numbers. If they are, add them to the return table + for i, ver in ipairs(versions) do + if split_version[i] then + local num = tonumber(split_version[i]) + + if not num then + log.warn("Invalid version provided, string cannot be converted to integral type.") + return + end + + ret[ver] = num + end + end + + return ret +end + + +--- Custom neorg notifications. Wrapper around vim.notify +---@param msg string message to send +---@param log_level integer|nil log level in `vim.log.levels`. +function utils.notify(msg, log_level) + vim.notify(msg, log_level, { title = "Neorg" }) +end + + +--- Opens up an array of files and runs a callback for each opened file. +---@param files string[] #An array of files to open. +---@param callback fun(buffer: integer, filename: string) #The callback to invoke for each file. +function utils.read_files(files, callback) + for _, file in ipairs(files) do + local bufnr = vim.uri_to_bufnr(vim.uri_from_fname(file)) + + local should_delete = not vim.api.nvim_buf_is_loaded(bufnr) + + vim.fn.bufload(bufnr) + callback(bufnr, file) + if should_delete then + vim.api.nvim_buf_delete(bufnr, { force = true }) + end + end +end + + +return utils diff --git a/lua/neorg/events.lua b/lua/neorg/events.lua deleted file mode 100644 index 68902d873..000000000 --- a/lua/neorg/events.lua +++ /dev/null @@ -1,188 +0,0 @@ ---[[ --- NEORG EVENT FILE --- This file is responsible for dealing with event handling and broadcasting. --- All modules that subscribe to an event will receive it once it is triggered. ---]] - --- Include the global instance of the logger -local log = require("neorg.external.log") - -require("neorg.modules") -require("neorg.external.helpers") -require("neorg.callbacks") - -neorg.events = {} - ---- The working of this function is best illustrated with an example: --- If type == 'core.some_plugin.events.my_event', this function will return { 'core.some_plugin', 'my_event' } ----@param type string #The full path of a module event -function neorg.events.split_event_type(type) - local start_str, end_str = type:find("%.events%.") - - local split_event_type = { type:sub(0, start_str - 1), type:sub(end_str + 1) } - - if #split_event_type ~= 2 then - log.warn("Invalid type name:", type) - return - end - - return split_event_type -end - ---- Returns an event template defined in module.events.defined ----@param module table #A reference to the module invoking the function ----@param type string #A full path to a valid event type (e.g. 'core.module.events.some_event') -function neorg.events.get_event_template(module, type) - -- You can't get the event template of a type if the type isn't loaded - if not neorg.modules.is_module_loaded(module.name) then - log.info("Unable to get event of type", type, "with module", module.name) - return - end - - -- Split the event type into two - local split_type = neorg.events.split_event_type(type) - - if not split_type then - log.warn("Unable to get event template for event", type, "and module", module.name) - return - end - - log.trace("Returning", split_type[2], "for module", split_type[1]) - - -- Return the defined event from the specific module - return neorg.modules.loaded_modules[module.name].events.defined[split_type[2]] -end - ---- Creates a deep copy of the neorg.events.base_event event and returns it with a custom type and referrer ----@param module table #A reference to the module invoking the function ----@param name string #A relative path to a valid event template -function neorg.events.define(module, name) - -- Create a copy of the base event and override the values with ones specified by the user - - local new_event = { - type = "core.base_event", - split_type = {}, - content = nil, - referrer = nil, - broadcast = true, - - cursor_position = {}, - filename = "", - filehead = "", - line_content = "", - buffer = 0, - window = 0, - mode = "", - } - - if name then - new_event.type = module.name .. ".events." .. name - end - - new_event.referrer = module.name - - return new_event -end - ---- Returns a copy of the event template provided by a module ----@param module table #A reference to the module invoking the function ----@param type string #A full path to a valid event type (e.g. 'core.module.events.some_event') ----@param content any #The content of the event, can be anything from a string to a table to whatever you please ----@return table #New event -function neorg.events.create(module, type, content) - -- Get the module that contains the event - local module_name = neorg.events.split_event_type(type)[1] - - -- Retrieve the template from module.events.defined - local event_template = - neorg.events.get_event_template(neorg.modules.loaded_modules[module_name] or { name = "" }, type) - - if not event_template then - log.warn("Unable to create event of type", type, ". Returning nil...") - return - end - - -- Make a deep copy here - we don't want to override the actual base table! - local new_event = vim.deepcopy(event_template) - - new_event.type = type - new_event.content = content - new_event.referrer = module.name - - -- Override all the important values - new_event.split_type = neorg.events.split_event_type(type) - new_event.filename = vim.fn.expand("%:t") - new_event.filehead = vim.fn.expand("%:p:h") - new_event.cursor_position = vim.api.nvim_win_get_cursor(0) - new_event.line_content = vim.api.nvim_get_current_line() - new_event.referrer = module.name - new_event.broadcast = true - new_event.buffer = vim.api.nvim_get_current_buf() - new_event.window = vim.api.nvim_get_current_win() - new_event.mode = vim.api.nvim_get_mode().mode - - return new_event -end - ---- Sends an event to all subscribed modules. The event contains the filename, filehead, cursor position and line content as a bonus. ----@param event table #An event, usually created by neorg.events.create() ----@param callback function? #A callback to be invoked after all events have been asynchronously broadcast -function neorg.events.broadcast_event(event, callback) - -- Broadcast the event to all modules - if not event.split_type then - log.error("Unable to broadcast event of type", event.type, "- invalid event name") - return - end - - -- Let the callback handler know of the event - neorg.callbacks.handle_callbacks(event) - - -- Loop through all the modules - for _, current_module in pairs(neorg.modules.loaded_modules) do - -- If the current module has any subscribed events and if it has a subscription bound to the event's module name then - if current_module.events.subscribed and current_module.events.subscribed[event.split_type[1]] then - -- Check whether we are subscribed to the event type - local evt = current_module.events.subscribed[event.split_type[1]][event.split_type[2]] - - if evt ~= nil and evt == true then - -- Run the on_event() for that module - current_module.on_event(event) - end - end - end - - -- Because the broadcasting of events is async we allow the event broadcaster to provide a callback - -- TODO: deprecate - if callback then - callback() - end -end - ---- Instead of broadcasting to all loaded modules, send_event() only sends to one module ----@param recipient string #The name of a loaded module that will be the recipient of the event ----@param event table #An event, usually created by neorg.events.create() -function neorg.events.send_event(recipient, event) - -- If the recipient is not loaded then there's no reason to send an event to it - if not neorg.modules.is_module_loaded(recipient) then - log.warn("Unable to send event to module", recipient, "- the module is not loaded.") - return - end - - -- Set the broadcast variable to false since we're not invoking broadcast_event() - event.broadcast = false - - -- Let the callback handler know of the event - neorg.callbacks.handle_callbacks(event) - - -- Get the recipient module and check whether it's subscribed to our event - local mod = neorg.modules.loaded_modules[recipient] - - if mod.events.subscribed and mod.events.subscribed[event.split_type[1]] then - local evt = mod.events.subscribed[event.split_type[1]][event.split_type[2]] - - -- If it is then trigger the module's on_event() function - if evt ~= nil and evt == true then - mod.on_event(event) - end - end -end diff --git a/lua/neorg/external/helpers.lua b/lua/neorg/external/helpers.lua deleted file mode 100644 index e2afcb6df..000000000 --- a/lua/neorg/external/helpers.lua +++ /dev/null @@ -1,632 +0,0 @@ ---[[ --- HELPER FUNCTIONS FOR NEORG --- This file contains some simple helper functions to improve QOL ---]] - -local version = vim.version() - -neorg.utils = { - --- A version agnostic way to call the neovim treesitter query parser - --- @param language string # Language to use for the query - --- @param query_string string # Query in s-expr syntax - --- @return any # Parsed query - ts_parse_query = function(language, query_string) - if vim.treesitter.query.parse then - return vim.treesitter.query.parse(language, query_string) - else - return vim.treesitter.parse_query(language, query_string) - end - end, - --- An OS agnostic way of querying the current user - get_username = function() - local current_os = require("neorg.config").os_info - - if not current_os then - return "" - end - - if current_os == "linux" or current_os == "mac" or current_os == "wsl" then - return os.getenv("USER") or "" - elseif current_os == "windows" then - return os.getenv("username") or "" - end - - return "" - end, - --- Returns an array of strings, the array being a list of languages that Neorg can inject - ---@param values boolean #If set to true will return an array of strings, if false will return a key-value table - get_language_list = function(values) - local regex_files = {} - local ts_files = {} - -- search for regex files in syntax and after/syntax - -- its best if we strip out anything but the ft name - for _, lang in pairs(vim.api.nvim_get_runtime_file("syntax/*.vim", true)) do - local lang_name = vim.fn.fnamemodify(lang, ":t:r") - table.insert(regex_files, lang_name) - end - for _, lang in pairs(vim.api.nvim_get_runtime_file("after/syntax/*.vim", true)) do - local lang_name = vim.fn.fnamemodify(lang, ":t:r") - table.insert(regex_files, lang_name) - end - -- search for available parsers - for _, parser in pairs(vim.api.nvim_get_runtime_file("parser/*.so", true)) do - local parser_name = vim.fn.fnamemodify(parser, ":t:r") - ts_files[parser_name] = true - end - local ret = {} - - for _, syntax in pairs(regex_files) do - if ts_files[syntax] then - ret[syntax] = { type = "treesitter" } - else - ret[syntax] = { type = "syntax" } - end - end - - return values and vim.tbl_keys(ret) or ret - end, - get_language_shorthands = function(reverse_lookup) - local langs = { - ["bash"] = { "sh", "zsh" }, - ["c_sharp"] = { "csharp", "cs" }, - ["clojure"] = { "clj" }, - ["cmake"] = { "cmake.in" }, - ["commonlisp"] = { "cl" }, - ["cpp"] = { "hpp", "cc", "hh", "c++", "h++", "cxx", "hxx" }, - ["dockerfile"] = { "docker" }, - ["erlang"] = { "erl" }, - ["fennel"] = { "fnl" }, - ["fortran"] = { "f90", "f95" }, - ["go"] = { "golang" }, - ["godot"] = { "gdscript" }, - ["gomod"] = { "gm" }, - ["haskell"] = { "hs" }, - ["java"] = { "jsp" }, - ["javascript"] = { "js", "jsx" }, - ["julia"] = { "julia-repl" }, - ["kotlin"] = { "kt" }, - ["python"] = { "py", "gyp" }, - ["ruby"] = { "rb", "gemspec", "podspec", "thor", "irb" }, - ["rust"] = { "rs" }, - ["supercollider"] = { "sc" }, - ["typescript"] = { "ts" }, - ["verilog"] = { "v" }, - ["yaml"] = { "yml" }, - } - - return reverse_lookup and vim.tbl_add_reverse_lookup(langs) or langs - end, - --- Checks whether Neovim is running at least at a specific version - ---@param major number #The major release of Neovim - ---@param minor number #The minor release of Neovim - ---@param patch number #The patch number (in case you need it) - ---@return boolean #Whether Neovim is running at the same or a higher version than the one given - is_minimum_version = function(major, minor, patch) - return major <= version.major and minor <= version.minor and patch <= version.patch - end, - --- Parses a version string like "0.4.2" and provides back a table like { major = , minor = , patch = } - ---@param version_string string #The input string - ---@return table #The parsed version string, or `nil` if a failure occurred during parsing - parse_version_string = function(version_string) - if not version_string then - return - end - - -- Define variables that split the version up into 3 slices - local split_version, versions, ret = - vim.split(version_string, ".", true), { "major", "minor", "patch" }, { major = 0, minor = 0, patch = 0 } - - -- If the sliced version string has more than 3 elements error out - if #split_version > 3 then - log.warn( - "Attempt to parse version:", - version_string, - "failed - too many version numbers provided. Version should follow this layout: .." - ) - return - end - - -- Loop through all the versions and check whether they are valid numbers. If they are, add them to the return table - for i, ver in ipairs(versions) do - if split_version[i] then - local num = tonumber(split_version[i]) - - if not num then - log.warn("Invalid version provided, string cannot be converted to integral type.") - return - end - - ret[ver] = num - end - end - - return ret - end, - - --- Custom neorg notifications. Wrapper around vim.notify - ---@param msg string message to send - ---@param log_level integer|nil log level in `vim.log.levels`. - notify = function(msg, log_level) - vim.notify(msg, log_level, { title = "Neorg" }) - end, - - --- Opens up an array of files and runs a callback for each opened file. - ---@param files string[] #An array of files to open. - ---@param callback fun(buffer: integer, filename: string) #The callback to invoke for each file. - read_files = function(files, callback) - for _, file in ipairs(files) do - local bufnr = vim.uri_to_bufnr(vim.uri_from_fname(file)) - - local should_delete = not vim.api.nvim_buf_is_loaded(bufnr) - - vim.fn.bufload(bufnr) - callback(bufnr, file) - if should_delete then - vim.api.nvim_buf_delete(bufnr, { force = true }) - end - end - end, -} - -neorg.lib = { - --- Returns the item that matches the first item in statements - ---@param value any #The value to compare against - ---@param compare? function #A custom comparison function - ---@return function #A function to invoke with a table of potential matches - match = function(value, compare) - -- Returning a function allows for such syntax: - -- match(something) { ..matches.. } - return function(statements) - if value == nil then - return - end - - -- Set the comparison function - -- A comparison function may be required for more complex - -- data types that need to be compared against another static value. - -- The default comparison function compares booleans as strings to ensure - -- that boolean comparisons work as intended. - compare = compare - or function(lhs, rhs) - if type(lhs) == "boolean" then - return tostring(lhs) == rhs - end - - return lhs == rhs - end - - -- Go through every statement, compare it, and perform the desired action - -- if the comparison was successful - for case, action in pairs(statements) do - -- If the case statement is a list of data then compare that - if type(case) == "table" and vim.tbl_islist(case) then - for _, subcase in ipairs(case) do - if compare(value, subcase) then - -- The action can be a function, in which case it is invoked - -- and the return value of that function is returned instead. - if type(action) == "function" then - return action(value) - end - - return action - end - end - end - - if compare(value, case) then - -- The action can be a function, in which case it is invoked - -- and the return value of that function is returned instead. - if type(action) == "function" then - return action(value) - end - - return action - end - end - - -- If we've fallen through all statements to check and haven't found - -- a single match then see if we can fall back to a `_` clause instead. - if statements._ then - local action = statements._ - - if type(action) == "function" then - return action(value) - end - - return action - end - end - end, - --- Wrapped around `match()` that performs an action based on a condition - ---@param comparison boolean #The comparison to perform - ---@param when_true function|any #The value to return when `comparison` is true - ---@param when_false function|any #The value to return when `comparison` is false - ---@return any #The value that either `when_true` or `when_false` returned - when = function(comparison, when_true, when_false) - if type(comparison) ~= "boolean" then - comparison = (comparison ~= nil) - end - - return neorg.lib.match(type(comparison) == "table" and unpack(comparison) or comparison)({ - ["true"] = when_true, - ["false"] = when_false, - }) - end, - --- Maps a function to every element of a table - -- The function can return a value, in which case that specific element will be assigned - -- the return value of that function. - ---@param tbl table #The table to iterate over - ---@param callback function #The callback that should be invoked on every iteration - ---@return table #A modified version of the original `tbl`. - map = function(tbl, callback) - local copy = vim.deepcopy(tbl) - - for k, v in pairs(tbl) do - local cb = callback(k, v, tbl) - - if cb then - copy[k] = cb - end - end - - return copy - end, - --- Iterates over all elements of a table and returns the first value returned by the callback. - ---@param tbl table #The table to iterate over - ---@param callback function #The callback function that should be invoked on each iteration. - --- Can return a value in which case that value will be returned from the `filter()` call. - ---@return any|nil #The value returned by `callback`, if any - filter = function(tbl, callback) - for k, v in pairs(tbl) do - local cb = callback(k, v) - - if cb then - return cb - end - end - end, - --- Finds any key in an array - ---@param tbl array #An array of values to iterate over - ---@param element any #The item to find - ---@return any|nil #The found value or `nil` if nothing could be found - find = function(tbl, element) - return neorg.lib.filter(tbl, function(key, value) - if value == element then - return key - end - end) - end, - --- Inserts a value into a table if it doesn't exist, else returns the existing value. - ---@param tbl table #The table to insert into - ---@param value number|string #The value to insert - ---@return any #The item to return - insert_or = function(tbl, value) - local item = neorg.lib.find(tbl, value) - - return item and tbl[item] - or (function() - table.insert(tbl, value) - return value - end)() - end, - --- Picks a set of values from a table and returns them in an array - ---@param tbl table #The table to extract the keys from - ---@param values array[string] #An array of strings, these being the keys you'd like to extract - ---@return array[any] #The picked values from the table - pick = function(tbl, values) - local result = {} - - for _, value in ipairs(values) do - if tbl[value] then - table.insert(result, tbl[value]) - end - end - - return result - end, - --- Tries to extract a variable in all nesting levels of a table. - ---@param tbl table #The table to traverse - ---@param value any #The value to look for - note that comparison is done through the `==` operator - ---@return any|nil #The value if it was found, else nil - extract = function(tbl, value) - local results = {} - - for key, expected_value in pairs(tbl) do - if key == value then - table.insert(results, expected_value) - end - - if type(expected_value) == "table" then - vim.list_extend(results, neorg.lib.extract(expected_value, value)) - end - end - - return results - end, - --- Wraps a conditional "not" function in a vim.tbl callback - ---@param cb function #The function to wrap - ---@vararg ... #The arguments to pass to the wrapped function - ---@return function #The wrapped function in a vim.tbl callback - wrap_cond_not = function(cb, ...) - local params = { ... } - return function(v) - return not cb(v, unpack(params)) - end - end, - --- Wraps a conditional function in a vim.tbl callback - ---@param cb function #The function to wrap - ---@vararg ... #The arguments to pass to the wrapped function - ---@return function #The wrapped function in a vim.tbl callback - wrap_cond = function(cb, ...) - local params = { ... } - return function(v) - return cb(v, unpack(params)) - end - end, - --- Wraps a function in a callback - ---@param function_pointer function #The function to wrap - ---@vararg ... #The arguments to pass to the wrapped function - ---@return function #The wrapped function in a callback - wrap = function(function_pointer, ...) - local params = { ... } - - if type(function_pointer) ~= "function" then - local prev = function_pointer - - -- luacheck: push ignore - function_pointer = function(...) - return prev, unpack(params) - end - -- luacheck: pop - end - - return function() - return function_pointer(unpack(params)) - end - end, - --- Modifiers for the `map` function - mod = { - --- Wrapper function to add two values - -- This function only takes in one argument because the second value - -- to add is provided as a parameter in the callback. - ---@param amount number #The number to add - ---@return function #A callback adding the static value to the dynamic amount - add = function(amount) - return function(_, value) - return value + amount - end - end, - --- Wrapper function to set a value to another value in a `map` sequence - ---@param to any #A static value to set each element of the table to - ---@return function #A callback that returns the static value - modify = function(to) - return function() - return to - end - end, - --- Filtering modifiers that exclude certain elements from a table - exclude = { - first = function(func, alt) - return function(i, val) - return i == 1 and (alt and alt(i, val) or val) or func(i, val) - end - end, - last = function(func, alt) - return function(i, val, tbl) - return next(tbl, i) and func(i, val) or (alt and alt(i, val) or val) - end - end, - }, - }, - --- Repeats an arguments `index` amount of times - ---@param value any #The value to repeat - ---@param index number #The amount of times to repeat the argument - ---@return ... #An expanded vararg with the repeated argument - reparg = function(value, index) - if index == 1 then - return value - end - - return value, neorg.lib.reparg(value, index - 1) - end, - --- Lazily concatenates a string to prevent runtime errors where an object may not exist - -- Consider the following example: - -- - -- neorg.lib.when(str ~= nil, str .. " extra text", "") - -- - -- This would fail, simply because the string concatenation will still be evaluated in order - -- to be placed inside the variable. You may use: - -- - -- neorg.lib.when(str ~= nil, neorg.lib.lazy_string_concat(str, " extra text"), "") - -- - -- To mitigate this issue directly. - --- @vararg string #An unlimited number of strings - ---@return string #The result of all the strings concatenateA. - lazy_string_concat = function(...) - return table.concat({ ... }) - end, - --- Converts an array of values to a table of keys - ---@param values string[]|number[] #An array of values to store as keys - ---@param default any #The default value to assign to all key pairs - ---@return table #The converted table - to_keys = function(values, default) - local ret = {} - - for _, value in ipairs(values) do - ret[value] = default or {} - end - - return ret - end, - --- Constructs a new key-pair table by running a callback on all elements of an array. - ---@param keys string[] #A string array with the keys to iterate over - ---@param cb function #A function that gets invoked with each key and returns a value to be placed in the output table - ---@return table #The newly constructed table - construct = function(keys, cb) - local result = {} - - for _, key in ipairs(keys) do - result[key] = cb(key) - end - - return result - end, - --- If `val` is a function, executes it with the desired arguments, else just returns `val` - ---@param val any|function #Either a function or any other value - ---@vararg any #Potential arguments to give `val` if it is a function - ---@return any #The returned evaluation of `val` - eval = function(val, ...) - if type(val) == "function" then - return val(...) - end - - return val - end, - --- Extends a list by constructing a new one vs mutating an existing - -- list in the case of `vim.list_extend` - list_extend = function(list, ...) - return list and { unpack(list), unpack(neorg.lib.list_extend(...)) } or {} - end, - --- Converts a table with `key = value` pairs to a `{ key, value }` array. - ---@param tbl_with_keys table #A table with key-value pairs - ---@return array #An array of `{ key, value }` pairs. - unroll = function(tbl_with_keys) - local res = {} - - for key, value in pairs(tbl_with_keys) do - table.insert(res, { key, value }) - end - - return res - end, - --- Works just like pcall, except returns only a single value or nil (useful for ternary operations - -- which are not possible with a function like `pcall` that returns two values). - ---@param func function #The function to invoke in a protected environment - ---@vararg any #The parameters to pass to `func` - ---@return any|nil #The return value of the executed function or `nil` - inline_pcall = function(func, ...) - local ok, ret = pcall(func, ...) - - if ok then - return ret - end - - -- return nil - end, - --- Perform a backwards search for a character and return the index of that character - ---@param str string #The string to search - ---@param char string #The substring to search for - ---@return number|nil #The index of the found substring or `nil` if not found - rfind = function(str, char) - local length = str:len() - local found_from_back = str:reverse():find(char) - return found_from_back and length - found_from_back - end, - --- Ensure that a nested set of variables exists. - -- Useful when you want to initialise a chain of nested values before writing to them. - ---@param tbl table #The table you want to modify - ---@vararg string #A list of indices to recursively nest into. - ensure_nested = function(tbl, ...) - local ref = tbl or {} - - for _, key in ipairs({ ... }) do - ref[key] = ref[key] or {} - ref = ref[key] - end - end, - - --- Capitalizes the first letter of each word in a given string. - ---@param str string #The string to capitalize - ---@return string #The capitalized string. - title = function(str) - local result = {} - - for word in str:gmatch("[^%s]+") do - local lower = word:sub(2):lower() - - table.insert(result, word:sub(1, 1):upper() .. lower) - end - return table.concat(result, " ") - end, - - --- Wraps a number so that it fits within a given range. - ---@param value number #The number to wrap - ---@param min number #The lower bound - ---@param max number #The higher bound - ---@return number #The wrapped number, guarantees `min <= value <= max`. - number_wrap = function(value, min, max) - local range = max - min + 1 - local wrapped_value = ((value - min) % range) + min - - if wrapped_value < min then - wrapped_value = wrapped_value + range - end - - return wrapped_value - end, - - --- Lazily copy a table-like object. - ---@param to_copy table|any #The table to copy. If any other type is provided it will be copied immediately. - ---@return table #The copied table - lazy_copy = function(to_copy) - if type(to_copy) ~= "table" then - return vim.deepcopy(to_copy) - end - - local proxy = { - original = function() - return to_copy - end, - - collect = function(self) - return vim.tbl_deep_extend("force", to_copy, self) - end, - } - - return setmetatable(proxy, { - __index = function(_, key) - if not to_copy[key] then - return nil - end - - if type(to_copy[key]) == "table" then - local copied = neorg.lib.lazy_copy(to_copy[key]) - - rawset(proxy, key, copied) - - return copied - end - - local copied = vim.deepcopy(to_copy[key]) - rawset(proxy, key, copied) - return copied - end, - - __pairs = function(tbl) - local function stateless_iter(_, key) - local value - key, value = next(to_copy, key) - if value ~= nil then - return key, neorg.lib.lazy_copy(value) - end - end - - return stateless_iter, tbl, nil - end, - - __ipairs = function(tbl) - local function stateless_iter(_, i) - i = i + 1 - local value = to_copy[i] - if value ~= nil then - return i, neorg.lib.lazy_copy(value) - end - end - - return stateless_iter, tbl, 0 - end, - }) - end, -} - -return neorg.utils diff --git a/lua/neorg/external/log.lua b/lua/neorg/external/log.lua index dbc02f38e..e69de29bb 100644 --- a/lua/neorg/external/log.lua +++ b/lua/neorg/external/log.lua @@ -1,153 +0,0 @@ --- log.lua --- --- Inspired by rxi/log.lua --- Modified by tjdevries and can be found at github.com/tjdevries/vlog.nvim --- Modified again by Vhyrro for use with neorg :) --- --- This library is free software; you can redistribute it and/or modify it --- under the terms of the MIT license. See LICENSE for details. - --- User configuration section -local default_config = { - -- Name of the plugin. Prepended to log messages - plugin = "neorg", - - -- Should print the output to neovim while running - use_console = true, - - -- Should highlighting be used in console (using echohl) - highlights = true, - - -- Should write to a file - use_file = true, - - -- Any messages above this level will be logged. - level = "warn", - - -- Level configuration - modes = { - { name = "trace", hl = "Comment", level = vim.log.levels.TRACE }, - { name = "debug", hl = "Comment", level = vim.log.levels.DEBUG }, - { name = "info", hl = "None", level = vim.log.levels.INFO }, - { name = "warn", hl = "WarningMsg", level = vim.log.levels.WARN }, - { name = "error", hl = "ErrorMsg", level = vim.log.levels.ERROR }, - { name = "fatal", hl = "ErrorMsg", level = 5 }, - }, - - -- Can limit the number of decimals displayed for floats - float_precision = 0.01, -} - --- {{{ NO NEED TO CHANGE -log = {} - -log.get_default_config = function() - return default_config -end - -local unpack = unpack or table.unpack - -log.new = function(config, standalone) - config = vim.tbl_deep_extend("force", default_config, config) - config.plugin = "neorg" -- Force the plugin name to be neorg - - local outfile = string.format("%s/%s.log", vim.api.nvim_call_function("stdpath", { "data" }), config.plugin) - - local obj = neorg.lib.match(standalone ~= nil)({ - ["true"] = log, - ["false"] = {}, - }) - - local levels = {} - for _, v in ipairs(config.modes) do - levels[v.name] = v.level - end - - local round = function(x, increment) - increment = increment or 1 - x = x / increment - return (x > 0 and math.floor(x + 0.5) or math.ceil(x - 0.5)) * increment - end - - local make_string = function(...) - local t = {} - for i = 1, select("#", ...) do - local x = select(i, ...) - - if type(x) == "number" and config.float_precision then - x = tostring(round(x, config.float_precision)) - elseif type(x) == "table" then - x = vim.inspect(x) - else - x = tostring(x) - end - - t[#t + 1] = x - end - return table.concat(t, " ") - end - - local log_at_level = function(level_config, message_maker, ...) - -- Return early if we"re below the config.level - if levels[level_config.name] < levels[config.level] then - return - end - local nameupper = level_config.name:upper() - - local msg = message_maker(...) - local info = debug.getinfo(2, "Sl") - local lineinfo = info.short_src .. ":" .. info.currentline - - -- Output to console - if config.use_console then - local v = string.format("(%s)\n%s\n%s", os.date("%H:%M:%S"), lineinfo, msg) - - if config.highlights and level_config.hl then - (vim.schedule_wrap(function() - vim.cmd(string.format("echohl %s", level_config.hl)) - end))() - end - - (vim.schedule_wrap(function() - vim.notify(string.format("[%s] %s", config.plugin, vim.fn.escape(v, '"')), level_config.level) - -- vim.cmd(string.format([[echom "[%s] %s"]], config.plugin, vim.fn.escape(v, '"'))) - end))() - - if config.highlights and level_config.hl then - (vim.schedule_wrap(function() - vim.cmd("echohl NONE") - end))() - end - end - - -- Output to log file - if config.use_file then - local fp = io.open(outfile, "a") - local str = string.format("[%-6s%s] %s: %s\n", nameupper, os.date(), lineinfo, msg) - fp:write(str) - fp:close() - end - end - - for _, x in ipairs(config.modes) do - obj[x.name] = function(...) - return log_at_level(x, make_string, ...) - end - - obj[("fmt_%s"):format(x.name)] = function() - return log_at_level(x, function(...) - local passed = { ... } - local fmt = table.remove(passed, 1) - local inspected = {} - for _, v in ipairs(passed) do - table.insert(inspected, vim.inspect(v)) - end - return string.format(fmt, unpack(inspected)) - end) - end - end -end - --- }}} - -return log diff --git a/lua/neorg/modules.lua b/lua/neorg/modules.lua deleted file mode 100644 index 9108daa22..000000000 --- a/lua/neorg/modules.lua +++ /dev/null @@ -1,370 +0,0 @@ ---[[ --- NEORG MODULE MANAGER --- This file is responsible for loading, calling and managing modules --- Modules are internal mini-programs that execute on certain events, they build the foundation of Neorg itself. ---]] - --- Include the global logger instance -local log = require("neorg.external.log") - -require("neorg.modules.base") - ---[[ --- The reason we do not just call this variable neorg.modules.loaded_modules.count is because --- someone could make a module called "count" and override the variable, causing bugs. ---]] -neorg.modules.loaded_module_count = 0 - ---- The table of currently loaded modules -neorg.modules.loaded_modules = {} - ---- Loads and enables a module --- Loads a specified module. If the module subscribes to any events then they will be activated too. ----@param module table #The actual module to load ----@return boolean #Whether the module successfully loaded -function neorg.modules.load_module_from_table(module) - log.info("Loading module with name", module.name) - - -- If our module is already loaded don't try loading it again - if neorg.modules.loaded_modules[module.name] then - log.trace("Module", module.name, "already loaded. Omitting...") - return true - end - - -- Invoke the setup function. This function returns whether or not the loading of the module was successful and some metadata. - local loaded_module = module.setup and module.setup() - or { - success = true, - replaces = {}, - replace_merge = false, - requires = {}, - wants = {}, - } - - -- We do not expect module.setup() to ever return nil, that's why this check is in place - if not loaded_module then - log.error( - "Module", - module.name, - "does not handle module loading correctly; module.setup() returned nil. Omitting..." - ) - return false - end - - -- A part of the table returned by module.setup() tells us whether or not the module initialization was successful - if loaded_module.success == false then - log.trace("Module", module.name, "did not load properly.") - return false - end - - --[[ - -- This small snippet of code creates a copy of an already loaded module with the same name. - -- If the module wants to replace an already loaded module then we need to create a deepcopy of that old module - -- in order to stop it from getting overwritten. - --]] - local module_to_replace - - -- If the return value of module.setup() tells us to hotswap with another module then cache the module we want to replace with - if loaded_module.replaces and loaded_module.replaces ~= "" then - module_to_replace = vim.deepcopy(neorg.modules.loaded_modules[loaded_module.replaces]) - end - - -- Add the module into the list of loaded modules - -- The reason we do this here is so other modules don't recursively require each other in the dependency loading loop below - neorg.modules.loaded_modules[module.name] = module - - -- If the module "wants" any other modules then verify they are loaded - if loaded_module.wants and not vim.tbl_isempty(loaded_module.wants) then - log.info("Module", module.name, "wants certain modules. Ensuring they are loaded...") - - -- Loop through each dependency and ensure it's loaded - for _, required_module in ipairs(loaded_module.wants) do - log.trace("Verifying", required_module) - - -- This would've always returned false had we not added the current module to the loaded module list earlier above - if not neorg.modules.is_module_loaded(required_module) then - if neorg.configuration.user_configuration[required_module] then - log.trace( - "Wanted module", - required_module, - "isn't loaded but can be as it's defined in the user's config. Loading..." - ) - - if not neorg.modules.load_module(required_module) then - log.error( - "Unable to load wanted module for", - loaded_module.name, - "- the module didn't load successfully" - ) - - -- Make sure to clean up after ourselves if the module failed to load - neorg.modules.loaded_modules[module.name] = nil - return false - end - else - log.error( - ("Unable to load module %s, wanted dependency %s was not satisfied. Be sure to load the module and its appropriate config too!"):format( - module.name, - required_module - ) - ) - - -- Make sure to clean up after ourselves if the module failed to load - neorg.modules.loaded_modules[module.name] = nil - return false - end - end - - -- Create a reference to the dependency's public table - module.required[required_module] = neorg.modules.loaded_modules[required_module].public - end - end - - -- If any dependencies have been defined, handle them - if loaded_module.requires and vim.tbl_count(loaded_module.requires) > 0 then - log.info("Module", module.name, "has dependencies. Loading dependencies first...") - - -- Loop through each dependency and load it one by one - for _, required_module in pairs(loaded_module.requires) do - log.trace("Loading submodule", required_module) - - -- This would've always returned false had we not added the current module to the loaded module list earlier above - if not neorg.modules.is_module_loaded(required_module) then - if not neorg.modules.load_module(required_module) then - log.error( - ("Unable to load module %s, required dependency %s did not load successfully"):format( - module.name, - required_module - ) - ) - - -- Make sure to clean up after ourselves if the module failed to load - neorg.modules.loaded_modules[module.name] = nil - return false - end - else - log.trace("Module", required_module, "already loaded, skipping...") - end - - -- Create a reference to the dependency's public table - module.required[required_module] = neorg.modules.loaded_modules[required_module].public - end - end - - -- After loading all our dependencies, see if we need to hotswap another module with ourselves - if module_to_replace then - -- Make sure the names of both modules match - module.name = module_to_replace.name - - -- Whenever a module gets hotswapped, a special flag is set inside the module in order to signalize that it has been hotswapped before - -- If this flag has already been set before, then throw an error - there is no way for us to know which hotswapped module should take priority. - if module_to_replace.replaced then - log.error( - ("Unable to replace module %s - module replacement clashing detected. This error triggers when a module tries to be replaced more than two times - neorg doesn't know which replacement to prioritize."):format( - module_to_replace.name - ) - ) - - -- Make sure to clean up after ourselves if the module failed to load - neorg.modules.loaded_modules[module.name] = nil - - return false - end - - -- If the replace_merge flag is set to true in the setup() return value then recursively merge the data from the - -- previous module into our new one. This allows for practically seamless hotswapping, as it allows you to retain the data - -- of the previous module. - if loaded_module.replace_merge then - module = vim.tbl_deep_extend("force", module, { - private = module_to_replace.private, - config = module_to_replace.config, - public = module_to_replace.public, - events = module_to_replace.events, - }) - end - - -- Set the special module.replaced flag to let everyone know we've been hotswapped before - module.replaced = true - end - - log.info("Successfully loaded module", module.name) - - -- Keep track of the number of loaded modules - neorg.modules.loaded_module_count = neorg.modules.loaded_module_count + 1 - - -- NOTE(vhyrro): Left here for debugging. - -- Maybe make controllable with a switch in the future. - -- local start = vim.loop.hrtime() - - -- Call the load function - if module.load then - module.load() - end - - -- local msg = ("%fms"):format((vim.loop.hrtime() - start) / 1e6) - -- vim.notify(msg .. " " .. module.name) - - neorg.events.broadcast_event({ - type = "core.module_loaded", - split_type = { "core", "module_loaded" }, - filename = "", - filehead = "", - cursor_position = { 0, 0 }, - referrer = "core", - line_content = "", - content = module, - broadcast = true, - }) - - return true -end - ---- Unlike `load_module_from_table()`, which loads a module from memory, `load_module()` tries to find the corresponding module file on disk and loads it into memory. --- If the module cannot not be found, attempt to load it off of github (unimplemented). This function also applies user-defined configurations and keymaps to the modules themselves. --- This is the recommended way of loading modules - `load_module_from_table()` should only really be used by neorg itself. ----@param module_name string #A path to a module on disk. A path seperator in neorg is '.', not '/' ----@param config table? #A configuration that reflects the structure of `neorg.configuration.user_configuration.load["module.name"].config` ----@return boolean #Whether the module was successfully loaded -function neorg.modules.load_module(module_name, config) - -- Don't bother loading the module from disk if it's already loaded - if neorg.modules.is_module_loaded(module_name) then - return true - end - - -- Attempt to require the module, does not throw an error if the module doesn't exist - local exists, module = pcall(require, "neorg.modules." .. module_name .. ".module") - - -- If the module doesn't exist then return false - if not exists then - local fallback_exists, fallback_module = pcall(require, "neorg.modules." .. module_name) - - if not fallback_exists then - log.error("Unable to load module", module_name, "-", module) - return false - end - - module = fallback_module - end - - -- If the module is nil for some reason return false - if not module then - log.error( - "Unable to load module", - module_name, - "- loaded file returned nil. Be sure to return the table created by neorg.modules.create() at the end of your module.lua file!" - ) - return false - end - - -- If the value of `module` is strictly true then it means the required file returned nothing - -- We obviously can't do anything meaningful with that! - if module == true then - log.error( - "An error has occurred when loading", - module_name, - "- loaded file didn't return anything meaningful. Be sure to return the table created by neorg.modules.create() at the end of your module.lua file!" - ) - return false - end - - -- Load the user-defined configuration - if config and not vim.tbl_isempty(config) then - module.config.custom = config - module.config.public = vim.tbl_deep_extend("force", module.config.public, config) - else - module.config.public = - vim.tbl_deep_extend("force", module.config.public, require("neorg.config").modules[module_name] or {}) - end - - -- Pass execution onto load_module_from_table() and let it handle the rest - return neorg.modules.load_module_from_table(module) -end - ---- Has the same principle of operation as load_module_from_table(), except it then sets up the parent module's "required" table, allowing the parent to access the child as if it were a dependency. ----@param module table #A valid table as returned by neorg.modules.create() ----@param parent_module string|table #If a string, then the parent is searched for in the loaded modules. If a table, then the module is treated as a valid module as returned by neorg.modules.create() -function neorg.modules.load_module_as_dependency_from_table(module, parent_module) - if neorg.modules.load_module_from_table(module) then - if type(parent_module) == "string" then - neorg.modules.loaded_modules[parent_module].required[module.name] = module.public - elseif type(parent_module) == "table" then - parent_module.required[module.name] = module.public - end - end -end - ---- Normally loads a module, but then sets up the parent module's "required" table, allowing the parent module to access the child as if it were a dependency. ----@param module_name string #A path to a module on disk. A path seperator in neorg is '.', not '/' ----@param parent_module string #The name of the parent module. This is the module which the dependency will be attached to. ----@param config table #A configuration that reflects the structure of neorg.configuration.user_configuration.load["module.name"].config -function neorg.modules.load_module_as_dependency(module_name, parent_module, config) - if neorg.modules.load_module(module_name, config) and neorg.modules.is_module_loaded(parent_module) then - neorg.modules.loaded_modules[parent_module].required[module_name] = neorg.modules.get_module_config(module_name) - end -end - ---- Retrieves the public API exposed by the module ----@param module_name string #The name of the module to retrieve -function neorg.modules.get_module(module_name) - if not neorg.modules.is_module_loaded(module_name) then - log.trace("Attempt to get module with name", module_name, "failed - module is not loaded.") - return - end - - return neorg.modules.loaded_modules[module_name].public -end - ---- Returns the module.config.public table if the module is loaded ----@param module_name string #The name of the module to retrieve (module must be loaded) -function neorg.modules.get_module_config(module_name) - if not neorg.modules.is_module_loaded(module_name) then - log.trace("Attempt to get module configuration with name", module_name, "failed - module is not loaded.") - return - end - - return neorg.modules.loaded_modules[module_name].config.public -end - ---- Returns true if module with name module_name is loaded, false otherwise ----@param module_name string #The name of an arbitrary module -function neorg.modules.is_module_loaded(module_name) - return neorg.modules.loaded_modules[module_name] ~= nil -end - ---- Reads the module's public table and looks for a version variable, then converts it from a string into a table, like so: { major = , minor = , patch = } ----@param module_name string #The name of a valid, loaded module. --- @Return struct | nil (if any error occurs) -function neorg.modules.get_module_version(module_name) - -- If the module isn't loaded then don't bother retrieving its version - if not neorg.modules.is_module_loaded(module_name) then - log.trace("Attempt to get module version with name", module_name, "failed - module is not loaded.") - return - end - - -- Grab the version of the module - local version = neorg.modules.get_module(module_name).version - - -- If it can't be found then error out - if not version then - log.trace("Attempt to get module version with name", module_name, "failed - version variable not present.") - return - end - - return neorg.utils.parse_version_string(version) -end - ---- Executes `callback` once `module` is a valid and loaded module, else the callback gets instantly executed. ----@param module_name string #The name of the module to listen for. ----@param callback fun(module_public_table: table) #The callback to execute. -function neorg.modules.await(module_name, callback) - if neorg.modules.is_module_loaded(module_name) then - callback(assert(neorg.modules.get_module(module_name))) - return - end - - neorg.callbacks.on_event("core.module_loaded", function(_, module) - callback(module.public) - end, function(event) - return event.content.name == module_name - end) -end diff --git a/lua/neorg/modules/base.lua b/lua/neorg/modules/base.lua deleted file mode 100644 index 5b31443af..000000000 --- a/lua/neorg/modules/base.lua +++ /dev/null @@ -1,191 +0,0 @@ ---[[ --- BASE FILE FOR MODULES --- This file contains the base module implementation ---]] - -neorg.modules = {} - ---- Returns a new Neorg module, exposing all the necessary function and variables ----@param name string #The name of the new module. Make sure this is unique. The recommended naming convention is category.module_name or category.subcategory.module_name ----@param imports? string[] #A list of imports to attach to the module. Import data is requestable via `module.required`. Use paths relative to the current module. -function neorg.modules.create(name, imports) - local new_module = { - - -- Invoked before any initial loading happens - setup = function() - return { success = true, requires = {}, replaces = nil, replace_merge = false } - end, - - -- Invoked after the module has been configured - load = function() end, - - -- Invoked whenever an event that the module has subscribed to triggers - -- callback function with a "event" parameter - on_event = function() end, - - -- Invoked after all plugins are loaded - neorg_post_load = function() end, - - -- The name of the module, note that modules beginning with core are neorg's inbuilt modules - name = "core.default", - - -- The path of the module, can be used in require() statements - path = "neorg.modules.core.default.module", - - -- A convenience table to place all of your private variables that you don't want to expose here. - private = {}, - - -- Every module can expose any set of information it sees fit through the public field - -- All functions and variables declared in this table will be visible to any other module loaded - public = { - -- Current Norg version that this module supports. - -- Your module will use this version if not specified, but you can override it. - -- Overriding it will mean that your module is only compatible with the overriden Norg revision. - -- E.g: setting version = "1.0.0" will mean that your module requires Norg 1.0.0+ to operate - version = require("neorg.config").norg_version, - }, - - -- Configuration for the module - config = { - private = { -- Private module configuration, cannot be changed by other modules or by the user - --[[ - config_option = false, - - ["option_group"] = { - sub_option = true - } - --]] - }, - - public = { -- Public config, can be changed by modules and the user - --[[ - config_option = false, - - ["option_group"] = { - sub_option = true - } - --]] - }, - - -- This table houses all the changes the user made to the public table, - -- useful for when you want to know exactly what the user tinkered with. - -- Shouldn't be commonly used. - custom = {}, - }, - - -- Event data regarding the current module - events = { - subscribed = { -- The events that the module is subscribed to - --[[ - ["core.test"] = { -- The name of the module that has events bound to it - ["test_event"] = true, -- Subscribes to event core.test.events.test_event - - ["other_event"] = true -- Subscribes to event core.test.events.other_event - } - --]] - }, - defined = { -- The events that the module itself has defined - --[[ - ["my_event"] = { event_data } -- Creates an event of type category.module.events.my_event - --]] - }, - }, - - -- If you ever require a module through the return value of the setup() function, - -- All of the modules' public APIs will become available here - required = { - --[[ - ["core.test"] = { - -- Their public API here... - }, - - ["core.some_other_plugin"] = { - -- Their public API here... - } - - --]] - }, - - -- Example bits of code that the user can look through - examples = { - --[[ - a_cool_test = function() - print("Some code!") - end - --]] - }, - - -- Imported submodules of the given module. - -- Contrary to `required`, which only exposes the public API of a module, - -- imported modules can be accessed in their entirety. - imported = { - --[[ - ["my.module.submodule"] = { ... }, - --]] - }, - } - - if imports then - for _, import in ipairs(imports) do - local fullpath = table.concat({ name, import }, ".") - - if not neorg.modules.load_module(fullpath) then - log.error("Unable to load import '" .. fullpath .. "'! An error occured (see traceback below):") - assert(false) -- Halt execution, no recovering from this error... - end - - new_module.imported[fullpath] = neorg.modules.loaded_modules[fullpath] - end - end - - if name then - new_module.name = name - new_module.path = "neorg.modules." .. name - end - - return new_module -end - ---- Constructs a metamodule from a list of submodules. Metamodules are modules that can autoload batches of modules at once. ----@param name string #The name of the new metamodule. Make sure this is unique. The recommended naming convention is category.module_name or category.subcategory.module_name --- @Param ... (varargs) - a list of module names to load. -function neorg.modules.create_meta(name, ...) - local module = neorg.modules.create(name) - - require("neorg.modules") - - module.config.public.enable = { ... } - - module.setup = function() - return { success = true } - end - - module.load = function() - module.config.public.enable = (function() - -- If we haven't define any modules to disable then just return all enabled modules - if not module.config.public.disable then - return module.config.public.enable - end - - local ret = {} - - -- For every enabled module - for _, mod in ipairs(module.config.public.enable) do - -- If that module does not exist in the disable table (ie. it is enabled) then add it to the `ret` table - if not vim.tbl_contains(module.config.public.disable, mod) then - table.insert(ret, mod) - end - end - - -- Return the table containing all the modules we would like to enable - return ret - end)() - - -- Go through every module that we have defined in the metamodule and load it! - for _, mod in ipairs(module.config.public.enable) do - neorg.modules.load_module(mod) - end - end - - return module -end diff --git a/lua/neorg/modules/core/autocommands/module.lua b/lua/neorg/modules/core/autocommands/module.lua index f64b579b3..6cd015b47 100644 --- a/lua/neorg/modules/core/autocommands/module.lua +++ b/lua/neorg/modules/core/autocommands/module.lua @@ -36,23 +36,23 @@ Upon receiving an event, it will come in this format: ``` --]] -require("neorg.modules.base") -require("neorg.events") +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules -local module = neorg.modules.create("core.autocommands") +local module = modules.create("core.autocommands") --- This function gets invoked whenever a core.autocommands enabled autocommand is triggered. Note that this function should be only used internally ---@param name string #The name of the autocommand that was just triggered ---@param triggered_from_norg boolean #If true, that means we have received this event as part of a *.norg autocommand function _neorg_module_autocommand_triggered(name, triggered_from_norg) - local event = neorg.events.create(module, name, { norg = triggered_from_norg }) + local event = modules.create_event(module, name, { norg = triggered_from_norg }) assert(event) - neorg.events.broadcast_event(event) + modules.broadcast_event(event) end --- A convenience wrapper around neorg.events.define_event +-- A convenience wrapper around modules.define_event_event module.autocmd_base = function(name) - return neorg.events.define(module, name) + return modules.define_event(module, name) end ---@class core.autocommands @@ -334,7 +334,7 @@ module.events.defined = { module.examples = { ["Binding to an Autocommand"] = function() - local mymodule = neorg.modules.create("my.module") + local mymodule = modules.create("my.module") mymodule.setup = function() return { diff --git a/lua/neorg/modules/core/clipboard/code-blocks/module.lua b/lua/neorg/modules/core/clipboard/code-blocks/module.lua index 1a2a40077..1ef4caa55 100644 --- a/lua/neorg/modules/core/clipboard/code-blocks/module.lua +++ b/lua/neorg/modules/core/clipboard/code-blocks/module.lua @@ -14,10 +14,13 @@ excluding the `@code` and `@end` portion itself. If the conditions are not met, the content is copied normally, preserving all indentation. --]] -local module = neorg.modules.create("core.clipboard.code-blocks") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.clipboard.code-blocks") module.load = function() - neorg.modules.await("core.clipboard", function(clipboard) + modules.await("core.clipboard", function(clipboard) clipboard.add_callback("ranged_verbatim_tag_content", function(node, content, position) -- TODO: Handle visual/visual line/visual block modes diff --git a/lua/neorg/modules/core/clipboard/module.lua b/lua/neorg/modules/core/clipboard/module.lua index 803e829ec..14b6d9286 100644 --- a/lua/neorg/modules/core/clipboard/module.lua +++ b/lua/neorg/modules/core/clipboard/module.lua @@ -1,3 +1,4 @@ + --[[ file: Clipboard title: Quality of Life Features for the Clipboard @@ -8,7 +9,10 @@ The clipboard module is a minimal and generic module allowing to overwrite or ad `y` (yank) keybind in Neovim. --]] -local module = neorg.modules.create("core.clipboard") +local neorg = require("neorg.core") +local lib, modules = neorg.lib, neorg.modules + +local module = modules.create("core.clipboard") module.setup = function() return { @@ -38,7 +42,7 @@ module.load = function() vim.fn.setreg( vim.v.register, - neorg.lib.filter(module.private.callbacks[node:type()], function(_, callback) + lib.filter(module.private.callbacks[node:type()], function(_, callback) if callback.strict and (range[1][1] < i or range[2][1] > node:end_()) then return end diff --git a/lua/neorg/modules/core/completion/module.lua b/lua/neorg/modules/core/completion/module.lua index 5f4eea22b..535817481 100644 --- a/lua/neorg/modules/core/completion/module.lua +++ b/lua/neorg/modules/core/completion/module.lua @@ -1,3 +1,4 @@ + --[[ file: Completion title: Get completions in Neorg files @@ -10,10 +11,10 @@ please read the corresponding wiki page for the engine you selected ([`nvim-cmp` or [`nvim-compe`](@core.integrations.nvim-compe)) to complete setup. --]] -require("neorg.modules.base") -require("neorg.modules") +local neorg = require("neorg.core") +local lib, log, modules = neorg.lib, neorg.log, neorg.modules -local module = neorg.modules.create("core.completion") +local module = modules.create("core.completion") module.config.public = { -- The engine to use for completion. @@ -43,12 +44,12 @@ module.load = function() end -- If our engine is compe then attempt to load the integration module for nvim-compe - if module.config.public.engine == "nvim-compe" and neorg.modules.load_module("core.integrations.nvim-compe") then - neorg.modules.load_module_as_dependency("core.integrations.nvim-compe", module.name, {}) - module.private.engine = neorg.modules.get_module("core.integrations.nvim-compe") - elseif module.config.public.engine == "nvim-cmp" and neorg.modules.load_module("core.integrations.nvim-cmp") then - neorg.modules.load_module_as_dependency("core.integrations.nvim-cmp", module.name, {}) - module.private.engine = neorg.modules.get_module("core.integrations.nvim-cmp") + if module.config.public.engine == "nvim-compe" and modules.load_module("core.integrations.nvim-compe") then + modules.load_module_as_dependency("core.integrations.nvim-compe", module.name, {}) + module.private.engine = modules.get_module("core.integrations.nvim-compe") + elseif module.config.public.engine == "nvim-cmp" and modules.load_module("core.integrations.nvim-cmp") then + modules.load_module_as_dependency("core.integrations.nvim-cmp", module.name, {}) + module.private.engine = modules.get_module("core.integrations.nvim-cmp") else log.error("Unable to load completion module -", module.config.public.engine, "is not a recognized engine.") return @@ -124,7 +125,7 @@ module.public = { regex = "code%s+%w*", -- No node variable, we don't need that sort of check here - complete = require("neorg.external.helpers").get_language_list(true), + complete = lib.get_language_list(true), -- Extra options options = { @@ -137,7 +138,7 @@ module.public = { { regex = "export%s+%w*", - complete = require("neorg.external.helpers").get_language_list(true), + complete = lib.get_language_list(true), options = { type = "Language", diff --git a/lua/neorg/modules/core/concealer/module.lua b/lua/neorg/modules/core/concealer/module.lua index 6902b76b0..abe74e14d 100644 --- a/lua/neorg/modules/core/concealer/module.lua +++ b/lua/neorg/modules/core/concealer/module.lua @@ -17,6 +17,9 @@ installed on your system. -- utils to be refactored +local neorg = require("neorg.core") +local lib, log, modules, utils = neorg.lib, neorg.log, neorg.modules, neorg.utils + local function in_range(k, l, r_ex) return l <= k and k < r_ex end @@ -59,12 +62,9 @@ end --- end utils -require("neorg.modules.base") -require("neorg.external.helpers") - -local has_anticonceal = neorg.utils.is_minimum_version(0, 10, 0) +local has_anticonceal = utils.is_minimum_version(0, 10, 0) -local module = neorg.modules.create("core.concealer", { +local module = modules.create("core.concealer", { "preset_basic", "preset_varied", "preset_diamond", @@ -377,7 +377,7 @@ module.public = { local foldstart = vim.v.foldstart local line = vim.api.nvim_buf_get_lines(0, foldstart - 1, foldstart, true)[1] - return neorg.lib.match(line, function(lhs, rhs) + return lib.match(line, function(lhs, rhs) return vim.startswith(lhs, rhs) end)({ ["@document.meta"] = "Document Metadata", @@ -1054,7 +1054,7 @@ local function get_parsed_query_lazy() table.insert(queries, "]") local query_combined = table.concat(queries, " ") - module.private.prettify_query = neorg.utils.ts_parse_query("norg", query_combined) + module.private.prettify_query = utils.ts_parse_query("norg", query_combined) assert(module.private.prettify_query) module.private.config_by_node_name = config_by_node_name return module.private.prettify_query @@ -1248,7 +1248,7 @@ local function handle_init_event(event) } vim.api.nvim_set_option_value("foldmethod", "expr", opts) vim.api.nvim_set_option_value("foldexpr", "nvim_treesitter#foldexpr()", opts) - vim.api.nvim_set_option_value("foldtext", "v:lua.neorg.modules.get_module('core.concealer').foldtext()", opts) + vim.api.nvim_set_option_value("foldtext", "v:lua.modules.get_module('core.concealer').foldtext()", opts) end end @@ -1357,7 +1357,7 @@ module.load = function() module.required["core.autocommands"].enable_autocommand("CursorMovedI") module.required["core.autocommands"].enable_autocommand("WinScrolled", true) - neorg.modules.await("core.neorgcmd", function(neorgcmd) + modules.await("core.neorgcmd", function(neorgcmd) neorgcmd.add_commands_from_table({ ["toggle-concealer"] = { name = "core.concealer.toggle", @@ -1366,7 +1366,7 @@ module.load = function() }, }) end) - if neorg.utils.is_minimum_version(0, 7, 0) then + if utils.is_minimum_version(0, 7, 0) then vim.api.nvim_create_autocmd("OptionSet", { pattern = "conceallevel", callback = function(_ev) diff --git a/lua/neorg/modules/core/concealer/preset_basic.lua b/lua/neorg/modules/core/concealer/preset_basic.lua index ce6c945cf..fff1fe2fe 100644 --- a/lua/neorg/modules/core/concealer/preset_basic.lua +++ b/lua/neorg/modules/core/concealer/preset_basic.lua @@ -1,4 +1,7 @@ -local module = neorg.modules.create("core.concealer.preset_basic") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.concealer.preset_basic") module.config.private.icon_preset_basic = {} diff --git a/lua/neorg/modules/core/concealer/preset_diamond.lua b/lua/neorg/modules/core/concealer/preset_diamond.lua index 8902fb2b3..23d032b82 100644 --- a/lua/neorg/modules/core/concealer/preset_diamond.lua +++ b/lua/neorg/modules/core/concealer/preset_diamond.lua @@ -1,4 +1,7 @@ -local module = neorg.modules.create("core.concealer.preset_diamond") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.concealer.preset_diamond") module.config.private.icon_preset_diamond = { heading = { diff --git a/lua/neorg/modules/core/concealer/preset_varied.lua b/lua/neorg/modules/core/concealer/preset_varied.lua index f04d1b0a5..cc7f0d84e 100644 --- a/lua/neorg/modules/core/concealer/preset_varied.lua +++ b/lua/neorg/modules/core/concealer/preset_varied.lua @@ -1,4 +1,7 @@ -local module = neorg.modules.create("core.concealer.preset_varied") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.concealer.preset_varied") module.config.private.icon_preset_varied = { heading = { diff --git a/lua/neorg/modules/core/defaults/module.lua b/lua/neorg/modules/core/defaults/module.lua index 726c601e1..c1dcc0f90 100644 --- a/lua/neorg/modules/core/defaults/module.lua +++ b/lua/neorg/modules/core/defaults/module.lua @@ -22,9 +22,10 @@ load = { ``` --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local modules = neorg.modules -return neorg.modules.create_meta( +return modules.create_meta( "core.defaults", "core.autocommands", "core.clipboard", diff --git a/lua/neorg/modules/core/dirman/module.lua b/lua/neorg/modules/core/dirman/module.lua index 28d4222e9..62db03ad0 100644 --- a/lua/neorg/modules/core/dirman/module.lua +++ b/lua/neorg/modules/core/dirman/module.lua @@ -35,10 +35,11 @@ To query the current workspace, run `:Neorg workspace`. To set the workspace, ru After a recent update `core.dirman` will no longer change the current working directory after switching workspace. To get the best experience it's recommended to set the `autochdir` Neovim option. --]] -require("neorg.modules.base") -require("neorg.modules") -local module = neorg.modules.create("core.dirman") +local neorg = require("neorg.core") +local config, log, modules, utils = neorg.config, neorg.log, neorg.modules, neorg.utils + +local module = modules.create("core.dirman") module.setup = function() return { @@ -162,8 +163,8 @@ module.public = { end -- Broadcast the workspace_changed event with all the necessary information - neorg.events.broadcast_event( - neorg.events.create( + modules.broadcast_event( + modules.create_event( module, "core.dirman.events.workspace_changed", { old = current_ws, new = new_workspace } @@ -185,8 +186,8 @@ module.public = { -- Set the new workspace and its path accordingly module.config.public.workspaces[workspace_name] = workspace_path -- Broadcast the workspace_added event with the newly added workspace as the content - neorg.events.broadcast_event( - neorg.events.create(module, "core.dirman.events.workspace_added", { workspace_name, workspace_path }) + modules.broadcast_event( + modules.create_event(module, "core.dirman.events.workspace_added", { workspace_name, workspace_path }) ) -- Sync autocompletions so the user can see the new workspace @@ -282,7 +283,7 @@ module.public = { end -- Split the path at every / - local split = vim.split(vim.trim(path), neorg.configuration.pathsep, true) + local split = vim.split(vim.trim(path), config.pathsep, true) -- If the last element is empty (i.e. if the string provided ends with '/') then trim it if split[#split]:len() == 0 then @@ -291,12 +292,12 @@ module.public = { -- Go through each directory (excluding the actual file name) and create each directory individually for _, element in ipairs(vim.list_slice(split, 0, #split - 1)) do - vim.loop.fs_mkdir(fullpath .. neorg.configuration.pathsep .. element, 16877) - fullpath = fullpath .. neorg.configuration.pathsep .. element + vim.loop.fs_mkdir(fullpath .. config.pathsep .. element, 16877) + fullpath = fullpath .. config.pathsep .. element end -- If the provided filepath ends in .norg then don't append the filetype automatically - local fname = fullpath .. neorg.configuration.pathsep .. split[#split] + local fname = fullpath .. config.pathsep .. split[#split] if not vim.endswith(path, ".norg") then fname = fname .. ".norg" end @@ -325,12 +326,12 @@ module.public = { return end - vim.cmd("e " .. workspace .. neorg.configuration.pathsep .. path .. " | w") + vim.cmd("e " .. workspace .. config.pathsep .. path .. " | w") end, --- Reads the neorg_last_workspace.txt file and loads the cached workspace from there set_last_workspace = function() -- Attempt to open the last workspace cache file in read-only mode - local storage = neorg.modules.get_module("core.storage") + local storage = modules.get_module("core.storage") if not storage then log.trace("Module `core.storage` not loaded, refusing to load last user's workspace.") @@ -351,9 +352,9 @@ module.public = { -- If we were successful in switching to that workspace then begin editing that workspace's index file if module.public.set_workspace(last_workspace) then - vim.cmd("e " .. workspace_path .. neorg.configuration.pathsep .. module.config.public.index) + vim.cmd("e " .. workspace_path .. config.pathsep .. module.config.public.index) - neorg.utils.notify("Last Workspace -> " .. workspace_path) + utils.notify("Last Workspace -> " .. workspace_path) end end, --- Checks for file existence by supplying a full path in `filepath` @@ -391,7 +392,7 @@ module.public = { for name, type in scanned_dir do if type == "file" and vim.endswith(name, ".norg") then - table.insert(res, workspace .. neorg.configuration.pathsep .. name) + table.insert(res, workspace .. config.pathsep .. name) end end @@ -414,7 +415,7 @@ module.public = { -- If we're switching to a workspace that isn't the default workspace then enter the index file if workspace ~= "default" then - vim.cmd("e " .. ws_match .. neorg.configuration.pathsep .. module.config.public.index) + vim.cmd("e " .. ws_match .. config.pathsep .. module.config.public.index) end end, --- Touches a file in workspace @@ -433,7 +434,7 @@ module.public = { return false end - local file = io.open(ws_match .. neorg.configuration.pathsep .. path, "w") + local file = io.open(ws_match .. config.pathsep .. path, "w") if not file then return false @@ -462,7 +463,7 @@ module.on_event = function(event) return end - neorg.utils.notify("New Workspace: " .. event.content[1] .. " -> " .. new_workspace) + utils.notify("New Workspace: " .. event.content[1] .. " -> " .. new_workspace) end) else -- No argument supplied, simply print the current workspace -- Query the current workspace @@ -470,7 +471,7 @@ module.on_event = function(event) -- Nicely print it. We schedule_wrap here because people with a configured logger will have this message -- silenced by other trace logs vim.schedule(function() - neorg.utils.notify("Current Workspace: " .. current_ws[1] .. " -> " .. current_ws[2]) + utils.notify("Current Workspace: " .. current_ws[1] .. " -> " .. current_ws[2]) end) end end @@ -480,7 +481,7 @@ module.on_event = function(event) local current_ws = module.public.get_current_workspace() if current_ws[1] == "default" then - neorg.utils.notify( + utils.notify( "No workspace is set! Use `:Neorg workspace ` to set the current workspace. Aborting..." ) return @@ -490,7 +491,7 @@ module.on_event = function(event) if vim.fn.filereadable(index_path) == 0 then if not module.public.touch_file(module.config.public.index, module.public.get_current_workspace()[1]) then - neorg.utils.notify( + utils.notify( table.concat({ "Unable to create '", module.config.public.index, @@ -532,9 +533,9 @@ module.on_event = function(event) end module.events.defined = { - workspace_changed = neorg.events.define(module, "workspace_changed"), - workspace_added = neorg.events.define(module, "workspace_added"), - workspace_cache_empty = neorg.events.define(module, "workspace_cache_empty"), + workspace_changed = modules.define_event(module, "workspace_changed"), + workspace_added = modules.define_event(module, "workspace_added"), + workspace_cache_empty = modules.define_event(module, "workspace_cache_empty"), } module.events.subscribed = { diff --git a/lua/neorg/modules/core/dirman/utils/module.lua b/lua/neorg/modules/core/dirman/utils/module.lua index b2190a8b4..e6e1fc982 100644 --- a/lua/neorg/modules/core/dirman/utils/module.lua +++ b/lua/neorg/modules/core/dirman/utils/module.lua @@ -8,6 +8,9 @@ Currently the only exposed API function is `expand_path`, which takes a path lik converts `$name` into the full path of the workspace called `name`. --]] +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules + local module = neorg.modules.create("core.dirman.utils") module.public = { @@ -16,7 +19,7 @@ module.public = { local custom_workspace_path = path:match("^%$([^/\\]*)[/\\]") if custom_workspace_path then - local dirman = neorg.modules.get_module("core.dirman") + local dirman = modules.get_module("core.dirman") if not dirman then log.error( diff --git a/lua/neorg/modules/core/esupports/hop/module.lua b/lua/neorg/modules/core/esupports/hop/module.lua index 844f067c5..fe43a2074 100644 --- a/lua/neorg/modules/core/esupports/hop/module.lua +++ b/lua/neorg/modules/core/esupports/hop/module.lua @@ -11,10 +11,10 @@ If the link location is found, you will be taken to the destination - if it is n prompted with a set of actions that you can perform on the broken link. --]] -require("neorg.modules.base") -require("neorg.external.helpers") +local neorg = require("neorg.core") +local config, lib, log, modules, utils = neorg.config, neorg.lib, neorg.log, neorg.modules, neorg.utils -local module = neorg.modules.create("core.esupports.hop") +local module = modules.create("core.esupports.hop") module.setup = function() return { @@ -79,15 +79,15 @@ module.public = { local function os_open_link(link_location) local o = {} - if neorg.configuration.os_info == "windows" then + if config.os_info == "windows" then o.command = "rundll32.exe" o.args = { "url.dll,FileProtocolHandler", link_location } else - if neorg.configuration.os_info == "linux" then + if config.os_info == "linux" then o.command = "xdg-open" - elseif neorg.configuration.os_info == "mac" then + elseif config.os_info == "mac" then o.command = "open" - elseif neorg.configuration.os_info == "wsl" then + elseif config.os_info == "wsl" then o.command = "explorer.exe" end o.args = { link_location } @@ -118,7 +118,7 @@ module.public = { end if located_link_information then - neorg.lib.match(located_link_information.type)({ + lib.match(located_link_information.type)({ -- If we're dealing with a URI, simply open the URI in the user's preferred method external_app = function() os_open_link(located_link_information.uri) @@ -160,13 +160,13 @@ module.public = { end, calendar = function() - local calendar = neorg.modules.get_module("core.ui.calendar") + local calendar = modules.get_module("core.ui.calendar") if not calendar then log.error("`core.ui.calendar` is not loaded! Unable to open timestamp.") return end - local tempus = neorg.modules.get_module("core.tempus") + local tempus = modules.get_module("core.tempus") if not tempus then log.error("`core.tempus` is not loaded! Unable to parse timestamp.") return @@ -336,7 +336,7 @@ module.public = { return end - local query = neorg.utils.ts_parse_query("norg", query_str) + local query = utils.ts_parse_query("norg", query_str) for id, node in query:iter_captures(document_root, 0) do local capture = query.captures[id] @@ -427,7 +427,7 @@ module.public = { return end - local query = neorg.utils.ts_parse_query("norg", query_text) + local query = utils.ts_parse_query("norg", query_text) local range = module.required["core.integrations.treesitter"].get_node_range(link_node) local parsed_link_information = { @@ -448,12 +448,12 @@ module.public = { and capture_node_range.column_end <= range.column_end then local extract_node_text = - neorg.lib.wrap(module.required["core.integrations.treesitter"].get_node_text, node) + lib.wrap(module.required["core.integrations.treesitter"].get_node_text, node) parsed_link_information[capture] = parsed_link_information[capture] - or neorg.lib.match(capture)({ + or lib.match(capture)({ link_file_text = extract_node_text, - link_type = neorg.lib.wrap(string.sub, node:type(), string.len("link_target_") + 1), + link_type = lib.wrap(string.sub, node:type(), string.len("link_target_") + 1), link_location_text = extract_node_text, link_description = extract_node_text, @@ -495,7 +495,7 @@ module.public = { end end - return neorg.lib.match(parsed_link_information.link_type)({ + return lib.match(parsed_link_information.link_type)({ url = function() return { type = "external_app", uri = parsed_link_information.link_location_text } end, @@ -511,7 +511,7 @@ module.public = { vim.tbl_contains({ "/", "~" }, destination:sub(1, 1)) and "" or (vim.fn.expand("%:p:h") .. "/") ) .. destination - return neorg.lib.match(vim.fn.fnamemodify(destination, ":e"))({ + return lib.match(vim.fn.fnamemodify(destination, ":e"))({ [{ "jpg", "jpeg", "png", "pdf" }] = { type = "external_app", uri = vim.uri_from_fname(vim.fn.expand(destination)), @@ -539,7 +539,7 @@ module.public = { end, timestamp = function() - local tempus = neorg.modules.get_module("core.tempus") + local tempus = modules.get_module("core.tempus") if not tempus then log.error("`core.tempus` is not loaded! Unable to parse timestamp.") @@ -561,7 +561,7 @@ module.public = { end, _ = function() - local query_str = neorg.lib.match(parsed_link_information.link_type)({ + local query_str = lib.match(parsed_link_information.link_type)({ generic = [[ (_ [(strong_carryover_set @@ -603,7 +603,7 @@ module.public = { (multi_%s_prefix) title: (paragraph_segment) @title)]) ]], - neorg.lib.reparg(parsed_link_information.link_type, 5) + lib.reparg(parsed_link_information.link_type, 5) ), _ = string.format( [[ @@ -621,7 +621,7 @@ module.public = { (%s_prefix) title: (paragraph_segment) @title) ]], - neorg.lib.reparg(parsed_link_information.link_type, 2) + lib.reparg(parsed_link_information.link_type, 2) ), }) @@ -631,7 +631,7 @@ module.public = { return end - local query = neorg.utils.ts_parse_query("norg", query_str) + local query = utils.ts_parse_query("norg", query_str) for id, node in query:iter_captures(document_root, buf_pointer) do local capture = query.captures[id] @@ -744,7 +744,7 @@ module.private = { ---@param parsed_link_information table #A table as returned by `parse_link()` ---@return table #A table of similarities (fuzzed items) fix_link_strict = function(parsed_link_information) - local query = neorg.lib.match(parsed_link_information.link_type)({ + local query = lib.match(parsed_link_information.link_type)({ generic = [[ (_ [(strong_carryover_set @@ -785,7 +785,7 @@ module.private = { (multi_%s_prefix) title: (paragraph_segment) @title)]) ]], - neorg.lib.reparg(parsed_link_information.link_type, 5) + lib.reparg(parsed_link_information.link_type, 5) ), _ = string.format( [[ @@ -803,7 +803,7 @@ module.private = { (%s_prefix) title: (paragraph_segment) @title) ]], - neorg.lib.reparg(parsed_link_information.link_type, 2) + lib.reparg(parsed_link_information.link_type, 2) ), }) @@ -827,7 +827,7 @@ module.private = { end end - local query = neorg.utils.ts_parse_query("norg", query_str) + local query = utils.ts_parse_query("norg", query_str) local document_root = module.required["core.integrations.treesitter"].get_document_root(buffer) @@ -854,7 +854,7 @@ module.private = { end if vim.tbl_isempty(similarities) then - neorg.utils.notify("Sorry, Neorg couldn't fix that link :(", vim.log.levels.WARN) + utils.notify("Sorry, Neorg couldn't fix that link :(", vim.log.levels.WARN) end table.sort(similarities, function(lhs, rhs) @@ -878,10 +878,10 @@ module.private = { local range = module.required["core.integrations.treesitter"].get_node_range(link_node) - local prefix = neorg.lib.when( + local prefix = lib.when( parsed_link_information.link_type == "generic" and not force_type, "#", - neorg.lib.match(most_similar.node:type())({ + lib.match(most_similar.node:type())({ heading1 = "*", heading2 = "**", heading3 = "***", @@ -909,17 +909,17 @@ module.private = { callback( "{" - .. neorg.lib.when( + .. lib.when( parsed_link_information.link_file_text, - neorg.lib.lazy_string_concat(":", parsed_link_information.link_file_text, ":"), + lib.lazy_string_concat(":", parsed_link_information.link_file_text, ":"), "" ) .. prefix .. most_similar.text .. "}" - .. neorg.lib.when( + .. lib.when( parsed_link_information.link_description, - neorg.lib.lazy_string_concat("[", parsed_link_information.link_description, "]"), + lib.lazy_string_concat("[", parsed_link_information.link_description, "]"), "" ) ) diff --git a/lua/neorg/modules/core/esupports/indent/module.lua b/lua/neorg/modules/core/esupports/indent/module.lua index 6540cbe6f..1c3786107 100644 --- a/lua/neorg/modules/core/esupports/indent/module.lua +++ b/lua/neorg/modules/core/esupports/indent/module.lua @@ -15,7 +15,10 @@ Indent levels are also calculated as you type, but may not be entirely correct due to incomplete syntax trees (if you find any such examples, then file an issue!). --]] -local module = neorg.modules.create("core.esupports.indent") +local neorg = require("neorg.core") +local lib, modules = neorg.lib, neorg.modules + +local module = modules.create("core.esupports.indent") module.setup = function() return { @@ -307,12 +310,12 @@ module.on_event = function(event) vim.api.nvim_buf_set_option( event.buffer, "indentexpr", - ("v:lua.neorg.modules.get_module('core.esupports.indent').indentexpr(%d)"):format(event.buffer) + ("v:lua.modules.get_module('core.esupports.indent').indentexpr(%d)"):format(event.buffer) ) local indentkeys = "o,O,*,*" - .. neorg.lib.when(module.config.public.format_on_enter, ",*", "") - .. neorg.lib.when(module.config.public.format_on_escape, ",*", "") + .. lib.when(module.config.public.format_on_enter, ",*", "") + .. lib.when(module.config.public.format_on_escape, ",*", "") vim.api.nvim_buf_set_option(event.buffer, "indentkeys", indentkeys) end end diff --git a/lua/neorg/modules/core/esupports/metagen/module.lua b/lua/neorg/modules/core/esupports/metagen/module.lua index a0dc7900d..3363627c6 100644 --- a/lua/neorg/modules/core/esupports/metagen/module.lua +++ b/lua/neorg/modules/core/esupports/metagen/module.lua @@ -11,10 +11,10 @@ The metagen module exposes two commands - `:Neorg inject-metadata` and `:Neorg u was last edited) as well as a few other non-destructive fields. --]] -require("neorg.modules.base") -require("neorg.external.helpers") +local neorg = require("neorg.core") +local config, lib, modules, utils = neorg.config, neorg.lib, neorg.modules, neorg.utils -local module = neorg.modules.create("core.esupports.metagen") +local module = modules.create("core.esupports.metagen") module.setup = function() return { requires = { "core.autocommands", "core.keybinds", "core.integrations.treesitter" } } @@ -50,7 +50,7 @@ module.config.public = { -- The authors field is autopopulated by querying the current user's system username. { "authors", - function() return require("neorg.external.helpers").get_username() end, + function() return lib.get_username() end, }, -- The categories field is always kept empty for the user to fill in. @@ -73,7 +73,7 @@ module.config.public = { -- the file was created. { "version", - function() return require("neorg.config").norg_version end + function() return config.norg_version end }, }, } @@ -89,7 +89,7 @@ module.public = { ---@param buf number #The buffer to check in ---@return boolean,table #Whether the metadata was present, and the range of the metadata node is_metadata_present = function(buf) - local query = neorg.utils.ts_parse_query( + local query = utils.ts_parse_query( "norg", [[ (ranged_verbatim_tag @@ -221,7 +221,7 @@ module.public = { end end - local query = neorg.utils.ts_parse_query( + local query = utils.ts_parse_query( "norg_meta", [[ (pair @@ -255,7 +255,7 @@ module.public = { } module.load = function() - neorg.modules.await("core.neorgcmd", function(neorgcmd) + modules.await("core.neorgcmd", function(neorgcmd) neorgcmd.add_commands_from_table({ ["inject-metadata"] = { args = 0, diff --git a/lua/neorg/modules/core/export/markdown/module.lua b/lua/neorg/modules/core/export/markdown/module.lua index 9afc9582c..ecfdf528e 100644 --- a/lua/neorg/modules/core/export/markdown/module.lua +++ b/lua/neorg/modules/core/export/markdown/module.lua @@ -14,7 +14,10 @@ To learn more about configuration, consult the [relevant section](#configuration -- from another person's perspective. Some cleanup and rethinking of certain implementation -- details will be necessary. -local module = neorg.modules.create("core.export.markdown") +local neorg = require("neorg.core") +local lib, modules = neorg.lib, neorg.modules + +local module = modules.create("core.export.markdown") module.setup = function() return { @@ -115,7 +118,7 @@ module.load = function() } end - module.config.public.extensions = neorg.lib.to_keys(module.config.public.extensions) + module.config.public.extensions = lib.to_keys(module.config.public.extensions) end module.config.public = { diff --git a/lua/neorg/modules/core/export/module.lua b/lua/neorg/modules/core/export/module.lua index 3b0f0f40f..af575bf02 100644 --- a/lua/neorg/modules/core/export/module.lua +++ b/lua/neorg/modules/core/export/module.lua @@ -26,7 +26,9 @@ It takes 3 arguments: (see [configuration](#configuration)). --]] -local module = neorg.modules.create("core.export") +local neorg = require("neorg.core") +local lib, log, modules, utils = neorg.lib, neorg.log, neorg.modules, neorg.utils +local module = modules.create("core.export") module.setup = function() return { @@ -38,7 +40,7 @@ module.setup = function() end module.load = function() - neorg.modules.await("core.neorgcmd", function(neorgcmd) + modules.await("core.neorgcmd", function(neorgcmd) neorgcmd.add_commands_from_table({ export = { args = 1, @@ -72,14 +74,14 @@ module.public = { ---@param ftype string #The filetype to export to ---@return table?,table? #The export module and its configuration, else nil get_converter = function(ftype) - if not neorg.modules.is_module_loaded("core.export." .. ftype) then - if not neorg.modules.load_module("core.export." .. ftype) then + if not modules.is_module_loaded("core.export." .. ftype) then + if not modules.load_module("core.export." .. ftype) then return end end - return neorg.modules.get_module("core.export." .. ftype), - neorg.modules.get_module_config("core.export." .. ftype) + return modules.get_module("core.export." .. ftype), + modules.get_module_config("core.export." .. ftype) end, --- Takes a buffer and exports it to a specific file @@ -223,16 +225,16 @@ module.on_event = function(event) local exported = module.public.export(event.buffer, filetype) vim.loop.fs_open(filepath, "w", 438, function(err, fd) - assert(not err, neorg.lib.lazy_string_concat("Failed to open file '", filepath, "' for export: ", err)) + assert(not err, lib.lazy_string_concat("Failed to open file '", filepath, "' for export: ", err)) vim.loop.fs_write(fd, exported, 0, function(werr) assert( not werr, - neorg.lib.lazy_string_concat("Failed to write to file '", filepath, "' for export: ", werr) + lib.lazy_string_concat("Failed to write to file '", filepath, "' for export: ", werr) ) end) - vim.schedule(neorg.lib.wrap(neorg.utils.notify, "Successfully exported 1 file!")) + vim.schedule(lib.wrap(utils.notify, "Successfully exported 1 file!")) end) elseif event.type == "core.neorgcmd.events.export.directory" then local path = event.content[3] and vim.fn.expand(event.content[3]) @@ -247,7 +249,7 @@ module.on_event = function(event) local old_event_ignore = table.concat(vim.opt.eventignore:get(), ",") vim.loop.fs_scandir(event.content[1], function(err, handle) - assert(not err, neorg.lib.lazy_string_concat("Failed to scan directory '", event.content[1], "': ", err)) + assert(not err, lib.lazy_string_concat("Failed to scan directory '", event.content[1], "': ", err)) local file_counter, parsed_counter = 0, 0 @@ -266,8 +268,8 @@ module.on_event = function(event) if parsed_counter >= file_counter then vim.schedule( - neorg.lib.wrap( - neorg.utils.notify, + lib.wrap( + utils.notify, string.format("Successfully exported %d files!", file_counter) ) ) @@ -298,7 +300,7 @@ module.on_event = function(event) vim.loop.fs_open(write_path, "w+", 438, function(fs_err, fd) assert( not fs_err, - neorg.lib.lazy_string_concat( + lib.lazy_string_concat( "Failed to open file '", write_path, "' for export: ", @@ -309,7 +311,7 @@ module.on_event = function(event) vim.loop.fs_write(fd, exported, 0, function(werr) assert( not werr, - neorg.lib.lazy_string_concat( + lib.lazy_string_concat( "Failed to write to file '", write_path, "' for export: ", diff --git a/lua/neorg/modules/core/fs/module.lua b/lua/neorg/modules/core/fs/module.lua index d1f4082eb..2d3288f1a 100644 --- a/lua/neorg/modules/core/fs/module.lua +++ b/lua/neorg/modules/core/fs/module.lua @@ -8,7 +8,10 @@ operations safely on arbitrary filesystems. --]] -local module = neorg.modules.create("core.fs") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.fs") module.public = { directory_map = function(path, callback) diff --git a/lua/neorg/modules/core/highlights/module.lua b/lua/neorg/modules/core/highlights/module.lua index c82b98a0d..d72fedd9f 100644 --- a/lua/neorg/modules/core/highlights/module.lua +++ b/lua/neorg/modules/core/highlights/module.lua @@ -8,9 +8,10 @@ Neorg under a single tree of highlights: `@neorg.*`. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local lib, log, modules = neorg.lib, neorg.log, neorg.modules -local module = neorg.modules.create("core.highlights") +local module = modules.create("core.highlights") --[[ --]] @@ -475,7 +476,7 @@ module.public = { local is_link = highlight:sub(1, 1) == "+" local full_highlight_name = "@neorg" .. prefix .. (hl_name:len() > 0 and ("." .. hl_name) or "") - local does_hl_exist = neorg.lib.inline_pcall(vim.api.nvim_exec, "highlight " .. full_highlight_name, true) + local does_hl_exist = lib.inline_pcall(vim.api.nvim_exec, "highlight " .. full_highlight_name, true) -- If we are dealing with a link then link the highlights together (excluding the + symbol) if is_link then @@ -512,7 +513,7 @@ module.public = { end local full_highlight_name = "@neorg" .. prefix .. (hl_name:len() > 0 and ("." .. hl_name) or "") - local does_hl_exist = neorg.lib.inline_pcall(vim.api.nvim_exec, "highlight " .. full_highlight_name, true) + local does_hl_exist = lib.inline_pcall(vim.api.nvim_exec, "highlight " .. full_highlight_name, true) -- If the highlight already exists then assume the user doesn't want it to be -- overwritten diff --git a/lua/neorg/modules/core/integrations/nvim-cmp/module.lua b/lua/neorg/modules/core/integrations/nvim-cmp/module.lua index 6a058810f..2aa3ce63b 100644 --- a/lua/neorg/modules/core/integrations/nvim-cmp/module.lua +++ b/lua/neorg/modules/core/integrations/nvim-cmp/module.lua @@ -17,9 +17,10 @@ sources = { ``` --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules -local module = neorg.modules.create("core.integrations.nvim-cmp") +local module = modules.create("core.integrations.nvim-cmp") module.private = { source = {}, diff --git a/lua/neorg/modules/core/integrations/nvim-compe/module.lua b/lua/neorg/modules/core/integrations/nvim-compe/module.lua index 1f87e9fb9..304254c0d 100644 --- a/lua/neorg/modules/core/integrations/nvim-compe/module.lua +++ b/lua/neorg/modules/core/integrations/nvim-compe/module.lua @@ -11,9 +11,10 @@ A module for integrating nvim-compe with Neorg. Works with [`core.completion`](@core.completion) to provide intelligent completions. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules -local module = neorg.modules.create("core.integrations.nvim-compe") +local module = modules.create("core.integrations.nvim-compe") -- Define some private data that's not supposed to be seen module.private = { diff --git a/lua/neorg/modules/core/integrations/treesitter/module.lua b/lua/neorg/modules/core/integrations/treesitter/module.lua index 4644e3247..531409c1c 100644 --- a/lua/neorg/modules/core/integrations/treesitter/module.lua +++ b/lua/neorg/modules/core/integrations/treesitter/module.lua @@ -6,10 +6,11 @@ internal: true --- --]] -require("neorg.modules.base") -require("neorg.external.helpers") -local module = neorg.modules.create("core.integrations.treesitter") +local neorg = require("neorg.core") +local lib, log, modules, utils = neorg.lib, neorg.log, neorg.modules, neorg.utils + +local module = modules.create("core.integrations.treesitter") module.private = { ts_utils = nil, @@ -152,7 +153,7 @@ module.public = { if not document_root then return end - local next_match_query = neorg.utils.ts_parse_query("norg", query_string) + local next_match_query = utils.ts_parse_query("norg", query_string) for id, node in next_match_query:iter_captures(document_root, 0, line_number - 1, -1) do if next_match_query.captures[id] == "next-segment" then local start_line, start_col = node:range() @@ -185,7 +186,7 @@ module.public = { if not document_root then return end - local previous_match_query = neorg.utils.ts_parse_query("norg", query_string) + local previous_match_query = utils.ts_parse_query("norg", query_string) local final_node = nil for id, node in previous_match_query:iter_captures(document_root, 0, 0, line_number) do @@ -463,7 +464,7 @@ module.public = { } end - local rs, cs, re, ce = neorg.lib.when(type(node) == "table", function() + local rs, cs, re, ce = lib.when(type(node) == "table", function() local brs, bcs, _, _ = node[1]:range() local _, _, ere, ece = node[#node]:range() return brs, bcs, ere, ece @@ -585,7 +586,7 @@ module.public = { return end - local query = neorg.utils.ts_parse_query( + local query = utils.ts_parse_query( "norg_meta", [[ (metadata @@ -601,7 +602,7 @@ module.public = { end local function parse_data(node) - return neorg.lib.match(node:type())({ + return lib.match(node:type())({ string = function() return trim(module.public.get_node_text(node, buf)) end, @@ -670,7 +671,7 @@ module.public = { ---@param start number? #The start line for the query ---@param finish number? #The end line for the query execute_query = function(query_string, callback, buffer, start, finish) - local query = neorg.utils.ts_parse_query("norg", query_string) + local query = utils.ts_parse_query("norg", query_string) local root = module.public.get_document_root(buffer) if not root then @@ -743,7 +744,7 @@ module.on_event = function(event) local ok = pcall(install_norg_ts) if not ok then - neorg.utils.notify( + utils.notify( [[Unable to install norg parser. ]], vim.log.levels.WARN diff --git a/lua/neorg/modules/core/integrations/truezen/module.lua b/lua/neorg/modules/core/integrations/truezen/module.lua index 4f0d1fc1d..54703c0f9 100644 --- a/lua/neorg/modules/core/integrations/truezen/module.lua +++ b/lua/neorg/modules/core/integrations/truezen/module.lua @@ -7,9 +7,10 @@ This is a basic wrapper around truezen that allows one to toggle the atraxis mode programatically. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local modules = neorg.modules -local module = neorg.modules.create("core.integrations.truezen") +local module = modules.create("core.integrations.truezen") module.load = function() local success, truezen = pcall(require, "true-zen.main") diff --git a/lua/neorg/modules/core/integrations/zen_mode/module.lua b/lua/neorg/modules/core/integrations/zen_mode/module.lua index 01755f14e..54fb4793c 100644 --- a/lua/neorg/modules/core/integrations/zen_mode/module.lua +++ b/lua/neorg/modules/core/integrations/zen_mode/module.lua @@ -7,9 +7,10 @@ This is a basic wrapper around `zen_mode` that allows one to toggle the zen mode programatically. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local modules = neorg.modules -local module = neorg.modules.create("core.integrations.zen_mode") +local module = modules.create("core.integrations.zen_mode") module.load = function() local success, zen_mode = pcall(require, "zen_mode") diff --git a/lua/neorg/modules/core/itero/module.lua b/lua/neorg/modules/core/itero/module.lua index 6a8c67ff8..63c32c2c7 100644 --- a/lua/neorg/modules/core/itero/module.lua +++ b/lua/neorg/modules/core/itero/module.lua @@ -32,7 +32,10 @@ This functionality is commonly paired with the [`core.promo`](@core.promo) modul the item under the cursor with the `` and `` bindings. --]] -local module = neorg.modules.create("core.itero") +local neorg = require("neorg.core") +local lib, log, modules, utils = neorg.lib, neorg.log, neorg.modules, neorg.utils + +local module = modules.create("core.itero") module.setup = function() return { @@ -92,7 +95,7 @@ module.on_event = function(event) while current:parent() do if - neorg.lib.filter(module.config.public.iterables, function(_, iterable) + lib.filter(module.config.public.iterables, function(_, iterable) return current:type():match(table.concat({ "^", iterable, "$" })) and iterable or nil end) then @@ -103,14 +106,14 @@ module.on_event = function(event) end if not current or current:type() == "document" then - neorg.utils.notify( + utils.notify( "No object to continue! Make sure you're under an iterable item like a list or heading.", vim.log.levels.WARN ) return end - local should_append_extension = neorg.lib.filter( + local should_append_extension = lib.filter( module.config.public.retain_extensions, function(match, should_append) return current:type():match(match) and should_append or nil diff --git a/lua/neorg/modules/core/journal/module.lua b/lua/neorg/modules/core/journal/module.lua index 007ab671c..7a0e18012 100644 --- a/lua/neorg/modules/core/journal/module.lua +++ b/lua/neorg/modules/core/journal/module.lua @@ -19,10 +19,10 @@ file found in the root of the journal. This file contains links to all other jou their titles. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local config, lib, log, modules = neorg.config, neorg.lib, neorg.log, neorg.modules -local module = neorg.modules.create("core.journal") -local log = require("neorg.external.log") +local module = modules.create("core.journal") module.examples = { ["Changing TOC format to divide year in quarters"] = function() @@ -132,12 +132,12 @@ module.private = { local workspace_path = module.required["core.dirman"].get_workspace(workspace) local journal_file_exists = module.required["core.dirman"].file_exists( - workspace_path .. "/" .. folder_name .. neorg.configuration.pathsep .. path + workspace_path .. "/" .. folder_name .. config.pathsep .. path ) - module.required["core.dirman"].create_file(folder_name .. neorg.configuration.pathsep .. path, workspace) + module.required["core.dirman"].create_file(folder_name .. config.pathsep .. path, workspace) - module.required["core.dirman"].create_file(folder_name .. neorg.configuration.pathsep .. path, workspace) + module.required["core.dirman"].create_file(folder_name .. config.pathsep .. path, workspace) if not journal_file_exists @@ -170,7 +170,7 @@ module.private = { local template_name = module.config.public.template_name module.required["core.dirman"].create_file( - folder_name .. neorg.configuration.pathsep .. template_name, + folder_name .. config.pathsep .. template_name, workspace or module.required["core.dirman"].get_current_workspace()[1] ) end, @@ -178,12 +178,12 @@ module.private = { --- Opens the toc file open_toc = function() local workspace = module.config.public.workspace or module.required["core.dirman"].get_current_workspace()[1] - local index = neorg.modules.get_module_config("core.dirman").index + local index = modules.get_module_config("core.dirman").index local folder_name = module.config.public.journal_folder -- If the toc exists, open it, if not, create it - if module.required["core.dirman"].file_exists(folder_name .. neorg.configuration.pathsep .. index) then - module.required["core.dirman"].open_file(workspace, folder_name .. neorg.configuration.pathsep .. index) + if module.required["core.dirman"].file_exists(folder_name .. config.pathsep .. index) then + module.required["core.dirman"].open_file(workspace, folder_name .. config.pathsep .. index) else module.private.create_toc() end @@ -192,7 +192,7 @@ module.private = { --- Creates or updates the toc file create_toc = function() local workspace = module.config.public.workspace or module.required["core.dirman"].get_current_workspace()[1] - local index = neorg.modules.get_module_config("core.dirman").index + local index = modules.get_module_config("core.dirman").index local workspace_path = module.required["core.dirman"].get_workspace(workspace) local workspace_name_for_links = module.config.public.workspace or "" local folder_name = module.config.public.journal_folder @@ -205,11 +205,11 @@ module.private = { local get_fs_handle = function(path) path = path or "" local handle = vim.loop.fs_scandir( - workspace_path .. neorg.configuration.pathsep .. folder_name .. neorg.configuration.pathsep .. path + workspace_path .. config.pathsep .. folder_name .. config.pathsep .. path ) if type(handle) ~= "userdata" then - error(neorg.lib.lazy_string_concat("Failed to scan directory '", workspace, path, "': ", handle)) + error(lib.lazy_string_concat("Failed to scan directory '", workspace, path, "': ", handle)) end return handle @@ -217,17 +217,17 @@ module.private = { -- Gets the title from the metadata of a file, must be called in a vim.schedule local get_title = function(file) - local buffer = vim.fn.bufadd(workspace_path .. neorg.configuration.pathsep .. folder_name .. neorg.configuration.pathsep .. file) + local buffer = vim.fn.bufadd(workspace_path .. config.pathsep .. folder_name .. config.pathsep .. file) local meta = module.required["core.integrations.treesitter"].get_document_metadata(buffer) return meta.title end vim.loop.fs_scandir( - workspace_path .. neorg.configuration.pathsep .. folder_name .. neorg.configuration.pathsep, + workspace_path .. config.pathsep .. folder_name .. config.pathsep, function(err, handle) assert( not err, - neorg.lib.lazy_string_concat("Unable to generate TOC for directory '", folder_name, "' - ", err) + lib.lazy_string_concat("Unable to generate TOC for directory '", folder_name, "' - ", err) ) while true do @@ -250,7 +250,7 @@ module.private = { end if mtype == "directory" then - local months_handle = get_fs_handle(name .. neorg.configuration.pathsep .. mname) + local months_handle = get_fs_handle(name .. config.pathsep .. mname) while true do -- dname is the day local dname, dtype = vim.loop.fs_scandir_next(months_handle) @@ -268,9 +268,9 @@ module.private = { -- Get the title from the metadata, else, it just defaults to the name of the file local title = get_title( name - .. neorg.configuration.pathsep + .. config.pathsep .. mname - .. neorg.configuration.pathsep + .. config.pathsep .. dname ) or file[1] @@ -281,13 +281,13 @@ module.private = { tonumber(file[1]), "{:$" .. workspace_name_for_links - .. neorg.configuration.pathsep + .. config.pathsep .. module.config.public.journal_folder - .. neorg.configuration.pathsep + .. config.pathsep .. name - .. neorg.configuration.pathsep + .. config.pathsep .. mname - .. neorg.configuration.pathsep + .. config.pathsep .. file[1] .. ":}", title, @@ -324,9 +324,9 @@ module.private = { parts[3], "{:$" .. workspace_name_for_links - .. neorg.configuration.pathsep + .. config.pathsep .. module.config.public.journal_folder - .. neorg.configuration.pathsep + .. config.pathsep .. file[1] .. ":}", title, @@ -376,7 +376,7 @@ module.private = { end module.required["core.dirman"].create_file( - folder_name .. neorg.configuration.pathsep .. index, + folder_name .. config.pathsep .. index, workspace or module.required["core.dirman"].get_current_workspace()[1] ) @@ -422,7 +422,7 @@ module.config.public = { module.config.private = { strategies = { flat = "%Y-%m-%d.norg", - nested = "%Y" .. neorg.configuration.pathsep .. "%m" .. neorg.configuration.pathsep .. "%d.norg", + nested = "%Y" .. config.pathsep .. "%m" .. config.pathsep .. "%d.norg", }, } @@ -466,7 +466,7 @@ module.on_event = function(event) module.private.diary_yesterday() elseif event.split_type[2] == "journal.custom" then if not event.content[1] then - local calendar = neorg.modules.get_module("core.ui.calendar") + local calendar = modules.get_module("core.ui.calendar") if not calendar then log.error("[ERROR]: `core.ui.calendar` is not loaded! Said module is required for this operation.") diff --git a/lua/neorg/modules/core/keybinds/keybinds.lua b/lua/neorg/modules/core/keybinds/keybinds.lua index da2024be3..6297efea4 100644 --- a/lua/neorg/modules/core/keybinds/keybinds.lua +++ b/lua/neorg/modules/core/keybinds/keybinds.lua @@ -1,4 +1,7 @@ -local module = neorg.modules.create("core.keybinds.keybinds") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.keybinds.keybinds") ---@class core.keybinds module.config.public = { diff --git a/lua/neorg/modules/core/keybinds/module.lua b/lua/neorg/modules/core/keybinds/module.lua index e6662bde2..f7787cf93 100644 --- a/lua/neorg/modules/core/keybinds/module.lua +++ b/lua/neorg/modules/core/keybinds/module.lua @@ -56,12 +56,10 @@ to finely control what gets set and where: ``` --]] -require("neorg.modules.base") -require("neorg.modules") +local neorg = require("neorg.core") +local lib, log, modules = neorg.lib, neorg.log, neorg.modules -local module = neorg.modules.create("core.keybinds", { "keybinds" }) - -local log = require("neorg.external.log") +local module = modules.create("core.keybinds", { "keybinds" }) module.setup = function() return { @@ -82,7 +80,7 @@ module.load = function() end module.config.public = { - -- Whether to use the default keybinds provided [here](https://github.com/nvim-neorg/neorg/blob/main/lua/neorg/modules/core/keybinds/keybinds.lua). + -- Whether to use the default keybinds provided [here](https://github.com/nvim-neorg/neorg/blob/main/lua/modules/core/keybinds/keybinds.lua). default_keybinds = true, -- The prefix to use for all Neorg keybinds. @@ -133,7 +131,7 @@ module.public = { -- If that keybind is not defined yet then define it if not module.events.defined[keybind_name] then - module.events.defined[keybind_name] = neorg.events.define(module, keybind_name) + module.events.defined[keybind_name] = modules.define_event(module, keybind_name) -- Define autocompletion for core.neorgcmd table.insert(module.public.neorg_commands.keybind.complete[2], keybind_name) @@ -154,7 +152,7 @@ module.public = { -- If that keybind is not defined yet then define it if not module.events.defined[keybind_name] then - module.events.defined[keybind_name] = neorg.events.define(module, keybind_name) + module.events.defined[keybind_name] = modules.define_event(module, keybind_name) -- Define autocompletion for core.neorgcmd table.insert(module.public.neorg_commands.keybind.complete[2], keybind_name) @@ -367,8 +365,8 @@ module.public = { end -- Broadcast our event with the desired payload! - neorg.events.broadcast_event( - neorg.events.create(module, "core.keybinds.events.enable_keybinds", payload), + modules.broadcast_event( + modules.create_event(module, "core.keybinds.events.enable_keybinds", payload), function() for neorg_mode, neovim_modes in pairs(bound_keys) do if neorg_mode == "all" or neorg_mode == current_mode then @@ -427,7 +425,7 @@ module.private = { module.neorg_post_load = module.public.sync module.on_event = function(event) - neorg.lib.match(event.type)({ + lib.match(event.type)({ ["core.neorgcmd.events.core.keybinds.trigger"] = function() -- Query the current mode and the expected mode (the one passed in by the user) local expected_mode = event.content[1] @@ -443,8 +441,8 @@ module.on_event = function(event) -- If it is defined then broadcast the event if module.events.defined[keybind_event_path] then - neorg.events.broadcast_event( - neorg.events.create( + modules.broadcast_event( + modules.create_event( module, "core.keybinds.events." .. keybind_event_path, vim.list_slice(event.content, 3) @@ -477,7 +475,7 @@ module.on_event = function(event) end module.events.defined = { - enable_keybinds = neorg.events.define(module, "enable_keybinds"), + enable_keybinds = modules.define_event(module, "enable_keybinds"), } module.events.subscribed = { @@ -499,10 +497,7 @@ module.events.subscribed = { module.examples = { ["Create keybinds in your module"] = function() -- The process of defining a keybind is only a tiny bit more involved than defining e.g. an autocommand. Let's see what differs in creating a keybind rather than creating an autocommand: - - require("neorg.modules.base") - - local test = neorg.modules.create("test.module") + local test = modules.create("test.module") test.setup = function() return { success = true, requires = { "core.keybinds" } } -- Require the keybinds module @@ -520,7 +515,7 @@ module.examples = { -- The event.split_type field is the type field except split into two. -- The split point is .events., meaning if the event type is e.g. "core.keybinds.events.test.module.my_keybind" the value of split_type will be { "core.keybinds", "test.module.my_keybind" }. if event.split_type[2] == "test.module.my_keybind" then - require("neorg.external.log").info("Keybind my_keybind has been pressed!") + log.info("Keybind my_keybind has been pressed!") end end diff --git a/lua/neorg/modules/core/looking-glass/module.lua b/lua/neorg/modules/core/looking-glass/module.lua index f465db853..005b7d2d5 100644 --- a/lua/neorg/modules/core/looking-glass/module.lua +++ b/lua/neorg/modules/core/looking-glass/module.lua @@ -13,12 +13,14 @@ core.looking-glass.magnify-code-block` with your cursor underneath the code block you would like to magnify - it is not bound to any key as of currently, but you may map it yourself via the [`core.keybinds`](@core.keybinds) module. --]] -require("neorg.external.helpers") -local module = neorg.modules.create("core.looking-glass") +local neorg = require("neorg.core") +local log, modules, utils = neorg.log, neorg.modules, neorg.utils + +local module = modules.create("core.looking-glass") module.setup = function() - if not neorg.utils.is_minimum_version(0, 7, 0) then + if not utils.is_minimum_version(0, 7, 0) then log.error("The `looking-glass` module requires Neovim 0.7+! Please upgrade your Neovim installation.") return { success = false, @@ -180,7 +182,7 @@ module.public = { module.on_event = function(event) if event.split_type[2] == "core.looking-glass.magnify-code-block" then -- First we must check if the user has their cursor under a code block - local query = neorg.utils.ts_parse_query( + local query = utils.ts_parse_query( "norg", [[ (ranged_verbatim_tag @@ -204,7 +206,7 @@ module.on_event = function(event) local tag_info = module.required["core.integrations.treesitter"].get_tag_info(node) if not tag_info then - neorg.utils.notify("Unable to magnify current code block :(", vim.log.levels.WARN) + utils.notify("Unable to magnify current code block :(", vim.log.levels.WARN) return end @@ -215,7 +217,7 @@ module.on_event = function(event) -- If the query above failed then we know that the user isn't under a code block if not code_block_info then - neorg.utils.notify("No code block found under cursor!", vim.log.levels.WARN) + utils.notify("No code block found under cursor!", vim.log.levels.WARN) return end @@ -229,7 +231,7 @@ module.on_event = function(event) ) if not vsplit then - neorg.utils.notify( + utils.notify( "Unable to magnify current code block because our split didn't want to open :(", vim.log.levels.WARN ) diff --git a/lua/neorg/modules/core/manoeuvre/module.lua b/lua/neorg/modules/core/manoeuvre/module.lua index 4b8b6af97..614b36948 100644 --- a/lua/neorg/modules/core/manoeuvre/module.lua +++ b/lua/neorg/modules/core/manoeuvre/module.lua @@ -11,12 +11,13 @@ There is no available successor to this module yet. -- NOTE(vhyrro): This module is obsolete! There is no successor module to this yet, although -- we hope to implement one with the module rewrite of 0.2. -require("neorg.modules.base") +local neorg = require("neorg.core") +local lib, log, modules = neorg.lib, neorg.log, neorg.modules -local module = neorg.modules.create("core.manoeuvre") +local module = modules.create("core.manoeuvre") module.setup = function() - if not require("neorg.external.helpers").is_minimum_version(0, 7, 0) then + if not lib.is_minimum_version(0, 7, 0) then log.error("This module requires at least Neovim 0.7 to run!") return { diff --git a/lua/neorg/modules/core/mode/module.lua b/lua/neorg/modules/core/mode/module.lua index 3389dc6c0..686016ee5 100644 --- a/lua/neorg/modules/core/mode/module.lua +++ b/lua/neorg/modules/core/mode/module.lua @@ -21,12 +21,10 @@ If `core.neorgcmd` is loaded, `core.mode.public.add_mode()` also updates the aut which can be used by the user to switch modes. --]] -require("neorg.modules.base") -require("neorg.events") +local neorg = require("neorg.core") +local log, modules, utils = neorg.log, neorg.modules, neorg.utils -local module = neorg.modules.create("core.mode") - -local log = require("neorg.external.log") +local module = modules.create("core.mode") module.config.public = { -- Stores the current mode @@ -68,8 +66,8 @@ module.public = { table.insert(module.private.modes, mode_name) -- Broadcast the mode_created event - neorg.events.broadcast_event( - neorg.events.create( + modules.broadcast_event( + modules.create_event( module, "core.mode.events.mode_created", { current = module.config.public.current_mode, new = mode_name } @@ -80,7 +78,7 @@ module.public = { table.insert(module.public.neorg_commands["mode"].complete[1], mode_name) -- If core.neorgcmd is loaded then update all autocompletions - local neorgcmd = neorg.modules.get_module("core.neorgcmd") + local neorgcmd = modules.get_module("core.neorgcmd") if neorgcmd then neorgcmd.sync() @@ -106,8 +104,8 @@ module.public = { module.config.public.current_mode = mode_name -- Broadcast the mode_set event to all subscribed modules - neorg.events.broadcast_event( - neorg.events.create( + modules.broadcast_event( + modules.create_event( module, "core.mode.events.mode_set", { current = module.config.public.previous_mode, new = mode_name } @@ -142,7 +140,7 @@ module.on_event = function(event) if event.type == "core.neorgcmd.events.mode" then -- If no parameters were given then just print the current mode if not event.content[1] then - neorg.utils.notify("Active Mode: " .. module.public.get_mode()) + utils.notify("Active Mode: " .. module.public.get_mode()) else -- Else actually set the mode to the one we specified module.public.set_mode(event.content[1]) end @@ -150,8 +148,8 @@ module.on_event = function(event) end module.events.defined = { - mode_created = neorg.events.define(module, "mode_created"), -- Broadcast when a mode is created - mode_set = neorg.events.define(module, "mode_set"), -- Broadcast when a mode changes + mode_created = modules.define_event(module, "mode_created"), -- Broadcast when a mode is created + mode_set = modules.define_event(module, "mode_set"), -- Broadcast when a mode changes } module.events.subscribed = { diff --git a/lua/neorg/modules/core/neorgcmd/commands/module/list/module.lua b/lua/neorg/modules/core/neorgcmd/commands/module/list/module.lua index 6cde2410e..eaf6e5554 100644 --- a/lua/neorg/modules/core/neorgcmd/commands/module/list/module.lua +++ b/lua/neorg/modules/core/neorgcmd/commands/module/list/module.lua @@ -8,9 +8,10 @@ Upon execution (`:Neorg module list`) an info popup is created with a list of cu modules. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local modules = neorg.modules -local module = neorg.modules.create("core.neorgcmd.commands.module.list") +local module = modules.create("core.neorgcmd.commands.module.list") module.setup = function() return { success = true, requires = { "core.neorgcmd", "core.ui" } } @@ -34,13 +35,13 @@ module.public = { module.on_event = function(event) if event.type == "core.neorgcmd.events.module.list" then local lines = { - -- neorg.modules.get_module_config("core.concealer").icons.heading.level_1.icon + -- modules.get_module_config("core.concealer").icons.heading.level_1.icon "*" .. " " .. "Loaded Neorg Modules", } - for _, mod in pairs(neorg.modules.loaded_modules) do + for _, mod in pairs(modules.loaded_modules) do table.insert(lines, " - `" .. mod.name .. "`") end diff --git a/lua/neorg/modules/core/neorgcmd/commands/module/load/module.lua b/lua/neorg/modules/core/neorgcmd/commands/module/load/module.lua index 836a4ccbf..0a6e26b34 100644 --- a/lua/neorg/modules/core/neorgcmd/commands/module/load/module.lua +++ b/lua/neorg/modules/core/neorgcmd/commands/module/load/module.lua @@ -8,9 +8,10 @@ Upon exection (`:Neorg module load `) dynamically docks a new modul into the current Neorg environment. Useful to include modules as a one-off. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local modules = neorg.modules -local module = neorg.modules.create("core.neorgcmd.commands.module.load") +local module = modules.create("core.neorgcmd.commands.module.load") module.setup = function() return { success = true, requires = { "core.neorgcmd" } } @@ -34,7 +35,7 @@ module.public = { module.on_event = function(event) if event.type == "core.neorgcmd.events.module.load" then - neorg.modules.load_module(event.content[1]) + modules.load_module(event.content[1]) end end diff --git a/lua/neorg/modules/core/neorgcmd/commands/return/module.lua b/lua/neorg/modules/core/neorgcmd/commands/return/module.lua index 52c8d72ca..26c401fa5 100644 --- a/lua/neorg/modules/core/neorgcmd/commands/return/module.lua +++ b/lua/neorg/modules/core/neorgcmd/commands/return/module.lua @@ -8,10 +8,10 @@ When executed (`:Neorg return`), all currently open `.norg` files are deleted fr the buffer list, and the current workspace is set to "default". --]] -require("neorg.modules.base") -require("neorg.modules") +local neorg = require("neorg.core") +local modules = neorg.modules -local module = neorg.modules.create("core.neorgcmd.commands.return") +local module = modules.create("core.neorgcmd.commands.return") module.setup = function() return { success = true, requires = { "core.neorgcmd" } } diff --git a/lua/neorg/modules/core/neorgcmd/module.lua b/lua/neorg/modules/core/neorgcmd/module.lua index 0b2c0324b..24eb600f7 100644 --- a/lua/neorg/modules/core/neorgcmd/module.lua +++ b/lua/neorg/modules/core/neorgcmd/module.lua @@ -14,13 +14,10 @@ For a full example on how to create your own command, it is recommended to read which walks you through the necessary steps. --]] -require("neorg.modules.base") -require("neorg.modules") -require("neorg.events") +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules -local log = require("neorg.external.log") - -local module = neorg.modules.create("core.neorgcmd") +local module = modules.create("core.neorgcmd") module.examples = { ["Adding a Neorg command"] = function() @@ -138,7 +135,7 @@ module.public = { --- Recursively merges the contents of the module's config.public.funtions table with core.neorgcmd's module.config.public.neorg_commands table. ---@param module_name string #An absolute path to a loaded module with a module.config.public.neorg_commands table following a valid structure add_commands = function(module_name) - local module_config = neorg.modules.get_module(module_name) + local module_config = modules.get_module(module_name) if not module_config or not module_config.neorg_commands then return @@ -171,13 +168,13 @@ module.public = { end -- Load the module from table - neorg.modules.load_module_from_table(ret) + modules.load_module_from_table(ret) end, --- Rereads data from all modules and rebuild the list of available autocompletions and commands sync = function() -- Loop through every loaded module and set up all their commands - for _, mod in pairs(neorg.modules.loaded_modules) do + for _, mod in pairs(modules.loaded_modules) do if mod.public.neorg_commands then module.public.add_commands_from_table(mod.public.neorg_commands) end @@ -283,11 +280,11 @@ module.private = { end if not module.events.defined[ref.name] then - module.events.defined[ref.name] = neorg.events.define(module, ref.name) + module.events.defined[ref.name] = modules.define_event(module, ref.name) end - neorg.events.broadcast_event( - neorg.events.create( + modules.broadcast_event( + modules.create_event( module, table.concat({ "core.neorgcmd.events.", ref.name }), vim.list_slice(args, argument_index + 1) diff --git a/lua/neorg/modules/core/pivot/module.lua b/lua/neorg/modules/core/pivot/module.lua index 783008c24..b7bab70e1 100644 --- a/lua/neorg/modules/core/pivot/module.lua +++ b/lua/neorg/modules/core/pivot/module.lua @@ -17,7 +17,10 @@ This module exposes two keybinds: items will become unordered. --]] -local module = neorg.modules.create("core.pivot") +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules + +local module = modules.create("core.pivot") module.setup = function() return { @@ -28,7 +31,7 @@ module.setup = function() end module.load = function() - neorg.modules.await("core.keybinds", function(keybinds) + modules.await("core.keybinds", function(keybinds) keybinds.register_keybinds(module.name, { "toggle-list-type", "invert-list-type" }) end) end diff --git a/lua/neorg/modules/core/presenter/module.lua b/lua/neorg/modules/core/presenter/module.lua index e12d7a432..ec47b58e1 100644 --- a/lua/neorg/modules/core/presenter/module.lua +++ b/lua/neorg/modules/core/presenter/module.lua @@ -15,9 +15,10 @@ NOTE: This module is due for a rewrite. All of its behaviour is not fully docume overwritten soon anyway. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules -local module = neorg.modules.create("core.presenter") +local module = modules.create("core.presenter") local api = vim.api module.setup = function() @@ -42,9 +43,9 @@ module.load = function() local keybinds = module.required["core.keybinds"] if module.config.public.zen_mode == "truezen" then - neorg.modules.load_module("core.integrations.truezen") + modules.load_module("core.integrations.truezen") elseif module.config.public.zen_mode == "zen-mode" then - neorg.modules.load_module("core.integrations.zen_mode") + modules.load_module("core.integrations.zen_mode") else log.error("Unrecognized mode for 'zen_mode' option. Please check your presenter config") error_loading = true @@ -132,13 +133,13 @@ module.public = { end if - module.config.public.zen_mode == "truezen" and neorg.modules.is_module_loaded("core.integrations.truezen") + module.config.public.zen_mode == "truezen" and modules.is_module_loaded("core.integrations.truezen") then - neorg.modules.get_module("core.integrations.truezen").toggle_ataraxis() + modules.get_module("core.integrations.truezen").toggle_ataraxis() elseif - module.config.public.zen_mode == "zen-mode" and neorg.modules.is_module_loaded("core.integrations.zen_mode") + module.config.public.zen_mode == "zen-mode" and modules.is_module_loaded("core.integrations.zen_mode") then - neorg.modules.get_module("core.integrations.zen_mode").toggle() + modules.get_module("core.integrations.zen_mode").toggle() end -- Generate views selection popup @@ -207,13 +208,13 @@ module.public = { module.required["core.mode"].set_mode(previous_mode) if - module.config.public.zen_mode == "truezen" and neorg.modules.is_module_loaded("core.integrations.truezen") + module.config.public.zen_mode == "truezen" and modules.is_module_loaded("core.integrations.truezen") then - neorg.modules.get_module("core.integrations.truezen").toggle_ataraxis() + modules.get_module("core.integrations.truezen").toggle_ataraxis() elseif - module.config.public.zen_mode == "zen-mode" and neorg.modules.is_module_loaded("core.integrations.zen_mode") + module.config.public.zen_mode == "zen-mode" and modules.is_module_loaded("core.integrations.zen_mode") then - neorg.modules.get_module("core.integrations.zen_mode").toggle() + modules.get_module("core.integrations.zen_mode").toggle() end api.nvim_buf_delete(module.private.buf, {}) diff --git a/lua/neorg/modules/core/promo/module.lua b/lua/neorg/modules/core/promo/module.lua index efa96da76..3f45c9051 100644 --- a/lua/neorg/modules/core/promo/module.lua +++ b/lua/neorg/modules/core/promo/module.lua @@ -24,7 +24,10 @@ In insert mode, you are also provided with two keybinds, also being Neovim defau This module is commonly used with the [`core.itero`](@core.itero) module for an effective workflow. --]] -local module = neorg.modules.create("core.promo") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.promo") module.setup = function() return { @@ -283,7 +286,7 @@ module.public = { return end - local indent_module = neorg.modules.get_module("core.esupports.indent") + local indent_module = modules.get_module("core.esupports.indent") if not indent_module then return end @@ -318,10 +321,10 @@ module.on_event = function(event) module.public.promote_or_demote(event.buffer, "promote", start_pos[1] + i) end - if neorg.modules.loaded_modules["core.concealer"] then - neorg.events.broadcast_event( - neorg.events.create( - neorg.modules.loaded_modules["core.concealer"], + if modules.loaded_modules["core.concealer"] then + modules.broadcast_event( + modules.create_event( + modules.loaded_modules["core.concealer"], "core.concealer.events.update_region", { start = start_pos[1] - 1, ["end"] = end_pos[1] + 2 } ) @@ -335,10 +338,10 @@ module.on_event = function(event) module.public.promote_or_demote(event.buffer, "demote", start_pos[1] + i) end - if neorg.modules.loaded_modules["core.concealer"] then - neorg.events.broadcast_event( - neorg.events.create( - neorg.modules.loaded_modules["core.concealer"], + if modules.loaded_modules["core.concealer"] then + modules.broadcast_event( + modules.create_event( + modules.loaded_modules["core.concealer"], "core.concealer.events.update_region", { start = start_pos[1] - 1, ["end"] = end_pos[1] + 2 } ) diff --git a/lua/neorg/modules/core/qol/toc/module.lua b/lua/neorg/modules/core/qol/toc/module.lua index baf8a3e1d..3f7669083 100644 --- a/lua/neorg/modules/core/qol/toc/module.lua +++ b/lua/neorg/modules/core/qol/toc/module.lua @@ -17,7 +17,10 @@ When in the TOC view, `` can be pressed on any of the entries to move to tha Norg document. The TOC view updates automatically when switching buffers. --]] -local module = neorg.modules.create("core.qol.toc") +local neorg = require("neorg.core") +local modules, utils = neorg.modules, neorg.utils + +local module = modules.create("core.qol.toc") module.setup = function() return { @@ -26,7 +29,7 @@ module.setup = function() end module.load = function() - neorg.modules.await("core.neorgcmd", function(neorgcmd) + modules.await("core.neorgcmd", function(neorgcmd) neorgcmd.add_commands_from_table({ toc = { name = "core.qol.toc", @@ -235,7 +238,7 @@ module.on_event = function(event) local qflist = module.public.generate_qflist(event.buffer) if not qflist then - neorg.utils.notify("An error occurred and the qflist could not be generated", vim.log.levels.WARN) + utils.notify("An error occurred and the qflist could not be generated", vim.log.levels.WARN) return end diff --git a/lua/neorg/modules/core/qol/todo_items/module.lua b/lua/neorg/modules/core/qol/todo_items/module.lua index b96d16346..e06a13c68 100644 --- a/lua/neorg/modules/core/qol/todo_items/module.lua +++ b/lua/neorg/modules/core/qol/todo_items/module.lua @@ -22,9 +22,10 @@ any of the above keys to toggle the state of that particular item. Parent items of the same type and children items of the same type are update accordingly. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules -local module = neorg.modules.create("core.qol.todo_items") +local module = modules.create("core.qol.todo_items") module.setup = function() return { success = true, requires = { "core.keybinds", "core.integrations.treesitter" } } diff --git a/lua/neorg/modules/core/queries/native/module.lua b/lua/neorg/modules/core/queries/native/module.lua index 292b71c42..902ce1072 100644 --- a/lua/neorg/modules/core/queries/native/module.lua +++ b/lua/neorg/modules/core/queries/native/module.lua @@ -8,14 +8,15 @@ The `core.queries.native` module provides useful Treesitter wrappers to query information from Norg documents. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local lib, log, modules = neorg.lib, neorg.log, neorg.modules ---@class core.queries.native.tree_node ---@field query string[] ---@field subtree core.queries.native.tree_node[]|nil ---@field recursive boolean|nil -local module = neorg.modules.create("core.queries.native") +local module = modules.create("core.queries.native") module.setup = function() return { @@ -229,10 +230,10 @@ module.public = { local uri = vim.uri_from_bufnr(buf) local fname = vim.uri_to_fname(uri) - neorg.lib.when(vim.fn.bufloaded(buf) == 1, function() + lib.when(vim.fn.bufloaded(buf) == 1, function() vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines) - vim.api.nvim_buf_call(buf, neorg.lib.wrap(vim.cmd, "write!")) - end, neorg.lib.wrap(vim.fn.writefile, lines, fname)) + vim.api.nvim_buf_call(buf, lib.wrap(vim.cmd, "write!")) + end, lib.wrap(vim.fn.writefile, lines, fname)) -- We reset the state as false because we are consistent with the original file temp_buf.changed = false @@ -244,7 +245,7 @@ module.public = { --- @overload fun() ---@param buf number #The content relative to the provided buffer delete_content = function(buf) - neorg.lib.when(buf, function() + lib.when(buf, function() module.private.data.temp_bufs[buf] = nil end, function() module.private.data.temp_bufs = {} diff --git a/lua/neorg/modules/core/scanner/module.lua b/lua/neorg/modules/core/scanner/module.lua index ce4ea8c01..1db291900 100644 --- a/lua/neorg/modules/core/scanner/module.lua +++ b/lua/neorg/modules/core/scanner/module.lua @@ -8,9 +8,10 @@ This module is an implementation of a scanner that can be used anywhere TS can't It is not currently used anywhere, and is small enough to be self-documenting. --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local modules = neorg.modules -local module = neorg.modules.create("core.scanner") +local module = modules.create("core.scanner") ---@class core.scanner module.public = { diff --git a/lua/neorg/modules/core/storage/module.lua b/lua/neorg/modules/core/storage/module.lua index 809968fc7..f56fad573 100644 --- a/lua/neorg/modules/core/storage/module.lua +++ b/lua/neorg/modules/core/storage/module.lua @@ -6,9 +6,10 @@ --- --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local modules = neorg.modules -local module = neorg.modules.create("core.storage") +local module = modules.create("core.storage") module.setup = function() return { diff --git a/lua/neorg/modules/core/summary/module.lua b/lua/neorg/modules/core/summary/module.lua index 34fdfc885..62fbfbf9d 100644 --- a/lua/neorg/modules/core/summary/module.lua +++ b/lua/neorg/modules/core/summary/module.lua @@ -16,11 +16,10 @@ which by default consults the document metadata (see also as a fallback to build up a tree of categories, titles and descriptions. --]] -require("neorg.modules.base") -require("neorg.modules") -require("neorg.external.helpers") +local neorg = require("neorg.core") +local lib, modules, utils = neorg.lib, neorg.modules, neorg.utils -local module = neorg.modules.create("core.summary") +local module = modules.create("core.summary") module.setup = function() return { @@ -40,7 +39,7 @@ module.load = function() local ts = module.required["core.integrations.treesitter"] - module.config.public.strategy = neorg.lib.match(module.config.public.strategy)({ + module.config.public.strategy = lib.match(module.config.public.strategy)({ default = function() -- declare query on load so that it's parsed once, on first use local heading_query @@ -59,7 +58,7 @@ module.load = function() ) ] ]] - heading_query = neorg.utils.ts_parse_query("norg", heading_query_string) + heading_query = utils.ts_parse_query("norg", heading_query_string) end -- search up to 20 lines (a doc could potentially have metadata without metadata.title) local _, heading = heading_query:iter_captures(document_root, bufnr)() @@ -79,7 +78,7 @@ module.load = function() return function(files, ws_root, heading_level) local categories = vim.defaulttable() - neorg.utils.read_files(files, function(bufnr, filename) + utils.read_files(files, function(bufnr, filename) local metadata = ts.get_document_metadata(bufnr) if not metadata then @@ -108,7 +107,7 @@ module.load = function() if metadata.description == vim.NIL then metadata.description = nil end - table.insert(categories[neorg.lib.title(category)], { + table.insert(categories[lib.title(category)], { title = tostring(metadata.title), norgname = norgname, description = metadata.description, @@ -128,7 +127,7 @@ module.load = function() " - {:$", datapoint.norgname, ":}[", - neorg.lib.title(datapoint.title), + lib.title(datapoint.title), "]", }) .. (datapoint.description and (table.concat({ " - ", datapoint.description })) or "") @@ -171,7 +170,7 @@ module.on_event = function(event) local node_at_cursor = ts.get_first_node_on_line(buffer, event.cursor_position[1] - 1) if not node_at_cursor or not node_at_cursor:type():match("^heading%d$") then - neorg.utils.notify( + utils.notify( "No heading under cursor! Please move your cursor under the heading you'd like to generate the summary under." ) return @@ -179,10 +178,10 @@ module.on_event = function(event) -- heading level of 'node_at_cursor' (summary headings should be one level deeper) local level = tonumber(string.sub(node_at_cursor:type(), -1)) - local dirman = neorg.modules.get_module("core.dirman") + local dirman = modules.get_module("core.dirman") if not dirman then - neorg.utils.notify("`core.dirman` is not loaded! It is required to generate summaries") + utils.notify("`core.dirman` is not loaded! It is required to generate summaries") return end @@ -194,7 +193,7 @@ module.on_event = function(event) ) if not generated or vim.tbl_isempty(generated) then - neorg.utils.notify( + utils.notify( "No summary to generate! Either change the `strategy` option or ensure you have some indexable files in your workspace." ) return diff --git a/lua/neorg/modules/core/syntax/module.lua b/lua/neorg/modules/core/syntax/module.lua index 32bedd998..ccf60270d 100644 --- a/lua/neorg/modules/core/syntax/module.lua +++ b/lua/neorg/modules/core/syntax/module.lua @@ -18,10 +18,10 @@ If one needs to edit this module, it is best to talk to me at `katawful` on GitH Any edit is assumed to break this module. --]] -require("neorg.modules.base") -require("neorg.external.helpers") +local neorg = require("neorg.core") +local lib, modules, utils = neorg.lib, neorg.modules, neorg.utils -local module = neorg.modules.create("core.syntax") +local module = modules.create("core.syntax") local function schedule(func) vim.schedule(function() @@ -116,7 +116,7 @@ module.public = { if tree then -- get the language node used by the code block - local code_lang = neorg.utils.ts_parse_query( + local code_lang = utils.ts_parse_query( "norg", [[( (ranged_verbatim_tag (tag_name) @_tagname (tag_parameters) @language) @@ -487,7 +487,7 @@ module.load = function() -- Load available regex languages -- get the available regex files for the current session - module.private.available_languages = require("neorg.external.helpers").get_language_list(false) + module.private.available_languages = lib.get_language_list(false) end module.on_event = function(event) diff --git a/lua/neorg/modules/core/tangle/module.lua b/lua/neorg/modules/core/tangle/module.lua index 8f6f0b365..f94f43268 100644 --- a/lua/neorg/modules/core/tangle/module.lua +++ b/lua/neorg/modules/core/tangle/module.lua @@ -147,9 +147,10 @@ print("Ayo") The first code block will be tangled to `./output.lua`, the second code block will also be tangled to `./output.lua` and the third code block will be ignored. --]] -require("neorg.external.helpers") +local neorg = require("neorg.core") +local lib, modules, utils = neorg.lib, neorg.modules, neorg.utils -local module = neorg.modules.create("core.tangle") +local module = modules.create("core.tangle") module.setup = function() return { @@ -216,7 +217,7 @@ module.public = { -- filename = { content } } - local query_str = neorg.lib.match(options.scope)({ + local query_str = lib.match(options.scope)({ _ = [[ (ranged_verbatim_tag name: (tag_name) @_name @@ -243,7 +244,7 @@ module.public = { ]], }) - local query = neorg.utils.ts_parse_query("norg", query_str) + local query = utils.ts_parse_query("norg", query_str) for id, node in query:iter_captures(document_root, buffer, 0, -1) do local capture = query.captures[id] @@ -294,7 +295,7 @@ module.on_event = function(event) local tangles = module.public.tangle(event.buffer) if not tangles or vim.tbl_isempty(tangles) then - neorg.utils.notify("Nothing to tangle!", vim.log.levels.WARN) + utils.notify("Nothing to tangle!", vim.log.levels.WARN) return end @@ -304,20 +305,20 @@ module.on_event = function(event) for file, content in pairs(tangles) do vim.loop.fs_open(vim.fn.expand(file), "w", 438, function(err, fd) file_count = file_count - 1 - assert(not err, neorg.lib.lazy_string_concat("Failed to open file '", file, "' for tangling: ", err)) + assert(not err, lib.lazy_string_concat("Failed to open file '", file, "' for tangling: ", err)) vim.loop.fs_write(fd, table.concat(content, "\n"), 0, function(werr) assert( not werr, - neorg.lib.lazy_string_concat("Failed to write to file '", file, "' for tangling: ", werr) + lib.lazy_string_concat("Failed to write to file '", file, "' for tangling: ", werr) ) end) tangled_count = tangled_count + 1 if file_count == 0 then vim.schedule( - neorg.lib.wrap( - neorg.utils.notify, + lib.wrap( + utils.notify, string.format( "Successfully tangled %d file%s!", tangled_count, diff --git a/lua/neorg/modules/core/tempus/module.lua b/lua/neorg/modules/core/tempus/module.lua index 9df966241..15f94b0b4 100644 --- a/lua/neorg/modules/core/tempus/module.lua +++ b/lua/neorg/modules/core/tempus/module.lua @@ -9,7 +9,10 @@ to handle complex dates. It exposes two functions: `parse_date(string) -> date|s and `to_lua_date(date) -> osdate`. --]] -local module = neorg.modules.create("core.tempus") +local neorg = require("neorg.core") +local lib, log, modules, utils = neorg.lib, neorg.log, neorg.modules, neorg.utils + +local module = modules.create("core.tempus") -- NOTE: Maybe encapsulate whole date parser in a single PEG grammar? local _, time_regex = pcall(vim.re.compile, [[{%d%d?} ":" {%d%d} ("." {%d%d?})?]]) @@ -211,7 +214,7 @@ local timezone_list = { } module.setup = function() - if not neorg.utils.is_minimum_version(0, 10, 0) then + if not utils.is_minimum_version(0, 10, 0) then log.error("`core.tempus` requires at least Neovim version 0.10.0 to run!") return { success = false, @@ -235,7 +238,7 @@ module.public = { hour = parsed_date.time and parsed_date.time.hour, min = parsed_date.time and parsed_date.time.minute, sec = parsed_date.time and parsed_date.time.second, - wday = parsed_date.weekday and neorg.lib.number_wrap(parsed_date.weekday.number + 1, 1, 7), + wday = parsed_date.weekday and lib.number_wrap(parsed_date.weekday.number + 1, 1, 7), }) end, @@ -257,17 +260,17 @@ module.public = { -- os.date("*t") returns wday with Sunday as 1, needs to be -- converted to Monday as 1 - local converted_weekday = neorg.lib.number_wrap(osdate.wday - 1, 1, 7) + local converted_weekday = lib.number_wrap(osdate.wday - 1, 1, 7) return module.private.tostringable_date({ weekday = osdate.wday and { number = converted_weekday, - name = neorg.lib.title(weekdays[converted_weekday]), + name = lib.title(weekdays[converted_weekday]), } or nil, day = osdate.day, month = osdate.month and { number = osdate.month, - name = neorg.lib.title(months[osdate.month]), + name = lib.title(months[osdate.month]), } or nil, year = osdate.year, time = osdate.hour and setmetatable({ @@ -353,7 +356,7 @@ module.public = { local valid_month_name, valid_month_number = next(valid_months) output.month = { - name = neorg.lib.title(valid_month_name), + name = lib.title(valid_month_name), number = valid_month_number, } @@ -381,7 +384,7 @@ module.public = { local valid_weekday_name, valid_weekday_number = next(valid_weekdays) output.weekday = { - name = neorg.lib.title(valid_weekday_name), + name = lib.title(valid_weekday_name), number = valid_weekday_number, } @@ -423,7 +426,7 @@ module.private = { } module.load = function() - neorg.modules.await("core.keybinds", function(keybinds) + modules.await("core.keybinds", function(keybinds) keybinds.register_keybinds(module.name, { "insert-date", "insert-date-insert-mode" }) end) end @@ -449,7 +452,7 @@ module.on_event = function(event) output = module.public.parse_date(input) if type(output) == "string" then - neorg.utils.notify(output, vim.log.levels.ERROR) + utils.notify(output, vim.log.levels.ERROR) vim.ui.input({ prompt = "Date: ", @@ -469,9 +472,9 @@ module.on_event = function(event) end end - if neorg.modules.is_module_loaded("core.ui.calendar") then + if modules.is_module_loaded("core.ui.calendar") then vim.cmd.stopinsert() - neorg.modules.get_module("core.ui.calendar").select_date({ callback = vim.schedule_wrap(callback) }) + modules.get_module("core.ui.calendar").select_date({ callback = vim.schedule_wrap(callback) }) else vim.ui.input({ prompt = "Date: ", diff --git a/lua/neorg/modules/core/ui/calendar/module.lua b/lua/neorg/modules/core/ui/calendar/module.lua index 9ebd0df36..5932de1fb 100644 --- a/lua/neorg/modules/core/ui/calendar/module.lua +++ b/lua/neorg/modules/core/ui/calendar/module.lua @@ -10,7 +10,10 @@ also be launched in standalone mode, select date range mode and others. To view keybinds and help, press `?` in the calendar view. --]] -local module = neorg.modules.create("core.ui.calendar") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.ui.calendar") module.setup = function() return { diff --git a/lua/neorg/modules/core/ui/calendar/views/monthly.lua b/lua/neorg/modules/core/ui/calendar/views/monthly.lua index b9cfde886..00e8454fb 100644 --- a/lua/neorg/modules/core/ui/calendar/views/monthly.lua +++ b/lua/neorg/modules/core/ui/calendar/views/monthly.lua @@ -1,4 +1,7 @@ -local module = neorg.modules.create("core.ui.calendar.views.monthly") +local neorg = require("neorg.core") +local lib, log, modules = neorg.lib, neorg.log, neorg.modules + +local module = modules.create("core.ui.calendar.views.monthly") local function reformat_time(date) return os.date("*t", os.time(date)) @@ -749,7 +752,7 @@ module.public = { vim.keymap.set( "n", "?", - neorg.lib.wrap(module.private.display_help, { + lib.wrap(module.private.display_help, { { { "", "@namespace" }, { " - " }, @@ -857,7 +860,7 @@ module.public = { vim.keymap.set( "n", "?", - neorg.lib.wrap(module.private.display_help, { + lib.wrap(module.private.display_help, { { { "", "@namespace" }, { " - " }, diff --git a/lua/neorg/modules/core/ui/module.lua b/lua/neorg/modules/core/ui/module.lua index 1959e0dcd..2a95c9191 100644 --- a/lua/neorg/modules/core/ui/module.lua +++ b/lua/neorg/modules/core/ui/module.lua @@ -6,9 +6,10 @@ --- --]] -require("neorg.modules.base") +local neorg = require("neorg.core") +local log, modules = neorg.log, neorg.modules -local module = neorg.modules.create("core.ui", { +local module = modules.create("core.ui", { "selection_popup", "text_popup", }) diff --git a/lua/neorg/modules/core/ui/selection_popup.lua b/lua/neorg/modules/core/ui/selection_popup.lua index d5b28089e..f02372e18 100644 --- a/lua/neorg/modules/core/ui/selection_popup.lua +++ b/lua/neorg/modules/core/ui/selection_popup.lua @@ -1,7 +1,11 @@ --[[ A UI module to allow the user to press different keys to select different actions --]] -local module = neorg.modules.create("core.ui.selection_popup") + +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.ui.selection_popup") module.private = { -- Stores all currently open selection popups @@ -141,7 +145,7 @@ module.public = { for _, key in ipairs(keys) do -- TODO: Docs local callback = function() - neorg.modules + modules .get_module(module.name) .invoke_key_in_selection(name, ({ key:gsub("<(.+)>", "|%1|") })[1], type) end @@ -177,7 +181,7 @@ module.public = { for _, key in pairs(keys) do -- TODO: Docs local callback = function() - neorg.modules + modules .get_module(module.name) .invoke_key_in_selection(name, ({ key:gsub("<(.+)>", "|%1|") })[1], type) end diff --git a/lua/neorg/modules/core/ui/text_popup.lua b/lua/neorg/modules/core/ui/text_popup.lua index cd3646ad5..eda37acd4 100644 --- a/lua/neorg/modules/core/ui/text_popup.lua +++ b/lua/neorg/modules/core/ui/text_popup.lua @@ -2,7 +2,10 @@ File for creating text popups for the user. --]] -local module = neorg.modules.create("core.ui.text_popup") +local neorg = require("neorg.core") +local modules = neorg.modules + +local module = modules.create("core.ui.text_popup") ---@class core.ui module.public = { @@ -21,7 +24,7 @@ module.public = { } -- Apply any custom modifiers that the user has specified - window_config = assert(neorg.modules.get_module("core.ui"), "core.ui is not loaded!").apply_custom_options( + window_config = assert(modules.get_module("core.ui"), "core.ui is not loaded!").apply_custom_options( modifiers, vim.tbl_extend("force", window_config, config or {}) ) diff --git a/lua/neorg/modules/core/upgrade/module.lua b/lua/neorg/modules/core/upgrade/module.lua index d31463f2e..e9d41ef44 100644 --- a/lua/neorg/modules/core/upgrade/module.lua +++ b/lua/neorg/modules/core/upgrade/module.lua @@ -18,7 +18,10 @@ When a backup is requested, Neorg backs up the file to `.old.norg`, th the original file/directory in-place. --]] -local module = neorg.modules.create("core.upgrade") +local neorg = require("neorg.core") +local lib, log, modules, utils = neorg.lib, neorg.log, neorg.modules, neorg.utils + +local module = modules.create("core.upgrade") module.setup = function() return { @@ -39,7 +42,7 @@ module.config.public = { } module.load = function() - neorg.modules.await("core.neorgcmd", function(neorgcmd) + modules.await("core.neorgcmd", function(neorgcmd) neorgcmd.add_commands_from_table({ upgrade = { subcommands = { @@ -91,7 +94,7 @@ module.public = { line = start_row end - local output = neorg.lib.match(node:type())({ + local output = lib.match(node:type())({ [{ "_open", "_close" }] = function() if node:parent():type() == "spoiler" then return { text = "!", stop = true } @@ -221,7 +224,7 @@ module.on_event = function(event) if module.config.public.ask_for_backup then local halt = false - neorg.utils.notify( + utils.notify( "Upgraders tend to be rock solid, but it's always good to be safe.\nDo you want to back up this file?" ) vim.ui.select({ ("Create backup (%s.old)"):format(path), "Don't create backup" }, { @@ -243,21 +246,21 @@ module.on_event = function(event) end end - neorg.utils.notify("Begin upgrade...") + utils.notify("Begin upgrade...") local output = table.concat(module.public.upgrade(event.buffer)) vim.loop.fs_open(path, "w", 438, function(err, fd) - assert(not err, neorg.lib.lazy_string_concat("Failed to open file '", path, "' for upgrade: ", err)) + assert(not err, lib.lazy_string_concat("Failed to open file '", path, "' for upgrade: ", err)) vim.loop.fs_write(fd, output, 0, function(werr) assert( not werr, - neorg.lib.lazy_string_concat("Failed to write to file '", path, "' for upgrade: ", werr) + lib.lazy_string_concat("Failed to write to file '", path, "' for upgrade: ", werr) ) end) - vim.schedule(neorg.lib.wrap(neorg.utils.notify, "Successfully upgraded 1 file!")) + vim.schedule(lib.wrap(utils.notify, "Successfully upgraded 1 file!")) end) end) elseif event.split_type[2] == "core.upgrade.current-directory" then @@ -267,7 +270,7 @@ module.on_event = function(event) do local halt = false - neorg.utils.notify( + utils.notify( ("Your current working directory is %s. This is the root that will be recursively searched for norg files.\nIs this the right directory?\nIf not, change the current working directory with `:cd` or `:lcd` and run this command again!"):format( path ) @@ -286,7 +289,7 @@ module.on_event = function(event) if module.config.public.ask_for_backup then local halt = false - neorg.utils.notify( + utils.notify( "\nUpgraders tend to be rock solid, but it's always good to be safe.\nDo you want to back up this directory?" ) vim.ui.select({ ("Create backup (%s.old)"):format(path), "Don't create backup" }, { @@ -331,8 +334,8 @@ module.on_event = function(event) if parsed_counter >= file_counter then vim.schedule( - neorg.lib.wrap( - neorg.utils.notify, + lib.wrap( + utils.notify, string.format("Successfully upgraded %d files!", file_counter) ) ) @@ -363,13 +366,13 @@ module.on_event = function(event) vim.loop.fs_open(filepath, "w+", 438, function(fs_err, fd) assert( not fs_err, - neorg.lib.lazy_string_concat("Failed to open file '", filepath, "' for upgrade: ", fs_err) + lib.lazy_string_concat("Failed to open file '", filepath, "' for upgrade: ", fs_err) ) vim.loop.fs_write(fd, output, 0, function(werr) assert( not werr, - neorg.lib.lazy_string_concat( + lib.lazy_string_concat( "Failed to write to file '", filepath, "' for upgrade: ", @@ -384,14 +387,14 @@ module.on_event = function(event) end) end) elseif event.split_type[2] == "core.upgrade.all-workspaces" then - local dirman = neorg.modules.get_module("core.dirman") + local dirman = modules.get_module("core.dirman") if not dirman then - neorg.utils.notify("ERROR: `core.dirman` is not loaded!", vim.log.levels.WARN) + utils.notify("ERROR: `core.dirman` is not loaded!", vim.log.levels.WARN) return end - neorg.utils.notify("This behaviour isn't implemented yet!", vim.log.levels.WARN) + utils.notify("This behaviour isn't implemented yet!", vim.log.levels.WARN) end end