diff --git a/lua/care/sources/path.lua b/lua/care/sources/path.lua new file mode 100644 index 0000000..4514ebb --- /dev/null +++ b/lua/care/sources/path.lua @@ -0,0 +1,173 @@ +-- parts of the code adapted from https://github.com/hrsh7th/cmp-path + +local NAME_REGEX = "\\%([^/\\\\:\\*?<>'\"`\\|]\\)" +local PATH_REGEX = + vim.regex(([[\%(\%(/PAT*[^/\\\\:\\*?<>\'"`\\| .~]\)\|\%(/\.\.\)\)*/\zePAT*$]]):gsub("PAT", NAME_REGEX)) + +local path_source = {} + +function path_source.setup() + require("care.sources").register_source(path_source.new()) +end + +local function has_slash_comment() + local commentstring = vim.bo.commentstring or "" + local no_filetype = vim.bo.filetype == "" + local is_slash_comment = false + is_slash_comment = is_slash_comment or commentstring:match("/%*") + is_slash_comment = is_slash_comment or commentstring:match("//") + return is_slash_comment and not no_filetype +end + +local function get_dirname(line_before_cursor, bufnr) + local s = PATH_REGEX:match_str(line_before_cursor) + if not s then + return nil + end + + local dirname = string.gsub(string.sub(line_before_cursor, s + 2), "%a*$", "") -- exclude '/' + local prefix = string.sub(line_before_cursor, 1, s + 1) -- include '/' + + local buf_dirname = vim.fn.expand(("#%d:p:h"):format(bufnr)) + if vim.api.nvim_get_mode().mode == "c" then + buf_dirname = vim.fn.getcwd() + end + if prefix:match("%.%./$") then + return vim.fn.resolve(buf_dirname .. "/../" .. dirname) + end + if prefix:match("%./$") or prefix:match('"$') or prefix:match("'$") then + return vim.fn.resolve(buf_dirname .. "/" .. dirname) + end + if prefix:match("~/$") then + return vim.fn.resolve(vim.fn.expand("~") .. "/" .. dirname) + end + local env_var_name = prefix:match("%$([%a_]+)/$") + if env_var_name then + local env_var_value = vim.fn.getenv(env_var_name) + if env_var_value ~= vim.NIL then + return vim.fn.resolve(env_var_value .. "/" .. dirname) + end + end + if prefix:match("/$") then + local accept = true + -- Ignore URL components + accept = accept and not prefix:match("%a/$") + -- Ignore URL scheme + accept = accept and not prefix:match("%a+:/$") and not prefix:match("%a+://$") + -- Ignore HTML closing tags + accept = accept and not prefix:match("