-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
420 lines (366 loc) · 17.3 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { App, Plugin, PluginSettingTab, Setting, TFile, Notice, getAllTags} from 'obsidian';
import * as path from 'path';
import * as fs from 'fs';
interface ObsidianToQuartoSettings {
dateOption: 'none' | 'created' | 'modified';
dateFormat: string;
outputFolder: string;
overwriteExisting: boolean;
importTags: boolean;
allowExternalPaths: boolean;
}
const DEFAULT_SETTINGS: ObsidianToQuartoSettings = {
dateOption: 'none',
dateFormat: 'YYYY-MM-DD',
outputFolder: '',
overwriteExisting: false,
importTags: true,
allowExternalPaths: false
}
export default class ObsidianToQuartoPlugin extends Plugin {
settings: ObsidianToQuartoSettings;
async onload() {
console.log('Loading ObsidianToQuartoPlugin');
await this.loadSettings();
this.addCommand({
id: 'export-to-quarto',
name: 'Export to Quarto QMD',
callback: () => this.exportToQuarto(),
});
this.addSettingTab(new ObsidianToQuartoSettingTab(this.app, this));
console.log('ObsidianToQuartoPlugin loaded');
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
async exportToQuarto() {
try {
const activeFile = this.app.workspace.getActiveFile();
if (!activeFile || activeFile.extension !== 'md') {
new Notice('Please open a Markdown file before exporting');
return;
}
const content = await this.app.vault.read(activeFile);
const convertedContent = await this.convertToQuarto(content, activeFile);
let outputPath: string;
let newFileName = activeFile.basename + '.qmd';
let newPath: string;
if (this.settings.allowExternalPaths && path.isAbsolute(this.settings.outputFolder)) {
// Handle absolute path outside vault
outputPath = this.settings.outputFolder;
try {
fs.mkdirSync(outputPath, { recursive: true });
newPath = path.join(outputPath, newFileName);
if (fs.existsSync(newPath)) {
if (this.settings.overwriteExisting) {
fs.unlinkSync(newPath);
} else {
let counter = 1;
while (fs.existsSync(newPath)) {
newFileName = `${activeFile.basename}_${counter}.qmd`;
newPath = path.join(outputPath, newFileName);
counter++;
}
}
}
fs.writeFileSync(newPath, convertedContent);
new Notice(`Successfully exported to ${newPath}`);
} catch (error) {
console.error('Error writing to external path:', error);
new Notice(`Failed to write to external path: ${error.message}`);
return;
}
} else {
// Handle vault path
outputPath = this.settings.outputFolder || activeFile.parent.path;
await this.app.vault.adapter.mkdir(outputPath);
newPath = `${outputPath}/${newFileName}`;
if (await this.app.vault.adapter.exists(newPath)) {
if (this.settings.overwriteExisting) {
await this.app.vault.adapter.remove(newPath);
} else {
let counter = 1;
while (await this.app.vault.adapter.exists(newPath)) {
newFileName = `${activeFile.basename}_${counter}.qmd`;
newPath = `${outputPath}/${newFileName}`;
counter++;
}
}
}
await this.app.vault.create(newPath, convertedContent);
const newFile = this.app.vault.getAbstractFileByPath(newPath);
if (newFile instanceof TFile) {
await this.app.workspace.openLinkText(newFile.path, '', true);
}
new Notice(`Successfully exported to ${newFileName}`);
}
} catch (error) {
console.error('Error in exportToQuarto:', error);
new Notice('Failed to export to Quarto QMD. Check console for details.');
}
}
convertObsidianImages(content: string): string {
// Convert Obsidian image syntax (![[image.png]]) to standard Markdown (![](<image.png>))
return content.replace(/!\[\[([^\]]+?)\]\]/g, '![]($1)');
}
async convertToQuarto(content: string, file: TFile): Promise<string> {
// Extract frontmatter if it exists
let frontmatter = '';
let mainContent = content;
const frontmatterMatch = content.match(/^---\n[\s\S]*?\n---\n/);
if (frontmatterMatch) {
frontmatter = frontmatterMatch[0];
mainContent = content.slice(frontmatter.length);
}
// Create new frontmatter
const title = file.basename;
let newFrontmatter = `---\ntitle: "${title}"\n`;
if (this.settings.dateOption !== 'none') {
const date = await this.getFileDate(file);
newFrontmatter += `date: "${date}"\n`;
}
// Add tags if enabled
if (this.settings.importTags) {
const fileTags = this.getFileTags(file);
if (fileTags.length > 0) {
newFrontmatter += `tags:\n${fileTags.map(tag => ` - ${tag}`).join('\n')}\n`;
}
}
// Merge existing frontmatter (if any) with new frontmatter, excluding tags
if (frontmatter) {
const existingFrontmatter = frontmatter
.slice(4, -4) // Remove '---' delimiters
.split('\n')
.filter(line => !line.startsWith('tags:') && !line.trim().startsWith('-'))
.join('\n');
newFrontmatter += existingFrontmatter + '\n';
}
newFrontmatter += '---\n\n';
// Process main content
let convertedContent = mainContent;
// Preserve content before the first header
const firstHeaderIndex = convertedContent.search(/^\s*#/m);
let preHeaderContent = '';
if (firstHeaderIndex !== -1) {
preHeaderContent = convertedContent.slice(0, firstHeaderIndex).trim() + '\n\n';
convertedContent = convertedContent.slice(firstHeaderIndex);
}
// Convert Obsidian image syntax before other conversions
convertedContent = this.convertObsidianImages(convertedContent);
convertedContent = await this.convertEmbeddedNotes(convertedContent);
// Add line breaks before headers
convertedContent = convertedContent.replace(/^(#+\s.*)/gm, '\n$1');
// Convert Obsidian callouts to Quarto callouts
convertedContent = convertedContent.replace(
/> \[!(\w+)\](.*?)\n((?:>.*\n?)*)/g,
(_, type, title, content) => {
const quartoType = this.mapCalloutType(type);
return `::: {.callout-${quartoType}}\n${title.trim() ? `## ${title.trim()}\n` : ''}${content.replace(/^>/gm, '').trim()}\n:::\n\n`;
}
);
// Combine all parts
return newFrontmatter + preHeaderContent + convertedContent;
}
getFileTags(file: TFile): string[] {
const fileCache = this.app.metadataCache.getFileCache(file);
if (fileCache) {
const tags = getAllTags(fileCache);
return tags ? tags.map(tag => tag.replace('#', '')) : [];
}
return [];
}
async getFileDate(file: TFile): Promise<string> {
try {
const stat = await this.app.vault.adapter.stat(file.path);
if (!stat) {
console.error('Failed to get file stats');
return this.formatDate(new Date()); // Use current date as fallback
}
const date = this.settings.dateOption === 'created' ? stat.ctime : stat.mtime;
return this.formatDate(new Date(date));
} catch (error) {
console.error('Error getting file date:', error);
return this.formatDate(new Date()); // Use current date as fallback
}
}
formatDate(date: Date): string {
const format = this.settings.dateFormat;
return format
.replace('YYYY', date.getFullYear().toString())
.replace('MM', (date.getMonth() + 1).toString().padStart(2, '0'))
.replace('DD', date.getDate().toString().padStart(2, '0'))
.replace('HH', date.getHours().toString().padStart(2, '0'))
.replace('mm', date.getMinutes().toString().padStart(2, '0'))
.replace('ss', date.getSeconds().toString().padStart(2, '0'));
}
async convertEmbeddedNotes(content: string): Promise<string> {
const embeddedNoteRegex = /!\[\[([^\]]+?)((?:#|\^).+?)?\]\]/g;
const embedPromises: Promise<string>[] = [];
content.replace(embeddedNoteRegex, (match, noteName, reference) => {
embedPromises.push(this.getEmbeddedNoteContent(noteName, reference));
return match;
});
const embeddedContents = await Promise.all(embedPromises);
return content.replace(embeddedNoteRegex, () => embeddedContents.shift() || '');
}
async getEmbeddedNoteContent(noteName: string, reference?: string): Promise<string> {
const file = this.app.metadataCache.getFirstLinkpathDest(noteName, '');
if (file instanceof TFile) {
let content = await this.app.vault.read(file);
console.log(`Original content length: ${content.length}`);
if (reference) {
console.log(`Processing reference: ${reference}`);
if (reference.startsWith('#')) {
// Header reference
const headerName = reference.slice(1);
console.log(`Looking for header: ${headerName}`);
const headerRegex = new RegExp(`^(#+)\\s*${this.escapeRegExp(headerName)}\\s*$`, 'im');
const headerMatch = content.match(headerRegex);
if (headerMatch) {
console.log(`Found header: ${headerMatch[0]}`);
const headerLevel = headerMatch[1].length;
const headerIndex = headerMatch.index!;
const nextHeaderRegex = new RegExp(`^#{1,${headerLevel}}\\s`, 'im');
const remainingContent = content.slice(headerIndex + headerMatch[0].length);
const nextHeaderMatch = remainingContent.match(nextHeaderRegex);
const nextHeaderIndex = nextHeaderMatch ? nextHeaderMatch.index! + headerMatch[0].length : content.length;
content = content.slice(headerIndex, headerIndex + nextHeaderIndex);
console.log(`Extracted content length: ${content.length}`);
} else {
console.log(`Header not found: ${headerName}`);
return `\n\n> [!warning] Header not found: ${headerName} in ${noteName}\n\n`;
}
} else if (reference.startsWith('^')) {
// Block reference
const blockId = reference.slice(1);
console.log(`Looking for block: ${blockId}`);
const blockRegex = new RegExp(`(^|\n)([^\n]+\\s*(?:{{[^}]*}})?\\s*\\^${this.escapeRegExp(blockId)}\\s*$)`, 'm');
const blockMatch = content.match(blockRegex);
if (blockMatch) {
console.log(`Found block: ${blockMatch[2]}`);
const blockIndex = blockMatch.index! + blockMatch[1].length;
const blockEndIndex = content.indexOf('\n\n', blockIndex);
content = blockEndIndex !== -1
? content.slice(blockIndex, blockEndIndex).trim()
: content.slice(blockIndex).trim();
console.log(`Extracted content length: ${content.length}`);
} else {
console.log(`Block not found: ${blockId}`);
return `\n\n> [!warning] Block not found: ${blockId} in ${noteName}\n\n`;
}
}
}
// Remove the block reference if it exists
content = content.replace(/\s*\^[a-zA-Z0-9-]+\s*$/, '');
return `\n\n${content.trim()}\n\n`;
} else {
console.log(`File not found: ${noteName}`);
return `\n\n> [!warning] Embedded note not found: ${noteName}${reference || ''}\n\n`;
}
}
private escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
private mapCalloutType(obsidianType: string): string {
const typeMap: {[key: string]: string} = {
'note': 'note',
'info': 'info',
'tip': 'tip',
'success': 'success',
'question': 'question',
'warning': 'warning',
'failure': 'error',
'danger': 'warning',
'bug': 'bug',
'example': 'example',
'quote': 'quote'
};
return typeMap[obsidianType.toLowerCase()] || 'note';
}
private slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^\w ]+/g, '')
.replace(/ +/g, '-');
}
}
class ObsidianToQuartoSettingTab extends PluginSettingTab {
plugin: ObsidianToQuartoPlugin;
constructor(app: App, plugin: ObsidianToQuartoPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Allow External Paths')
.setDesc('If enabled, allows exporting files to locations outside the Obsidian vault using absolute paths')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.allowExternalPaths)
.onChange(async (value) => {
this.plugin.settings.allowExternalPaths = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Output Folder')
.setDesc('Specify the folder where QMD files should be saved. Use absolute path (e.g., /home/user/exports) to save outside vault, or relative path for inside vault. Leave blank to use same folder as original file.')
.addText(text => text
.setPlaceholder('Enter folder path')
.setValue(this.plugin.settings.outputFolder)
.onChange(async (value) => {
this.plugin.settings.outputFolder = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Date Option')
.setDesc('Choose which date to add to the Quarto document')
.addDropdown(dropdown => dropdown
.addOption('none', 'No date')
.addOption('created', 'Creation date')
.addOption('modified', 'Last modified date')
.setValue(this.plugin.settings.dateOption)
.onChange(async (value) => {
this.plugin.settings.dateOption = value as 'none' | 'created' | 'modified';
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Date Format')
.setDesc('Specify the date format (YYYY: year, MM: month, DD: day, HH: hour, mm: minute, ss: second)')
.addText(text => text
.setPlaceholder('YYYY-MM-DD')
.setValue(this.plugin.settings.dateFormat)
.onChange(async (value) => {
this.plugin.settings.dateFormat = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Overwrite Existing Files')
.setDesc('If checked, existing files will be overwritten. If unchecked, a new file with a number appended will be created.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.overwriteExisting)
.onChange(async (value) => {
this.plugin.settings.overwriteExisting = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Import Tags')
.setDesc('If checked, tags from the Obsidian note will be imported into the Quarto file.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.importTags)
.onChange(async (value) => {
this.plugin.settings.importTags = value;
await this.plugin.saveSettings();
}));
}
}
declare module 'obsidian' {
interface App {
vault: Vault;
workspace: Workspace;
metadataCache: MetadataCache;
}
}