Repository: domluna/JuliaFormatter.jl
Pull request #109 (2019-11-01 03:59:21)

Nest assignment if RHS is binary or conditional op
Currently binary and conditional ops are nested starting from the line offset of the start of the expression. This feels a little odd to me, particularly in a case like this it doesn't quite feel natural:

```julia
shmem[pout*rows+row] = shmem[pin*rows+row] +
                       shmem[pin*rows+row-offset]
```



With this PR if it's the RHS of an assignment (`=`) the indentation is consistent with most other expressions. This is also what prettier, elixir formatter, and refmt do. Python doesn't do this
because it's a syntax error, if it wasn't, a formatter like black probably would.

```julia
# indent 4
shmem[pout*rows+row] = 
    shmem[pin*rows+row] + shmem[pin*rows+row-offset]
```

####  Example

**MASTER**


With margin 70:

```julia
function gpu_accumulate!(
    op::Function,
    data::CuDeviceMatrix{T},
) where {T}
    col = blockIdx().x
    cols = gridDim().x

    row = threadIdx().x
    rows = blockDim().x

    if col <= cols && row <= rows
        shmem = @cuDynamicSharedMem(T, 2 * rows)
        shmem[row] = data[row, col]
        sync_threads()

        # parallel reduction
        pin, pout = 1, 0
        offset = 1
        while offset < rows
            pout = 1 - pout
            pin = 1 - pin
            if row > offset
                shmem[pout*rows+row] = shmem[pin*rows+row] +
                                       shmem[pin*rows+row-offset]
                value = shmem[pin*rows+row] ?
                        shmem[pin*rows+row-offset] :
                        shmem[pin+rows+row-offset]
            else
                shmem[pout*rows+row] = shmem[pin*rows+row]
            end
            sync_threads()
            offset *= UInt32(2)
        end
        shmem[pin*rows+row] = shmem[pout*rows+row]
        sync_threads()

        # write back results
        data[row, col] = shmem[row]
    end

    return
end
```
**THIS PR**

With margin 70:

```julia
function gpu_accumulate!(
    op::Function,
    data::CuDeviceMatrix{T},
) where {T}
    col = blockIdx().x
    cols = gridDim().x

    row = threadIdx().x
    rows = blockDim().x

    if col <= cols && row <= rows
        shmem = @cuDynamicSharedMem(T, 2 * rows)
        shmem[row] = data[row, col]
        sync_threads()

        # parallel reduction
        pin, pout = 1, 0
        offset = 1
        while offset < rows
            pout = 1 - pout
            pin = 1 - pin
            if row > offset
                shmem[pout*rows+row] =
                    shmem[pin*rows+row] + shmem[pin*rows+row-offset]
                value =
                    shmem[pin*rows+row] ? shmem[pin*rows+row-offset] :
                    shmem[pin+rows+row-offset]
            else
                shmem[pout*rows+row] = shmem[pin*rows+row]
            end
            sync_threads()
            offset *= UInt32(2)
        end
        shmem[pin*rows+row] = shmem[pout*rows+row]
        sync_threads()

        # write back results
        data[row, col] = shmem[row]
    end

    return
end
```

With margin 65:

```julia
function gpu_accumulate!(
    op::Function,
    data::CuDeviceMatrix{T},
) where {T}
    col = blockIdx().x
    cols = gridDim().x

    row = threadIdx().x
    rows = blockDim().x

    if col <= cols && row <= rows
        shmem = @cuDynamicSharedMem(T, 2 * rows)
        shmem[row] = data[row, col]
        sync_threads()

        # parallel reduction
        pin, pout = 1, 0
        offset = 1
        while offset < rows
            pout = 1 - pout
            pin = 1 - pin
            if row > offset
                shmem[pout*rows+row] =
                    shmem[pin*rows+row] +
                    shmem[pin*rows+row-offset]
                # unnest if possible
                value = shmem[pin*rows+row] ?
                    shmem[pin*rows+row-offset] :
                    shmem[pin+rows+row-offset]
            else
                shmem[pout*rows+row] = shmem[pin*rows+row]
            end
            sync_threads()
            offset *= UInt32(2)
        end
        shmem[pin*rows+row] = shmem[pout*rows+row]
        sync_threads()

        # write back results
        data[row, col] = shmem[row]
    end

    return
end
```

domluna: In addition:

- Comparison and ChainOpCalls now nest all ops if over the margin
- Only nests a iterables types with single args in certain cases, see `unnestable_arg`. With the changes introduces in #120 and #121 this was too liberal.

Patch:
diff --git a/src/JuliaFormatter.jl b/src/JuliaFormatter.jl
index fd265731..5eca31d9 100644
--- a/src/JuliaFormatter.jl
+++ b/src/JuliaFormatter.jl
@@ -212,7 +212,7 @@ function format_text(
     isempty(text) && return text
 
     x, ps = CSTParser.parse(CSTParser.ParseState(text), true)
-    ps.errored && error("Parsing error for input $text")
+    ps.errored && error("Parsing error for input:\n\n$text")
 
     # no actual code
     x.args[1].kind === Tokens.NOTHING && length(x) == 1 && return text
@@ -243,7 +243,7 @@ function format_text(
     text = normalize_line_ending(text)
 
     _, ps = CSTParser.parse(CSTParser.ParseState(text), true)
-    ps.errored && error("Parsing error for formatted text:\n\n $text")
+    ps.errored && error("Parsing error for formatted text:\n\n$text")
     return text
 end
 
diff --git a/src/nest.jl b/src/nest.jl
index 9eba6e69..bf969e5f 100644
--- a/src/nest.jl
+++ b/src/nest.jl
@@ -104,7 +104,7 @@ function nest!(x::PTree, s::State; extra_width = 0)
     elseif x.typ === CSTParser.Braces
         n_tuple!(x, s, extra_width = extra_width)
     elseif x.typ === CSTParser.InvisBrackets
-        n_invisbrackets!(x, s, extra_width = extra_width)
+        n_tuple!(x, s, extra_width = extra_width)
     elseif x.typ === CSTParser.UnaryOpCall && x.nodes[2].typ === CSTParser.OPERATOR
         nest!(x.nodes[1], s, extra_width = extra_width + length(x.nodes[2]))
         nest!(x.nodes[2], s)
@@ -132,13 +132,12 @@ function n_do!(x, s; extra_width = 0)
     nest!(x.nodes[2:end], s, x.indent, extra_width = extra_width)
 end
 
-n_invisbrackets!(x, s; extra_width = 0) = n_tuple!(x, s, extra_width = extra_width)
 
 # Import,Using,Export,ImportAll
 function n_import!(x, s; extra_width = 0)
-    line_width = s.line_offset + length(x) + extra_width
+    line_margin = s.line_offset + length(x) + extra_width
     idx = findfirst(n -> n.typ === PLACEHOLDER, x.nodes)
-    if idx !== nothing && (line_width > s.margin || x.force_nest)
+    if idx !== nothing && (line_margin > s.margin || x.force_nest)
         sidx = findfirst(n -> is_colon(n), x.nodes)
         if sidx === nothing
             sidx = 2
@@ -165,11 +164,11 @@ function n_import!(x, s; extra_width = 0)
 end
 
 function n_tuple!(x, s; extra_width = 0)
-    line_width = s.line_offset + length(x) + extra_width
+    line_margin = s.line_offset + length(x) + extra_width
     idx = findlast(n -> n.typ === PLACEHOLDER, x.nodes)
     # @info "ENTERING" idx x.typ s.line_offset length(x) extra_width
     opener = length(x.nodes) > 0 ? is_opener(x.nodes[1]) : false
-    if idx !== nothing && (line_width > s.margin || x.force_nest)
+    if idx !== nothing && (line_margin > s.margin || x.force_nest)
         if opener
             x.nodes[end].indent = x.indent
         end
@@ -236,10 +235,10 @@ function n_for!(x, s; extra_width = 0)
 end
 
 function n_call!(x, s; extra_width = 0)
-    line_width = s.line_offset + length(x) + extra_width
+    line_margin = s.line_offset + length(x) + extra_width
     idx = findlast(n -> n.typ === PLACEHOLDER, x.nodes)
     # @info "ENTERING" x.typ s.line_offset length(x) extra_width s.margin x.nodes[1].val
-    if idx !== nothing && (line_width > s.margin || x.force_nest)
+    if idx !== nothing && (line_margin > s.margin || x.force_nest)
         x.nodes[end].indent = x.indent
         line_offset = s.line_offset
 
@@ -287,9 +286,9 @@ end
 
 # "A where B"
 function n_wherecall!(x, s; extra_width = 0)
-    line_width = s.line_offset + length(x) + extra_width
-    # @debug "" s.line_offset x.typ line_width extra_width length(x)
-    if line_width > s.margin || x.force_nest
+    line_margin = s.line_offset + length(x) + extra_width
+    # @debug "" s.line_offset x.typ line_margin extra_width length(x)
+    if line_margin > s.margin || x.force_nest
         line_offset = s.line_offset
         # after "A where "
         idx = findfirst(n -> n.typ === PLACEHOLDER, x.nodes)
@@ -339,28 +338,19 @@ function n_wherecall!(x, s; extra_width = 0)
             (!is_leaf(n) || n.typ === CSTParser.IDENTIFIER) && (last_typ = n.typ)
         end
 
-
         # @info "" s.line_offset x.typ extra_width has_braces
-
-        # Properly reset line offset in the case the last
-        # argument is an IDENTIFIER.
-        # if over && has_braces && last_typ === CSTParser.IDENTIFIER && x.nodes[end-2].typ === TRAILINGCOMMA
         if over && has_braces
             s.line_offset = x.nodes[end].indent + 1
         end
-
-        # s.line_offset = line_offset
-        # walk(reset_line_offset!, x, s)
-        # @info "" s.line_offset x.typ extra_width has_braces
     else
         nest!(x.nodes, s, x.indent, extra_width = extra_width)
     end
 end
 
-function n_chainopcall!(x, s; extra_width = 0)
-    line_width = s.line_offset + length(x) + extra_width
-    # @info "ENTERING" x.typ extra_width s.line_offset length(x)
-    if line_width > s.margin || x.force_nest
+function n_condcall!(x, s; extra_width = 0)
+    line_margin = s.line_offset + length(x) + extra_width
+    # @info "ENTERING" x.typ s.line_offset line_margin x.force_nest
+    if line_margin > s.margin || x.force_nest
         line_offset = s.line_offset
         x.indent = s.line_offset
         phs = reverse(findall(n -> n.typ === PLACEHOLDER, x.nodes))
@@ -417,9 +407,30 @@ function n_chainopcall!(x, s; extra_width = 0)
         nest!(x.nodes, s, x.indent, extra_width = extra_width)
     end
 end
+n_comparison!(x, s; extra_width = 0) = n_block!(x, s, extra_width = extra_width)
+n_chainopcall!(x, s; extra_width = 0) = n_block!(x, s, extra_width = extra_width)
+
+function dedent!(x::PTree, s::State, pindent::Int, line_margin::Int)
+    is_leaf(x) && return
+    x.typ === CSTParser.ConditionalOpCall && return
+    x.typ === CSTParser.Comparison && return
+    x.typ === CSTParser.ChainOpCall && return
+    x.typ === CSTParser.BinaryOpCall && return
+    if x.typ === CSTParser.InvisBrackets &&
+       length(x.nodes) == 3 && closing_punc_type(x.nodes[2])
+        dedent!(x.nodes[2], s, pindent, line_margin)
+        return
+    end
 
-n_comparison!(x, s; extra_width = 0) = n_chainopcall!(x, s, extra_width = extra_width)
-n_condcall!(x, s; extra_width = 0) = n_chainopcall!(x, s, extra_width = extra_width)
+    if closing_punc_type(x)
+        diff = min(line_margin, pindent + s.indent_size) - x.indent
+        # @info "" pindent diff x.indent x.typ
+        add_indent!(x, s, diff)
+        x.nodes[end].indent = pindent
+    else
+        add_indent!(x, s, -s.indent_size)
+    end
+end
 
 # arg1 op arg2
 #
@@ -430,15 +441,16 @@ n_condcall!(x, s; extra_width = 0) = n_chainopcall!(x, s, extra_width = extra_wi
 function n_binarycall!(x, s; extra_width = 0)
     # If there's no placeholder the binary call is not nestable
     idxs = findall(n -> n.typ === PLACEHOLDER, x.nodes)
-    line_width = s.line_offset + length(x) + extra_width
+    line_margin = s.line_offset + length(x) + extra_width
     # @info "ENTERING" x.typ extra_width s.line_offset length(x) idxs x.ref[][2]
-    if length(idxs) == 2 && (line_width > s.margin || x.force_nest)
+    if length(idxs) == 2 && (line_margin > s.margin || x.force_nest)
         line_offset = s.line_offset
         i1 = idxs[1]
         i2 = idxs[2]
         x.nodes[i1] = Newline()
+        cst = x.ref[]
 
-        has_eq = CSTParser.defines_function(x.ref[]) || nest_assignment(x.ref[])
+        has_eq = CSTParser.defines_function(cst) || nest_assignment(cst)
         if has_eq
             s.line_offset = x.indent + s.indent_size
             x.nodes[i2] = Whitespace(s.indent_size)
@@ -462,39 +474,32 @@ function n_binarycall!(x, s; extra_width = 0)
 
         # Undo nest if possible
         if !x.force_nest
-            # @info "" s.line_offset rw line_width length_to(x, (NEWLINE,), start=1)
             arg2 = x.nodes[end]
             arg2.typ === CSTParser.Block && (arg2 = arg2.nodes[1])
-
-            line_width = 0
-            can_unnest = false
-            if arg2.typ === CSTParser.BinaryOpCall
-                line_width = s.line_offset + 1 + length(x.nodes[end])
-                can_unnest = line_width + extra_width <= s.margin
+            cst = arg2.ref[]
+
+            if (
+                arg2.typ === CSTParser.BinaryOpCall && (
+                    !(is_lazy_op(cst) && !has_eq) && cst[2].kind !== Tokens.IN
+                )
+            ) || arg2.typ === CSTParser.UnaryOpCall
+                line_margin = s.line_offset + 1 + length(x.nodes[end])
             else
                 rw, _ = length_to(x, [NEWLINE], start = i2 + 1)
-                line_width = s.line_offset + 1 + rw
-                can_unnest = line_width + extra_width <= s.margin
+                line_margin = s.line_offset + 1 + rw
             end
+            # @info "" can_unnest arg2.typ has_eq
 
-            if can_unnest
+            if line_margin + extra_width <= s.margin
                 x.nodes[i1] = Whitespace(1)
                 if has_eq
                     x.nodes[i2] = Placeholder(0)
-
-                    if !is_leaf(arg2)
-                        add_indent!(arg2, s, -s.indent_size)
-
-                        # There might need to be an additional
-                        if closing_punc_type(arg2)
-                            close_indent = arg2.nodes[end].indent
-                            diff = min(
-                                s.indent_size - arg2.indent,
-                                line_width - arg2.indent,
-                            )
-                            add_indent!(arg2, s, diff)
-                            arg2.nodes[end].indent = close_indent
-                        end
+                    # recursive dedent
+                    if arg2.typ === CSTParser.BinaryOpCall
+                        dedent!(arg2.nodes[1], s, x.indent, line_margin)
+                        dedent!(arg2.nodes[end], s, x.indent, line_margin)
+                    else
+                        dedent!(arg2, s, x.indent, line_margin)
                     end
                 end
             end
@@ -531,7 +536,7 @@ function n_binarycall!(x, s; extra_width = 0)
         if idx !== nothing && idx > 1
             return_width = length(x.nodes[idx].nodes[1]) + length(x.nodes[2])
         elseif idx === nothing
-            return_width, _ = length_to(x, [PLACEHOLDER, NEWLINE], start = 2)
+            return_width, _ = length_to(x, [NEWLINE], start = 2)
         end
 
         # @info "" return_width
@@ -552,10 +557,10 @@ function n_binarycall!(x, s; extra_width = 0)
 end
 
 function n_block!(x, s; extra_width = 0, custom_indent = 0)
-    line_width = s.line_offset + length(x) + extra_width
+    line_margin = s.line_offset + length(x) + extra_width
     idx = findfirst(n -> n.typ === PLACEHOLDER, x.nodes)
     # @info "ENTERING" idx x.typ s.line_offset length(x) extra_width
-    if idx !== nothing && (line_width > s.margin || x.force_nest)
+    if idx !== nothing && (line_margin > s.margin || x.force_nest)
         line_offset = s.line_offset
 
         x.indent = custom_indent > 0 ? custom_indent : s.line_offset
diff --git a/src/pretty.jl b/src/pretty.jl
index b7fcc0ed..82d8028d 100644
--- a/src/pretty.jl
+++ b/src/pretty.jl
@@ -58,10 +58,17 @@ is_comma(x::PTree) =
 is_comment(x::PTree) = x.typ === INLINECOMMENT || x.typ === NOTCODE
 
 is_colon_op(x) =
-    (x.typ === CSTParser.BinaryOpCall && x.args[2].kind === Tokens.COLON) || x.typ === CSTParser.ColonOpCall
+    (
+     x.typ === CSTParser.BinaryOpCall && x[2].kind === Tokens.COLON
+    ) || x.typ === CSTParser.ColonOpCall
+
+is_lazy_op(x) =
+    x.typ === CSTParser.BinaryOpCall && (
+        x[2].kind === Tokens.LAZY_OR || x[2].kind === Tokens.LAZY_AND
+    )
 
 # f a function which returns a bool
-function parent_is(x, f; ignore_typs = (CSTParser.InvisBrackets,))
+function parent_is(x, f; ignore_typs = [])
     p = x.parent
     p === nothing && return false
     while p !== nothing && p.typ in ignore_typs
@@ -72,10 +79,10 @@ end
 
 # TODO: Remove once this is fixed in CSTParser.
 # https://github.com/julia-vscode/CSTParser.jl/issues/108
-function n_args(x::CSTParser.EXPR)
-    n = 0
+function get_args(x::CSTParser.EXPR)
+    args = []
     if x.typ === CSTParser.MacroCall ||
-       x.typ === CSTParser.TypedVcat || x.typ === CSTParser.Ref
+       x.typ === CSTParser.TypedVcat || x.typ === CSTParser.Ref || x.typ === CSTParser.Curly
         for i = 2:length(x.args)
             arg = x.args[i]
             CSTParser.ispunctuation(arg) && continue
@@ -83,35 +90,32 @@ function n_args(x::CSTParser.EXPR)
                 for j = 1:length(arg.args)
                     parg = arg.args[j]
                     CSTParser.ispunctuation(parg) && continue
-                    parg_name = CSTParser.get_arg_name(parg)
-                    n += 1
+                    push!(args, parg)
                 end
             else
-                arg_name = CSTParser.get_arg_name(arg)
-                n += 1
+                push!(args, arg)
             end
         end
-        return n
-    elseif x.typ === CSTParser.Parameters ||
-           x.typ === CSTParser.Braces ||
-           x.typ === CSTParser.Vcat ||
-           x.typ === CSTParser.TupleH ||
+        return args
+    elseif x.typ === CSTParser.Parameters || x.typ === CSTParser.Braces ||
+           x.typ === CSTParser.Vcat || x.typ === CSTParser.TupleH ||
            x.typ === CSTParser.Vect || x.typ === CSTParser.InvisBrackets
         for i = 1:length(x.args)
             arg = x.args[i]
             CSTParser.ispunctuation(arg) && continue
-            n += 1
+            push!(args, arg)
         end
-        return n
+        return args
     end
-    length(CSTParser.get_args(x))
+    CSTParser.get_args(x)
 end
+n_args(x::CSTParser.EXPR) = length(get_args(x))
 
 function add_node!(t::PTree, n::PTree, s::State; join_lines = false, max_padding = -1)
     if n.typ === SEMICOLON
         join_lines = true
         loc = s.offset > length(s.doc.text) && t.typ === CSTParser.TopLevel ?
-              loc = cursor_loc(s, s.offset - 1) : cursor_loc(s)
+            cursor_loc(s, s.offset - 1) : cursor_loc(s)
         for l = t.endline:loc[1]
             if has_semicolon(s.doc, l)
                 # @info "found semicolon" l
@@ -133,15 +137,14 @@ function add_node!(t::PTree, n::PTree, s::State; join_lines = false, max_padding
         end
     elseif n.typ === TRAILINGCOMMA
         en = t.nodes[end]
-        if en.typ === CSTParser.Generator ||
-           en.typ === CSTParser.Filter ||
-           en.typ === CSTParser.Flatten ||
-           en.typ === CSTParser.MacroCall || (
+        if en.typ === CSTParser.Generator || en.typ === CSTParser.Filter ||
+           en.typ === CSTParser.Flatten || en.typ === CSTParser.MacroCall || (
             is_comma(en) && t.typ === CSTParser.TupleH && n_args(t.ref[]) == 1
         )
             # don't insert trailing comma in these cases
         elseif is_comma(en)
             t.nodes[end] = n
+            t.len -= 1
         else
             t.len += length(n)
             n.startline = t.startline
@@ -447,38 +450,38 @@ end
 function p_keyword(x, s)
     loc = cursor_loc(s)
     val = x.kind === Tokens.ABSTRACT ? "abstract" :
-          x.kind === Tokens.BAREMODULE ? "baremodule" :
-          x.kind === Tokens.BEGIN ? "begin" :
-          x.kind === Tokens.BREAK ? "break" :
-          x.kind === Tokens.CATCH ? "catch" :
-          x.kind === Tokens.CONST ? "const" :
-          x.kind === Tokens.CONTINUE ? "continue" :
-          x.kind === Tokens.NEW ? "new" :
-          x.kind === Tokens.DO ? "do" :
-          x.kind === Tokens.IF ? "if" :
-          x.kind === Tokens.ELSEIF ? "elseif" :
-          x.kind === Tokens.ELSE ? "else" :
-          x.kind === Tokens.END ? "end" :
-          x.kind === Tokens.EXPORT ? "export" :
-          x.kind === Tokens.FINALLY ? "finally" :
-          x.kind === Tokens.FOR ? "for" :
-          x.kind === Tokens.FUNCTION ? "function" :
-          x.kind === Tokens.GLOBAL ? "global" :
-          x.kind === Tokens.IMPORT ? "import" :
-          x.kind === Tokens.IMPORTALL ? "importall" :
-          x.kind === Tokens.LET ? "let" :
-          x.kind === Tokens.LOCAL ? "local" :
-          x.kind === Tokens.MACRO ? "macro" :
-          x.kind === Tokens.MODULE ? "module" :
-          x.kind === Tokens.MUTABLE ? "mutable" :
-          x.kind === Tokens.OUTER ? "outer " :
-          x.kind === Tokens.PRIMITIVE ? "primitive" :
-          x.kind === Tokens.QUOTE ? "quote" :
-          x.kind === Tokens.RETURN ? "return" :
-          x.kind === Tokens.STRUCT ? "struct" :
-          x.kind === Tokens.TYPE ? "type" :
-          x.kind === Tokens.TRY ? "try" :
-          x.kind === Tokens.USING ? "using" : x.kind === Tokens.WHILE ? "while" : ""
+        x.kind === Tokens.BAREMODULE ? "baremodule" :
+        x.kind === Tokens.BEGIN ? "begin" :
+        x.kind === Tokens.BREAK ? "break" :
+        x.kind === Tokens.CATCH ? "catch" :
+        x.kind === Tokens.CONST ? "const" :
+        x.kind === Tokens.CONTINUE ? "continue" :
+        x.kind === Tokens.NEW ? "new" :
+        x.kind === Tokens.DO ? "do" :
+        x.kind === Tokens.IF ? "if" :
+        x.kind === Tokens.ELSEIF ? "elseif" :
+        x.kind === Tokens.ELSE ? "else" :
+        x.kind === Tokens.END ? "end" :
+        x.kind === Tokens.EXPORT ? "export" :
+        x.kind === Tokens.FINALLY ? "finally" :
+        x.kind === Tokens.FOR ? "for" :
+        x.kind === Tokens.FUNCTION ? "function" :
+        x.kind === Tokens.GLOBAL ? "global" :
+        x.kind === Tokens.IMPORT ? "import" :
+        x.kind === Tokens.IMPORTALL ? "importall" :
+        x.kind === Tokens.LET ? "let" :
+        x.kind === Tokens.LOCAL ? "local" :
+        x.kind === Tokens.MACRO ? "macro" :
+        x.kind === Tokens.MODULE ? "module" :
+        x.kind === Tokens.MUTABLE ? "mutable" :
+        x.kind === Tokens.OUTER ? "outer " :
+        x.kind === Tokens.PRIMITIVE ? "primitive" :
+        x.kind === Tokens.QUOTE ? "quote" :
+        x.kind === Tokens.RETURN ? "return" :
+        x.kind === Tokens.STRUCT ? "struct" :
+        x.kind === Tokens.TYPE ? "type" :
+        x.kind === Tokens.TRY ? "try" :
+        x.kind === Tokens.USING ? "using" : x.kind === Tokens.WHILE ? "while" : ""
     s.offset += x.fullspan
     PTree(x, loc[1], loc[1], val)
 end
@@ -486,14 +489,14 @@ end
 function p_punctuation(x, s)
     loc = cursor_loc(s)
     val = x.kind === Tokens.LPAREN ? "(" :
-          x.kind === Tokens.LBRACE ? "{" :
-          x.kind === Tokens.LSQUARE ? "[" :
-          x.kind === Tokens.RPAREN ? ")" :
-          x.kind === Tokens.RBRACE ? "}" :
-          x.kind === Tokens.RSQUARE ? "]" :
-          x.kind === Tokens.COMMA ? "," :
-          x.kind === Tokens.SEMICOLON ? ";" :
-          x.kind === Tokens.AT_SIGN ? "@" : x.kind === Tokens.DOT ? "." : ""
+        x.kind === Tokens.LBRACE ? "{" :
+        x.kind === Tokens.LSQUARE ? "[" :
+        x.kind === Tokens.RPAREN ? ")" :
+        x.kind === Tokens.RBRACE ? "}" :
+        x.kind === Tokens.RSQUARE ? "]" :
+        x.kind === Tokens.COMMA ? "," :
+        x.kind === Tokens.SEMICOLON ? ";" :
+        x.kind === Tokens.AT_SIGN ? "@" : x.kind === Tokens.DOT ? "." : ""
     s.offset += x.fullspan
     PTree(x, loc[1], loc[1], val)
 end
@@ -629,7 +632,8 @@ function p_macrocall(x, s)
         return t
     end
 
-    multi_arg = n_args(x) > 0
+    args = get_args(x)
+    nest = length(args) > 0 && !(length(args) == 1 && unnestable_arg(args[1]))
     has_closer = is_closer(x.args[end])
 
     # @info "" has_closer
@@ -645,10 +649,10 @@ function p_macrocall(x, s)
                 # assumes the next argument is a brace of some sort
                 add_node!(t, n, s, join_lines = true)
             end
-        elseif is_opener(n) && multi_arg
+        elseif is_opener(n) && nest
             add_node!(t, n, s, join_lines = true)
             add_node!(t, Placeholder(0), s)
-        elseif is_closer(n) && multi_arg
+        elseif is_closer(n) && nest
             add_node!(t, Placeholder(0), s)
             add_node!(t, n, s, join_lines = true)
         elseif CSTParser.is_comma(a) && i < length(x) && !is_punc(x.args[i+1])
@@ -678,7 +682,7 @@ end
 function p_block(x, s; ignore_single_line = false, from_quote = false, join_body = false)
     t = PTree(x, nspaces(s))
     single_line = ignore_single_line ? false :
-                  cursor_loc(s)[1] == cursor_loc(s, s.offset + x.span - 1)[1]
+        cursor_loc(s)[1] == cursor_loc(s, s.offset + x.span - 1)[1]
 
     # @info "" from_quote single_line ignore_single_line join_body
     for (i, a) in enumerate(x)
@@ -1175,19 +1179,18 @@ function p_chaincall(x, s; nonest = false, nospace = false)
         if a.typ === CSTParser.OPERATOR
             !nospace && add_node!(t, Whitespace(1), s)
             add_node!(t, n, s, join_lines = true)
-            !(nospace && nonest) && add_node!(t, Placeholder(1), s)
+            if !(nospace && nonest)
+                add_node!(t, Placeholder(1), s)
+            end
         elseif i == length(x) - 1 && is_punc(a) && is_punc(x.args[i+1])
             add_node!(t, n, s, join_lines = true)
-        elseif CSTParser.is_comma(a) && i != length(x)
-            add_node!(t, n, s, join_lines = true)
-            add_node!(t, Whitespace(1), s)
         else
             add_node!(t, n, s, join_lines = true)
         end
     end
     t
 end
-#
+
 # ColonOpCall
 function p_coloncall(x, s)
     t = PTree(x, nspaces(s))
@@ -1202,7 +1205,7 @@ function p_coloncall(x, s)
     t
 end
 
-# CSTParser.Kw
+# Kw
 function p_kw(x, s)
     t = PTree(x, nspaces(s))
     for a in x
@@ -1218,30 +1221,33 @@ function p_kw(x, s)
 end
 
 closing_punc_type(x) =
-    x.typ === CSTParser.TupleH ||
-    x.typ === CSTParser.Vect ||
-    x.typ === CSTParser.Vcat ||
-    x.typ === CSTParser.Braces ||
-    x.typ === CSTParser.Call ||
-    x.typ === CSTParser.Curly ||
-    x.typ === CSTParser.Comprehension ||
-    x.typ === CSTParser.MacroCall ||
-    x.typ === CSTParser.InvisBrackets ||
+    x.typ === CSTParser.TupleH || x.typ === CSTParser.Vect ||
+    x.typ === CSTParser.Vcat || x.typ === CSTParser.Braces || x.typ === CSTParser.Call ||
+    x.typ === CSTParser.Curly || x.typ === CSTParser.Comprehension ||
+    x.typ === CSTParser.MacroCall || x.typ === CSTParser.InvisBrackets ||
     x.typ === CSTParser.Ref || x.typ === CSTParser.TypedVcat
 
-# TODO: think of a better name?
 block_type(x::CSTParser.EXPR) =
     x.typ === CSTParser.If ||
-    x.typ === CSTParser.Do ||
-    x.typ === CSTParser.Try ||
-    x.typ === CSTParser.For ||
+    x.typ === CSTParser.Do || x.typ === CSTParser.Try || x.typ === CSTParser.For ||
     x.typ === CSTParser.While || (x.typ === CSTParser.Let && length(x) > 3)
 
-nest_assignment(x::CSTParser.EXPR) = CSTParser.is_assignment(x) && block_type(x.args[3])
+nest_rhs(x::CSTParser.EXPR) =
+    block_type(x) || x.typ === CSTParser.ConditionalOpCall ||
+    x.typ === CSTParser.ChainOpCall || x.typ === CSTParser.Comparison || (
+        x.typ === CSTParser.BinaryOpCall && x[2].kind !== Tokens.COLON
+    )
+
+nest_assignment(x::CSTParser.EXPR) = CSTParser.precedence(x[2].kind) == 1 && nest_rhs(x[3])
+
+unnestable_arg(x) =
+    closing_punc_type(x) || x.typ === CSTParser.StringH || x.typ === CSTParser.LITERAL || (
+        x.typ === CSTParser.BinaryOpCall && x[2].kind === Tokens.DOT
+    )
 
 function nestable(x::CSTParser.EXPR)
     CSTParser.defines_function(x) && x[1].typ !== CSTParser.UnaryOpCall && return true
-    CSTParser.is_assignment(x) && return block_type(x.args[3])
+    nest_assignment(x) && return true
     (
      x[1].typ === CSTParser.InvisBrackets || x[3].typ === CSTParser.InvisBrackets
     ) && return false
@@ -1256,7 +1262,7 @@ function nestable(x::CSTParser.EXPR)
         end
         if arg.typ === CSTParser.BinaryOpCall
             op = arg.args[2].kind
-            (op == Tokens.LAZY_AND || op == Tokens.LAZY_OR) && (return true)
+            (op == Tokens.LAZY_AND || op == Tokens.LAZY_OR) && return true
         end
 
         arg = x.args[3]
@@ -1265,12 +1271,13 @@ function nestable(x::CSTParser.EXPR)
         end
         if arg.typ === CSTParser.BinaryOpCall
             op = arg.args[2].kind
-            (op == Tokens.LAZY_AND || op == Tokens.LAZY_OR) && (return true)
+            (op == Tokens.LAZY_AND || op == Tokens.LAZY_OR) && return true
         end
 
         return parent_is(
             x,
             x -> x.typ in (CSTParser.If, CSTParser.BinaryOpCall, CSTParser.While),
+            ignore_typs = [CSTParser.InvisBrackets],
         )
     end
     true
@@ -1364,9 +1371,12 @@ function p_wherecall(x, s)
     # Used to mark where `B` starts.
     add_node!(t, Placeholder(0), s)
 
-    multi_arg = length(CSTParser.get_where_params(x)) > 0
-    add_braces = !CSTParser.is_lbrace(x.args[3]) &&
-                 x.parent.typ !== CSTParser.Curly && x.args[3].typ !== CSTParser.Curly
+    nest = length(CSTParser.get_where_params(x)) > 0
+    # nest = !(length(CSTParser.get_where_params(x)) == 1 && unnestable_arg(x[1]))
+    add_braces =
+        !CSTParser.is_lbrace(x.args[3]) &&
+        x.parent.typ !== CSTParser.Curly && x.args[3].typ !== CSTParser.Curly
+
     add_braces && add_node!(
         t,
         PTree(CSTParser.PUNCTUATION, t.endline, t.endline, "{"),
@@ -1374,13 +1384,13 @@ function p_wherecall(x, s)
         join_lines = true,
     )
 
-    # @debug "" multi_arg in_braces x.args[3].val == "{" x.args[end].val
+    # @debug "" nest in_braces x.args[3].val == "{" x.args[end].val
     for (i, a) in enumerate(x.args[3:end])
-        if is_opener(a) && multi_arg
+        if is_opener(a) && nest
             add_node!(t, pretty(a, s), s, join_lines = true)
             add_node!(t, Placeholder(0), s)
             s.indent += s.indent_size
-        elseif is_closer(a) && multi_arg
+        elseif is_closer(a) && nest
             add_node!(t, TrailingComma(), s)
             add_node!(t, Placeholder(0), s)
             add_node!(t, pretty(a, s), s, join_lines = true)
@@ -1433,14 +1443,15 @@ function p_curly(x, s)
     add_node!(t, pretty(x.args[1], s), s)
     add_node!(t, pretty(x.args[2], s), s, join_lines = true)
 
-    multi_arg = length(CSTParser.get_curly_params(x)) > 0
+    args = get_args(x)
+    nest = length(args) > 0 && !(length(args) == 1 && unnestable_arg(x[1]))
 
-    if multi_arg
+    if nest
         add_node!(t, Placeholder(0), s)
     end
 
     for (i, a) in enumerate(x.args[3:end])
-        if i + 2 == length(x) && multi_arg
+        if i + 2 == length(x) && nest
             add_node!(t, TrailingComma(), s)
             add_node!(t, Placeholder(0), s)
             add_node!(t, pretty(a, s), s, join_lines = true)
@@ -1459,14 +1470,15 @@ function p_call(x, s)
     add_node!(t, pretty(x.args[1], s), s)
     add_node!(t, pretty(x.args[2], s), s, join_lines = true)
 
-    multi_arg = n_args(x) > 0
+    args = get_args(x)
+    nest = length(args) > 0 && !(length(args) == 1 && unnestable_arg(args[1]))
 
-    if multi_arg
+    if nest
         add_node!(t, Placeholder(0), s)
     end
 
     for (i, a) in enumerate(x.args[3:end])
-        if i + 2 == length(x) && multi_arg
+        if i + 2 == length(x) && nest
             add_node!(t, TrailingComma(), s)
             add_node!(t, Placeholder(0), s)
             add_node!(t, pretty(a, s), s, join_lines = true)
@@ -1484,6 +1496,7 @@ end
 function p_invisbrackets(x, s; nonest = false, nospace = false)
     t = PTree(x, nspaces(s))
     parent_invis = x[2].typ === CSTParser.InvisBrackets
+    parent_invis = closing_punc_type(x[2])
     # @info "" x parent_invis
 
     for (i, a) in enumerate(x)
@@ -1521,14 +1534,16 @@ end
 # TupleH
 function p_tuple(x, s)
     t = PTree(x, nspaces(s))
-    multi_arg = n_args(x) > 0
+
+    args = get_args(x)
+    nest = length(args) > 0 && !(length(args) == 1 && unnestable_arg(args[1]))
 
     for (i, a) in enumerate(x)
         n = pretty(a, s)
-        if is_opener(n) && multi_arg
+        if is_opener(n) && nest
             add_node!(t, n, s, join_lines = true)
             add_node!(t, Placeholder(0), s)
-        elseif is_closer(n) && multi_arg
+        elseif is_closer(n) && nest
             add_node!(t, TrailingComma(), s)
             add_node!(t, Placeholder(0), s)
             add_node!(t, n, s, join_lines = true)
@@ -1545,14 +1560,14 @@ end
 # Braces
 function p_braces(x, s)
     t = PTree(x, nspaces(s))
-    multi_arg = length(x) > 2
+    nest = length(x) > 2 && !(length(x) == 3 && unnestable_arg(x[2]))
 
     for (i, a) in enumerate(x)
         n = pretty(a, s)
-        if i == 1 && multi_arg
+        if i == 1 && nest
             add_node!(t, n, s, join_lines = true)
             add_node!(t, Placeholder(0), s)
-        elseif i == length(x) && multi_arg
+        elseif i == length(x) && nest
             add_node!(t, TrailingComma(), s)
             add_node!(t, Placeholder(0), s)
             add_node!(t, n, s, join_lines = true)
@@ -1569,14 +1584,14 @@ end
 # Vect
 function p_vect(x, s)
     t = PTree(x, nspaces(s))
-    multi_arg = length(x) > 2
+    nest = length(x) > 2 && !(length(x) == 3 && unnestable_arg(x[2]))
 
     for (i, a) in enumerate(x)
         n = pretty(a, s)
-        if i == 1 && multi_arg
+        if i == 1 && nest
             add_node!(t, n, s, join_lines = true)
             add_node!(t, Placeholder(0), s)
-        elseif i == length(x) && multi_arg
+        elseif i == length(x) && nest
             add_node!(t, TrailingComma(), s)
             add_node!(t, Placeholder(0), s)
             add_node!(t, n, s, join_lines = true)
@@ -1630,13 +1645,13 @@ end
 # Ref
 function p_ref(x, s)
     t = PTree(x, nspaces(s))
-    multi_arg = length(x) > 5
+    nest = length(x) > 5 && !(length(x) == 5 && unnestable_arg(x[3]))
     for (i, a) in enumerate(x)
-        if is_closer(a) && multi_arg
+        if is_closer(a) && nest
             add_node!(t, TrailingComma(), s)
             add_node!(t, Placeholder(0), s)
             add_node!(t, pretty(a, s), s, join_lines = true)
-        elseif is_opener(a) && multi_arg
+        elseif is_opener(a) && nest
             add_node!(t, pretty(a, s), s, join_lines = true)
             add_node!(t, Placeholder(0), s)
         elseif CSTParser.is_comma(a) && i < length(x) && !is_punc(x.args[i+1])
@@ -1667,13 +1682,14 @@ end
 function p_vcat(x, s)
     t = PTree(x, nspaces(s))
     st = x.typ === CSTParser.Vcat ? 1 : 2
-    multi_arg = n_args(x) > 0
-    # @info "" multi_arg length(x) st
+    args = get_args(x)
+    nest = length(args) > 0 && !(length(args) == 1 && unnestable_arg(args[1]))
+    # @info "" nest length(x) st
 
     for (i, a) in enumerate(x)
         n = pretty(a, s)
         diff_line = t.endline != t.startline
-        if is_opener(a) && multi_arg
+        if is_opener(a) && nest
             add_node!(t, n, s, join_lines = true)
             add_node!(t, Placeholder(0), s)
         elseif !is_closer(a) && i > st


Test patch:
diff --git a/test/files/Docs.jl b/test/files/Docs.jl
index eae1039e..97a761fe 100644
--- a/test/files/Docs.jl
+++ b/test/files/Docs.jl
@@ -280,8 +280,9 @@ function astname(x::Expr, ismacro::Bool)
     if isexpr(x, :.)
         ismacro ? macroname(x) : x
     # Call overloading, e.g. `(a::A)(b) = b` or `function (a::A)(b) b end` should document `A(b)`
-    elseif (isexpr(x, :function) || isexpr(x, :(=))) && isexpr(x.args[1], :call) &&
-                                                        isexpr(x.args[1].args[1], :(::))
+    elseif (
+        isexpr(x, :function) || isexpr(x, :(=))
+    ) && isexpr(x.args[1], :call) && isexpr(x.args[1].args[1], :(::))
         return astname(x.args[1].args[1].args[end], ismacro)
     else
         n = isexpr(x, (:module, :struct)) ? 2 : 1
@@ -296,10 +297,9 @@ macroname(s::Symbol) = Symbol('@', s)
 macroname(x::Expr) = Expr(x.head, x.args[1], macroname(x.args[end].value))
 
 isfield(@nospecialize x) =
-    isexpr(x, :.) &&
-    (isa(x.args[1], Symbol) || isfield(x.args[1])) && (
-        isa(x.args[2], QuoteNode) || isexpr(x.args[2], :quote)
-    )
+    isexpr(x, :.) && (
+     isa(x.args[1], Symbol) || isfield(x.args[1])
+    ) && (isa(x.args[2], QuoteNode) || isexpr(x.args[2], :quote))
 
 # @doc expression builders.
 # =========================
@@ -341,11 +341,10 @@ function metadata(__source__, __module__, expr, ismodule)
                 end
             elseif isexpr(each, :function) || isexpr(each, :(=))
                 break
-            elseif isa(each, String) ||
-                   isexpr(each, :string) ||
-                   isexpr(each, :call) || (
-                isexpr(each, :macrocall) && each.args[1] === Symbol("@doc_str")
-            )
+            elseif isa(each, String) || isexpr(each, :string) || isexpr(
+                each,
+                :call,
+            ) || (isexpr(each, :macrocall) && each.args[1] === Symbol("@doc_str"))
                 # forms that might be doc strings
                 last_docstr = each
             end
@@ -358,28 +357,24 @@ end
 
 function keyworddoc(__source__, __module__, str, def::Base.BaseDocs.Keyword)
     @nospecialize str
-    docstr = esc(
-        docexpr(
-            __source__,
-            __module__,
-            lazy_iterpolate(str),
-            metadata(__source__, __module__, def, false),
-        ),
-    )
+    docstr = esc(docexpr(
+        __source__,
+        __module__,
+        lazy_iterpolate(str),
+        metadata(__source__, __module__, def, false),
+    ),)
     return :($setindex!($(keywords), $docstr, $(esc(quot(def.name)))); nothing)
 end
 
 function objectdoc(__source__, __module__, str, def, expr, sig = :(Union{}))
     @nospecialize str def expr sig
     binding = esc(bindingexpr(namify(expr)))
-    docstr = esc(
-        docexpr(
-            __source__,
-            __module__,
-            lazy_iterpolate(str),
-            metadata(__source__, __module__, expr, false),
-        ),
-    )
+    docstr = esc(docexpr(
+        __source__,
+        __module__,
+        lazy_iterpolate(str),
+        metadata(__source__, __module__, expr, false),
+    ),)
     # Note: we want to avoid introducing line number nodes here (issue #24468)
     return Expr(:block, esc(def), :($(doc!)($__module__, $binding, $docstr, $(esc(sig)))))
 end
@@ -566,11 +561,11 @@ function docm(source::LineNumberNode, mod::Module, meta, ex, define::Bool = true
     #   function f end
     #   f(...)
     #
-          isexpr(x, FUNC_HEADS) && is_signature(x.args[1]) ?
-          objectdoc(source, mod, meta, def, x, signature(x)) :
-          isexpr(x, [:function, :macro]) && !isexpr(x.args[1], :call) ?
-          objectdoc(source, mod, meta, def, x) :
-          isexpr(x, :call) ? calldoc(source, mod, meta, x) :
+        isexpr(x, FUNC_HEADS) && is_signature(x.args[1]) ?
+        objectdoc(source, mod, meta, def, x, signature(x)) :
+        isexpr(x, [:function, :macro]) && !isexpr(x.args[1], :call) ?
+        objectdoc(source, mod, meta, def, x) :
+        isexpr(x, :call) ? calldoc(source, mod, meta, x) :
 
     # Type definitions.
     #
@@ -578,8 +573,7 @@ function docm(source::LineNumberNode, mod::Module, meta, ex, define::Bool = true
     #   abstract type T end
     #   primitive type T N end
     #
-          isexpr(x, [:struct, :abstract, :primitive]) ?
-          objectdoc(source, mod, meta, def, x) :
+        isexpr(x, [:struct, :abstract, :primitive]) ? objectdoc(source, mod, meta, def, x) :
 
     # "Bindings". Names that resolve to objects with different names, ie.
     #
@@ -587,26 +581,26 @@ function docm(source::LineNumberNode, mod::Module, meta, ex, define::Bool = true
     #   T = S
     #   global T = S
     #
-          isexpr(x, BINDING_HEADS) && !isexpr(x.args[1], :call) ?
-          objectdoc(source, mod, meta, def, x) :
+        isexpr(x, BINDING_HEADS) && !isexpr(x.args[1], :call) ?
+        objectdoc(source, mod, meta, def, x) :
 
     # Quoted macrocall syntax. `:@time` / `:(Base.@time)`.
-          isquotedmacrocall(x) ? objectdoc(source, mod, meta, def, x) :
+        isquotedmacrocall(x) ? objectdoc(source, mod, meta, def, x) :
     # Modules and baremodules.
-          isexpr(x, :module) ? moduledoc(source, mod, meta, def, x) :
+        isexpr(x, :module) ? moduledoc(source, mod, meta, def, x) :
     # Document several expressions with the same docstring. `a, b, c`.
-          isexpr(x, :tuple) ? multidoc(source, mod, meta, x, define) :
+        isexpr(x, :tuple) ? multidoc(source, mod, meta, x, define) :
     # Errors generated by calling `macroexpand` are passed back to the call site.
-          isexpr(x, :error) ? esc(x) :
+        isexpr(x, :error) ? esc(x) :
     # When documenting macro-generated code we look for embedded `@__doc__` calls.
-          __doc__!(meta, x, define) ? esc(x) :
+        __doc__!(meta, x, define) ? esc(x) :
     # Any "basic" expression such as a bare function or module name or numeric literal.
-          isbasicdoc(x) ? objectdoc(source, mod, meta, nothing, x) :
+        isbasicdoc(x) ? objectdoc(source, mod, meta, nothing, x) :
 
     # All other expressions are undocumentable and should be handled on a case-by-case basis
     # with `@__doc__`. Unbound string literals are also undocumentable since they cannot be
     # retrieved from the module's metadata `IdDict` without a reference to the string.
-          docerror(ex)
+        docerror(ex)
 
     return doc
 end
diff --git a/test/files/PProf.jl b/test/files/PProf.jl
index 29686e77..aaaf38df 100644
--- a/test/files/PProf.jl
+++ b/test/files/PProf.jl
@@ -18,9 +18,7 @@ clear
 # Load in `deps.jl`, complaining if it does not exist
 const depsjl_path = joinpath(@__DIR__, "..", "deps", "deps.jl")
 if !isfile(depsjl_path)
-    error(
-        "PProf not installed properly, run Pkg.build(\"PProf\"), restart Julia and try again",
-    )
+    error("PProf not installed properly, run Pkg.build(\"PProf\"), restart Julia and try again",)
 end
 include(depsjl_path)
 
diff --git a/test/files/adjoint.jl b/test/files/adjoint.jl
index 675b210e..91cebe38 100644
--- a/test/files/adjoint.jl
+++ b/test/files/adjoint.jl
@@ -28,8 +28,8 @@ function gradm(ex, mut = false)
     kw = length(args) > 1 && isexpr(args[1], :parameters) ? esc(popfirst!(args)) : nothing
     isclosure = isexpr(name, :(::)) && length(name.args) > 1
     f, T = isexpr(name, :(::)) ?
-           (length(name.args) == 1 ? (esc(gensym()), esc(name.args[1])) : esc.(name.args)) :
-           (esc(gensym()), :(Core.Typeof($(esc(name)))))
+        (length(name.args) == 1 ? (esc(gensym()), esc(name.args[1])) : esc.(name.args)) :
+        (esc(gensym()), :(Core.Typeof($(esc(name)))))
     kT = :(Core.kwftype($T))
     Ts == nothing && (Ts = [])
     args = named.(args)
diff --git a/test/files/reverse.jl b/test/files/reverse.jl
index 13b2d94d..bf626353 100644
--- a/test/files/reverse.jl
+++ b/test/files/reverse.jl
@@ -147,18 +147,17 @@ function record_branches!(ir::IR)
     return ir, brs
 end
 
-ignored_f(f) =
-    f in (
-        GlobalRef(Base, :not_int),
-        GlobalRef(Core.Intrinsics, :not_int),
-        GlobalRef(Core, :(===)),
-        GlobalRef(Core, :apply_type),
-        GlobalRef(Core, :typeof),
-        GlobalRef(Core, :throw),
-        GlobalRef(Base, :kwerr),
-        GlobalRef(Core, :kwfunc),
-        GlobalRef(Core, :isdefined),
-    )
+ignored_f(f) = f in (
+    GlobalRef(Base, :not_int),
+    GlobalRef(Core.Intrinsics, :not_int),
+    GlobalRef(Core, :(===)),
+    GlobalRef(Core, :apply_type),
+    GlobalRef(Core, :typeof),
+    GlobalRef(Core, :throw),
+    GlobalRef(Base, :kwerr),
+    GlobalRef(Core, :kwfunc),
+    GlobalRef(Core, :isdefined),
+)
 ignored_f(ir, f) = ignored_f(f)
 ignored_f(ir, f::Variable) = ignored_f(get(ir, f, nothing))
 
@@ -256,7 +255,7 @@ function adjointcfg(pr::Primal)
         rb = block(ir, b.id)
         for i = 1:length(preds)
             cond = i == length(preds) ? nothing :
-                   push!(rb, xcall(Base, :(!==), alpha(pr.branches[b.id]), BranchNumber(i)))
+                push!(rb, xcall(Base, :(!==), alpha(pr.branches[b.id]), BranchNumber(i)))
             branch!(rb, preds[i].id, unless = cond)
         end
         if !isempty(branches(b)) && branches(b)[end] == IRTools.unreachable
diff --git a/test/runtests.jl b/test/runtests.jl
index 61ff08b6..06d7c6ee 100644
--- a/test/runtests.jl
+++ b/test/runtests.jl
@@ -2,7 +2,7 @@ using JuliaFormatter
 using CSTParser
 using Test
 
-fmt1(s, i, m, always_for_in) =
+fmt1(s, i = 4, m = 80, always_for_in = false) =
     JuliaFormatter.format_text(s, indent = i, margin = m, always_for_in = always_for_in)
 
 # Verifies formatting the formatted text
@@ -604,15 +604,184 @@ end
         str_ = """a, b = cond ? e1 : e2"""
         str = """
         a, b = cond ?
-               e1 :
-               e2"""
+            e1 : e2"""
         @test fmt(str_, 4, 13) == str
 
         str = """
-        a,
-        b = cond ?
+        a, b =
+            cond ?
             e1 : e2"""
         @test fmt(str_, 4, 12) == str
+
+        str = """
+        begin
+            variable_name =
+                argument1 + argument2
+        end"""
+        @test fmt(str, 4, 40) == str
+
+        str = """
+        begin
+            variable_name =
+                argument1 +
+                argument2
+        end"""
+        @test fmt(str, 4, 28) == str
+
+        str = """
+        begin
+            variable_name =
+                conditional ? expression1 : expression2
+        end"""
+        @test fmt(str, 4, 58) == str
+
+        str = """
+        begin
+            variable_name =
+                conditional ? expression1 :
+                expression2
+        end"""
+        @test fmt(str, 4, 46) == str
+
+        str = """
+        begin
+            variable_name = conditional ?
+                expression1 : expression2
+        end"""
+        @test fmt(str, 4, 34) == str
+
+        str = """
+        begin
+            variable_name =
+                conditional ?
+                expression1 :
+                expression2
+        end"""
+        @test fmt(str, 4, 32) == str
+
+        str = "shmem[pout*rows+row] += shmem[pin*rows+row] + shmem[pin*rows+row-offset]"
+
+        str_ = """
+        shmem[pout*rows+row] +=
+               shmem[pin*rows+row] + shmem[pin*rows+row-offset]"""
+        @test fmt(str, 7, 71) == str_
+        str_ = """
+        shmem[pout*rows+row] +=
+               shmem[pin*rows+row] +
+               shmem[pin*rows+row-offset]"""
+        @test fmt(str, 7, 54) == str_
+
+        str = """
+        begin
+           var = func(arg1, arg2, arg3) * num
+        end"""
+        @test fmt(str, 3, 37) == str
+
+        str_ = """
+        begin
+           var =
+              func(arg1, arg2, arg3) * num
+        end"""
+        @test fmt(str, 3, 36) == str_
+        @test fmt(str, 3, 34) == str_
+
+        str_ = """
+        begin
+           var =
+              func(arg1, arg2, arg3) *
+              num
+        end"""
+        @test fmt(str, 3, 33) == str_
+        @test fmt(str, 3, 30) == str_
+
+        str_ = """
+        begin
+           var =
+              func(
+                 arg1,
+                 arg2,
+                 arg3,
+              ) * num
+        end"""
+        @test fmt(str, 3, 29) == str_
+
+        str_ = """
+        begin
+           var =
+              func(
+                 arg1,
+                 arg2,
+                 arg3,
+              ) *
+              num
+        end"""
+        @test fmt(str, 3, 1) == str_
+
+        str = """
+        begin
+            foo() =
+                (one, x -> (true, false))
+        end"""
+        @test fmt(str, 4, 36) == str
+        @test fmt(str, 4, 33) == str
+
+        str = """
+        begin
+            foo() = 
+                (
+                 one,
+                 x -> (true, false),
+                )
+        end"""
+        str = """
+        begin
+            foo() = (
+                one,
+                x -> (true, false),
+            )
+        end"""
+        @test fmt(str, 4, 32) == str
+        @test fmt(str, 4, 28) == str
+
+        str = """
+        begin
+                  foo() = (
+                           one,
+                           x -> (
+                                 true,
+                                 false,
+                           ),
+                  )
+        end"""
+        @test fmt(str, 10, 39) == str
+
+        str = """
+        ignored_f(f) = f in (
+            GlobalRef(Base, :not_int),
+            GlobalRef(Core.Intrinsics, :not_int),
+            GlobalRef(Core, :(===)),
+            GlobalRef(Core, :apply_type),
+            GlobalRef(Core, :typeof),
+            GlobalRef(Core, :throw),
+            GlobalRef(Base, :kwerr),
+            GlobalRef(Core, :kwfunc),
+            GlobalRef(Core, :isdefined),
+        )"""
+        @test fmt(str) == str
+
+        str = """
+        ignored_f(f) = f in (((
+            GlobalRef(Base, :not_int),
+            GlobalRef(Core.Intrinsics, :not_int),
+            GlobalRef(Core, :(===)),
+            GlobalRef(Core, :apply_type),
+            GlobalRef(Core, :typeof),
+            GlobalRef(Core, :throw),
+            GlobalRef(Base, :kwerr),
+            GlobalRef(Core, :kwfunc),
+            GlobalRef(Core, :isdefined),
+        )))"""
+        @test fmt(str) == str
     end
 
     @testset "op chain" begin
@@ -845,13 +1014,10 @@ end
 
         str = """
         map(1:10, 11:20) do x, y
-            x + y + foo + bar + ba
-            x + y + foo + bar +
-            baz
+            z = reallylongvariablename
         end"""
         t = run_pretty(str, 80)
-        @test length(t) == 27
-        @test fmt(str, 4, 26) == str
+        @test length(t) == 30
 
         # issue #58
 
@@ -1387,23 +1553,7 @@ end
            end
         end"""
         @test fmt(str_, 4, 200) == str
-
-        str = """
-        begin
-            begin
-                throw(
-                    ErrorException(
-                        \"""An error occured formatting \$filename. :-(
-
-                        Please file an issue at https://github.com/domluna/JuliaFormatter.jl/issues
-                        with a link to a gist containing the contents of the file. A gist
-                        can be created at https://gist.github.com/.\""",
-                    ),
-                )
-            end
-        end"""
-        @test fmt(str_) == str
-
+        @test fmt(str_, 4, 1) == str
 
         str = """
         foo() = llvmcall(\"""
@@ -1431,24 +1581,14 @@ end
                      llvm2
                      \""")"""
         @test fmt(str, 4, 19) == str_
-        str_ = """
-        foo() = llvmcall(
-            \"""
-            llvm1
-            llvm2
-            \""",
-        )"""
         @test fmt(str, 4, 18) == str_
 
-
         str_ = """
         foo() =
-          llvmcall(
-            \"""
-            llvm1
-            llvm2
-            \""",
-          )"""
+          llvmcall(\"""
+                   llvm1
+                   llvm2
+                   \""")"""
         @test fmt(str, 2, 10) == str_
 
         str = """
@@ -1479,35 +1619,7 @@ end
             \"""))
         end"""
         @test fmt(str) == str
-
-        # Technically it nests sonner than it should but that's due to the 
-        # closing parenthesis. ATM I don't think it's worth factoring that in.
-
-        str_ = raw"""
-        if free < min_space
-            throw(
-                ErrorException(\"""
-          Free space: \$free Gb
-          Please make sure to have at least \$min_space Gb of free disk space
-          before downloading the $database_name database.
-          \"""),
-            )
-        end"""
-        @test fmt(str, 4, 71) == str_
-
-        str_ = raw"""
-        if free < min_space
-            throw(
-                ErrorException(
-                    \"""
-        Free space: \$free Gb
-        Please make sure to have at least \$min_space Gb of free disk space
-        before downloading the $database_name database.
-        \""",
-                ),
-            )
-        end"""
-        @test fmt(str, 4, 69) == str_
+        @test fmt(str, 4, 1) == str
 
     end
 
@@ -2005,9 +2117,7 @@ end
                          e8
                      end
                  end"""
-        @test fmt(
-            "begin if cond1 e1; e2 elseif cond2 e3; e4 elseif cond3 e5;e6 else e7;e8  end end",
-        ) == str
+        @test fmt("begin if cond1 e1; e2 elseif cond2 e3; e4 elseif cond3 e5;e6 else e7;e8  end end",) == str
 
         str = """if cond1
                      e1
@@ -2275,30 +2385,6 @@ end
                          b"""
         @test fmt("import M1.M2.M3:a,b", 4, 1) == str
 
-        str = """
-        foo() =
-            (one, x -> (true, false))"""
-        @test fmt("foo() = (one, x -> (true, false))", 4, 30) == str
-
-        str = """
-        foo() = (
-            one,
-            x -> (
-                true,
-                false,
-            ),
-        )"""
-        @test fmt("foo() = (one, x -> (true, false))", 4, 20) == str
-
-        str = """
-        foo() = (
-                 one,
-                 x -> (
-                       true,
-                       false,
-                 ),
-        )"""
-        @test fmt("foo() = (one, x -> (true, false))", 10, 20) == str
 
         str = """
         @somemacro function (fcall_ | fcall_)
@@ -2425,12 +2511,8 @@ end
              :numberofpointattributes => NAttributes,
              :numberofpointmtrs => NMTr,
              :numberofcorners => NSimplex,
-             :firstnumber => Cint(
-                  1,
-             ),
-             :mesh_dim => Cint(
-                  3,
-             ),
+             :firstnumber => Cint(1),
+             :mesh_dim => Cint(3),
         )"""
         @test fmt(str_, 5, 1) == str
 
@@ -2510,31 +2592,7 @@ end
         @test fmt("a[(1 + 2)]", 4, 1) == str
 
         str_ = "(a + b + c + d)"
-        @test fmt(str_, 4, 15) == str_
-
-        str = """
-        (
-         a + b + c +
-         d
-        )"""
-        @test fmt(str_, 4, 14) == str
-        @test fmt(str_, 4, 12) == str
-
-        str = """
-        (
-         a + b +
-         c + d
-        )"""
-        @test fmt(str_, 4, 11) == str
-        @test fmt(str_, 4, 8) == str
-
-        str = """
-        (
-         a +
-         b +
-         c + d
-        )"""
-        @test fmt(str_, 4, 7) == str
+        @test fmt(str_, 4, length(str_)) == str_
 
         str = """
         (
@@ -2543,35 +2601,11 @@ end
          c +
          d
         )"""
+        @test fmt(str_, 4, length(str_) - 1) == str
         @test fmt(str_, 4, 1) == str
 
         str_ = "(a <= b <= c <= d)"
-        @test fmt(str_, 4, 18) == str_
-
-        str = """
-        (
-         a <= b <= c <=
-         d
-        )"""
-        @test fmt(str_, 4, 17) == str
-        @test fmt(str_, 4, 15) == str
-
-        str = """
-        (
-         a <= b <=
-         c <= d
-        )"""
-        @test fmt(str_, 4, 14) == str
-        @test fmt(str_, 4, 10) == str
-
-        str = """
-        (
-         a <=
-         b <=
-         c <= d
-        )"""
-        @test fmt(str_, 4, 9) == str
-        @test fmt(str_, 4, 8) == str
+        @test fmt(str_, 4, length(str_)) == str_
 
         str = """
         (
@@ -2580,7 +2614,7 @@ end
          c <=
          d
         )"""
-        @test fmt(str_, 4, 7) == str
+        @test fmt(str_, 4, length(str_) - 1) == str
         @test fmt(str_, 4, 1) == str
 
         # https://github.com/domluna/JuliaFormatter.jl/issues/60
@@ -3030,23 +3064,14 @@ end
         # issue 56
         str_ = "a_long_function_name(Array{Float64,2}[[1.0], [0.5 0.5], [0.5 0.5; 0.5 0.5], [0.5 0.5; 0.5 0.5]])"
         str = """
-        a_long_function_name(
-            Array{Float64,2}[[1.0], [0.5 0.5], [0.5 0.5; 0.5 0.5], [0.5 0.5; 0.5 0.5]],
-        )"""
+        a_long_function_name(Array{Float64,2}[
+            [1.0],
+            [0.5 0.5],
+            [0.5 0.5; 0.5 0.5],
+            [0.5 0.5; 0.5 0.5],
+        ])"""
         @test fmt(str, 4, length(str)) == str_
-        @test fmt(str_) == str
-        @test fmt(str_, 4, 79) == str
-
-        str = """
-        a_long_function_name(
-            Array{Float64,2}[
-                [1.0],
-                [0.5 0.5],
-                [0.5 0.5; 0.5 0.5],
-                [0.5 0.5; 0.5 0.5],
-            ],
-        )"""
-        @test fmt(str_, 4, 78) == str
+        @test fmt(str_, 4, length(str_) - 1) == str
 
         # unary op
         str_ = "[1, 1]'"
@@ -3297,9 +3322,10 @@ end
         begin
             weights = Dict(
                 (file, i) => w for (file, subject) in subjects
-                for (i, w) in enumerate(
-                    weightfn.(eachrow(subject.events)),
-                )
+                for (
+                    i,
+                    w,
+                ) in enumerate(weightfn.(eachrow(subject.events)))
             )
         end"""
         @test fmt(str_, 4, 60) == str
@@ -3309,9 +3335,10 @@ end
             weights = Dict(
                 (file, i) => w
                 for (file, subject) in subjects
-                for (i, w) in enumerate(
-                    weightfn.(eachrow(subject.events)),
-                )
+                for (
+                    i,
+                    w,
+                ) in enumerate(weightfn.(eachrow(subject.events)))
             )
         end"""
         @test fmt(str_, 4, 50) == str