Saving changes in codeblock post-processor?

Hi,

I want to implement a kind of table using registerMarkdownCodeBlockProcessor. I was following the example from Markdown post processing | Obsidian Plugin Developer Docs which shows how to implement a viewer for a csv-code block:

import { Plugin } from "obsidian";

export default class ExamplePlugin extends Plugin {
  async onload() {
    this.registerMarkdownCodeBlockProcessor("csv", (source, el, ctx) => {
      const rows = source.split("\n").filter((row) => row.length > 0);

      const table = el.createEl("table");
      const body = table.createEl("tbody");

      for (let i = 0; i < rows.length; i++) {
        const cols = rows[i].split(",");

        const row = body.createEl("tr");

        for (let j = 0; j < cols.length; j++) {
          row.createEl("td", { text: cols[j] });
        }
      }
    });
  }
}

What I want to do is, to allow individual numbers in that table to be changed. After creating the individual cells, I could add an input element with the number in it:

let inputel = row.createEl("input", {attr: {value: cols[j]}});
inputel.oninput = (ev) => {
     // How do I save this back to the original code-block stored in source?
}

But then, is there any way to save that input back to the original code-cell?

Thanks for any pointers!

I found a way accessing the editor field through the active view. Basically, I extract the line I am currently in, replace the cell I was editing, and save it back:

// view contains the editor to change the markdown
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
// the context contains the begin and end of the block in the markdown file
const sec = ctx.getSectionInfo(ctx.el);
const lineno = sec?.lineStart+(i+1);
let line = view?.editor.getLine(lineno).split(",");
line[j]=ev.currentTarget.value;
view?.editor.setLine(lineno, line?.join(","));

Not sure if that’s the best way, though?

1 Like