### Get Extended Help with Examples Source: https://cmakefmt.dev/getting-started Show a detailed description of every flag with usage examples. ```bash cmakefmt --help ``` -------------------------------- ### Build local docs preview Source: https://cmakefmt.dev/contributing Installs dependencies and starts a local development server for previewing the documentation. ```shell cd docs npm install npm run dev ``` -------------------------------- ### Example CMake Project Structure Source: https://cmakefmt.dev/playground A basic CMake project setup including minimum required version, project definition, finding a package, defining a library, linking libraries, and setting include directories. This serves as a foundation for demonstrating formatting. ```cmake cmake_minimum_required(VERSION 3.20) project(MyProject LANGUAGES CXX) find_package(Boost REQUIRED COMPONENTS filesystem system) add_library(mylib STATIC src/main.cpp src/utils.cpp src/helper.cpp) target_link_libraries(mylib PUBLIC Boost::filesystem Boost::system) target_include_directories(mylib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) ``` -------------------------------- ### GitHub Actions: Install only, run yourself Source: https://cmakefmt.dev/ci Use this to install the cmakefmt binary without running it, allowing for custom invocations. The example shows a check using SARIF report format. ```yaml - uses: cmakefmt/cmakefmt-action@v2 with: mode: setup - run: cmakefmt --check --report-format sarif . > cmakefmt.sarif ``` -------------------------------- ### GitHub Actions: Full example Source: https://cmakefmt.dev/ci A comprehensive GitHub Actions workflow demonstrating a full setup for format checking on push and pull request events. ```yaml name: Format check on: [push, pull_request] jobs: cmakefmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: cmakefmt/cmakefmt-action@v2 ``` -------------------------------- ### Install cmakefmt with winget Source: https://cmakefmt.dev/installation Recommended for Windows users. Installs a native binary using the Windows Package Manager. ```bash winget install cmakefmt.cmakefmt ``` -------------------------------- ### Install cmakefmt with Homebrew Source: https://cmakefmt.dev/getting-started Recommended installation method for macOS. No Rust toolchain is required. ```bash brew install cmakefmt/cmakefmt/cmakefmt ``` -------------------------------- ### Install Fish shell completions Source: https://cmakefmt.dev/installation Installs Fish shell completions by placing the completion file in the appropriate directory. Fish picks up the new file automatically. ```bash cmakefmt completions fish > ~/.config/fish/completions/cmakefmt.fish ``` -------------------------------- ### Install pre-commit and pre-push hooks Source: https://cmakefmt.dev/contributing Installs the git hooks for pre-commit and pre-push using the pre-commit tool. ```shell pre-commit install pre-commit install --hook-type pre-push ``` -------------------------------- ### Install cmakefmt with pip Source: https://cmakefmt.dev/installation Installs cmakefmt using pip. This method installs a native binary, not a Python wrapper. ```bash pip install cmakefmt ``` -------------------------------- ### Basic `set()` command examples Source: https://cmakefmt.dev/behavior Demonstrates simple and short value assignments for the `set()` command, which remain inline. ```cmake set(FOO bar) set(FOO a b c) set(FOO "value" PARENT_SCOPE) set(ENV{FOO} "value") set(FOO) ``` -------------------------------- ### Install cmakefmt with Cargo Source: https://cmakefmt.dev/getting-started Install using Cargo for developers who already use Rust. This method works on any platform. ```bash cargo install cmakefmt-rust ``` -------------------------------- ### Example: keyword_case with command_case Source: https://cmakefmt.dev/config Demonstrates how `keyword_case` and `command_case` interact to affect the output of `target_link_libraries`. ```cmake target_link_libraries(foo PUBLIC bar) ``` -------------------------------- ### Install Zsh shell completions Source: https://cmakefmt.dev/installation Installs Zsh shell completions by placing the completion file on your fpath and configuring your .zshrc. ```bash cmakefmt completions zsh > ~/.zfunc/_cmakefmt fpath=(~/.zfunc $fpath) autoload -Uz compinit && compinit ``` -------------------------------- ### Recommended YAML Starter Configuration Source: https://cmakefmt.dev/config This is a recommended starting point for your `.cmakefmt.yaml` configuration file, setting basic formatting preferences. ```yaml format: line_width: 80 tab_size: 2 command_case: lower keyword_case: upper ``` -------------------------------- ### Install Bash shell completions Source: https://cmakefmt.dev/installation Installs Bash shell completions either for the current user or system-wide. ```bash cmakefmt completions bash > ~/.local/share/bash-completion/completions/cmakefmt ``` ```bash cmakefmt completions bash | sudo tee /etc/bash_completion.d/cmakefmt > /dev/null ``` -------------------------------- ### Install cmakefmt locally Source: https://cmakefmt.dev/contributing Installs the cmakefmt project locally from the source path for manual testing. ```shell cargo install --path . ``` -------------------------------- ### Install pre-commit hook Source: https://cmakefmt.dev/ci Installs the configured pre-commit hooks, including the cmakefmt hook, for the current repository clone. This command only needs to be run once per clone. ```bash pre-commit install ``` -------------------------------- ### Neovim conform.nvim Setup for cmakefmt Source: https://cmakefmt.dev/editors Configure Neovim's conform.nvim plugin to use cmakefmt as a custom formatter. This setup uses stdin and allows config discovery. ```lua require("conform").setup({ formatters_by_ft = { cmake = { "cmakefmt" }, }, formatters = { cmakefmt = { command = "cmakefmt", args = { "--stdin-path", "$FILENAME", "-" }, stdin = true, }, }, format_on_save = { timeout_ms = 2000, lsp_fallback = false, }, }) ``` -------------------------------- ### Install project dependencies with mise Source: https://cmakefmt.dev/contributing Installs all required development tools and hooks for the cmakefmt project from the repository root. ```shell mise install ``` -------------------------------- ### Compact Layout Example Source: https://cmakefmt.dev/behavior Shows how cmakefmt keeps a simple command on a single line when it fits within the configured width. ```cmake target_link_libraries(foo PUBLIC bar) ``` ```cmake target_link_libraries(foo PUBLIC bar) ``` -------------------------------- ### Explaining formatting decisions Source: https://cmakefmt.dev/cli Use --explain to get detailed per-command formatting decisions for a single file. ```bash cmakefmt --explain ``` -------------------------------- ### GitLab CI: Install via Cargo Source: https://cmakefmt.dev/ci Installs cmakefmt using Cargo, suitable for Rust-enabled GitLab CI images. This approach leverages the Rust toolchain for installation. ```yaml cmakefmt: stage: lint image: rust:latest cache: paths: - $CARGO_HOME/bin/ script: - cargo install cmakefmt-rust --quiet - cmakefmt --check . ``` -------------------------------- ### CMake Formatting Example Source: https://cmakefmt.dev Demonstrates the transformation of messy CMake code into a stable, readable layout by cmakefmt. Shows casing normalization, list collapsing, and call wrapping. ```cmake CMAKE_MINIMUM_REQUIRED(VERSION 3.20) Project(myproject LANGUAGES CXX) set(SOURCES src/main.cpp src/utils.cpp src/parser.cpp) target_link_libraries(mylib PUBLIC Boost::filesystem Boost::system fmt::fmt PRIVATE spdlog::spdlog) IF(WIN32) MESSAGE(STATUS "building on Windows") ENDIF() ``` -------------------------------- ### Example: command_case with keyword_case Source: https://cmakefmt.dev/config Shows the effect of `command_case: upper` and `keyword_case: lower` on `TARGET_LINK_LIBRARIES`. ```cmake TARGET_LINK_LIBRARIES(foo public bar) ``` -------------------------------- ### Minimal Project Install Source: https://cmakefmt.dev/playground This snippet shows a basic CMakeLists.txt file for a minimal project, including finding packages, adding a library, and linking targets. ```cmake CMAKE_MINIMUM_REQUIRED(VERSION 3.20) PROJECT(MyProject LANGUAGES CXX) find_package(Boost REQUIRED COMPONENTS filesystem system) add_library(mylib STATIC src/main.cpp src/utils.cpp src/helper.cpp ) target_link_libraries(mylib PUBLIC Boost::filesystem Boost::system) target_include_directories(mylib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) # Custom function defined by the project my_add_test( NAME mylib_test SOURCES tests/test_main.cpp tests/test_utils.cpp LIBRARIES mylib TIMEOUT 30 VERBOSE ) if(BUILD_TESTING) enable_testing() add_test(NAME integration COMMAND mylib_test --verbose) endif() ``` -------------------------------- ### Verify cmakefmt Installation Source: https://cmakefmt.dev/getting-started Check if cmakefmt has been installed correctly by verifying its version. ```bash cmakefmt --version ``` -------------------------------- ### Verify cmakefmt installation Source: https://cmakefmt.dev/installation Check if the cmakefmt binary is installed and accessible on your system's PATH. ```bash cmakefmt --version cmakefmt --help ``` -------------------------------- ### Continuation Alignment Example (Default) Source: https://cmakefmt.dev/config Illustrates the default 'under-first-value' alignment for continuation lines, aligning under the first value. ```cmake install(DIRECTORY src/ DESTINATION include PATTERN *.h PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_EXECUTE GROUP_READ) ``` -------------------------------- ### Install mise Source: https://cmakefmt.dev/contributing Installs the mise version manager on macOS using Homebrew, or on any system using a curl script. ```shell # macOS brew install mise ``` ```shell # macOS / Linux / WSL curl https://mise.run | sh ``` -------------------------------- ### Install Pre-commit Hook Source: https://cmakefmt.dev/getting-started Set up a git pre-commit hook to automatically check formatting on staged files. ```bash cmakefmt install-hook ``` -------------------------------- ### Command Layout Overrides Source: https://cmakefmt.dev/config Example of specifying layout hints like wrapping and line width for a specific command. ```yaml commands: my_command: pargs: 1 kwargs: SOURCES: nargs: "+" layout: always_wrap: true # always use vertical layout line_width: 120 # allow wider lines for this command tab_size: 4 dangle_parens: true ``` -------------------------------- ### Using cmakefmt CLI Subcommands Source: https://cmakefmt.dev/changelog Examples of using the new subcommand structure for cmakefmt configuration management, replacing older flags. ```bash cmakefmt lsp ``` ```bash cmakefmt completions ``` ```bash cmakefmt config dump ``` ```bash cmakefmt config schema ``` ```bash cmakefmt config check ``` ```bash cmakefmt config show ``` ```bash cmakefmt config path ``` ```bash cmakefmt config explain ``` ```bash cmakefmt config convert ``` ```bash cmakefmt config init ``` -------------------------------- ### Override Settings Example Source: https://cmakefmt.dev/cookbook Compares the formatting of a `message` command before and after applying a specific `line_width` override. ```cmake message( STATUS "Building project ${PROJECT_NAME} version ${PROJECT_VERSION} for ${CMAKE_SYSTEM_NAME}") ``` ```cmake message( STATUS "Building project ${PROJECT_NAME} version ${PROJECT_VERSION} for ${CMAKE_SYSTEM_NAME}") ``` -------------------------------- ### Install Cargo LLVM-cov Source: https://cmakefmt.dev/coverage Command to install the cargo-llvm-cov utility, which is used for generating code coverage reports. ```bash cargo install cargo-llvm-cov ``` -------------------------------- ### Start cmakefmt LSP Server Source: https://cmakefmt.dev/faq Launch the Language Server Protocol (LSP) server for cmakefmt using this command. This enables features like format-on-save and range formatting in editors that support LSP. ```bash cmakefmt lsp ``` -------------------------------- ### Install and Build WASM Package Source: https://cmakefmt.dev/wasm-api Installs `wasm-pack` and builds the WASM package for the web target. This command generates a `pkg/` directory containing the WASM module and TypeScript bindings. ```bash # Install wasm-pack ``` ```bash cargo install wasm-pack # Build the WASM package ``` ```bash wasm-pack build --target web ``` -------------------------------- ### Continuation Alignment Example (Same Indent) Source: https://cmakefmt.dev/config Illustrates the 'same-indent' alignment for continuation lines, aligning with the subkwarg's own indent. ```cmake install(DIRECTORY src/ DESTINATION include PATTERN *.h PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_EXECUTE GROUP_READ) ``` -------------------------------- ### Initial Check on a Small Directory Source: https://cmakefmt.dev/migration Start by running a check on a small, low-risk directory to understand the output without modifying files. ```bash cmakefmt --check cmake/ ``` -------------------------------- ### Sort Argument Lists Example Source: https://cmakefmt.dev/cookbook Demonstrates how `cmake-fmt` sorts `target_link_libraries` arguments when `enable_sort` and `autosort` are true. ```cmake target_link_libraries( mylib PUBLIC spdlog::spdlog Boost::filesystem fmt::fmt Boost::system) ``` ```cmake target_link_libraries( mylib PUBLIC Boost::filesystem Boost::system fmt::fmt spdlog::spdlog) ``` -------------------------------- ### Larger CMake Call Example Source: https://cmakefmt.dev/config A complex CMake call demonstrating various arguments and flags. ```cmake my_library(mylib SOURCES src/foo.cpp src/bar.cpp src/baz.cpp HEADERS include/foo.h include/bar.h LIBRARIES Boost::filesystem fmt::fmt INSTALL DESTINATION lib/mylib OPTIONAL QUIET) ``` -------------------------------- ### Example: Wrap After First Argument Enabled Source: https://cmakefmt.dev/config Demonstrates how `wrap_after_first_arg: true` affects the layout of `target_link_libraries`. ```cmake # wrap_after_first_arg: true target_link_libraries(mylib PUBLIC dep1 dep2 PRIVATE dep3 dep4) ``` -------------------------------- ### Get Short Flag Summary Source: https://cmakefmt.dev/getting-started Display a brief summary of all available command-line flags. ```bash cmakefmt -h ``` -------------------------------- ### Original CMake Call Source: https://cmakefmt.dev/config An example of a CMake call that exceeds the default line width. ```cmake my_library(mylib SOURCES src/foo.cpp src/bar.cpp src/baz.cpp LIBRARIES Boost::filesystem fmt::fmt spdlog::spdlog QUIET) ``` -------------------------------- ### Configuring Keyword Arguments (kwargs) with nargs Source: https://cmakefmt.dev/config Examples of defining keyword arguments and the number of values they accept using nargs. ```yaml commands: my_command: kwargs: OUTPUT_DIRECTORY: nargs: 1 # exactly one value SOURCES: nargs: "+" # one or more values OPTIONAL_SOURCES: nargs: "*" # zero or more values MAYBE_ONE: nargs: "?" # zero or one value AT_LEAST_TWO: nargs: "2+" # two or more values ``` -------------------------------- ### Neovim LSP Setup for cmakefmt Source: https://cmakefmt.dev/editors Configure Neovim to use cmakefmt as a language server via nvim-lspconfig for formatting on save. ```lua vim.api.nvim_create_autocmd("FileType", { pattern = "cmake", callback = function() vim.lsp.start({ name = "cmakefmt", cmd = { "cmakefmt", "lsp" }, }) end, }) -- Format on save vim.api.nvim_create_autocmd("BufWritePre", { pattern = { "CMakeLists.txt", "*.cmake" }, callback = function() vim.lsp.buf.format({ timeout_ms = 2000 }) end, }) ``` -------------------------------- ### Force Wrapping Example Source: https://cmakefmt.dev/cookbook Shows the transformation of a `target_link_libraries` command from a single line to a vertical layout when `always_wrap` is configured. ```cmake target_link_libraries(mylib PUBLIC dep1 dep2) ``` ```cmake target_link_libraries( mylib PUBLIC dep1 dep2) ``` -------------------------------- ### Override Continuation Alignment Per Command Source: https://cmakefmt.dev/config Applies 'same-indent' continuation alignment specifically to the 'install' command using per-command overrides. ```yaml per_command_overrides: install: continuation_align: same-indent ``` -------------------------------- ### Dump Spec Coverage Source: https://cmakefmt.dev/cli Run the default command to get a human-readable table of registry coverage. ```bash cmakefmt dump spec-coverage ``` -------------------------------- ### Wrapped Layout Example Source: https://cmakefmt.dev/behavior Demonstrates cmakefmt's hanging-wrap layout for commands that exceed line width, adapting to command specs and configuration. ```cmake target_link_libraries(foo PUBLIC very_long_dependency_name another_dependency) ``` ```cmake target_link_libraries( foo PUBLIC very_long_dependency_name another_dependency) ``` -------------------------------- ### Zed LSP Setup for cmakefmt Source: https://cmakefmt.dev/editors Configure Zed to use cmakefmt as a language server. This enables format on save for CMake files. ```json { "lsp": { "cmakefmt": { "binary": { "path": "cmakefmt", "arguments": ["lsp"] } } }, "languages": { "CMake": { "language_servers": ["cmakefmt"], "format_on_save": "on" } } } ``` -------------------------------- ### Generate shell completions Source: https://cmakefmt.dev/installation Generates shell completion scripts for Bash, Zsh, and Fish from an installed cmakefmt binary. ```bash cmakefmt completions bash > cmakefmt.bash cmakefmt completions zsh > _cmakefmt cmakefmt completions fish > cmakefmt.fish ``` -------------------------------- ### Upgrade Local Source Install of CMakefmt Source: https://cmakefmt.dev/installation Upgrades a CMakefmt installation from local source by pulling the latest changes and reinstalling using Cargo. Assumes a Git repository setup. ```bash git pull --ff-only cargo install --path . --force ``` -------------------------------- ### Generate a Starter cmakefmt Configuration Source: https://cmakefmt.dev/getting-started Create a basic configuration file in your repository root. ```bash cmakefmt config init ``` -------------------------------- ### AST Structure Example Source: https://cmakefmt.dev/architecture Defines the basic hierarchical structure of the Abstract Syntax Tree (AST) generated from CMake source code. ```text File -> Statement* -> CommandInvocation -> Argument* ``` -------------------------------- ### GitLab CI: Download Linux binary Source: https://cmakefmt.dev/ci Installs the cmakefmt Linux binary by downloading it from GitHub Releases. This method is suitable for Ubuntu-based GitLab CI images. ```yaml cmakefmt: stage: lint image: ubuntu:latest before_script: - apt-get update -qq && apt-get install -y -qq curl - | LATEST=$(curl -sI https://github.com/cmakefmt/cmakefmt/releases/latest \ | grep -i '^location:' \ | sed 's|.*/tag/v||;s/[[:space:]]//g') curl -sSL \ "https://github.com/cmakefmt/cmakefmt/releases/download/v${LATEST}/cmakefmt-x86_64-unknown-linux-musl.tar.gz" \ | tar -xz -C /usr/local/bin script: - cmakefmt --check . ``` -------------------------------- ### Generate Starter Configuration File Source: https://cmakefmt.dev/cli Generates a starter configuration file for CMakeFmt. Can dump the full template to stdout in YAML or TOML format. ```bash cmakefmt config init ``` ```bash cmakefmt config dump > .cmakefmt.yaml ``` ```bash cmakefmt config dump toml > .cmakefmt.toml ``` -------------------------------- ### Benchmark Per-File Formatting with hyperfine Source: https://cmakefmt.dev/performance Compares the single-file formatting performance of cmakefmt and cmake-format using hyperfine. This setup isolates single-file formatting speed from batch overhead. ```bash hyperfine --warmup 10 --runs 50 \ "cmakefmt path/to/CMakeLists.txt" \ "cmake-format path/to/CMakeLists.txt" ``` -------------------------------- ### Check CMake formatting in Bitbucket Pipelines Source: https://cmakefmt.dev/ci Sets up a Bitbucket Pipeline to check CMake formatting. It uses a Rust Docker image and installs cmakefmt via Cargo. ```yaml pipelines: default: - step: name: Check CMake formatting image: rust:latest caches: - cargo script: - cargo install cmakefmt-rust --quiet - cmakefmt --check . ``` -------------------------------- ### Install cmakefmt with conda-forge Source: https://cmakefmt.dev/installation Installs cmakefmt using the conda-forge channel. This is a community-maintained installation. ```bash conda install -c conda-forge cmakefmt ``` -------------------------------- ### Using Custom Command `my_add_test` in CMake Source: https://cmakefmt.dev/playground Demonstrates the usage of a custom command `my_add_test` with its defined arguments (NAME, SOURCES, LIBRARIES, TIMEOUT) and a flag (VERBOSE). This example shows how to integrate custom command definitions into a CMake build script. ```cmake # Custom function defined by the project my_add_test( NAME mylib_test SOURCES tests/test_main.cpp tests/test_utils.cpp LIBRARIES mylib TIMEOUT 30 VERBOSE) ``` -------------------------------- ### Get Selected Configuration Path Source: https://cmakefmt.dev/cli Retrieves and prints the path to the CMakeFmt configuration file that was selected for the given CMake file. ```bash cmakefmt config path src/CMakeLists.txt ``` -------------------------------- ### Example: Wrap After First Argument Disabled (Default) Source: https://cmakefmt.dev/config Illustrates the default behavior where `wrap_after_first_arg` is false, placing the first argument on a new line. ```cmake # wrap_after_first_arg: false (default) target_link_libraries( mylib PUBLIC dep1 dep2 PRIVATE dep3 dep4) ``` -------------------------------- ### Basic cmakefmt Commands Source: https://cmakefmt.dev Common commands for initializing configuration, checking for changes, previewing formatted output, viewing diffs, applying formatting, and using in pre-commit hooks. Also shows how to format specific paths. ```bash cmakefmt config init # generate a starter .cmakefmt.yaml cmakefmt --check . # dry-run: just show which files would change cmakefmt . # dry-run: preview formatted output; changed lines shown in blue cmakefmt --diff . # dry-run: view a unified diff of what would change (like `git diff`) cmakefmt --in-place . # apply formatting across the whole project cmakefmt --staged --check # use in pre-commit hooks cmakefmt --path-regex 'src/.*' . # format CMake files only under src/ ``` -------------------------------- ### Zed External Formatter Setup for cmakefmt Source: https://cmakefmt.dev/editors Configure Zed to use cmakefmt as an external formatter. This method uses stdin and enables config discovery via buffer path substitution. ```json { "languages": { "CMake": { "formatter": { "external": { "command": "cmakefmt", "arguments": ["--stdin-path", "{buffer_path}", "-"] } }, "format_on_save": "on" } } } ``` -------------------------------- ### Explain Configuration Resolution Source: https://cmakefmt.dev/cli Provides a detailed explanation of how the configuration file is resolved, including the target path, considered config files, selected config, and applied CLI overrides. ```bash cmakefmt config explain ``` -------------------------------- ### Build cmakefmt from source Source: https://cmakefmt.dev/installation Clones the cmakefmt repository, builds the release binary, and provides a help command. This is suitable for active development or reviewing changes. ```bash git clone https://github.com/cmakefmt/cmakefmt cd cmakefmt cargo build --release ./target/release/cmakefmt --help ``` -------------------------------- ### Generate Shell Completions and Man Page Source: https://cmakefmt.dev/release Preview packaging helper outputs from a local build to generate shell completions for bash and zsh, and a man page. ```bash cmakefmt completions bash > cmakefmt.bash cmakefmt completions zsh > _cmakefmt cmakefmt manpage > cmakefmt.1 ``` -------------------------------- ### Install CMakefmt using Cargo in Azure Pipelines Source: https://cmakefmt.dev/ci Installs cmakefmt using the Cargo package manager. This is an alternative for Azure Pipelines if you prefer managing dependencies via Rust's ecosystem. ```yaml steps: - script: cargo install cmakefmt-rust --quiet displayName: Install cmakefmt - script: cmakefmt --check . displayName: Check CMake formatting ``` -------------------------------- ### Install CMakefmt using curl in Azure Pipelines Source: https://cmakefmt.dev/ci Installs the latest release of cmakefmt directly from GitHub releases using curl and tar. This method is suitable for CI environments where direct download is preferred. ```yaml steps: - script: | LATEST=$(curl -sI https://github.com/cmakefmt/cmakefmt/releases/latest \ | grep -i '^location:' \ | sed 's|.*/tag/v||;s/[[:space:]]//g') curl -sSL \ "https://github.com/cmakefmt/cmakefmt/releases/download/v${LATEST}/cmakefmt-${LATEST}-x86_64-unknown-linux-musl.tar.gz" \ | tar -xz --strip-components=1 -C /usr/local/bin displayName: Install cmakefmt - script: cmakefmt --check . displayName: Check CMake formatting ``` -------------------------------- ### Defining Standalone Flags Source: https://cmakefmt.dev/config Example of listing keyword tokens that are treated as boolean flags. ```yaml commands: my_command: flags: - QUIET - REQUIRED - GLOBAL ``` -------------------------------- ### Format CMake Source with Custom Command Registry Source: https://cmakefmt.dev/api Demonstrates how to load a custom command registry, merge overrides, and format source code using the custom commands. This is useful for syntax not part of the built-in registry. ```rust use cmakefmt::{Config, format_source_with_registry}; use cmakefmt::spec::registry::CommandRegistry; fn main() -> Result<(), cmakefmt::Error> { let mut registry = CommandRegistry::load()?; registry.merge_override_str( r#"#, "inline-override.toml", )?; let src = "my_custom_command(foo QUIET SOURCES a.cc b.cc)"; let out = format_source_with_registry(src, &Config::default(), ®istry)?; println!("{out}"); Ok(()) } ``` -------------------------------- ### Debug Config Path and Explanation Source: https://cmakefmt.dev/installation Commands to diagnose configuration issues by showing the effective configuration path and explaining configuration settings. ```bash cmakefmt config path path/to/CMakeLists.txt cmakefmt config explain ``` -------------------------------- ### cmakefmt Config Show with File Path Source: https://cmakefmt.dev/changelog Demonstrates how to use 'cmakefmt config show' with an optional file path argument to inspect configuration for a specific file. ```bash cmakefmt config show src/CMakeLists.txt ``` -------------------------------- ### Remove CMakefmt with Homebrew Source: https://cmakefmt.dev/installation Uninstalls cmakefmt and untaps the repository from Homebrew. This completely removes the Homebrew-managed installation. ```bash brew uninstall cmakefmt brew untap cmakefmt/cmakefmt ``` -------------------------------- ### Nested kwargs and flags within a keyword Source: https://cmakefmt.dev/config Example of a command with nested structures, where a keyword itself has sub-keywords and flags. ```yaml commands: my_command: kwargs: INSTALL: nargs: 0 kwargs: DESTINATION: nargs: 1 flags: - OPTIONAL ``` -------------------------------- ### Specifying Positional Arguments (pargs) Source: https://cmakefmt.dev/config Example of defining the number of positional arguments before keyword processing begins. ```yaml commands: my_command: pargs: 2 # exactly two positional args before keywords ``` -------------------------------- ### Apply Formatting In-Place Source: https://cmakefmt.dev/getting-started Format all CMake files in the current directory and its subdirectories. ```bash cmakefmt --in-place . ``` -------------------------------- ### Space Before Definition Parenthesis Example Source: https://cmakefmt.dev/config Illustrates 'space_before_definition_paren: true' by showing a space before the parenthesis in a 'function' definition. ```cmake function (my_helper arg) ... endfunction () ``` -------------------------------- ### Upgrade CMakefmt with Homebrew Source: https://cmakefmt.dev/installation Updates Homebrew and then upgrades the cmakefmt installation. This is the standard procedure for updating Homebrew packages. ```bash brew update brew upgrade cmakefmt ``` -------------------------------- ### Config::from_file Source: https://cmakefmt.dev/api Loads configuration from a specified file path. This allows using the same configuration behavior as the CLI tool. ```APIDOC ## Config::from_file ### Description Loads configuration from a specified file path. This allows using the same configuration behavior as the CLI tool. ### Function Signature `Config::from_file(path: &Path) -> Result` ### Parameters - **path** (*Path) - The path to the configuration file. ### Request Example ```rust use std::path::Path; use cmakefmt::Config; fn main() -> Result<(), cmakefmt::Error> { let config = Config::from_file(Path::new(".cmakefmt.yaml"))?; println!("line width: {}", config.line_width); Ok(()) } ``` ### Response #### Success Response - **Config**: The loaded configuration object. #### Response Example ```json { "line_width": 80, "command_case": "Preserve", "keyword_case": "Preserve", "dangle_parens": false } ``` ``` -------------------------------- ### Space Before Control Parenthesis Example Source: https://cmakefmt.dev/config Demonstrates the effect of 'space_before_control_paren: true', showing a space before the parenthesis in an 'if' statement. ```cmake if (WIN32) message(STATUS "Windows") endif () ``` -------------------------------- ### Run Formatter Benchmark Suite Source: https://cmakefmt.dev/performance Execute the full benchmark suite for the formatter. This is the primary command for running all performance tests. ```bash cargo bench --bench formatter ``` -------------------------------- ### Clone and build cmakefmt from source Source: https://cmakefmt.dev/contributing Clones the cmakefmt repository and builds the project using Cargo. ```shell git clone https://github.com/cmakefmt/cmakefmt.git cd cmakefmt cargo build ``` -------------------------------- ### Comment reflow example Source: https://cmakefmt.dev/behavior Illustrates how long trailing comments are reflowed with continuation lines aligned to the `#` when `markup.enable_markup` is true. ```cmake # Before: set(FOO bar) # this trailing comment is deliberately long enough to exceed the default line width and demonstrate reflow clearly ``` -------------------------------- ### Run cmakefmt Benchmarks Source: https://cmakefmt.dev/troubleshooting Execute the benchmark suite using `cargo bench --bench formatter` to assess performance. For one-off timing, use `hyperfine`. ```bash cargo bench --bench formatter ``` -------------------------------- ### Disabled Region Example Source: https://cmakefmt.dev/behavior Illustrates how to use a disabled region to prevent cmakefmt from formatting a specific block of code. ```cmake # cmakefmt: off set(SPECIAL_CASE keep this exactly) # cmakefmt: on ``` -------------------------------- ### Typical Local CMakefmt Workflow Source: https://cmakefmt.dev/installation A collection of common CMakefmt commands for daily use, including checking, in-place formatting, verification, and staged file checks. ```bash cmakefmt --check . cmakefmt --in-place . cmakefmt --verify CMakeLists.txt cmakefmt --cache --check . cmakefmt --require-pragma --check . cmakefmt --staged --check cmakefmt --changed --since origin/main --check ``` -------------------------------- ### Running cmakefmt on a single file Source: https://cmakefmt.dev/cli Use this command to format a single CMakeLists.txt file and print the formatted output to standard output. ```bash cmakefmt CMakeLists.txt ``` -------------------------------- ### cmakefmt Formatting Pipeline Source: https://cmakefmt.dev/architecture Illustrates the core data flow from source text to formatted output through parsing, AST generation, and formatting stages. ```text source text -> parser -> AST -> formatter -> formatted output ``` -------------------------------- ### Parse Error with Unclosed Parenthesis Source: https://cmakefmt.dev/cli Example of a parse error indicating an unclosed parenthesis, highlighting the specific location in the file. ```text error: failed to parse a command invocation --> src/CMakeLists.txt:19:6 18 | 19 | endif( | ^ hint: unclosed `(` — the closing `)` is missing ``` -------------------------------- ### Enable Gradual Rollout with Pragmas Source: https://cmakefmt.dev/troubleshooting Use `--require-pragma` to only format files that explicitly opt-in using a marker comment. This allows for a gradual rollout of formatting changes. ```bash cmakefmt --require-pragma --check . ``` ```cmake # cmakefmt: enable ``` -------------------------------- ### Helix LSP Setup for cmakefmt Source: https://cmakefmt.dev/editors Configure Helix to use cmakefmt as a language server. This enables auto-formatting for CMake files. ```toml [language-server.cmakefmt] command = "cmakefmt" args = ["lsp"] [[language]] name = "cmake" language-servers = ["cmakefmt"] auto-format = true ``` -------------------------------- ### Review Formatting Changes on Windows (Git Bash/WSL/PowerShell) Source: https://cmakefmt.dev/cookbook On Windows, use a temporary file with Git Bash, WSL, or PowerShell to perform side-by-side diffs with tools like `meld`. This avoids process substitution limitations. ```powershell $tmp = New-TemporaryFile cmakefmt CMakeLists.txt | Set-Content $tmp meld CMakeLists.txt $tmp Remove-Item $tmp ``` -------------------------------- ### Configure Dangling Parenthesis Alignment Source: https://cmakefmt.dev/config Sets the alignment strategy for a dangling closing parenthesis. 'prefix' aligns it with the start of the line. ```yaml format: dangle_align: prefix ``` -------------------------------- ### Minimal CMake Formatting Source: https://cmakefmt.dev/api Formats a given CMake source string using default configuration. This is the simplest entry point when source text is already in memory. ```rust use cmakefmt::{Config, format_source}; fn main() -> Result<(), cmakefmt::Error> { let src = "target_link_libraries(foo PUBLIC bar)"; let out = format_source(src, &Config::default())?; println!("{out}"); Ok(()) } ``` -------------------------------- ### Synopsis of cmakefmt Source: https://cmakefmt.dev/cli This is the basic command structure for cmakefmt. It shows the command followed by optional flags and file arguments. ```bash cmakefmt [OPTIONS] [FILES]... ``` -------------------------------- ### Remove Cargo-Installed Binary Source: https://cmakefmt.dev/installation Uninstalls the cmakefmt-rust binary installed via Cargo. This command removes the executable from your system's PATH. ```bash cargo uninstall cmakefmt-rust ``` -------------------------------- ### Dangling Parenthesis Alignment Example Source: https://cmakefmt.dev/config Demonstrates the effect of 'dangle_parens: true' on a 'target_link_libraries' call, showing the closing parenthesis on a new line. ```cmake target_link_libraries( foo PUBLIC bar baz ) ``` -------------------------------- ### Config::from_files Source: https://cmakefmt.dev/api Loads and merges configurations from multiple files in the specified order of precedence. ```APIDOC ## Config::from_files ### Description Loads and merges configurations from multiple files in the specified order of precedence. ### Function Signature `Config::from_files(paths: &[PathBuf]) -> Result` ### Parameters - **paths** (slice of PathBuf) - A slice containing the paths to the configuration files. ### Request Example ```rust use std::path::PathBuf; use cmakefmt::Config; fn main() -> Result<(), cmakefmt::Error> { let config = Config::from_files(&[ PathBuf::from("base.yaml"), PathBuf::from("team.yaml"), ])?; println!("{:#?}", config); Ok(()) } ``` ### Response #### Success Response - **Config**: The merged configuration object. #### Response Example ```json { "line_width": 80, "command_case": "Preserve", "keyword_case": "Preserve", "dangle_parens": false } ``` ``` -------------------------------- ### Example Error Output for Line Width Violation Source: https://cmakefmt.dev/cookbook Illustrates the error message produced when `require_valid_layout` is enabled and a line exceeds the specified `line_width`. ```text error: line 2 is 74 characters wide, exceeding the limit of 40 hint: set line_width = 74 (or higher), add the command to always_wrap, or disable require_valid_layout ``` -------------------------------- ### Emacs Apheleia Setup for cmakefmt Source: https://cmakefmt.dev/editors Configure Emacs with apheleia to use cmakefmt as a formatter. Apheleia substitutes filepath with the buffer's path. ```emacs-lisp (require 'apheleia) (add-to-list 'apheleia-formatters '(cmakefmt . ("cmakefmt" "--stdin-path" filepath "-"))) (add-to-list 'apheleia-mode-alist '(cmake-mode . cmakefmt)) (apheleia-global-mode +1) ``` -------------------------------- ### Compare Against Benchmark Baseline Source: https://cmakefmt.dev/performance Compare the current benchmark results against a previously saved baseline. This helps identify performance regressions. ```bash cargo bench --bench formatter -- --baseline before-change ```