Skip to content

Commit

Permalink
Merge pull request #76 from jghauser/small-refactors
Browse files Browse the repository at this point in the history
refactor: various small refactors
  • Loading branch information
jghauser authored Jun 18, 2024
2 parents cd37ad4 + 08237dc commit 3014915
Show file tree
Hide file tree
Showing 11 changed files with 124 additions and 99 deletions.
8 changes: 4 additions & 4 deletions lua/papis/completion/data.lua
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ local function make_completion_items()
local completion_items = {}
local tags = get_all_tags()
for _, tag in ipairs(tags) do
table.insert(completion_items, {
word = tag, -- what is inserted?
label = tag, -- what is visible in the completion popup
})
completion_items[#completion_items + 1] = {
word = tag,
label = tag,
}
end
return completion_items
end
Expand Down
36 changes: 19 additions & 17 deletions lua/papis/completion/source.lua
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,32 @@ if not db then
end
local tag_delimiter

-- Mapping table for tag delimiters
local tag_delimiters = {
tbl = "- ",
[","] = ", ",
[";"] = "; ",
[" "] = " ",
}

---Gets tag_delimiter for the tag_format
---@return string|nil #The delimiter between tags given the format
local function get_tag_delimiter()
local tag_format = db.state:get_value({ id = 1 }, "tag_format")
if tag_format == "tbl" then
tag_delimiter = "- "
elseif tag_format == "," then
tag_delimiter = ", "
elseif tag_format == ";" then
tag_delimiter = "; "
elseif tag_format == " " then
tag_delimiter = tag_format
end
-- Use the mapping table to get the tag_delimiter
tag_delimiter = tag_delimiters[tag_format]
return tag_delimiter
end

local parse_query = ts.query.parse(
"yaml",
[[
(block_mapping_pair
key: (flow_node) @name (#eq? @name "tags")
) @capture
]]
)

local M = {}

---Creates a new cmp source
Expand Down Expand Up @@ -64,14 +74,6 @@ function M:is_available()
local parser = ts.get_parser(0, "yaml")
local root = parser:parse()[1]:root()
local start_row, _, _, end_row, _, _ = unpack(ts.get_range(root))
local parse_query = ts.query.parse(
"yaml",
[[
(block_mapping_pair
key: (flow_node) @name (#eq? @name "tags")
) @capture
]]
)
local cur_row, _ = unpack(api.nvim_win_get_cursor(0))
-- check all captured nodes
for id, node, _ in parse_query:iter_captures(root, 0, start_row, end_row) do
Expand Down
26 changes: 15 additions & 11 deletions lua/papis/formatter/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,24 @@ local log = require("papis.log")
local create_autocmd = vim.api.nvim_create_autocmd
local create_augroup = vim.api.nvim_create_augroup

local augroup = create_augroup("papisFormatter", { clear = true })
local autocmd = {
pattern = nil,
callback = nil,
group = augroup,
once = true,
desc = "Papis: format a newly created note",
}

local M = {}

function M.create_autocmd(pattern, callback, entry)
local papisFormatter = create_augroup("papisFormatter", { clear = true })
create_autocmd("BufEnter", {
pattern = pattern,
callback = function()
log.debug("Running formatter callback...")
callback(entry)
end,
group = papisFormatter,
once = true,
desc = "Papis: format a newly created note",
})
autocmd.pattern = pattern
autocmd.callback = function()
log.debug("Running formatter callback...")
callback(entry)
end
create_autocmd("BufEnter", autocmd)
end

return M
35 changes: 21 additions & 14 deletions lua/papis/fs-watcher.lua
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,11 @@ local fs_watching_stopped = false
---@param on_error function #Function to run on error
local function do_watch(path, on_event, on_error)
local handle = uv.new_fs_event()
if not handle then
return
end
local unwatch_cb = function()
uv.fs_event_stop(handle)
handle:stop()
end
local event_cb = function(err, filename)
if err then
Expand All @@ -44,8 +47,8 @@ local function do_watch(path, on_event, on_error)
on_event(filename, unwatch_cb)
end
end
uv.fs_event_start(handle, tostring(path), {}, event_cb)
table.insert(handles, handle)
handle:start(tostring(path), {}, event_cb)
handles[#handles + 1] = handle
end

---Gets all directories in the library_dir
Expand All @@ -54,7 +57,7 @@ local function get_library_dirs()
local library_dir = Path(db.config:get_value({ id = 1 }, "dir"))
local library_dirs = {}
for path in library_dir:fs_iterdir() do
table.insert(library_dirs, path)
library_dirs[#library_dirs + 1] = path
end
return library_dirs
end
Expand All @@ -79,14 +82,16 @@ local function init_fs_watcher(dir_to_watch, is_library_root)
log.debug("Filesystem event in the library root directory")
entry_dir = Path(dir_to_watch, filename)
info_path = entry_dir / info_name
local entry_dir_str = tostring(entry_dir)
local info_path_str = tostring(info_path)
if entry_dir:exists() and entry_dir:is_dir() then
log.debug(string.format("Filesystem event: path '%s' added", tostring(entry_dir)))
init_fs_watcher(tostring(entry_dir))
log.debug(string.format("Filesystem event: path '%s' added", entry_dir_str))
init_fs_watcher(entry_dir_str)
if info_path:exists() then
mtime = fs_stat(tostring(info_path)).mtime.sec
mtime = fs_stat(info_path_str).mtime.sec
end
elseif entry_dir:is_dir() then
log.debug(string.format("Filesystem event: path '' removed", tostring(entry_dir)))
log.debug(string.format("Filesystem event: path '' removed", entry_dir_str))
-- don't update here, because we'll catch it below under entry events
do_update = false
else
Expand All @@ -97,24 +102,26 @@ local function init_fs_watcher(dir_to_watch, is_library_root)
log.debug("Filesystem event in entry directory")
entry_dir = Path(dir_to_watch)
info_path = entry_dir / info_name
local info_path_str = tostring(info_path)
if info_path:exists() then
-- info file exists, update with new info
log.debug(string.format("Filesystem event: '%s' changed", tostring(info_path)))
log.debug(string.format("Filesystem event: '%s' changed", info_path_str))
mtime = fs_stat(tostring(info_path)).mtime.sec
elseif not entry_dir:exists() then
-- info file and entry dir don't exist. delete entry (mtime = nil) and remove watcher
log.debug(string.format("Filesystem event: '%s' removed", tostring(info_path)))
log.debug(string.format("Filesystem event: '%s' removed", info_path_str))
do_unwatch = true
else
-- info file doesn't exist but entry dir does. delete entry but keep watcher
log.debug(string.format("Filesystem event: '%s' removed", tostring(info_path)))
log.debug(string.format("Filesystem event: '%s' removed", info_path_str))
end
end
if do_update then
local info_path_str = tostring(info_path)
log.debug("Update database for this fs event...")
log.debug("Updating: " .. vim.inspect({ path = tostring(info_path), mtime = mtime }))
log.debug("Updating: " .. vim.inspect({ path = info_path_str, mtime = mtime }))
vim.defer_fn(function()
data.update_db({ path = tostring(info_path), mtime = mtime })
data.update_db({ path = info_path_str, mtime = mtime })
end, 200)
elseif do_unwatch then
log.debug("Removing watcher")
Expand Down Expand Up @@ -225,7 +232,7 @@ function M.stop()
if not vim.tbl_isempty(handles) then
log.trace("Stopping the fs watchers")
for _, handle in ipairs(handles) do
uv.fs_event_stop(handle)
handle:stop()
end
handles = {}
db.state:set_fw_running()
Expand Down
30 changes: 18 additions & 12 deletions lua/papis/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

local config = require("papis.config")
local api = vim.api

local log

---Creates the `autocmd` that starts papis.nvim when configured conditions are fulfilled
Expand All @@ -21,6 +20,20 @@ local function make_start_autocmd()
})
end

---Checks whether dependencies are available
local function are_dependencies_available()
local dependencies = { "papis", config["yq_bin"] }
for _, dependency in ipairs(dependencies) do
if vim.fn.executable(dependency) == 0 then
log.error(
string.format("The executable '%s' could not be found. Please install it to use papis.nvim", dependency)
)
return false
end
end
return true
end

local M = {}

---This function is run when neovim starts and sets up papis.nvim.
Expand All @@ -42,15 +55,8 @@ function M.start()
-- ensure that config options from Papis (python app) are setup
config:setup_papis_py_conf()

-- checking for dependencies
local dependencies = { "papis", config["yq_bin"] }
for _, dependency in ipairs(dependencies) do
if vim.fn.executable(dependency) == 0 then
log.error(
string.format("The executable '%s' could not be found. Please install it to use papis.nvim", dependency)
)
return nil
end
if not are_dependencies_available() then
return nil
end

-- require what's necessary within `M.start()` instead of globally to allow lazy-loading
Expand All @@ -64,14 +70,13 @@ function M.start()
log.warn("Requiring `data.lua` failed. Aborting...")
return nil
end
local does_pid_exist = require("papis.utils").does_pid_exist

-- setup commands
require("papis.commands").setup()
-- setup keymaps
require("papis.keymaps"):setup()

-- get all functions that we need to run the various commands
-- setup enabled modules
for module_name, _ in pairs(config["enable_modules"]) do
log.trace(module_name .. " is enabled")
local has_module, module = pcall(require, "papis." .. module_name)
Expand All @@ -83,6 +88,7 @@ function M.start()
end

-- check if other neovim instances has file watchers
local does_pid_exist = require("papis.utils").does_pid_exist
if not does_pid_exist(db.state:get_fw_running()) then
-- setup file watchers (or an autocmd if another instance has file watchers)
if config["enable_fs_watcher"] then
Expand Down
2 changes: 1 addition & 1 deletion lua/papis/log.lua
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ M.new = function(config, standalone)
local fmt = table.remove(passed, 1)
local inspected = {}
for _, v in ipairs(passed) do
table.insert(inspected, vim.inspect(v))
inspected[#inspected + 1] = vim.inspect(v)
end
return string.format(fmt, unpack(inspected))
end)
Expand Down
10 changes: 5 additions & 5 deletions lua/papis/papis-storage.lua
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ local function make_full_paths(filenames, path)
local full_paths = {}
for _, filename in ipairs(filenames) do
local full_path = tostring(Path(path, filename))
table.insert(full_paths, full_path)
full_paths[#full_paths + 1] = full_path
end
return full_paths
end
Expand All @@ -147,14 +147,14 @@ function M.get_metadata(paths)
paths = {}
for path in library_dir:fs_iterdir() do
if path:basename() == info_name then
table.insert(paths, path)
paths[#paths + 1] = path
end
end
end
local metadata = {}
for _, path in ipairs(paths) do
local mtime = fs_stat(tostring(path)).mtime.sec
table.insert(metadata, { path = tostring(path), mtime = mtime })
metadata[#metadata + 1] = { path = tostring(path), mtime = mtime }
end
return metadata
end
Expand All @@ -170,7 +170,7 @@ function M.get_data_full(metadata)
local mtime = metadata_v["mtime"]
local entry = read_yaml(path)
if is_valid_entry(entry, path) then
entry = do_convert_entry_keys(entry)
entry = do_convert_entry_keys(entry) --NOTE: entry is never nil because of `is_valid_entry()`
local data = {}
for key, type_of_val in pairs(data_tbl_schema) do
if type(type_of_val) == "table" then
Expand Down Expand Up @@ -205,7 +205,7 @@ function M.get_data_full(metadata)
end
end
end
table.insert(data_complete, { data, { path = path, mtime = mtime } })
data_complete[#data_complete + 1] = { data, { path = path, mtime = mtime } }
end
end
return data_complete
Expand Down
18 changes: 9 additions & 9 deletions lua/papis/search/data.lua
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,21 @@ local function format_search_string(entry)

local str_elements = {}
if do_incl_str("author") then
table.insert(str_elements, entry["author"])
str_elements[#str_elements + 1] = entry["author"]
elseif do_incl_str("editor", "author") then
table.insert(str_elements, entry["editor"])
str_elements[#str_elements + 1] = entry["editor"]
end
if do_incl_str("year") then
table.insert(str_elements, entry["year"])
str_elements[#str_elements + 1] = entry["year"]
end
if do_incl_str("title") then
table.insert(str_elements, entry["title"])
str_elements[#str_elements + 1] = entry["title"]
end
if do_incl_str("type") then
table.insert(str_elements, entry["type"])
str_elements[#str_elements + 1] = entry["type"]
end
if do_incl_str("tags") then
table.insert(str_elements, table.concat(entry["tags"], " "))
str_elements[#str_elements + 1] = table.concat(entry["tags"], " ")
end
local search_string = table.concat(str_elements, " ")
return search_string
Expand Down Expand Up @@ -107,10 +107,10 @@ local function init_tbl()
local items = {}
local displayer_tbl = {}
for _, vv in ipairs(display_strings) do
table.insert(items, { width = vim.fn.strdisplaywidth(vv[1], 1) })
table.insert(displayer_tbl, { vv[1], vv[2] })
items[#items + 1] = { width = vim.fn.strdisplaywidth(vv[1], 1) }
displayer_tbl[#displayer_tbl + 1] = { vv[1], vv[2] }
end
table.insert(items, { remaining = true })
items[#items + 1] = { remaining = true }

local timestamp = make_timestamp(entry)

Expand Down
7 changes: 7 additions & 0 deletions lua/papis/search/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ end

local telescope_precalc = {}

---Create a telescope entry for a given db entry
---@param entry table #A entry in the library db
---@return table #A telescope entry
local entry_maker = function(entry)
local entry_pre_calc = db["search"]:get(entry["id"])[1]
local timestamp = entry_pre_calc["timestamp"]
Expand Down Expand Up @@ -78,11 +81,15 @@ local module_keymaps = {

local M = {}

---Updates the precalculated telescope entry for the picker
---@param entry table #The db entry for which to update the telescope entry
function M.update_precalc(entry)
local id = entry["id"]
telescope_precalc[id] = entry_maker(entry)
end

---Get precalcuated telescope entries (or create them if they don't yet exist)
---@return table #Table with precalculated telescope entries for all db entries
function M.get_precalc()
if vim.tbl_isempty(telescope_precalc) then
local entries = db.data:get()
Expand Down
Loading

0 comments on commit 3014915

Please sign in to comment.