Skip to content

Commit

Permalink
feat(capture): Add on_compile hook for templates
Browse files Browse the repository at this point in the history
  • Loading branch information
kristijanhusak committed Mar 20, 2024
1 parent b7c42e6 commit cc1c4c2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lua/orgmode/capture/template/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ local expansions = {
end,
}

---@class OrgCaptureTemplate
---@class OrgCaptureTemplateOpts
---@field description? string
---@field template? string|string[]
---@field target? string
Expand All @@ -43,9 +43,12 @@ local expansions = {
---@field regexp? string
---@field properties? OrgCaptureTemplateProperties
---@field subtemplates? table<string, OrgCaptureTemplate>

---@class OrgCaptureTemplate:OrgCaptureTemplateOpts
---@field private _compile_hooks (fun(content:string):string)[]
local Template = {}

---@param opts OrgCaptureTemplate
---@param opts OrgCaptureTemplateOpts
---@return OrgCaptureTemplate
function Template:new(opts)
opts = opts or {}
Expand Down Expand Up @@ -94,6 +97,11 @@ function Template:setup()
end
end

function Template:on_compile(hook)
self._compile_hooks = self._compile_hooks or {}
table.insert(self._compile_hooks, hook)
end

function Template:validate_options()
self:_validate_regexp()
if self.datetree then
Expand Down Expand Up @@ -204,6 +212,11 @@ function Template:_compile(content)
content = self:_compile_expansions(content)
content = self:_compile_expressions(content)
content = self:_compile_prompts(content)
if self._compile_hooks then
for _, hook in ipairs(self._compile_hooks) do
content = hook(content)
end
end
return content
end

Expand Down
12 changes: 12 additions & 0 deletions tests/plenary/capture/templates_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,16 @@ describe('Capture template', function()

assert.are.same(date:to_string(), template:get_datetree_opts().date:to_string())
end)

it('should process custom compile hooks', function()
local template = Template:new({
template = '* This is a test {title} and {slug} in headline',
})
template:on_compile(function(content)
content = content:gsub('{title}', 'Org Test')
content = content:gsub('{slug}', 'org-test')
return content
end)
assert.are.same({ '* This is a test Org Test and org-test in headline' }, template:compile())
end)
end)

0 comments on commit cc1c4c2

Please sign in to comment.