diff --git a/src/converters/MarkdownPreprocessor.ts b/src/converters/MarkdownPreprocessor.ts index 8d9f54b..45c0926 100644 --- a/src/converters/MarkdownPreprocessor.ts +++ b/src/converters/MarkdownPreprocessor.ts @@ -8,6 +8,7 @@ import { WikilinkProcessor, WikilinkConfig, WikilinkProcessorConfig } from './pr import { EmbedProcessor, EmbedProcessorConfig } from './preprocessors/EmbedProcessor'; import { CalloutProcessor } from './preprocessors/CalloutProcessor'; import { MetadataExtractor } from './preprocessors/MetadataExtractor'; +import { HorizontalRuleProcessor } from './preprocessors/HorizontalRuleProcessor'; export interface PreprocessorOptions { /** Preserve existing frontmatter */ @@ -75,6 +76,7 @@ export class MarkdownPreprocessor { private options: PreprocessorOptions; private wikilinkConfig: WikilinkConfig; private noteTitle?: string; + private horizontalRuleProcessor: HorizontalRuleProcessor; private frontmatterProcessor: FrontmatterProcessor; private wikilinkProcessor: WikilinkProcessor; private embedProcessor: EmbedProcessor; @@ -86,6 +88,8 @@ export class MarkdownPreprocessor { this.wikilinkConfig = config.wikilinkConfig; this.noteTitle = config.noteTitle; + this.horizontalRuleProcessor = new HorizontalRuleProcessor(); + const frontmatterConfig: FrontmatterProcessorConfig = { noteTitle: this.noteTitle, preserveFrontmatter: this.options.preserveFrontmatter, @@ -123,22 +127,25 @@ export class MarkdownPreprocessor { }; try { - // Step 1: Extract and process frontmatter first (always process for metadata extraction) + // Step 1: Process horizontal rules to avoid YAML delimiter conflicts + result.content = this.horizontalRuleProcessor.process(result.content); + + // Step 2: Extract and process frontmatter (always process for metadata extraction) result.content = this.frontmatterProcessor.processFrontmatter(result.content, result); - // Step 2: Convert email blocks to Typst format + // Step 3: Convert email blocks to Typst format result.content = this.calloutProcessor.processEmailBlocks(result.content, result); - // Step 3: Filter out unnecessary links (Open: links and Mail.app links) + // Step 4: Filter out unnecessary links (Open: links and Mail.app links) result.content = this.calloutProcessor.filterUnnecessaryLinks(result.content, result); - // Step 4: Convert embeds FIRST (before wikilinks to avoid .md extension being added) + // Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added) result.content = this.embedProcessor.processEmbeds(result.content, result); - // Step 5: Convert wikilinks (after embeds are processed) + // Step 6: Convert wikilinks (after embeds are processed) result.content = this.wikilinkProcessor.processWikilinks(result.content, result); - // Step 6: Convert callouts + // Step 7: Convert callouts result.content = this.calloutProcessor.processCallouts(result.content, result); // Extract title from content if not available from frontmatter diff --git a/src/converters/PandocTypstConverter.ts b/src/converters/PandocTypstConverter.ts index 9f3570a..625c224 100644 --- a/src/converters/PandocTypstConverter.ts +++ b/src/converters/PandocTypstConverter.ts @@ -94,42 +94,42 @@ export class PandocTypstConverter { * Convert markdown content to PDF */ async convertMarkdownToPDF( - content: string, - outputPath: string, - options: Partial = {}, - progressCallback?: ProgressCallback - ): Promise { + content: string, + outputPath: string, + options: Partial = {}, + progressCallback?: ProgressCallback +): Promise { + try { + progressCallback?.('Preparing markdown content...', 10); + + // Create temporary markdown file + await this.ensureTempDirectory(); + const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`); + + await fsPromises.writeFile(tempInputPath, content, 'utf-8'); + + // Merge options + this.pandocOptions = { ...this.pandocOptions, ...options }; + + // Convert using the file-based method + const result = await this.convertToPDF(tempInputPath, outputPath, progressCallback); + + // Cleanup temp file try { - progressCallback?.('Preparing markdown content...', 10); - - // Create temporary markdown file - await this.ensureTempDirectory(); - const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`); - - await fsPromises.writeFile(tempInputPath, content, 'utf-8'); - - // Merge options - this.pandocOptions = { ...this.pandocOptions, ...options }; - - // Convert using the file-based method - const result = await this.convertToPDF(tempInputPath, outputPath, progressCallback); - - // Cleanup temp file - try { - await fsPromises.unlink(tempInputPath); - } catch (error) { - console.warn('Failed to cleanup temp file:', error); - } - - return result; + await fsPromises.unlink(tempInputPath); } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - return { - success: false, - error: `Conversion failed: ${errorMessage}` - }; + console.warn('Failed to cleanup temp file:', error); } + + return result; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + return { + success: false, + error: `Conversion failed: ${errorMessage}` + }; } +} /** * Set up cleanup handlers for temporary files diff --git a/src/converters/preprocessors/FrontmatterProcessor.ts b/src/converters/preprocessors/FrontmatterProcessor.ts index 665904a..f7733de 100644 --- a/src/converters/preprocessors/FrontmatterProcessor.ts +++ b/src/converters/preprocessors/FrontmatterProcessor.ts @@ -27,188 +27,220 @@ export class FrontmatterProcessor { * Process frontmatter using the gray-matter library approach */ public processFrontmatter(content: string, result: PreprocessingResult): string { - try { - // Use gray-matter for robust frontmatter parsing - const matter = require('gray-matter'); - const parsed = matter(content); - - if (parsed.data && Object.keys(parsed.data).length > 0) { - // Replace frontmatter title with filename if noteTitle is provided - if (this.noteTitle) { - const frontmatterCopy = { ...parsed.data }; - frontmatterCopy.title = this.noteTitle; - result.metadata.frontmatter = frontmatterCopy; - } else { - result.metadata.frontmatter = parsed.data; - } - - // Extract tags from frontmatter if they exist - if (parsed.data.tags) { - let frontmatterTags: string[] = []; - - if (Array.isArray(parsed.data.tags)) { - // Handle array of tags - frontmatterTags = parsed.data.tags - .map((tag: unknown) => typeof tag === 'string' ? tag : String(tag)) - .filter((tag: string) => tag.trim() !== ''); - } else if (typeof parsed.data.tags === 'string') { - // Handle comma-separated string or single tag - frontmatterTags = parsed.data.tags - .split(/[,\s]+/) - .map((tag: string) => tag.trim()) - .filter((tag: string) => tag !== ''); - } - - // Merge with existing tags (avoid duplicates) - for (const tag of frontmatterTags) { - if (!result.metadata.tags.includes(tag)) { - result.metadata.tags.push(tag); - } - } - } - - // Extract title - use noteTitle if available, otherwise frontmatter title - if (this.noteTitle) { - result.metadata.title = this.noteTitle; - } else if (parsed.data.title && typeof parsed.data.title === 'string') { - result.metadata.title = parsed.data.title.trim(); - } - - // Handle frontmatter preservation and display options - const finalFrontmatter = this.noteTitle ? - { ...parsed.data, title: this.noteTitle } : - parsed.data; - - if (this.preserveFrontmatter) { - // Keep the frontmatter in the content, but reconstruct it with the modified title - const yaml = require('js-yaml'); - const newFrontmatter = yaml.dump(finalFrontmatter); - let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`; - - // Add printed frontmatter if requested - if (this.printFrontmatter) { - const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter); - processedContent = `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n${parsed.content}`; - } - - return processedContent; - } else { - // Return content without frontmatter, but add title as frontmatter for Pandoc - let processedContent: string; - if (this.noteTitle) { - const yaml = require('js-yaml'); - const titleFrontmatter = yaml.dump({ title: this.noteTitle }); - processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`; - } else { - processedContent = parsed.content; - } - - // Add printed frontmatter if requested - if (this.printFrontmatter) { - const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter); - // Insert after the title frontmatter but before content - const lines = processedContent.split('\n'); - if (lines[0] === '---' && lines.findIndex(line => line === '---') > 0) { - const endIndex = lines.findIndex((line, i) => i > 0 && line === '---'); - lines.splice(endIndex + 1, 0, '', frontmatterDisplay, ''); - processedContent = lines.join('\n'); - } else { - processedContent = `${frontmatterDisplay}\n\n${processedContent}`; - } - } - - return processedContent; - } + try { + // Check if content actually has frontmatter before trying to parse + if (!this.FRONTMATTER_PATTERN.test(content)) { + // No frontmatter found - add title frontmatter if we have a noteTitle + if (this.noteTitle) { + const yaml = require('js-yaml'); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + result.metadata.title = this.noteTitle; + result.metadata.frontmatter = { title: this.noteTitle }; + return `---\n${titleFrontmatter}---\n${content}`; } else { - // No frontmatter found - add title frontmatter if we have a noteTitle + return content; + } + } + + // Use gray-matter for robust frontmatter parsing + const matter = require('gray-matter'); + + // Add debugging to see what's being parsed + console.log('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected'); + console.log('First 200 chars:', content.substring(0, 200)); + + const parsed = matter(content); + + if (parsed.data && Object.keys(parsed.data).length > 0) { + // Replace frontmatter title with filename if noteTitle is provided + if (this.noteTitle) { + const frontmatterCopy = { ...parsed.data }; + frontmatterCopy.title = this.noteTitle; + result.metadata.frontmatter = frontmatterCopy; + } else { + result.metadata.frontmatter = parsed.data; + } + + // Extract tags from frontmatter if they exist + if (parsed.data.tags) { + let frontmatterTags: string[] = []; + + if (Array.isArray(parsed.data.tags)) { + // Handle array of tags + frontmatterTags = parsed.data.tags + .map((tag: unknown) => typeof tag === 'string' ? tag : String(tag)) + .filter((tag: string) => tag.trim() !== ''); + } else if (typeof parsed.data.tags === 'string') { + // Handle comma-separated string or single tag + frontmatterTags = parsed.data.tags + .split(/[,\s]+/) + .map((tag: string) => tag.trim()) + .filter((tag: string) => tag !== ''); + } + + // Merge with existing tags (avoid duplicates) + for (const tag of frontmatterTags) { + if (!result.metadata.tags.includes(tag)) { + result.metadata.tags.push(tag); + } + } + } + + // Extract title - use noteTitle if available, otherwise frontmatter title + if (this.noteTitle) { + result.metadata.title = this.noteTitle; + } else if (parsed.data.title && typeof parsed.data.title === 'string') { + result.metadata.title = parsed.data.title.trim(); + } + + // Handle frontmatter preservation and display options + const finalFrontmatter = this.noteTitle ? + { ...parsed.data, title: this.noteTitle } : + parsed.data; + + if (this.preserveFrontmatter) { + // Keep the frontmatter in the content, but reconstruct it with the modified title + const yaml = require('js-yaml'); + const newFrontmatter = yaml.dump(finalFrontmatter); + let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`; + + // Add printed frontmatter if requested + if (this.printFrontmatter) { + const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter); + processedContent = `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n${parsed.content}`; + } + + return processedContent; + } else { + // Return content without frontmatter, but add title as frontmatter for Pandoc + let processedContent: string; if (this.noteTitle) { const yaml = require('js-yaml'); const titleFrontmatter = yaml.dump({ title: this.noteTitle }); - return `---\n${titleFrontmatter}---\n${content}`; + processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`; } else { - return content; + processedContent = parsed.content; } - } - } catch (error: unknown) { - const errorMessage = error instanceof Error ? error.message : String(error); - result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`); - - // Fallback to simple regex-based parsing - const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN); - - if (frontmatterMatch) { - try { - const yamlContent = frontmatterMatch[1]; - const frontmatter: Record = {}; - - const lines = yamlContent.split('\n'); - for (const line of lines) { - const colonIndex = line.indexOf(':'); - if (colonIndex > 0) { - const key = line.substring(0, colonIndex).trim(); - const value = line.substring(colonIndex + 1).trim(); - const cleanValue = value.replace(/^["']|["']$/g, ''); - frontmatter[key] = cleanValue; - } - } - - // Replace title with noteTitle if provided - if (this.noteTitle) { - frontmatter.title = this.noteTitle; - } - - result.metadata.frontmatter = frontmatter; - - if (this.preserveFrontmatter) { - // Reconstruct frontmatter with modified title - if (this.noteTitle) { - const yaml = require('js-yaml'); - const newFrontmatter = yaml.dump(frontmatter); - let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`); - - // Add printed frontmatter if requested - if (this.printFrontmatter) { - const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter); - processedContent = processedContent.replace( - this.FRONTMATTER_PATTERN, - `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n` - ); - } - - return processedContent; - } else { - return content; - } + + // Add printed frontmatter if requested + if (this.printFrontmatter) { + const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter); + // Insert after the title frontmatter but before content + const lines = processedContent.split('\n'); + if (lines[0] === '---' && lines.findIndex(line => line === '---') > 0) { + const endIndex = lines.findIndex((line, i) => i > 0 && line === '---'); + lines.splice(endIndex + 1, 0, '', frontmatterDisplay, ''); + processedContent = lines.join('\n'); } else { - // Add title as frontmatter for Pandoc even when not preserving original - if (this.noteTitle) { - const yaml = require('js-yaml'); - const titleFrontmatter = yaml.dump({ title: this.noteTitle }); - let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`); - - // Add printed frontmatter if requested - if (this.printFrontmatter) { - const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter); - processedContent = processedContent.replace( - this.FRONTMATTER_PATTERN, - `---\n${titleFrontmatter}---\n\n${frontmatterDisplay}\n\n` - ); - } - - return processedContent; - } else { - return content.replace(this.FRONTMATTER_PATTERN, ''); - } + processedContent = `${frontmatterDisplay}\n\n${processedContent}`; } - } catch (fallbackError: unknown) { - const fallbackErrorMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError); - result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackErrorMessage}`); } + + return processedContent; + } + } else { + // No frontmatter found - add title frontmatter if we have a noteTitle + if (this.noteTitle) { + const yaml = require('js-yaml'); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + result.metadata.title = this.noteTitle; + result.metadata.frontmatter = { title: this.noteTitle }; + return `---\n${titleFrontmatter}---\n${content}`; + } else { + return content; } - - return content; } + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); + console.log('FrontmatterProcessor: gray-matter failed with error:', errorMessage); + console.log('Content being parsed (first 500 chars):', content.substring(0, 500)); + result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`); + + // Fallback to simple regex-based parsing + const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN); + + if (frontmatterMatch) { + try { + const yamlContent = frontmatterMatch[1]; + const frontmatter: Record = {}; + + const lines = yamlContent.split('\n'); + for (const line of lines) { + const colonIndex = line.indexOf(':'); + if (colonIndex > 0) { + const key = line.substring(0, colonIndex).trim(); + const value = line.substring(colonIndex + 1).trim(); + const cleanValue = value.replace(/^["']|["']$/g, ''); + frontmatter[key] = cleanValue; + } + } + + // Replace title with noteTitle if provided + if (this.noteTitle) { + frontmatter.title = this.noteTitle; + } + + result.metadata.frontmatter = frontmatter; + + if (this.preserveFrontmatter) { + // Reconstruct frontmatter with modified title + if (this.noteTitle) { + const yaml = require('js-yaml'); + const newFrontmatter = yaml.dump(frontmatter); + let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`); + + // Add printed frontmatter if requested + if (this.printFrontmatter) { + const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter); + processedContent = processedContent.replace( + this.FRONTMATTER_PATTERN, + `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n` + ); + } + + return processedContent; + } else { + return content; + } + } else { + // Add title as frontmatter for Pandoc even when not preserving original + if (this.noteTitle) { + const yaml = require('js-yaml'); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`); + + // Add printed frontmatter if requested + if (this.printFrontmatter) { + const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter); + processedContent = processedContent.replace( + this.FRONTMATTER_PATTERN, + `---\n${titleFrontmatter}---\n\n${frontmatterDisplay}\n\n` + ); + } + + return processedContent; + } else { + return content.replace(this.FRONTMATTER_PATTERN, ''); + } + } + } catch (fallbackError: unknown) { + const fallbackErrorMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError); + result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackErrorMessage}`); + } + } else { + // No frontmatter pattern found, but gray-matter failed - treat as file without frontmatter + if (this.noteTitle) { + const yaml = require('js-yaml'); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + result.metadata.title = this.noteTitle; + result.metadata.frontmatter = { title: this.noteTitle }; + return `---\n${titleFrontmatter}---\n${content}`; + } + } + + return content; } +} /** * Format frontmatter as a readable display block diff --git a/src/converters/preprocessors/HorizontalRuleProcessor.ts b/src/converters/preprocessors/HorizontalRuleProcessor.ts new file mode 100644 index 0000000..b6977b1 --- /dev/null +++ b/src/converters/preprocessors/HorizontalRuleProcessor.ts @@ -0,0 +1,77 @@ +/** + * Processes horizontal rules to avoid conflicts with YAML frontmatter delimiters + * + * Transforms markdown horizontal rules that could be mistaken for YAML delimiters + * into alternative formats that Pandoc will still recognize as horizontal rules + * but won't interpret as YAML frontmatter boundaries. + * + * Preserves YAML frontmatter sections by detecting and skipping them. + */ +export class HorizontalRuleProcessor { + private readonly FRONTMATTER_PATTERN = /^---\s*\n([\s\S]*?)\n---\s*\n/; + + constructor() { + // No initialization needed + } + + /** + * Process horizontal rules to avoid YAML conflicts + * + * Transforms: + * - `---` (3 dashes) -> `***` (3 asterisks) + * - `----` (4+ dashes) -> `****` (4+ asterisks) + * + * Both formats are valid markdown horizontal rules but `***` won't be + * mistaken for YAML delimiters by Pandoc. + * + * Skips YAML frontmatter sections to preserve them. + */ + process(content: string): string { + // Check if content has frontmatter at the beginning + const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN); + + if (frontmatterMatch) { + // Content has frontmatter - separate it from the main content + const frontmatter = frontmatterMatch[0]; + const mainContent = content.slice(frontmatter.length); + + // Process only the main content (after frontmatter) + const processedMainContent = this.processContentLines(mainContent); + + // Recombine frontmatter with processed main content + return frontmatter + processedMainContent; + } else { + // No frontmatter - process the entire content + return this.processContentLines(content); + } + } + + /** + * Process lines for horizontal rule transformation + */ + private processContentLines(content: string): string { + // Split content into lines for processing + const lines = content.split('\n'); + const processedLines: string[] = []; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Check if line is a horizontal rule made of dashes + // Must be at least 3 dashes, optionally with spaces + const dashRuleMatch = line.match(/^(\s*)(---+)(\s*)$/); + + if (dashRuleMatch) { + // Transform dash horizontal rule to asterisk horizontal rule + const [, leadingSpaces, dashes, trailingSpaces] = dashRuleMatch; + const asterisks = '*'.repeat(dashes.length); + processedLines.push(`${leadingSpaces}${asterisks}${trailingSpaces}`); + } else { + // Keep line unchanged + processedLines.push(line); + } + } + + return processedLines.join('\n'); + } +} \ No newline at end of file diff --git a/templates/article.typ b/templates/article.typ index 5e36380..5b73c11 100644 --- a/templates/article.typ +++ b/templates/article.typ @@ -1,3 +1,6 @@ +// Horizontal rule definition for Pandoc compatibility +#let horizontalrule = line(start: (25%,0%), end: (75%,0%)) + // Email block styling function #let email-block(from: none, to: none, subject: none, date: none, body) = { block( diff --git a/templates/default.typ b/templates/default.typ index b704522..5f4ede7 100644 --- a/templates/default.typ +++ b/templates/default.typ @@ -1,3 +1,6 @@ +// Horizontal rule definition for Pandoc compatibility +#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%))) + // Email block styling function #let email-block(from: none, to: none, subject: none, date: none, body) = { block( diff --git a/templates/modern.typ b/templates/modern.typ index 9c7d25f..9007b2c 100644 --- a/templates/modern.typ +++ b/templates/modern.typ @@ -1,3 +1,6 @@ +// Horizontal rule definition for Pandoc compatibility +#let horizontalrule = line(start: (25%,0%), end: (75%,0%)) + // Email block styling function - compact for single page #let email-block(from: none, to: none, subject: none, date: none, body) = { block( diff --git a/templates/report.typ b/templates/report.typ index 78bd84c..906bf28 100644 --- a/templates/report.typ +++ b/templates/report.typ @@ -1,3 +1,6 @@ +// Horizontal rule definition for Pandoc compatibility +#let horizontalrule = line(start: (25%,0%), end: (75%,0%)) + // Email block styling function #let email-block(from: none, to: none, subject: none, date: none, body) = { block( diff --git a/templates/universal-wrapper.pandoc.typ b/templates/universal-wrapper.pandoc.typ index f2588ea..4b4dbce 100644 --- a/templates/universal-wrapper.pandoc.typ +++ b/templates/universal-wrapper.pandoc.typ @@ -1,7 +1,7 @@ // Universal Pandoc wrapper for all Typst templates // This wrapper handles Pandoc's variable substitution and passes them to the actual Typst template -#import "$template_path$": conf, email-block +#import "$template_path$": conf, email-block, horizontalrule #show: doc => conf( $if(title)$title: [$title$],$else$title: none,$endif$