Skip to content

Commit

Permalink
Add replaceCodeBlock
Browse files Browse the repository at this point in the history
  • Loading branch information
mnaoumov committed Nov 14, 2024
1 parent c11b743 commit bd30332
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/obsidian/MarkdownCodeBlockProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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<string, [string]>): Promise<void> {
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));
}

0 comments on commit bd30332

Please sign in to comment.