One thing I miss about Obsidian is note refractor, i.e. select a block of text and add them to a new page, and in the original place there is now a link the new page. I'm considering write a command like this but I could not find api for passing select text to new page. I would be grateful if anyone could point me to the right direction.
Thank you for reading my post.
Update: Thank y'all again for taking your time to answer my question. After a little tinkering I achieved my goal to put selected text into new created page's title while creating from a page template. This is achieved by adding ${editor.getSelection().text} to the frontmatter choice suggestedName of the template.
I would like to thank @Mike for pointing me to this function.
(I realized in hindsight that I didn't even write my first goal out. I'm very sorry for my low effort question writing.)
I was amazed to find out that an official function Page: Extract did exactly what I described. For further customization I would dive harder into space-lua.
I'm not familiar with the note refactor function in Obsidian, but based on your description, I asked deepwiki to write me a function and it seems to work. This is the direction I would explore for such a function, using space.writePage() and editor.replaceRange()
BTW: the first solution deepwiki gave me made no sense whatsoever, so YMMV, but it typically helps me to get going.
command.define {
name = "Note: Refactor",
key = "Ctrl-Shift-r",
run = function()
local selection = editor.getSelection()
-- Check if text is selected
if not selection or selection.text == "" then
editor.flashNotification("No text selected", "error")
return
end
-- Extract the selected text
local text = selection.text
-- Try to extract a header as the suggested page name
local match = text:match("#%s*([^\n]+)")
local suggestedName = match or "new page"
-- Prompt for new page name
local newName = editor.prompt("New page name:", suggestedName)
if not newName or newName == "" then
return
end
newName = newName:trim()
-- Check if page already exists
if space.pageExists(newName) then
editor.flashNotification("Page " .. newName .. " already exists", "error")
return
end
-- Replace selection with wikilink
editor.replaceRange(selection.from, selection.to, "[[" .. newName .. "]]")
-- Write the new page with the extracted text
space.writePage(newName, text)
-- Navigate to the new page
editor.navigate(newName)
editor.flashNotification("Refactored to " .. newName, "info")
end
}
Thank you so much for pointing to these two functions and providing sample codes. I will play with the code to see if I could customize the new page a bit more.