Hi all, just wanted to share my custom search I’ve come up with since downloading SilverBullet last night. I’m finding this really helpful and I’ve added this to a Library/Custom/Search
page.
command.define {
name = "Search: Custom Search",
key = "Ctrl-s",
run = function()
local search_term = editor.prompt("Search:", "")
local search_results = search(search_term, false)
local filter_options = {}
for _, item in ipairs(search_results) do
table.insert(filter_options, { name = "[" .. item.file .. "] " .. item.search_result, value = item })
end
local result = editor.filterBox("Select:", filter_options)
if result and result.value then
local page, count = string.gsub(result.value.file, ".md", "")
editor.navigate({ kind = "page", page = page })
editor.moveCursorToLine(result.value.line, result.value.col, true)
end
end
}
function search(search_term, use_template)
use_template = (use_template ~= false)
local search_results = shell.run("git", {"grep", "--line-number", "--column", search_term})
local parts = string.split(search_results.stdout, "\n")
local output = {}
for _, item in ipairs(parts) do
local fullpath, line, col, result = string.match(item, "^(.-):(.-):(.-):(.+)$")
if fullpath then
local search_result = string.trim(result)
if not string.startsWith(search_result, "${search(") then
table.insert(output, { file = fullpath, search_result = search_result, line = line, col = col })
end
end
end
if not use_template then
return output
else
local template_output = {}
for _, item in ipairs(output) do
local page, count = string.gsub(item.file, ".md", "")
local t = { file = page, search_result = item.search_result, line = item.line, col = item.col }
table.insert(template_output, dom.li({
onclick = function()
editor.navigate({ kind = "page", page = t.file })
editor.moveCursorToLine(t.line, t.col, true)
end,
dom.a({
href = "javascript:void(0);",
"[" .. t.file .. ":" .. t.line .. ":" .. t.col .. "] - " .. t.search_result
})
}))
end
return widget.new({
cssClasses = {"template-basic"},
html = dom.div({
class = "search-list",
dom.ul(template_output)
}),
})
end
end
.template-basic .wrapper,
.template-basic.sb-lua-directive-inline {
border: 0 !important;
margin: 0 !important;
padding: 0 !important;
}
.search-list {
border: 0;
padding: 0;
}
.search-list li {
margin-bottom: 8px;
}
You can then use this in a few ways:
${search("some search term")}
on any page which will render an inline clickable list that brings you directly to the line and column of the search term:
Or via the custom Search: Custom Search
command that I’ve bound to ctrl-s
. This is nice as it asks you for a search term and then shows all results in a picker window:
This also brings you directly to the search result and has the nice added bonus of being filterable.