# API Documentation

JuliaFormatter.AlignGroupType
AlignGroup

Group of FST node indices and required metadata to potentially align them.

- node_idxs. Indices of FST nodes affected by alignment.
- line_offsets. Line offset of the character nodes may be aligned to
in the source file.
- lens. Length of the FST node prior to the alignment character. Used
to calculate extra whitespace padding.
- whitespaces. Number of whitespaces between the alignment character and
the prior FST node. If this is > 1 it signifies additional whitespace was
manually added by the user since the formatter would only use 0 or 1 whitespaces.
source
JuliaFormatter.add_node!Method
add_node!(
t::FST,
n::FST,
s::State;
join_lines::Bool = false,
override_join_lines_based_on_source::Bool = false,
)

Appends n to t.

• join_lines if false a NEWLINE node will be added and n will appear

on the next line, otherwise it will appear on the same line as the previous node (when printing).

• max_padding >= 0 indicates margin of t should be based on whether the margin

of n + max_padding is greater than the current margin of t. Otherwise the margin n will be added to t.

• override_join_lines_based_on_source is only used when join_lines_based_on_source option is true. In which

n is added to t as if join_lines_based_on_source was false.

source
JuliaFormatter.align_binaryopcalls!Method
align_binaryopcalls!(fst::FST, op_idxs::Vector{Int})

Aligns binary operator expressions.

Additionally handles the case where a keyword such as const is used prior to the binary op call.

source
JuliaFormatter.binaryop_to_whereop!Method
binaryop_to_whereop(fst::FST, s::State)

Handles the case of a function def defined as:

foo(a::A)::R where A = body

In this case instead of it being parsed as (1):

Binary
- Where
- OP
- RHS

It's parsed as (2):

Binary
- Binary
- LHS
- OP
- Where
- R
- ...
- OP
- RHS

(1) is preferrable since it's the same parsed result as:

foo(a::A) where A = body

This transformation converts (2) to (1).

ref https://github.com/julia-vscode/CSTParser.jl/issues/93

source
JuliaFormatter.eq_to_in_normalization!Method
eq_to_in_normalization!(fst::FST, always_for_in::Bool)

Transforms

for i = iter body end

=>

for i in iter body end

AND

for i in 1:10 body end

=>

for i = 1:10 body end
• https://github.com/domluna/JuliaFormatter.jl/issues/34
source
JuliaFormatter.formatMethod
format(
paths; # a path or collection of paths
options...,
)::Bool

Recursively descend into files and directories, formatting any .jl files by calling format_file on them.

See format_file and format_text for a description of the options.

This function will look for .JuliaFormatter.toml in the location of the file being formatted, and searching up the file tree until a config file is (or isn't) found. When found, the configurations in the file will overwrite the given options. See Configuration File for more details.

Output

Returns a boolean indicating whether the file was already formatted (true) or not (false).

source
JuliaFormatter.format_fileMethod
format_file(
filename::AbstractString;
overwrite::Bool = true,
verbose::Bool = false,
format_markdown::Bool = false,
format_options...,
)::Bool

Formats the contents of filename assuming it's a .jl or .md file.

File Options

overwrite

default: true

If true the file will be reformatted in place, overwriting the existing file; if it is false, the formatted version of foo.jl will not be written anywhere.

verbose

default: false

If true details related to formatting the file will be printed to stdout.

format_markdown

default: false

If true, Markdown files are also formatted. Julia code blocks will be formatted in addition to the Markdown being normalized.

Formatting Options

See format_text for description of formatting options.

Output

Returns a boolean indicating whether the file was already formatted (true) or not (false).

source
JuliaFormatter.format_textMethod
format_text(
text::AbstractString;
style::AbstractStyle = DefaultStyle(),
indent::Int = 4,
margin::Int = 92,
always_for_in::Bool = false,
whitespace_typedefs::Bool = false,
whitespace_ops_in_indices::Bool = false,
remove_extra_newlines::Bool = false,
import_to_using::Bool = false,
pipe_to_function_call::Bool = false,
short_to_long_function_def::Bool = false,
always_use_return::Bool = false,
whitespace_in_kwargs::Bool = true,
annotate_untyped_fields_with_any::Bool = true,
format_docstrings::Bool = false,
align_struct_field::Bool = false,
align_conditional::Bool = false,
align_assignment::Bool = false,
align_pair_arrow::Bool = false,
conditional_to_if = false,
normalize_line_endings = "auto",
align_matrix::Bool = false,
trailing_comma::Bool = false,
)::String

Formats a Julia source passed in as a string, returning the formatted code as another string.

Formatting Options

indent

default: 4

The number of spaces used for an indentation.

margin

default: 92

The maximum length of a line. Code exceeding this margin will be formatted across multiple lines.

always_for_in

default: false

If true, = is always replaced with in if part of a for loop condition. For example, for i = 1:10 will be transformed to for i in 1:10.

whitespace_typedefs

default: false

If true, whitespace is added for type definitions. Make this true if you prefer Union{A <: B, C} to Union{A<:B,C}.

whitespace_ops_in_indices

default: false

If true, whitespace is added for binary operations in indices. Make this true if you prefer arr[a + b] to arr[a+b]. Additionally, if there's a colon : involved, parenthesis will be added to the LHS and RHS.

Example: arr[(i1 + i2):(i3 + i4)] instead of arr[i1+i2:i3+i4].

remove_extra_newlines

default: false

If true, superflous newlines will be removed. For example:

module M

a = 1

function foo()

return nothing

end

b = 2

end

is rewritten as

module M

a = 1

function foo()
return nothing
end

b = 2

end

Modules are the only type of code block allowed to keep a single newline prior to the intial or after the final piece of code.

import_to_using

default: false

If true, import expressions are rewritten to using expressions in the following cases:

import A

import A, B, C

is rewritten to:

using A: A

using A: A
using B: B
using C: C

Exceptions:

If as is found in the import expression. using CANNOT be used in this context. The following example will NOT BE rewritten.

import Base.Threads as th

If import is used in the following context it is NOT rewritten. This may change in a future patch.

@everywhere import A, B

pipe_to_function_call

default: false

If true, x |> f is rewritten to f(x).

short_to_long_function_def

default: false

Transforms a short function definition

f(arg1, arg2) = body

to a long function definition

function f(arg2, arg2)
body
end

always_use_return

default: false

If true, return will be prepended to the last expression where applicable in function definitions, macro definitions, and do blocks.

Example:

function foo()
expr1
expr2
end

to

function foo()
expr1
return expr2
end

whitespace_in_kwargs

default: true

If true, = in keyword arguments will be surrounded by whitespace.

f(; a=4)

to

f(; a = 4)

An exception to this is if the LHS ends with "!" then even if whitespace_in_kwargs is false, = will still be surrounded by whitespace. The logic behind this intervention being on the following parse the ! will be treated as part of =, as in a "not equal" binary operation. This would change the semantics of the code and is therefore disallowed.

annotate_untyped_fields_with_any

default: true

Annotates fields in a type definitions with ::Any if no type annotation is provided:

struct A
arg1
end

to

struct A
arg1::Any
end

format_docstrings

default: false

Format code docstrings with the same options used for the code source.

Markdown is formatted with CommonMark alongside Julia code.

align_*

default: false

See Custom Alignment documentation.

conditional_to_if

default: false

If the conditional E ? A : B exceeds the maximum margin converts it into the equivalent if block:

if E
A
else
B
end

normalize_line_endings

default: "auto"

One of "unix" (normalize all to ), "windows" (normalize all to ), "auto" (automatically choose based on which line ending is more common in the file).

trailing_comma

default: true

One of true, false, or nothing.

Trailing commas are added after the final argument when nesting occurs and the closing punctuation appears on the next line.

For example when the following is nested (assuming DefaultStyle):

funccall(arg1, arg2, arg3)

it turns into:

funccall(
arg1,
arg2,
arg3, # trailing comma added after arg3 (final arugment) !!!
)
• When set to true, the trailing comma is always added during nesting.
• When set to false, the trailing comma is always removed during nesting.
• When set to nothing, the trailing comma appears as it does in the original source.

join_lines_based_on_source

default: false

When true lines are joined as they appear in the original source file.

function foo(arg1,
arg2, arg3
)
body
end

When false and the maximum margin is > than the length of "function foo(arg1, arg2, arg3)" this is formatted to

function foo(arg1, arg2, arg3)
body
end

When true, arg1 and arg2, arg3 will remain on separate lines even if they can fit on the same line since it's within maximum margin. The indentation is dependent on the style.

function foo(arg1,
arg2, arg3,
)
end

There are exceptions to this:

if a body1 elseif b body2 else body3 end

will be formatted to the following, even if this option is set to true:

if a
body1
elseif b
body2
else
body3
end
Warning

The maximum margin still applies even when this option is set to true.

indent_submodule

default: false

When set to true, submodule(s) appearing in the same file will be indented.

module A
a = 1

module B
b = 2
module C
c = 3
end
end

d = 4

end

will be formatted to:

module A
a = 1

module B
b = 2
module C
c = 3
end
end

d = 4

end
source
JuliaFormatter.is_iterable_argMethod

Returns whether fst can be an iterable argument. For example in the case of a function call, which is of type Call:

(a, b, c; k1=v1)

This would return true for a, b, c and k1=v1 and false for all other nodes.

source
JuliaFormatter.is_standalone_shortcircuitMethod
is_standalone_shortcircuit(cst::CSTParser.EXPR)

Returns true if the cst is a short-circuit expression (uses &&, ||) and is standalone, meaning it's not directly associated with another statement or expression.

Examples

# this IS a standalone short-circuit
a && b

# this IS NOT a standalone short-circuit
if a && b
end

# this IS NOT a standalone short-circuit
var = a && b

# this IS NOT a standalone short-circuit
@macro a && b

# operation inside parenthesis IS NOT a standalone short-circuit
# operation outside parenthesis IS a standalone short-circuit
(a && b) && c
source
JuliaFormatter.length_toMethod
length_to(x::FST, ntyps; start::Int = 1)

Returns the length to any node type in ntyps based off the start index.

source
JuliaFormatter.move_at_sign_to_the_endMethod
move_at_sign_to_the_end(fst::FST, s::State)

NOTE: Assumes fst is the caller name of a macrocall such as @macro or Module.@macro.

Moves @ to the last indentifier.

Example:

@Module.macro

to

Module.@macro
source
JuliaFormatter.nest_if_over_margin!Method
nest_if_over_margin!(
style,
fst::FST,
s::State,
idx::Int;
stop_idx::Union{Int,Nothing} = nothing,
)::Bool

Converts the node at idx to a NEWLINE if the current margin plus the additional margin from fst[idx:stop_idx-1] is greater than the allowed margin.

If stop_idx == nothing the range is fst[idx:end].

Returns whether nesting occurred.

source
JuliaFormatter.p_macrostr_identifierMethod

This is a special prettifier to handle the case of string macros. As such it is not part of pretty.

format"hello"

The above "format" identifier is parsed by CSTParser as if the text is "@format_str". This creates problems when we format without intervention:

1. "@format_str" is printed instead of "format"
2. The state offset is incorrect since the length of "@format_str" is greater than "format"
source
JuliaFormatter.parent_isMethod

Returns whether the first unignored parent of cst matches the criteria determined by valid, which is a function that returns a boolean. ignore can be used to ignore certain parent nodes if desired, also a function which returns a boolean.

source
JuliaFormatter.prepend_return!Method
prepend_return!(fst::FST, s::State)

Prepends return to the last expression of a block if applicable.

function foo()
a = 2 * 3
a / 3
end

to

function foo()
a = 2 * 3
return a / 3
end
source
JuliaFormatter.separate_kwargs_with_semicolon!Method
separate_kwargs_with_semicolon!(fst::FST)

Ensures keyword arguments are separated by a ";".

Examples

Replace "," with ";".

a = f(x, y = 3)

->

a = f(x; y = 3)

Move ";" to the prior to the first positional argument.

a = f(x = 1; y = 2)

->

a = f(; x = 1, y = 2)
source
JuliaFormatter.short_to_long_function_def!Method
short_to_long_function_def!(fst::FST, s::State)

Transforms a short function definition

f(arg1, arg2) = body

to a long function definition

function f(arg2, arg2)
body
end
source
JuliaFormatter.walkMethod
walk(f, fst::FST, s::State)

Walks fst calling f on each node.

In situations where descending further into a subtree is not desirable f should return a value other than nothing.

source