Skip to content

Flawed line wrapping for strings with newlines #529

@elmuerte

Description

@elmuerte

Describe the bug
Wrapping of long strings does not work correctly. After a newline is encountered in the value it will no longer wrap any more content.

Further more, if the line length becomes small enough it inserts a leading newline and doesn't even wrap at the correct line length.

To Reproduce

import yaml from "yaml";

const data = {
	foo: "bar",
	longlines:
		"first line which is long enough to be wrapped to a another line\nsecond line which is long enough to be wrapped to a another line\nthird line which is long enough to be wrapped to a another line",
};

console.log(
	yaml.stringify(data, {
		lineWidth: 40,
	}),
);

// Inserts a leading newline
console.log(
	yaml.stringify(data, {
		lineWidth: 20,
	}),
);

This will print

foo: bar
longlines: >-
  first line which is long enough to be
  wrapped to a another line

  second line which is long enough to be wrapped to a another line

  third line which is long enough to be wrapped to a another line

foo: bar
longlines: >-

  first line which
  is long enough to be
  wrapped to a another
  line

  second line which is long enough to be wrapped to a another line

  third line which is long enough to be wrapped to a another line

Expected behaviour

foo: bar
longlines: >-
  first line which is long enough to be
  wrapped to a another line

  second line which is long enough to
  be wrapped to a another line

  third line which is long enough to be
  wrapped to a another line

foo: bar
longlines: >-
  first line which
  is long enough
  to be wrapped to
  a another line

  second line which
  is long enough to
  be wrapped to a
  another line

  third line which
  is long enough to
  be wrapped to a 
  another line

Versions (please complete the following information):

  • Environment: Node.js v18.17.0
  • yaml: 2.4.0

Additional context
Add any other context about the problem here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions