Add indentation to flow values on new lines (#759)

This commit is contained in:
Shuhei Kitagawa 2025-11-29 03:43:49 +01:00 committed by GitHub
parent 0040ab4161
commit 07c09c0287
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 61 additions and 2 deletions

View file

@ -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) {

View file

@ -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]
`,
},
{