2022-04-21 11:57:45 +00:00
|
|
|
import { getCursor, getText, insertAtPos, replaceRange } from "@silverbulletmd/plugos-silverbullet-syscall/editor";
|
2022-02-24 16:24:49 +00:00
|
|
|
|
|
|
|
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) {
|
2022-04-01 15:07:08 +00:00
|
|
|
let text = await getText();
|
|
|
|
let pos = await getCursor();
|
2022-02-24 16:24:49 +00:00
|
|
|
if (text[pos] === "\n") {
|
|
|
|
pos--;
|
|
|
|
}
|
|
|
|
while (pos > 0 && text[pos] !== "\n") {
|
|
|
|
if (lookBack(text, pos, prefix)) {
|
|
|
|
// Already has this prefix, let's flip it
|
2022-04-01 15:07:08 +00:00
|
|
|
await replaceRange(pos - prefix.length, pos, "");
|
2022-02-24 16:24:49 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
pos--;
|
|
|
|
}
|
|
|
|
if (pos) {
|
|
|
|
pos++;
|
|
|
|
}
|
2022-04-01 15:07:08 +00:00
|
|
|
await insertAtPos(prefix, pos);
|
2022-02-24 16:24:49 +00:00
|
|
|
}
|