diff --git a/suggest-require.lua b/suggest-require.lua index 78c9b41..15ecb10 100644 --- a/suggest-require.lua +++ b/suggest-require.lua @@ -2,7 +2,7 @@ -- This is a tiny library to discover which modules can be imported using -- `require`. It's intended to be included in an auto-complete system for Lua. --- Not sure if it works on a system without GNU find :/ +-- Not sure if it works on a system without GNU find --- -- Constants @@ -84,6 +84,13 @@ local function get_loaded_module_names () return l end +local function get_preloaded_module_names () + -- Get the names of preloaded modules. + local l = {} + for k in pairs(package.loaded) do l[#l+1] = k end + return l +end + local function get_module_names_from_path () local paths = get_module_paths(package.path) @@ -106,20 +113,28 @@ local function get_c_module_names_from_path () return modules end +local PACKAGE_SEARCH_METHODS = { + get_loaded_module_names, + get_preloaded_module_names, + get_module_names_from_path, + get_c_module_names_from_path, +} + local function get_available_module_names () + + -- Searches through the package system to determine which modules can be + -- imported by using `require`. Returns a sequence of strings, each of which + -- can be directly used by `require` to import the module. + assert(type(package) == 'table') - local names_loaded = get_loaded_module_names() - local names_path = get_module_names_from_path() - local names_cpath = get_c_module_names_from_path() - - -- - - -- Dedub and Sort + -- Find and Dedub local dedub = {} - for i = 1, #names_loaded do dedub[names_loaded[i]] = true end - for i = 1, #names_path do dedub[names_path[i]] = true end - for i = 1, #names_cpath do dedub[names_cpath[i]] = true end + for _, method in ipairs(PACKAGE_SEARCH_METHODS) do + for _, name in ipairs(method()) do dedub[name] = true end + end + + -- Sort local module_names = {} for name in pairs(dedub) do module_names[#module_names+1] = name end table.sort(module_names)