fix(cst): keep a block scalar's content indent in setScalarValue
setScalarValue reconstructed a block scalar's content indent as token.indent plus one step, but token.indent is the indent of the node, not of its contents. Contents sitting further in than one step were pulled back, and without afterKey they lost their indentation entirely, which for a block scalar in a collection changes what the document means rather than just how it looks. resolveBlockScalar already measures the real content indent when reading: an explicit indentation indicator counts from the node indent, and otherwise the indent is that of the first non-empty line. Measure the same way before stringifying, and fall back to the previous behaviour when a block scalar has no contents to measure. Fixes #349
This commit is contained in:
1 parent
6744b4a7a9
commit
0717920c8d
2 files changed
+106
No files matched your search
@@ -180,6 +180,16 @@ export function setScalarValue(
|
||||
default:
|
||||
type = 'PLAIN'
|
||||
}
|
||||
if (
|
||||
token.type === 'block-scalar' &&
|
||||
(type === 'BLOCK_FOLDED' || type === 'BLOCK_LITERAL')
|
||||
) {
|
||||
// A block scalar's contents are not necessarily indented by exactly one
|
||||
// step past its own indent; the extra indentation is not semantic, but it
|
||||
// is the author's, so re-use it rather than silently re-indenting.
|
||||
const contentIndent = blockScalarContentIndent(token)
|
||||
if (contentIndent !== null) indent = contentIndent
|
||||
}
|
||||
const source = stringifyString(
|
||||
{ type, value } as Scalar,
|
||||
{
|
||||
@@ -205,6 +215,30 @@ export function setScalarValue(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the indent of a block scalar's current contents, matching how
|
||||
* `resolveBlockScalar()` reads it back: an explicit indentation indicator in
|
||||
* the header counts from the token's own indent, and otherwise the contents
|
||||
* are indented by however much the first non-empty line is.
|
||||
*
|
||||
* @returns `null` if the token has no contents to infer an indent from.
|
||||
*/
|
||||
function blockScalarContentIndent(token: BlockScalar): number | null {
|
||||
const header = token.props[0]
|
||||
if (header?.type === 'block-scalar-header') {
|
||||
const match = /\d/.exec(header.source)
|
||||
const explicit = match ? Number(match[0]) : 0
|
||||
if (explicit > 0) return token.indent + explicit
|
||||
}
|
||||
for (const line of token.source.split('\n')) {
|
||||
let indent = 0
|
||||
while (line[indent] === ' ') indent += 1
|
||||
const content = line.substring(indent)
|
||||
if (content !== '' && content !== '\r') return indent
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function setBlockScalarValue(token: Token, source: string) {
|
||||
const he = source.indexOf('\n')
|
||||
const head = source.substring(0, he)
|
||||
|
||||
Reference in new issue
Block a user