Skip to content

Instantly share code, notes, and snippets.

@GitMurf
Last active January 27, 2023 21:42
Show Gist options
  • Save GitMurf/c34ab5aedb2161ac26cc8076a116000a to your computer and use it in GitHub Desktop.
Save GitMurf/c34ab5aedb2161ac26cc8076a116000a to your computer and use it in GitHub Desktop.
Replace a block ref in the current line with the actual text from the block ref. It replicates Roam's feature where you right-click a block ref and choose "Replace as text".
<%*
//v1.1: Changed to using the new "view.editor" instead of deprecated "view.sourceMode.cmEditor"
let thisFile = this.app.workspace.getActiveFile();
let thisFileCache = this.app.metadataCache.getFileCache(thisFile);
let embedsOnPage = thisFileCache.embeds;
if(embedsOnPage) {
let cmEditorAct = this.app.workspace.activeLeaf.view.editor;
let curLine = cmEditorAct.getCursor().line;
foundEmbed = embedsOnPage.find(eachItem => {
let embedLine = eachItem.position.start.line;
if(embedLine == curLine){
return true;
} else { return false; }
});
if(foundEmbed) {
let thisName = foundEmbed.link;
let fileName = thisName.split('#^')[0];
if(!fileName){fileName = thisFile.basename}
let blockId = thisName.split('#^')[1];
let myNewFile = this.app.metadataCache.getFirstLinkpathDest(fileName, '');
if(myNewFile) {
let newFileCache = this.app.metadataCache.getFileCache(myNewFile);
let foundBlock = newFileCache.blocks[blockId];
let newFileContents = await this.app.vault.cachedRead(myNewFile);
let foundBlockValue = newFileContents.substring(foundBlock.position.start.offset, foundBlock.position.end.offset).replace('^' + blockId,'').trim();
if(foundBlockValue) {
cmEditorAct.setSelection({ line: curLine, ch: 0 }, { line: curLine, ch: 9999 });
tR = tp.file.selection().replace(foundEmbed.original, foundBlockValue).split("\n").join("");
}
}
}
}
%>
@trungng2006
Copy link

Thank you for this gist!
Could you please kindly also create one to do the same for block heading?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment