### Basic Snippet Examples Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/README.md Illustrates common text expansions for mathematical expressions. Type the shortcut to get the LaTeX equivalent. ```Markdown - "sqx" instead of "\sqrt{x}" - "a/b" instead of "\frac{a}{b}" - "par x y " instead of "\frac{\partial x}{\partial y}" ``` -------------------------------- ### Display Math Mode Snippet Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/README.md Example of entering display math mode and using a snippet. Pressing Tab after 'x/y' expands it to a fraction. ```Markdown - "xsr" → "x^{2}" - "x/y Tab" → "\frac{x}{y}" - "sin @t" → "\sin \theta" ``` -------------------------------- ### Install and Run Obsidian Latex Suite Plugin Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/CONTRIBUTING.md Instructions for setting up the development environment for the Obsidian Latex Suite plugin. This involves cloning the repository, installing dependencies, and running the development build. ```bash npm install ``` ```bash npm run dev ``` -------------------------------- ### Example Environments Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-environment.md Provides examples of common LaTeX environments used for defining contexts like chemistry, text within math, matrices, and custom chemical notations. ```typescript // Chemistry context (from EXCLUSIONS) { openSymbol: "\\pu{", closeSymbol: "}" } // Text context within math { openSymbol: "\\text{", closeSymbol: "}" } // Array/matrix context { openSymbol: "\\begin{matrix}", closeSymbol: "\\end{matrix}" } // Custom chemical environment { openSymbol: "\\ce{", closeSymbol: "}" } ``` -------------------------------- ### Environment Example Values Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/types.md Provides example values for the Environment interface, demonstrating different delimiter pairs used for LaTeX environments like text and inline math. ```typescript { openSymbol: "\\text{", closeSymbol: "}" } { openSymbol: "\\left(", closeSymbol: "\\right)" } { openSymbol: "$", closeSymbol: "$" } ``` -------------------------------- ### Get Bounds Method Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-context.md Demonstrates how to use the `getBounds()` method to retrieve the boundaries of a math equation or code block at the current cursor position. It shows how to extract the content and access boundary positions for manipulation. ```typescript const ctx = getContextPlugin(view); const bounds = ctx.getBounds(); if (bounds) { const equation = view.state.sliceDoc(bounds.inner_start, bounds.inner_end); console.log("Equation content:", equation); // Can also access positions for manipulation: const outerBounds = { start: bounds.outer_start, end: bounds.outer_end }; } ``` -------------------------------- ### Auto-Fraction Expansion Examples Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/README.md Shows how the auto-fraction feature expands simple fraction notations into LaTeX. ```Markdown - `x/` → `\frac{x}{}` - `(a + b(c + d))/` → `\frac{a + b(c + d)}{}` ``` -------------------------------- ### Default Snippet Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/README.md This is an example of a default snippet configuration. It shows how to define a trigger, replacement text, and options for snippet expansion. ```typescript {trigger: "@l", replacement: "\\lambda", options: "mA"} ``` -------------------------------- ### Example: Checking Math Mode Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-context.md An example demonstrating how to check if the cursor is within a math environment using the `strictlyInMath()` method and how to check for plain text mode. ```typescript const ctx = getContextPlugin(view); if (ctx.mode.strictlyInMath()) { console.log("Cursor is in real math mode"); // Safe to expand math snippets } if (ctx.mode.text) { console.log("Cursor is in plain text"); } ``` -------------------------------- ### Advanced Snippet Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/README.md Demonstrates more complex snippet expansions involving multiple arguments and Tab navigation. ```Markdown - "par Tab f Tab x Tab" → "\frac{\partial f}{\partial x}" - "dint Tab 2pi Tab sin @t Tab @t Tab" → "\int_{0}^{2\]pi} \sin \theta \, d\theta" ``` -------------------------------- ### Bounds Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/types.md An example demonstrating the Bounds interface and its usage for extracting content within delimiters. This snippet shows how to define bounds and use them to slice a document string. ```typescript const bounds: Bounds = { outer_start: 10, // Position of first $ inner_start: 11, // Position after first $ inner_end: 19, // Position before second $ outer_end: 20 // Position after second $ }; // Document slice const equation = doc.sliceDoc(bounds.inner_start, bounds.inner_end); // "equation" ``` -------------------------------- ### CodeMirror 6 Keyboard Format Examples Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/configuration.md Illustrates the standard CodeMirror 6 key format for specifying keyboard triggers in settings. ```string "Tab" - Tab key "Shift-Tab" - Shift + Tab "Ctrl-a" or "Cmd-a" - Ctrl/Cmd + a "Alt-d" - Alt + d "Enter" - Enter key "Backspace" - Backspace key ``` -------------------------------- ### String Snippet Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippets.md Example of a string snippet that expands '/' to a fraction format '\\frac{$0}{$1}'. String snippets are triggered by exact string matches. ```typescript { trigger: "/", replacement: (match: string) => `\\frac{${match}}{$0}$1`, options: "mA" } ``` -------------------------------- ### Visual Snippet Replacement Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippets.md Example of how to use the VISUAL_SNIPPET_MAGIC_SELECTION_PLACEHOLDER in a snippet definition for visual mode. This shows how to wrap selected text with a LaTeX command. ```typescript { trigger: "U", replacement: `\\underbrace{${VISUAL_SNIPPET_MAGIC_SELECTION_PLACEHOLDER}}`, options: "v" // Visual mode } ``` -------------------------------- ### Multiple Tabstops Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Illustrates a string replacement with multiple tabstops ($0, $1, $2). The cursor navigates sequentially through these positions after expansion. ```typescript { trigger: "frac", replacement: "\\frac{$0}{$1}$2", options: "mA" } ``` -------------------------------- ### Snippet Description Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Shows how to add a human-readable description to a snippet, useful for documentation and debugging. ```typescript description?: string ``` ```typescript { trigger: "@a", replacement: "\\alpha", options: "mA", description: "Greek letter alpha" } ``` -------------------------------- ### SnippetVariables Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/types.md An example of how to define a SnippetVariables object, mapping placeholder variables like ${GREEK} and ${TRIG} to their possible substitution values. ```typescript const vars: SnippetVariables = { "${GREEK}": "alpha|beta|gamma", "${TRIG}": "sin|cos|tan" }; ``` -------------------------------- ### Vim Mode Keyboard Format Examples Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/configuration.md Shows the specific keyboard trigger formats used when Vim mode is enabled in the plugin settings. ```string "" - Ctrl + g in Vim "" - Alt + x in Vim "o" - Letter o key ``` -------------------------------- ### Parsing Workflow Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-parsing.md Demonstrates a three-step process for loading and using snippets: loading variables from a file, loading snippets with variable substitution, and then iterating through the parsed snippets to log their details. ```typescript // Step 1: Load snippet variables from file const variablesCode = ` export default { GREEK: "alpha|beta|gamma", SYMBOL: "sum|prod|int" } `; const variables = await parseSnippetVariables(variablesCode, "vars.js"); // Step 2: Load snippets, substituting variables const snippetsCode = ` export default [ { trigger: "@a", replacement: "\\alpha", options: "mA" }, { trigger: /\ ${SYMBOL}/, replacement: "\\$1", options: "mr" } ] `; const snippets = await parseSnippets(snippetsCode, variables, "snippets.js"); // Step 3: Use snippets in editor for (const snippet of snippets) { console.log(snippet.type, snippet.data.trigger, snippet.options); } ``` -------------------------------- ### Snippet Execution Pipeline Architecture Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/README.md Details the sequence of events in the snippet execution pipeline, from keypress to tabstop setup. ```text Keypress → Plugin checks automatic snippets → Match trigger? → Queue change → Call expandSnippets() → Setup tabstops → Await Tab key ``` -------------------------------- ### Example Custom Plugin Settings Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/configuration.md Demonstrates a custom configuration for the Latex Suite plugin, overriding default settings and enabling specific features like continued fractions and conceal mode. ```typescript // Plugin settings file const customSettings = { ...DEFAULT_SETTINGS, autofractionEnabled: true, autofractionSymbol: "\\cfrac", // Use continued fractions autofractionExcludedEnvs: "[ [\"\\pu{\", \"}\"], [\"\\ce{\", \"}\"], [\"\\matrix{\", \"}\"] ]", concealEnabled: true, concealRevealTimeout: 200, mathPreviewEnabled: true, taboutClosingSymbols: "), ], }, \\rangle, \\rbrack" }; ``` -------------------------------- ### Options.fromSource Method Examples Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-options.md Creates an Options instance from option flag characters. Useful for setting multiple options concisely. The 'language' parameter can override the default code mode. ```typescript // Automatic math-mode snippet with word boundary requirement const options = Options.fromSource("mAw"); // Result: automatic=true, regex=false, onWordBoundary=true, // mode.blockMath=true, mode.inlineMath=true // Code block with specific language const codeOptions = Options.fromSource("c", "javascript"); // Result: mode.code="javascript" ``` -------------------------------- ### Get Context Plugin Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-context.md Import and get the context plugin for a CodeMirror view. This is the primary way to access context information. ```typescript import { getContextPlugin } from "src/utils/context"; const ctx = getContextPlugin(view); // Get context for a CodeMirror view ``` -------------------------------- ### String Replacement Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Demonstrates a simple string replacement for a snippet. Supports tabstops like $0 for the primary cursor position and $1, $2 for subsequent navigation. ```typescript { trigger: "@a", replacement: "\\alpha", options: "mA" } ``` ```typescript { trigger: "sqrt", replacement: "\\sqrt{$0}$1", options: "mA" } ``` -------------------------------- ### Regex Snippet Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippets.md Example of a regex snippet that expands '@a' followed by a word boundary to '\\alpha'. Regex snippets are triggered by pattern matching. ```typescript { trigger: /@a\b/, replacement: "\\alpha", options: "mA" } ``` -------------------------------- ### Complete Snippet Expansion Flow Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-management.md Demonstrates the complete flow of queuing and expanding snippets in an editor view. This function checks the context, queues a snippet replacement, and then expands all queued snippets. ```typescript import { EditorView } from "@codemirror/view"; import { getContextPlugin } from "src/utils/context"; import { queueSnippet } from "src/snippets/codemirror/snippet_queue_state_field"; import { expandSnippets } from "src/snippets/snippet_management"; function exampleFeature(view: EditorView): boolean { const ctx = getContextPlugin(view); if (!ctx.mode.strictlyInMath()) { return false; } const from = ctx.pos - 4; // Start of trigger const to = ctx.pos; // End of trigger (current cursor) const replacement = "\\sqrt{$0}$1"; // With tabstops // Step 1: Queue the change queueSnippet(view, from, to, replacement, "t"); // Step 2: Expand all queued snippets const expanded = expandSnippets(view); if (expanded) { // Cursor is now at $0 (first tabstop) // User can press Tab to move to $1 return true; } return false; } ``` -------------------------------- ### Get Plugin Instance and API Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/INDEX.md Retrieve the plugin instance and cast it to the public API type to access its functionalities. ```typescript // Get the plugin instance const plugin = app.plugins.plugins['obsidian-latex-suite']; const api = plugin as LatexSuitePluginPublicApi; // Access editor extensions const extensions = api.editorExtensions; // Disable math mode if needed api.disableMath(view); ``` -------------------------------- ### Visual Snippet Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippets.md Example of a visual snippet that surrounds selected text with \\underbrace. Visual snippets are triggered by selected text and typically use single-character triggers. ```typescript { trigger: "U", replacement: (selection: string) => `\\underbrace{${selection}}` } ``` -------------------------------- ### Using Variables in Snippets Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Demonstrates an attempt to use variables directly in snippet definitions, highlighting the need for proper import or access methods. ```javascript export default [ { trigger: new RegExp(`@(${GREEK})`), // Error: GREEK is not defined replacement: "\\$1", options: "mr" } ]; **Issue:** Variables need to be imported or accessed from the parsed variables. ``` -------------------------------- ### Example of Processed Settings Transformation Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/configuration.md Demonstrates how the `processLatexSuiteSettings` function transforms raw settings, specifically showing the conversion of `autoEnlargeBracketsTriggers` from a comma-separated string to an array with LaTeX commands prefixed. ```typescript const settings = { ...DEFAULT_SETTINGS, autoEnlargeBracketsTriggers: "sum, int" }; const processed = processLatexSuiteSettings(snippets, settings); // Result: autoEnlargeBracketsTriggers = ["\\sum", "\\int"] ``` -------------------------------- ### Snippet Tabstop Syntax Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-management.md Illustrates the syntax for defining tabstops within snippet replacement strings. $0 is the primary tabstop, and $1, $2, etc., are subsequent tabstops. ```typescript { trigger: "frac", replacement: "\\frac{$0}{$1}$2", options: "mA" } // After expansion: // \frac{cursor_here}{} → Tab → \frac{}{cursor_here} → Tab → exit ``` -------------------------------- ### Expand Snippets and Setup Tabstops Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-management.md Applies queued snippet expansions and sets up tabstop navigation. Use this function when snippets need to be processed and the cursor positioned at the first tabstop. ```typescript function expandSnippets(view: EditorView): boolean ``` ```typescript import { expandSnippets } from "src/snippets/snippet_management"; const expanded = expandSnippets(view); if (expanded) { console.log("Snippets expanded successfully"); // Cursor is now at first tabstop ($0) } ``` -------------------------------- ### Snippet Priority Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Demonstrates how to use priority to control which snippet is executed when multiple snippets match the same trigger text. Higher values execute first. ```typescript priority?: number ``` ```typescript // Higher priority version { trigger: "x1", replacement: "x_{1}", options: "m", priority: 10 } // Lower priority fallback { trigger: "x1", replacement: "times 1", options: "m", priority: 0 } // When both match in $x1$, first one (priority 10) is used ``` -------------------------------- ### Snippet Trigger Key Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Illustrates using `triggerKey` to define an alternative keyboard shortcut for expanding a snippet, bypassing standard text triggering. ```typescript triggerKey?: string ``` ```typescript { trigger: "pal", replacement: "\\partial", options: "m", triggerKey: "Alt-p" } // Instead of typing "pal" + Tab, user presses Alt+p // Place cursor where the snippet should expand // Press Alt+p to expand ``` -------------------------------- ### Example User Notification for Snippet Loading Failure Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/errors.md Illustrates how a user-facing notice is displayed when snippets fail to load from settings. This provides immediate feedback to the user about the issue. ```typescript new Notice(`Failed to load snippets from settings: Syntax error on line 5`); ``` -------------------------------- ### Visual Snippet for Underlining Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md A visual snippet example using the 'v' flag for visual mode, which triggers on selected text. The replacement function wraps the selection. ```typescript { trigger: "U", replacement: (sel) => `\\underbrace{${sel}}`, options: "v" } ``` -------------------------------- ### String Trigger Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Defines a snippet with a simple string trigger. The trigger is matched exactly as written, is case-sensitive, and can include special characters. ```typescript { trigger: "sqrt", replacement: "\\sqrt{$0}$1", options: "mA" } ``` -------------------------------- ### Create Custom String Snippet Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippets.md Example of creating a custom string snippet. This snippet expands 'sqrt' to '\sqrt{}' and is configured to trigger in math mode and expand automatically. ```typescript import { StringSnippet, Options } from "obsidian-latex-suite/snippets"; // Create a snippet that expands "sqrt" to "\\sqrt{}" const sqrtSnippet = new StringSnippet( "sqrt", // trigger "\\sqrt{$0}$1", // replacement with tabstop $0 and exit point $1 Options.fromSource("mA"), // math mode, automatic 10, // priority "Square root snippet" // description ); // The snippet will: // - Only trigger in math mode (m flag) // - Expand automatically when "sqrt" is typed (A flag) // - Place the cursor at $0 (inside braces) // - Allow exiting to $1 (after braces) with Tab ``` -------------------------------- ### Define a Custom Snippet Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/INDEX.md This JavaScript example shows how to define a custom snippet in the plugin settings. It includes a trigger, replacement string with cursor positioning, and options for math mode and automatic expansion. ```javascript // In plugin settings > Snippets > Edit Snippets export default [ { trigger: "sqrt", replacement: "\\sqrt{$0}$1", options: "mA" // Math mode, automatic } ]; // Now typing "sqrt" in math mode automatically expands to \sqrt{cursor_here} // Press Tab to exit the braces ``` -------------------------------- ### Snippet Configuration with Recursion Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-management.md Example of configuring snippets with recursion enabled. This allows nested snippet expansions, where typing a trigger within a tabstop of another snippet can cause further expansion. ```typescript // With recursion enabled { trigger: "frac", replacement: "\\frac{$0}{$1}$2", options: "mA", priority: 10 } { trigger: "sqrt", replacement: "\\sqrt{$0}$1", options: "mA", priority: 5 } // User types "sqrt" in math // Expands to \sqrt{} // At $0, user types "frac" // If recursion >= 1, expands to \sqrt{\\frac{}{}} ``` -------------------------------- ### Physics Snippets Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Define snippets for physics notations like integrals and derivatives. The 'mA' option indicates that the replacement should be treated as a macro and that the cursor should be placed at the start of the replacement. ```javascript export default [ { trigger: "integral", replacement: "\\int_{$0}^{$1} $2 \\, d$3$4", options: "mA", description: "Integral with limits" }, { trigger: "deriv", replacement: "\\frac{d$0}{d$1}$2", options: "mA", description: "Derivative" } ]; ``` -------------------------------- ### Snippet Regex Flags Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Explains the use of the `flags` property for regular expression snippets to control matching behavior like case-insensitivity or multiline matching. ```typescript flags?: string ``` ```typescript { trigger: /ALPHA/, replacement: "\\alpha", options: "mr", flags: "i" // Case-insensitive, so /alpha/, /ALPHA/, /Alpha/ all match } ``` -------------------------------- ### Using Context in a Feature Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-context.md Demonstrates how to retrieve and use context information within a custom editor feature. This includes checking the current mode, getting equation boundaries, and verifying if the cursor is within a specific environment. Requires importing `EditorView` and `getContextPlugin`. ```typescript import { EditorView } from "@codemirror/view"; import { getContextPlugin } from "src/utils/context"; function myFeature(view: EditorView): boolean { // Get current context const ctx = getContextPlugin(view); // Check what mode we're in if (!ctx.mode.strictlyInMath()) { return false; // Not in math mode } // Get equation boundaries const bounds = ctx.getBounds(); if (!bounds) { return false; // Not in an equation } // Get the equation content const equation = view.state.sliceDoc(bounds.inner_start, bounds.inner_end); console.log("Current equation:", equation); // Check if in excluded environment const chemEnv = ctx.isWithinEnvironment(ctx.pos, { openSymbol: "\\ce{", closeSymbol: "}" }); if (chemEnv) { return false; // Don't run in chemistry environments } // Feature logic here... return true; } ``` -------------------------------- ### Automatic Math Mode Snippet with Word Boundary Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md An example of a snippet configured for automatic expansion in math mode, triggered only on word boundaries. Flags include 'm' (math), 'A' (automatic), and 'w' (word boundary). ```typescript { trigger: "alpha", replacement: "\\alpha", options: "mAw" } ``` -------------------------------- ### Example Error Output for Erring Snippet Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/errors.md Illustrates the typical error message format when a snippet fails to parse, including the specific error details and the serialized offending snippet. This helps in debugging individual snippet issues. ```text Invalid snippet trigger: Must be a string or RegExp Erroring snippet: {trigger:123,replacement:"\\alpha",options:"m"} ``` -------------------------------- ### ProcessSnippetResult Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/types.md An example of a ProcessSnippetResult object, illustrating a snippet match at a specific position and its corresponding replacement. This result indicates that the snippet matched at position 100 and should be replaced with 'x_{1}', including text up to position 102. ```typescript // Snippet matching "x1" at position 100, replacing to position 102 { triggerPos: 100, replacement: "x_{1}", triggerEndPos: 102 } ``` -------------------------------- ### Configuration and Settings Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/README.md Reference for all plugin settings, including types, defaults, and processing functions. ```APIDOC ## Configuration and Settings ### Description This section provides a comprehensive reference for all configurable settings within the Obsidian LaTeX Suite plugin. It details the structure of settings types, default values, and the function used to process these settings. ### Settings Types - **LatexSuitePluginSettings**: The main type for all plugin settings. - **LatexSuiteBasicSettings**: Basic settings for the plugin. - **LatexSuiteCMKeymapSettings**: Settings related to CodeMirror keymaps. - **LatexSuiteRawSettings**: Raw settings before processing. - **LatexSuiteCMSettings**: Processed settings for CodeMirror integration. ### Functions - **processLatexSuiteSettings(rawSettings)**: Processes raw settings into a usable format. ### Keyboard Format Reference Details on the format for defining keyboard shortcuts and keymaps. ### JSON Format Settings Information on configuring settings using JSON, including environments, symbols, and languages. ``` -------------------------------- ### Context-Aware Features Architecture Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/README.md Illustrates the flow for context-aware features, from checking context to executing changes. ```text Feature checks context → Mode valid? → Bounds available? → Environment excluded? → Execute → Queue changes → Expand ``` -------------------------------- ### File Structure Overview Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/INDEX.md A hierarchical view of the Obsidian Latex Suite plugin's source code directories and key files. ```bash obsidian-latex-suite/ ├── src/ │ ├── main.ts # Plugin entry point │ ├── api.d.ts # Public API interface │ ├── latex_suite.ts # Event handling & keybindings │ ├── snippets/ # Snippet system │ │ ├── snippets.ts # Snippet classes │ │ ├── parse.ts # Snippet parsing │ │ ├── options.ts # Options & Mode classes │ │ ├── environment.ts # Environment definitions │ │ └── ... │ ├── features/ # Plugin features │ │ ├── run_snippets.ts │ │ ├── autofraction.ts │ │ ├── tabout.ts │ │ └── ... │ ├── settings/ # Settings system │ │ ├── settings.ts # Settings types │ │ └── settings_tab.ts # Settings UI │ ├── utils/ # Utilities │ │ ├── context.ts # Context plugin │ │ ├── editor_utils.ts # Editor helpers │ │ └── ... │ └── editor_extensions/ # CodeMirror extensions │ ├── conceal.ts │ ├── highlight_brackets.ts │ └── ... ├── package.json ├── tsconfig.json └── manifest.json ``` -------------------------------- ### Get Context Plugin Instance Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-context.md Retrieves the context plugin instance for a given CodeMirror view. It can be initialized automatically or on demand. ```typescript import { getContextPlugin } from "src/utils/context"; const view = editor.cm; // CodeMirror view const ctx = getContextPlugin(view); // Get context for this view ``` ```typescript // Get context and run init (recommended) const ctx = getContextPlugin(view); // init=true (default) // Get context without init (for performance-critical code) const ctx = getContextPlugin(view, false); // init=false ``` -------------------------------- ### JSON Format for autofractionExcludedEnvs Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/configuration.md Example of the JSON array format used for `autofractionExcludedEnvs`, where each element is a pair of opening and closing symbols. ```json [ ["\\pu{", "}"], ["\\ce{", "}"], ["^{", "}"] ] ``` -------------------------------- ### Mode.inEquation Method Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-options.md Checks if the cursor is inside an equation bounded by $ or $$ delimiters. Returns true if 'inlineMath' or 'blockMath' is true. ```typescript const mode = new Mode(); mode.inlineMath = true; console.log(mode.inEquation()); // true mode.inlineMath = false; mode.codeMath = true; console.log(mode.inEquation()); // false ``` -------------------------------- ### Snippet Trigger After Regex Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Demonstrates using `triggerAfter` with a regular expression to define a more complex lookahead condition for snippet triggering. ```typescript triggerAfter?: string | RegExp ``` ```typescript { trigger: /x/, replacement: "\\times", options: "mr", triggerAfter: /[+\\-]/ } // Matches "x+" or "x-" but not "xy" ``` -------------------------------- ### Snippet Trigger After String Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Shows how to use `triggerAfter` with a string to ensure a snippet only triggers if followed by specific text, like a space. ```typescript triggerAfter?: string | RegExp ``` ```typescript { trigger: "x", replacement: "\\times", options: "m", triggerAfter: " " } // Only matches "x " (x followed by space) // "xy" won't trigger this snippet ``` -------------------------------- ### Tabstop Insertion in Replacement Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/README.md Demonstrates how to use tabstops within the `replacement` string of a snippet. '$0', '$1', etc., define positions where the cursor will jump after expansion. ```plaintext Insert **tabstops** for the cursor to jump to by writing "$0", "$1", etc. in the `replacement`. ``` -------------------------------- ### Snippet Language Specificity Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Demonstrates how to restrict a snippet to only trigger within specific code block languages using the `language` property. ```typescript language?: string ``` ```typescript { trigger: "sqrt", replacement: "Math.sqrt", options: "c", language: "javascript" } // Only triggers in ```javascript code blocks ``` -------------------------------- ### Snippet Options Explanation Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/README.md Illustrates the various options available for configuring snippet behavior, such as mode (text, math, block math, inline math, code), expansion timing (auto, tab), and special behaviors (regex, visual, word boundary, skip undo). ```plaintext - `t` : Text mode. Only run this snippet outside math - `m` : Math mode. Only run this snippet inside math. Shorthand for both `M` and `n` - `M` : Block math mode. Only run this snippet inside a `$$ ... $$` block - `n` : Inline math mode. Only run this snippet inside a `$ ... $` block - `A` : Auto. Expand this snippet as soon as the trigger is typed. If omitted, the Tab key must be pressed to expand the snippet. This doesn't always work for [IME keyboards](./DOCS.md@IME-keyboards) (like chinese/pinyin, gboard, german/french diacritic keyboards). - `r` : [Regex](./DOCS.md#regex-snippets). The `trigger` will be treated as a regular expression - `v` : [Visual](./DOCS.md#visual-snippets). Only run this snippet on a selection. The trigger should be a single character - `w` : Word boundary. Only run this snippet when the trigger is preceded (and followed by) a word delimiter, such as `.`, `,`, or `-` - `c` : Code mode. Only run this snippet inside a ```` ``` ... ``` ```` block - `U`: Skip undo. When an automatic snippet expands, pressing undo returns to the state before the trigger key was typed, instead of first removing the snippet and reinserting that key. ``` -------------------------------- ### TabstopSpec Type Definition Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-management.md Defines the internal representation of a tabstop position, including its start and end points in the document and its group for simultaneous jumps. ```typescript type TabstopSpec = { from: number; // Start position of tabstop in document to: number; // End position of tabstop group: number; // Tabstop group (for multi-cursor jumps) } ``` -------------------------------- ### Create Options from Source String Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-options.md Use `Options.fromSource` to configure snippet behavior based on mode and expansion type. This allows for fine-grained control over when and how snippets are triggered. ```typescript import { Options, Mode } from "obsidian-latex-suite"; // Snippet that expands "\frac{x}{y}" with Tab, only in math mode const options = Options.fromSource("m"); // Math mode only // Result: // - mode: Math mode (inline and block) // - automatic: false (requires Tab key) // - regex: false (string trigger) // - onWordBoundary: false // - visual: false // - undoKey: true // Snippet that auto-expands in text mode with word boundary const autoTextOptions = Options.fromSource("tAw"); // Result: // - mode: Text mode only // - automatic: true (expands on keypress) // - onWordBoundary: true (only match after delimiters) // Snippet for Python code blocks const pythonOptions = Options.fromSource("c", "python"); // Result: // - mode.code: "python" // - automatic: false ``` -------------------------------- ### Mode Class Default Constructor Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-options.md Creates a new Mode instance with all modes disabled. Use this as a starting point for custom mode configurations. ```typescript constructor() { text: false, // Not in plain text blockMath: false, // Not in block math ($$ $$) inlineMath: false, // Not in inline math ($ $) code: false, // Not in code block textEnv: false // Not in \text{} or similar } ``` -------------------------------- ### Mark Transaction with Temporary Keypress Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-management.md Example of dispatching a transaction with the temporary keypress annotation. This is useful for marking changes that should not be processed by certain editor extensions. ```typescript // Mark a transaction as temporary keypress view.dispatch({ changes: {...}, annotations: [tempKeyPress.of(true)] }); ``` -------------------------------- ### Mode.fromSource Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-options.md Creates a Mode instance from a string of option flag characters and an optional language identifier. This allows for flexible configuration of snippet contexts. ```APIDOC ## Mode.fromSource ### Description Creates a Mode instance from option flag characters. ### Method `static fromSource(source: string, language?: string): Mode` ### Parameters #### Path Parameters - **source** (string) - Required - Mode flag characters: "t", "m", "M", "n", "c" - **language** (string) - Optional - Code language (sets mode.code to this value) ### Return Type `Mode` ### Flag Behavior | Flag | Effect | |------|--------| | t | Sets text=true | | m | Sets blockMath=true, inlineMath=true | | M | Sets blockMath=true | | n | Sets inlineMath=true | | c | Sets code=true | | language param | Sets code=language (overrides "c" flag) | ### Default Behavior If no flags are provided and language is undefined, inverts all defaults to create a "catch-all" mode (triggers everywhere). ### Example ```typescript // Only in math mode const mathMode = Mode.fromSource("m"); // Result: blockMath=true, inlineMath=true, text=false // Only in text mode const textMode = Mode.fromSource("t"); // Result: text=true, blockMath=false, inlineMath=false // In JavaScript code blocks const codeMode = Mode.fromSource("c", "javascript"); // Result: code="javascript" // No flags: triggers everywhere const catchAll = Mode.fromSource(""); // Result: All modes inverted, triggers everywhere ``` ``` -------------------------------- ### Settings Processing Architecture Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/README.md Outlines the process of converting raw settings into processed configurations and registering them with CodeMirror. ```text Raw Settings (strings) → Parse/Convert → Processed Settings (arrays/sets) → Generate CodeMirror extensions → Register with Obsidian ``` -------------------------------- ### Context and Environment Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/README.md APIs for accessing and manipulating the editor's context, including cursor position, bounds, and environment detection. ```APIDOC ## Context and Environment ### Description Provides interfaces and methods for understanding and interacting with the editor's current state, such as cursor position, text boundaries, and whether the cursor is within a specific environment. ### Interfaces - **Context**: Represents the editor state plugin, providing methods for context checking. - **Bounds**: Defines the boundaries of a text selection or element. ### Constants - **EXCLUSIONS**: A constant list of elements or contexts to be excluded from certain operations. ### Methods - **Context.isWithinEnvironment(environmentName)**: Checks if the current cursor is within a specified environment. - **Context.getBounds()**: Retrieves the boundaries of the current selection or cursor. - **Context.getInnerBounds()**: Retrieves the inner boundaries of the current selection. - **Context.isWithinEnvironment()**: Checks if the current cursor is within any recognized environment. - **Context.disableMath()**: Disables math rendering for the current context. - **getContextPlugin()**: Access function to retrieve the Context plugin instance. ``` -------------------------------- ### SelectionRange Interface Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/types.md Represents a selection or cursor position within a CodeMirror editor. It includes start and end points, anchor, head, and an empty flag. ```typescript interface SelectionRange { from: number; // Start of selection (or cursor position) to: number; // End of selection (or cursor position) empty: boolean; // True if from === to (no selection) anchor: number; // Anchor point of selection head: number; // Head point of selection } ``` -------------------------------- ### Catching Plugin Initialization Errors Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/errors.md Use a try-catch block to handle potential errors during the initialization of the context plugin. ```typescript try { const ctx = getContextPlugin(view); } catch (e) { console.error("Plugin initialization failed:", e); // Handle gracefully } ``` -------------------------------- ### Enable All Features Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-features.md Enables all LaTeX Suite features, including snippets, auto-fraction, matrix shortcuts, tabout, and auto-enlarge brackets. ```APIDOC ## Enable All Features ### Description Enables all LaTeX Suite features. ### Details - Snippets - Auto-fraction - Matrix shortcuts - Tabout - Auto-enlarge brackets ``` -------------------------------- ### Regex Trigger Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Defines a snippet using a regular expression for the trigger. Requires the 'r' flag in options and supports capture groups for dynamic replacements. ```typescript { trigger: /x(\d)/, replacement: "x_{$1}", options: "mr", flags: "g" } ``` -------------------------------- ### Mode.inMath Method Example Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-options.md Checks if the cursor is in any math mode, including equations and forced-math code blocks. Returns true if 'inlineMath', 'blockMath', or 'codeMath' is true. ```typescript const mode = new Mode(); mode.blockMath = true; console.log(mode.inMath()); // true mode.blockMath = false; mode.codeMath = true; console.log(mode.inMath()); // true ``` -------------------------------- ### runAutoFraction Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-features.md Expands the "/" key into a "\frac{numerator}{denominator}" LaTeX pattern. It intelligently finds the numerator by parsing backward from the cursor, handles nested parentheses, and auto-enlarges brackets. It also creates tabstops for cursor placement. ```APIDOC ## runAutoFraction ### Description Expands the "/" key into a "\frac{numerator}{denominator}" LaTeX pattern. It intelligently finds the numerator by parsing backward from the cursor, handles nested parentheses, and auto-enlarges brackets. It also creates tabstops for cursor placement. ### Function Signature ```typescript function runAutoFraction( view: EditorView, ctx: Context ): boolean ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |-----------|------|-------------| | view | EditorView | The CodeMirror editor view | | ctx | Context | Current editor context with cursor position | ### Details - Runs for all cursors in the current selection - Only triggers in math mode (checked via context) - Skips expansion if cursor is in excluded environment (e.g., \pu{}) - Intelligently finds numerator by parsing backward from cursor - Handles nested parentheses correctly - Auto-enlarges brackets after expansion - Creates tabstops for cursor placement ### Numerator Detection Scans backward from cursor to find the numerator, stopping at: - Space or newline - Math delimiter ($, {, [, () - Configured breaking characters (default: "+-=\t") ### Example ```typescript // In math mode: $x + 1/ // Pressing / (with runAutoFraction enabled) produces: // $\frac{x + 1}{cursor_here} // With selection: select "x+1" then press / // Produces: $\frac{x + 1}{cursor_here} // In nested parentheses: $(a + b(c + d))/` // Produces: $\frac{a + b(c + d)}{cursor_here} ``` ### Configuration - `autofractionEnabled`: Enable/disable feature - `autofractionSymbol`: LaTeX command (\frac, \dfrac, \cfrac, etc.) - `autofractionBreakingChars`: Characters that end numerator scanning - `autofractionExcludedEnvs`: Environments where not to trigger ### Return Type `boolean` - True if auto-fraction expanded, false otherwise. ### Response #### Success Response (200) `boolean` - True if auto-fraction expanded, false otherwise. #### Response Example `true` or `false` ``` -------------------------------- ### Quantum State Snippet with Tabstops Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/DOCS.md A snippet for inserting a quantum state notation, using tabstops for cursor positioning and placeholders. ```typescript {trigger: "outp", replacement: "\\ket{$0:\psi}} \\bra{$0:\psi}} $1", options: "mA"} ``` -------------------------------- ### Using isWithinEnvironment to Check Context Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-environment.md Demonstrates how to use the isWithinEnvironment method to determine if a cursor is within specific text or math environments and log the enclosed content and boundaries. ```typescript import { getContextPlugin } from "src/utils/context"; const ctx = getContextPlugin(view); const envs = [ { openSymbol: "\\text{", closeSymbol: "}" }, { openSymbol: "\\mathrm{", closeSymbol: "}" } ]; const result = ctx.isWithinEnvironment(cursorPos, envs); if (result) { console.log("Inside environment, text content:", view.state.sliceDoc(result.inner_start, result.inner_end)); console.log("Bounds:", { outer: [result.outer_start, result.outer_end], inner: [result.inner_start, result.inner_end] }); } else { console.log("Not inside any specified environment"); } ``` -------------------------------- ### Advanced Snippet File Format with All Features Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippet-definitions.md Illustrates a comprehensive snippet definition file including various features like regex triggers, function replacements, visual snippets, tabstops, and language-specific snippets. ```javascript export default [ // Simple string snippet { trigger: "@a", replacement: "\\alpha", options: "mA", description: "Greek letter alpha", priority: 10 }, // Regex snippet with function replacement { trigger: /x(\d)/, replacement: (match) => `x_{${match[1]}}`, options: "mr", flags: "g", description: "Subscript: x1 -> x_1", priority: 5 }, // Visual snippet { trigger: "U", replacement: (selection) => `\\underbrace{${selection}}`, options: "v", description: "Underbrace selected text" }, // Snippet with multiple tabstops { trigger: "frac", replacement: "\\frac{$0}{$1}$2", options: "mA", description: "Fraction with two arguments" }, // Code block snippet { trigger: "sqrt", replacement: "Math.sqrt", options: "c", language: "javascript", description: "Square root in JavaScript" } ]; ``` -------------------------------- ### LatexSuitePluginPublicApi Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/README.md Provides the main public API for the LatexSuitePlugin. Includes access to editor extensions and methods to control math rendering. ```APIDOC ## LatexSuitePluginPublicApi ### Description This interface exposes the core functionalities of the Obsidian LaTeX Suite plugin to external systems or advanced users. ### Properties - **editorExtensions** (Extension[]) - An array of CodeMirror editor extensions provided by the plugin. - **disableMath** (function) - A method to disable math rendering within the editor. ### Methods - **disableMath()**: Disables math rendering. ``` -------------------------------- ### Enable All Features Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-features.md Enables all LaTeX Suite features including snippets, auto-fraction, matrix shortcuts, tabout, and auto-enlarge brackets. ```typescript function enableAllFeatures() { // Enables all features } ``` -------------------------------- ### Math Mode Snippet with Tabstop Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/DOCS.md A snippet for inserting a fraction in math mode, using tabstops for cursor placement and placeholders. ```typescript {trigger: "//", replacement: "\\frac{$0}{$1}$2", options: "mA"} ``` -------------------------------- ### getKeymaps Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-features.md Generates CodeMirror key bindings for enabled LaTeX Suite features based on the provided settings. The order of generated bindings is significant. ```APIDOC ## getKeymaps ### Description Generates CodeMirror key bindings for LaTeX Suite features. ### Parameters #### Path Parameters - **settings** (LatexSuiteCMSettings) - Required - Current plugin settings ### Return Type `LatexSuiteKeyBinding[]` - Array of CodeMirror key bindings ### Details - Creates key bindings for all enabled features - Order matters: bindings are checked in order - All bindings scoped to "latex-suite" scope ### Bindings Generated 1. Auto-delete $ (if autoDelete$ enabled) 2. Snippet triggers (based on snippetsTrigger and triggerKey) 3. Tabstop navigation (next/previous) 4. Auto-fraction trigger (if enabled) 5. Matrix shortcuts (if enabled) - placed before tabout 6. Tabout shortcuts (if enabled) ### Example ```typescript const keymaps = getKeymaps(settings); // Returns array of { key, run, scope: "latex-suite" } objects // Example entry: // { key: "Tab", run: (view) => runSnippets(...), scope: "latex-suite" } ``` ``` -------------------------------- ### Bounds Interface Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/types.md Represents the start and end positions within a document, defining the boundaries of a math region or code block. It specifies both inner and outer limits relative to delimiters. ```typescript interface Bounds { inner_start: number; // Position after opening delimiter inner_end: number; // Position before closing delimiter outer_start: number; // Position at opening delimiter outer_end: number; // Position at closing delimiter } ``` -------------------------------- ### Snippet Constructor Source: https://github.com/artisticat1/obsidian-latex-suite/blob/main/_autodocs/api-reference-snippets.md Defines the parameters for initializing a snippet, including its type, trigger, replacement, options, priority, description, excluded environments, and trigger key. ```typescript constructor( type: T, trigger: SnippetData["trigger"], replacement: SnippetData["replacement"], options: Options, priority?: number, description?: string, excludedEnvironments?: Environment[], triggerKey?: string ) ```