17
17
18
18
import com .opencastsoftware .prettier4j .Doc ;
19
19
import java .util .ArrayList ;
20
+ import java .util .Arrays ;
20
21
import java .util .Iterator ;
21
22
import java .util .List ;
22
23
import java .util .Optional ;
23
24
import java .util .function .Function ;
25
+ import java .util .stream .Collectors ;
24
26
import java .util .stream .Stream ;
25
27
import software .amazon .smithy .model .loader .ModelSyntaxException ;
26
28
import software .amazon .smithy .model .shapes .ShapeId ;
@@ -178,6 +180,7 @@ private Doc visit(TreeCursor cursor) {
178
180
case APPLY_STATEMENT :
179
181
case NODE_VALUE :
180
182
case NODE_KEYWORD :
183
+ case NODE_STRING_VALUE :
181
184
case SIMPLE_TYPE_NAME :
182
185
case ENUM_TYPE_NAME :
183
186
case AGGREGATE_TYPE_NAME :
@@ -408,12 +411,25 @@ private Doc visit(TreeCursor cursor) {
408
411
}
409
412
410
413
case NODE_OBJECT_KVP : {
414
+ // Since text blocks span multiple lines, when they are the NODE_VALUE for NODE_OBJECT_KVP,
415
+ // they have to be indented. Since we only format valid models, NODE_OBJECT_KVP is guaranteed to
416
+ // have a NODE_VALUE child.
417
+ TreeCursor nodeValue = cursor .getFirstChild (TreeType .NODE_VALUE );
418
+ boolean isTextBlock = Optional .ofNullable (nodeValue .getFirstChild (TreeType .NODE_STRING_VALUE ))
419
+ .map (nodeString -> nodeString .getFirstChild (TreeType .TEXT_BLOCK ))
420
+ .isPresent ();
421
+ Doc nodeValueDoc = visit (nodeValue );
422
+ if (isTextBlock ) {
423
+ nodeValueDoc = nodeValueDoc .indent (4 );
424
+ }
425
+
426
+
411
427
// Hoist awkward comments in the KVP *before* the KVP rather than between the values and colon.
412
428
// If there is an awkward comment before the TRAIT value, hoist it above the statement.
413
429
return skippedComments (cursor , false )
414
430
.append (visit (cursor .getFirstChild (TreeType .NODE_OBJECT_KEY )))
415
431
.append (Doc .text (": " ))
416
- .append (visit ( cursor . getFirstChild ( TreeType . NODE_VALUE )) );
432
+ .append (nodeValueDoc );
417
433
}
418
434
419
435
case NODE_OBJECT_KEY : {
@@ -427,9 +443,17 @@ private Doc visit(TreeCursor cursor) {
427
443
: Doc .text (tree .concatTokens ());
428
444
}
429
445
446
+ case TEXT_BLOCK : {
447
+ // Dispersing the lines of the text block preserves any indentation applied from formatting parent
448
+ // nodes.
449
+ List <Doc > lines = Arrays .stream (tree .concatTokens ().split (System .lineSeparator ()))
450
+ .map (String ::trim )
451
+ .map (Doc ::text )
452
+ .collect (Collectors .toList ());
453
+ return Doc .intersperse (Doc .line (), lines );
454
+ }
455
+
430
456
case TOKEN :
431
- case TEXT_BLOCK :
432
- case NODE_STRING_VALUE :
433
457
case QUOTED_TEXT :
434
458
case NUMBER :
435
459
case SHAPE_ID :
0 commit comments