API Documentation
JuliaFormatter.AlignGroup — Type
AlignGroupGroup of FST node indices and required metadata to potentially align them.
node_inds. Indices of FST nodes affected by alignment.nodes. FST nodes affected by alignment.line_offsets. Display 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.
JuliaFormatter.DefaultStyle — Type
DefaultStyleThe default formatting style. See the Style section of the documentation for more details.
See also: BlueStyle, YASStyle, SciMLStyle, MinimalStyle
JuliaFormatter.FST — Type
Formatted Syntax Tree
JuliaFormatter.MinimalStyle — Type
MinimalStyle()JuliaFormatter.add_node! — Method
add_node!(
t::FST,
n::FST,
s::State;
join_lines::Bool = false,
max_padding::Int = -1,
override_join_lines_based_on_source::Bool = false,
)Appends n to t.
join_linesiffalsea NEWLINE node will be added andnwill appear on the next line, otherwise it will appear on the same line as the previous node (when printing).max_padding>= 0 indicates margin oftshould be based on whether the margin ofn+max_paddingis greater than the current margin oft. Otherwise the marginnwill be added tot.override_join_lines_based_on_sourceis only used whenjoin_lines_based_on_sourceoption istrue. In whichnis added totas ifjoin_lines_based_on_sourcewas false.
JuliaFormatter.align_binaryopcalls! — Method
align_binaryopcalls!(doc::Document, fst::FST, op_inds::Vector{Int})Aligns binary operator expressions.
Additionally handles the case where a keyword such as const is used prior to the binary op call. doc is used to compare source locations in display columns rather than raw source offsets.
JuliaFormatter.align_conditional! — Method
align_conditional!(doc::Document, fst::FST)Aligns a conditional expression.
doc supplies the original source text so ? and : alignment is computed using display columns.
JuliaFormatter.align_fst! — Method
align_fst!(fst::FST, doc::Document, opts::Options)Walk fst and apply the alignment passes enabled by opts.
doc is the original source document and is used to translate parser line offsets into display columns before padding is adjusted. This keeps alignment stable for source text containing combining and other zero-width characters.
JuliaFormatter.align_matrix! — Method
align_matrix!(doc::Document, fst::FST)Adjust whitespace between matrix elements so it matches the original source layout.
doc is used to recover the source display columns for each element, which avoids overpadding when the source contains zero-width characters.
JuliaFormatter.align_struct! — Method
align_struct!(doc::Document, fst::FST)Aligns struct fields.
doc supplies the original source text so field and type operator columns can be measured using display width.
JuliaFormatter.annotate_typefields_with_any! — Method
annotate_typefields_with_any!(fst::FST, s::State)Annotates fields in a type definitions with ::Any if no type annotation is provided.
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 = bodyIn this case instead of it being parsed as (1):
Binary
- Where
- OP
- RHSIt'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 = bodyThis transformation converts (2) to (1).
JuliaFormatter.eq_to_in_normalization! — Method
eq_to_in_normalization!(fst::FST, always_for_in::Bool, for_in_replacement::String)
eq_to_in_normalization!(fst::FST, always_for_in::Nothing, for_in_replacement::String)Transforms
for i = iter body end
=>
for i in iter body endAND
for i in 1:10 body end
=>
for i = 1:10 body endalways_for_in=nothing disables this normalization behavior.
JuliaFormatter.find_optimal_nest_placeholders — Method
Finds the optimal placeholders to turn into a newlines such that the length of the arguments on each line is as close as possible while following margin constraints.
JuliaFormatter.first_nonws_leaf_and_offset — Function
first_nonws_leaf_and_offset(
node::JuliaSyntax.GreenNode,
)::Union{Nothing,Tuple{JuliaSyntax.GreenNode,Int}Return the first non-whitespace leaf node in node plus its offset from the beginning of node, or nothing if there are no non-whitespace leaves.
JuliaFormatter.flatten_binaryopcall — Method
Flattens a binary operation call tree if the operation repeats 2 or more times. "a && b && c" will be transformed while "a && b" will not.
JuliaFormatter.format — Method
format(path, style::AbstractStyle; options...)::BoolJuliaFormatter.format — Method
format(
paths; # a path or collection of paths
options...,
)::BoolRecursively descend into files and directories, formatting any .jl, .md, .jmd, or .qmd files.
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).
JuliaFormatter.format — Method
format(mod::Module, args...; options...)JuliaFormatter.format_file — Method
format_file(
filename::AbstractString;
overwrite::Bool = true,
verbose::Bool = false,
format_markdown::Bool = false,
format_options...,
)::BoolFormats the contents of filename assuming it's a .jl, .md, .jmd or .qmd file.
See File Options for details on available options.
Output
Returns a boolean indicating whether the file was already formatted (true) or not (false).
JuliaFormatter.format_md — Method
format_md(text::AbstractString; style::AbstractStyle = DefaultStyle(), kwargs...)Normalizes the Markdown source and formats Julia code blocks.
See format_text for description of formatting options.
JuliaFormatter.format_text — Method
format_text(
text::AbstractString;
style::AbstractStyle = DefaultStyle(),
indent::Int = 4,
margin::Int = 92,
options...,
)::StringFormats a Julia source passed in as a string, returning the formatted code as another string.
See Formatting Options for details on available options.
JuliaFormatter.has_delimiters — Method
has_delimiters(cst::JuliaSyntax.GreenNode)cst is assumed to be a single child node. Returns true if the node is of the syntactic form {...}, [...], or (...).
JuliaFormatter.is_iterable_arg — Method
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.
JuliaFormatter.length_to — Method
length_to(x::FST, ntyps; start::Int = 1)Returns the length to any node type in ntyps based off the start index.
JuliaFormatter.long_to_short_function_def! — Method
long_to_short_function_def!(fst::FST, s::State)Transforms a long function definition
function f(arg2, arg2)
body
endto a short function definition
f(arg1, arg2) = bodyJuliaFormatter.move_at_sign_to_the_end — Method
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 identifier.
Example:
@Module.macroto
Module.@macroJuliaFormatter.nest_if_over_margin! — Method
nest_if_over_margin!(
style,
fst::FST,
s::State,
idx::Int;
stop_idx::Union{Int,Nothing} = nothing,
)::BoolConverts 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.
JuliaFormatter.p_pipe_to_call — Method
p_pipe_to_callTake a CST of the form x |> y or x .|> y, but return a FST with the equivalent function call y(x) or y.(x) instead.
Note that this function is only called for certain pipe-applications. See the call site in p_binaryopcall for details.
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
endto
function foo()
a = 2 * 3
return a / 3
endJuliaFormatter.remove_superfluous_whitespace! — Method
remove_superfluous_whitespace!(fst::FST)Soft deletes WHITESPACE or PLACEHOLDER that's directly followed by a NEWLINE or INLINECOMMENT node.
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)JuliaFormatter.short_to_long_function_def! — Method
short_to_long_function_def!(fst::FST, s::State)Transforms a short function definition
f(arg1, arg2) = bodyto a long function definition
function f(arg2, arg2)
body
endJuliaFormatter.source_begins_with_op_needing_parens — Method
sourcebeginswithopneeding_parens(s, cst, offset)
Check whether the first token of cst is an operator. Used in p_kw: if the value on the rhs of kwarg=value begins with an operator, then we parenthesise value to avoid ambiguity.
Note that the behaviour of this differs from unary_info(cst): for example, unary_info(cst) does not pick up expressions such as >=(1), which is interpreted as a function call, not an application of a unary operator. However, these are exactly the sort of things that we want to parenthesise in p_kw – hence this function.
JuliaFormatter.source_display_line_offset — Method
source_display_line_offset(doc::Document, line::Int, line_offset::Int) -> IntConvert a 1-based source line offset into a 1-based display column for line in doc.
line_offset follows the offsets recorded in the parsed source and therefore advances through the original text representation. Alignment, however, needs display width semantics so that combining marks and other zero-width codepoints do not consume extra padding. This helper measures the source line prefix with textwidth and returns the corresponding display column.
JuliaFormatter.source_op_kind_from_offset — Method
source_op_kind_from_offset(s, cst, offset)::Union{Nothing,JuliaSyntax.Kind}Return the operator kind of cst, using the source text at offset if necessary to help determine this. If cst is not an operator, returns nothing.
Note that this function may still return a K"Identifier"! This is because Julia allows some weird postfix operators. See the comments in the function for more info.
The check against the source is needed because JuliaSyntax v1 can encode source operators as Identifier leaves in call forms. For example:
julia> JuliaSyntax.parseall(JuliaSyntax.GreenNode, "+y")
1:2 │[toplevel]
1:2 │ [call]
1:1 │ Identifier ✔
2:2 │ Identifier ✔See https://github.com/JuliaLang/JuliaSyntax.jl/issues/548 for more information.
JuliaFormatter.unary_info — Method
unary_info(x::JuliaSyntax.GreenNode)::Union{Bool,Nothing}Returns:
trueifxis a prefix unary operator application, such as+xor<:xfalseifxis a postfix unary operator application, such asx'orx...;nothingifxis not an application of a unary operator.
JuliaFormatter.walk — Method
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.
JuliaFormatter.Internal.format_to_stage — Function
JuliaFormatter.Internal.format_to_stage(
stage::Symbol,
text::AbstractString,
[style=DefaultStyle(),]
options...
)Run formatting on a given string up until a certain stage, and return the output of that stage.
Available stages:
:gnor:cst: the output of the JuliaSyntax parser, which is aJuliaSyntax.GreenNode. Note that directly callingJuliaSyntax.parseallwill yield atoplevelnode with the actual tree of interest as its only child. This function will directly return the child.:fst: the output of prettification.:nest: the nested FST.
:out: the string output of the formatter.:print: the string output but printed. Saves you having to wrap it inprint().
For a utility that is meant to be convenient to access, typing the full qualified name can be a bit of a hassle! If you are using this function a lot, you may want to use BasicAutoloads.jl to automatically import it, and possibly even with a shorter name. For example, you can add something like this to your ~/.julia/config/startup.jl:
if isinteractive()
import BasicAutoloads
BasicAutoloads.register_autoloads([
["fs"] => :(using JuliaFormatter.Internal: format_to_stage as fs),
])
endand then just call fs(:gn, "1 + 2") from the REPL without having to import it.