generated from SevenOutman/ts-lib-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
47 lines (38 loc) · 1.53 KB
/
index.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
import type { Plugin } from "prettier"
import { parsers as prettierMarkdownParsers } from "prettier/parser-markdown"
const markdownParser = prettierMarkdownParsers["markdown"]
export const parsers: Plugin["parsers"] = {
markdown: {
...markdownParser,
preprocess(text, options) {
if (markdownParser.preprocess) {
text = markdownParser.preprocess(text, options)
}
// Sort the table directly following <!-- prettier-sort-markdown-table --> annotation (if any)
text = text.replace(
// Regex reference: https://stackoverflow.com/a/29616512
/<!--\s*prettier-sort-markdown-table\s*-->\r?\n(?:\s*\r?\n)*(\|(?:([^\r\n|]*)\|)+\r?\n\|(?:(\s*:?-+:?\s*)\|)+\r?\n(\|(?:([^\r\n|]*)\|)+(?:\r?\n)?)+)/g,
(match) => {
const lines = match.split(/\r?\n/)
const annotationLines = [lines.shift()]
// Push empty lines between annotation and table
while (!lines[0].startsWith("|")) {
annotationLines.push(lines.shift())
}
const tableHeaderLines = [lines.shift(), lines.shift()]
// Sort table body rows here
const tableBodyLines = lines.filter(Boolean).sort()
// The regex matched trailing newlines following the table
const trailingNewlines = lines.slice(tableBodyLines.length)
return [
...annotationLines,
...tableHeaderLines,
...tableBodyLines,
...trailingNewlines,
].join("\n")
},
)
return text
},
},
}