Skip to content

Commit bb89dfc

Browse files
feat(capture): Add on_compile hook for templates
1 parent b7c42e6 commit bb89dfc

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

lua/orgmode/capture/template/init.lua

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ local expansions = {
3434
end,
3535
}
3636

37-
---@class OrgCaptureTemplate
37+
---@class OrgCaptureTemplateOpts
3838
---@field description? string
3939
---@field template? string|string[]
4040
---@field target? string
@@ -43,9 +43,12 @@ local expansions = {
4343
---@field regexp? string
4444
---@field properties? OrgCaptureTemplateProperties
4545
---@field subtemplates? table<string, OrgCaptureTemplate>
46+
47+
---@class OrgCaptureTemplate:OrgCaptureTemplateOpts
48+
---@field private _compile_hooks (fun(content:string):string)[]
4649
local Template = {}
4750

48-
---@param opts OrgCaptureTemplate
51+
---@param opts OrgCaptureTemplateOpts
4952
---@return OrgCaptureTemplate
5053
function Template:new(opts)
5154
opts = opts or {}
@@ -94,6 +97,12 @@ function Template:setup()
9497
end
9598
end
9699

100+
function Template:on_compile(hook)
101+
self._compile_hooks = self._compile_hooks or {}
102+
table.insert(self._compile_hooks, hook)
103+
return self
104+
end
105+
97106
function Template:validate_options()
98107
self:_validate_regexp()
99108
if self.datetree then
@@ -204,6 +213,11 @@ function Template:_compile(content)
204213
content = self:_compile_expansions(content)
205214
content = self:_compile_expressions(content)
206215
content = self:_compile_prompts(content)
216+
if self._compile_hooks then
217+
for _, hook in ipairs(self._compile_hooks) do
218+
content = hook(content)
219+
end
220+
end
207221
return content
208222
end
209223

tests/plenary/capture/templates_spec.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,16 @@ describe('Capture template', function()
6060

6161
assert.are.same(date:to_string(), template:get_datetree_opts().date:to_string())
6262
end)
63+
64+
it('should process custom compile hooks', function()
65+
local template = Template:new({
66+
template = '* This is a test {title} and {slug} in headline',
67+
})
68+
template:on_compile(function(content)
69+
content = content:gsub('{title}', 'Org Test')
70+
content = content:gsub('{slug}', 'org-test')
71+
return content
72+
end)
73+
assert.are.same({ '* This is a test Org Test and org-test in headline' }, template:compile())
74+
end)
6375
end)

0 commit comments

Comments
 (0)