Skip to content

Commit

Permalink
Fix inserting templates from nested directory
Browse files Browse the repository at this point in the history
Fixes #409.
  • Loading branch information
epwalsh committed Feb 19, 2024
1 parent cdbc615 commit a83a958
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 10 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Fixed

- Fixed inserting templates when the templates directory structure is nested.

## [v3.3.0](https://github.com/epwalsh/obsidian.nvim/releases/tag/v3.3.0) - 2024-02-17

### Added
Expand Down
11 changes: 3 additions & 8 deletions lua/obsidian/commands/template.lua
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,8 @@ return function(client, data)
end

if string.len(data.args) > 0 then
local template_name = data.args
local path = client:templates_dir() / template_name
if path:is_file() then
insert_template(data.args)
else
log.err "Not a valid template file"
end
local template_name = util.strip_whitespace(data.args)
insert_template(template_name)
return
end

Expand All @@ -35,7 +30,7 @@ return function(client, data)

picker:find_templates {
callback = function(path)
insert_template(vim.fs.basename(path))
insert_template(path)
end,
}
end
24 changes: 22 additions & 2 deletions lua/obsidian/templates.lua
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ end

---Insert a template at the given location.
---
---@param name string name of a template in the configured templates folder
---@param name string name or path of a template in the configured templates folder
---@param client obsidian.Client
---@param location table a tuple with {bufnr, winnr, row, col}
M.insert_template = function(name, client, location)
Expand All @@ -95,9 +95,29 @@ M.insert_template = function(name, client, location)
return
end
local buf, win, row, col = unpack(location)
local template_path = templates_dir / name
local title = require("obsidian.note").from_buffer(buf, client.dir):display_name()

---@type Path
local template_path
local paths_to_check = { templates_dir / name, Path:new(name) }
for _, path in ipairs(paths_to_check) do
if path:is_file() then
template_path = path
break
elseif not vim.endswith(tostring(path), ".md") then
local path_with_suffix = Path:new(tostring(path) .. ".md")
if path_with_suffix:is_file() then
template_path = path_with_suffix
break
end
end
end

if template_path == nil then
log.err("Template '%s' not found", name)
return
end

local insert_lines = {}
local template_file = io.open(tostring(template_path), "r")
if template_file then
Expand Down

0 comments on commit a83a958

Please sign in to comment.