Skip to content

Instantly share code, notes, and snippets.

@robinsonkwame
Last active February 25, 2024 05:14
Show Gist options
  • Save robinsonkwame/c64d43362ac8f5131e2ef12221e7df3f to your computer and use it in GitHub Desktop.
Save robinsonkwame/c64d43362ac8f5131e2ef12221e7df3f to your computer and use it in GitHub Desktop.
Logseq custom.js functions for creating named blocked references with CMD-T
const getBlock = async (selectedText) => {
const currentBlock = logseq.api.get_current_block();
if (currentBlock) {
const newText = `[${selectedText}](())`
const updatedContent = currentBlock.content.replace(
selectedText, newText
);
await logseq.api.update_block(
currentBlock.uuid,
updatedContent
); // seems to insert a block id
return updatedContent.indexOf(newText) + newText.length - 2 // for ))'s
}
}
const adjustCaret = (offset) => {
const selection = window.getSelection();
const textArea = selection.anchorNode.firstChild
textArea.focus()
textArea.selectionEnd = offset
}
document.addEventListener('keydown', async (event) => {
if (event.metaKey && event.key === 't') { // CMD + T to fire the script; select content first
const selectionObject = document.getSelection();
const selectionText = selectionObject.toString();
if (selectionText) {
console.log("Selected text surrounded by brackets:", selectionText);
const offset = await getBlock(selectionText);
adjustCaret(offset);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment