14 Commits
Author SHA1 Message Date
AlexKucera bc836ae56b Merge branch 'release/1.0.2' 2025-09-08 11:03:12 +02:00
Jarvis c9f36648d6 1.1.0 2025-09-08 11:00:43 +02:00
Jarvis 6a00786227 docs: prepare release 1.1.0 documentation
- Update CHANGELOG.md with comprehensive 1.1.0 release notes
- Add Generic File Embedding feature to Key Features in README.md
- Document all major fixes and improvements since 1.0.1

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-08 11:00:30 +02:00
AlexKucera c0b45979eb Merge branch 'hotfix/dependency_fix' 2025-09-08 10:56:27 +02:00
AlexKucera 2fea3fdff3 Merge branch 'hotfix/dependency_fix' into develop 2025-09-08 10:56:27 +02:00
AlexKucera cd3ce0ec89 Add guidance.md to .gitignore
Excludes local guidance documentation from version control

Prevents potential sensitive or personal guidance notes from being tracked in the repository
2025-09-08 10:56:00 +02:00
Jarvis 8879f40be5 fix: update ImageMagick to use 'magick' instead of deprecated 'convert'
- Update default ImageMagick executable from 'convert' to 'magick' in constants
- Remove deprecated 'convert' subcommand from ImageMagick spawn calls
- Update UI labels and settings descriptions to reflect 'magick' command
- Fix pdf2img PATH environment to include Node.js installation paths

This resolves ImageMagick v7 deprecation warning and fixes pdf2img execution
failure caused by missing Node.js in PATH. The 'convert' command was deprecated
in ImageMagick v7 in favor of the unified 'magick' command.

Fixes: "env: node: No such file or directory" error in pdf2img execution

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-08 10:55:27 +02:00
Jarvis 1b36ebb705 fix(core): enhance dependency checker with comprehensive path resolution
- Add support for user-configured additionalPaths in dependency checking
- Implement comprehensive default system paths (home-relative and absolute)
- Update path resolution to handle both full paths and bare executable names
- Use 'which' command fallback with augmented PATH for executable discovery
- Ensure consistent path handling across sync and async dependency methods

This resolves issues where executables installed in common locations like
/opt/homebrew/bin were not found when executable path settings were empty.
The plugin now searches standard package manager installation directories
by default while respecting user-configured additional paths.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-08 10:32:16 +02:00
Jarvis a1380d88a0 fix: address Obsidian Review Bot feedback for plugin submission
- Replace hardcoded '.obsidian' paths with Vault#configDir for proper config directory support
- Move inline styles to CSS classes for better theme compatibility
- Remove unnecessary type casting by using proper type predicates
- Add proper TypeScript type narrowing for filtered arrays

This addresses all required issues identified by the Obsidian Review Bot:
* TempDirectoryManager now accepts configDir parameter from app.vault.configDir
* PdfToImageConverter uses configDir instead of hardcoded '.obsidian'
* ExportConfigModal uses CSS classes (.export-progress-visible, .export-form-hidden) instead of inline styles
* Progress bar width controlled via CSS custom property --progress-width
* Removed 'as TFile[]' casting by implementing isMarkdownFile type predicate

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-06 23:10:31 +02:00
AlexKucera 20e8c0ccf9 Merge branch 'feature/generic_embed' into develop 2025-09-05 18:32:35 +02:00
AlexKucera 31cbb0010e Merge branch 'develop' into feature/generic_embed 2025-09-05 18:03:49 +02:00
AlexKucera a37aef183c Merge branch 'master' into develop 2025-09-05 18:03:38 +02:00
AlexKucera 5f92a07a75 Merge branch 'hotfix/font_caching' into develop 2025-09-05 17:57:13 +02:00
AlexKucera 05f28f84f3 Add Generic File embedding 2025-09-05 17:41:18 +02:00
20 changed files with 657 additions and 71 deletions

No files matched your search

+2
View File
@@ -68,3 +68,5 @@ temp-pandoc/*
typst2pdf-icon.afdesign
CLAUDE.md
repomix-output.xml
guidance.md
+17
View File
@@ -5,6 +5,23 @@ All notable changes to the Obsidian Typst PDF Export plugin will be documented i
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.1.0]
### Added
- **Generic File Embedding**: Added support for embedding any file type as attachments in the output PDF
- **Comprehensive Dependency Discovery**: Enhanced dependency checker to automatically find executables in common installation locations including Homebrew, Cargo, npm-global, and system directories
- **Smart Path Resolution**: Added intelligent path resolution that handles both full paths and bare executable names with fallback to `which` command
### Fixed
- **ImageMagick Compatibility**: Updated to use `magick` command instead of deprecated `convert` command for ImageMagick v7 compatibility
- **PDF Conversion PATH Issues**: Fixed pdf2img execution failures by ensuring Node.js paths are included in the execution environment
- **Dependency Checker Robustness**: Improved executable discovery to work with user-configured additional paths and system installations
- **Obsidian Plugin Store Compatibility**: Addressed feedback from Obsidian Review Bot for plugin submission requirements
### Changed
- **Default ImageMagick Command**: Changed from `convert` to `magick` in default settings and UI labels
- **Path Environment Handling**: Enhanced PATH augmentation to include comprehensive system and package manager locations
## [1.0.1]
### Fixed
+1
View File
@@ -28,6 +28,7 @@ Export Obsidian notes to PDF using the Typst typesetting system. Supports custom
- **🎨 Multiple Templates**: Choose from built-in templates (default, modern, article, report) or create custom ones
- **📁 Batch Export**: Export entire folders of notes with a single click
- **🖼️ Media Support**: Smart handling of embedded images and PDFs
- **📎 File Embedding**: Embed any file type as attachments in the output PDF
- **⚡ Real-time Progress**: Visual progress tracking with cancellation support
- **🔧 Advanced Configuration**: Comprehensive export options including typography, layout, and behavior settings
- **🔍 Font Discovery**: Automatic system font detection and caching
+285 -19
View File
@@ -44,6 +44,11 @@ export class obsidianTypstPDFExport extends Plugin {
templateManager: TemplateManager;
private embeddedTemplateManager: EmbeddedTemplateManager;
private currentExportController: AbortController | null = null;
// Type predicate to filter for markdown TFiles
private isMarkdownFile(file: TAbstractFile): file is TFile {
return file instanceof TFile && file.extension === 'md';
}
async onload() {
await this.loadSettings();
@@ -65,8 +70,11 @@ export class obsidianTypstPDFExport extends Plugin {
new Notice(`Error extracting templates: ${error.message}`);
}
// Initialize components
this.converter = new PandocTypstConverter(this);
// Initialize components with executable paths from settings
this.converter = new PandocTypstConverter(this, {
pandocPath: this.settings.pandocPath,
typstPath: this.settings.typstPath
});
this.templateManager = new TemplateManager(this);
// Register custom icon
@@ -99,6 +107,42 @@ export class obsidianTypstPDFExport extends Plugin {
this.cacheAvailableFonts();
}
/**
* Resolve an executable path, handling empty settings by falling back to system search
*/
private resolveExecutablePath(userPath: string | undefined, defaultName: string): string {
// If user provided a path and it's not empty, use it
if (userPath && userPath.trim() !== '') {
return userPath;
}
// Try to find the executable using which command
const { spawnSync } = require('child_process');
try {
const augmentedEnv = {
...process.env,
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
};
const result = spawnSync('which', [defaultName], {
encoding: 'utf8',
env: augmentedEnv
});
if (result.status === 0 && result.stdout) {
const foundPath = result.stdout.trim();
if (foundPath) {
return foundPath;
}
}
} catch {
// Ignore errors from which command
}
// Fall back to the default name (will be found via PATH if available)
return defaultName;
}
/**
* Cache available fonts from typst to a file for quick access
*/
@@ -106,7 +150,7 @@ export class obsidianTypstPDFExport extends Plugin {
try {
const { spawn } = require('child_process');
const typstPath = this.settings.typstPath || 'typst';
const typstPath = this.resolveExecutablePath(this.settings.typstPath, 'typst');
// Use spawn instead of exec for security - arguments passed separately
const stdout = await new Promise<string>((resolve, reject) => {
@@ -196,7 +240,8 @@ export class obsidianTypstPDFExport extends Plugin {
// Check if cache is older than 24 hours or typst path changed
const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000;
const pathChanged = cacheData.typstPath !== (this.settings.typstPath || 'typst');
const resolvedTypstPath = this.resolveExecutablePath(this.settings.typstPath, 'typst');
const pathChanged = cacheData.typstPath !== resolvedTypstPath;
if (isStale || pathChanged) {
// Refresh cache in background
@@ -278,9 +323,7 @@ export class obsidianTypstPDFExport extends Plugin {
this.registerEvent(
this.app.workspace.on('files-menu', (menu: Menu, files: TAbstractFile[]) => {
// Filter for markdown files only
const markdownFiles = files.filter(file =>
file instanceof TFile && file.extension === 'md'
) as TFile[];
const markdownFiles = files.filter(this.isMarkdownFile);
if (markdownFiles.length > 0) {
menu.addItem((item) => {
@@ -478,7 +521,7 @@ export class obsidianTypstPDFExport extends Plugin {
try {
// Create temp directory for conversion
const tempManager = new TempDirectoryManager({ vaultPath: vaultPath });
const tempManager = new TempDirectoryManager({ vaultPath: vaultPath, configDir: this.app.vault.configDir });
const tempDir = tempManager.ensureTempDir('pandoc');
// Load file content
@@ -529,6 +572,12 @@ export class obsidianTypstPDFExport extends Plugin {
await this.processImageEmbeds(processedResult, vaultPath, tempDir, file);
}
// Process file embeds if any were found
if (processedResult.metadata.fileEmbeds && processedResult.metadata.fileEmbeds.length > 0) {
const embedAllFiles = config.embedAllFiles ?? this.settings.behavior.embedAllFiles;
await this.processFileEmbeds(processedResult, vaultPath, tempDir, file, embedAllFiles);
}
// Prepare output path
const outputPath = await this.prepareOutputPath(file, config.outputFolder || this.settings.outputFolder);
@@ -578,7 +627,7 @@ export class obsidianTypstPDFExport extends Plugin {
// Clean up temporary directories
try {
const cleanupManager = TempDirectoryManager.create(vaultPath);
const cleanupManager = TempDirectoryManager.create(vaultPath, this.app.vault.configDir);
cleanupManager.cleanupAllTempDirs();
} catch (cleanupError) {
console.warn('Export: Failed to clean up temporary directories:', cleanupError);
@@ -644,9 +693,7 @@ export class obsidianTypstPDFExport extends Plugin {
*/
private async handleFolderExport(folder: TFolder): Promise<void> {
// Get all markdown files in the folder
const markdownFiles = folder.children.filter(
(file) => file instanceof TFile && file.extension === 'md'
) as TFile[];
const markdownFiles = folder.children.filter(this.isMarkdownFile);
if (markdownFiles.length === 0) {
new Notice('No markdown files found in this folder');
@@ -676,7 +723,8 @@ export class obsidianTypstPDFExport extends Plugin {
const dependencyResult = await DependencyChecker.checkAllDependencies(
this.settings.pandocPath,
this.settings.typstPath,
this.settings.executablePaths?.imagemagickPath
this.settings.executablePaths?.imagemagickPath,
this.settings.executablePaths?.additionalPaths || []
);
const formatVersion = (dep: any) => dep.isAvailable ? (dep.version || 'Available') : 'Not found';
@@ -699,7 +747,8 @@ ${dependencyResult.allAvailable
const missingDeps = DependencyChecker.checkDependenciesSync(
this.settings.pandocPath,
this.settings.typstPath,
this.settings.executablePaths?.imagemagickPath
this.settings.executablePaths?.imagemagickPath,
this.settings.executablePaths?.additionalPaths || []
);
// Only show notice if dependencies are missing
@@ -828,6 +877,154 @@ ${dependencyResult.allAvailable
return content.filter(line => line !== null).join('\n');
}
/**
* Generate file embed content with proper Typst pdf.embed syntax
*/
private generateFileEmbedContent(
relativeFilePath: string,
baseName: string,
fileExtension: string,
errorSuffix?: string
): string {
const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
const mimeType = this.getMimeTypeFromExtension(fileExtension);
const fileIcon = this.getFileTypeIcon(fileExtension);
const content = [];
// Add file embed using Typst's pdf.embed
content.push('```{=typst}');
content.push(`#pdf.embed("${relativeFilePath}", description: "${description}", mime-type: "${mimeType}")`);
content.push('```');
content.push('');
content.push(`*File attached: ${fileIcon} ${description} - check your PDF reader's attachment panel*`);
return content.filter(line => line !== null).join('\n');
}
/**
* Get MIME type from file extension
*/
private getMimeTypeFromExtension(extension: string): string {
const mimeTypes: Record<string, string> = {
// Office documents
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.xls': 'application/vnd.ms-excel',
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'.ppt': 'application/vnd.ms-powerpoint',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.doc': 'application/msword',
// Open Document Format
'.odt': 'application/vnd.oasis.opendocument.text',
'.ods': 'application/vnd.oasis.opendocument.spreadsheet',
'.odp': 'application/vnd.oasis.opendocument.presentation',
// Archives
'.zip': 'application/zip',
'.rar': 'application/vnd.rar',
'.7z': 'application/x-7z-compressed',
'.tar': 'application/x-tar',
'.gz': 'application/gzip',
'.bz2': 'application/x-bzip2',
// Text/data formats
'.json': 'application/json',
'.xml': 'application/xml',
'.csv': 'text/csv',
'.yaml': 'text/yaml',
'.yml': 'text/yaml',
'.toml': 'text/plain',
'.txt': 'text/plain',
'.md': 'text/markdown',
'.rtf': 'application/rtf',
// Code files
'.js': 'text/javascript',
'.ts': 'text/typescript',
'.py': 'text/x-python',
'.java': 'text/x-java-source',
'.cpp': 'text/x-c++src',
'.c': 'text/x-csrc',
'.h': 'text/x-chdr',
'.css': 'text/css',
'.html': 'text/html',
'.php': 'text/x-php',
// Database files
'.db': 'application/x-sqlite3',
'.sqlite': 'application/x-sqlite3',
'.sql': 'application/sql',
// E-books
'.epub': 'application/epub+zip',
'.mobi': 'application/x-mobipocket-ebook',
// Other formats
'.ics': 'text/calendar',
'.vcf': 'text/vcard',
'.log': 'text/plain'
};
return mimeTypes[extension.toLowerCase()] || 'application/octet-stream';
}
/**
* Get appropriate icon for file type
*/
private getFileTypeIcon(extension: string): string {
const iconMap: Record<string, string> = {
// Office documents
'.xlsx': '📊', '.xls': '📊',
'.pptx': '📽️', '.ppt': '📽️',
'.docx': '📄', '.doc': '📄',
// Open Document
'.odt': '📄', '.ods': '📊', '.odp': '📽️',
// Archives
'.zip': '📦', '.rar': '📦', '.7z': '📦', '.tar': '📦', '.gz': '📦', '.bz2': '📦',
// Text/data
'.json': '🗃️', '.xml': '🗃️', '.csv': '📊', '.yaml': '⚙️', '.yml': '⚙️',
'.toml': '⚙️', '.txt': '📄', '.md': '📝', '.rtf': '📄',
// Code files
'.js': '💻', '.ts': '💻', '.py': '🐍', '.java': '☕', '.cpp': '💻', '.c': '💻',
'.h': '💻', '.css': '🎨', '.html': '🌐', '.php': '💻',
// Database
'.db': '🗄️', '.sqlite': '🗄️', '.sql': '🗄️',
// E-books
'.epub': '📖', '.mobi': '📖',
// Other
'.ics': '📅', '.vcf': '👤', '.log': '📋'
};
return iconMap[extension.toLowerCase()] || '📎';
}
/**
* Resolve file path (similar to resolvePdfPath but for generic files)
*/
private async resolveFilePath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise<string | null> {
const pathModule = require('path');
const fs = require('fs');
// Decode the URL-encoded sanitized path back to normal characters
const decodedPath = decodeURIComponent(sanitizedPath);
// Try multiple path resolution strategies
const possiblePaths = [
// Strategy 1: Relative to vault root (standard Obsidian behavior)
pathModule.resolve(vaultBasePath, decodedPath),
// Strategy 2: Relative to current file's directory (for local attachments)
currentFile ? pathModule.resolve(vaultBasePath, pathModule.dirname(currentFile.path), decodedPath) : null,
// Strategy 3: Check in attachments folder (common pattern)
pathModule.resolve(vaultBasePath, 'attachments', pathModule.basename(decodedPath))
].filter(p => p !== null);
// Try each possible path until we find one that exists
for (const possiblePath of possiblePaths) {
try {
await fs.promises.access(possiblePath);
return possiblePath;
} catch {
// File doesn't exist, continue to next path
}
}
return null;
}
private async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise<void> {
const { PdfToImageConverter } = await import('./src/converters/PdfToImageConverter');
const converter = PdfToImageConverter.getInstance(this);
@@ -988,6 +1185,65 @@ ${dependencyResult.allAvailable
processedResult.content = updatedContent;
}
/**
* Process file embeds - Convert to attachments using Typst's pdf.embed
*/
private async processFileEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedAllFiles: boolean = true): Promise<void> {
const pathModule = require('path');
const fs = require('fs');
let updatedContent = processedResult.content;
for (const fileEmbed of processedResult.metadata.fileEmbeds) {
try {
// Resolve file path using helper method (similar to PDF processing)
const fullFilePath = await this.resolveFilePath(fileEmbed.sanitizedPath, vaultBasePath, currentFile);
if (!fullFilePath) {
console.warn(`Export: File not found: ${decodeURIComponent(fileEmbed.sanitizedPath)}`);
// Replace marker with fallback message
const fallbackOutput = `*⚠️ File not found: ${fileEmbed.baseName}*`;
updatedContent = updatedContent.replace(fileEmbed.marker, fallbackOutput);
continue;
}
if (embedAllFiles) {
// Get relative path from vault base
const relativeFilePath = pathModule.relative(vaultBasePath, fullFilePath);
// Create file embed content using helper method
const combinedOutput = this.generateFileEmbedContent(
relativeFilePath,
fileEmbed.baseName,
fileEmbed.fileType,
undefined
);
// Replace the placeholder with the combined output
updatedContent = updatedContent.replace(fileEmbed.marker, combinedOutput);
} else {
// Just show as a link if embedding is disabled
const relativeFilePath = pathModule.relative(vaultBasePath, fullFilePath);
const fileIcon = this.getFileTypeIcon(fileEmbed.fileType);
const linkOutput = `[${fileIcon} ${fileEmbed.fileName}](${relativeFilePath})`;
updatedContent = updatedContent.replace(fileEmbed.marker, linkOutput);
}
} catch (error) {
ExportErrorHandler.handleProcessingError('File embed', fileEmbed.originalPath, error);
// Still try to show as a link even if there's a processing error
const relativeFilePath = pathModule.relative(vaultBasePath, fileEmbed.originalPath);
const fileIcon = this.getFileTypeIcon(fileEmbed.fileType);
const fallbackOutput = `[${fileIcon} ${fileEmbed.fileName} (error occurred)](${relativeFilePath})`;
updatedContent = updatedContent.replace(fileEmbed.marker, fallbackOutput);
}
}
// Update the processed result with the new content
processedResult.content = updatedContent;
}
/**
* Prepare the output path for a file
*/
@@ -1074,7 +1330,7 @@ ${dependencyResult.allAvailable
private cleanupStartupTempDirectories(): void {
try {
const vaultPath = (this.app.vault.adapter as any).basePath;
const cleanupManager = TempDirectoryManager.create(vaultPath);
const cleanupManager = TempDirectoryManager.create(vaultPath, this.app.vault.configDir);
const result = cleanupManager.cleanupAllTempDirs();
if (this.settings.behavior.debugMode) {
@@ -1094,7 +1350,7 @@ ${dependencyResult.allAvailable
// Clean up temp directories on plugin unload
try {
const vaultPath = (this.app.vault.adapter as any).basePath;
const cleanupManager = TempDirectoryManager.create(vaultPath);
const cleanupManager = TempDirectoryManager.create(vaultPath, this.app.vault.configDir);
cleanupManager.cleanupAllTempDirs();
} catch (error) {
console.warn('Export: Failed to clean up temp directories during unload:', error);
@@ -1181,10 +1437,10 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
}));
new Setting(containerEl)
.setName('ImageMagick convert path')
.setDesc('Path to ImageMagick convert executable (leave empty to use system PATH)')
.setName('ImageMagick path')
.setDesc('Path to ImageMagick executable (leave empty to use system PATH)')
.addText(text => text
.setPlaceholder('convert')
.setPlaceholder('magick')
.setValue(this.plugin.settings.executablePaths.imagemagickPath)
.onChange(async (value) => {
if (!SecurityUtils.validateExecutablePath(value)) {
@@ -1485,6 +1741,16 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Embed all file types')
.setDesc('Include all referenced file types (office documents, archives, etc.) as PDF attachments')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.behavior.embedAllFiles)
.onChange(async (value) => {
this.plugin.settings.behavior.embedAllFiles = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Print frontmatter')
.setDesc('Display frontmatter as formatted text at the beginning of documents')
+2 -2
View File
@@ -1,7 +1,7 @@
{
"id": "typst-pdf-export",
"name": "Typst PDF Export",
"version": "1.0.1",
"version": "1.1.0",
"minAppVersion": "1.9.12",
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
"author": "Alexander Kucera",
@@ -12,4 +12,4 @@
"Patreon": "https://patreon.com/babylondreams"
},
"isDesktopOnly": true
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "obsidian-typst-pdf-export",
"version": "1.0.0",
"version": "1.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "obsidian-typst-pdf-export",
"version": "1.0.0",
"version": "1.1.0",
"license": "MIT",
"dependencies": {
"gray-matter": "^4.0.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "obsidian-typst-pdf-export",
"version": "1.0.1",
"version": "1.1.0",
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
"main": "main.js",
"scripts": {
+67 -2
View File
@@ -46,6 +46,15 @@ export interface PreprocessingResult {
sizeOrAlt?: string;
marker: string;
}>;
fileEmbeds?: Array<{
originalPath: string;
sanitizedPath: string;
fileName: string;
baseName: string;
fileType: string;
options?: string;
marker: string;
}>;
};
/** Processing errors and warnings */
errors: string[];
@@ -594,6 +603,9 @@ export class MarkdownPreprocessor {
case 'pdf':
return this.processPdfEmbed(cleanPath, sizeOrAlt, result);
case 'file':
return this.processFileEmbed(cleanPath, sizeOrAlt, result);
default:
// Fallback to link reference for unknown types
result.warnings.push(`Unknown file type for embed: ${cleanPath}`);
@@ -618,20 +630,39 @@ export class MarkdownPreprocessor {
/**
* Determine file type based on extension
*/
private determineFileType(extension: string): 'image' | 'video' | 'audio' | 'document' | 'pdf' | 'unknown' {
private determineFileType(extension: string): 'image' | 'video' | 'audio' | 'document' | 'pdf' | 'file' | 'unknown' {
const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp', '.ico', '.tiff'];
const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v'];
const audioExtensions = ['.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', '.wma'];
const documentExtensions = ['.md', '.txt', '.doc', '.docx', '.rtf'];
const pdfExtensions = ['.pdf'];
// Additional file types that should be embedded
const fileExtensions = [
// Office documents
'.xlsx', '.xls', '.pptx', '.ppt', '.odt', '.ods', '.odp',
// Archives and compressed files
'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz',
// Data and configuration files
'.json', '.xml', '.csv', '.yaml', '.yml', '.toml', '.ini', '.cfg',
// Code files
'.js', '.ts', '.py', '.java', '.cpp', '.c', '.h', '.css', '.html', '.php', '.rb', '.go', '.rs', '.swift',
// Database files
'.db', '.sqlite', '.sql',
// Other common files
'.log', '.epub', '.mobi', '.ics', '.vcf'
];
if (imageExtensions.includes(extension)) return 'image';
if (videoExtensions.includes(extension)) return 'video';
if (audioExtensions.includes(extension)) return 'audio';
if (documentExtensions.includes(extension)) return 'document';
if (pdfExtensions.includes(extension)) return 'pdf';
if (fileExtensions.includes(extension)) return 'file';
return 'unknown';
// Default to 'file' for unknown extensions instead of 'unknown'
// This ensures all file types get embedded unless they're explicitly excluded
return extension ? 'file' : 'unknown';
}
/**
@@ -735,6 +766,40 @@ export class MarkdownPreprocessor {
return marker;
}
/**
* Process generic file embeds - Convert to attachment using Typst's pdf.embed
*/
private processFileEmbed(filePath: string, options: string | undefined, result: PreprocessingResult): string {
const sanitizedPath = this.sanitizeFilePath(filePath);
// For now, we'll mark this for async processing and return a placeholder
// The actual embedding will be handled in the main export process
const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
const fileExtension = this.getFileExtension(fileName);
// Create a marker that the export process can detect and replace with Typst code
const marker = `FILE_EMBED_MARKER:${filePath}:${baseName}:${options || ''}`;
// Add to processing queue for later conversion
if (!result.metadata.fileEmbeds) {
result.metadata.fileEmbeds = [];
}
result.metadata.fileEmbeds.push({
originalPath: filePath,
sanitizedPath: sanitizedPath,
fileName: fileName,
baseName: baseName,
fileType: fileExtension,
options: options,
marker: marker
});
result.warnings.push(`File embed queued for processing with Typst pdf.embed: ${filePath}`);
return marker;
}
/**
* Convert Obsidian callouts to standard blockquotes with styling markers
*/
+41 -7
View File
@@ -250,7 +250,8 @@ export class PandocTypstConverter {
if (!this.tempDir) {
if (this.pandocOptions.vaultBasePath) {
// Use TempDirectoryManager for plugin temp directories
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath);
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir);
this.tempDir = tempManager.ensureTempDir('pandoc');
} else {
// Fallback to system temp if plugin folder not available
@@ -276,11 +277,8 @@ export class PandocTypstConverter {
args.push('--from', 'markdown-smart');
// Set PDF engine to Typst (use configured path if available)
if (this.pandocOptions.typstPath) {
args.push(`--pdf-engine=${this.pandocOptions.typstPath}`);
} else {
args.push('--pdf-engine=typst');
}
const typstPath = this.resolveExecutablePath(this.pandocOptions.typstPath, 'typst');
args.push(`--pdf-engine=${typstPath}`);
// Enable standalone mode (required for PDF output)
args.push('--standalone');
@@ -548,12 +546,48 @@ export class PandocTypstConverter {
return args;
}
/**
* Resolve an executable path, handling empty settings by falling back to system search
*/
private resolveExecutablePath(userPath: string | undefined, defaultName: string): string {
// If user provided a path and it's not empty, use it
if (userPath && userPath.trim() !== '') {
return userPath;
}
// Try to find the executable using which command
const { spawnSync } = require('child_process');
try {
const augmentedEnv = {
...process.env,
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
};
const result = spawnSync('which', [defaultName], {
encoding: 'utf8',
env: augmentedEnv
});
if (result.status === 0 && result.stdout) {
const foundPath = result.stdout.trim();
if (foundPath) {
return foundPath;
}
}
} catch {
// Ignore errors from which command
}
// Fall back to the default name (will be found via PATH if available)
return defaultName;
}
/**
* Execute pandoc process with the given arguments
*/
private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise<ConversionResult> {
return new Promise((resolve) => {
const pandocPath = this.pandocOptions.pandocPath || 'pandoc';
const pandocPath = this.resolveExecutablePath(this.pandocOptions.pandocPath, 'pandoc');
const timeout = this.pandocOptions.timeout || 60000;
// Log the exact command being executed for debugging
+16 -6
View File
@@ -129,11 +129,12 @@ export class PdfToImageConverter {
// Try multiple strategies to find the plugin directory
const pluginDirName = this.plugin?.manifest?.dir || 'typst-pdf-export';
const configDir = this.plugin?.app.vault.configDir || '.obsidian';
const possiblePluginDirs = [
// Strategy 1: From process.cwd() if it's in the vault
path.join(process.cwd(), '.obsidian', 'plugins', pluginDirName),
path.join(process.cwd(), configDir, 'plugins', pluginDirName),
// Strategy 2: Assuming we're running from vault root
path.join('.obsidian', 'plugins', pluginDirName),
path.join(configDir, 'plugins', pluginDirName),
// Strategy 3: From vault base path if plugin is available
...(this.plugin ? [path.join((this.plugin.app.vault.adapter as any).basePath, this.plugin.manifest.dir!)] : [])
];
@@ -179,11 +180,21 @@ export class PdfToImageConverter {
const additionalPaths = this.plugin?.settings?.executablePaths?.additionalPaths ||
['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'];
// Ensure Node.js paths are included for pdf2img execution
const nodePaths = [
'/usr/local/bin', // Common Node.js installation
'/opt/homebrew/bin', // Homebrew on macOS
'/usr/bin', // System Node.js
'/usr/local/node/bin' // Alternative Node.js location
];
const env = {
...process.env,
PATH: process.env.PATH + (additionalPaths.length > 0
? ':' + additionalPaths.join(':')
: '')
PATH: [
process.env.PATH,
...nodePaths,
...additionalPaths
].filter(Boolean).join(':')
};
const result = await execAsync(cliCommand, {
@@ -262,7 +273,6 @@ export class PdfToImageConverter {
// Use ImageMagick to convert PNG to JPEG
const convertProcess = spawn('magick', [
'convert',
actualOutputPath,
'-quality', opts.quality.toString(),
finalOutputPath
+156 -14
View File
@@ -21,24 +21,112 @@ export interface DependencyCheckResult {
export class DependencyChecker {
/**
* Get augmented PATH with common binary locations
* Get augmented PATH with common binary locations and additional paths
*/
private static getAugmentedPath(): string {
private static getAugmentedPath(additionalPaths: string[] = []): string {
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
const commonPaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.map(p => homeDir + p);
return `${process.env.PATH}:${commonPaths.join(':')}`;
// Build default system paths - always included regardless of user settings
const homeRelativePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.map(p => homeDir + p);
const absolutePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE;
const defaultSystemPaths = [...homeRelativePaths, ...absolutePaths];
// Combine default system paths with user-provided additional paths
const allAdditionalPaths = [...defaultSystemPaths, ...additionalPaths];
return `${process.env.PATH}:${allAdditionalPaths.join(':')}`;
}
/**
* Get augmented environment with extended PATH
*/
private static getAugmentedEnv(): NodeJS.ProcessEnv {
private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv {
return {
...process.env,
PATH: this.getAugmentedPath()
PATH: this.getAugmentedPath(additionalPaths)
};
}
/**
* Try to find an executable using which command
*/
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
console.log(`[DependencyChecker] findExecutableWithWhich: searching for "${executableName}"`);
const { spawn } = require('child_process');
try {
const stdout = await new Promise<string>((resolve, reject) => {
const env = this.getAugmentedEnv(additionalPaths);
console.log(`[DependencyChecker] findExecutableWithWhich: using PATH="${env.PATH}"`);
const whichProcess = spawn('which', [executableName], {
stdio: ['pipe', 'pipe', 'pipe'],
env: env
});
let output = '';
let error = '';
whichProcess.stdout?.on('data', (data: Buffer) => {
output += data.toString();
});
whichProcess.stderr?.on('data', (data: Buffer) => {
error += data.toString();
});
whichProcess.on('close', (code: number | null) => {
console.log(`[DependencyChecker] which ${executableName} exited with code ${code}, stdout: "${output.trim()}", stderr: "${error.trim()}"`);
if (code === 0) {
resolve(output);
} else {
reject(new Error(`which command failed with code ${code}: ${error}`));
}
});
whichProcess.on('error', (err: Error) => {
console.log(`[DependencyChecker] which ${executableName} spawn error:`, err.message);
reject(new Error(`Failed to spawn which process: ${err.message}`));
});
});
const foundPath = stdout.trim();
console.log(`[DependencyChecker] findExecutableWithWhich result: "${foundPath}"`);
return foundPath || null;
} catch (error) {
console.log(`[DependencyChecker] findExecutableWithWhich caught error:`, error.message);
return null;
}
}
/**
* Resolve the actual executable path, handling empty/undefined settings
*/
private static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise<string> {
console.log(`[DependencyChecker] ASYNC Resolving path for ${defaultName}: userPath="${userPath}"`);
// If user provided a full path (contains /), use it as-is
if (userPath && userPath.trim() !== '' && userPath.includes('/')) {
console.log(`[DependencyChecker] ASYNC Using user-provided full path: ${userPath}`);
return userPath;
}
// If user provided just an executable name or empty path, resolve it
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
console.log(`[DependencyChecker] ASYNC Searching for: ${searchName}`);
// Try to find the executable using which command
const foundPath = await this.findExecutableWithWhich(searchName, additionalPaths);
if (foundPath) {
console.log(`[DependencyChecker] ASYNC Found via which: ${foundPath}`);
return foundPath;
}
// Fall back to the search name (will be found via PATH if available)
console.log(`[DependencyChecker] ASYNC Falling back to search name: ${searchName}`);
return searchName;
}
/**
* Check if a dependency is available and get its version
*/
@@ -101,6 +189,46 @@ export class DependencyChecker {
}
}
/**
* Synchronous version of resolving executable path
*/
private static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string {
console.log(`[DependencyChecker] SYNC Resolving path for ${defaultName}: userPath="${userPath}"`);
// If user provided a full path (contains /), use it as-is
if (userPath && userPath.trim() !== '' && userPath.includes('/')) {
console.log(`[DependencyChecker] SYNC Using user-provided full path: ${userPath}`);
return userPath;
}
// If user provided just an executable name or empty path, resolve it
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
console.log(`[DependencyChecker] SYNC Searching for: ${searchName}`);
// Try to find the executable using which command synchronously
const { spawnSync } = require('child_process');
try {
const result = spawnSync('which', [searchName], {
encoding: 'utf8',
env: this.getAugmentedEnv(additionalPaths)
});
if (result.status === 0 && result.stdout) {
const foundPath = result.stdout.trim();
if (foundPath) {
console.log(`[DependencyChecker] SYNC Found via which: ${foundPath}`);
return foundPath;
}
}
} catch {
// Ignore errors from which command
}
// Fall back to the search name (will be found via PATH if available)
console.log(`[DependencyChecker] SYNC Falling back to search name: ${searchName}`);
return searchName;
}
/**
* Check if a dependency is available (synchronous version for startup)
*/
@@ -124,11 +252,19 @@ export class DependencyChecker {
public static async checkAllDependencies(
pandocPath?: string,
typstPath?: string,
imagemagickPath?: string
imagemagickPath?: string,
additionalPaths: string[] = []
): Promise<DependencyCheckResult> {
const pandocExec = pandocPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc;
const typstExec = typstPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst;
const imagemagickExec = imagemagickPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick;
console.log(`[DependencyChecker] checkAllDependencies called with:`, { pandocPath, typstPath, imagemagickPath, additionalPaths });
// Resolve actual executable paths, handling empty settings
const [pandocExec, typstExec, imagemagickExec] = await Promise.all([
this.resolveExecutablePath(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths),
this.resolveExecutablePath(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths),
this.resolveExecutablePath(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths)
]);
console.log(`[DependencyChecker] Resolved paths:`, { pandocExec, typstExec, imagemagickExec });
const [pandocInfo, typstInfo, imagemagickInfo] = await Promise.all([
this.checkDependency('Pandoc', pandocExec, '--version', /pandoc\s+([\d.]+)/),
@@ -155,11 +291,17 @@ export class DependencyChecker {
public static checkDependenciesSync(
pandocPath?: string,
typstPath?: string,
imagemagickPath?: string
imagemagickPath?: string,
additionalPaths: string[] = []
): string[] {
const pandocExec = pandocPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc;
const typstExec = typstPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst;
const imagemagickExec = imagemagickPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick;
console.log(`[DependencyChecker] checkDependenciesSync called with:`, { pandocPath, typstPath, imagemagickPath, additionalPaths });
// Resolve actual executable paths, handling empty settings
const pandocExec = this.resolveExecutablePathSync(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths);
const typstExec = this.resolveExecutablePathSync(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths);
const imagemagickExec = this.resolveExecutablePathSync(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths);
console.log(`[DependencyChecker] Resolved paths SYNC:`, { pandocExec, typstExec, imagemagickExec });
const missingDeps: string[] = [];
+8 -4
View File
@@ -7,6 +7,8 @@ import { PLUGIN_DIRS } from './constants';
export interface TempDirectoryOptions {
/** Base path for the vault */
vaultPath: string;
/** Configuration directory path (from Vault#configDir) */
configDir: string;
/** Plugin directory name (defaults to 'typst-pdf-export') */
pluginName?: string;
}
@@ -15,10 +17,12 @@ export class TempDirectoryManager {
private readonly fs = require('fs');
private readonly path = require('path');
private readonly vaultPath: string;
private readonly configDir: string;
private readonly pluginName: string;
constructor(options: TempDirectoryOptions) {
this.vaultPath = options.vaultPath;
this.configDir = options.configDir;
this.pluginName = options.pluginName || 'typst-pdf-export';
}
@@ -26,7 +30,7 @@ export class TempDirectoryManager {
* Get the plugin directory path
*/
private getPluginDir(): string {
return this.path.join(this.vaultPath, '.obsidian', 'plugins', this.pluginName);
return this.path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
}
/**
@@ -83,10 +87,10 @@ export class TempDirectoryManager {
}
/**
* Static helper to create manager from vault path
* Static helper to create manager from vault path and configDir
*/
public static create(vaultPath: string, pluginName?: string): TempDirectoryManager {
return new TempDirectoryManager({ vaultPath, pluginName });
public static create(vaultPath: string, configDir: string, pluginName?: string): TempDirectoryManager {
return new TempDirectoryManager({ vaultPath, configDir, pluginName });
}
/**
+24 -8
View File
@@ -49,16 +49,32 @@ export const DEPENDENCY_CONSTANTS = {
DEFAULT_EXECUTABLES: {
pandoc: 'pandoc',
typst: 'typst',
imagemagick: 'convert'
imagemagick: 'magick'
},
/**
* Common paths to augment PATH with
* Common paths to augment PATH with - these are always checked regardless of user settings
*/
COMMON_PATHS: [
'/.local/bin',
'/.cargo/bin',
'/usr/local/bin',
'/opt/homebrew/bin'
]
COMMON_PATHS: {
/**
* Paths relative to home directory (will have HOME prepended)
*/
HOME_RELATIVE: [
'/.local/bin',
'/.cargo/bin',
'/go/bin',
'/.npm-global/bin'
],
/**
* System-wide absolute paths (used as-is)
*/
ABSOLUTE: [
'/usr/local/bin',
'/opt/homebrew/bin',
'/usr/bin',
'/bin',
'/opt/local/bin',
'/snap/bin'
]
}
} as const;
+4 -1
View File
@@ -19,7 +19,7 @@ export interface obsidianTypstPDFExportSettings {
/** Executable paths configuration */
executablePaths: {
/** Path to ImageMagick convert command (optional, uses PATH if not specified) */
/** Path to ImageMagick command (optional, uses PATH if not specified) */
imagemagickPath: string;
/** Additional paths to append to PATH environment variable */
additionalPaths: string[];
@@ -91,6 +91,8 @@ export interface obsidianTypstPDFExportSettings {
debugMode: boolean;
/** Whether to embed PDF files as attachments in the output PDF */
embedPdfFiles: boolean;
/** Whether to embed all file types as attachments in the output PDF */
embedAllFiles: boolean;
/** Display frontmatter as formatted text at the beginning of the document */
printFrontmatter: boolean;
};
@@ -151,6 +153,7 @@ export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
exportConcurrency: 3,
debugMode: false,
embedPdfFiles: true,
embedAllFiles: true,
printFrontmatter: false
}
};;;;
+3 -3
View File
@@ -324,13 +324,13 @@ export class ExportConfigModal extends Modal {
}
private showProgress(message: string, percent: number): void {
this.progressContainer.style.display = 'block';
this.formContainer.style.display = 'none';
this.progressContainer.addClass('export-progress-visible');
this.formContainer.addClass('export-form-hidden');
this.progressText.textContent = message;
if (percent >= 0) {
this.progressBar.style.width = `${percent}%`;
this.progressBar.style.setProperty('--progress-width', `${percent}%`);
const percentEl = this.progressContainer.querySelector('.export-progress-percent');
if (percentEl) {
percentEl.textContent = `${Math.round(percent)}%`;
+2
View File
@@ -20,6 +20,8 @@ export interface ExportConfig {
preserveFolderStructure?: boolean;
/** Whether to embed PDF files as attachments in the output PDF */
embedPdfFiles?: boolean;
/** Whether to embed all file types as attachments in the output PDF */
embedAllFiles?: boolean;
/** Display frontmatter as formatted text at the beginning of the document */
printFrontmatter?: boolean;
}
+12
View File
@@ -55,6 +55,18 @@ export class BehaviorSection implements ModalSection {
});
});
// Embed all files toggle
new Setting(this.container)
.setName('Embed all file types as attachments')
.setDesc('Embed all referenced file types (office documents, archives, etc.) as PDF attachments')
.addToggle(toggle => {
toggle
.setValue(state.settings.embedAllFiles !== false)
.onChange(value => {
state.updateSettings({ embedAllFiles: value });
});
});
// Print frontmatter toggle
new Setting(this.container)
.setName('Print frontmatter')
+1
View File
@@ -86,6 +86,7 @@ export class ModalState implements IModalState {
openAfterExport: this.settings.openAfterExport,
preserveFolderStructure: this.settings.preserveFolderStructure,
embedPdfFiles: this.settings.embedPdfFiles,
embedAllFiles: this.settings.embedAllFiles,
printFrontmatter: this.settings.printFrontmatter
};
+10
View File
@@ -123,4 +123,14 @@
/* Progress bar styling */
.export-progress-bar {
transition: width 0.3s ease;
width: var(--progress-width, 0%);
}
/* Modal display states */
.export-progress-visible {
display: block !important;
}
.export-form-hidden {
display: none !important;
}
+3 -2
View File
@@ -1,4 +1,5 @@
{
"1.0.0": "1.9.12",
"1.0.1": "1.9.12"
}
"1.0.1": "1.9.12",
"1.1.0": "1.9.12"
}