diff --git a/ast/ast.go b/ast/ast.go index a1a7de1..ca15053 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -1450,16 +1450,25 @@ func (n *MappingValueNode) toString() string { } return fmt.Sprintf("%s%s: %s", space, n.Key.String(), value) } else if keyIndentLevel < valueIndentLevel && !n.IsFlowStyle { + valueStr := n.Value.String() + // For flow-style values indented on the next line, we need to add the proper indentation + if m, ok := n.Value.(*MappingNode); ok && m.IsFlowStyle { + valueIndent := strings.Repeat(" ", n.Value.GetToken().Position.Column-1) + valueStr = valueIndent + valueStr + } else if s, ok := n.Value.(*SequenceNode); ok && s.IsFlowStyle { + valueIndent := strings.Repeat(" ", n.Value.GetToken().Position.Column-1) + valueStr = valueIndent + valueStr + } if keyComment != nil { return fmt.Sprintf( "%s%s: %s\n%s", space, n.Key.stringWithoutComment(), keyComment.String(), - n.Value.String(), + valueStr, ) } - return fmt.Sprintf("%s%s:\n%s", space, n.Key.String(), n.Value.String()) + return fmt.Sprintf("%s%s:\n%s", space, n.Key.String(), valueStr) } else if m, ok := n.Value.(*MappingNode); ok && (m.IsFlowStyle || len(m.Values) == 0) { return fmt.Sprintf("%s%s: %s", space, n.Key.String(), n.Value.String()) } else if s, ok := n.Value.(*SequenceNode); ok && (s.IsFlowStyle || len(s.Values) == 0) { diff --git a/parser/parser_test.go b/parser/parser_test.go index f3ea3b0..a7fdb63 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -290,6 +290,30 @@ r: s - b - c - d - e - f +`, + }, + { + ` +elem1: + - elem2: + {a: b, c: d} +`, + ` +elem1: + - elem2: + {a: b, c: d} +`, + }, + { + ` +elem1: + - elem2: + [a, b, c, d] +`, + ` +elem1: + - elem2: + [a, b, c, d] `, }, { @@ -1520,6 +1544,32 @@ foo2: &anchor text # anchor comment # foo3 comment # foo3 comment2 foo3: *anchor # alias comment +`, + }, + { + name: "flow map with inline key comment", + yaml: ` +elem1: + - elem2: # comment + {a: b, c: d} +`, + expected: ` +elem1: + - elem2: # comment + {a: b, c: d} +`, + }, + { + name: "flow sequence with inline key comment", + yaml: ` +elem1: + - elem2: # comment + [a, b, c, d] +`, + expected: ` +elem1: + - elem2: # comment + [a, b, c, d] `, }, {