-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathpug-comment-preserve-spaces.ts
75 lines (72 loc) · 2.1 KB
/
pug-comment-preserve-spaces.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
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
import type { ChoiceSupportOption } from 'prettier';
import { CATEGORY_PUG } from './constants';
/** Pug comment preserve spaces option. */
export const PUG_COMMENT_PRESERVE_SPACES_OPTION: ChoiceSupportOption<PugCommentPreserveSpaces> =
{
// since: '1.6.0',
category: CATEGORY_PUG,
type: 'choice',
default: 'keep-all',
description: 'Change behavior of spaces within comments.',
choices: [
{
value: 'keep-all',
description:
'Keep all spaces within comments. Example: `// this is a comment`',
},
{
value: 'keep-leading',
description:
'Keep leading spaces within comments. Example: `// this is a comment`',
},
{
value: 'trim-all',
description:
'Trim all spaces within comments. Example: `// this is a comment`',
},
],
};
/** Pug Comment preserve spaces. */
export type PugCommentPreserveSpaces = 'keep-all' | 'keep-leading' | 'trim-all';
/**
* Format comment with the given settings.
*
* @param input The comment.
* @param pugCommentPreserveSpaces How to preserve spaces in the comment.
* @param pipeless Whether it's a pipeless comment ot not. Default: `false`.
* @returns The formatted comment.
*/
export function formatPugCommentPreserveSpaces(
input: string,
pugCommentPreserveSpaces: PugCommentPreserveSpaces,
pipeless: boolean = false,
): string {
switch (pugCommentPreserveSpaces) {
case 'keep-leading': {
let result: string = '';
let firstNonSpace: number = 0;
for (
firstNonSpace;
firstNonSpace < input.length && input[firstNonSpace] === ' ';
firstNonSpace++
) {
result += ' ';
}
result += input.slice(firstNonSpace).trim().replaceAll(/\s\s+/g, ' ');
return result;
}
case 'trim-all': {
let result: string = input.trim();
result = result.replaceAll(/\s\s+/g, ' ');
if (!pipeless && input[0] === ' ') {
result = ` ${result}`;
}
return result;
}
case 'keep-all':
default: {
// Don't touch comment
return input;
}
}
}