From bd30332a8b432922553d724c67dbbf3654022ada Mon Sep 17 00:00:00 2001 From: Michael Naumov Date: Wed, 13 Nov 2024 20:19:10 -0600 Subject: [PATCH] Add replaceCodeBlock --- src/obsidian/MarkdownCodeBlockProcessor.ts | 31 +++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/obsidian/MarkdownCodeBlockProcessor.ts b/src/obsidian/MarkdownCodeBlockProcessor.ts index ea1ce42..55c5bcd 100644 --- a/src/obsidian/MarkdownCodeBlockProcessor.ts +++ b/src/obsidian/MarkdownCodeBlockProcessor.ts @@ -3,11 +3,18 @@ * This module provides utility functions for processing code blocks in Obsidian. */ -import type { MarkdownPostProcessorContext } from 'obsidian'; +import type { + App, + MarkdownPostProcessorContext +} from 'obsidian'; import { parse } from 'shell-quote'; +import type { ValueProvider } from '../ValueProvider.ts'; + import { throwExpression } from '../Error.ts'; +import { resolveValue } from '../ValueProvider.ts'; +import { process } from './Vault.ts'; /** * Retrieves the argument of a code block from the given MarkdownPostProcessorContext and HTMLElement. @@ -29,3 +36,25 @@ export function getCodeBlockArguments(ctx: MarkdownPostProcessorContext, el: HTM } return parse(match[1] ?? '').map(String); } + +/** + * Replaces the code block. + * + * @param app - The Obsidian App object. + * @param ctx - The MarkdownPostProcessorContext object. + * @param el - The HTMLElement representing the code block. + * @param codeBlockProvider - The ValueProvider that provides the new code block. + */ +export async function replaceCodeBlock(app: App, ctx: MarkdownPostProcessorContext, el: HTMLElement, codeBlockProvider: ValueProvider): Promise { + const sectionInfo = ctx.getSectionInfo(el); + if (!sectionInfo) { + return; + } + const lines = sectionInfo.text.split('\n'); + const prefix = lines.slice(0, sectionInfo.lineStart).join('\n'); + const oldCodeBlock = lines.slice(sectionInfo.lineStart, sectionInfo.lineEnd + 1).join('\n'); + const suffix = lines.slice(sectionInfo.lineEnd + 1).join('\n'); + const newCodeBlock = await resolveValue(codeBlockProvider, oldCodeBlock); + const newSectionText = prefix + '\n' + newCodeBlock + (newCodeBlock ? '\n' : '') + suffix; + await process(app, ctx.sourcePath, (content) => content.replace(sectionInfo.text, newSectionText)); +}