Lua: [Productivity] Token replacement

---
# Define key-value to replace
replace:
  t:  text 
  d: demonstration
---


```space-lua
function replaceValue(content, tags)
  local c= content
  for k, v in pairs(tags) do
    local key="_"..k.."_"
    c=c:gsub(key, v)
  end
  return c
end

function getParent(path)
    local parent = path:match("^(.*)/[^/]+$")
    return parent
end

function getMeta(name)
  local tagsToReplace= index.extractFrontmatter(space.readPage(name)).frontmatter--space.getPageMeta(name)
  local parent = getParent(name)
  if (tagsToReplace == nil or (tagsToReplace ~=nil and   tagsToReplace["replace"] ==nil)) and parent ~=nil then 
    tagsToReplace = getMeta(parent)
  end
  if tagsToReplace ~=nil and tagsToReplace["replace"] ~=nil then 
    return tagsToReplace
  end
end


command.define {
  name = "replace ",
  run = function()
    local pageName=editor.getCurrentPage()
    local tagsToReplace=getMeta(pageName)
    if tagsToReplace ~=nil then
      local content= space.readPage(pageName)
      local result=replaceValue(content, tagsToReplace["replace"])  
      space.writePage(pageName, result)
      editor.navigate(pageName)
    else
      print("Nothing to replace")
    end
  end
}
```

d with this t will be transformed to demonstration with this text

2 Likes

add Inheritance from parent pages