Show a random list of N notes

This snippet allows to show N random pages from the vault. For instance, I’m showing 7 random notes on my home page, as an attempt to provoke serendipity. The number of random notes to be displayed can be passed as a function parameter.

function show_random(num_random)
  num_random = num_random or 7
  
  local results = query[[
      from p = index.tag('page')
      where not string.startsWith(p.name, 'Library/')
      select '[[' .. p.name .. ']]'
  ]]

  local picked_set = {}
  local show = {}
  local num_attempts = 2 * num_random
  while #show < num_random and num_attempts > 0 do
    num_attempts = num_attempts - 1
    local index = math.floor(math.random() * #results)
    if not picked_set[index] then
      if results[index] then
        table.insert(show, results[index])
        picked_set[index] = true
      end
    end
  end
  
  return show
end

Some ways to use this:

${show_random()} -- will show 7 random notes

${show_random(42)} -- will show 42 random notes

5 Likes