Recreate the forPrefix hook in page templates

Just playing with this today myself, and here’s my solution. It’s a little hacky in that I’m chaining together the editor:pageCreating event (where @roberth renders the template) with the subsequent editor:pageLoaded event that occurs when the editor loads the new page, with a little bit of global state to correlate the two.

On the pageLoaded, assuming we’re indeed loading the same page we just created, I scan the new page’s content for the cursor marker |^|, remove it, and place the cursor at the spot.

-- based on createPageFromTemplate but return the string
local function returnPageFromTemplate(templatePage)
  local tpl, fm = template.fromPage(templatePage)
  local initialText = ""
  if fm.frontmatter then
    initialText = "---\n"
      .. string.trim(template.new(fm.frontmatter)())
      .. "\n---\n"
  end
  return initialText .. tpl()
end

-- Cache the last created page
forprefix_latest_page = ""

-- Create event handler for all page templates with a forPrefix key in frontmatter
for pt in query[[
    from index.tag "meta/template/page"
    where _.tag == "page" and _.forPrefix
    order by _.priority desc
  ]] do
  event.listen {
    name = "editor:pageCreating",
    run = function(e)
      if e.data.name:startsWith(pt.forPrefix) then
        forprefix_latest_page = e.data.name
        return {
          text = returnPageFromTemplate(pt.name)
        }
      end
    end
  }
end
event.listen {
  name = "editor:pageLoaded",
  run = function(e)
    local nav_to = e.data[1]
    if nav_to == forprefix_latest_page then
      forprefix_latest_page = "" -- One-time only after page creation
      local page_text = editor.getText()
      local cursor_idx, _ = string.find(page_text, "|^|", 1, true)
      if cursor_idx then
        cursor_idx = cursor_idx - 1 -- editor is 0-based
        editor.replaceRange(cursor_idx, cursor_idx+3, "")
        editor.moveCursor(cursor_idx, true)
      end
    end
  end
}