Repository navigation
Expand file tree
/
Copy pathextension.js
More file actions
423 lines (353 loc) · 15.5 KB
/
Copy pathextension.js
File metadata and controls
423 lines (353 loc) · 15.5 KB
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
421
422
423
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const markdownpdf = require('markdown-pdf');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const util = require('util');
const os = require('os');
const crypto = require('crypto');
const execPromise = util.promisify(exec);
// Pattern to detect markdown headings
const HEADING_PATTERN = /^\s*#{1,6}\s+.*/;
// Global reference to extension path for resource access
let extensionPath = null;
// Configuration defaults
const DEFAULT_CONFIG = {
openaiBaseUrl: 'http://localhost:11434/v1',
openaiModel: 'translategemma',
openaiApiKey: 'sk-1234'
};
// Load configuration from settings
function getConfig() {
return {
openaiBaseUrl: vscode.workspace.getConfiguration('markdown-export-tools').get('openaiBaseUrl', DEFAULT_CONFIG.openaiBaseUrl),
openaiModel: vscode.workspace.getConfiguration('markdown-export-tools').get('openaiModel', DEFAULT_CONFIG.openaiModel),
openaiApiKey: vscode.workspace.getConfiguration('markdown-export-tools').get('openaiApiKey', DEFAULT_CONFIG.openaiApiKey)
};
}
// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
// Store extension path for later use
extensionPath = context.extensionPath;
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "markdown-export-tools" is now active!');
// Register the export to PDF command
let exportToPdfDisposable = vscode.commands.registerCommand('markdown-export-tools.exportToPdf', function () {
// Get the currently active text editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('No active editor found!');
return;
}
// Check if the current file is a markdown file
if (editor.document.languageId !== 'markdown') {
vscode.window.showErrorMessage('The current file is not a Markdown file!');
return;
}
// Get the file path
const filePath = editor.document.fileName;
const fileName = path.basename(filePath, '.md');
const fileDir = path.dirname(filePath);
// Create the output path
const outputPath = path.join(fileDir, `${fileName}.pdf`);
// Show progress message
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "Exporting to PDF...",
cancellable: false
}, async (progress, token) => {
return new Promise((resolve) => {
// Use cssPath option to reference the external CSS file
markdownpdf({ cssPath: path.join(__dirname, 'table-styles.css') }).from(filePath).to(outputPath, () => {
vscode.window.showInformationMessage(`PDF exported successfully: ${outputPath}`);
resolve();
});
});
});
});
// Function to optimize markdown headings by adding empty lines before headings
function optimizeMarkdownHeadings(markdownText) {
const lines = markdownText.split(/\r\n|\r|\n/); // 兼容各种换行符
if (lines.length === 0) return markdownText;
const newLines = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isHeading = HEADING_PATTERN.test(line);
if (i === 0) {
newLines.push(line);
} else {
if (isHeading) {
const prevLine = lines[i - 1];
// 如果前一行不是空行(非全空白),则插入空行
if (prevLine.trim() !== '') {
newLines.push(''); // 插入空行
}
newLines.push(line);
} else {
newLines.push(line);
}
}
}
// 自动检测原文件换行符类型(简单策略:看第一行结尾)
let eol = '\n';
if (markdownText.includes('\r\n')) {
eol = '\r\n';
} else if (markdownText.includes('\r')) {
eol = '\r';
}
return newLines.join(eol);
}
// 修改 exportToWordDisposable 的实现,使用 Pandoc 和临时文件 + 自定义参考文档
let exportToWordDisposable = vscode.commands.registerCommand('markdown-export-tools.exportToWord', async function () {
// Get the currently active text editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('No active editor found!');
return;
}
// Check if the current file is a markdown file
if (editor.document.languageId !== 'markdown') {
vscode.window.showErrorMessage('The current file is not a Markdown file!');
return;
}
// Get the file path
const filePath = editor.document.fileName;
const fileName = path.basename(filePath, '.md');
const fileDir = path.dirname(filePath);
// Create the output path
const outputPath = path.join(fileDir, `${fileName}.docx`);
// Show progress message
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "Exporting to Word Docx (using Pandoc)...",
cancellable: false
}, async (progress, token) => {
let tempInputFile = null;
try {
// Read the markdown content
let markdownContent = editor.document.getText();
// Preprocess markdown content to optimize headings
markdownContent = optimizeMarkdownHeadings(markdownContent);
// Add CSS styles for tables
const tableCss = `
<style>
table {
border-collapse: collapse !important;
width: 100% !important;
margin: 5px 0 !important;
}
table, th, td {
border: 1px solid #000 !important;
}
th, td {
padding: 4px !important;
text-align: left !important;
}
th {
background-color: #f2f2f2 !important;
font-weight: bold !important;
}
tr:nth-child(even) {
background-color: #f9f9f9 !important;
}
</style>
`;
// markdownContent = tableCss + markdownContent;
// Create a temporary markdown file for input
const tempDir = os.tmpdir();
const tempFileName = `temp-md-${crypto.randomBytes(8).toString('hex')}.md`;
tempInputFile = path.join(tempDir, tempFileName);
// Write markdown content to temp file
fs.writeFileSync(tempInputFile, markdownContent, 'utf8');
// Get path to bundled reference.docx (place it in your extension root)
const referenceDocPath = path.join(extensionPath, 'template.docx');
// Check if reference doc exists
if (!fs.existsSync(referenceDocPath)) {
throw new Error('template.docx not found in extension folder. Please create it with custom table styles.');
}
// Prepare Pandoc command using the temp file and reference doc for styling
const pandocCommand = `pandoc "${tempInputFile}" -f markdown -t docx --reference-doc="${referenceDocPath}" -o "${outputPath}"`;
// Execute Pandoc
const { stdout, stderr } = await execPromise(pandocCommand);
if (stderr && !stderr.includes('Warning:') && !stderr.includes('Note:')) {
throw new Error(stderr);
}
vscode.window.showInformationMessage(`Word document exported successfully: ${outputPath}`);
} catch (error) {
// Check if Pandoc is not installed
if (error.message.includes('spawn pandoc ENOENT') || error.message.includes('command not found')) {
vscode.window.showErrorMessage('Pandoc is not installed or not in PATH. Please install Pandoc from https://pandoc.org/installing.html');
} else if (error.message.includes('reference.docx not found')) {
vscode.window.showErrorMessage(error.message + '\n\nHow to create reference.docx:\n1. Open Word, insert a table (e.g., 2x2).\n2. Select the table, go to Table Design > Borders > All Borders (set to black, 1pt).\n3. Save as reference.docx in your extension folder.\n4. Pandoc will apply this style to all tables.');
} else {
vscode.window.showErrorMessage('Error exporting to Word: ' + error.message);
}
console.error(error);
} finally {
// Clean up temp file if it exists
if (tempInputFile && fs.existsSync(tempInputFile)) {
fs.unlinkSync(tempInputFile);
}
}
});
});
context.subscriptions.push(exportToPdfDisposable);
context.subscriptions.push(exportToWordDisposable);
// Register the format markdown command
let formatMarkdownDisposable = vscode.commands.registerCommand('markdown-export-tools.formatMarkdown', async function () {
// Get the currently active text editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('No active editor found!');
return;
}
// Check if the current file is a markdown file
if (editor.document.languageId !== 'markdown') {
vscode.window.showErrorMessage('The current file is not a Markdown file!');
return;
}
// Get the markdown content
const markdownContent = editor.document.getText();
// Optimize the markdown headings
const formattedContent = optimizeMarkdownHeadings(markdownContent);
// Apply the formatted content back to the editor
const fullRange = new vscode.Range(
editor.document.positionAt(0),
editor.document.positionAt(markdownContent.length)
);
// Edit the document with the formatted content
await editor.edit(editBuilder => {
editBuilder.replace(fullRange, formattedContent);
});
vscode.window.showInformationMessage('Markdown formatted successfully!');
});
context.subscriptions.push(formatMarkdownDisposable);
// Register the translate to Chinese command
// Register the translate to Chinese command
let translateToChineseDisposable = vscode.commands.registerCommand('markdown-export-tools.translateToChinese', async function () {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('No active editor found!');
return;
}
if (editor.document.languageId !== 'markdown') {
vscode.window.showErrorMessage('The current file is not a Markdown file!');
return;
}
const config = getConfig();
const filePath = editor.document.fileName;
const fileName = path.basename(filePath, '.md');
const fileDir = path.dirname(filePath);
const cnFilePath = path.join(fileDir, `${fileName}_CN.md`);
const markdownContent = editor.document.getText();
const paragraphs = markdownContent.split(/\n\s*\n/);
// 初始化文件
fs.writeFileSync(cnFilePath, '');
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "Translating to Chinese...",
cancellable: true
}, async (progress, token) => {
let result = '';
for (let i = 0; i < paragraphs.length; i++) {
if (token.isCancellationRequested) break;
const para = paragraphs[i];
const trimmedPara = para.trim();
// 1. 添加原文
result += para;
if (i < paragraphs.length - 1) result += '\n\n';
if (!trimmedPara) continue;
progress.report({ message: `Translating paragraph ${i + 1}/${paragraphs.length}` });
let translatedText = null; // 移除了 TypeScript 类型注释
let shouldStopTask = false;
// 2. 独立的重试逻辑
for (let retry = 0; retry < 3; retry++) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 120000);
const response = await fetch(`${config.openaiBaseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.openaiApiKey}`
},
body: JSON.stringify({
model: config.openaiModel,
messages: [
{ role: 'system', content: 'You are a professional translator. Translate the following markdown text to Chinese. Translate only the text content, DO NOT translate any code blocks (enclosed in ```), inline code (enclosed in `), or any programming-related content. Keep the markdown formatting intact.' },
{ role: 'user', content: trimmedPara }
]
}),
signal: controller.signal
});
clearTimeout(timeoutId);
// 处理 HTTP 错误状态
if (!response.ok) {
const status = response.status;
// 如果是 4xx (如 401, 429),通常重试无效,直接抛出错误停止任务
if (status >= 400 && status < 500) {
throw new Error(`API Client Error: ${status}. Please check your API Key or settings.`);
}
// 5xx 或网络错误,抛出错误进入 catch 进行重试
throw new Error(`API Server Error: ${status}`);
}
const data = await response.json();
translatedText = data.choices[0].message.content.trim();
break; // 成功,跳出重试循环
} catch (error) {
// 明确判断是否为超时
if (error.name === 'AbortError' || error.message.includes('ETIMEDOUT') || error.message.includes('ECONNRESET')) {
if (retry === 2) {
vscode.window.showErrorMessage(`Translation timed out at paragraph ${i + 1} after 3 retries.`);
shouldStopTask = true;
} else {
progress.report({ message: `Timeout/Network error, retrying paragraph ${i + 1} (${retry + 1}/3)...` });
}
} else {
// 非网络错误(如 401 Unauthorized),直接停止
vscode.window.showErrorMessage(`Translation failed at paragraph ${i + 1}: ${error.message}`);
shouldStopTask = true;
}
}
}
// 3. 检查是否需要停止整个任务
if (shouldStopTask) {
break;
}
// 4. 如果翻译成功,写入结果
if (translatedText) {
result += translatedText;
if (i < paragraphs.length - 1) result += '\n\n';
// 写入文件
fs.appendFileSync(cnFilePath, translatedText);
if (i < paragraphs.length - 1) fs.appendFileSync(cnFilePath, '\n\n');
// 建议:不要每段都更新 UI,或者使用 debounce,这里为了演示保持原逻辑
// 注意:频繁 edit 会导致撤销栈爆炸,建议仅在最后更新,或者每 N 段更新一次
const fullRange = new vscode.Range(
editor.document.positionAt(0),
editor.document.positionAt(result.length) // 注意这里应该是 result 的长度,不是原文长度
);
// 使用 applyEdit 可能会更好,但 edit 也可以
await editor.edit(editBuilder => editBuilder.replace(fullRange, result));
}
}
if (!token.isCancellationRequested) {
vscode.window.showInformationMessage(`Translation completed! Chinese file: ${cnFilePath}`);
}
});
});
context.subscriptions.push(translateToChineseDisposable);
}
// This method is called when your extension is deactivated
function deactivate() {}
module.exports = {
activate,
deactivate
}