Skip to content

Commit

Permalink
syntax: allow escaped newlines to precede unquoted words again
Browse files Browse the repository at this point in the history
As part of fixing #832, to prevent breaking some programs with escaped
newlines, I went slightly too far with the tightening of the rules.
The input script

	foo <<< \
		"bar baz"

would now reformat as

	foo <<< "\
	bar baz"

The script is functionally the same, but it looks objectively worse.
It is harmless to allow a leading escaped newline when not quoted,
as it doesn't break any programs nor result in worse formatting.

Note that the script

	foo=\
	bar

will still reformat as `foo=bar`, so in that case we keep the recent
change in behavior. That case is different, as we can't safely indent
the continuing line - thus we can't produce good formatting unless we
join the lines.

While here, remove incomplete code that I had left commented out in the
last patch, and then forgot to remove before merging.

Fixes #873.
  • Loading branch information
mvdan committed Jul 3, 2022
1 parent b37fb54 commit a66ddcd
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
11 changes: 8 additions & 3 deletions syntax/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,14 @@ func (p *Printer) comments(comments ...Comment) {
}

func (p *Printer) wordParts(wps []WordPart, quoted bool) {
// We disallow unquoted escaped newlines between word parts below.
// However, we want to allow a leading escaped newline for cases such as:
//
// foo <<< \
// "bar baz"
if !quoted && !p.singleLine && wps[0].Pos().Line() > p.line {
p.bslashNewl()
}
for i, wp := range wps {
var next WordPart
if i+1 < len(wps) {
Expand Down Expand Up @@ -1413,10 +1421,7 @@ func (p *Printer) assigns(assigns []*Assign) {
// because that can result in indentation, thus
// splitting "foo=bar" into "foo= bar".
p.line = a.Value.Pos().Line()
// Similar to the above, we want to print the word as if it were
// quoted, as otherwise escaped newlines could split
p.word(a.Value)
// p.wordParts(a.Value.Parts, true)
} else if a.Array != nil {
p.wantSpace = spaceNotRequired
p.WriteByte('(')
Expand Down
6 changes: 4 additions & 2 deletions syntax/printer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,16 @@ var printTests = []printCase{
"a bb\\\ncc d",
"a bbcc d",
},
samePrint("a \\\n\tb \\\n\tc \\\n\t;"),
samePrint("a=1 \\\n\tb=2 \\\n\tc=3 \\\n\t;"),
samePrint("a \\\n\tb \\\n\t\"c\" \\\n\t;"),
samePrint("a=1 \\\n\tb=2 \\\n\tc=\"3\" \\\n\t;"),
{
"a=\\\nfoo\nb=\\\n\"bar\"\nc=\\\n'baz'",
"a=foo\nb=\"bar\"\nc='baz'",
},

samePrint("if a \\\n\t; then b; fi"),
samePrint("a > \\\n\tfoo"),
samePrint("a <<< \\\n\t\"foo\""),
samePrint("a 'b\nb' c"),
samePrint("a $'b\nb' c"),
{
Expand Down

0 comments on commit a66ddcd

Please sign in to comment.