diff --git a/js/ast.go b/js/ast.go index b2fa3f7..515f2a5 100644 --- a/js/ast.go +++ b/js/ast.go @@ -505,7 +505,14 @@ func (n ExprStmt) String() string { // JS writes JavaScript to writer. func (n ExprStmt) JS(w io.Writer) { buf := &bytes.Buffer{} - n.Value.JS(buf) + wb := io.Writer(buf) + if wi, ok := w.(parse.Indenter); ok { + // make sure that buf is indenter if w is so as well + // this is to prevent newlines in literals from indenting + wb = parse.NewIndenter(wb, wi.Indent()) + w = wi.Writer + } + n.Value.JS(wb) expr := buf.Bytes() group := bytes.HasPrefix(expr, []byte("let ")) @@ -1686,6 +1693,9 @@ func (n LiteralExpr) JS(w io.Writer) { // JSON writes JSON to writer. func (n LiteralExpr) JSON(w io.Writer) error { + if wi, ok := w.(parse.Indenter); ok { + w = wi.Writer + } if n.TokenType == TrueToken || n.TokenType == FalseToken || n.TokenType == NullToken || n.TokenType == DecimalToken || n.TokenType == IntegerToken { w.Write(n.Data) return nil @@ -1974,6 +1984,9 @@ func (n TemplateExpr) JS(w io.Writer) { // JSON writes JSON to writer. func (n TemplateExpr) JSON(w io.Writer) error { + if wi, ok := w.(parse.Indenter); ok { + w = wi.Writer + } if n.Tag != nil || len(n.List) != 0 { js := &strings.Builder{} n.JS(js) diff --git a/js/ast_test.go b/js/ast_test.go index 6468f59..1b5ba0d 100644 --- a/js/ast_test.go +++ b/js/ast_test.go @@ -126,6 +126,7 @@ func TestJS(t *testing.T) { {"//!\nn=>{ return n }", "//! (n) => { return n; };"}, // space after //! is newline {"//!\n{//!\n}", "//! { //! }"}, // space after //! is newline {`for(;;)let = 5`, `for ( ; ; ) { (let = 5); }`}, + {"{`\n`}", "{ ` `; }"}, // space in template literal is newline } re := regexp.MustCompile("\n *") diff --git a/util.go b/util.go index de8dab3..a90ac6c 100644 --- a/util.go +++ b/util.go @@ -196,6 +196,10 @@ func NewIndenter(w io.Writer, n int) Indenter { } } +func (in Indenter) Indent() int { + return len(in.b) +} + func (in Indenter) Write(b []byte) (int, error) { n, j := 0, 0 for i, c := range b {