Skip to content

📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

Separe editor into modules files

Smaug6739eaf9f99f5600
diff --git a/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue b/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
index d93d111a..d7741365 100644
--- a/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
+++ b/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
@@ -2,7 +2,7 @@
<template>
<div style="height: 100%">
<div class="editor-container">
- <Toolbar v-model="document" :minimal="minimal" @execute-action="exec" />
+ <Toolbar v-model="document" :minimal="minimal" @execute-action="commands.exec" />
<div style="display: flex; min-height: 0; padding: 6px 0; flex: 1; flex-direction: column; gap: 8px">
<input v-if="!minimal" v-model="document.name" placeholder="Title" class="title" @input="autoSaveConditional" />
<input v-if="!minimal" v-model="document.description" placeholder="Description" class="description" @input="autoSaveConditional" />
@@ -23,22 +23,22 @@
</template>
<script setup lang="ts">
-import { EditorView, keymap, highlightSpecialChars, drawSelection, lineNumbers, type KeyBinding } from '@codemirror/view';
-import { EditorState, Compartment } from '@codemirror/state';
-import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
-import { highlightSelectionMatches, searchKeymap } from '@codemirror/search';
-import { autocompletion, completionKeymap, snippet, type CompletionContext } from '@codemirror/autocomplete';
-import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
+import { EditorView } from '@codemirror/view';
import { loadTheme } from './themes';
-import { katexSnippets } from './katex-snippets';
+import { createEditorState } from './modules/editorState';
+import { createKeymaps } from './modules/editorKeymaps';
+import { createUploadsHandlers } from './modules/editorUploads';
+import { createSnippetSource } from './modules/editorUtils';
+import { createCommands } from './modules/editorCommands';
import Toolbar from './Toolbar.vue';
-import ImageSelectorModal from './ImageSelectorModal.vue';
-import GridOrganizationModal from './GridOrganizationModal.vue';
-import ColorPickerModal from './ColorPickerModal.vue';
import compile from '~/helpers/markdown';
import type { Node } from '~/stores';
-import { useModal, Modal } from '~/composables/ModalBus';
+
+/* Modals */
+import ImageSelectorModal from './ImageSelectorModal.vue';
+import GridOrganizationModal from './GridOrganizationModal.vue';
+import ColorPickerModal from './ColorPickerModal.vue';
const resourcesStore = useRessourcesStore();
const preferences = usePreferences();
@@ -57,339 +57,32 @@ const document = ref<Partial<Node>>({
content_compiled: compile(props.doc?.content || ''),
});
-// ... [FONCTIONS EXEC, MODALS, ETC. INCHANGÉES] ...
-// Je ne répète pas le bloc exec/insertText/Modals pour gagner de la place,
-// gardez exactement ce que vous aviez.
-
-function exec(action: string, payload?: string) {
- if (action === 'preview') return (showPreview.value = !showPreview.value);
- if (action === 'openColorPicker') return openColorModal();
- if (action === 'save') return save();
- if (action === 'goto') if (document.value.id) return useRouter().push(`/dashboard/docs/${document.value.id}`);
- if (action === 'image') return openImageSelector();
- if (action === 'gridOrganization') return openGridOrganization();
- if (action === 'insertText') return insertText(payload || '');
-
- if (!editorView.value) return;
-
- const view = editorView.value;
- const state = view.state;
-
- const { from, to } = state.selection.main;
- const selectedText = state.sliceDoc(from, to);
-
- let changes;
- let select_from = from + 2;
- let select_to = to + 2;
-
- switch (action) {
- case 'bold':
- changes = { from, to, insert: `**${selectedText}**` };
- break;
- case 'italic':
- changes = { from, to, insert: `*${selectedText}*` };
- select_from = from + 1;
- select_to = select_from + selectedText.length;
- break;
- case 'underline':
- changes = { from, to, insert: `__${selectedText}__` };
- break;
- case 'strike':
- changes = { from, to, insert: `~~${selectedText}~~` };
- break;
- case 'link':
- changes = { from, to, insert: `[](${selectedText})` };
- select_from = from + 3;
- select_to = select_from;
- break;
- case 'code':
- changes = { from, to, insert: `\`${selectedText}\`` };
- break;
- case 'quote':
- changes = { from, to, insert: `> ${selectedText}\n` };
- break;
- case 'list':
- changes = { from, to, insert: `- ${selectedText}\n` };
- break;
- case 'orderedList':
- changes = { from, to, insert: `1. ${selectedText}\n` };
- break;
- case 'color': {
- const color = String(payload || '').trim();
- if (!color) return;
- const insert = `{color:${color}}(${selectedText})`;
- changes = { from, to, insert };
- select_from = insert.indexOf('(') + 1 + from;
- select_to = select_from + selectedText.length;
- break;
- }
- }
-
- view.dispatch({
- changes,
- selection: { anchor: select_from, head: select_to },
- });
-
- view.focus();
-}
-
-function insertText(text: string) {
- if (!editorView.value || !text) return;
-
- const view = editorView.value;
- const state = view.state;
- const { from, to } = state.selection.main;
-
- view.dispatch({
- changes: { from, to, insert: text },
- selection: { anchor: from + text.length, head: from + text.length },
- });
-
- view.focus();
-}
-
-function openColorModal() {
- const modalManager = useModal();
- modalManager.add(new Modal(shallowRef(ColorPickerModal), { props: { onColorSelect: handleColorSelect } }));
-}
-
-function handleColorSelect(color: string) {
- exec('color', color);
-}
-
-function openImageSelector() {
- const modalManager = useModal();
- modalManager.add(new Modal(shallowRef(ImageSelectorModal), { props: { onImageSelect: handleImageSelect }, size: 'large' }));
-}
-
-function openGridOrganization() {
- const modalManager = useModal();
- modalManager.add(new Modal(shallowRef(GridOrganizationModal), { props: { onGridSelect: handleGridSelect } }));
-}
-
-function handleImageSelect(imageUrl: string, altText: string) {
- if (!editorView.value) return;
-
- const view = editorView.value;
- const state = view.state;
- const { from, to } = state.selection.main;
- const selectedText = state.sliceDoc(from, to);
-
- const alt = selectedText || altText;
- const insert = `![${alt}](${imageUrl})`;
-
- view.dispatch({
- changes: { from, to, insert },
- selection: { anchor: from + insert.length, head: from + insert.length },
- });
-
- view.focus();
-}
-
-function handleGridSelect(gridMarkdown: string) {
- if (!editorView.value) return;
-
- const view = editorView.value;
- const state = view.state;
- const { from, to } = state.selection.main;
-
- view.dispatch({
- changes: { from, to, insert: gridMarkdown },
- selection: { anchor: from + gridMarkdown.length, head: from + gridMarkdown.length },
- });
-
- view.focus();
-}
-
-const fileUploadHandler = EditorView.domEventHandlers({
- paste: event => {
- const items = event.clipboardData?.items;
- if (!items) return;
- for (const item of items) {
- if (item.kind === 'file') {
- const file = item.getAsFile();
- if (!file) return;
- const body = new FormData();
- body.append('file', file);
- resourcesStore.post(body).then((result: Node) => {
- const url = `${CDN}/${(result as Node).user_id}/${(result as Node).content_compiled}`;
- exec('insertText', `![${file.name}](${url})\n`);
- });
- }
- }
- },
- drop: event => {
- const items = event.dataTransfer?.items;
- if (!items) return;
- for (const item of items) {
- if (item.kind === 'file') {
- const file = item.getAsFile();
- if (!file) return;
- const body = new FormData();
- body.append('file', file);
- resourcesStore.post(body).then((result: Node) => {
- const url = `${CDN}/${(result as Node).user_id}/${(result as Node).content_compiled}`;
- exec('insertText', `![${file.name}](${url})\n`);
- });
- }
- }
+const commands = createCommands({
+ getView: () => editorView.value,
+ getDoc: () => document.value,
+ setDoc: d => (document.value = d),
+ showPreview,
+ save: () => save(),
+ modals: {
+ ImageSelectorModal,
+ GridOrganizationModal,
+ ColorPickerModal,
},
});
-const markdownKeysmap: readonly KeyBinding[] = [
- {
- key: 'Mod-b',
- run: () => {
- exec('bold');
- return true;
- },
- },
- {
- key: 'Mod-i',
- run: () => {
- exec('italic');
- return true;
- },
- },
- {
- key: 'Mod-u',
- run: () => {
- exec('underline');
- return true;
- },
- },
- {
- key: 'Mod-e',
- run: () => {
- exec('image');
- return true;
- },
- },
- {
- key: 'Mod-l',
- run: () => {
- exec('link');
- return true;
- },
- },
-];
+const uploadsHandlers = createUploadsHandlers({ resourcesStore, CDN, insertText: (t: string) => commands.exec('insertText', t) });
-const themeCompartment = new Compartment();
-
-const updateListener = EditorView.updateListener.of(v => {
- if (v.docChanged) {
+const state = createEditorState({
+ initialDoc: document.value.content || '',
+ preferences,
+ themeExtension: loadTheme(),
+ keymaps: createKeymaps(commands),
+ snippetSource: createSnippetSource(preferences),
+ onDocChanged: () => {
updateDocumentContent();
autoSaveConditional();
- }
-});
-function isInsideMath(context: CompletionContext): boolean {
- const doc = context.state.doc.toString();
- const pos = context.pos;
- const len = doc.length;
- const tokens: { pos: number; type: '$' | '$$' }[] = [];
-
- // Tokenize: find $ and $$ that are NOT escaped (preceded by backslash)
- for (let i = 0; i < len; i++) {
- if (doc[i] !== '$') continue;
- // count backslashes immediately before to check escaping
- let j = i - 1;
- let backslashes = 0;
- while (j >= 0 && doc[j] === '\\') {
- backslashes++;
- j--;
- }
- if (backslashes % 2 === 1) continue; // escaped -> ignore
-
- if (i + 1 < len && doc[i + 1] === '$') {
- tokens.push({ pos: i, type: '$$' });
- i++; // skip second $
- } else {
- tokens.push({ pos: i, type: '$' });
- }
- }
-
- // Count $$ before the cursor
- const blockDollarPositions = tokens.filter(t => t.type === '$$').map(t => t.pos);
- const blockCountBefore = blockDollarPositions.filter(p => p < pos).length;
- // If odd number of $$ before cursor -> we're inside a $$...$$ block
- if (blockCountBefore % 2 === 1) return true;
-
- // Build intervals of $$ pairs to exclude single $ inside them
- const blockIntervals: Array<[number, number]> = [];
- for (let i = 0; i + 1 < blockDollarPositions.length; i += 2) {
- const start = blockDollarPositions[i] ?? 0;
- const end = (blockDollarPositions[i + 1] ?? 0) + 2; // end index after closing $$
- blockIntervals.push([start, end]);
- }
-
- // Helper: check if position is inside any $$ interval
- const inBlock = (p: number) => blockIntervals.some(([s, e]) => p >= s && p < e);
-
- // Filter single $ tokens that are NOT inside a $$ interval
- const singleDollarPositions = tokens.filter(t => t.type === '$' && !inBlock(t.pos)).map(t => t.pos);
-
- const singleCountBefore = singleDollarPositions.filter(p => p < pos).length;
-
- // If odd -> inside inline $...$
- return singleCountBefore % 2 === 1;
-}
-
-function snippetSource(context: CompletionContext) {
- if (!preferences.get('editorSnippetsEnabled').value) return null;
- const allSnippets = preferences.get('snippets').value;
-
- const word = context.matchBefore(/[\w!:]+/);
- if (!word && !context.explicit) return null;
-
- const inMath = isInsideMath(context);
-
- return {
- from: word ? word.from : context.pos,
- options: [
- ...allSnippets.map(s => ({
- label: s.id,
- detail: 'Snippet',
- type: 'snippet',
- apply: snippet(s.label),
- })),
-
- ...(inMath
- ? katexSnippets.map(s => ({
- label: s.id,
- detail: 'KaTeX',
- type: 'snippet',
- apply: snippet(s.label),
- }))
- : []),
- ],
- };
-}
-
-const state = EditorState.create({
- doc: document.value.content || '',
- extensions: [
- lineNumbers(),
- highlightSpecialChars(),
- history(),
- drawSelection(),
- autocompletion(),
- keymap.of([...completionKeymap, ...defaultKeymap, ...historyKeymap, indentWithTab, ...searchKeymap, ...markdownKeysmap]),
- markdown({ base: markdownLanguage }),
- markdownLanguage.data.of({
- autocomplete: snippetSource,
- }),
- updateListener,
- fileUploadHandler,
- themeCompartment.of(loadTheme()),
- highlightSelectionMatches({}),
- EditorView.lineWrapping,
- EditorState.allowMultipleSelections.of(true),
- EditorView.contentAttributes.of({
- spellcheck: preferences.get('editorSpellCheck').value ? 'true' : 'false',
- autocorrect: 'on',
- autocapitalize: 'on',
- }),
- ],
+ },
+ uploadsHandlers,
});
onMounted(() => {
diff --git a/frontend/app/components/MarkdownEditor/modules/editorCommands.ts b/frontend/app/components/MarkdownEditor/modules/editorCommands.ts
new file mode 100644
index 00000000..e4331930
--- /dev/null
+++ b/frontend/app/components/MarkdownEditor/modules/editorCommands.ts
@@ -0,0 +1,144 @@
+import ImageSelectorModal from '../ImageSelectorModal.vue';
+import GridOrganizationModal from '../GridOrganizationModal.vue';
+import ColorPickerModal from '../ColorPickerModal.vue';
+import type { EditorView } from '@codemirror/view';
+import type { Node } from '~/stores';
+
+export interface CreateCommandsParams {
+ getView: () => EditorView | null;
+ getDoc: () => Node;
+ setDoc: (d: Node) => void;
+ showPreview: { value: boolean };
+ save: () => void;
+}
+
+export function createCommands(params: CreateCommandsParams) {
+ function insertText(text: string) {
+ const view = params.getView();
+ if (!view || !text) return;
+ const state = view.state;
+ const { from, to } = state.selection.main;
+ view.dispatch({
+ changes: { from, to, insert: text },
+ selection: { anchor: from + text.length, head: from + text.length },
+ });
+ view.focus();
+ }
+
+ function openColorModal() {
+ const modalManager = useModal();
+ modalManager.add(new Modal(shallowRef(ColorPickerModal), { props: { onColorSelect: handleColorSelect } }));
+ }
+ function handleColorSelect(color: string) {
+ exec('color', color);
+ }
+ function openImageSelector() {
+ const modalManager = useModal();
+ modalManager.add(new Modal(shallowRef(ImageSelectorModal), { props: { onImageSelect: handleImageSelect }, size: 'large' }));
+ }
+ function openGridOrganization() {
+ const modalManager = useModal();
+ modalManager.add(new Modal(shallowRef(GridOrganizationModal), { props: { onGridSelect: handleGridSelect } }));
+ }
+
+ function handleImageSelect(imageUrl: string, altText: string) {
+ const view = params.getView();
+ if (!view) return;
+ const state = view.state;
+ const { from, to } = state.selection.main;
+ const selectedText = state.sliceDoc(from, to);
+ const alt = selectedText || altText;
+ const insert = `![${alt}](${imageUrl})`;
+ view.dispatch({
+ changes: { from, to, insert },
+ selection: { anchor: from + insert.length, head: from + insert.length },
+ });
+ view.focus();
+ }
+
+ function handleGridSelect(gridMarkdown: string) {
+ const view = params.getView();
+ if (!view) return;
+ const state = view.state;
+ const { from, to } = state.selection.main;
+ view.dispatch({
+ changes: { from, to, insert: gridMarkdown },
+ selection: { anchor: from + gridMarkdown.length, head: from + gridMarkdown.length },
+ });
+ view.focus();
+ }
+
+ function exec(action: string, payload?: string) {
+ if (action === 'preview') return (params.showPreview.value = !params.showPreview.value);
+ if (action === 'openColorPicker') return openColorModal();
+ if (action === 'save') return params.save();
+ if (action === 'goto') {
+ const d = params.getDoc();
+ if (d?.id) return useRouter().push(`/dashboard/docs/${d.id}`);
+ }
+ if (action === 'image') return openImageSelector();
+ if (action === 'gridOrganization') return openGridOrganization();
+ if (action === 'insertText') return insertText(payload || '');
+
+ const view = params.getView();
+ if (!view) return;
+
+ const state = view.state;
+ const { from, to } = state.selection.main;
+ const selectedText = state.sliceDoc(from, to);
+
+ let changes: { from: number; to: number; insert: string } | undefined;
+ let select_from = from + 2;
+ let select_to = to + 2;
+
+ switch (action) {
+ case 'bold':
+ changes = { from, to, insert: `**${selectedText}**` };
+ break;
+ case 'italic':
+ changes = { from, to, insert: `*${selectedText}*` };
+ select_from = from + 1;
+ select_to = select_from + selectedText.length;
+ break;
+ case 'underline':
+ changes = { from, to, insert: `__${selectedText}__` };
+ break;
+ case 'strike':
+ changes = { from, to, insert: `~~${selectedText}~~` };
+ break;
+ case 'link':
+ changes = { from, to, insert: `[](${selectedText})` };
+ select_from = from + 3;
+ select_to = select_from;
+ break;
+ case 'code':
+ changes = { from, to, insert: `\`${selectedText}\`` };
+ break;
+ case 'quote':
+ changes = { from, to, insert: `> ${selectedText}\n` };
+ break;
+ case 'list':
+ changes = { from, to, insert: `- ${selectedText}\n` };
+ break;
+ case 'orderedList':
+ changes = { from, to, insert: `1. ${selectedText}\n` };
+ break;
+ case 'color': {
+ const color = String(payload || '').trim();
+ if (!color) return;
+ const insert = `{color:${color}}(${selectedText})`;
+ changes = { from, to, insert };
+ select_from = insert.indexOf('(') + 1 + from;
+ select_to = select_from + selectedText.length;
+ break;
+ }
+ }
+
+ if (changes) {
+ view.dispatch({ changes, selection: { anchor: select_from, head: select_to } });
+ view.focus();
+ }
+ }
+
+ return { exec, insertText };
+}
diff --git a/frontend/app/components/MarkdownEditor/modules/editorKeymaps.ts b/frontend/app/components/MarkdownEditor/modules/editorKeymaps.ts
new file mode 100644
index 00000000..caf07593
--- /dev/null
+++ b/frontend/app/components/MarkdownEditor/modules/editorKeymaps.ts
@@ -0,0 +1,43 @@
+import { type KeyBinding } from '@codemirror/view';
+
+export function createKeymaps(commands: { exec: (action: string) => void }) {
+ const markdownKeysmap: readonly KeyBinding[] = [
+ {
+ key: 'Mod-b',
+ run: () => {
+ commands.exec('bold');
+ return true;
+ },
+ },
+ {
+ key: 'Mod-i',
+ run: () => {
+ commands.exec('italic');
+ return true;
+ },
+ },
+ {
+ key: 'Mod-u',
+ run: () => {
+ commands.exec('underline');
+ return true;
+ },
+ },
+ {
+ key: 'Mod-e',
+ run: () => {
+ commands.exec('image');
+ return true;
+ },
+ },
+ {
+ key: 'Mod-l',
+ run: () => {
+ commands.exec('link');
+ return true;
+ },
+ },
+ ];
+
+ return markdownKeysmap;
+}
diff --git a/frontend/app/components/MarkdownEditor/modules/editorState.ts b/frontend/app/components/MarkdownEditor/modules/editorState.ts
new file mode 100644
index 00000000..bdb7028c
--- /dev/null
+++ b/frontend/app/components/MarkdownEditor/modules/editorState.ts
@@ -0,0 +1,51 @@
+import { EditorView, keymap, highlightSpecialChars, drawSelection, lineNumbers, type KeyBinding } from '@codemirror/view';
+import { EditorState, Compartment } from '@codemirror/state';
+import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
+import { highlightSelectionMatches, searchKeymap } from '@codemirror/search';
+import { autocompletion } from '@codemirror/autocomplete';
+import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
+
+export interface CreateEditorStateParams {
+ initialDoc: string;
+ preferences: any;
+ themeExtension: any;
+ keymaps: readonly KeyBinding[];
+ snippetSource: any;
+ onDocChanged: () => void;
+ uploadsHandlers: ReturnType<typeof EditorView.domEventHandlers>;
+}
+
+const themeCompartment = new Compartment();
+
+export function createEditorState(params: CreateEditorStateParams) {
+ const updateListener = EditorView.updateListener.of(v => {
+ if (v.docChanged) params.onDocChanged();
+ });
+
+ return EditorState.create({
+ doc: params.initialDoc,
+ extensions: [
+ lineNumbers(),
+ highlightSpecialChars(),
+ history(),
+ drawSelection(),
+ autocompletion(),
+ keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab, ...searchKeymap, ...params.keymaps]),
+ markdown({ base: markdownLanguage }),
+ markdownLanguage.data.of({
+ autocomplete: params.snippetSource,
+ }),
+ updateListener,
+ params.uploadsHandlers,
+ themeCompartment.of(params.themeExtension),
+ highlightSelectionMatches({}),
+ EditorView.lineWrapping,
+ EditorState.allowMultipleSelections.of(true),
+ EditorView.contentAttributes.of({
+ spellcheck: params.preferences.get('editorSpellCheck').value ? 'true' : 'false',
+ autocorrect: 'on',
+ autocapitalize: 'on',
+ }),
+ ],
+ });
+}
diff --git a/frontend/app/components/MarkdownEditor/modules/editorUploads.ts b/frontend/app/components/MarkdownEditor/modules/editorUploads.ts
new file mode 100644
index 00000000..9ee32982
--- /dev/null
+++ b/frontend/app/components/MarkdownEditor/modules/editorUploads.ts
@@ -0,0 +1,45 @@
+import { EditorView } from '@codemirror/view';
+import type { Node } from '~/stores';
+
+interface UploadHandlersParams {
+ resourcesStore: any;
+ CDN: string;
+ insertText: (text: string) => void;
+}
+
+export function createUploadsHandlers({ resourcesStore, CDN, insertText }: UploadHandlersParams) {
+ return EditorView.domEventHandlers({
+ paste: event => {
+ const items = event.clipboardData?.items;
+ if (!items) return;
+ for (const item of items) {
+ if (item.kind === 'file') {
+ const file = item.getAsFile();
+ if (!file) return;
+ const body = new FormData();
+ body.append('file', file);
+ resourcesStore.post(body).then((result: Node) => {
+ const url = `${CDN}/${(result as Node).user_id}/${(result as Node).content_compiled}`;
+ insertText(`![${file.name}](${url})\n`);
+ });
+ }
+ }
+ },
+ drop: event => {
+ const items = event.dataTransfer?.items;
+ if (!items) return;
+ for (const item of items) {
+ if (item.kind === 'file') {
+ const file = item.getAsFile();
+ if (!file) return;
+ const body = new FormData();
+ body.append('file', file);
+ resourcesStore.post(body).then((result: Node) => {
+ const url = `${CDN}/${(result as Node).user_id}/${(result as Node).content_compiled}`;
+ insertText(`![${file.name}](${url})\n`);
+ });
+ }
+ }
+ },
+ });
+}
diff --git a/frontend/app/components/MarkdownEditor/modules/editorUtils.ts b/frontend/app/components/MarkdownEditor/modules/editorUtils.ts
new file mode 100644
index 00000000..18987c16
--- /dev/null
+++ b/frontend/app/components/MarkdownEditor/modules/editorUtils.ts
@@ -0,0 +1,76 @@
+import { snippet, type CompletionContext } from '@codemirror/autocomplete';
+import { katexSnippets } from '../katex-snippets';
+
+function isInsideMath(context: CompletionContext): boolean {
+ const doc = context.state.doc.toString();
+ const pos = context.pos;
+ const len = doc.length;
+ const tokens: { pos: number; type: '$' | '$$' }[] = [];
+
+ for (let i = 0; i < len; i++) {
+ if (doc[i] !== '$') continue;
+ let j = i - 1;
+ let backslashes = 0;
+ while (j >= 0 && doc[j] === '\\') {
+ backslashes++;
+ j--;
+ }
+ if (backslashes % 2 === 1) continue;
+
+ if (i + 1 < len && doc[i + 1] === '$') {
+ tokens.push({ pos: i, type: '$$' });
+ i++;
+ } else {
+ tokens.push({ pos: i, type: '$' });
+ }
+ }
+
+ const blockDollarPositions = tokens.filter(t => t.type === '$$').map(t => t.pos);
+ const blockCountBefore = blockDollarPositions.filter(p => p < pos).length;
+ if (blockCountBefore % 2 === 1) return true;
+
+ const blockIntervals: Array<[number, number]> = [];
+ for (let i = 0; i + 1 < blockDollarPositions.length; i += 2) {
+ const start = blockDollarPositions[i] ?? 0;
+ const end = (blockDollarPositions[i + 1] ?? 0) + 2;
+ blockIntervals.push([start, end]);
+ }
+
+ const inBlock = (p: number) => blockIntervals.some(([s, e]) => p >= s && p < e);
+
+ const singleDollarPositions = tokens.filter(t => t.type === '$' && !inBlock(t.pos)).map(t => t.pos);
+ const singleCountBefore = singleDollarPositions.filter(p => p < pos).length;
+ return singleCountBefore % 2 === 1;
+}
+
+export function createSnippetSource(preferences: any) {
+ return function snippetSource(context: CompletionContext) {
+ if (!preferences.get('editorSnippetsEnabled').value) return null;
+ const allSnippets = preferences.get('snippets').value;
+
+ const word = context.matchBefore(/[\w!:]+/);
+ if (!word && !context.explicit) return null;
+
+ const inMath = isInsideMath(context);
+
+ return {
+ from: word ? word.from : context.pos,
+ options: [
+ ...allSnippets.map((s: any) => ({
+ label: s.id,
+ detail: 'Snippet',
+ type: 'snippet',
+ apply: snippet(s.label),
+ })),
+ ...(inMath
+ ? katexSnippets.map(s => ({
+ label: s.id,
+ detail: 'KaTeX',
+ type: 'snippet',
+ apply: snippet(s.label),
+ }))
+ : []),
+ ],
+ };
+ };
+}