1
0
silverbullet/packages/plugs/core/markup.ts
2022-04-25 10:33:38 +02:00

39 lines
828 B
TypeScript

import {
getCursor,
getText,
insertAtPos,
replaceRange,
} from "@plugos/plugos-silverbullet-syscall/editor";
export async function toggleH1() {
await togglePrefix("# ");
}
export async function toggleH2() {
await togglePrefix("## ");
}
function lookBack(s: string, pos: number, backString: string): boolean {
return s.substring(pos - backString.length, pos) === backString;
}
async function togglePrefix(prefix: string) {
let text = await getText();
let pos = await getCursor();
if (text[pos] === "\n") {
pos--;
}
while (pos > 0 && text[pos] !== "\n") {
if (lookBack(text, pos, prefix)) {
// Already has this prefix, let's flip it
await replaceRange(pos - prefix.length, pos, "");
return;
}
pos--;
}
if (pos) {
pos++;
}
await insertAtPos(prefix, pos);
}