### TOML Configuration Example Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Example of a .stylua.toml configuration file. ```toml column_width = 100 indent_type = "spaces" ``` -------------------------------- ### Stylua Configuration File Example Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Example of a `.stylua.toml` configuration file. This file allows customization of various formatting options. ```toml # .stylua.toml syntax = "lua54" column_width = 100 indent_type = "spaces" indent_width = 2 quote_style = "force_single" call_parentheses = "none" ``` -------------------------------- ### Install StyLua with pip or uv Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua by referencing the Git repository directly using pip or uv. This method installs StyLua from its source repository. ```sh pip install git+https://github.com/johnnymorganz/stylua ``` ```sh uv tool install git+https://github.com/johnnymorganz/stylua ``` -------------------------------- ### Install StyLua with Cargo (LuaJIT Feature) Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua using Cargo with the 'luajit' feature enabled for LuaJIT syntax formatting. ```sh cargo install stylua --features luajit ``` -------------------------------- ### QuoteStyle Usage Examples Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/api-reference-core.md Illustrates the behavior of AutoPreferDouble and ForceSingle quote styles with examples. ```rust // AutoPreferDouble: "hello" but 'can\'t' becomes 'can\'t' // ForceSingle: 'hello' and 'can\'t' ``` -------------------------------- ### Instantiate Config with Defaults Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/api-reference-core.md Example of creating a new `Config` object using the default constructor. ```rust let config = Config::new(); ``` -------------------------------- ### EditorConfig Configuration Example Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of an .editorconfig file that Stylua can read for formatting options when no .stylua.toml is found. This allows for project-specific formatting rules. ```ini root = true [*.lua] end_of_line = lf indent_style = space indent_size = 2 max_line_length = 100 quote_type = single call_parentheses = none ``` -------------------------------- ### Install StyLua with Cargo (Luau Feature) Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua using Cargo with the 'luau' feature enabled for Luau syntax formatting. ```sh cargo install stylua --features luau ``` -------------------------------- ### Configure pre-commit with StyLua Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Add StyLua to your .pre-commit-config.yaml. Choose 'stylua' for cargo installation, 'stylua-system' for PATH binary, or 'stylua-github' for automatic binary installation. ```yaml - repo: https://github.com/JohnnyMorganz/StyLua rev: v2.5.2 hooks: - id: stylua # or stylua-system / stylua-github ``` -------------------------------- ### Use specific configuration file Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of specifying a custom configuration file path using the -f or --config-path flag. ```bash # Use specific configuration file stylua -f custom.toml src/ ``` -------------------------------- ### Format a single file with defaults Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of formatting a single Lua file using Stylua's default configuration. ```bash # Format a single file with defaults stylua myfile.lua ``` -------------------------------- ### JSON Output Example for Check Mode Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md An example of the JSON output format when using `stylua --check --output-format json`. ```json { "file": "src/main.lua", "mismatches": [ { "start": 10, "end": 15, "original": " x = 1", "expected": "x = 1" } ] } ``` -------------------------------- ### Rust Language Server Formatting Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Implement a language server for code formatting with Stylua. This example shows how to format an entire document or a specific range. ```rust use stylua_lib::{format_code, Config, OutputVerification, Range}; pub struct FormattingServer { config: Config, } impl FormattingServer { pub fn format_document(&self, code: &str) -> Result { format_code(code, self.config, None, OutputVerification::Full) .map_err(|e| e.to_string()) } pub fn format_range(&self, code: &str, start: usize, end: usize) -> Result { let range = Range::from_values(Some(start), Some(end)); format_code(code, self.config, Some(range), OutputVerification::Full) .map_err(|e| e.to_string()) } } ``` -------------------------------- ### Run StyLua CLI with npx Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Execute the StyLua binary installed via npm using npx. This is useful for quick checks or running StyLua without global installation. ```sh npx @johnnymorganz/stylua-bin --help ``` -------------------------------- ### Specify Range Start for Formatting Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Define the byte offset where formatting should begin using `--range-start`. The rest of the file remains unchanged. ```bash stylua --range-start 100 myfile.lua # Format from byte 100 to end of file ``` -------------------------------- ### CLI Configuration Override Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Example of overriding configuration file settings using CLI flags. ```bash stylua --column-width 80 file.lua ``` -------------------------------- ### Install StyLua with Cargo (Lua 5.3 Feature) Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua using Cargo with the 'lua53' feature enabled for Lua 5.3 syntax formatting. ```sh cargo install stylua --features lua53 ``` -------------------------------- ### Install StyLua with Cargo (Default) Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua using Cargo, Rust's package manager. This installs the default version which formats Lua 5.1. ```sh cargo install stylua ``` -------------------------------- ### Verbose output Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of enabling verbose output using the -v or --verbose flag to get more detailed information during the formatting process. ```bash # Verbose output stylua -v src/ ``` -------------------------------- ### Example .stylua.toml Configuration Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md This TOML file demonstrates various configuration options for Stylua, including column width, line endings, indentation, quote style, and more. It also shows how to configure specific features like sorting requires. ```toml column_width = 100 line_endings = "unix" indent_type = "spaces" indent_width = 2 quote_style = "auto_prefer_single" call_parentheses = "always" collapse_simple_statement = "never" preserve_block_newline_gaps = "never" space_after_function_names = "never" sort_requires = false [sort_requires] enabled = false ``` -------------------------------- ### Parallel File Formatting with CLI Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Example of using the Stylua CLI to format multiple files in parallel using multiple threads. ```bash stylua --num-threads 8 src/ ``` -------------------------------- ### Install StyLua with Cargo (Lua 5.4 Feature) Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua using Cargo with the 'lua54' feature enabled for Lua 5.4 syntax formatting. ```sh cargo install stylua --features lua54 ``` -------------------------------- ### Install StyLua with Cargo (Lua 5.2 Feature) Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua using Cargo with the 'lua52' feature enabled for Lua 5.2 syntax formatting. ```sh cargo install stylua --features lua52 ``` -------------------------------- ### Config::new() Constructor Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/api-reference-core.md Creates a new `Config` instance with default values. This is the starting point for customizing formatting behavior. ```rust pub fn new() -> Self ``` -------------------------------- ### Lua Examples for CollapseSimpleStatement Variants Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/types.md Illustrates the effect of each CollapseSimpleStatement variant on Lua code formatting. ```lua -- Never local function add(a, b) return a + b end -- FunctionOnly local function add(a, b) return a + b end -- ConditionalOnly if condition then return result end -- Always (both collapsed) local function add(a, b) return a + b end if condition then return result end ``` -------------------------------- ### Install StyLua Docker Image Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Copy the StyLua binary from a Docker image into your container. This is an efficient way to include StyLua in Dockerized build processes. ```dockerfile COPY --from=JohnnyMorganz/StyLua:2.5.2 /stylua /usr/bin/stylua ``` -------------------------------- ### VS Code Extension Settings for Stylua Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md Example VS Code settings.json configuration for the Stylua extension. Customize formatting behavior and integration options. ```json { "stylua.searchParentDirectories": true, "stylua.columnWidth": 120, "stylua.indentType": "tabs", "stylua.indentWidth": 4, "stylua.syntax": "all", "stylua.quoteStyle": "auto_prefer_double", "stylua.callParentheses": "always", "stylua.collapseSimpleStatement": "never", "stylua.preserveBlockNewlineGaps": "never", "stylua.sortRequires": false, "stylua.spaceAfterFunctionNames": "never" } ``` -------------------------------- ### Lua Examples for SpaceAfterFunctionNames Variants Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/types.md Shows how SpaceAfterFunctionNames variants affect spacing in Lua function definitions and calls. ```lua -- Never function greet(name) end greet("world") -- Definitions function greet (name) end greet("world") -- Calls function greet(name) end greet ("world") -- Always function greet (name) end greet ("world") ``` -------------------------------- ### Format with Lua 5.4 syntax Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of enforcing a specific Lua syntax version (Lua 5.4 in this case) for formatting using the --syntax flag. ```bash # Format with Lua 5.4 syntax stylua --syntax lua54 myfile.lua ``` -------------------------------- ### Lua Examples for BlockNewlineGaps Variants Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/types.md Demonstrates the impact of BlockNewlineGaps variants on Lua code, showing preservation or removal of blank lines around blocks. ```lua -- Never: blank lines are removed function process() local x = 1 end -- Preserve: blank lines are kept if in input function process() local x = 1 end ``` -------------------------------- ### Format with custom column width Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of formatting a Lua file with a specified maximum line length using the --column-width flag. ```bash # Format with custom column width stylua --column-width 80 myfile.lua ``` -------------------------------- ### Full Output Verification in Rust Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Example of performing a full semantic verification of the formatted output using the Stylua API in Rust. This helps detect formatter bugs. ```rust format_code(code, config, None, OutputVerification::Full)? // Reparses output and compares AST to input // Catches semantic changes ``` -------------------------------- ### Format directory with spaces indentation Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of formatting all Lua files within a directory, enforcing space indentation with a specific width. ```bash # Format directory with spaces indentation stylua --indent-type spaces --indent-width 2 src/ ``` -------------------------------- ### Include hidden files and directories Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Use the --allow-hidden flag to format files and directories that start with a dot (.). ```bash stylua --allow-hidden src/ ``` -------------------------------- ### Rust Plugin System Formatter Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Implement a formatter plugin for Stylua using Rust. This example shows how to define a trait for plugins and a concrete implementation for Stylua. ```rust use stylua_lib::{format_code, Config}; pub trait FormatterPlugin { fn get_config(&self) -> Config; fn format(&self, code: &str) -> Result; } pub struct StyluaFormatter { config: Config, } impl FormatterPlugin for StyluaFormatter { fn get_config(&self) -> Config { self.config } fn format(&self, code: &str) -> Result { format_code(code, self.config, None, stylua_lib::OutputVerification::None) .map_err(|e| e.to_string()) } } ``` -------------------------------- ### Predefined Formatting Profiles Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md Define reusable `FormattingProfile` structs for common configurations like Roblox, FiveM, or an opinionated setup. Each profile encapsulates a specific `Config`. ```rust use stylua_lib::* pub struct FormattingProfile { name: String, config: Config, } impl FormattingProfile { pub fn roblox() -> Self { let mut config = Config::new(); config.syntax = LuaVersion::Luau; config.indent_type = IndentType::Spaces; config.indent_width = 4; config.column_width = 120; Self { name: "Roblox".to_string(), config, } } pub fn fivem() -> Self { let mut config = Config::new(); config.syntax = LuaVersion::CfxLua; config.indent_type = IndentType::Tabs; config.column_width = 100; Self { name: "FiveM".to_string(), config, } } pub fn opinionated() -> Self { let mut config = Config::new(); config.indent_type = IndentType::Spaces; config.indent_width = 2; config.quote_style = QuoteStyle::ForceSingle; config.call_parentheses = CallParenType::None; config.collapse_simple_statement = CollapseSimpleStatement::FunctionOnly; Self { name: "Opinionated".to_string(), config, } } pub fn config(&self) -> Config { self.config } } ``` -------------------------------- ### LSP textDocument/formatting Request Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md Example JSON payload for the textDocument/formatting LSP method. Editors use this to request full document formatting. ```json { "jsonrpc": "2.0", "id": 1, "method": "textDocument/formatting", "params": { "textDocument": { "uri": "file:///path/to/file.lua" }, "options": { "tabSize": 4, "insertSpaces": false } } } ``` -------------------------------- ### Format specific byte range Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of formatting only a specific portion of a file, defined by byte offsets, using --range-start and --range-end flags. ```bash # Format specific byte range stylua --range-start 100 --range-end 500 myfile.lua ``` -------------------------------- ### Use Custom Config and Check Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Apply a custom configuration file (e.g., './stylua.toml') and then check the formatting with a summary output. ```bash stylua -f ./stylua.toml --check --output-format summary src/ ``` -------------------------------- ### Create a Range Struct Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/api-reference-core.md Use `Range::from_values` to create a new `Range` instance with specified start and end byte offsets. Pass `None` for either parameter to indicate formatting from the beginning or to the end of the file, respectively. ```rust // Format bytes 0-100 let range = Range::from_values(Some(0), Some(100)); // Format from byte 50 to end let range = Range::from_values(Some(50), None); // Format entire file (same as None) let range = Range::from_values(None, None); ``` -------------------------------- ### Ignore Code Blocks Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Use '-- stylua: ignore start' and '-- stylua: ignore end' to skip formatting entire blocks of code. Formatting is re-enabled after the block is exited. ```lua -- stylua: ignore start local bar = false local baz = 0 -- stylua: ignore end ``` -------------------------------- ### Check files without modifying Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Example of using the --check flag to verify code style without making any changes. This will report differences as a diff. ```bash # Check files without modifying (show diffs) stylua --check src/ ``` -------------------------------- ### Handling Stylua Formatting Errors Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/api-reference-core.md Demonstrates how to handle potential errors when formatting code using `stylua_lib::format_code`. This example shows matching on the `Error` enum to provide specific feedback for parsing issues, formatter bugs, or semantic differences. ```rust use stylua_lib::{format_code, Config, OutputVerification, Error}; match format_code(code, Config::new(), None, OutputVerification::Full) { Ok(formatted) => println!("{}", formatted), Err(Error::ParseError(errs)) => { eprintln!("Syntax error in input code:"); for err in errs { eprintln!(" {}", err); } } Err(Error::VerificationAstError(errs)) => { eprintln!("BUG: Formatter produced invalid output!"); eprintln!("Please report at https://github.com/johnnymorganz/stylua/issues"); } Err(Error::VerificationAstDifference) => { eprintln!("BUG: Output has different meaning than input!"); eprintln!("Please report at https://github.com/johnnymorganz/stylua/issues"); } } ``` -------------------------------- ### Load Stylua Configuration from Directory Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md Searches the current directory and its parents for a .stylua.toml file to load configuration. Returns default configuration if no file is found. ```rust use stylua_lib::Config; use std::fs; use std::path::Path; fn load_config_for_path(path: &Path) -> Result { // Search up directory tree for .stylua.toml let mut current = path.parent(); while let Some(dir) = current { let config_path = dir.join(".stylua.toml"); if config_path.exists() { let contents = fs::read_to_string(&config_path) .map_err(|e| e.to_string())?; return toml::from_str(&contents) .map_err(|e| e.to_string()); } current = dir.parent(); } Ok(Config::new()) // Default if not found } ``` -------------------------------- ### Install StyLua with Homebrew Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua on macOS using the Homebrew package manager. This command adds StyLua to your system's PATH. ```sh brew install stylua ``` -------------------------------- ### QuoteStyle Enum Definition and Examples Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/types.md Specifies quote handling in string literals. Defaults to AutoPreferDouble. Examples show behavior for different variants. ```rust #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Deserialize)] pub enum QuoteStyle { #[default] AutoPreferDouble, AutoPreferSingle, ForceDouble, ForceSingle, } ``` ```lua -- AutoPreferDouble "hello" 'can\'t' -- switches to single quotes to avoid escaping -- AutoPreferSingle 'hello' "don\"t" -- switches to double quotes to avoid escaping -- ForceDouble "hello" "can't" -- ForceSingle 'hello' 'can\'t' ``` -------------------------------- ### Specify explicit configuration file path Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Use -f or --config-path to specify the exact path to the configuration file. ```bash stylua -f custom-config.toml myfile.lua stylua --config-path ./stylua.toml src/ ``` -------------------------------- ### Basic CLI Formatting Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Format all Lua files in the 'src/' directory using the Stylua CLI with default settings. ```bash stylua src/ ``` -------------------------------- ### Define a Byte Range for Formatting Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/api-reference-core.md Use the `Range` struct to specify a byte range within source code for formatting. Initialize with `start` and `end` byte offsets, or `None` to format from the start or to the end of the file. ```rust pub struct Range { pub start: Option, pub end: Option, } ``` -------------------------------- ### Dynamic Configuration Builder Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md Use the `ConfigBuilder` to construct a `Config` object step-by-step. This builder allows you to set individual configuration options like syntax version, indentation type and width, and column width. ```rust use stylua_lib::* pub struct ConfigBuilder { syntax: LuaVersion, column_width: usize, indent_type: IndentType, indent_width: usize, quote_style: QuoteStyle, call_parentheses: CallParenType, } impl ConfigBuilder { pub fn new() -> Self { let default = Config::new(); Self { syntax: default.syntax, column_width: default.column_width, indent_type: default.indent_type, indent_width: default.indent_width, quote_style: default.quote_style, call_parentheses: default.call_parentheses, } } pub fn syntax(mut self, syntax: LuaVersion) -> Self { self.syntax = syntax; self } pub fn spaces(mut self, width: usize) -> Self { self.indent_type = IndentType::Spaces; self.indent_width = width; self } pub fn tabs(mut self) -> Self { self.indent_type = IndentType::Tabs; self } pub fn build(self) -> Config { let mut config = Config::new(); config.syntax = self.syntax; config.column_width = self.column_width; config.indent_type = self.indent_type; config.indent_width = self.indent_width; config.quote_style = self.quote_style; config.call_parentheses = self.call_parentheses; config } } // Usage let config = ConfigBuilder::new() .syntax(LuaVersion::Lua54) .spaces(2) .build(); ``` -------------------------------- ### Full-moon Parse Error Message Examples Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/errors.md These examples illustrate common parse error messages encountered during code analysis, indicating issues like unexpected tokens, unclosed comments, invalid characters, and missing syntax elements. ```text unexpected token `end` (5:1 to 5:4), expected '}' to close function call unclosed comment (starting at line 1) unexpected character '@' at line 3, column 5 expected label name after `::` ``` -------------------------------- ### CLI Formatting with Options Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Format Lua files with specific CLI options for indentation type and column width. ```bash stylua --indent-type spaces --column-width 80 src/ ``` -------------------------------- ### Per-Project Default Configurations Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Defines default configurations for specific projects like Roblox or FiveM. Allows for project-specific formatting rules. ```rust use stylua_lib::Config; struct ProjectFormatter { config: Config, } impl ProjectFormatter { fn for_roblox() -> Self { let mut config = Config::new(); config.syntax = stylua_lib::LuaVersion::Luau; config.indent_type = stylua_lib::IndentType::Spaces; config.indent_width = 4; Self { config } } fn for_fivem() -> Self { let mut config = Config::new(); config.syntax = stylua_lib::LuaVersion::CfxLua; config.indent_type = stylua_lib::IndentType::Tabs; Self { config } } fn format(&self, code: &str) -> Result { stylua_lib::format_code(code, self.config, None, stylua_lib::OutputVerification::Full) } } ``` -------------------------------- ### Load Configuration from TOML File Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Loads Stylua configuration from a TOML file. Ensure the TOML file is correctly formatted and accessible. ```rust use stylua_lib::Config; use std::fs; fn load_config_from_file(path: &str) -> Result { let contents = fs::read_to_string(path)?; toml::from_str(&contents) } fn main() { let config = load_config_from_file(".stylua.toml")?; // Use config... } ``` -------------------------------- ### Specify Lua Syntax Version Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/errors.md Explicitly set the desired Lua syntax version for the configuration, for example, to Lua 5.4. ```rust let mut config = Config::new(); config.syntax = LuaVersion::Lua54; ``` -------------------------------- ### Search parent directories for configuration Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Use -s or --search-parent-directories to automatically find a stylua.toml file in the current or parent directories. ```bash stylua -s src/main.lua # Searches: ./stylua.toml, ../stylua.toml, ../../stylua.toml, ... ``` -------------------------------- ### Format Code in Browser with Bundler Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Set up an event listener for input changes on an editor element to format code in real-time. Assumes the presence of 'editor' and 'output' HTML elements. ```javascript import init, { formatCode, Config } from '@johnnymorganz/stylua'; async function setupFormatter() { await init(); const editorElement = document.getElementById('editor'); const outputElement = document.getElementById('output'); editorElement.addEventListener('input', (e) => { try { const config = new Config(); const result = formatCode(e.target.value, config, null, 1); // 1 = Full outputElement.textContent = result; } catch (error) { outputElement.textContent = `Error: ${error}`; } }); } setupFormatter(); ``` -------------------------------- ### CLI Formatting Specific File Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Format a single Lua file using a specified configuration file. ```bash stylua -f config.toml myfile.lua ``` -------------------------------- ### Preserve Block Newline Gaps Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md Control the preservation of blank lines at the start and end of code blocks. 'preserve' keeps them if present in the input. ```toml preserve_block_newline_gaps = "preserve" ``` -------------------------------- ### Override Configuration with CLI Flags Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md CLI flags take precedence over configuration files. This example shows a CLI flag overriding a setting in `.stylua.toml`. ```bash # .stylua.toml has: column_width = 100 # CLI flag overrides to: column_width = 80 stylua --column-width 80 src/ ``` -------------------------------- ### Verification Levels for Formatting Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Use `OutputVerification::None` for faster formatting in production and `OutputVerification::Full` in tests to ensure complete verification. ```rust use stylua_lib::{format_code, Config, OutputVerification}; fn main() { let config = Config::new(); let code = "local x = 1"; // In production: skip verification for speed let _result = format_code(code, config, None, OutputVerification::None); // In tests: use Full verification let _result = format_code(code, config, None, OutputVerification::Full); } ``` -------------------------------- ### Format with Verification and Debugging Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Combine verbose output, verification, checking, and a unified output format for detailed debugging during formatting. ```bash stylua -v --verify --check --output-format unified src/ ``` -------------------------------- ### LSP textDocument/rangeFormatting Request Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md Example JSON payload for the textDocument/rangeFormatting LSP method. Editors use this to request formatting for a specific range within a document. ```json { "jsonrpc": "2.0", "id": 2, "method": "textDocument/rangeFormatting", "params": { "textDocument": { "uri": "file:///path/to/file.lua" }, "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 10, "character": 0 } }, "options": { "tabSize": 4, "insertSpaces": false } } } ``` -------------------------------- ### Custom LSP Client Implementation in Rust Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md A basic Rust implementation of an LSP client that handles textDocument/formatting requests using stylua_lib. Requires `lsp-server` and `lsp-types` crates. ```rust use lsp_server::{Connection, Message, Request, Response}; use lsp_types::*; use stylua_lib::{format_code, Config, OutputVerification}; fn main() -> Result<(), String> { let (connection, io_threads) = Connection::listen()?; loop { match connection.receiver.recv()? { Message::Request(req) => { if req.method == "textDocument/formatting" { handle_format_request(&connection, req)?; } } Message::Response(_) => {} // Ignore responses Message::Notification(_) => {} // Ignore notifications } } } fn handle_format_request( connection: &Connection, request: Request, ) -> Result<(), String> { let params: DocumentFormattingParams = serde_json::from_value(request.params)?; let code = get_document_content(¶ms.text_document.uri)?; let config = load_config_for_path(¶ms.text_document.uri)?; let formatted = format_code(&code, config, None, OutputVerification::Full) .map_err(|e| e.to_string())?; let edits = vec![TextEdit { range: Range { start: Position { line: 0, character: 0 }, end: Position { line: u32::MAX, character: 0 }, }, new_text: formatted, }]; let response = Response { id: request.id, result: Some(serde_json::to_value(edits)?), error: None, }; connection.sender.send(Message::Response(response))?; Ok(()) } // Placeholder functions - actual implementation needed fn get_document_content(uri: &Url) -> Result { // In a real client, you would read the file content here. Ok("local x = 1\nreturn x".to_string()) } fn load_config_for_path(uri: &Url) -> Result { // In a real client, you would load the configuration from a file or settings. Ok(Config::default()) } ``` -------------------------------- ### Format a Specific Range within a File Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/INDEX.md Utilize the `Range::from_values` function to specify start and end points for formatting only a portion of a Lua file. ```rust Range::from_values(Some(start), Some(end)) ``` -------------------------------- ### Format Files and Directories Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Pass files or directories to the CLI to format them. StyLua searches directories recursively for Lua files. ```sh stylua src/ foo.lua bar.lua ``` -------------------------------- ### Config::new() Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/api-reference-core.md Creates a new `Config` object with default values for all formatting options. ```APIDOC ## Config::new() ### Description Creates a new `Config` object with default values. ### Method `Config::new()` ### Returns `Self` (a new `Config` instance with default values) ### Example ```rust let config = Config::new(); ``` ``` -------------------------------- ### Deserialize Stylua Configuration from TOML Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/types.md Demonstrates how to load Stylua configuration from a TOML string using the `serde` and `toml` crates. ```rust use stylua_lib::Config; use toml; let toml_str = r#" syntax = "lua54" column_width = 100 indent_type = "spaces" indent_width = 2 "#; let config: Config = toml::from_str(toml_str)?; ``` -------------------------------- ### Format with Custom Settings Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Combine multiple flags to customize formatting, including syntax version, indent type and width, column width, and quote style. ```bash stylua \ --syntax lua54 \ --indent-type spaces \ --indent-width 2 \ --column-width 100 \ --quote-style force_single \ src/ ``` -------------------------------- ### Create Configuration using Builder Pattern Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Constructs a Stylua configuration object programmatically using a builder pattern. Useful for setting specific formatting options. ```rust use stylua_lib::{Config, IndentType, QuoteStyle, CallParenType}; fn create_config() -> Config { let mut config = Config::new(); config.indent_type = IndentType::Spaces; config.indent_width = 2; config.quote_style = QuoteStyle::ForceSingle; config.call_parentheses = CallParenType::None; config } ``` -------------------------------- ### Add StyLua via Aftman Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Install StyLua using the Aftman package manager. This command adds a specific version of StyLua to your project's managed tools. ```sh aftman add johnnymorganz/stylua@2.5.2 ``` -------------------------------- ### Load Stylua Configuration from Environment Variables Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md Loads Stylua configuration settings from environment variables such as STYLUA_INDENT_WIDTH, STYLUA_COLUMN_WIDTH, and STYLUA_LINE_ENDINGS. Parses values and applies them to a new Config object. ```rust use stylua_lib::*; use std::env; fn load_config_from_env() -> Config { let mut config = Config::new(); if let Ok(indent) = env::var("STYLUA_INDENT_WIDTH") { if let Ok(width) = indent.parse() { config.indent_width = width; } } if let Ok(width) = env::var("STYLUA_COLUMN_WIDTH") { if let Ok(width) = width.parse() { config.column_width = width; } } if let Ok(endings) = env::var("STYLUA_LINE_ENDINGS") { config.line_endings = match endings.as_str() { "windows" => LineEndings::Windows, _ => LineEndings::Unix, }; } config } ``` -------------------------------- ### Stylua CLI Basic Usage Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/configuration.md The basic command structure for using the Stylua CLI. Options can be provided as flags to override configuration file settings. ```bash stylua [OPTIONS] [FILES]... ``` -------------------------------- ### Handling VerificationAstError in Rust Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/errors.md Provides Rust code for handling VerificationAstError. This error signifies a critical bug in Stylua, and the example suggests reporting the issue and potentially falling back to unformatted input. ```rust use stylua_lib::Error; match format_code(code, config, None, OutputVerification::Full) { Err(Error::VerificationAstError(errors)) => { eprintln!("BUG: Formatter produced invalid syntax!"); eprintln!("Please report at https://github.com/johnnymorganz/stylua/issues"); for error in errors { eprintln!(" {}", error); } // Consider falling back to unformatted input } _ => {} } ``` -------------------------------- ### Stylua Configuration Structure Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/types.md Illustrates the hierarchical structure of Stylua's configuration options, including enums and nested structs. ```text Config (struct) ├── syntax: LuaVersion (enum) ├── line_endings: LineEndings (enum) ├── indent_type: IndentType (enum) ├── quote_style: QuoteStyle (enum) ├── call_parentheses: CallParenType (enum) ├── collapse_simple_statement: CollapseSimpleStatement (enum) ├── block_newline_gaps: BlockNewlineGaps (enum) ├── space_after_function_names: SpaceAfterFunctionNames (enum) └── sort_requires: SortRequiresConfig (struct) ``` -------------------------------- ### Lua code causing ParseError Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/errors.md Examples of Lua code with syntax errors that will trigger a ParseError. These include missing values in assignments, unclosed strings, unexpected tokens, and invalid number formats. ```lua -- Missing value in assignment local x = -- Unclosed string local msg = "hello -- Unexpected token local y = 1 2 3 -- Invalid number local z = 0x_invalid ``` -------------------------------- ### Get Detailed Parse Error Information Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/errors.md Use this Rust code to read a Lua file, attempt to format it, and then print detailed information about any parse errors encountered, including token, line, and character information. ```rust use stylua_lib::{format_code, Config, OutputVerification, Error}; use std::fs; let code = fs::read_to_string("myfile.lua")?; match format_code(&code, Config::new(), None, OutputVerification::None) { Ok(formatted) => println!("{}", formatted), Err(Error::ParseError(errors)) => { for error in errors { match error { full_moon::Error::AstError(ast_error) => { let (start, end) = ast_error.range(); println!("Parse error at {}:{} to {}:{}", start.line(), start.character(), end.line(), end.character()); println!("Token: {}", ast_error.token()); println!("Expected: {}", ast_error.error_message()); } full_moon::Error::TokenizerError(tok_error) => { println!("Tokenizer error: {}", tok_error); } } } } _ => {} } ``` -------------------------------- ### Range Formatting in Rust Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Demonstrates how to format a specific range of code using the Stylua API in Rust. Useful for editor integration. ```rust let range = Range::from_values(Some(100), Some(500)); format_code(code, config, Some(range), OutputVerification::None)? ``` -------------------------------- ### Enable Language Server Protocol (LSP) Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Run Stylua in LSP mode for editor integration. This is used by VS Code extensions and other editors. ```bash stylua --lsp ``` -------------------------------- ### Format multiple files Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Formats multiple specified Lua files in place. ```bash stylua src/main.lua src/utils.lua ``` -------------------------------- ### Ignore Files with .styluaignore Source: https://github.com/johnnymorganz/stylua/blob/main/README.md Create a .styluaignore file to specify patterns of files or directories that StyLua should ignore during formatting. ```sh stylua . ``` -------------------------------- ### Format Code as a Library (Simple) Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md Format a string of Lua code using the `format_code` function with default configuration and no specific range. `OutputVerification::None` is used for faster formatting. ```rust let formatted = format_code(code, Config::new(), None, OutputVerification::None)?; ``` -------------------------------- ### Specify stdin filepath for configuration Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md When reading from stdin, use --stdin-filepath to indicate the path for determining the relevant configuration file. ```bash cat src/main.lua | stylua --stdin-filepath src/main.lua - # Loads configuration relative to src/ directory ``` -------------------------------- ### Use Full Output Verification Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/errors.md Employ `OutputVerification::Full` during the `format_code` process in production environments to ensure comprehensive verification of the formatted output. ```rust format_code(code, config, None, OutputVerification::Full)? ``` -------------------------------- ### Configure Syntax for Luau Generics/Bitshift Conflict Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/errors.md If encountering parse errors related to '>>', configure Stylua to explicitly use Luau syntax by adding this to your .stylua.toml file. ```toml syntax = "Luau" ``` -------------------------------- ### Parse and Format Lua AST Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Parse Lua code into an AST, format it using Stylua's configuration, and convert it back to a string. Requires `stylua_lib` and `full_moon`. ```rust use stylua_lib::{format_ast, Config, OutputVerification}; fn main() { let code = "local x=1"; // Parse with full-moon let ast = full_moon::parse(code).expect("Parse failed"); // Format the AST let config = Config::new(); let formatted_ast = format_ast(ast, config, None, OutputVerification::None)?; // Convert back to string let output = formatted_ast.to_string(); println!("{}", output); } ``` -------------------------------- ### Configure Parallel Formatting with Stylua Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/INDEX.md Control the number of threads used for formatting with the `--num-threads N` flag or by leveraging the rayon crate for parallel processing. ```bash --num-threads N ``` -------------------------------- ### Format Multiple Files Sequentially Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Use this function to format a list of Lua files sequentially. It reads each file, formats its content using Stylua, and writes the formatted code back to the original file. Ensure the files exist and are accessible. ```rust use stylua_lib::{format_code, Config, OutputVerification}; use std::fs; use std::path::Path; fn format_file(path: &Path, config: &Config) -> Result<(), String> { let code = fs::read_to_string(path) .map_err(|e| format!("Read failed: {}", e))?; let formatted = format_code(&code, *config, None, OutputVerification::None) .map_err(|e| e.to_string())?; fs::write(path, formatted) .map_err(|e| format!("Write failed: {}", e))?; Ok(()) } fn main() { let config = Config::new(); let files = ["main.lua", "utils.lua", "lib.lua"]; for file in &files { match format_file(Path::new(file), &config) { Ok(_) => println!("✓ {}", file), Err(e) => println!("✗ {}: {}", file, e), } } } ``` -------------------------------- ### Format Lua Code with Default Settings Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/INDEX.md Use the `format_code` function with default configuration and no output verification for basic code formatting. ```rust format_code(code, Config::new(), None, OutputVerification::None) ``` -------------------------------- ### Configuration Inheritance with Overrides Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/advanced-integration.md Implement configuration inheritance using `ConfigChain`, which allows a base configuration to be modified by a series of key-value overrides. This method returns a `Result` to handle potential parsing errors for override values. ```rust use stylua_lib::* pub struct ConfigChain { base: Config, overrides: Vec<(String, String) היי } impl ConfigChain { pub fn new(base: Config) -> Self { Self { base, overrides: Vec::new(), } } pub fn with_override(mut self, key: &str, value: &str) -> Self { self.overrides.push((key.to_string(), value.to_string())); self } pub fn build(self) -> Result { let mut config = self.base; for (key, value) in self.overrides { match key.as_str() { "indent_width" => { config.indent_width = value.parse() .map_err(|_| "indent_width must be a number")?; } "column_width" => { config.column_width = value.parse() .map_err(|_| "column_width must be a number")?; } "indent_type" => { config.indent_type = match value.as_str() { "tabs" => IndentType::Tabs, "spaces" => IndentType::Spaces, _ => return Err("indent_type must be tabs or spaces".to_string()), }; } _ => return Err(format!("Unknown config key: {}", key)), } } Ok(config) } } ``` -------------------------------- ### Enable Full Verification Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/README.md To detect more subtle issues, enable Full verification using the --verify flag. This performs a more thorough check of the code. ```bash stylua --verify src/ ``` -------------------------------- ### Create Custom Stylua Configuration Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/INDEX.md Define a `Config` struct and modify its fields to customize formatting options beyond the defaults. ```rust Config ``` -------------------------------- ### Respect .styluaignore rules for direct paths Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/cli-reference.md Use --respect-ignores to apply .styluaignore rules to files specified directly on the command line, not just during directory traversal. ```bash stylua --respect-ignores myfile.lua ``` -------------------------------- ### Format Code with Custom Configuration Source: https://github.com/johnnymorganz/stylua/blob/main/_autodocs/library-usage.md Customize formatting options such as indentation type, width, and column width using `Config`. This allows for tailored code style. ```rust use stylua_lib::{format_code, Config, OutputVerification, IndentType, LineEndings}; fn main() { let code = "local x=1"; let mut config = Config::new(); config.indent_type = IndentType::Spaces; config.indent_width = 2; config.column_width = 80; let formatted = format_code(code, config, None, OutputVerification::None)?; println!("{}", formatted); } ```