-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugin.js
101 lines (96 loc) · 2.97 KB
/
plugin.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
const { parsers } = require("prettier/parser-html");
const {
printer: { printDocToString },
} = require("prettier").doc;
const quotation = require("./quotation");
const tag = require("./tag");
const ESCAPE_TAG_REGEX = /<(\s*\/\s*)?([\w:-]+)/g;
const ESCAPE_JSP_TAG_REGEX = /<%@([\w\W]+?)%>/g;
const ESCAPE_JSP_COMMENT_REGEX = /<%--([\w\W]+?)--%>/g;
const ESCAPE_ATTRS_REGEX = /<([\w]+)\s*([\s\S]*?)>/g;
const ESCAPE_ATTR_REGEX = /\$\{(.+?)\}/g;
const parser = {
...parsers.html,
astFormat: "jsp",
preprocess: (text) => {
return text
.replace(ESCAPE_JSP_TAG_REGEX, "<JSP $1 />")
.replace(ESCAPE_JSP_COMMENT_REGEX, "<!--$1-->")
.replace(ESCAPE_TAG_REGEX, (_, m1, m2) => `<${m1 ?? ""}${tag.escape(m2)}`)
.replace(ESCAPE_ATTRS_REGEX, (_, m1, m2) => {
const attrs = m2.replace(
ESCAPE_ATTR_REGEX,
(_, m1) => "${" + quotation.escape(m1) + "}"
);
return `<${m1} ${attrs}>`;
});
},
};
const getPrinter = (options) => {
const plugin = options.plugins.find((p) => p.parsers?.html);
return plugin.printers.html;
};
/**
* @type {import('prettier').Plugin}
*/
const plugin = {
languages: [
{
name: "Java Server Pages",
parsers: ["jsp"],
tmScope: "text.html.jsp",
aceMode: "jsp",
codemirrorMode: "htmlembedded",
codemirrorMimeType: "application/x-jsp",
extensions: [".jsp", ".tag"],
linguistLanguageId: 182,
vscodeLanguageIds: ["jsp"],
},
],
parsers: {
jsp: parser,
},
printers: {
jsp: {
preprocess: (ast, options) => {
return getPrinter(options).preprocess(ast, options);
},
insertPragma: (text) => {
return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
},
embed: (path, print, textToDoc, options) => {
const node = path.getValue();
switch (node.type) {
case "attribute":
node.value = quotation.unescape(node.value);
node.name = quotation.unescape(node.name);
if (node.name === style) return node.value;
break;
case "element":
node.name = tag.unescape(node.name);
break;
case "text":
node.value = quotation.unescape(node.value);
break;
}
return getPrinter(options).embed(path, print, textToDoc, options);
},
print: (path, options, print) => {
const node = path.getValue();
if (node.type === "element" && node.name === "JSP") {
const res = getPrinter(options).print(path, options, print);
const txt = printDocToString(res, {
...options,
printWidth: Infinity,
}).formatted;
return txt.replace(/^<JSP/, "<%@").replace(/\/>$/, "%>");
} else if (node.type === "comment") {
return `<%-- ${node.value.trim()} --%>`;
} else {
return getPrinter(options).print(path, options, print);
}
},
},
},
};
module.exports = plugin;