Command in space-lua to set page attributes

Hi, I discovered silverbullet a few weeks ago and it was love on first sight :heart:

Currently I am exploring space-lua, and I came up with a command to modify page attributes:

```space-lua
command.define {
  name = "Page: Set Attribute",
  run = function(a)
    local data = a[1]
    local mypath = data.page or _CTX.currentPage.name
    local myattr = data.attribute or "foo"
    local myvalue = data.value or 0
    local mychange = data.change or 0
    local mypage = space.read_page(mypath)
    local oldline = "[%[]%s*" .. myattr .. "%s*:%s*%w+%s*]"
    local oldval = nil
    local newline = "[" .. myattr .. ":" .. myvalue .. "]"
    local newpage = ""
    local matches = string.match(mypage,oldline).values
    if matches[1] then
      local oldval = tonumber(string.match(matches[1],"%d+").values[1])
      if oldval and mychange != 0 then
        newline = "["..myattr .. ":" .. oldval+mychange .. "]"
      end 
      newpage = string.gsub(mypage,oldline,newline,1)
    else
      newpage = mypage.."\n"..newline
    end
    space.write_page(mypath,newpage)
    codeWidget.refreshAll()
    if mypath == _CTX.currentPage.name then
      editor.set_text(newpage)
    end
  end
}

This can then be used as a command button to set or change attributes of the current page:

{[Page: Set Attribute|Reset Stars]({"attribute": "stars","value": 0})}
{[Page: Set Attribute|Add Star]({"attribute": "stars","change":1})}

or any other page:

{[Page: Set Attribute|Reset Stars on test]({"page": "test","attribute": "stars","value": 0})}
{[Page: Set Attribute|Add Star on test]({"page": "test","attribute": "stars","change": 1})}

It really shines when parametrized in a template:

```template
{{#each {page where stars and stars>=0} }}
* [[{{name}}]]: ⭐{{stars}} {[Page: Set Attribute|Add Star]({"page": "{{name}}","attribute": "stars","change": 1})}
{{/each}}

this renders to:

Maybe this is useful for someone. Have fun!

3 Likes