-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathprint-block-comment.ts
More file actions
42 lines (36 loc) · 1.14 KB
/
print-block-comment.ts
File metadata and controls
42 lines (36 loc) · 1.14 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
import { doc } from 'prettier';
import type { Doc } from 'prettier';
import type { BlockComment } from '../slang-nodes/types.d.ts';
const { hardline, join, literalline } = doc.builders;
function trimmedIndentableLines(lines: string[]): string[] | undefined {
// If the comment has multiple lines and every line starts with a star
// we can fix the indentation of each line.
if (lines.length > 1) {
const trimmedLines = [];
for (let line of lines) {
line = line.trimStart();
if (!line.startsWith('*')) {
return;
}
trimmedLines.push(line);
}
return trimmedLines;
}
}
function printIndentableBlockComment(lines: string[]): Doc {
return join(
hardline,
lines.map((line, index) => `${index === 0 ? '' : ' '}${line.trimEnd()}`)
);
}
export function printBlockComment(comment: BlockComment): Doc {
// We remove the initial `/` to check if every line starts with `*`
const lines = comment.value.slice(1).split('\n');
const trimmedLines = trimmedIndentableLines(lines);
return [
'/',
trimmedLines
? printIndentableBlockComment(trimmedLines)
: join(literalline, lines)
];
}