JuliaFormatter.jl Alignment Help

I’ve been experimenting with JuliaFormatter v0.15.1 with 1.6.2 and I’ve had some trouble using the alignment flags. I have not changed any default settings or defined a JuliaFormatter.toml file.

Here’s the contents of my test file formattest.jl

struct Test
    a::Any
    ab::Any
    cde::Any
end

function test(abcd, edfg; qwert = 2)
    a = 2
    ab = 3+a
    abcd+2 - qwert+ab
end

abe = 1
bc = 2
qwerty = 3

long_variable = 1
other_var = 2

which I’m running like

julia> format_file(“formattest.jl”, align_assignment=true, align_struct_field=true)

I know the formatter is running because it fixes the spacing around the + operators, but it does not align any of the spacing around = or in the type definition.

Am I missing a step or misunderstanding the intended behavior?

So it looks like you might need to give the formatter a hint for this to work. For example in the type definition, if I align the first two, the third will get corrected. This doesn’t always seem to work, however, but seems to depend sometimes on the length of the variable… maybe?

I believe this section is trying to explain the rule, but I’m having trouble understanding the “heuristic.”
https://domluna.github.io/JuliaFormatter.jl/stable/custom_alignment/#Custom-Alignment

1 Like

It’s a heuristic. Sometimes it works and sometimes it doesn’t. Figuring out a good alignment is something you can easily do visually (helped because you know the context of the code), but it’s hard to do via code.

If the align_assignment option is enabled the formatter will detect that var2 is aligned to variable1 AND var2 has several whitespaces (>1) prior to = . Since var3 , var4 , and var5 are part of the same code block (no comments or newlines separating code) they will also be aligned.

This seems to explain things. long_variable doesn’t get formatted with qwerty because there is a space, and bc doesn’t get formatted with abe because there are not > 1 whitespaces between bc and =.

It seems the heuristic is really a “make an attempt manually and it will clean things up for you” rather than “automatically align everything without me doing anything.”

1 Like

odow is right, it’s based on heuristics so you have to nudge it in the right direction by manually adding whitespace. If you find a case where it should align but doesn’t feel free to post an issue.

2 Likes