Extract to specified heading with Note Composer

I modified the script that @AlanG created so that it creates a bidirectional link between where the text is extracted to and from. I found this to be helpful in situations where you are extracting a lot of content to a note and you are having trouble returning to the source because the backlinks tab is overwhelming and of no use when trying to find backlinks for a specific block or heading (see Option to sort backlinks by heading/block-ids).

As is obvious by my modifications to AlanG’s code, I am definitely not experienced creating or even editing scripts. Fortunately, so far, based on my testing, the following appears to work.

//Modified from @AlanG’s awesome script at https://share.note.sx/tus76cc6
<%*
// Get the selected text
let text = app.workspace.activeEditor.getSelection()
const srcnote = tp.file.title

// Get the desired file - credits to https://forum.obsidian.md/t/67901/4
const files = app.vault.getMarkdownFiles().map(file => {
  const fileCache = app.metadataCache.getFileCache(file)
  file.display = file.basename
  if (fileCache?.frontmatter?.aliases) {
    if (Array.isArray(fileCache.frontmatter.aliases)) {
      file.display = `${file.basename}\n${fileCache.frontmatter.aliases.join(", ")}`
    } else if (typeof fileCache.frontmatter.aliases === 'string') {
      file.display = `${file.basename}\n${fileCache.frontmatter.aliases}`
    }
  }
  return file
})
const destination = (await tp.system.suggester(files.map(x => x.display), files, false, 'Start typing any note name...', 10)).path

// Get the heading
let embed
const backref = Math.random().toString(36).slice(2, 7)
const heading = await tp.system.prompt('Enter the new heading or escape/cancel to use a block reference')
if (heading) {
  text = `\n\n## ${heading.trim()}\n`+  "FROM—> [[" + srcnote + "#^" + backref + "]]" + `\n${text.trim()}\n\n`
  embed = "EXTRACTED ^" + backref +  `\n\n![[${destination.slice(0, -3)}#${heading}]]\n`
} else {
  // Block reference
  const ref = Math.random().toString(36).slice(2, 7)
  text = `\n`+  "FROM—> [[" + srcnote + "#^" + backref + "]]" +`\n${text.trim()} ^${ref}\n\n`
  embed = "EXTRACTED ^" + backref +`\n\n![[${destination.slice(0, -3)}#^${ref}]]\n`
}

// Add the text to the destination note
await app.vault.adapter.append(destination, text)

// Replace the selection with an embedded link to the new location
app.workspace.activeEditor.editor.replaceSelection(embed)
-%>

If the embeds appear wrong after running the script, try navigating away from them back into the current note. For me, this fixed any erroneous rendering of transclusions. I only tested on mobile, and am not sure this would technically be an Obsidian bug, since plugins are being utilized. Perhaps there is a way to fix this such as triggering some sort of reloading of the current note at the end of the script.

Anyways, use this modified version of AlanG’s script at your own risk.

Thanks!