-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathprinter.ts
1216 lines (1122 loc) · 37.9 KB
/
printer.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { format, RequiredOptions } from 'prettier';
import {
AndAttributesToken,
AttributeToken,
BlockcodeToken,
BlockToken,
CallToken,
CaseToken,
ClassToken,
CodeToken,
ColonToken,
CommentToken,
DefaultToken,
DoctypeToken,
DotToken,
EachOfToken,
EachToken,
ElseIfToken,
ElseToken,
EndAttributesToken,
EndPipelessTextToken,
EndPugInterpolationToken,
EosToken,
ExtendsToken,
FilterToken,
IdToken,
IfToken,
IncludeToken,
IndentToken,
InterpolatedCodeToken,
InterpolationToken,
LexTokenType,
MixinBlockToken,
MixinToken,
NewlineToken,
OutdentToken,
PathToken,
SlashToken,
StartAttributesToken,
StartPipelessTextToken,
StartPugInterpolationToken,
TagToken,
TextHtmlToken,
TextToken,
Token,
WhenToken,
WhileToken,
YieldToken
} from 'pug-lexer';
import { DoctypeShortcut, DOCTYPE_SHORTCUT_REGISTRY } from './doctype-shortcut-registry';
import { createLogger, Logger, LogLevel } from './logger';
import { AttributeSeparator, resolveAttributeSeparatorOption } from './options/attribute-separator';
import { SortAttributes } from './options/attribute-sorting';
import { compareAttributeToken, partialSort } from './options/attribute-sorting/utils';
import { ClosingBracketPosition, resolveClosingBracketPositionOption } from './options/closing-bracket-position';
import { CommentPreserveSpaces, formatCommentPreserveSpaces } from './options/comment-preserve-spaces';
import { ArrowParens } from './options/common';
import { isAngularAction, isAngularBinding, isAngularDirective, isAngularInterpolation } from './utils/angular';
import {
handleBracketSpacing,
isMultilineInterpolation,
isQuoted,
makeString,
previousNormalAttributeToken,
unwrapLineFeeds
} from './utils/common';
import { isVueEventBinding, isVueExpression } from './utils/vue';
const logger: Logger = createLogger(console);
if (process.env.NODE_ENV === 'test') {
logger.setLogLevel(LogLevel.DEBUG);
}
export interface PugPrinterOptions {
readonly printWidth: number;
readonly pugPrintWidth: number;
readonly singleQuote: boolean;
readonly pugSingleQuote: boolean;
readonly tabWidth: number;
readonly pugTabWidth: number;
readonly useTabs: boolean;
readonly pugUseTabs: boolean;
readonly bracketSpacing: boolean;
readonly pugBracketSpacing: boolean;
readonly arrowParens: ArrowParens;
readonly pugArrowParens: ArrowParens;
readonly semi: boolean;
readonly pugSemi: boolean;
readonly attributeSeparator: AttributeSeparator;
readonly closingBracketPosition: ClosingBracketPosition;
readonly commentPreserveSpaces: CommentPreserveSpaces;
readonly pugSortAttributes: SortAttributes;
readonly pugSortAttributesBeginning: string[];
readonly pugSortAttributesEnd: string[];
readonly pugWrapAttributesThreshold: number;
readonly pugWrapAttributesPattern: string;
}
export class PugPrinter {
private result: string = '';
/**
* The index of the current token inside the `tokens` array
*/
// Start at -1, because `getNextToken()` increases it before retreval
private currentIndex: number = -1;
private currentLineLength: number = 0;
private readonly indentString: string;
private indentLevel: number = 0;
private readonly quotes: "'" | '"';
private readonly otherQuotes: "'" | '"';
private readonly alwaysUseAttributeSeparator: boolean;
private readonly neverUseAttributeSeparator: boolean;
private readonly closingBracketRemainsAtNewLine: boolean;
private readonly wrapAttributesPattern: RegExp | null;
/* eslint-disable @typescript-eslint/indent */
private readonly codeInterpolationOptions: Pick<
RequiredOptions,
'singleQuote' | 'bracketSpacing' | 'arrowParens' | 'printWidth' | 'endOfLine'
>;
/* eslint-enable @typescript-eslint/indent */
private currentTagPosition: number = 0;
private possibleIdPosition: number = 0;
private possibleClassPosition: number = 0;
private previousAttributeRemapped: boolean = false;
private wrapAttributes: boolean = false;
private pipelessText: boolean = false;
private pipelessComment: boolean = false;
public constructor(
private readonly content: string,
private tokens: Token[],
private readonly options: PugPrinterOptions
) {
this.indentString = options.pugUseTabs ? '\t' : ' '.repeat(options.pugTabWidth);
this.quotes = this.options.pugSingleQuote ? "'" : '"';
this.otherQuotes = this.options.pugSingleQuote ? '"' : "'";
const attributeSeparator: AttributeSeparator = resolveAttributeSeparatorOption(options.attributeSeparator);
this.alwaysUseAttributeSeparator = attributeSeparator === 'always';
this.neverUseAttributeSeparator = attributeSeparator === 'none';
this.closingBracketRemainsAtNewLine = resolveClosingBracketPositionOption(options.closingBracketPosition);
const wrapAttributesPattern: string = options.pugWrapAttributesPattern;
this.wrapAttributesPattern = wrapAttributesPattern ? new RegExp(wrapAttributesPattern) : null;
const codeSingleQuote: boolean = !options.pugSingleQuote;
this.codeInterpolationOptions = {
singleQuote: codeSingleQuote,
bracketSpacing: options.pugBracketSpacing ?? options.bracketSpacing,
arrowParens: options.pugArrowParens ?? options.arrowParens,
printWidth: 9000,
endOfLine: 'lf'
};
}
public build(): string {
const results: string[] = [];
if (this.tokens[0]?.type === 'text') {
results.push('| ');
} else if (this.tokens[0]?.type === 'eos') {
return '';
}
let token: Token | null = this.getNextToken();
while (token) {
logger.debug('[PugPrinter]:', JSON.stringify(token));
try {
switch (token.type) {
case 'attribute':
case 'class':
case 'end-attributes':
case 'id':
case 'eos':
// TODO: These tokens write directly into the result
this.result = results.join('');
// @ts-expect-error
this[token.type](token);
results.length = 0;
results.push(this.result);
break;
case 'tag':
case 'start-attributes':
case 'interpolation':
case 'call':
case ':':
// TODO: These tokens read the length of the result
this.result = results.join('');
// eslint-disable-next-line no-fallthrough
default:
// @ts-expect-error
results.push(this[token.type](token));
break;
}
} catch {
throw new Error('Unhandled token: ' + JSON.stringify(token));
}
token = this.getNextToken();
}
return results.join('');
}
// ## ## ######## ## ######## ######## ######## ######
// ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## ## ## ## ## ## ## ##
// ######### ###### ## ######## ###### ######## ######
// ## ## ## ## ## ## ## ## ##
// ## ## ## ## ## ## ## ## ## ##
// ## ## ######## ######## ## ######## ## ## ######
//#region Helpers
private get computedIndent(): string {
switch (this.previousToken?.type) {
case 'newline':
case 'outdent':
return this.indentString.repeat(this.indentLevel);
case 'indent':
return this.indentString;
}
return '';
}
private get previousToken(): Token | undefined {
return this.tokens[this.currentIndex - 1];
}
private get nextToken(): Token | undefined {
return this.tokens[this.currentIndex + 1];
}
private getNextToken(): Token | null {
this.currentIndex++;
return this.tokens[this.currentIndex] ?? null;
}
private quoteString(val: string): string {
return `${this.quotes}${val}${this.quotes}`;
}
private checkTokenType(token: Token | undefined, possibilities: LexTokenType[], invert: boolean = false): boolean {
return !!token && possibilities.includes(token.type) !== invert;
}
private tokenNeedsSeparator(token: AttributeToken): boolean {
return this.neverUseAttributeSeparator
? false
: this.alwaysUseAttributeSeparator || /^(\(|\[|:).*/.test(token.name);
}
private getUnformattedContentLines(firstToken: Token, lastToken: Token): string[] {
const { start } = firstToken.loc;
const { end } = lastToken.loc;
const lines: string[] = this.content.split(/\r\n|\n|\r/);
const startLine: number = start.line - 1;
const endLine: number = end.line - 1;
const parts: string[] = [];
parts.push(lines[startLine].slice(start.column - 1));
for (let line: number = startLine + 1; line < endLine; line++) {
parts.push(lines[line]);
}
parts.push(lines[endLine].slice(0, end.column - 1));
return parts;
}
private replaceTagWithLiteralIfPossible(search: RegExp, replace: string): void {
const currentTagEnd: number = Math.max(this.possibleIdPosition, this.possibleClassPosition);
const tag: string = this.result.slice(this.currentTagPosition, currentTagEnd);
const replaced: string = tag.replace(search, replace);
if (replaced !== tag) {
const prefix: string = this.result.slice(0, this.currentTagPosition);
const suffix: string = this.result.slice(currentTagEnd);
this.result = `${prefix}${replaced}${suffix}`;
// tag was replaced, so adjust possible positions as well
const diff: number = tag.length - replaced.length;
this.possibleIdPosition -= diff;
this.possibleClassPosition -= diff;
}
}
private formatDelegatePrettier(
val: string,
parser: '__vue_expression' | '__ng_binding' | '__ng_action' | '__ng_directive'
): string {
val = val.trim();
val = val.slice(1, -1);
val = format(val, { parser: parser as any, ...this.codeInterpolationOptions });
val = unwrapLineFeeds(val);
return this.quoteString(val);
}
private formatText(text: string): string {
let result: string = '';
while (text) {
const start: number = text.indexOf('{{');
if (start !== -1) {
result += text.slice(0, start);
text = text.slice(start + 2);
const end: number = text.indexOf('}}');
if (end !== -1) {
let code: string = text.slice(0, end);
try {
// Index of primary quote
const q1: number = code.indexOf(this.quotes);
// Index of secondary (other) quote
const q2: number = code.indexOf(this.otherQuotes);
// Index of backtick
const qb: number = code.indexOf('`');
if (q1 >= 0 && q2 >= 0 && q2 > q1 && (qb < 0 || q1 < qb)) {
logger.log({
code,
quotes: this.quotes,
otherQuotes: this.otherQuotes,
q1,
q2,
qb
});
logger.warn(
'The following expression could not be formatted correctly. Please try to fix it yourself and if there is a problem, please open a bug issue:',
code
);
result += handleBracketSpacing(this.options.pugBracketSpacing, code);
text = text.slice(end + 2);
continue;
} else {
code = format(code, {
parser: '__ng_interpolation' as any,
...this.codeInterpolationOptions
});
}
} catch (error: unknown) {
if (typeof error === 'string') {
if (error.includes('Unexpected token Lexer Error')) {
if (!error.includes('Unexpected character [`]')) {
logger.debug('[PugPrinter:formatText]: Using fallback strategy');
}
} else if (error.includes('Bindings cannot contain assignments')) {
logger.warn(
'[PugPrinter:formatText]: Bindings should not contain assignments:',
code.trim()
);
} else if (error.includes("Unexpected token '('")) {
logger.warn(
"[PugPrinter:formatText]: Found unexpected token '('. If you are using Vue, you can ignore this message."
);
} else {
logger.warn('[PugPrinter:formatText]: ', error);
}
// else ignore message
} else {
logger.warn('[PugPrinter:formatText]: ', error);
}
try {
code = format(code, {
parser: 'babel',
...this.codeInterpolationOptions,
semi: false
});
if (code[0] === ';') {
code = code.slice(1);
}
} catch (error: unknown) {
logger.warn(error);
}
}
code = unwrapLineFeeds(code);
result += handleBracketSpacing(this.options.pugBracketSpacing, code);
text = text.slice(end + 2);
} else {
result += '{{';
result += text;
text = '';
}
} else {
result += text;
text = '';
}
}
return result;
}
private formatVueEventBinding(val: string): string {
val = val.trim();
val = val.slice(1, -1); // Remove quotes
val = format(val, { parser: '__vue_event_binding' as any, ...this.codeInterpolationOptions });
val = unwrapLineFeeds(val);
if (val[val.length - 1] === ';') {
val = val.slice(0, -1);
}
return this.quoteString(val);
}
private formatVueExpression(val: string): string {
return this.formatDelegatePrettier(val, '__vue_expression');
}
private formatAngularBinding(val: string): string {
return this.formatDelegatePrettier(val, '__ng_binding');
}
private formatAngularAction(val: string): string {
return this.formatDelegatePrettier(val, '__ng_action');
}
private formatAngularDirective(val: string): string {
return this.formatDelegatePrettier(val, '__ng_directive');
}
private formatAngularInterpolation(val: string): string {
val = val.slice(1, -1); // Remove quotes
val = val.slice(2, -2); // Remove braces
val = val.trim();
if (val.includes(`\\${this.otherQuotes}`)) {
logger.warn(
'The following expression could not be formatted correctly. Please try to fix it yourself and if there is a problem, please open a bug issue:',
val
);
} else {
val = format(val, {
parser: '__ng_interpolation' as any,
...this.codeInterpolationOptions
});
val = unwrapLineFeeds(val);
}
val = handleBracketSpacing(this.options.pugBracketSpacing, val);
return this.quoteString(val);
}
//#endregion
// ######## ####### ## ## ######## ## ## ######## ######## ####### ###### ######## ###### ###### ####### ######## ######
// ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## ##### ###### ## ## ## ######## ######## ## ## ## ###### ###### ###### ## ## ######## ######
// ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
// ## ####### ## ## ######## ## ## ## ## ## ####### ###### ######## ###### ###### ####### ## ## ######
//#region Token Processors
private tag(token: TagToken): string {
let val: string = token.val;
if (val === 'div' && this.nextToken && (this.nextToken.type === 'class' || this.nextToken.type === 'id')) {
val = '';
}
this.currentLineLength += val.length;
const result: string = `${this.computedIndent}${val}`;
logger.debug('tag', { result, val: token.val, length: token.val.length }, this.currentLineLength);
this.currentTagPosition = this.result.length + this.computedIndent.length;
this.possibleIdPosition = this.result.length + result.length;
this.possibleClassPosition = this.result.length + result.length;
return result;
}
private ['start-attributes'](token: StartAttributesToken): string {
let result: string = '';
if (this.nextToken?.type === 'attribute') {
this.previousAttributeRemapped = false;
this.possibleClassPosition = this.result.length;
result = '(';
logger.debug(this.currentLineLength);
let tempToken: AttributeToken | EndAttributesToken = this.nextToken;
let tempIndex: number = this.currentIndex + 1;
// In pug, tags can have two kind of attributes: normal attributes that appear between parantheses,
// and literals for ids and classes, prefixing the paranthesis, e.g.: `#id.class(attribute="value")`
// https://pugjs.org/language/attributes.html#class-literal
// https://pugjs.org/language/attributes.html#id-literal
// In the stream of attribute tokens, distinguish those that can be converted to literals,
// and count those that cannot (normal attributes) to determine the resulting line length correctly.
let hasLiteralAttributes: boolean = false;
let numNormalAttributes: number = 0;
while (tempToken.type === 'attribute') {
if (!this.wrapAttributes && this.wrapAttributesPattern?.test(tempToken.name)) {
this.wrapAttributes = true;
}
switch (tempToken.name) {
case 'class':
case 'id': {
hasLiteralAttributes = true;
const val: string = tempToken.val.toString();
if (isQuoted(val)) {
this.currentLineLength -= 2;
}
this.currentLineLength += 1 + val.length;
logger.debug(
{ tokenName: tempToken.name, length: tempToken.name.length },
this.currentLineLength
);
break;
}
default: {
this.currentLineLength += tempToken.name.length;
if (numNormalAttributes > 0) {
// This isn't the first normal attribute that will appear between parantheses,
// add space and separator
this.currentLineLength += 1;
if (this.tokenNeedsSeparator(tempToken)) {
this.currentLineLength += 1;
}
}
logger.debug(
{ tokenName: tempToken.name, length: tempToken.name.length },
this.currentLineLength
);
const val: string = tempToken.val.toString();
if (val.length > 0 && val !== 'true') {
this.currentLineLength += 1 + val.length;
logger.debug({ tokenVal: val, length: val.length }, this.currentLineLength);
}
numNormalAttributes++;
break;
}
}
tempToken = this.tokens[++tempIndex] as AttributeToken | EndAttributesToken;
}
logger.debug('after token', this.currentLineLength);
if (hasLiteralAttributes) {
// Remove div as it will be replaced with the literal for id and/or class
if (this.previousToken?.type === 'tag' && this.previousToken.val === 'div') {
this.currentLineLength -= 3;
}
}
if (numNormalAttributes > 0) {
// Add leading and trailing parantheses
this.currentLineLength += 2;
}
logger.debug(this.currentLineLength);
if (
!this.wrapAttributes &&
(this.currentLineLength > this.options.pugPrintWidth ||
(this.options.pugWrapAttributesThreshold >= 0 &&
numNormalAttributes > this.options.pugWrapAttributesThreshold))
) {
this.wrapAttributes = true;
}
if (
this.options.pugSortAttributes !== 'as-is' ||
this.options.pugSortAttributesEnd.length > 0 ||
this.options.pugSortAttributesBeginning.length > 0
) {
const startAttributesIndex: number = this.tokens.indexOf(token);
const endAttributesIndex: number = tempIndex;
if (endAttributesIndex - startAttributesIndex > 2) {
this.tokens = partialSort(this.tokens, startAttributesIndex + 1, endAttributesIndex, (a, b) =>
compareAttributeToken(
a as AttributeToken,
b as AttributeToken,
this.options.pugSortAttributes,
this.options.pugSortAttributesBeginning,
this.options.pugSortAttributesEnd
)
);
}
}
}
return result;
}
private attribute(token: AttributeToken): void {
if (typeof token.val === 'string') {
if (isQuoted(token.val)) {
if (token.name === 'class') {
// Handle class attribute
const val: string = token.val.slice(1, -1).trim();
const classes: string[] = val.split(/\s+/);
const specialClasses: string[] = [];
const normalClasses: string[] = [];
const validClassNameRegex: RegExp = /^-?[_a-zA-Z]+[_a-zA-Z0-9-]*$/;
for (const className of classes) {
if (!validClassNameRegex.test(className)) {
specialClasses.push(className);
} else {
normalClasses.push(className);
}
}
if (normalClasses.length > 0) {
// Write css-class in front of attributes
const position: number = this.possibleClassPosition;
this.result = [
this.result.slice(0, position),
'.',
normalClasses.join('.'),
this.result.slice(position)
].join('');
this.possibleClassPosition += 1 + normalClasses.join('.').length;
this.replaceTagWithLiteralIfPossible(/div\./, '.');
}
if (specialClasses.length > 0) {
token.val = makeString(specialClasses.join(' '), this.quotes);
this.previousAttributeRemapped = false;
} else {
this.previousAttributeRemapped = true;
return;
}
} else if (token.name === 'id') {
// Handle id attribute
let val: string = token.val;
val = val.slice(1, -1);
val = val.trim();
const validIdNameRegex: RegExp = /^-?[_a-zA-Z]+[_a-zA-Z0-9-]*$/;
if (!validIdNameRegex.test(val)) {
val = makeString(val, this.quotes);
this.result += 'id';
if (token.mustEscape === false) {
this.result += '!';
}
this.result += `=${val}`;
return;
}
// Write css-id in front of css-classes
const position: number = this.possibleIdPosition;
const literal: string = `#${val}`;
this.result = [this.result.slice(0, position), literal, this.result.slice(position)].join('');
this.possibleClassPosition += literal.length;
this.replaceTagWithLiteralIfPossible(/div#/, '#');
this.previousAttributeRemapped = true;
return;
}
}
}
const hasNormalPreviousToken: AttributeToken | undefined = previousNormalAttributeToken(
this.tokens,
this.currentIndex
);
if (this.previousToken?.type === 'attribute' && (!this.previousAttributeRemapped || hasNormalPreviousToken)) {
if (this.tokenNeedsSeparator(token)) {
this.result += ',';
}
if (!this.wrapAttributes) {
this.result += ' ';
}
}
this.previousAttributeRemapped = false;
if (this.wrapAttributes) {
this.result += '\n';
this.result += this.indentString.repeat(this.indentLevel + 1);
}
this.result += `${token.name}`;
if (typeof token.val === 'boolean') {
if (token.val !== true) {
this.result += `=${token.val}`;
}
} else {
let val: string = token.val;
if (isMultilineInterpolation(val)) {
// do not reformat multiline strings surrounded by `
} else if (isVueExpression(token.name)) {
val = this.formatVueExpression(val);
} else if (isVueEventBinding(token.name)) {
val = this.formatVueEventBinding(val);
} else if (isAngularBinding(token.name)) {
val = this.formatAngularBinding(val);
} else if (isAngularAction(token.name)) {
val = this.formatAngularAction(val);
} else if (isAngularDirective(token.name)) {
val = this.formatAngularDirective(val);
} else if (isAngularInterpolation(val)) {
val = this.formatAngularInterpolation(val);
} else if (isQuoted(val)) {
val = makeString(val.slice(1, -1), this.quotes);
} else if (val === 'true') {
// The value is exactly true and is not quoted
return;
} else if (token.mustEscape) {
val = format(val, {
parser: '__js_expression' as any,
...this.codeInterpolationOptions
});
const lines: string[] = val.split('\n');
const codeIndentLevel: number = this.wrapAttributes ? this.indentLevel + 1 : this.indentLevel;
if (lines.length > 1) {
val = lines[0];
for (let index: number = 1; index < lines.length; index++) {
val += '\n';
val += this.indentString.repeat(codeIndentLevel);
val += lines[index];
}
}
} else {
// The value is not quoted and may be js-code
val = val.trim();
val = val.replace(/\s\s+/g, ' ');
if (val[0] === '{' && val[1] === ' ') {
val = `{${val.slice(2, val.length)}`;
}
}
if (token.mustEscape === false) {
this.result += '!';
}
this.result += `=${val}`;
}
}
private ['end-attributes'](token: EndAttributesToken): void {
if (this.wrapAttributes && this.result[this.result.length - 1] !== '(') {
if (this.closingBracketRemainsAtNewLine) {
this.result += '\n';
}
this.result += this.indentString.repeat(this.indentLevel);
}
this.wrapAttributes = false;
if (this.result[this.result.length - 1] === '(') {
// There were no attributes
this.result = this.result.slice(0, -1);
} else if (this.previousToken?.type === 'attribute') {
if (!this.closingBracketRemainsAtNewLine) {
this.result = this.result.trimRight();
}
this.result += ')';
}
if (this.nextToken?.type === 'text' || this.nextToken?.type === 'path') {
this.result += ' ';
}
}
private indent(token: IndentToken): string {
const result: string = `\n${this.indentString.repeat(this.indentLevel)}`;
this.indentLevel++;
this.currentLineLength = result.length - 1 + 1 + this.indentString.length; // -1 for \n, +1 for non zero based
logger.debug('indent', { result, indentLevel: this.indentLevel }, this.currentLineLength);
return result;
}
private outdent(token: OutdentToken): string {
let result: string = '';
if (this.previousToken && this.previousToken.type !== 'outdent') {
if (token.loc.start.line - this.previousToken.loc.end.line > 1) {
// Insert one extra blank line
result += '\n';
}
result += '\n';
}
this.indentLevel--;
this.currentLineLength = 1 + this.indentString.repeat(this.indentLevel).length; // -1 for \n, +1 for non zero based
logger.debug('outdent', { result, indentLevel: this.indentLevel }, this.currentLineLength);
return result;
}
private class(token: ClassToken): void {
const val: string = `.${token.val}`;
this.currentLineLength += val.length;
logger.debug('class', { val, length: val.length }, this.currentLineLength);
switch (this.previousToken?.type) {
case 'newline':
case 'outdent':
case 'indent': {
this.possibleIdPosition = this.result.length + this.computedIndent.length;
const result: string = `${this.computedIndent}${val}`;
this.result += result;
this.possibleClassPosition = this.result.length;
break;
}
default: {
const prefix: string = this.result.slice(0, this.possibleClassPosition);
this.result = [prefix, val, this.result.slice(this.possibleClassPosition)].join('');
this.possibleClassPosition += val.length;
break;
}
}
if (this.nextToken?.type === 'text') {
this.currentLineLength += 1;
this.result += ' ';
}
}
private eos(token: EosToken): void {
// Remove all newlines at the end
while (this.result[this.result.length - 1] === '\n') {
this.result = this.result.slice(0, -1);
}
// Insert one newline
this.result += '\n';
}
private comment(commentToken: CommentToken): string {
let result: string = this.computedIndent;
// See if this is a `//- prettier-ignore` comment, which would indicate that the part of the template
// that follows should be left unformatted. Support the same format as typescript-eslint is using for descriptons:
// https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/ban-ts-comment.md#allow-with-description
if (/^ prettier-ignore($|[: ])/.test(commentToken.val)) {
// Use a separate token processing loop to find the end of the stream of tokens to be ignored by formatting,
// and uses their `loc` properties to retrieve the original pug code to be used instead.
let token: Token | null = this.getNextToken();
if (token) {
let skipNewline: boolean = token.type === 'newline';
let ignoreLevel: number = 0;
while (token) {
const { type } = token;
if (type === 'newline' && ignoreLevel === 0) {
// Skip first newline after `prettier-ignore` comment
if (skipNewline) {
skipNewline = false;
} else {
break;
}
} else if (type === 'indent') {
ignoreLevel++;
} else if (type === 'outdent') {
ignoreLevel--;
if (ignoreLevel === 0) {
break;
}
}
token = this.getNextToken();
}
if (token) {
const lines: string[] = this.getUnformattedContentLines(commentToken, token);
// Trim the last line, since indentation of formatted pug is handled separately.
const lastLine: string | undefined = lines.pop();
if (lastLine !== undefined) {
lines.push(lastLine.trimRight());
}
result += lines.join('\n');
}
}
} else {
if (this.checkTokenType(this.previousToken, ['newline', 'indent', 'outdent'], true)) {
result += ' ';
}
result += '//';
if (!commentToken.buffer) {
result += '-';
}
result += formatCommentPreserveSpaces(commentToken.val, this.options.commentPreserveSpaces);
if (this.nextToken?.type === 'start-pipeless-text') {
this.pipelessComment = true;
}
}
return result;
}
private newline(token: NewlineToken): string {
let result: string = '';
if (this.previousToken && token.loc.start.line - this.previousToken.loc.end.line > 1) {
// Insert one extra blank line
result += '\n';
}
result += '\n';
this.currentLineLength = 1 + this.indentString.repeat(this.indentLevel).length; // -1 for \n, +1 for non zero based
logger.debug('newline', { result, indentLevel: this.indentLevel }, this.currentLineLength);
return result;
}
private text(token: TextToken): string {
let result: string = '';
let val: string = token.val;
let needsTrailingWhitespace: boolean = false;
if (this.pipelessText) {
switch (this.previousToken?.type) {
case 'newline':
if (val.trim().length > 0) {
result += this.indentString.repeat(this.indentLevel + 1);
}
break;
case 'start-pipeless-text':
result += this.indentString;
break;
}
if (this.pipelessComment) {
val = formatCommentPreserveSpaces(val, this.options.commentPreserveSpaces, true);
}
} else {
if (this.nextToken && val[val.length - 1] === ' ') {
switch (this.nextToken.type) {
case 'interpolated-code':
case 'start-pug-interpolation':
needsTrailingWhitespace = true;
break;
}
}
val = val.replace(/\s\s+/g, ' ');
switch (this.previousToken?.type) {
case 'newline':
result += this.indentString.repeat(this.indentLevel);
if (/^ .+$/.test(val)) {
result += '|\n';
result += this.indentString.repeat(this.indentLevel);
}
result += '|';
if (/.*\S.*/.test(token.val) || this.nextToken?.type === 'start-pug-interpolation') {
result += ' ';
}
break;
case 'indent':
case 'outdent':
result += this.indentString;
if (/^ .+$/.test(val)) {
result += '|\n';
result += this.indentString.repeat(this.indentLevel);
}
result += '|';
if (/.*\S.*/.test(token.val)) {
result += ' ';
}
break;
case 'interpolated-code':
case 'end-pug-interpolation':
if (/^ .+$/.test(val)) {
result += ' ';
}
break;
}
val = val.trim();
val = this.formatText(val);
val = val.replace(/#(\{|\[)/g, '\\#$1');
}
if (this.checkTokenType(this.previousToken, ['tag', 'id', 'interpolation', 'call', '&attributes', 'filter'])) {
val = ` ${val}`;
}
result += val;
if (needsTrailingWhitespace) {
result += ' ';
}
return result;
}
private ['interpolated-code'](token: InterpolatedCodeToken): string {
let result: string = '';
switch (this.previousToken?.type) {
case 'tag':
case 'class':
case 'id':
case 'end-attributes':
result = ' ';
break;
case 'start-pug-interpolation':
result = '| ';
break;
case 'indent':
case 'newline':
case 'outdent':
result = this.computedIndent;
result += this.pipelessText ? this.indentString : '| ';
break;
}
result += token.mustEscape ? '#' : '!';
result += `{${token.val}}`;
return result;
}
private code(token: CodeToken): string {
let result: string = this.computedIndent;
if (!token.mustEscape && token.buffer) {
result += '!';
}
result += token.buffer ? '=' : '-';
let useSemi: boolean = this.options.pugSemi;
if (useSemi && (token.mustEscape || token.buffer)) {
useSemi = false;
}
let val: string = token.val;
try {
const valBackup: string = val;
val = format(val, {
parser: 'babel',
...this.codeInterpolationOptions,
semi: useSemi,
// Always pass endOfLine 'lf' here to be sure that the next `val.slice(0, -1)` call is always working
endOfLine: 'lf'
});
val = val.slice(0, -1);
if (val[0] === ';') {
val = val.slice(1);
}
if (val.includes('\n')) {
val = valBackup;
}
} catch (error: unknown) {
logger.warn('[PugPrinter]:', error);
}
result += ` ${val}`;
return result;
}
private id(token: IdToken): void {
const val: string = `#${token.val}`;
this.currentLineLength += val.length;
switch (this.previousToken?.type) {
case 'newline':
case 'outdent':
case 'indent': {
const result: string = `${this.computedIndent}${val}`;
this.result += result;