"Unlinked documents" as a virtual page

I sync a lot of handwritten pngs from my e-ink to my SB space. I then link some of these pngs (for eg. drawings) in my pages.

The other images (that don’t get linked) take up unnecessary space. So I wrote a virtual page to get a list of these pngs so I may review them & delete if necessary.

virtualPage.define {
  pattern = "udocs:(.+)",
  run = function(_)
    local result = {"# Unlinked documents"}

    local all_docs = query[[
      from index.tag "document"
      where not name.match("js$")
      select name
    ]]

    local linked_docs = query[[
      from index.tag "link"
      where toFile
      select toFile
    ]]

    local linked_set = {}
    for _, doc in ipairs(linked_docs) do
      linked_set[doc] = true
    end

    local unlinked_docs = {}
    for _, doc in ipairs(all_docs) do
      if not linked_set[doc] then
        table.insert(unlinked_docs, doc)
      end
    end
    for _, doc in ipairs(unlinked_docs) do
      local line = {}
      table.insert(line, "- [[")
      table.insert(line, doc)
      table.insert(line, "]]")
      table.insert(result, table.concat(line))
    end

    return table.concat(result, "\n")
  end
}
2 Likes

This is useful :+1: Thank You!

1 Like

If you move the document collection into its own function, like so:

unlinked_documents = {}

function unlinked_documents.get()
  local all_docs = query[[
    from index.tag "document"
    where not name.match("js$")
    select name
  ]]

  local linked_docs = query[[
    from index.tag "link"
    where toFile
    select toFile
  ]]

  local linked_set = {}
  for _, doc in ipairs(linked_docs) do
    linked_set[doc] = true
  end

  local unlinked_docs = {}
  for _, doc in ipairs(all_docs) do
    if not linked_set[doc] then
      table.insert(unlinked_docs, doc)
    end
  end

  return unlinked_docs
end

virtualPage.define {
  pattern = "udocs:(.+)",
  run = function(_)
    local result = {"# Unlinked documents"}

    local unlinked_docs = unlinked_documents.get()
    for _, doc in ipairs(unlinked_docs) do
      local line = {}
      table.insert(line, "- [[")
      table.insert(line, doc)
      table.insert(line, "]]")
      table.insert(result, table.concat(line))
    end

    return table.concat(result, "\n")
  end
}

You can make a widget button to open the virtual page that mentions how many documents there are:

${widgets.button("Unlinked Documents (" .. #unlinked_documents.get() .. ")", function() editor.navigate("udocs:Unlinked Documents") end)}

2 Likes