obsidian-auto-typography/main.ts

52 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-05-20 08:47:27 +00:00
import { MarkdownPostProcessor, MarkdownPostProcessorContext, MarkdownPreviewRenderer, Plugin } from 'obsidian';
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
export default class AutoTypographyPlugin extends Plugin {
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
static postprocessor: MarkdownPostProcessor = (el: HTMLElement, ctx: MarkdownPostProcessorContext) => {
const treeWalker = el.ownerDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT);
let currentNode;
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// Go through all text nodes in the rendered HTML
while ((currentNode = treeWalker.nextNode())) {
let t = currentNode.textContent!;
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// convert triple hyphens to em-dash
t = t.replace(/---/g, "\u2014");
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// convert double hyphens to en-dash
t = t.replace(/--/g, "\u2013");
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// convert triple periods to horizontal ellipsis
t = t.replace(/\.\.\./g, "\u2026");
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// convert apostrophe in the middle of a word to right single quotation mark
t = t.replace(/(?<=\w)'(?=\w)/gu, "\u2019");
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// convert double quote at the end of a word to right double quotation mark
t = t.replace(/(?<=(\w|\p{P}))"/gu, "\u201d");
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// convert single quote at the end of a word to right single quotation mark
t = t.replace(/(?<=(\w|\p{P}))'/gu, "\u2019");
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// convert double quote at the beginning of a word to left double quotation mark
t = t.replace(/"(?=(\w|\p{P}))/gu, "\u201c");
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
// convert single quote at the beginning of a word to left single quotation mark
t = t.replace(/'(?=(\w|\p{P}))/gu, "\u2018");
if (currentNode.textContent != t) {
currentNode.textContent = t;
}
}
}
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
async onload() {
MarkdownPreviewRenderer.registerPostProcessor(AutoTypographyPlugin.postprocessor);
}
2023-05-20 07:21:16 +00:00
2023-05-20 08:47:27 +00:00
async onunload() {
MarkdownPreviewRenderer.unregisterPostProcessor(AutoTypographyPlugin.postprocessor);
}
2023-05-20 07:21:16 +00:00
}