Add support for preserve_single_line_if::Bool#937
Conversation
preserve_single_line_if = x::Boolpreserve_single_line_if = ::Bool
preserve_single_line_if = ::Boolpreserve_single_line_if::Bool
domluna
left a comment
There was a problem hiding this comment.
please add some test cases
looks good otherwise.
|
This patch no longer works on the current version: julia> using JuliaFormatter: format_text
julia> s = "if rand() < 0.5 return 2 end"
"if rand() < 0.5 return 2 end"
julia> format_text(s; preserve_single_line_if=true) |> println
if rand() < 0.5
return 2
end@alexandergunnarson Are you still interested in working on this? No worries if not as I can pick it up (at some point in time....). |
- Fix the preserve_single_line_if option which was broken after merging with master. The previous approach only controlled ignore_single_line on the block context, but didn't handle the add_node! calls that force newlines via max_padding. - Now properly checks if the entire if statement is on a single line using on_same_line(), and when preserve_single_line=true: - Adds block content with join_lines=true instead of max_padding - Adds else/elseif/end keywords with join_lines=true - Inserts explicit Whitespace(1) between elements - Skips indent adjustments (not needed for single-line) - Add comprehensive test cases covering: - Basic single-line if - Default behavior (expand single-line if) - Multi-line if unaffected by the option - Single-line if-else - Single-line if-elseif-else - Multi-line if-else unaffected - Nested single-line if - Single-line if inside a function - Expansion when option is false
|
@domluna Sorry — added test cases in the most recent commit. @penelopeysm — Thanks for alerting me! Patch now works with latest version. |
|
Thanks 😊 This looks generally great. I have one question about what the intended behaviour should be when overflowing the max width. Currently we have this: julia> using JuliaFormatter: format_text
julia> format_text("if x > 0 return 1 end"; preserve_single_line_if=true, margin=7) |> println
if x >
0 return 1 end
julia> format_text("if x > 0 return 1 end"; preserve_single_line_if=true, margin=8) |> println
if x > 0 return 1 endThe issue is that the
|
| end | ||
| elseif !JuliaSyntax.is_whitespace(c) | ||
| add_node!(t, Whitespace(1), s) | ||
| add_node!(t, pretty(style, c, s, ctx, lineage), s; join_lines = true) |
There was a problem hiding this comment.
(If you agree with (2), then I believe this is the appropriate fix:)
| add_node!(t, pretty(style, c, s, ctx, lineage), s; join_lines = true) | |
| ctx2 = preserve_single_line_if ? newctx(ctx; nonest=true) : ctx | |
| add_node!(t, pretty(style, c, s, ctx2, lineage), s; join_lines = true) |
There was a problem hiding this comment.
(1) looks trickier to accomplish to me. I haven't attempted to figure out how that would be done.
Before formatting (or with
preserve_single_line_if = true):After formatting with
preserve_single_line_if = false(default):Resolves #516.