diff --git a/src/editor_helpers.ts b/src/editor_helpers.ts index 27d48df..8bc3b57 100644 --- a/src/editor_helpers.ts +++ b/src/editor_helpers.ts @@ -114,6 +114,31 @@ export function isWithinInlineEquationState(state: EditorState):boolean { } +export function isTouchingInlineEquation(state: EditorState, pos: number):number { + // Returns 0 if pos is not touching a $ that marks an inline equation + // Returns 1 if pos+1 is inside an inline eqn + // Returns -1 if pos-1 is inside an inline eqn + + const tree = syntaxTree(state); + const prevToken = tree.resolveInner(pos-1, 1).name; + const token = tree.resolveInner(pos, 1).name; + const nextToken = tree.resolveInner(pos+1, 1).name; + + if (token.contains("math-end") && !(prevToken.contains("math-end")) && !(nextToken.contains("math-end"))) { + return -1; + } + else if (!(token.contains("math-begin")) && nextToken.contains("math-begin")) { + const nextNextToken = tree.resolveInner(pos+2, 1).name; + + if (!(nextNextToken.contains("math-begin"))) { + return 1; + } + } + + return 0; +} + + export function getEquationBounds(view: EditorView | EditorState, pos?: number):{start: number, end: number} { const s = view instanceof EditorView ? view.state : view; diff --git a/src/inline_math_tooltip.ts b/src/inline_math_tooltip.ts index 9b81ba0..e935967 100644 --- a/src/inline_math_tooltip.ts +++ b/src/inline_math_tooltip.ts @@ -1,6 +1,6 @@ import {Tooltip, showTooltip, EditorView} from "@codemirror/view" import {StateField, EditorState} from "@codemirror/state" -import { getEquationBounds, isWithinEquation, isWithinInlineEquationState } from "./editor_helpers"; +import { getEquationBounds, isTouchingInlineEquation, isWithinEquation, isWithinInlineEquationState } from "./editor_helpers"; import { MarkdownRenderer } from "obsidian"; export const cursorTooltipField = StateField.define({ @@ -17,9 +17,25 @@ export const cursorTooltipField = StateField.define({ function getCursorTooltips(state: EditorState): readonly Tooltip[] { + const isInsideInlineEqn = (isWithinEquation(state) && isWithinInlineEquationState(state)); + let shouldShowTooltip = isInsideInlineEqn; + let isTouchingInlineEqn; + let pos = state.selection.main.from; + + if (!isInsideInlineEqn) { + isTouchingInlineEqn = isTouchingInlineEquation(state, pos - 1); - if (isWithinEquation(state) && isWithinInlineEquationState(state)) { - const bounds = getEquationBounds(state); + if (isTouchingInlineEqn != 0) { + pos += isTouchingInlineEqn; + shouldShowTooltip = true; + } + } + + + + if (shouldShowTooltip) { + + const bounds = getEquationBounds(state, pos); if (!bounds) return []; // Don't render an empty equation