Skip to content

Commit 758bd63

Browse files
authored
Assign document leading format to the first node instead (#138)
Fixes: #136
1 parent 439aa63 commit 758bd63

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

src/document.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -669,12 +669,13 @@ final;";
669669
doc.iter_dash_args("foo").collect::<Vec<&KdlValue>>(),
670670
vec![&1.into(), &2.into(), &"three".into()]
671671
);
672+
assert_eq!(doc.format().map(|f| &f.leading[..]), Some(""));
673+
674+
let foo = doc.get("foo").expect("expected a foo node");
672675
assert_eq!(
673-
doc.format().map(|f| &f.leading[..]),
676+
foo.format().map(|f| &f.leading[..]),
674677
Some("\n// This is the first node\n")
675678
);
676-
677-
let foo = doc.get("foo").expect("expected a foo node");
678679
assert_eq!(foo.format().map(|f| &f.terminator[..]), Some("\n"));
679680
assert_eq!(&foo[2], &"three".into());
680681
assert_eq!(&foo["bar"], &"baz".into());

src/v2_parser.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -282,12 +282,12 @@ pub(crate) fn document(input: &mut Input<'_>) -> PResult<KdlDocument> {
282282

283283
/// `nodes := (line-space* node)* line-space*`
284284
fn nodes(input: &mut Input<'_>) -> PResult<KdlDocument> {
285-
let leading = repeat(0.., alt((line_space.void(), (slashdash, base_node).void())))
285+
let mut leading = repeat(0.., alt((line_space.void(), (slashdash, base_node).void())))
286286
.map(|()| ())
287287
.take()
288288
.parse_next(input)?;
289289
let _start = input.checkpoint();
290-
let ns: Vec<KdlNode> = separated(
290+
let mut ns: Vec<KdlNode> = separated(
291291
0..,
292292
node,
293293
alt((node_terminator.void(), (eof.void(), any.void()).void())),
@@ -299,6 +299,16 @@ fn nodes(input: &mut Input<'_>) -> PResult<KdlDocument> {
299299
.map(|()| ())
300300
.take()
301301
.parse_next(input)?;
302+
303+
// If there is a node, let it have the leading format
304+
// This gives more consistent behavior
305+
if let Some(first_node) = ns.get_mut(0) {
306+
if let Some(first_node_format) = first_node.format_mut() {
307+
first_node_format.leading = leading.into();
308+
leading = "";
309+
}
310+
}
311+
302312
Ok(KdlDocument {
303313
nodes: ns,
304314
format: Some(KdlDocumentFormat {

0 commit comments

Comments
 (0)