I’m trying to create a simple Obsidian plugin that would display a preview when editing inline LaTeX equations in Live Preview mode: namely it should render a full math block beneath any inline equation editing field that currently contains the cursor within it.
I do so by creating a state field which on update()
does the following: iterate over all nodes in the transaction’s state, and whenever a pair of matching formatting-math
elements is found (begin
and end
), if they represent an inline equation (as opposed to a block equation), create a new Decoration.widget
based on a WidgetType
object with the math
and block
attributes set. The code can be found here: main.ts
(GitHub link).
Admittedly, it sort of works, i.e. when the plugin is active and there are inline equations present in the currently opened note, I can move the cursor inside one of them and see the preview rendered beneath it, as in the screenshot:
However, it comes with a bunch of issues:
- The preview does not appear if there’s anything else on the line, besides the inline equation itself.
- When editing the contents of an inline equation, the cursor may jump a few characters backwards on each update (e.g. after each keypress), with no apparent pattern to it; using
Backspace
may remove more than one character, and the shift selection (Shift
+ arrows) does not work at all. - The preview does not update dynamically while editing an inline equation. Only moving the cursor outside of it and then coming back updates the preview.
- Although I explicitly set the
block
attribute of the newly createdWidgetType
object to betrue
, the preview does not appear as a block equation preview: namely, it is not centered on the page and does not have any padding around it. - The development console log outputs the following
Uncaught TypeError
’s when moving the cursor within an inline equation:
this.widget.toDOM is not a function
Cannot read properties of undefined (reading 'dom')
Cannot read properties of null (reading 'getBoundingClientRect')
So there is totally something wrong with my code, but with the little knowledge I have of TypeScript and CodeMirror, I’m completely unable to even guess what might cause the issue. Any advice or guidance would be greatly appreciated!
Steps to reproduce:
- Download files from the GitHub Repository.
- Put them into a folder inside of the
.obsidian/plugins
directory. - Run
$ npm install ; npm run dev
inside of that folder. - Enable the “Aberone’s Sample Plugin” plugin in Obsidian settings.
- Write down an inline equation and try the aforementioned actions.
Alternatively, instead of copying all the files from my GitHub repository, you may download the Obsidian Sample Plugin and replace the contents of the original main.ts
file with the contents of my plugin’s main.ts
file.