1
0
silverbullet/web/cm_plugins/smart_quotes.ts
Zef Hemel aaebea5e54
Major directive refactor (#195)
Fixes #188 #144 #76: major refactor of directive parsing, rendering, styling
2022-12-14 20:04:20 +01:00

63 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { KeyBinding, syntaxTree } from "../deps.ts";
const straightQuoteContexts = [
"CommentBlock",
"FencedCode",
"InlineCode",
"FrontMatterCode",
"DirectiveStart",
];
// TODO: Add support for selection (put quotes around or create blockquote block?)
function keyBindingForQuote(
quote: string,
left: string,
right: string,
): KeyBinding {
return {
any: (target, event): boolean => {
// Moving this check here rather than using the regular "key" property because
// for some reason the "ä" key is not recognized as a quote key by CodeMirror.
if (event.key !== quote) {
return false;
}
const cursorPos = target.state.selection.main.from;
const chBefore = target.state.sliceDoc(cursorPos - 1, cursorPos);
// Figure out the context, if in some sort of code/comment fragment don't be smart
let node = syntaxTree(target.state).resolveInner(cursorPos);
while (node) {
if (straightQuoteContexts.includes(node.type.name)) {
return false;
}
if (node.parent) {
node = node.parent;
} else {
break;
}
}
// Ok, still here, let's use a smart quote
let q = right;
if (/\W/.exec(chBefore) && !/[!\?,\.\-=“]/.exec(chBefore)) {
q = left;
}
target.dispatch({
changes: {
insert: q,
from: cursorPos,
},
selection: {
anchor: cursorPos + 1,
},
});
return true;
},
};
}
export const smartQuoteKeymap: KeyBinding[] = [
keyBindingForQuote('"', "“", "”"),
keyBindingForQuote("'", "", ""),
];