### Install JuliaFormatter.jl Source: https://domluna.github.io/JuliaFormatter.jl/stable Use the Julia package manager to add JuliaFormatter.jl to your environment. ```julia ] add JuliaFormatter ``` -------------------------------- ### Install JuliaFormatter CLI Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Install JuliaFormatter using Julia's package manager to make the `jlfmt` command available in your PATH. ```julia pkg> app add JuliaFormatter ``` -------------------------------- ### Configuration File Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/blue_style Shows how to configure the BlueStyle formatting using a `.JuliaFormatter.toml` file, including setting the style to 'blue' or customizing specific options. ```APIDOC ## Configuration File Example Set the style to 'blue' in `.JuliaFormatter.toml`: ```toml style = "blue" ``` Use 'blue' style but override a specific setting: ```toml style = "blue" remove_extra_newlines = false ``` ``` -------------------------------- ### Align Assignment Operators Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/custom_alignment Provides examples of various assignment and definition alignments using `align_assignment`. ```julia const UTF8PROC_STABLE = (1 << 1) const UTF8PROC_COMPAT = (1 << 2) const UTF8PROC_COMPOSE = (1 << 3) const UTF8PROC_DECOMPOSE = (1 << 4) const UTF8PROC_IGNORE = (1 << 5) const UTF8PROC_REJECTNA = (1 << 6) const UTF8PROC_NLF2LS = (1 << 7) const UTF8PROC_NLF2PS = (1 << 8) const UTF8PROC_NLF2LF = (UTF8PROC_NLF2LS | UTF8PROC_NLF2PS) const UTF8PROC_STRIPCC = (1 << 9) const UTF8PROC_CASEFOLD = (1 << 10) const UTF8PROC_CHARBOUND = (1 << 11) const UTF8PROC_LUMP = (1 << 12) const UTF8PROC_STRIP = (1 << 13) vcat(X::T...) where {T} = T[X[i] for i = 1:length(X)] vcat(X::T...) where {T<:Number} = T[X[i] for i = 1:length(X)] hcat(X::T...) where {T} = T[X[j] for i = 1:1, j = 1:length(X)] hcat(X::T...) where {T<:Number} = T[X[j] for i = 1:1, j = 1:length(X)] a = 1 bc = 2 long_variable = 1 other_var = 2 ``` -------------------------------- ### FST Generation Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/how_it_works Demonstrates how syntactically different Julia code can produce the same FST, highlighting whitespace irrelevance during this stage. ```julia # p1.jl a = foo(a, b, c,d) ``` ```julia # p2.jl a = foo(a, b, c,d) ``` ```julia # fst output a = foo(a, b, c, d) ``` -------------------------------- ### YAS Style Argument Alignment Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/yas_style Demonstrates how YASStyle aligns arguments to appear just after the opening parenthesis, bracket, or brace. ```julia function_call(arg1, arg2) ``` -------------------------------- ### Align Conditional Expressions Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/custom_alignment Demonstrates alignment of conditional expressions using `?` and `:`, showing behavior with different styles and margin settings. ```julia # This will remain like this if using YASStyle index = zeros(n <= typemax(Int8) ? Int8 : n <= typemax(Int16) ? Int16 : n <= typemax(Int32) ? Int32 : Int64, n) # Using DefaultStyle index = zeros( n <= typemax(Int8) ? Int8 : n <= typemax(Int16) ? Int16 : n <= typemax(Int32) ? Int32 : Int64, n, ) # Note even if the maximum margin is set to 1, the alignment remains intact index = zeros( n <= typemax(Int8) ? Int8 : n <= typemax(Int16) ? Int16 : n <= typemax(Int32) ? Int32 : Int64, n, ) ``` -------------------------------- ### Align Struct Field Definitions Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/custom_alignment Shows alignment of struct fields to `::` or `=` operators, demonstrating `align_struct_field`. ```julia Base.@kwdef struct Options 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_fields::Bool = false # no custom whitespace so this block is not aligned another_field1::BlahBlahBlah = 10 field2::Foo = 10 # no custom whitespace but single line blocks are not aligned # either way Options() = new() end mutable struct Foo a :: T longfieldname :: T end ``` -------------------------------- ### Nesting Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/how_it_works Shows how the FST is nested to meet margin constraints, converting PLACEHOLDER nodes to NEWLINE nodes to break long lines, such as in function calls. ```julia begin foo = funccall(argument1, argument2, ..., argument120) # way over margin limit !!! end begin foo = funccall( argument1, argument2, ..., argument120 ) # way over margin limit !!! end ``` -------------------------------- ### Ambiguous Alignment Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/custom_alignment Shows a case where the formatter will not apply custom alignment due to uniform spacing, reverting to normal formatting behavior. ```julia const variable1 = 1 const variable2 = 2 const var3 = 3 const var4 = 4 const var5 = 5 ``` -------------------------------- ### FST Transformation Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/how_it_works Illustrates how a typical FST represents code structure, with expressions on single lines if possible and multi-line structures like 'try' blocks formatted appropriately. ```julia # original source try a1;a2 catch e b1;b2 finally c1;c2 end -> # printed FST try a1 a2 catch e b1 b2 finally c1 c2 end ``` -------------------------------- ### Invoke JuliaFormatter Directly Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Alternatively, invoke the `jlfmt` command directly using `julia -m` without prior installation. ```julia julia -m JuliaFormatter [] ... ``` -------------------------------- ### YAS Style Nesting Behavior Example Source: https://domluna.github.io/JuliaFormatter.jl/stable/yas_style Illustrates YASStyle's nesting behavior where line breaks for arguments only occur if the next argument exceeds the maximum line limit. ```julia function_call(arg1, arg2, arg3) ``` -------------------------------- ### Example of Custom Assignment Alignment Source: https://domluna.github.io/JuliaFormatter.jl/stable/custom_alignment Demonstrates how JuliaFormatter aligns assignment operators when `align_assignment` is enabled, even with varying whitespace. This behavior overrides nesting. ```julia const variable1 = 1 const var2 = 2 const var3 = 3 const var4 = 4 const var5 = 5 ``` ```julia const variable1 = 1 const var2 = 2 const var3 = 3 const var4 = 4 const var5 = 5 ``` -------------------------------- ### length_to Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Calculates the length to a specified node type within a given structure, starting from a specified index. ```APIDOC ## length_to ### Description Returns the length to any node type in `ntyps` based off the `start` index. ### Method ```julia length_to(x::FST, ntyps; start::Int = 1) ``` ### Parameters - `x` (FST) - The structure to traverse. - `ntyps` - The target node types. - `start` (Int, optional) - The starting index. Defaults to `1`. ``` -------------------------------- ### Calculate length to a node type Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Returns the length from a starting index to any node type specified in `ntyps`. ```Julia length_to(x::FST, ntyps; start::Int = 1) ``` -------------------------------- ### Separate keyword arguments with semicolon Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Ensures keyword arguments are separated by a semicolon (`;`). Includes examples of replacing commas with semicolons and moving semicolons. ```Julia separate_kwargs_with_semicolon!(fst::FST) ``` ```Julia a = f(x, y = 3) -> a = f(x; y = 3) ``` ```Julia a = f(x = 1; y = 2) -> a = f(; x = 1, y = 2) ``` -------------------------------- ### Surround type parameters with curly brackets Source: https://domluna.github.io/JuliaFormatter.jl/stable When true, surrounds type parameters with curly brackets if they are not already present, for example in `where` clauses. ```julia function func(...) where TPARAM end -> function func(...) where {TPARAM} end ``` -------------------------------- ### Instantiate BlueStyle Source: https://domluna.github.io/JuliaFormatter.jl/stable/blue_style Use this to apply the BlueStyle formatting. It can be configured with specific options. ```julia BlueStyle() ``` -------------------------------- ### Run jlfmt with Help Option Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Displays the help message for `jlfmt`, listing all available options and their descriptions. This is useful for understanding the full range of customization available. ```bash jlfmt --help ``` -------------------------------- ### Direct Usage of BlueStyle Source: https://domluna.github.io/JuliaFormatter.jl/stable/blue_style Demonstrates how to apply the BlueStyle formatting to a file directly using the `format` function, with an option to override specific settings. ```APIDOC ## Direct Usage Apply `BlueStyle` to a file: ```julia format("file.jl", BlueStyle()) ``` Apply `BlueStyle` with a specific setting overridden: ```julia format("file.jl", BlueStyle(), remove_extra_newlines=false) ``` ``` -------------------------------- ### Use Specific Style Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Formats a file using a predefined style configuration. Replace 'blue' with any available style name. ```bash jlfmt --style=blue src/file.jl ``` -------------------------------- ### Instantiate SciMLStyle Source: https://domluna.github.io/JuliaFormatter.jl/stable/sciml_style Use this to create an instance of the SciMLStyle for formatting. ```julia SciMLStyle() ``` -------------------------------- ### Format Stdin with Configuration Directory Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli When formatting from stdin, specify a directory for configuration file lookup using `--config-dir`. This allows project-specific configurations to be applied. ```bash # Format stdin using config from ./src directory echo 'f(x,y)=x+y' | jlfmt --config-dir=./src ``` ```bash # Useful in editor integrations to respect project config cat file.jl | jlfmt --config-dir=$(dirname file.jl) ``` -------------------------------- ### Format from Stdin with Project Config Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Formats code piped from standard input, applying formatting rules defined in a project configuration file located in the specified directory. ```bash echo 'f(x,y)=x+y' | jlfmt --config-dir=./src ``` -------------------------------- ### Apply BlueStyle formatting to a file Source: https://domluna.github.io/JuliaFormatter.jl/stable/blue_style Directly use the `format` function with `BlueStyle()` to format a specific file. Custom options can be passed as keyword arguments. ```julia format("file.jl", BlueStyle()) ``` ```julia format("file.jl", BlueStyle(), remove_extra_newlines=false) ``` -------------------------------- ### Preview Formatted Output Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Use `jlfmt` to preview how a Julia file would be formatted without making any changes. ```bash jlfmt src/file.jl ``` -------------------------------- ### Instantiate MinimalStyle Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Creates an instance of the MinimalStyle, a predefined formatting style. ```julia MinimalStyle() ``` -------------------------------- ### Override Configuration File Settings Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Command-line options take precedence over settings in `.JuliaFormatter.toml` files. Use this to enforce specific formatting rules. ```bash # Use indent=2 even if config file specifies indent=4 jlfmt --indent=2 src/file.jl ``` -------------------------------- ### Show Diff Without Modifying Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Display the differences between the current file and its formatted version without altering the original file. ```bash jlfmt --diff src/file.jl ``` -------------------------------- ### Basic Configuration in .JuliaFormatter.toml Source: https://domluna.github.io/JuliaFormatter.jl/stable/config Specify indentation and margin for files within a directory. This configuration is applied to files in the same directory and its subdirectories. ```toml indent = 2 margin = 100 ``` -------------------------------- ### Prioritize Configuration File Settings Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Use `--prioritize-config-file` to ensure settings from `.JuliaFormatter.toml` take precedence over command-line options. This is useful for maintaining project-wide consistency, especially in editor integrations. ```bash jlfmt --prioritize-config-file --indent=2 src/file.jl ``` -------------------------------- ### format(mod::Module, args...; options...) Source: https://domluna.github.io/JuliaFormatter.jl/stable/api This is a general format function that likely takes a module and arguments with options to perform formatting. Specific usage details are not provided in the source. ```APIDOC ## format(mod::Module, args...; options...) ### Description General formatting function that accepts a module, arguments, and options. ### Parameters - `mod` (Module) - The module to format. - `args` (...) - Additional arguments for formatting. - `options` (; ...) - Formatting options. ### Note This is a high-level function and specific usage examples or detailed parameter descriptions are not available in the provided source. ``` -------------------------------- ### Check Directory with Threads Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Checks formatting for all files in a directory using multiple threads for faster processing. The `--` separates options from file paths. ```bash jlfmt --threads=4 -- --check src/ ``` -------------------------------- ### YASStyle Constructor Source: https://domluna.github.io/JuliaFormatter.jl/stable/yas_style Instantiate the YASStyle with default settings. This style is based on YASGuide and offers specific defaults for options like `always_for_in`, `always_use_return`, and `remove_extra_newlines`. ```julia YASStyle() ``` -------------------------------- ### Format Multiple Paths Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Recursively formats files in specified paths, respecting configuration files and applying various formatting options. Returns a boolean indicating if any file was modified. ```julia format( paths; # a path or collection of paths options..., )::Bool ``` -------------------------------- ### Format from Stdin (Pipe) Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Formats code piped from standard input. Useful for quick checks or integrating with other tools. ```bash echo 'f(x,y)=x+y' | jlfmt ``` -------------------------------- ### Ignoring Files and Directories Source: https://domluna.github.io/JuliaFormatter.jl/stable/config Define patterns for files and directories to be ignored by the formatter. This prevents formatting for specified entries. ```toml ignore = ["file.jl", "directory", "file_*.jl"] ``` -------------------------------- ### Format File by Path Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Formats a single file specified by its path, applying a given style and options. Returns a boolean indicating if the file was modified. ```julia format(path, style::AbstractStyle; options...)::Bool ``` -------------------------------- ### Format file with SciMLStyle Source: https://domluna.github.io/JuliaFormatter.jl/stable/sciml_style Directly apply the SciMLStyle to a file using the format function. You can also override specific settings. ```julia format("file.jl", SciMLStyle()) ``` ```julia format("file.jl", SciMLStyle(), remove_extra_newlines=false) ``` -------------------------------- ### Find Optimal Nesting Placeholders Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Identifies optimal locations within the FST to insert newlines, aiming to balance line lengths while respecting margin constraints. ```julia find_optimal_nest_placeholders ``` -------------------------------- ### walk Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Traverses the Abstract Syntax Tree (AST), applying a given function to each node. It allows for custom processing and can optionally prevent further traversal into subtrees. ```APIDOC ## walk ### Description 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`. Note This function mutates the State's (`s`) `line_offset`. If this is not desired you should save the value before calling this function and restore it after. ### Method ```julia walk(f, fst::FST, s::State) ``` ### Parameters - `f` - The function to apply to each node. - `fst` (FST) - The Abstract Syntax Tree node to start walking from. - `s` (State) - The current state of the formatter. ``` -------------------------------- ### Configure BlueStyle in .JuliaFormatter.toml Source: https://domluna.github.io/JuliaFormatter.jl/stable/blue_style Set the style to 'blue' in your .JuliaFormatter.toml file for project-wide formatting. You can override specific settings here. ```toml style = "blue" ``` ```toml style = "blue" remove_extra_newlines = false ``` -------------------------------- ### Format File with YASStyle Directly Source: https://domluna.github.io/JuliaFormatter.jl/stable/yas_style Format a specific file using the YASStyle directly in code. This method is useful for programmatic formatting. ```julia format("file.jl", YASStyle()) ``` -------------------------------- ### Show Diff with Custom Indentation Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Displays the differences (diff) that would be applied to a file if formatted, using a 2-space indentation. Does not modify the file. ```bash jlfmt --diff --indent=2 src/file.jl ``` -------------------------------- ### Format Files In-Place with Threads Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Format files in-place using multiple threads for faster processing. The `--` separator is used to distinguish `jlfmt` options from file paths. ```bash jlfmt --threads=6 -- --inplace -v src/ ``` -------------------------------- ### Setting a Non-Default Style Source: https://domluna.github.io/JuliaFormatter.jl/stable/config Use this to set a specific formatting style like 'yas' (YASStyle). Available styles include 'default', 'yas', 'blue', 'sciml', and 'minimal'. ```toml style = "yas" ``` -------------------------------- ### Turn Off and On Formatting Source: https://domluna.github.io/JuliaFormatter.jl/stable/skipping_formatting Use `#! format: off` to disable formatting from that point onwards and `#! format: on` to re-enable it. Ensure these directives are on their own lines with exact whitespace. ```julia #! format: off # Turns off formatting from this point onwards ... #! format: on # Turns formatting back on from this point onwards ``` -------------------------------- ### Format from Stdin (Explicit) Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Formats code from standard input, explicitly reading from stdin using '-'. Reads input from the specified file. ```bash jlfmt - < input.jl ``` -------------------------------- ### Rewrite Import to Using Expressions Source: https://domluna.github.io/JuliaFormatter.jl/stable When `import_to_using` is true, `import` expressions are rewritten to `using` expressions, with exceptions for `as` clauses and `@everywhere` contexts. ```julia import A import A, B, C ``` ```julia using A: A using A: A using B: B using C: C ``` ```julia import Base.Threads as th ``` ```julia @everywhere import A, B ``` -------------------------------- ### Format an Individual Julia File Source: https://domluna.github.io/JuliaFormatter.jl/stable Formats a single specified Julia file. Provide the file path as an argument. ```julia # Formats an individual file julia> format_file("foo.jl") ``` -------------------------------- ### Format Julia Code Recursively Source: https://domluna.github.io/JuliaFormatter.jl/stable Recursively formats all Julia files in the current directory. Ensure you are in the desired directory before running. ```julia julia> using JuliaFormatter # Recursively formats all Julia files in the current directory julia> format(".") ``` -------------------------------- ### Configure SciMLStyle in .JuliaFormatter.toml Source: https://domluna.github.io/JuliaFormatter.jl/stable/sciml_style Set the style to 'sciml' in your configuration file. You can override specific settings by adding them to the file. ```toml style = "sciml" ``` ```toml style = "sciml" remove_extra_newlines = false ``` -------------------------------- ### Format Single-Line Functions and Types Source: https://domluna.github.io/JuliaFormatter.jl/stable/style Functions, macros, structs without arguments, abstract types, and primitive types are formatted onto a single line. ```julia function foo end -> function foo end ``` ```julia abstract type AbstractFoo end -> abstract type AbstractFoo end ``` -------------------------------- ### prepend_return! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Adds a `return` statement to the last expression of a code block if it's deemed appropriate. ```APIDOC ## prepend_return! ### Description Prepends `return` to the last expression of a block if applicable. ```julia function foo() a = 2 * 3 a / 3 end ``` to ```julia function foo() a = 2 * 3 return a / 3 end ``` ### Method ```julia prepend_return!(fst::FST, s::State) ``` ### Parameters - `fst` (FST) - The Abstract Syntax Tree node representing the block. - `s` (State) - The current state of the formatter. ``` -------------------------------- ### Format a Julia file Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Formats the contents of a specified file. Returns true if the file was already formatted, false otherwise. Supports .jl, .md, .jmd, and .qmd files. ```Julia format_file( filename::AbstractString; overwrite::Bool = true, verbose::Bool = false, format_markdown::Bool = false, format_options..., )::Bool ``` -------------------------------- ### Walk the Abstract Syntax Tree Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Traverses the Abstract Syntax Tree (`fst`), applying a function `f` to each node. The traversal can be stopped by returning a non-`nothing` value from `f`. Mutates the `State`'s `line_offset`. ```Julia walk(f, fst::FST, s::State) ``` -------------------------------- ### format Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Formats Julia code files or directories based on specified styles and options, recursively processing files and respecting configuration files. ```APIDOC ## format - Method ### Description Recursively 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`). ### Method ```julia format( paths; # a path or collection of paths options..., )::Bool ``` ``` ```APIDOC ## format - Method ### Method ```julia format(path, style::AbstractStyle; options...)::Bool ``` ``` -------------------------------- ### Convert short-circuit expressions to if statements Source: https://domluna.github.io/JuliaFormatter.jl/stable Converts expressions using `||` or `&&` for conditional returns into equivalent `if` statements for potentially clearer control flow. ```julia function foo(a, b) a || return "bar" "hello" b && return "ooo" end BECOMES function foo(a, b) if !(a) return "bar" end "hello" if b return "ooo" else false end end ``` -------------------------------- ### format_file Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Formats the contents of a specified file. It supports Julia, Markdown, and Quarto files and can optionally overwrite the original file. ```APIDOC ## format_file ### Description Formats the contents of `filename` assuming it's a `.jl`, `.md`, `.jmd` or `.qmd` file. See File Options for details on available options. ### Method ```julia format_file( filename::AbstractString; overwrite::Bool = true, verbose::Bool = false, format_markdown::Bool = false, format_options..., )::Bool ``` ### Parameters - `filename` (AbstractString) - The path to the file to be formatted. - `overwrite` (Bool, optional) - Whether to overwrite the original file. Defaults to `true`. - `verbose` (Bool, optional) - If true, prints verbose output. Defaults to `false`. - `format_markdown` (Bool, optional) - Whether to format Markdown content. Defaults to `false`. - `format_options` (...) - Additional formatting options. ### Output Returns a boolean indicating whether the file was already formatted (`true`) or not (`false`). ``` -------------------------------- ### find_optimal_nest_placeholders Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Identifies optimal locations within nested structures to insert newlines, aiming for balanced line lengths while respecting margin constraints. ```APIDOC ## find_optimal_nest_placeholders - Method ### Description 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. ``` -------------------------------- ### Join lines based on source with join_lines_based_on_source Source: https://domluna.github.io/JuliaFormatter.jl/stable When true, lines are joined as they appear in the original source file, preserving original line breaks even if they could fit on one line. The maximum margin still applies. ```julia function foo(arg1, arg2, arg3 ) body end ``` ```julia function foo(arg1, arg2, arg3) body end ``` ```julia function foo(arg1, arg2, arg3, ) end ``` ```julia if a body1 elseif b body2 else body3 end ``` ```julia if a body1 elseif b body2 else body3 end ``` -------------------------------- ### Format Function Calls, Tuples, Arrays, and Braces Source: https://domluna.github.io/JuliaFormatter.jl/stable/style Code enclosed in parentheses, braces, or brackets, such as function calls, tuples, arrays, and struct definitions with arguments, are formatted onto a single line. ```julia f( a,b ,c ) -> f(a, b, c) ``` ```julia Foo{ a,b ,c } -> Foo{a,b,c} ``` -------------------------------- ### binaryop_to_whereop Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Transforms a specific nested Binary AST structure into a preferred 'where' clause structure for function definitions. ```APIDOC ## binaryop_to_whereop - Method ### Description 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 ### Method ```julia binaryop_to_whereop(fst::FST, s::State) ``` ``` -------------------------------- ### Format File In-Place Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Formats the specified Julia file (`src/file.jl`) and overwrites the original file with the formatted content. Use with caution as this modifies the source file directly. ```bash jlfmt --inplace src/file.jl ``` -------------------------------- ### short_to_long_function_def! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Transforms a short function definition into its long, multi-line equivalent. ```APIDOC ## short_to_long_function_def! ### Description Transforms a _short_ function definition ```julia f(arg1, arg2) = body ``` to a _long_ function definition ```julia function f(arg2, arg2) body end ``` ### Method ```julia short_to_long_function_def!(fst::FST, s::State) ``` ### Parameters - `fst` (FST) - The function definition node. - `s` (State) - The current state of the formatter. ``` -------------------------------- ### Combine Options with Stdin Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Combines multiple formatting options, such as `--always_for_in`, when formatting code piped from standard input. ```bash echo 'for i=1:10; end' | jlfmt --always_for_in ``` -------------------------------- ### Format Binary Operations Source: https://domluna.github.io/JuliaFormatter.jl/stable/style Binary calls are placed on a single line with whitespace separation, except for colon operations and indexing expressions. ```julia a+b -> a + b ``` ```julia a : a : c -> a:b:c ``` ```julia list[a + b] -> list[a+b] ``` -------------------------------- ### Format Directory Verbose Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Formats all files in a directory with verbose output enabled. Use `--inplace` to modify files directly. ```bash jlfmt --inplace --verbose src/ ``` -------------------------------- ### Control Code Formatting with Special Comments Source: https://domluna.github.io/JuliaFormatter.jl/stable Use `#! format: off` and `#! format: on` to disable and re-enable formatting for specific code blocks. This is useful for preserving manual formatting in certain sections. ```julia # this should be formatted a = f(aaa, bbb, ccc) # this should not be formatted #! format: off a = f(aaa, bbb,ccc) c = 102000 d = @foo 10 20 e = "what the foocho" #! format: on # this should be formatted a = f(aaa, bbb, ccc) # ok ``` -------------------------------- ### Prepend return to block expression Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Prepends the `return` keyword to the last expression of a block if it's applicable, ensuring the block returns a value. ```Julia prepend_return!(fst::FST, s::State) ``` -------------------------------- ### Annotate Type Fields with Any Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Annotates type fields with `::Any` if no type annotation is present in the FST. ```julia annotate_typefields_with_any!(fst::FST, s::State) ``` -------------------------------- ### YAS Style Variable Call Indentation Source: https://domluna.github.io/JuliaFormatter.jl/stable/yas_style Demonstrates the `variable_call_indent` option in YASStyle, showing how calls within data structures like Dict can be aligned. ```julia # Allowed with and without `Dict in variable_call_indent` Dict{Int,Int}(1 => 2, 3 => 4) # Allowed when `Dict in variable_call_indent`, but # will be changed to the first example when `Dict ∉ variable_call_indent`. Dict{Int,Int}( 1 => 2, 3 => 4) ``` -------------------------------- ### eq_to_in_normalization! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Normalizes `=` to `in` in `for` loops and vice-versa based on configuration, addressing specific formatting issues. ```APIDOC ## eq_to_in_normalization! - Method ### Description 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 ``` `always_for_in=nothing` disables this normalization behavior. * https://github.com/domluna/JuliaFormatter.jl/issues/34 ### Method ```julia 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) ``` ``` -------------------------------- ### Format Julia source code string Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Formats a Julia source code string and returns the formatted code as another string. Allows customization of style, indentation, and margin. ```Julia format_text( text::AbstractString; style::AbstractStyle = DefaultStyle(), indent::Int = 4, margin::Int = 92, options..., )::String ``` -------------------------------- ### format_md Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Normalizes and formats Markdown source, specifically targeting Julia code blocks within the Markdown. ```APIDOC ## format_md ### Description Normalizes the Markdown source and formats Julia code blocks. See `format_text` for description of formatting options. ### Method ```julia format_md(text::AbstractString; style::AbstractStyle = DefaultStyle(), kwargs...) ``` ### Parameters - `text` (AbstractString) - The Markdown text to format. - `style` (AbstractStyle, optional) - The styling to apply. Defaults to `DefaultStyle()`. - `kwargs` (...) - Additional keyword arguments for formatting. ``` -------------------------------- ### long_to_short_function_def! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Transforms a long function definition into its short, single-line equivalent. ```APIDOC ## long_to_short_function_def! ### Description Transforms a _long_ function definition ```julia function f(arg2, arg2) body end ``` to a _short_ function definition ```julia f(arg1, arg2) = body ``` ### Method ```julia long_to_short_function_def!(fst::FST, s::State) ``` ### Parameters - `fst` (FST) - The function definition node. - `s` (State) - The current state of the formatter. ``` -------------------------------- ### Format File with Customized YASStyle Directly Source: https://domluna.github.io/JuliaFormatter.jl/stable/yas_style Format a file using YASStyle and override specific options, like `remove_extra_newlines`, directly within the `format` function call. ```julia format("file.jl", YASStyle(), remove_extra_newlines=false) ``` -------------------------------- ### Format Julia Code from a String Source: https://domluna.github.io/JuliaFormatter.jl/stable Formats a Julia code string. This is useful for formatting code that is not yet saved to a file. ```julia # Formats a string (contents of a Julia file) julia> format_text(str) ``` -------------------------------- ### align_matrix! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Adjusts whitespace within matrix elements to match the original source file. ```APIDOC ## align_matrix! - Method ### Description Adjust whitespace in between matrix elements such that it's the same as the original source file. ``` -------------------------------- ### Define DefaultStyle Type Source: https://domluna.github.io/JuliaFormatter.jl/stable/api The default formatting style for Julia code. Refer to the Style section for more details. ```julia DefaultStyle ``` -------------------------------- ### format_text Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Formats a given Julia source code string and returns the formatted code as a new string. ```APIDOC ## format_text ### Description Formats a Julia source passed in as a string, returning the formatted code as another string. See Formatting Options for details on available options. ### Method ```julia format_text( text::AbstractString; style::AbstractStyle = DefaultStyle(), indent::Int = 4, margin::Int = 92, options..., )::String ``` ### Parameters - `text` (AbstractString) - The Julia source code string to format. - `style` (AbstractStyle, optional) - The styling to apply. Defaults to `DefaultStyle()`. - `indent` (Int, optional) - The indentation level. Defaults to `4`. - `margin` (Int, optional) - The maximum line width. Defaults to `92`. - `options` (...) - Additional formatting options. ### Output Returns the formatted Julia code as a String. ``` -------------------------------- ### Align Pair Arrows (`=>`) Source: https://domluna.github.io/JuliaFormatter.jl/stable/custom_alignment Use this option to align pair arrows (`=>`) in your code. This is useful for maintaining consistent alignment in dictionaries or other key-value structures. ```julia pages = [ "Introduction" => "index.md", "How It Works" => "how_it_works.md", "Code Style" => "style.md", "Skipping Formatting" => "skipping_formatting.md", "Syntax Transforms" => "transforms.md", "Custom Alignment" => "custom_alignment.md", "Custom Styles" => "custom_styles.md", "YAS Style" => "yas_style.md", "Configuration File" => "config.md", "API Reference" => "api.md", ] ``` -------------------------------- ### Check File Formatting Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Checks if a specific file is formatted according to JuliaFormatter rules. Does not modify the file. ```bash jlfmt --check src/file.jl ``` -------------------------------- ### Align Matrix Elements (`align_matrix=true`) Source: https://domluna.github.io/JuliaFormatter.jl/stable/custom_alignment Set `align_matrix` to `true` to preserve whitespace surrounding matrix elements as they appear in the original source. This differs from other alignment options as it does not attempt to auto-detect and adjust alignment. ```julia # Elements left-aligned in original source julia> s = """ a = [ 100 300 400 1 eee 40000 2 α b ]""" "a = [\n100 300 400\n1 eee 40000\n2 α b\n]" julia> format_text(s, align_matrix=true) |> print a = [ 100 300 400 1 eee 40000 2 α b ] # Elements right-aligned in original source julia> s = """ a = [ 100 300 400 1 ee 40000 2 a b ]""" "a = [\n100 300 400\n 1 ee 40000\n 2 a b\n]" julia> julia> format_text(s, align_matrix=true) |> print a = [ 100 300 400 1 ee 40000 2 a b ] ``` -------------------------------- ### Nest 'where' Clauses Source: https://domluna.github.io/JuliaFormatter.jl/stable/style With `where` clauses, the main expression is nested prior to the `where` part, and further nesting occurs within the clause if necessary. ```julia function f(arg1::A, key1 = val1; key2 = val2) where {A,B,C} body end -> function f( arg1::A, key1 = val1; key2 = val2, ) where {A,B,C} body end -> function f( arg1::A, key1 = val1; key2 = val2, ) where { A, B, C, } body end ``` -------------------------------- ### Check Formatting Verbose Source: https://domluna.github.io/JuliaFormatter.jl/stable/cli Check if files in a directory are already formatted. The verbose flag (`-v`) provides more detailed output. ```bash jlfmt --check -v src/ ``` -------------------------------- ### SciMLStyle yas_style_nesting option Source: https://domluna.github.io/JuliaFormatter.jl/stable/sciml_style Illustrates the effect of the `yas_style_nesting` option on function definition formatting. When false (default), arguments are indented based on line length. When true, it adopts YASStyle nesting rules for consistent indentation. ```julia # With `yas_style_nesting = false` function my_large_function(argument1, argument2, argument3, argument4, argument5, x, y, z) foo(x) + goo(y) end # With `yas_style_nesting = true` function my_large_function(argument1, argument2, argument3, argument4, argument5, x, y, z) foo(x) + goo(y) end ``` -------------------------------- ### Format line endings with normalize_line_endings Source: https://domluna.github.io/JuliaFormatter.jl/stable Normalizes line endings in a file. Use 'unix' to convert all to '\n', 'windows' to convert all to '\r\n', or 'auto' to detect the most common line ending. ```julia "auto" ``` -------------------------------- ### Use YAS style nesting for functions Source: https://domluna.github.io/JuliaFormatter.jl/stable When true, the SciMLStyle uses YASStyle nesting rules, which can lead to different indentation for function arguments. ```julia # With `yas_style_nesting = false` function my_large_function(argument1, argument2, argument3, argument4, argument5, x, y, z) foo(x) + goo(y) end # With `yas_style_nesting = true` function my_large_function(argument1, argument2, argument3, argument4, argument5, x, y, z) foo(x) + goo(y) end ``` -------------------------------- ### annotate_typefields_with_any! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Annotates fields in type definitions with `::Any` if no type annotation is present. ```APIDOC ## annotate_typefields_with_any! - Method ### Description Annotates fields in a type definitions with `::Any` if no type annotation is provided. ### Method ```julia annotate_typefields_with_any!(fst::FST, s::State) ``` ``` -------------------------------- ### Format Code Blocks and Struct Definitions Source: https://domluna.github.io/JuliaFormatter.jl/stable/style Blocks and their bodies are properly indented across multiple lines. Struct definitions with arguments are also formatted with indented fields. ```julia begin a b; c end -> begin a b c end ``` ```julia struct Foo{A, B} a::A b::B end -> struct Foo{A,B} a::A b::B end ``` -------------------------------- ### separate_kwargs_with_semicolon! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Ensures that keyword arguments in function calls and definitions are consistently separated by semicolons. ```APIDOC ## separate_kwargs_with_semicolon! ### Description Ensures keyword arguments are separated by a ";". **Examples** Replace "," with ";". ```julia a = f(x, y = 3) -> a = f(x; y = 3) ``` Move ";" to the prior to the first positional argument. ```julia a = f(x = 1; y = 2) -> a = f(; x = 1, y = 2) ``` ### Method ```julia separate_kwargs_with_semicolon!(fst::FST) ``` ### Parameters - `fst` (FST) - The Abstract Syntax Tree node representing the function call or definition. ``` -------------------------------- ### align_binaryopcalls! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Aligns binary operator expressions within an FST, also handling keywords like `const` preceding the operator. ```APIDOC ## align_binaryopcalls! - Method ### Description Aligns binary operator expressions. Additionally handles the case where a keyword such as `const` is used prior to the binary op call. ### Method ```julia align_binaryopcalls!(fst::FST, op_inds::Vector{Int}) ``` ``` -------------------------------- ### SciMLStyle variable_call_indent option Source: https://domluna.github.io/JuliaFormatter.jl/stable/sciml_style Demonstrates how the `variable_call_indent` option affects call formatting within the SciMLStyle. By default, it is an empty list, allowing calls to align with the opening parenthesis. ```julia # Allowed with and without `Dict in variable_call_indent` Dict{Int, Int}(1 => 2, 3 => 4) # Allowed when `Dict in variable_call_indent`, but # will be changed to the first example when `Dict ∉ variable_call_indent`. Dict{Int, Int}( 1 => 2, 3 => 4) ``` -------------------------------- ### add_node! Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Appends a new node `n` to an existing FST node `t` with configurable line joining and padding behavior. ```APIDOC ## add_node! - Method ### Description 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. ### Method ```julia add_node!( t::FST, n::FST, s::State; join_lines::Bool = false, max_padding::Int = -1, override_join_lines_based_on_source::Bool = false, ) ``` ``` -------------------------------- ### Format `Float32` literals without decimal points Source: https://domluna.github.io/JuliaFormatter.jl/stable/transforms For `Float32` literals without a decimal point, `.0` is appended. ```julia a = 1f0 -> a = 1.0f0 ``` -------------------------------- ### Prepend Return to Last Expression Source: https://domluna.github.io/JuliaFormatter.jl/stable When `always_use_return` is true, `return` is prepended to the last expression in function definitions, macro definitions, and do blocks where applicable. ```julia function foo() expr1 expr2 end ``` ```julia function foo() expr1 return expr2 end ``` -------------------------------- ### Format Markdown text Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Normalizes Markdown source and formats Julia code blocks within it. Accepts a string and returns the formatted Markdown string. ```Julia format_md(text::AbstractString; style::AbstractStyle = DefaultStyle(), kwargs...) ``` -------------------------------- ### Align Matrix Whitespace Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Adjusts whitespace between matrix elements to match the original source file. ```julia align_matrix!(fst::FST) ``` -------------------------------- ### Indent submodules with indent_submodule Source: https://domluna.github.io/JuliaFormatter.jl/stable When set to true, submodules within the same file will be indented relative to their parent module. ```julia module A a = 1 module B b = 2 module C c = 3 end end d = 4 end ``` ```julia module A a = 1 module B b = 2 module C c = 3 end end d = 4 end ``` -------------------------------- ### Define FST Type Source: https://domluna.github.io/JuliaFormatter.jl/stable/api Represents the Formatted Syntax Tree structure used internally by the formatter. ```julia FST ``` -------------------------------- ### Disable Formatting for an Entire File Source: https://domluna.github.io/JuliaFormatter.jl/stable/skipping_formatting Place `#! format: off` at the top of a file to prevent any formatting for the entire file. The formatter requires the directive to be on its own line with exact whitespace. ```julia #! format: off # # It doesn't actually matter if it's on # the first line of the line but anything # onwards will NOT be formatted. module Foo ... end ``` -------------------------------- ### Nest Function Call Arguments Source: https://domluna.github.io/JuliaFormatter.jl/stable/style If a function call or any expression with opening/closing punctuation exceeds the margin, its arguments are indented one level. ```julia function longfunctionname_that_is_long(lots, of, args, even, more, args) body end -> function longfunctionname_that_is_long( lots, of, args, even, more, args, ) body end ``` -------------------------------- ### Annotate Untyped Fields with Any Source: https://domluna.github.io/JuliaFormatter.jl/stable When `annotate_untyped_fields_with_any` is true, fields in type definitions without explicit type annotations are annotated with `::Any`. ```julia struct A arg1 end ``` ```julia struct A arg1::Any end ```