Created
March 29, 2022 03:26
-
-
Save pengx17/4af8e5369855202abfeb77f4fb67274b to your computer and use it in GitHub Desktop.
auto pairing double quotes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let currentRepo = logseq.api.get_current_graph().path; | |
function isActive() { | |
return logseq.api.get_current_graph().path === currentRepo; | |
} | |
function isEditing() { | |
return logseq.api.check_editing(); | |
} | |
function getActiveTextarea() { | |
if (isEditing()) { | |
const textarea = document.activeElement; | |
return textarea.nodeName === "TEXTAREA" ? textarea : undefined; | |
} | |
} | |
function quoteTextInTextarea(textarea, quote) { | |
if (isEditing()) { | |
const { selectionStart, selectionEnd } = textarea; | |
const selectedText = textarea.value.substring(selectionStart, selectionEnd); | |
if (selectedText) { | |
textarea.value = | |
textarea.value.substring(0, selectionStart) + | |
quote + | |
selectedText + | |
quote + | |
textarea.value.substring(selectionEnd); | |
textarea.selectionStart = selectionStart + 1; | |
textarea.selectionEnd = selectionEnd + 1; | |
return true; | |
} | |
} | |
} | |
window.addEventListener( | |
"keydown", | |
(e) => { | |
if (isActive() && e.key === '"') { | |
const textarea = getActiveTextarea(); | |
if (textarea) { | |
const quoted = quoteTextInTextarea(textarea, '"'); | |
if (quoted) { | |
e.stopPropagation(); | |
e.preventDefault(); | |
} | |
} | |
} | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment