Skip to content

Instantly share code, notes, and snippets.

@benhughes
Last active February 4, 2024 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benhughes/1cd1a3f6239d51ffdf8fbf2e3efe7286 to your computer and use it in GitHub Desktop.
Save benhughes/1cd1a3f6239d51ffdf8fbf2e3efe7286 to your computer and use it in GitHub Desktop.
Obsidian Templater - Copy link to current block
<%*
const currentFile = app.workspace.activeLeaf.view.file;
const editor = app.workspace.activeLeaf.view.sourceMode.cmEditor
const cursor = editor.getCursor();
const cursorLine = cursor.line;
const lineText = editor.getLine(cursor.line);
let lineId
if (lineText.contains(" ^")) {
const lineTextSplit = lineText.split(" ^");
// If the line already contains a ^ then get the text after it
lineId = lineTextSplit[lineTextSplit.length -1]
} else {
// Create a new ID
lineId = createBlockHash();
const result = await app.vault.read(currentFile)
const newLines = result.split("\n")
// replace the line at the cursor with the text followed by the new ID
newLines[cursorLine] = `${lineText} ^${lineId}`
// save the file with the new line of text
app.vault.modify(currentFile, newLines.join("\n"));
}
// copy the embed link to the block
navigator.clipboard.writeText(`![[${tp.file.title}#^${lineId}]]`);
function createBlockHash() {
let result = "";
const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
for ( var i = 0; i < 7; i++ ) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
-%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment