-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
105 lines (83 loc) · 2.51 KB
/
extension.js
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
const { mdToPdf } = require("md-to-pdf");
const vscode = require("vscode");
const fs = require("fs");
/**
* turns code snippet into markdown code snippet
* @param {string} content - content
* @param {string} language - file/language extension
* @returns {string} string as markdown code embed
*/
function textToMD(content, language) {
return `\`\`\`${language}\n${content}\n`;
}
function shouldIncludePdfExtension(filepath) {
if (filepath.includes(".pdf")) return filepath;
return filepath + ".pdf";
}
function getFilePath(filePathWithExtension) {
const filePath = filePathWithExtension.split(".");
filePath.pop();
return filePath.join(".");
}
async function save(text, language) {
const md = textToMD(text, language);
const options = {
saveLabel: "Save",
filters: {
"PDF Files": ["pdf"],
},
};
const uri = await vscode.window.showSaveDialog(options);
if (!uri) {
vscode.window.showWarningMessage(
"A file path is required to save the PDF file."
);
return;
}
const filePath = uri.fsPath;
try {
const { content, filename } = await mdToPdf(
{ content: md },
{ dest: shouldIncludePdfExtension(filePath) }
);
const showInExplorerButton = { title: "Open in explorer" };
const shouldOpenInExplorer = await vscode.window.showInformationMessage(
"File saved to: " + filePath,
showInExplorerButton
);
if (shouldOpenInExplorer === showInExplorerButton)
vscode.commands.executeCommand(
"revealFileInOS",
vscode.Uri.file(getFilePath(filename))
);
fs.writeFileSync(filename, content);
} catch (error) {
vscode.window.showErrorMessage(
"An error occurred: Could not convert to pdf \n" + error
);
}
}
function activate(context) {
const otherCmd = vscode.commands.registerCommand("pdfycode.isInstalled", () => {
vscode.window.showInformationMessage("PDFyCode is installed");
})
context.subscriptions.push(otherCmd)
const cmd = vscode.commands.registerCommand("pdfycode.code2pdf", () => {
const ed = vscode.window.activeTextEditor;
if (!ed) return;
const selection = ed.selection;
if (!selection.isEmpty) {
const fileName = ed.document.fileName;
const selectedText = ed.document.getText(selection);
const lang = fileName.split(".").pop();
save(selectedText, lang);
}
});
context.subscriptions.push(cmd);
}
// This method is called when your extension is deactivated
function deactivate() {}
module.exports = {
activate,
deactivate,
};