From ae9ed30f0969198026700028583b7a8897eb8524 Mon Sep 17 00:00:00 2001 From: Fredrik Ekre Date: Sun, 23 Jun 2024 09:44:21 +0200 Subject: [PATCH] Spacing around ternary operators, fixes #11. --- src/Runic.jl | 1 + src/runestone.jl | 8 ++++++++ test/runtests.jl | 11 +++++++++++ 3 files changed, 20 insertions(+) diff --git a/src/Runic.jl b/src/Runic.jl index e99117b..9262f41 100644 --- a/src/Runic.jl +++ b/src/Runic.jl @@ -303,6 +303,7 @@ function format_node!(ctx::Context, node::Node)::Union{Node, Nothing, NullNode} @return_something spaces_around_operators(ctx, node) @return_something spaces_around_assignments(ctx, node) @return_something spaces_around_anonymous_function(ctx, node) + @return_something spaces_around_ternary(ctx, node) @return_something spaces_around_keywords(ctx, node) @return_something no_spaces_around_colon_etc(ctx, node) @return_something parens_around_op_calls_in_colon(ctx, node) diff --git a/src/runestone.jl b/src/runestone.jl index c1a124b..5b8d549 100644 --- a/src/runestone.jl +++ b/src/runestone.jl @@ -682,6 +682,14 @@ function spaces_around_anonymous_function(ctx::Context, node::Node) return spaces_around_x(ctx, node, is_x) end +function spaces_around_ternary(ctx::Context, node::Node) + if !(kind(node) === K"?" && !is_leaf(node)) + return nothing + end + is_x = x -> is_leaf(x) && kind(x) in KSet"? :" + return spaces_around_x(ctx, node, is_x) +end + # Opposite of `spaces_around_x`: remove spaces around `x` function no_spaces_around_x(ctx::Context, node::Node, is_x::F) where {F} @assert !is_leaf(node) diff --git a/test/runtests.jl b/test/runtests.jl index 1bbe353..82c593f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -277,6 +277,17 @@ end end end +@testset "whitespace around ternary" begin + for sp in (" ", " ") + @test format_string("a$(sp)?$(sp)b$(sp):$(sp)c") == "a ? b : c" + @test format_string("a$(sp)?\nb$(sp):\nc") == "a ?\n b :\n c" + @test format_string("a$(sp)?$(sp)b$(sp):$(sp)c$(sp)?$(sp)d$(sp):$(sp)e") == + "a ? b : c ? d : e" + @test format_string("a$(sp)?\nb$(sp):\nc$(sp)?\nd$(sp):\ne") == + "a ?\n b :\n c ?\n d :\n e" + end +end + @testset "whitespace in comparison chains" begin for sp in ("", " ", " ") @test format_string("a$(sp)==$(sp)b") == "a == b"